blob: ae8b3b385d511119786db8852549885fe900677f [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
Svetoslavb412f6e2015-04-29 16:50:41 -070034#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070035#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070036#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070038
39#include <gui/ISensorServer.h>
40#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070041#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070042
43#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070044#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070045
Mathias Agopian787ac1b2012-09-18 18:49:18 -070046#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070047#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080048#include "GravitySensor.h"
49#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070050#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080051#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070052#include "SensorFusion.h"
53#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070054
55namespace android {
56// ---------------------------------------------------------------------------
57
Mathias Agopian33015422011-05-27 18:18:13 -070058/*
59 * Notes:
60 *
61 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070062 * - run mag sensor from time to time to force calibration
63 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
64 *
65 */
66
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070067const char* SensorService::WAKE_LOCK_NAME = "SensorService";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070068// Permissions.
69static const String16 sDataInjectionPermission("android.permission.HARDWARE_TEST");
70static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070071
Mathias Agopianfc328812010-07-14 23:41:37 -070072SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070073 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
74 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070075{
76}
77
78void SensorService::onFirstRef()
79{
Steve Blocka5512372011-12-20 16:23:08 +000080 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080081 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070082
Mathias Agopianf001c922010-11-11 17:58:51 -080083 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080084 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070085 ssize_t count = dev.getSensorList(&list);
86 if (count > 0) {
87 ssize_t orientationIndex = -1;
88 bool hasGyro = false;
89 uint32_t virtualSensorsNeeds =
90 (1<<SENSOR_TYPE_GRAVITY) |
91 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
92 (1<<SENSOR_TYPE_ROTATION_VECTOR);
93
94 mLastEventSeen.setCapacity(count);
95 for (ssize_t i=0 ; i<count ; i++) {
96 registerSensor( new HardwareSensor(list[i]) );
97 switch (list[i].type) {
98 case SENSOR_TYPE_ORIENTATION:
99 orientationIndex = i;
100 break;
101 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700102 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700103 hasGyro = true;
104 break;
105 case SENSOR_TYPE_GRAVITY:
106 case SENSOR_TYPE_LINEAR_ACCELERATION:
107 case SENSOR_TYPE_ROTATION_VECTOR:
108 virtualSensorsNeeds &= ~(1<<list[i].type);
109 break;
110 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700111 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700112
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700113 // it's safe to instantiate the SensorFusion object here
114 // (it wants to be instantiated after h/w sensors have been
115 // registered)
116 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700117
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700118 // build the sensor list returned to users
119 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700120
121 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700122 Sensor aSensor;
123
124 // Add Android virtual sensors if they're not already
125 // available in the HAL
126
127 aSensor = registerVirtualSensor( new RotationVectorSensor() );
128 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
129 mUserSensorList.add(aSensor);
130 }
131
132 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
133 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
134 mUserSensorList.add(aSensor);
135 }
136
137 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
138 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
139 mUserSensorList.add(aSensor);
140 }
141
142 aSensor = registerVirtualSensor( new OrientationSensor() );
143 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
144 // if we are doing our own rotation-vector, also add
145 // the orientation sensor and remove the HAL provided one.
146 mUserSensorList.replaceAt(aSensor, orientationIndex);
147 }
148
Mathias Agopian33264862012-06-28 19:46:54 -0700149 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700150 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700151 registerVirtualSensor( new GyroDriftSensor() );
152 }
153
Mathias Agopian33264862012-06-28 19:46:54 -0700154 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700155 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700156
Aravind Akella5466c3d2014-08-22 16:11:10 -0700157 // Check if the device really supports batching by looking at the FIFO event
158 // counts for each sensor.
159 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700160 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700161 if (mSensorList[i].getFifoMaxEventCount() > 0) {
162 batchingSupported = true;
163 break;
164 }
165 }
166
167 if (batchingSupported) {
168 // Increase socket buffer size to a max of 100 KB for batching capabilities.
169 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
170 } else {
171 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
172 }
173
174 // Compare the socketBufferSize value against the system limits and limit
175 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700176 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
177 char line[128];
178 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
179 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700180 size_t maxSystemSocketBufferSize;
181 sscanf(line, "%zu", &maxSystemSocketBufferSize);
182 if (mSocketBufferSize > maxSystemSocketBufferSize) {
183 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700184 }
185 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700186 if (fp) {
187 fclose(fp);
188 }
189
Aravind Akella9a844cf2014-02-11 18:58:52 -0800190 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700191 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700192 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
193 mSensorEventBuffer = new sensors_event_t[minBufferSize];
194 mSensorEventScratch = new sensors_event_t[minBufferSize];
195 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700196 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700197
Aravind Akellab4373ac2014-10-29 17:55:20 -0700198 mAckReceiver = new SensorEventAckReceiver(this);
199 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700200 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700201 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700202 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700203 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700204}
205
Mathias Agopian03193062013-05-10 19:32:39 -0700206Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800207{
208 sensors_event_t event;
209 memset(&event, 0, sizeof(event));
210
211 const Sensor sensor(s->getSensor());
212 // add to the sensor list (returned to clients)
213 mSensorList.add(sensor);
214 // add to our handle->SensorInterface mapping
215 mSensorMap.add(sensor.getHandle(), s);
216 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700217 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700218
219 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800220}
221
Mathias Agopian03193062013-05-10 19:32:39 -0700222Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800223{
Mathias Agopian03193062013-05-10 19:32:39 -0700224 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800225 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700226 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800227}
228
Mathias Agopianfc328812010-07-14 23:41:37 -0700229SensorService::~SensorService()
230{
Mathias Agopianf001c922010-11-11 17:58:51 -0800231 for (size_t i=0 ; i<mSensorMap.size() ; i++)
232 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700233}
234
Aravind Akella4949c502015-02-11 15:54:35 -0800235status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700236{
Mathias Agopianfc328812010-07-14 23:41:37 -0700237 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700238 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700239 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000240 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700241 IPCThreadState::self()->getCallingPid(),
242 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700243 } else {
Aravind Akella4949c502015-02-11 15:54:35 -0800244 if (args.size() > 1) {
245 return INVALID_OPERATION;
246 }
247 Mutex::Autolock _l(mLock);
248 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella444f2672015-05-07 12:40:52 -0700249 if (args.size() == 1 && args[0] == String16("restrict")) {
250 // If already in restricted mode. Ignore.
251 if (mCurrentOperatingMode == RESTRICTED) {
252 return status_t(NO_ERROR);
253 }
254 // If in any mode other than normal, ignore.
255 if (mCurrentOperatingMode != NORMAL) {
256 return INVALID_OPERATION;
257 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700258 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800259 dev.disableAllSensors();
260 // Clear all pending flush connections for all active sensors. If one of the active
261 // connections has called flush() and the underlying sensor has been disabled before a
262 // flush complete event is returned, we need to remove the connection from this queue.
263 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
264 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
265 }
Aravind Akella444f2672015-05-07 12:40:52 -0700266 return status_t(NO_ERROR);
267 } else if (args.size() == 1 && args[0] == String16("enable")) {
268 // If currently in restricted mode, reset back to NORMAL mode else ignore.
269 if (mCurrentOperatingMode == RESTRICTED) {
270 mCurrentOperatingMode = NORMAL;
271 dev.enableAllSensors();
272 }
273 return status_t(NO_ERROR);
274 } else {
275 // Default dump the sensor list and debugging information.
276 result.append("Sensor List:\n");
277 for (size_t i=0 ; i<mSensorList.size() ; i++) {
278 const Sensor& s(mSensorList[i]);
279 result.appendFormat(
280 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
281 s.getName().string(),
282 s.getVendor().string(),
283 s.getVersion(),
284 s.getStringType().string(),
285 s.getHandle(),
286 s.getRequiredPermission().string(),
287 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700288
Aravind Akella444f2672015-05-07 12:40:52 -0700289 const int reportingMode = s.getReportingMode();
290 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
291 result.append(" continuous | ");
292 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
293 result.append(" on-change | ");
294 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
295 result.append(" one-shot | ");
296 } else {
297 result.append(" special-trigger | ");
298 }
299
300 if (s.getMaxDelay() > 0) {
301 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
302 } else {
303 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
304 }
305
306 if (s.getMinDelay() > 0) {
307 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
308 } else {
309 result.appendFormat("minDelay=%dus |", s.getMinDelay());
310 }
311
312 if (s.getFifoMaxEventCount() > 0) {
313 result.appendFormat("FifoMax=%d events | ",
314 s.getFifoMaxEventCount());
315 } else {
316 result.append("no batching | ");
317 }
318
319 if (s.isWakeUpSensor()) {
320 result.appendFormat("wakeUp | ");
321 } else {
322 result.appendFormat("non-wakeUp | ");
323 }
324
325 const CircularBuffer* buf = mLastEventSeen.valueFor(s.getHandle());
326 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
327 buf->printBuffer(result);
328 } else {
329 result.append("last=<> \n");
330 }
331 result.append("\n");
332 }
333 SensorFusion::getInstance().dump(result);
334 SensorDevice::getInstance().dump(result);
335
336 result.append("Active sensors:\n");
337 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
338 int handle = mActiveSensors.keyAt(i);
339 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
340 getSensorName(handle).string(),
341 handle,
342 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700343 }
344
Aravind Akella444f2672015-05-07 12:40:52 -0700345 result.appendFormat("Socket Buffer size = %d events\n",
346 mSocketBufferSize/sizeof(sensors_event_t));
347 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
348 result.appendFormat("Mode :");
349 switch(mCurrentOperatingMode) {
350 case NORMAL:
351 result.appendFormat(" NORMAL\n");
352 break;
353 case RESTRICTED:
354 result.appendFormat(" RESTRICTED\n");
355 break;
356 case DATA_INJECTION:
357 result.appendFormat(" DATA_INJECTION\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700358 }
Aravind Akella444f2672015-05-07 12:40:52 -0700359 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700360
Aravind Akella444f2672015-05-07 12:40:52 -0700361 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
362 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
363 if (connection != 0) {
364 result.appendFormat("Connection Number: %zu \n", i);
365 connection->dump(result);
366 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700367 }
368 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700369 }
370 write(fd, result.string(), result.size());
371 return NO_ERROR;
372}
373
Aravind Akella9a844cf2014-02-11 18:58:52 -0800374void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700375 sensors_event_t const* buffer, const int count) {
376 for (int i=0 ; i<count ; i++) {
377 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700378 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
379 handle = buffer[i].meta_data.sensor;
380 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700381 if (connection->hasSensor(handle)) {
382 SensorInterface* sensor = mSensorMap.valueFor(handle);
383 // If this buffer has an event from a one_shot sensor and this connection is registered
384 // for this particular one_shot sensor, try cleaning up the connection.
385 if (sensor != NULL &&
386 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
387 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800388 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700389 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700390
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700391 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700392 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700393}
394
Mathias Agopianfc328812010-07-14 23:41:37 -0700395bool SensorService::threadLoop()
396{
Steve Blocka5512372011-12-20 16:23:08 +0000397 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700398
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700399 // each virtual sensor could generate an event per "real" event, that's why we need
400 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
401 // in practice, this is too aggressive, but guaranteed to be enough.
402 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
403 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
404
Mathias Agopianf001c922010-11-11 17:58:51 -0800405 SensorDevice& device(SensorDevice::getInstance());
406 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700407
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700408 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700409 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700410 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
411 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000412 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700413 break;
414 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700415
416 // Reset sensors_event_t.flags to zero for all events in the buffer.
417 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700418 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700419 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700420
421 // Make a copy of the connection vector as some connections may be removed during the
422 // course of this loop (especially when one-shot sensor events are present in the
423 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
424 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
425 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
426 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
427 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700428 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800429 Mutex::Autolock _l(mLock);
430 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
431 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
432 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
433 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
434 // releasing the wakelock.
435 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700436 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700437 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800438 bufferHasWakeUpEvent = true;
439 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700440 }
441 }
442
Aravind Akella9a844cf2014-02-11 18:58:52 -0800443 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700444 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800445 }
Aravind Akella8493b792014-09-08 15:45:47 -0700446 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800447
Mathias Agopianf001c922010-11-11 17:58:51 -0800448 // handle virtual sensors
449 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700450 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800451 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800452 if (activeVirtualSensorCount) {
453 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700454 SensorFusion& fusion(SensorFusion::getInstance());
455 if (fusion.isEnabled()) {
456 for (size_t i=0 ; i<size_t(count) ; i++) {
457 fusion.process(event[i]);
458 }
459 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700460 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800461 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700462 if (count + k >= minBufferSize) {
463 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700464 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700465 count, k, minBufferSize);
466 break;
467 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800468 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800469 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700470 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700471 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800472 k++;
473 }
474 }
475 }
476 if (k) {
477 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700478 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800479 count += k;
480 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700481 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700482 }
483 }
484 }
485
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700486 // handle backward compatibility for RotationVector sensor
487 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
488 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700489 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700490 // All the 4 components of the quaternion should be available
491 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700492 mSensorEventBuffer[i].data[4] = -1;
493 }
494 }
495 }
496
497 // Map flush_complete_events in the buffer to SensorEventConnections which called
498 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
499 // SensorEventConnection mapped to the corresponding flush_complete_event in
500 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
501 for (int i = 0; i < count; ++i) {
502 mMapFlushEventsToConnections[i] = NULL;
503 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
504 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
505 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
506 if (rec != NULL) {
507 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
508 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700509 }
510 }
511 }
512
Aravind Akella9a844cf2014-02-11 18:58:52 -0800513 // Send our events to clients. Check the state of wake lock for each client and release the
514 // lock if none of the clients need it.
515 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700516 size_t numConnections = activeConnections.size();
517 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700518 if (activeConnections[i] != 0) {
519 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700520 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700521 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700522 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
523 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700524 if (activeConnections[i]->hasOneShotSensors()) {
525 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
526 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700527 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800528 }
529 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700530
Aravind Akella9a844cf2014-02-11 18:58:52 -0800531 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700532 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800533 }
Aravind Akella8493b792014-09-08 15:45:47 -0700534 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700535
Steve Block3c20fbe2012-01-05 23:22:43 +0000536 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800537 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700538 return false;
539}
540
Aravind Akella56ae4262014-07-10 16:01:10 -0700541sp<Looper> SensorService::getLooper() const {
542 return mLooper;
543}
544
Aravind Akellab4373ac2014-10-29 17:55:20 -0700545void SensorService::resetAllWakeLockRefCounts() {
546 SortedVector< sp<SensorEventConnection> > activeConnections;
547 populateActiveConnections(&activeConnections);
548 {
549 Mutex::Autolock _l(mLock);
550 for (size_t i=0 ; i < activeConnections.size(); ++i) {
551 if (activeConnections[i] != 0) {
552 activeConnections[i]->resetWakeLockRefCount();
553 }
554 }
555 setWakeLockAcquiredLocked(false);
556 }
557}
558
559void SensorService::setWakeLockAcquiredLocked(bool acquire) {
560 if (acquire) {
561 if (!mWakeLockAcquired) {
562 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
563 mWakeLockAcquired = true;
564 }
565 mLooper->wake();
566 } else {
567 if (mWakeLockAcquired) {
568 release_wake_lock(WAKE_LOCK_NAME);
569 mWakeLockAcquired = false;
570 }
571 }
572}
573
Aravind Akellab4373ac2014-10-29 17:55:20 -0700574bool SensorService::isWakeLockAcquired() {
575 Mutex::Autolock _l(mLock);
576 return mWakeLockAcquired;
577}
578
Aravind Akella56ae4262014-07-10 16:01:10 -0700579bool SensorService::SensorEventAckReceiver::threadLoop() {
580 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700581 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700582 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700583 bool wakeLockAcquired = mService->isWakeLockAcquired();
584 int timeout = -1;
585 if (wakeLockAcquired) timeout = 5000;
586 int ret = looper->pollOnce(timeout);
587 if (ret == ALOOPER_POLL_TIMEOUT) {
588 mService->resetAllWakeLockRefCounts();
589 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700590 } while(!Thread::exitPending());
591 return false;
592}
593
Aravind Akella9a844cf2014-02-11 18:58:52 -0800594void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800595 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800596 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700597 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
598 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
599 if (circular_buf == NULL) {
600 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800601 }
Aravind Akella444f2672015-05-07 12:40:52 -0700602 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800603 }
604 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800605}
606
Mathias Agopianf001c922010-11-11 17:58:51 -0800607void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
608{
609 struct compar {
610 static int cmp(void const* lhs, void const* rhs) {
611 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
612 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700613 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800614 }
615 };
616 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
617}
618
Mathias Agopian5d270722010-07-19 15:20:39 -0700619String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700620 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700621 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700622 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700623 if (sensor.getHandle() == handle) {
624 return sensor.getName();
625 }
626 }
627 String8 result("unknown");
628 return result;
629}
630
Aravind Akellab4099e72013-10-15 15:43:10 -0700631bool SensorService::isVirtualSensor(int handle) const {
632 SensorInterface* sensor = mSensorMap.valueFor(handle);
633 return sensor->isVirtual();
634}
635
Aravind Akella9a844cf2014-02-11 18:58:52 -0800636bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700637 int handle = event.sensor;
638 if (event.type == SENSOR_TYPE_META_DATA) {
639 handle = event.meta_data.sensor;
640 }
641 SensorInterface* sensor = mSensorMap.valueFor(handle);
642 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800643}
644
Aravind Akella6c2664a2014-08-13 12:24:50 -0700645SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
646 return mActiveSensors.valueFor(handle);
647}
648
Svetoslavb412f6e2015-04-29 16:50:41 -0700649Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700650{
Mathias Agopian33264862012-06-28 19:46:54 -0700651 char value[PROPERTY_VALUE_MAX];
652 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000653 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
654 mUserSensorListDebug : mUserSensorList;
655 Vector<Sensor> accessibleSensorList;
656 for (size_t i = 0; i < initialSensorList.size(); i++) {
657 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700658 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000659 accessibleSensorList.add(sensor);
660 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700661 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100662 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700663 sensor.getRequiredPermission().string(),
664 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000665 }
Mathias Agopian33264862012-06-28 19:46:54 -0700666 }
Aravind Akella70018042014-04-07 22:52:37 +0000667 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700668}
669
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700670sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700671 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700672 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
673 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
674 return NULL;
675 }
676 // DATA_INJECTION mode needs to have the required permissions set.
677 if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) {
678 return NULL;
679 }
680
681 Mutex::Autolock _l(mLock);
Mathias Agopian5307d172012-09-18 17:02:43 -0700682 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700683 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700684 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700685 if (requestedMode == DATA_INJECTION) {
686 if (mActiveConnections.indexOf(result) < 0) {
687 mActiveConnections.add(result);
688 }
689 // Add the associated file descriptor to the Looper for polling whenever there is data to
690 // be injected.
691 result->updateLooperRegistration(mLooper);
692 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700693 return result;
694}
695
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700696status_t SensorService::enableDataInjection(int requestedMode) {
697 if (!hasDataInjectionPermissions()) {
698 return INVALID_OPERATION;
699 }
700 Mutex::Autolock _l(mLock);
701 ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode);
702 SensorDevice& dev(SensorDevice::getInstance());
703 status_t err(NO_ERROR);
704 if (requestedMode == DATA_INJECTION) {
705 if (mCurrentOperatingMode == NORMAL) {
706 dev.disableAllSensors();
707 err = dev.setMode(requestedMode);
708 if (err == NO_ERROR) {
709 mCurrentOperatingMode = DATA_INJECTION;
710 } else {
711 // Re-enable sensors.
712 dev.enableAllSensors();
713 }
714 } else if (mCurrentOperatingMode == DATA_INJECTION) {
715 // Already in DATA_INJECTION mode. Treat this as a no_op.
716 return NO_ERROR;
717 } else {
718 // Transition to data injection mode supported only from NORMAL mode.
719 return INVALID_OPERATION;
720 }
721 } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) {
722 err = resetToNormalModeLocked();
723 }
724 return err;
725}
726
727status_t SensorService::resetToNormalMode() {
728 Mutex::Autolock _l(mLock);
729 return resetToNormalModeLocked();
730}
731
732status_t SensorService::resetToNormalModeLocked() {
733 SensorDevice& dev(SensorDevice::getInstance());
734 dev.enableAllSensors();
735 status_t err = dev.setMode(NORMAL);
736 mCurrentOperatingMode = NORMAL;
737 return err;
738}
739
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800740void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700741{
742 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800743 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700744 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700745 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700746 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800747 int handle = mActiveSensors.keyAt(i);
748 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700749 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800750 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000751 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800752 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800753 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800754 }
Aravind Akella8a969552014-09-28 17:52:41 -0700755 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800756 }
757 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700758 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000759 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700760 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700761 c, i, handle);
762
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800763 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000764 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700765 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800766 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700767 delete rec;
768 size--;
769 } else {
770 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700771 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700772 }
Aravind Akella8a969552014-09-28 17:52:41 -0700773 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700774 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700775 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800776 if (c->needsWakeLock()) {
777 checkWakeLockStateLocked();
778 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700779}
780
Aravind Akella70018042014-04-07 22:52:37 +0000781Sensor SensorService::getSensorFromHandle(int handle) const {
782 return mSensorMap.valueFor(handle)->getSensor();
783}
784
Mathias Agopianfc328812010-07-14 23:41:37 -0700785status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700786 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
787 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700788{
Mathias Agopian50df2952010-07-19 19:09:10 -0700789 if (mInitCheck != NO_ERROR)
790 return mInitCheck;
791
Mathias Agopianf001c922010-11-11 17:58:51 -0800792 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700793 if (sensor == NULL) {
794 return BAD_VALUE;
795 }
Aravind Akella70018042014-04-07 22:52:37 +0000796
Svetoslavb412f6e2015-04-29 16:50:41 -0700797 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000798 return BAD_VALUE;
799 }
800
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700801 Mutex::Autolock _l(mLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700802 if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800803 return INVALID_OPERATION;
804 }
805
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700806 SensorRecord* rec = mActiveSensors.valueFor(handle);
807 if (rec == 0) {
808 rec = new SensorRecord(connection);
809 mActiveSensors.add(handle, rec);
810 if (sensor->isVirtual()) {
811 mActiveVirtualSensors.add(handle, sensor);
812 }
813 } else {
814 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800815 // this sensor is already activated, but we are adding a connection that uses it.
816 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700817 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700818 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800819 // NOTE: The wake_up flag of this event may get set to
820 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700821 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
822 if (circular_buf) {
823 sensors_event_t event;
824 memset(&event, 0, sizeof(event));
825 // It is unlikely that this buffer is empty as the sensor is already active.
826 // One possible corner case may be two applications activating an on-change
827 // sensor at the same time.
828 if(circular_buf->populateLastEvent(&event)) {
829 event.sensor = handle;
830 if (event.version == sizeof(sensors_event_t)) {
831 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
832 setWakeLockAcquiredLocked(true);
833 }
834 connection->sendEvents(&event, 1, NULL);
835 if (!connection->needsWakeLock() && mWakeLockAcquired) {
836 checkWakeLockStateLocked();
837 }
838 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800839 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700840 }
841 }
842 }
843 }
844
845 if (connection->addSensor(handle)) {
846 BatteryService::enableSensor(connection->getUid(), handle);
847 // the sensor was added (which means it wasn't already there)
848 // so, see if this connection becomes active
849 if (mActiveConnections.indexOf(connection) < 0) {
850 mActiveConnections.add(connection);
851 }
852 } else {
853 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
854 handle, connection.get());
855 }
856
Aravind Akella724d91d2013-06-27 12:04:23 -0700857 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
858 if (samplingPeriodNs < minDelayNs) {
859 samplingPeriodNs = minDelayNs;
860 }
861
Aravind Akella6c2664a2014-08-13 12:24:50 -0700862 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
863 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700864 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
865
Aravind Akella4949c502015-02-11 15:54:35 -0800866 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700867 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700868
Aravind Akella5466c3d2014-08-22 16:11:10 -0700869 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
870 // event before sending events on this connection. Ignore one-shot sensors which don't
871 // support flush(). Also if this sensor isn't already active, don't call flush().
872 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
873 rec->getNumConnections() > 1) {
874 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700875 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700876 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700877 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700878 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700879 } else {
880 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700881 }
882 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700883
884 if (err == NO_ERROR) {
885 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
886 err = sensor->activate(connection.get(), true);
887 }
888
Aravind Akella8a969552014-09-28 17:52:41 -0700889 if (err == NO_ERROR) {
890 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700891 }
892
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700893 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700894 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700895 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700896 }
897 return err;
898}
899
900status_t SensorService::disable(const sp<SensorEventConnection>& connection,
901 int handle)
902{
Mathias Agopian50df2952010-07-19 19:09:10 -0700903 if (mInitCheck != NO_ERROR)
904 return mInitCheck;
905
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700906 Mutex::Autolock _l(mLock);
907 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700908 if (err == NO_ERROR) {
909 SensorInterface* sensor = mSensorMap.valueFor(handle);
910 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
911 }
912 return err;
913}
914
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700915status_t SensorService::cleanupWithoutDisable(
916 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700917 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700918 return cleanupWithoutDisableLocked(connection, handle);
919}
920
921status_t SensorService::cleanupWithoutDisableLocked(
922 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700923 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700924 if (rec) {
925 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700926 if (connection->removeSensor(handle)) {
927 BatteryService::disableSensor(connection->getUid(), handle);
928 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700929 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700930 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700931 mActiveConnections.remove(connection);
932 }
933 // see if this sensor becomes inactive
934 if (rec->removeConnection(connection)) {
935 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800936 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700937 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700938 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700939 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700940 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700941 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700942}
943
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700944status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700945 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700946{
Mathias Agopian50df2952010-07-19 19:09:10 -0700947 if (mInitCheck != NO_ERROR)
948 return mInitCheck;
949
Mathias Agopianae09d652011-11-01 17:37:49 -0700950 SensorInterface* sensor = mSensorMap.valueFor(handle);
951 if (!sensor)
952 return BAD_VALUE;
953
Svetoslavb412f6e2015-04-29 16:50:41 -0700954 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000955 return BAD_VALUE;
956 }
957
Mathias Agopian1cd70002010-07-21 15:59:50 -0700958 if (ns < 0)
959 return BAD_VALUE;
960
Mathias Agopian62569ec2011-11-07 21:21:47 -0800961 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
962 if (ns < minDelayNs) {
963 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700964 }
965
Mathias Agopianf001c922010-11-11 17:58:51 -0800966 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700967}
968
Svetoslavb412f6e2015-04-29 16:50:41 -0700969status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
970 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +0000971 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700972 SensorDevice& dev(SensorDevice::getInstance());
973 const int halVersion = dev.getHalDeviceVersion();
974 status_t err(NO_ERROR);
975 Mutex::Autolock _l(mLock);
976 // Loop through all sensors for this connection and call flush on each of them.
977 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
978 const int handle = connection->mSensorInfo.keyAt(i);
979 SensorInterface* sensor = mSensorMap.valueFor(handle);
980 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
981 ALOGE("flush called on a one-shot sensor");
982 err = INVALID_OPERATION;
983 continue;
984 }
Aravind Akella8493b792014-09-08 15:45:47 -0700985 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700986 // For older devices just increment pending flush count which will send a trivial
987 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700988 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700989 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700990 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
991 err = INVALID_OPERATION;
992 continue;
993 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700994 status_t err_flush = sensor->flush(connection.get(), handle);
995 if (err_flush == NO_ERROR) {
996 SensorRecord* rec = mActiveSensors.valueFor(handle);
997 if (rec != NULL) rec->addPendingFlushConnection(connection);
998 }
999 err = (err_flush != NO_ERROR) ? err_flush : err;
1000 }
Aravind Akella70018042014-04-07 22:52:37 +00001001 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001002 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001003}
Aravind Akella70018042014-04-07 22:52:37 +00001004
Svetoslavb412f6e2015-04-29 16:50:41 -07001005bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1006 const String16& opPackageName) {
1007 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001008
Svetoslavb412f6e2015-04-29 16:50:41 -07001009 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001010 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001011 }
1012
1013 bool hasPermission = false;
1014
1015 // Runtime permissions can't use the cache as they may change.
1016 if (sensor.isRequiredPermissionRuntime()) {
1017 hasPermission = checkPermission(String16(requiredPermission),
1018 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001019 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001020 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1021 }
1022
1023 if (!hasPermission) {
1024 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1025 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001026 return false;
1027 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001028
1029 const int32_t opCode = sensor.getRequiredAppOp();
1030 if (opCode >= 0) {
1031 AppOpsManager appOps;
1032 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1033 != AppOpsManager::MODE_ALLOWED) {
1034 ALOGE("%s a sensor (%s) without enabled required app op: %D",
1035 operation, sensor.getName().string(), opCode);
1036 return false;
1037 }
1038 }
1039
1040 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001041}
1042
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001043bool SensorService::hasDataInjectionPermissions() {
1044 if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) {
1045 ALOGE("Permission Denial trying to activate data injection without"
1046 " the required permission");
1047 return false;
1048 }
1049 return true;
1050}
1051
Aravind Akella9a844cf2014-02-11 18:58:52 -08001052void SensorService::checkWakeLockState() {
1053 Mutex::Autolock _l(mLock);
1054 checkWakeLockStateLocked();
1055}
1056
1057void SensorService::checkWakeLockStateLocked() {
1058 if (!mWakeLockAcquired) {
1059 return;
1060 }
1061 bool releaseLock = true;
1062 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1063 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1064 if (connection != 0) {
1065 if (connection->needsWakeLock()) {
1066 releaseLock = false;
1067 break;
1068 }
1069 }
1070 }
1071 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001072 setWakeLockAcquiredLocked(false);
1073 }
1074}
1075
1076void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1077 Mutex::Autolock _l(mLock);
1078 connection->writeToSocketFromCache();
1079 if (connection->needsWakeLock()) {
1080 setWakeLockAcquiredLocked(true);
1081 }
1082}
1083
1084void SensorService::populateActiveConnections(
1085 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1086 Mutex::Autolock _l(mLock);
1087 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1088 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1089 if (connection != 0) {
1090 activeConnections->add(connection);
1091 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001092 }
1093}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001094
Aravind Akella4949c502015-02-11 15:54:35 -08001095bool SensorService::isWhiteListedPackage(const String8& packageName) {
1096 // TODO: Come up with a list of packages.
1097 return (packageName.find(".cts.") != -1);
1098}
1099
Aravind Akella444f2672015-05-07 12:40:52 -07001100int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1101 switch (sensor_event_type) {
1102 case SENSOR_TYPE_ROTATION_VECTOR:
1103 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1104 return 5;
1105
1106 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1107 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1108 return 6;
1109
1110 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1111 return 4;
1112
1113 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1114 case SENSOR_TYPE_STEP_DETECTOR:
1115 case SENSOR_TYPE_STEP_COUNTER:
1116 return 1;
1117
1118 default:
1119 return 3;
1120 }
1121}
1122
Mathias Agopianfc328812010-07-14 23:41:37 -07001123// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001124SensorService::SensorRecord::SensorRecord(
1125 const sp<SensorEventConnection>& connection)
1126{
1127 mConnections.add(connection);
1128}
1129
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001130bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001131 const sp<SensorEventConnection>& connection)
1132{
1133 if (mConnections.indexOf(connection) < 0) {
1134 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001135 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001136 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001137 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001138}
1139
1140bool SensorService::SensorRecord::removeConnection(
1141 const wp<SensorEventConnection>& connection)
1142{
1143 ssize_t index = mConnections.indexOf(connection);
1144 if (index >= 0) {
1145 mConnections.removeItemsAt(index, 1);
1146 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001147 // Remove this connections from the queue of flush() calls made on this sensor.
1148 for (Vector< wp<SensorEventConnection> >::iterator it =
1149 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001150
Aravind Akella6c2664a2014-08-13 12:24:50 -07001151 if (it->unsafe_get() == connection.unsafe_get()) {
1152 it = mPendingFlushConnections.erase(it);
1153 } else {
1154 ++it;
1155 }
1156 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001157 return mConnections.size() ? false : true;
1158}
1159
Aravind Akella6c2664a2014-08-13 12:24:50 -07001160void SensorService::SensorRecord::addPendingFlushConnection(
1161 const sp<SensorEventConnection>& connection) {
1162 mPendingFlushConnections.add(connection);
1163}
1164
1165void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1166 if (mPendingFlushConnections.size() > 0) {
1167 mPendingFlushConnections.removeAt(0);
1168 }
1169}
1170
1171SensorService::SensorEventConnection *
1172SensorService::SensorRecord::getFirstPendingFlushConnection() {
1173 if (mPendingFlushConnections.size() > 0) {
1174 return mPendingFlushConnections[0].unsafe_get();
1175 }
1176 return NULL;
1177}
1178
Aravind Akella4949c502015-02-11 15:54:35 -08001179void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1180 mPendingFlushConnections.clear();
1181}
1182
Aravind Akella444f2672015-05-07 12:40:52 -07001183// --------------------------------------------------------------------------
1184SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1185 mNextInd = 0;
1186 mTrimmedSensorEventArr = new TrimmedSensorEvent *[CIRCULAR_BUF_SIZE];
1187 mSensorType = sensor_event_type;
1188 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1189 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) {
1190 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(numData, mSensorType);
1191 }
1192}
1193
1194void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1195 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1196 curr_event->mTimestamp = sensor_event.timestamp;
1197 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1198 curr_event->mStepCounter = sensor_event.u64.step_counter;
1199 } else {
1200 memcpy(curr_event->mData, sensor_event.data,
1201 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1202 }
1203 time_t rawtime = time(NULL);
1204 struct tm * timeinfo = localtime(&rawtime);
1205 curr_event->mHour = timeinfo->tm_hour;
1206 curr_event->mMin = timeinfo->tm_min;
1207 curr_event->mSec = timeinfo->tm_sec;
1208 mNextInd = (mNextInd + 1) % CIRCULAR_BUF_SIZE;
1209}
1210
1211void SensorService::CircularBuffer::printBuffer(String8& result) const {
1212 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1213 int i = mNextInd, eventNum = 1;
1214 result.appendFormat("last %d events = < ", CIRCULAR_BUF_SIZE);
1215 do {
1216 if (mTrimmedSensorEventArr[i]->mTimestamp == -1) {
1217 // Sentinel, ignore.
1218 i = (i + 1) % CIRCULAR_BUF_SIZE;
1219 continue;
1220 }
1221 result.appendFormat("%d) ", eventNum++);
1222 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1223 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1224 } else {
1225 for (int j = 0; j < numData; ++j) {
1226 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1227 }
1228 }
1229 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1230 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1231 mTrimmedSensorEventArr[i]->mSec);
1232 i = (i + 1) % CIRCULAR_BUF_SIZE;
1233 } while (i != mNextInd);
1234 result.appendFormat(">\n");
1235}
1236
1237bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
1238 int lastEventInd = (mNextInd - 1 + CIRCULAR_BUF_SIZE) % CIRCULAR_BUF_SIZE;
1239 // Check if the buffer is empty.
1240 if (mTrimmedSensorEventArr[lastEventInd]->mTimestamp == -1) {
1241 return false;
1242 }
1243 event->version = sizeof(sensors_event_t);
1244 event->type = mSensorType;
1245 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1246 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1247 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1248 } else {
1249 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1250 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1251 }
1252 return true;
1253}
1254
1255SensorService::CircularBuffer::~CircularBuffer() {
1256 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) {
1257 delete mTrimmedSensorEventArr[i];
1258 }
1259 delete [] mTrimmedSensorEventArr;
1260}
1261
Mathias Agopianfc328812010-07-14 23:41:37 -07001262// ---------------------------------------------------------------------------
1263
1264SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001265 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1266 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001267 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001268 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1269 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001270 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001271#if DEBUG_CONNECTIONS
1272 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001273 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001274#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001275}
1276
Aravind Akella56ae4262014-07-10 16:01:10 -07001277SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001278 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001279 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001280 if (mEventCache != NULL) {
1281 delete mEventCache;
1282 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001283}
1284
Aravind Akella56ae4262014-07-10 16:01:10 -07001285void SensorService::SensorEventConnection::onFirstRef() {
1286 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001287}
1288
Aravind Akella9a844cf2014-02-11 18:58:52 -08001289bool SensorService::SensorEventConnection::needsWakeLock() {
1290 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001291 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001292}
1293
Aravind Akellab4373ac2014-10-29 17:55:20 -07001294void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1295 Mutex::Autolock _l(mConnectionLock);
1296 mWakeLockRefCount = 0;
1297}
1298
Aravind Akella4c8b9512013-09-05 17:03:38 -07001299void SensorService::SensorEventConnection::dump(String8& result) {
1300 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001301 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella4949c502015-02-11 15:54:35 -08001302 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1303 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001304 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1305 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001306 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001307 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001308 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001309 flushInfo.mFirstFlushPending ? "First flush pending" :
1310 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001311 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001312 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001313#if DEBUG_CONNECTIONS
1314 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1315 " total_acks_needed %d | total_acks_recvd %d\n",
1316 mEventsReceived,
1317 mEventsSent,
1318 mEventsSentFromCache,
1319 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1320 mTotalAcksNeeded,
1321 mTotalAcksReceived);
1322#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001323}
1324
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001325bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001326 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001327 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1328 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001329 return false;
1330 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001331 if (mSensorInfo.indexOfKey(handle) < 0) {
1332 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001333 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001334 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001335 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001336}
1337
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001338bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001339 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001340 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001341 return true;
1342 }
1343 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001344}
1345
1346bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001347 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001348 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001349}
1350
1351bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001352 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001353 return mSensorInfo.size() ? true : false;
1354}
1355
Aravind Akella8493b792014-09-08 15:45:47 -07001356bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1357 Mutex::Autolock _l(mConnectionLock);
1358 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1359 const int handle = mSensorInfo.keyAt(i);
1360 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1361 return true;
1362 }
1363 }
1364 return false;
1365}
1366
Aravind Akella4949c502015-02-11 15:54:35 -08001367String8 SensorService::SensorEventConnection::getPackageName() const {
1368 return mPackageName;
1369}
1370
Aravind Akella4c8b9512013-09-05 17:03:38 -07001371void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1372 bool value) {
1373 Mutex::Autolock _l(mConnectionLock);
1374 ssize_t index = mSensorInfo.indexOfKey(handle);
1375 if (index >= 0) {
1376 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1377 flushInfo.mFirstFlushPending = value;
1378 }
1379}
1380
Aravind Akella8a969552014-09-28 17:52:41 -07001381void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1382 Mutex::Autolock _l(mConnectionLock);
1383 updateLooperRegistrationLocked(looper);
1384}
1385
1386void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1387 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001388 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1389 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001390 // If all sensors are unregistered OR Looper has encountered an error, we
1391 // can remove the Fd from the Looper if it has been previously added.
1392 if (!isConnectionActive || mDead) {
1393 if (mHasLooperCallbacks) {
1394 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1395 looper->removeFd(mChannel->getSendFd());
1396 mHasLooperCallbacks = false;
1397 }
1398 return;
1399 }
1400
1401 int looper_flags = 0;
1402 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001403 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001404 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1405 const int handle = mSensorInfo.keyAt(i);
1406 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1407 looper_flags |= ALOOPER_EVENT_INPUT;
1408 break;
1409 }
1410 }
1411 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1412 // the fd has already been added, remove it. This is likely to happen when ALL the
1413 // events stored in the cache have been sent to the corresponding app.
1414 if (looper_flags == 0) {
1415 if (mHasLooperCallbacks) {
1416 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1417 looper->removeFd(mChannel->getSendFd());
1418 mHasLooperCallbacks = false;
1419 }
1420 return;
1421 }
1422 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1423 // registered for wake-up sensors OR for sending events in the cache.
1424 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1425 if (ret == 1) {
1426 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1427 mHasLooperCallbacks = true;
1428 } else {
1429 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1430 }
1431}
1432
1433void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1434 Mutex::Autolock _l(mConnectionLock);
1435 ssize_t index = mSensorInfo.indexOfKey(handle);
1436 if (index >= 0) {
1437 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1438 flushInfo.mPendingFlushEventsToSend++;
1439 }
1440}
1441
Mathias Agopianfc328812010-07-14 23:41:37 -07001442status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001443 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001444 sensors_event_t* scratch,
1445 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001446 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001447 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001448 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001449 if (scratch) {
1450 size_t i=0;
1451 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001452 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001453 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1454 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001455 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001456 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1457 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1458 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001459 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001460 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001461 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001462 // Check if this connection has registered for this sensor. If not continue to the
1463 // next sensor_event.
1464 if (index < 0) {
1465 ++i;
1466 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001467 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001468
Aravind Akella56ae4262014-07-10 16:01:10 -07001469 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001470 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001471 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1472 this == mapFlushEventsToConnections[i]) {
1473 flushInfo.mFirstFlushPending = false;
1474 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1475 buffer[i].meta_data.sensor);
1476 ++i;
1477 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001478 }
1479
1480 // If there is a pending flush complete event for this sensor on this connection,
1481 // ignore the event and proceed to the next.
1482 if (flushInfo.mFirstFlushPending) {
1483 ++i;
1484 continue;
1485 }
1486
1487 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001488 // Keep copying events into the scratch buffer as long as they are regular
1489 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1490 // from the same sensor_handle AND the current connection is mapped to the
1491 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001492 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001493 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001494 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001495 }
1496 ++i;
1497 } else {
1498 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001499 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001500 }
Aravind Akella8493b792014-09-08 15:45:47 -07001501 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1502 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001503 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001504 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001505 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001506 } else {
1507 scratch = const_cast<sensors_event_t *>(buffer);
1508 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001509 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001510
Aravind Akella6c2664a2014-08-13 12:24:50 -07001511 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001512 // Early return if there are no events for this connection.
1513 if (count == 0) {
1514 return status_t(NO_ERROR);
1515 }
1516
1517#if DEBUG_CONNECTIONS
1518 mEventsReceived += count;
1519#endif
1520 if (mCacheSize != 0) {
1521 // There are some events in the cache which need to be sent first. Copy this buffer to
1522 // the end of cache.
1523 if (mCacheSize + count <= mMaxCacheSize) {
1524 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1525 mCacheSize += count;
1526 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001527 // Check if any new sensors have registered on this connection which may have increased
1528 // the max cache size that is desired.
1529 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1530 reAllocateCacheLocked(scratch, count);
1531 return status_t(NO_ERROR);
1532 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001533 // Some events need to be dropped.
1534 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1535 if (remaningCacheSize != 0) {
1536 memcpy(&mEventCache[mCacheSize], scratch,
1537 remaningCacheSize * sizeof(sensors_event_t));
1538 }
1539 int numEventsDropped = count - remaningCacheSize;
1540 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1541 // Drop the first "numEventsDropped" in the cache.
1542 memmove(mEventCache, &mEventCache[numEventsDropped],
1543 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1544
1545 // Copy the remainingEvents in scratch buffer to the end of cache.
1546 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1547 numEventsDropped * sizeof(sensors_event_t));
1548 }
1549 return status_t(NO_ERROR);
1550 }
1551
Aravind Akella6c2664a2014-08-13 12:24:50 -07001552 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1553 if (index_wake_up_event >= 0) {
1554 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1555 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001556#if DEBUG_CONNECTIONS
1557 ++mTotalAcksNeeded;
1558#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001559 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001560
1561 // NOTE: ASensorEvent and sensors_event_t are the same type.
1562 ssize_t size = SensorEventQueue::write(mChannel,
1563 reinterpret_cast<ASensorEvent const*>(scratch), count);
1564 if (size < 0) {
1565 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001566 if (index_wake_up_event >= 0) {
1567 // If there was a wake_up sensor_event, reset the flag.
1568 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001569 if (mWakeLockRefCount > 0) {
1570 --mWakeLockRefCount;
1571 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001572#if DEBUG_CONNECTIONS
1573 --mTotalAcksNeeded;
1574#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001575 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001576 if (mEventCache == NULL) {
1577 mMaxCacheSize = computeMaxCacheSizeLocked();
1578 mEventCache = new sensors_event_t[mMaxCacheSize];
1579 mCacheSize = 0;
1580 }
1581 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1582 mCacheSize += count;
1583
1584 // Add this file descriptor to the looper to get a callback when this fd is available for
1585 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001586 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001587 return size;
1588 }
1589
1590#if DEBUG_CONNECTIONS
1591 if (size > 0) {
1592 mEventsSent += count;
1593 }
1594#endif
1595
1596 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1597}
1598
Aravind Akella6c2664a2014-08-13 12:24:50 -07001599void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1600 int count) {
1601 sensors_event_t *eventCache_new;
1602 const int new_cache_size = computeMaxCacheSizeLocked();
1603 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1604 eventCache_new = new sensors_event_t[new_cache_size];
1605 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1606 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1607
1608 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1609 new_cache_size);
1610
1611 delete mEventCache;
1612 mEventCache = eventCache_new;
1613 mCacheSize += count;
1614 mMaxCacheSize = new_cache_size;
1615}
1616
1617void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1618 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001619 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001620 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001621 // Loop through all the sensors for this connection and check if there are any pending
1622 // flush complete events to be sent.
1623 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1624 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1625 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001626 const int sensor_handle = mSensorInfo.keyAt(i);
1627 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001628 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1629 if (wakeUpSensor) {
1630 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001631 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1632 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001633 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1634 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001635 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001636 return;
1637 }
1638 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1639 flushCompleteEvent.meta_data.sensor);
1640 flushInfo.mPendingFlushEventsToSend--;
1641 }
1642 }
1643}
1644
Aravind Akellab4373ac2014-10-29 17:55:20 -07001645void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001646 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1647 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1648 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1649 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001650 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001651 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001652 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001653 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001654 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001655 int index_wake_up_event =
1656 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1657 if (index_wake_up_event >= 0) {
1658 mEventCache[index_wake_up_event + numEventsSent].flags |=
1659 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1660 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001661#if DEBUG_CONNECTIONS
1662 ++mTotalAcksNeeded;
1663#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001664 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001665
Aravind Akella56ae4262014-07-10 16:01:10 -07001666 ssize_t size = SensorEventQueue::write(mChannel,
1667 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001668 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001669 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001670 if (index_wake_up_event >= 0) {
1671 // If there was a wake_up sensor_event, reset the flag.
1672 mEventCache[index_wake_up_event + numEventsSent].flags &=
1673 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001674 if (mWakeLockRefCount > 0) {
1675 --mWakeLockRefCount;
1676 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001677#if DEBUG_CONNECTIONS
1678 --mTotalAcksNeeded;
1679#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001680 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001681 memmove(mEventCache, &mEventCache[numEventsSent],
1682 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1683 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001684 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001685 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001686 return;
1687 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001688 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001689#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001690 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001691#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001692 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001693 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1694 // All events from the cache have been sent. Reset cache size to zero.
1695 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001696 // There are no more events in the cache. We don't need to poll for write on the fd.
1697 // Update Looper registration.
1698 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001699}
1700
Aravind Akellac551eac2013-10-14 17:04:42 -07001701void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001702 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001703 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001704 // Count flushComplete events in the events that are about to the dropped. These will be sent
1705 // separately before the next batch of events.
1706 for (int j = 0; j < numEventsDropped; ++j) {
1707 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1708 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1709 flushInfo.mPendingFlushEventsToSend++;
1710 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1711 flushInfo.mPendingFlushEventsToSend);
1712 }
1713 }
1714 return;
1715}
1716
Aravind Akella6c2664a2014-08-13 12:24:50 -07001717int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1718 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001719 for (int i = 0; i < count; ++i) {
1720 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001721 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001722 }
1723 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001724 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001725}
1726
Mathias Agopianb3989272011-10-20 18:42:02 -07001727sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001728{
1729 return mChannel;
1730}
1731
1732status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001733 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1734 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001735{
1736 status_t err;
1737 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001738 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001739 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001740
Mathias Agopianfc328812010-07-14 23:41:37 -07001741 } else {
1742 err = mService->disable(this, handle);
1743 }
1744 return err;
1745}
1746
1747status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001748 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001749{
Svetoslavb412f6e2015-04-29 16:50:41 -07001750 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001751}
1752
Aravind Akella701166d2013-10-08 14:59:26 -07001753status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001754 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001755}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001756
Aravind Akella8a969552014-09-28 17:52:41 -07001757int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001758 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001759 {
1760 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1761 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1762 // can release the wake-lock.
1763 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1764 Mutex::Autolock _l(mConnectionLock);
1765 mDead = true;
1766 mWakeLockRefCount = 0;
1767 updateLooperRegistrationLocked(mService->getLooper());
1768 }
1769 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001770 if (mDataInjectionMode) {
1771 // If the Looper has encountered some error in data injection mode, reset SensorService
1772 // back to normal mode.
1773 mService->resetToNormalMode();
1774 mDataInjectionMode = false;
1775 }
Aravind Akella8a969552014-09-28 17:52:41 -07001776 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001777 }
1778
1779 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001780 unsigned char buf[sizeof(sensors_event_t)];
1781 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001782 {
1783 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001784 if (numBytesRead == sizeof(sensors_event_t)) {
1785 if (!mDataInjectionMode) {
1786 ALOGE("Data injected in normal mode, dropping event"
1787 "package=%s uid=%d", mPackageName.string(), mUid);
1788 // Unregister call backs.
1789 return 0;
1790 }
1791 SensorDevice& dev(SensorDevice::getInstance());
1792 sensors_event_t sensor_event;
1793 memset(&sensor_event, 0, sizeof(sensor_event));
1794 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1795 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1796 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001797 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001798#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001799 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001800#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001801 } else if (numBytesRead == sizeof(uint32_t)) {
1802 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001803 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001804 // Sanity check to ensure there are no read errors in recv, numAcks is always
1805 // within the range and not zero. If any of the above don't hold reset
1806 // mWakeLockRefCount to zero.
1807 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1808 mWakeLockRefCount -= numAcks;
1809 } else {
1810 mWakeLockRefCount = 0;
1811 }
1812#if DEBUG_CONNECTIONS
1813 mTotalAcksReceived += numAcks;
1814#endif
1815 } else {
1816 // Read error, reset wakelock refcount.
1817 mWakeLockRefCount = 0;
1818 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001819 }
1820 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1821 // here as checkWakeLockState() will need it.
1822 if (mWakeLockRefCount == 0) {
1823 mService->checkWakeLockState();
1824 }
1825 // continue getting callbacks.
1826 return 1;
1827 }
1828
1829 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001830 // send sensor data that is stored in mEventCache for this connection.
1831 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001832 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001833 return 1;
1834}
1835
1836int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001837 size_t fifoWakeUpSensors = 0;
1838 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001839 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1840 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1841 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1842 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1843 // non wake_up sensors.
1844 if (sensor.isWakeUpSensor()) {
1845 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1846 } else {
1847 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1848 }
1849 } else {
1850 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1851 if (sensor.isWakeUpSensor()) {
1852 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1853 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1854
1855 } else {
1856 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1857 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1858
1859 }
1860 }
1861 }
1862 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1863 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001864 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001865 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001866 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001867 }
1868 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001869}
1870
Mathias Agopianfc328812010-07-14 23:41:37 -07001871// ---------------------------------------------------------------------------
1872}; // namespace android
1873