blob: b6a5d66e7ea7fc109e608f00075b47cae943ec9d [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
Aravind Akella8ef3c892015-07-10 11:24:28 -070067const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070068// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070069static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070070
Mathias Agopianfc328812010-07-14 23:41:37 -070071SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070072 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
73 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070074{
75}
76
77void SensorService::onFirstRef()
78{
Steve Blocka5512372011-12-20 16:23:08 +000079 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080080 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070081
Mathias Agopianf001c922010-11-11 17:58:51 -080082 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080083 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070084 ssize_t count = dev.getSensorList(&list);
85 if (count > 0) {
86 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070087 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070088 uint32_t virtualSensorsNeeds =
89 (1<<SENSOR_TYPE_GRAVITY) |
90 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070091 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
92 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
93 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070094
95 mLastEventSeen.setCapacity(count);
96 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070097 bool useThisSensor=true;
98
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070099 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700100 case SENSOR_TYPE_ACCELEROMETER:
101 hasAccel = true;
102 break;
103 case SENSOR_TYPE_MAGNETIC_FIELD:
104 hasMag = true;
105 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700106 case SENSOR_TYPE_ORIENTATION:
107 orientationIndex = i;
108 break;
109 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700110 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700111 hasGyro = true;
112 break;
113 case SENSOR_TYPE_GRAVITY:
114 case SENSOR_TYPE_LINEAR_ACCELERATION:
115 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700116 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
117 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
118 if (IGNORE_HARDWARE_FUSION) {
119 useThisSensor = false;
120 } else {
121 virtualSensorsNeeds &= ~(1<<list[i].type);
122 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700123 break;
124 }
Peng Xuf66684a2015-07-23 11:41:53 -0700125 if (useThisSensor) {
126 registerSensor( new HardwareSensor(list[i]) );
127 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700128 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700129
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700130 // it's safe to instantiate the SensorFusion object here
131 // (it wants to be instantiated after h/w sensors have been
132 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700133 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700134
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700135 // build the sensor list returned to users
136 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700137
Aravind Akellaf5047892015-07-20 17:29:33 -0700138 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700139 // Add Android virtual sensors if they're not already
140 // available in the HAL
Peng Xuf66684a2015-07-23 11:41:53 -0700141 Sensor aSensor;
Mathias Agopian03193062013-05-10 19:32:39 -0700142
143 aSensor = registerVirtualSensor( new RotationVectorSensor() );
144 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
145 mUserSensorList.add(aSensor);
146 }
147
Mathias Agopian03193062013-05-10 19:32:39 -0700148 aSensor = registerVirtualSensor( new OrientationSensor() );
149 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
150 // if we are doing our own rotation-vector, also add
151 // the orientation sensor and remove the HAL provided one.
152 mUserSensorList.replaceAt(aSensor, orientationIndex);
153 }
154
Peng Xuf66684a2015-07-23 11:41:53 -0700155 aSensor = registerVirtualSensor(
156 new LinearAccelerationSensor(list, count) );
157 if (virtualSensorsNeeds &
158 (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
159 mUserSensorList.add(aSensor);
160 }
161
Mathias Agopian33264862012-06-28 19:46:54 -0700162 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700163 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700164 registerVirtualSensor( new GyroDriftSensor() );
165 }
166
Peng Xuf66684a2015-07-23 11:41:53 -0700167 if (hasAccel && hasGyro) {
168 Sensor aSensor;
169
170 aSensor = registerVirtualSensor(
171 new GravitySensor(list, count) );
172 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
173 mUserSensorList.add(aSensor);
174 }
175
176 aSensor = registerVirtualSensor(
177 new GameRotationVectorSensor() );
178 if (virtualSensorsNeeds &
179 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) {
180 mUserSensorList.add(aSensor);
181 }
182 }
183
184 if (hasAccel && hasMag) {
185 Sensor aSensor;
186
187 aSensor = registerVirtualSensor(
188 new GeoMagRotationVectorSensor() );
189 if (virtualSensorsNeeds &
190 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) {
191 mUserSensorList.add(aSensor);
192 }
193 }
194
Mathias Agopian33264862012-06-28 19:46:54 -0700195 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700196 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700197
Aravind Akella5466c3d2014-08-22 16:11:10 -0700198 // Check if the device really supports batching by looking at the FIFO event
199 // counts for each sensor.
200 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700201 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700202 if (mSensorList[i].getFifoMaxEventCount() > 0) {
203 batchingSupported = true;
204 break;
205 }
206 }
207
208 if (batchingSupported) {
209 // Increase socket buffer size to a max of 100 KB for batching capabilities.
210 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
211 } else {
212 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
213 }
214
215 // Compare the socketBufferSize value against the system limits and limit
216 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700217 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
218 char line[128];
219 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
220 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700221 size_t maxSystemSocketBufferSize;
222 sscanf(line, "%zu", &maxSystemSocketBufferSize);
223 if (mSocketBufferSize > maxSystemSocketBufferSize) {
224 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700225 }
226 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700227 if (fp) {
228 fclose(fp);
229 }
230
Aravind Akella9a844cf2014-02-11 18:58:52 -0800231 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700232 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700233 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
234 mSensorEventBuffer = new sensors_event_t[minBufferSize];
235 mSensorEventScratch = new sensors_event_t[minBufferSize];
236 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700237 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700238
Aravind Akella18d6d512015-06-18 14:18:28 -0700239 mNextSensorRegIndex = 0;
240 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
241 mLastNSensorRegistrations.push();
242 }
243
244 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700245 mAckReceiver = new SensorEventAckReceiver(this);
246 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700247 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700248 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700249 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700250}
251
Mathias Agopian03193062013-05-10 19:32:39 -0700252Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800253{
254 sensors_event_t event;
255 memset(&event, 0, sizeof(event));
256
257 const Sensor sensor(s->getSensor());
258 // add to the sensor list (returned to clients)
259 mSensorList.add(sensor);
260 // add to our handle->SensorInterface mapping
261 mSensorMap.add(sensor.getHandle(), s);
262 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700263 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700264
265 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800266}
267
Mathias Agopian03193062013-05-10 19:32:39 -0700268Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800269{
Mathias Agopian03193062013-05-10 19:32:39 -0700270 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800271 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700272 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800273}
274
Mathias Agopianfc328812010-07-14 23:41:37 -0700275SensorService::~SensorService()
276{
Mathias Agopianf001c922010-11-11 17:58:51 -0800277 for (size_t i=0 ; i<mSensorMap.size() ; i++)
278 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700279}
280
Aravind Akella4949c502015-02-11 15:54:35 -0800281status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700282{
Mathias Agopianfc328812010-07-14 23:41:37 -0700283 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700284 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700285 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000286 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700287 IPCThreadState::self()->getCallingPid(),
288 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700289 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700290 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800291 return INVALID_OPERATION;
292 }
293 Mutex::Autolock _l(mLock);
294 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700295 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700296 // If already in restricted mode. Ignore.
297 if (mCurrentOperatingMode == RESTRICTED) {
298 return status_t(NO_ERROR);
299 }
300 // If in any mode other than normal, ignore.
301 if (mCurrentOperatingMode != NORMAL) {
302 return INVALID_OPERATION;
303 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700304 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800305 dev.disableAllSensors();
306 // Clear all pending flush connections for all active sensors. If one of the active
307 // connections has called flush() and the underlying sensor has been disabled before a
308 // flush complete event is returned, we need to remove the connection from this queue.
309 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
310 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
311 }
Aravind Akella841a5922015-06-29 12:37:48 -0700312 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700313 return status_t(NO_ERROR);
314 } else if (args.size() == 1 && args[0] == String16("enable")) {
315 // If currently in restricted mode, reset back to NORMAL mode else ignore.
316 if (mCurrentOperatingMode == RESTRICTED) {
317 mCurrentOperatingMode = NORMAL;
318 dev.enableAllSensors();
319 }
Aravind Akella841a5922015-06-29 12:37:48 -0700320 if (mCurrentOperatingMode == DATA_INJECTION) {
321 resetToNormalModeLocked();
322 }
323 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700324 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700325 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
326 if (mCurrentOperatingMode == NORMAL) {
327 dev.disableAllSensors();
328 status_t err = dev.setMode(DATA_INJECTION);
329 if (err == NO_ERROR) {
330 mCurrentOperatingMode = DATA_INJECTION;
331 } else {
332 // Re-enable sensors.
333 dev.enableAllSensors();
334 }
335 mWhiteListedPackage.setTo(String8(args[1]));
336 return NO_ERROR;
337 } else if (mCurrentOperatingMode == DATA_INJECTION) {
338 // Already in DATA_INJECTION mode. Treat this as a no_op.
339 return NO_ERROR;
340 } else {
341 // Transition to data injection mode supported only from NORMAL mode.
342 return INVALID_OPERATION;
343 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700344 } else if (mSensorList.size() == 0) {
345 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700346 } else {
347 // Default dump the sensor list and debugging information.
348 result.append("Sensor List:\n");
349 for (size_t i=0 ; i<mSensorList.size() ; i++) {
350 const Sensor& s(mSensorList[i]);
351 result.appendFormat(
352 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
353 s.getName().string(),
354 s.getVendor().string(),
355 s.getVersion(),
356 s.getStringType().string(),
357 s.getHandle(),
358 s.getRequiredPermission().string(),
359 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700360
Aravind Akella444f2672015-05-07 12:40:52 -0700361 const int reportingMode = s.getReportingMode();
362 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
363 result.append(" continuous | ");
364 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
365 result.append(" on-change | ");
366 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
367 result.append(" one-shot | ");
368 } else {
369 result.append(" special-trigger | ");
370 }
371
372 if (s.getMaxDelay() > 0) {
373 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
374 } else {
375 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
376 }
377
378 if (s.getMinDelay() > 0) {
379 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
380 } else {
381 result.appendFormat("minDelay=%dus |", s.getMinDelay());
382 }
383
384 if (s.getFifoMaxEventCount() > 0) {
385 result.appendFormat("FifoMax=%d events | ",
386 s.getFifoMaxEventCount());
387 } else {
388 result.append("no batching | ");
389 }
390
391 if (s.isWakeUpSensor()) {
392 result.appendFormat("wakeUp | ");
393 } else {
394 result.appendFormat("non-wakeUp | ");
395 }
396
Aravind Akella18d6d512015-06-18 14:18:28 -0700397 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
398 if (bufIndex >= 0) {
399 const CircularBuffer* buf = mLastEventSeen.valueAt(bufIndex);
400 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
401 buf->printBuffer(result);
402 } else {
403 result.append("last=<> \n");
404 }
Aravind Akella444f2672015-05-07 12:40:52 -0700405 }
406 result.append("\n");
407 }
408 SensorFusion::getInstance().dump(result);
409 SensorDevice::getInstance().dump(result);
410
411 result.append("Active sensors:\n");
412 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
413 int handle = mActiveSensors.keyAt(i);
414 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
415 getSensorName(handle).string(),
416 handle,
417 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700418 }
419
Andreas Gamped4036b62015-07-28 13:49:04 -0700420 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700421 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700422 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
423 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700424 result.appendFormat("Mode :");
425 switch(mCurrentOperatingMode) {
426 case NORMAL:
427 result.appendFormat(" NORMAL\n");
428 break;
429 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700430 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700431 break;
432 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700433 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700434 }
Aravind Akella444f2672015-05-07 12:40:52 -0700435 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700436
Aravind Akella444f2672015-05-07 12:40:52 -0700437 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
438 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
439 if (connection != 0) {
440 result.appendFormat("Connection Number: %zu \n", i);
441 connection->dump(result);
442 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700443 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700444
445 result.appendFormat("Previous Registrations:\n");
446 // Log in the reverse chronological order.
447 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
448 SENSOR_REGISTRATIONS_BUF_SIZE;
449 const int startIndex = currentIndex;
450 do {
451 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
452 if (SensorRegistrationInfo::isSentinel(reg_info)) {
453 // Ignore sentinel, proceed to next item.
454 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
455 SENSOR_REGISTRATIONS_BUF_SIZE;
456 continue;
457 }
458 if (reg_info.mActivated) {
459 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
460 "samplingRate=%dus maxReportLatency=%dus\n",
461 reg_info.mHour, reg_info.mMin, reg_info.mSec,
462 reg_info.mPackageName.string(), reg_info.mSensorHandle,
463 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
464 } else {
465 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
466 reg_info.mHour, reg_info.mMin, reg_info.mSec,
467 reg_info.mPackageName.string(), reg_info.mSensorHandle);
468 }
469 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
470 SENSOR_REGISTRATIONS_BUF_SIZE;
471 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700472 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700473 }
474 write(fd, result.string(), result.size());
475 return NO_ERROR;
476}
477
Aravind Akella9a844cf2014-02-11 18:58:52 -0800478void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700479 sensors_event_t const* buffer, const int count) {
480 for (int i=0 ; i<count ; i++) {
481 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700482 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
483 handle = buffer[i].meta_data.sensor;
484 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700485 if (connection->hasSensor(handle)) {
486 SensorInterface* sensor = mSensorMap.valueFor(handle);
487 // If this buffer has an event from a one_shot sensor and this connection is registered
488 // for this particular one_shot sensor, try cleaning up the connection.
489 if (sensor != NULL &&
490 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
491 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800492 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700493 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700494
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700495 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700496 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700497}
498
Mathias Agopianfc328812010-07-14 23:41:37 -0700499bool SensorService::threadLoop()
500{
Steve Blocka5512372011-12-20 16:23:08 +0000501 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700502
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700503 // each virtual sensor could generate an event per "real" event, that's why we need
504 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
505 // in practice, this is too aggressive, but guaranteed to be enough.
506 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
507 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
508
Mathias Agopianf001c922010-11-11 17:58:51 -0800509 SensorDevice& device(SensorDevice::getInstance());
510 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700511
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700512 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700513 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700514 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
515 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000516 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700517 break;
518 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700519
520 // Reset sensors_event_t.flags to zero for all events in the buffer.
521 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700522 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700523 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700524
525 // Make a copy of the connection vector as some connections may be removed during the
526 // course of this loop (especially when one-shot sensor events are present in the
527 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
528 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
529 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
530 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
531 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700532 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800533 Mutex::Autolock _l(mLock);
534 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
535 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
536 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
537 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
538 // releasing the wakelock.
539 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700540 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700541 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800542 bufferHasWakeUpEvent = true;
543 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700544 }
545 }
546
Aravind Akella9a844cf2014-02-11 18:58:52 -0800547 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700548 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800549 }
Aravind Akella8493b792014-09-08 15:45:47 -0700550 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800551
Mathias Agopianf001c922010-11-11 17:58:51 -0800552 // handle virtual sensors
553 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700554 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800555 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800556 if (activeVirtualSensorCount) {
557 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700558 SensorFusion& fusion(SensorFusion::getInstance());
559 if (fusion.isEnabled()) {
560 for (size_t i=0 ; i<size_t(count) ; i++) {
561 fusion.process(event[i]);
562 }
563 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700564 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800565 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700566 if (count + k >= minBufferSize) {
567 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700568 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700569 count, k, minBufferSize);
570 break;
571 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800572 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800573 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700574 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700575 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800576 k++;
577 }
578 }
579 }
580 if (k) {
581 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700582 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800583 count += k;
584 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700585 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700586 }
587 }
588 }
589
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700590 // handle backward compatibility for RotationVector sensor
591 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
592 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700593 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700594 // All the 4 components of the quaternion should be available
595 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700596 mSensorEventBuffer[i].data[4] = -1;
597 }
598 }
599 }
600
601 // Map flush_complete_events in the buffer to SensorEventConnections which called
602 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
603 // SensorEventConnection mapped to the corresponding flush_complete_event in
604 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
605 for (int i = 0; i < count; ++i) {
606 mMapFlushEventsToConnections[i] = NULL;
607 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
608 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
609 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
610 if (rec != NULL) {
611 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
612 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700613 }
614 }
615 }
616
Aravind Akella9a844cf2014-02-11 18:58:52 -0800617 // Send our events to clients. Check the state of wake lock for each client and release the
618 // lock if none of the clients need it.
619 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700620 size_t numConnections = activeConnections.size();
621 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700622 if (activeConnections[i] != 0) {
623 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700624 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700625 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700626 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
627 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700628 if (activeConnections[i]->hasOneShotSensors()) {
629 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
630 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700631 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800632 }
633 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700634
Aravind Akella9a844cf2014-02-11 18:58:52 -0800635 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700636 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800637 }
Aravind Akella8493b792014-09-08 15:45:47 -0700638 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700639
Steve Block3c20fbe2012-01-05 23:22:43 +0000640 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800641 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700642 return false;
643}
644
Aravind Akella56ae4262014-07-10 16:01:10 -0700645sp<Looper> SensorService::getLooper() const {
646 return mLooper;
647}
648
Aravind Akellab4373ac2014-10-29 17:55:20 -0700649void SensorService::resetAllWakeLockRefCounts() {
650 SortedVector< sp<SensorEventConnection> > activeConnections;
651 populateActiveConnections(&activeConnections);
652 {
653 Mutex::Autolock _l(mLock);
654 for (size_t i=0 ; i < activeConnections.size(); ++i) {
655 if (activeConnections[i] != 0) {
656 activeConnections[i]->resetWakeLockRefCount();
657 }
658 }
659 setWakeLockAcquiredLocked(false);
660 }
661}
662
663void SensorService::setWakeLockAcquiredLocked(bool acquire) {
664 if (acquire) {
665 if (!mWakeLockAcquired) {
666 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
667 mWakeLockAcquired = true;
668 }
669 mLooper->wake();
670 } else {
671 if (mWakeLockAcquired) {
672 release_wake_lock(WAKE_LOCK_NAME);
673 mWakeLockAcquired = false;
674 }
675 }
676}
677
Aravind Akellab4373ac2014-10-29 17:55:20 -0700678bool SensorService::isWakeLockAcquired() {
679 Mutex::Autolock _l(mLock);
680 return mWakeLockAcquired;
681}
682
Aravind Akella56ae4262014-07-10 16:01:10 -0700683bool SensorService::SensorEventAckReceiver::threadLoop() {
684 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700685 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700686 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700687 bool wakeLockAcquired = mService->isWakeLockAcquired();
688 int timeout = -1;
689 if (wakeLockAcquired) timeout = 5000;
690 int ret = looper->pollOnce(timeout);
691 if (ret == ALOOPER_POLL_TIMEOUT) {
692 mService->resetAllWakeLockRefCounts();
693 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700694 } while(!Thread::exitPending());
695 return false;
696}
697
Aravind Akella9a844cf2014-02-11 18:58:52 -0800698void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800699 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800700 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700701 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
702 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
703 if (circular_buf == NULL) {
704 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800705 }
Aravind Akella444f2672015-05-07 12:40:52 -0700706 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800707 }
708 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800709}
710
Mathias Agopianf001c922010-11-11 17:58:51 -0800711void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
712{
713 struct compar {
714 static int cmp(void const* lhs, void const* rhs) {
715 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
716 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700717 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800718 }
719 };
720 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
721}
722
Mathias Agopian5d270722010-07-19 15:20:39 -0700723String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700724 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700725 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700726 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700727 if (sensor.getHandle() == handle) {
728 return sensor.getName();
729 }
730 }
731 String8 result("unknown");
732 return result;
733}
734
Aravind Akellab4099e72013-10-15 15:43:10 -0700735bool SensorService::isVirtualSensor(int handle) const {
736 SensorInterface* sensor = mSensorMap.valueFor(handle);
737 return sensor->isVirtual();
738}
739
Aravind Akella9a844cf2014-02-11 18:58:52 -0800740bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700741 int handle = event.sensor;
742 if (event.type == SENSOR_TYPE_META_DATA) {
743 handle = event.meta_data.sensor;
744 }
745 SensorInterface* sensor = mSensorMap.valueFor(handle);
746 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800747}
748
Aravind Akella6c2664a2014-08-13 12:24:50 -0700749SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
750 return mActiveSensors.valueFor(handle);
751}
752
Svetoslavb412f6e2015-04-29 16:50:41 -0700753Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700754{
Mathias Agopian33264862012-06-28 19:46:54 -0700755 char value[PROPERTY_VALUE_MAX];
756 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000757 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
758 mUserSensorListDebug : mUserSensorList;
759 Vector<Sensor> accessibleSensorList;
760 for (size_t i = 0; i < initialSensorList.size(); i++) {
761 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700762 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000763 accessibleSensorList.add(sensor);
764 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700765 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100766 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700767 sensor.getRequiredPermission().string(),
768 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000769 }
Mathias Agopian33264862012-06-28 19:46:54 -0700770 }
Aravind Akella70018042014-04-07 22:52:37 +0000771 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700772}
773
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700774sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700775 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700776 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
777 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
778 return NULL;
779 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700780
781 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700782 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
783 // operating in DI mode.
784 if (requestedMode == DATA_INJECTION) {
785 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
786 if (!isWhiteListedPackage(packageName)) return NULL;
787 }
788
Mathias Agopian5307d172012-09-18 17:02:43 -0700789 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700790 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700791 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700792 if (requestedMode == DATA_INJECTION) {
793 if (mActiveConnections.indexOf(result) < 0) {
794 mActiveConnections.add(result);
795 }
796 // Add the associated file descriptor to the Looper for polling whenever there is data to
797 // be injected.
798 result->updateLooperRegistration(mLooper);
799 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700800 return result;
801}
802
Aravind Akella841a5922015-06-29 12:37:48 -0700803int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700804 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700805 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700806}
807
808status_t SensorService::resetToNormalMode() {
809 Mutex::Autolock _l(mLock);
810 return resetToNormalModeLocked();
811}
812
813status_t SensorService::resetToNormalModeLocked() {
814 SensorDevice& dev(SensorDevice::getInstance());
815 dev.enableAllSensors();
816 status_t err = dev.setMode(NORMAL);
817 mCurrentOperatingMode = NORMAL;
818 return err;
819}
820
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800821void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700822{
823 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800824 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700825 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700826 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700827 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800828 int handle = mActiveSensors.keyAt(i);
829 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700830 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800831 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000832 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800833 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800834 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800835 }
Aravind Akella8a969552014-09-28 17:52:41 -0700836 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800837 }
838 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700839 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000840 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700841 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700842 c, i, handle);
843
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800844 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000845 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700846 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800847 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700848 delete rec;
849 size--;
850 } else {
851 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700852 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700853 }
Aravind Akella8a969552014-09-28 17:52:41 -0700854 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700855 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700856 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800857 if (c->needsWakeLock()) {
858 checkWakeLockStateLocked();
859 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700860}
861
Aravind Akella70018042014-04-07 22:52:37 +0000862Sensor SensorService::getSensorFromHandle(int handle) const {
863 return mSensorMap.valueFor(handle)->getSensor();
864}
865
Mathias Agopianfc328812010-07-14 23:41:37 -0700866status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700867 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
868 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700869{
Mathias Agopian50df2952010-07-19 19:09:10 -0700870 if (mInitCheck != NO_ERROR)
871 return mInitCheck;
872
Mathias Agopianf001c922010-11-11 17:58:51 -0800873 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700874 if (sensor == NULL) {
875 return BAD_VALUE;
876 }
Aravind Akella70018042014-04-07 22:52:37 +0000877
Svetoslavb412f6e2015-04-29 16:50:41 -0700878 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000879 return BAD_VALUE;
880 }
881
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700882 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700883 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
884 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800885 return INVALID_OPERATION;
886 }
887
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700888 SensorRecord* rec = mActiveSensors.valueFor(handle);
889 if (rec == 0) {
890 rec = new SensorRecord(connection);
891 mActiveSensors.add(handle, rec);
892 if (sensor->isVirtual()) {
893 mActiveVirtualSensors.add(handle, sensor);
894 }
895 } else {
896 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800897 // this sensor is already activated, but we are adding a connection that uses it.
898 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700899 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700900 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800901 // NOTE: The wake_up flag of this event may get set to
902 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700903 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
904 if (circular_buf) {
905 sensors_event_t event;
906 memset(&event, 0, sizeof(event));
907 // It is unlikely that this buffer is empty as the sensor is already active.
908 // One possible corner case may be two applications activating an on-change
909 // sensor at the same time.
910 if(circular_buf->populateLastEvent(&event)) {
911 event.sensor = handle;
912 if (event.version == sizeof(sensors_event_t)) {
913 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
914 setWakeLockAcquiredLocked(true);
915 }
916 connection->sendEvents(&event, 1, NULL);
917 if (!connection->needsWakeLock() && mWakeLockAcquired) {
918 checkWakeLockStateLocked();
919 }
920 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800921 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700922 }
923 }
924 }
925 }
926
927 if (connection->addSensor(handle)) {
928 BatteryService::enableSensor(connection->getUid(), handle);
929 // the sensor was added (which means it wasn't already there)
930 // so, see if this connection becomes active
931 if (mActiveConnections.indexOf(connection) < 0) {
932 mActiveConnections.add(connection);
933 }
934 } else {
935 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
936 handle, connection.get());
937 }
938
Aravind Akella724d91d2013-06-27 12:04:23 -0700939 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
940 if (samplingPeriodNs < minDelayNs) {
941 samplingPeriodNs = minDelayNs;
942 }
943
Aravind Akella6c2664a2014-08-13 12:24:50 -0700944 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
945 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700946 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
947
Aravind Akella4949c502015-02-11 15:54:35 -0800948 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700949 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700950
Peng Xu20483c42015-10-26 15:14:43 -0700951 // Call flush() before calling activate() on the sensor. Wait for a first
952 // flush complete event before sending events on this connection. Ignore
953 // one-shot sensors which don't support flush(). Ignore on-change sensors
954 // to maintain the on-change logic (any on-change events except the initial
955 // one should be trigger by a change in value). Also if this sensor isn't
956 // already active, don't call flush().
957 if (err == NO_ERROR &&
958 sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
959 sensor->getSensor().getReportingMode() != AREPORTING_MODE_ON_CHANGE &&
Aravind Akella5466c3d2014-08-22 16:11:10 -0700960 rec->getNumConnections() > 1) {
961 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700962 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700963 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700964 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700965 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700966 } else {
967 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700968 }
969 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700970
971 if (err == NO_ERROR) {
972 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
973 err = sensor->activate(connection.get(), true);
974 }
975
Aravind Akella8a969552014-09-28 17:52:41 -0700976 if (err == NO_ERROR) {
977 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700978 SensorRegistrationInfo &reg_info =
979 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
980 reg_info.mSensorHandle = handle;
981 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
982 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
983 reg_info.mActivated = true;
984 reg_info.mPackageName = connection->getPackageName();
985 time_t rawtime = time(NULL);
986 struct tm * timeinfo = localtime(&rawtime);
987 reg_info.mHour = timeinfo->tm_hour;
988 reg_info.mMin = timeinfo->tm_min;
989 reg_info.mSec = timeinfo->tm_sec;
990 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700991 }
992
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700993 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700994 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700995 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700996 }
997 return err;
998}
999
1000status_t SensorService::disable(const sp<SensorEventConnection>& connection,
1001 int handle)
1002{
Mathias Agopian50df2952010-07-19 19:09:10 -07001003 if (mInitCheck != NO_ERROR)
1004 return mInitCheck;
1005
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001006 Mutex::Autolock _l(mLock);
1007 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001008 if (err == NO_ERROR) {
1009 SensorInterface* sensor = mSensorMap.valueFor(handle);
1010 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001011
1012 }
1013 if (err == NO_ERROR) {
1014 SensorRegistrationInfo &reg_info =
1015 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1016 reg_info.mActivated = false;
1017 reg_info.mPackageName= connection->getPackageName();
1018 reg_info.mSensorHandle = handle;
1019 time_t rawtime = time(NULL);
1020 struct tm * timeinfo = localtime(&rawtime);
1021 reg_info.mHour = timeinfo->tm_hour;
1022 reg_info.mMin = timeinfo->tm_min;
1023 reg_info.mSec = timeinfo->tm_sec;
1024 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001025 }
1026 return err;
1027}
1028
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001029status_t SensorService::cleanupWithoutDisable(
1030 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001031 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001032 return cleanupWithoutDisableLocked(connection, handle);
1033}
1034
1035status_t SensorService::cleanupWithoutDisableLocked(
1036 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001037 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001038 if (rec) {
1039 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001040 if (connection->removeSensor(handle)) {
1041 BatteryService::disableSensor(connection->getUid(), handle);
1042 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001043 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001044 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001045 mActiveConnections.remove(connection);
1046 }
1047 // see if this sensor becomes inactive
1048 if (rec->removeConnection(connection)) {
1049 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001050 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001051 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001052 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001053 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001054 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001055 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001056}
1057
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001058status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001059 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001060{
Mathias Agopian50df2952010-07-19 19:09:10 -07001061 if (mInitCheck != NO_ERROR)
1062 return mInitCheck;
1063
Mathias Agopianae09d652011-11-01 17:37:49 -07001064 SensorInterface* sensor = mSensorMap.valueFor(handle);
1065 if (!sensor)
1066 return BAD_VALUE;
1067
Svetoslavb412f6e2015-04-29 16:50:41 -07001068 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001069 return BAD_VALUE;
1070 }
1071
Mathias Agopian1cd70002010-07-21 15:59:50 -07001072 if (ns < 0)
1073 return BAD_VALUE;
1074
Mathias Agopian62569ec2011-11-07 21:21:47 -08001075 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1076 if (ns < minDelayNs) {
1077 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001078 }
1079
Mathias Agopianf001c922010-11-11 17:58:51 -08001080 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001081}
1082
Svetoslavb412f6e2015-04-29 16:50:41 -07001083status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1084 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001085 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001086 SensorDevice& dev(SensorDevice::getInstance());
1087 const int halVersion = dev.getHalDeviceVersion();
1088 status_t err(NO_ERROR);
1089 Mutex::Autolock _l(mLock);
1090 // Loop through all sensors for this connection and call flush on each of them.
1091 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1092 const int handle = connection->mSensorInfo.keyAt(i);
1093 SensorInterface* sensor = mSensorMap.valueFor(handle);
1094 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1095 ALOGE("flush called on a one-shot sensor");
1096 err = INVALID_OPERATION;
1097 continue;
1098 }
Aravind Akella8493b792014-09-08 15:45:47 -07001099 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001100 // For older devices just increment pending flush count which will send a trivial
1101 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001102 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001103 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001104 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1105 err = INVALID_OPERATION;
1106 continue;
1107 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001108 status_t err_flush = sensor->flush(connection.get(), handle);
1109 if (err_flush == NO_ERROR) {
1110 SensorRecord* rec = mActiveSensors.valueFor(handle);
1111 if (rec != NULL) rec->addPendingFlushConnection(connection);
1112 }
1113 err = (err_flush != NO_ERROR) ? err_flush : err;
1114 }
Aravind Akella70018042014-04-07 22:52:37 +00001115 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001116 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001117}
Aravind Akella70018042014-04-07 22:52:37 +00001118
Svetoslavb412f6e2015-04-29 16:50:41 -07001119bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1120 const String16& opPackageName) {
1121 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001122
Svetoslavb412f6e2015-04-29 16:50:41 -07001123 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001124 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001125 }
1126
1127 bool hasPermission = false;
1128
1129 // Runtime permissions can't use the cache as they may change.
1130 if (sensor.isRequiredPermissionRuntime()) {
1131 hasPermission = checkPermission(String16(requiredPermission),
1132 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001133 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001134 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1135 }
1136
1137 if (!hasPermission) {
1138 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1139 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001140 return false;
1141 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001142
1143 const int32_t opCode = sensor.getRequiredAppOp();
1144 if (opCode >= 0) {
1145 AppOpsManager appOps;
1146 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1147 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001148 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001149 operation, sensor.getName().string(), opCode);
1150 return false;
1151 }
1152 }
1153
1154 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001155}
1156
Aravind Akella9a844cf2014-02-11 18:58:52 -08001157void SensorService::checkWakeLockState() {
1158 Mutex::Autolock _l(mLock);
1159 checkWakeLockStateLocked();
1160}
1161
1162void SensorService::checkWakeLockStateLocked() {
1163 if (!mWakeLockAcquired) {
1164 return;
1165 }
1166 bool releaseLock = true;
1167 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1168 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1169 if (connection != 0) {
1170 if (connection->needsWakeLock()) {
1171 releaseLock = false;
1172 break;
1173 }
1174 }
1175 }
1176 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001177 setWakeLockAcquiredLocked(false);
1178 }
1179}
1180
1181void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1182 Mutex::Autolock _l(mLock);
1183 connection->writeToSocketFromCache();
1184 if (connection->needsWakeLock()) {
1185 setWakeLockAcquiredLocked(true);
1186 }
1187}
1188
1189void SensorService::populateActiveConnections(
1190 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1191 Mutex::Autolock _l(mLock);
1192 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1193 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1194 if (connection != 0) {
1195 activeConnections->add(connection);
1196 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001197 }
1198}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001199
Aravind Akella4949c502015-02-11 15:54:35 -08001200bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001201 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001202}
1203
Aravind Akella444f2672015-05-07 12:40:52 -07001204int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1205 switch (sensor_event_type) {
1206 case SENSOR_TYPE_ROTATION_VECTOR:
1207 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1208 return 5;
1209
1210 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1211 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1212 return 6;
1213
1214 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1215 return 4;
1216
1217 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1218 case SENSOR_TYPE_STEP_DETECTOR:
1219 case SENSOR_TYPE_STEP_COUNTER:
1220 return 1;
1221
1222 default:
1223 return 3;
1224 }
1225}
1226
Mathias Agopianfc328812010-07-14 23:41:37 -07001227// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001228SensorService::SensorRecord::SensorRecord(
1229 const sp<SensorEventConnection>& connection)
1230{
1231 mConnections.add(connection);
1232}
1233
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001234bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001235 const sp<SensorEventConnection>& connection)
1236{
1237 if (mConnections.indexOf(connection) < 0) {
1238 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001239 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001240 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001241 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001242}
1243
1244bool SensorService::SensorRecord::removeConnection(
1245 const wp<SensorEventConnection>& connection)
1246{
1247 ssize_t index = mConnections.indexOf(connection);
1248 if (index >= 0) {
1249 mConnections.removeItemsAt(index, 1);
1250 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001251 // Remove this connections from the queue of flush() calls made on this sensor.
1252 for (Vector< wp<SensorEventConnection> >::iterator it =
1253 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001254
Aravind Akella6c2664a2014-08-13 12:24:50 -07001255 if (it->unsafe_get() == connection.unsafe_get()) {
1256 it = mPendingFlushConnections.erase(it);
1257 } else {
1258 ++it;
1259 }
1260 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001261 return mConnections.size() ? false : true;
1262}
1263
Aravind Akella6c2664a2014-08-13 12:24:50 -07001264void SensorService::SensorRecord::addPendingFlushConnection(
1265 const sp<SensorEventConnection>& connection) {
1266 mPendingFlushConnections.add(connection);
1267}
1268
1269void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1270 if (mPendingFlushConnections.size() > 0) {
1271 mPendingFlushConnections.removeAt(0);
1272 }
1273}
1274
1275SensorService::SensorEventConnection *
1276SensorService::SensorRecord::getFirstPendingFlushConnection() {
1277 if (mPendingFlushConnections.size() > 0) {
1278 return mPendingFlushConnections[0].unsafe_get();
1279 }
1280 return NULL;
1281}
1282
Aravind Akella4949c502015-02-11 15:54:35 -08001283void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1284 mPendingFlushConnections.clear();
1285}
1286
Aravind Akella18d6d512015-06-18 14:18:28 -07001287
1288// ---------------------------------------------------------------------------
1289SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
1290 mTimestamp = -1;
1291 const int numData = SensorService::getNumEventsForSensorType(sensorType);
1292 if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
1293 mStepCounter = 0;
1294 } else {
1295 mData = new float[numData];
1296 for (int i = 0; i < numData; ++i) {
1297 mData[i] = -1.0;
1298 }
1299 }
1300 mHour = mMin = mSec = INT32_MIN;
1301}
1302
1303bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
1304 return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
1305}
Aravind Akella444f2672015-05-07 12:40:52 -07001306// --------------------------------------------------------------------------
1307SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1308 mNextInd = 0;
Aravind Akella18d6d512015-06-18 14:18:28 -07001309 mBufSize = CIRCULAR_BUF_SIZE;
1310 if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
1311 sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
1312 sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
1313 mBufSize = CIRCULAR_BUF_SIZE * 5;
1314 }
1315 mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
Aravind Akella444f2672015-05-07 12:40:52 -07001316 mSensorType = sensor_event_type;
Aravind Akella18d6d512015-06-18 14:18:28 -07001317 for (int i = 0; i < mBufSize; ++i) {
1318 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
Aravind Akella444f2672015-05-07 12:40:52 -07001319 }
1320}
1321
1322void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1323 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1324 curr_event->mTimestamp = sensor_event.timestamp;
1325 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1326 curr_event->mStepCounter = sensor_event.u64.step_counter;
1327 } else {
1328 memcpy(curr_event->mData, sensor_event.data,
1329 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1330 }
1331 time_t rawtime = time(NULL);
1332 struct tm * timeinfo = localtime(&rawtime);
1333 curr_event->mHour = timeinfo->tm_hour;
1334 curr_event->mMin = timeinfo->tm_min;
1335 curr_event->mSec = timeinfo->tm_sec;
Aravind Akella18d6d512015-06-18 14:18:28 -07001336 mNextInd = (mNextInd + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001337}
1338
1339void SensorService::CircularBuffer::printBuffer(String8& result) const {
1340 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1341 int i = mNextInd, eventNum = 1;
Aravind Akella18d6d512015-06-18 14:18:28 -07001342 result.appendFormat("last %d events = < ", mBufSize);
Aravind Akella444f2672015-05-07 12:40:52 -07001343 do {
Aravind Akella18d6d512015-06-18 14:18:28 -07001344 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001345 // Sentinel, ignore.
Aravind Akella18d6d512015-06-18 14:18:28 -07001346 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001347 continue;
1348 }
1349 result.appendFormat("%d) ", eventNum++);
1350 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001351 result.appendFormat("%" PRIu64 ",", mTrimmedSensorEventArr[i]->mStepCounter);
Aravind Akella444f2672015-05-07 12:40:52 -07001352 } else {
1353 for (int j = 0; j < numData; ++j) {
1354 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1355 }
1356 }
Andreas Gamped4036b62015-07-28 13:49:04 -07001357 result.appendFormat("%" PRId64 " %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
Aravind Akella444f2672015-05-07 12:40:52 -07001358 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1359 mTrimmedSensorEventArr[i]->mSec);
Aravind Akella18d6d512015-06-18 14:18:28 -07001360 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001361 } while (i != mNextInd);
1362 result.appendFormat(">\n");
1363}
1364
1365bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
Aravind Akella18d6d512015-06-18 14:18:28 -07001366 int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001367 // Check if the buffer is empty.
Aravind Akella18d6d512015-06-18 14:18:28 -07001368 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001369 return false;
1370 }
1371 event->version = sizeof(sensors_event_t);
1372 event->type = mSensorType;
1373 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1374 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1375 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1376 } else {
1377 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1378 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1379 }
1380 return true;
1381}
1382
1383SensorService::CircularBuffer::~CircularBuffer() {
Aravind Akella18d6d512015-06-18 14:18:28 -07001384 for (int i = 0; i < mBufSize; ++i) {
Aravind Akella444f2672015-05-07 12:40:52 -07001385 delete mTrimmedSensorEventArr[i];
1386 }
1387 delete [] mTrimmedSensorEventArr;
1388}
1389
Mathias Agopianfc328812010-07-14 23:41:37 -07001390// ---------------------------------------------------------------------------
1391
1392SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001393 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1394 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001395 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001396 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1397 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001398 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001399#if DEBUG_CONNECTIONS
1400 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001401 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001402#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001403}
1404
Aravind Akella56ae4262014-07-10 16:01:10 -07001405SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001406 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001407 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001408 if (mEventCache != NULL) {
1409 delete mEventCache;
1410 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001411}
1412
Aravind Akella56ae4262014-07-10 16:01:10 -07001413void SensorService::SensorEventConnection::onFirstRef() {
1414 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001415}
1416
Aravind Akella9a844cf2014-02-11 18:58:52 -08001417bool SensorService::SensorEventConnection::needsWakeLock() {
1418 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001419 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001420}
1421
Aravind Akellab4373ac2014-10-29 17:55:20 -07001422void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1423 Mutex::Autolock _l(mConnectionLock);
1424 mWakeLockRefCount = 0;
1425}
1426
Aravind Akella4c8b9512013-09-05 17:03:38 -07001427void SensorService::SensorEventConnection::dump(String8& result) {
1428 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8ef3c892015-07-10 11:24:28 -07001429 result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella18d6d512015-06-18 14:18:28 -07001430 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
1431 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
1432 mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001433 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1434 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001435 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001436 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001437 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001438 flushInfo.mFirstFlushPending ? "First flush pending" :
1439 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001440 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001441 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001442#if DEBUG_CONNECTIONS
1443 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1444 " total_acks_needed %d | total_acks_recvd %d\n",
1445 mEventsReceived,
1446 mEventsSent,
1447 mEventsSentFromCache,
1448 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1449 mTotalAcksNeeded,
1450 mTotalAcksReceived);
1451#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001452}
1453
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001454bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001455 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001456 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1457 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001458 return false;
1459 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001460 if (mSensorInfo.indexOfKey(handle) < 0) {
1461 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001462 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001463 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001464 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001465}
1466
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001467bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001468 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001469 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001470 return true;
1471 }
1472 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001473}
1474
1475bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001476 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001477 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001478}
1479
1480bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001481 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001482 return mSensorInfo.size() ? true : false;
1483}
1484
Aravind Akella8493b792014-09-08 15:45:47 -07001485bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1486 Mutex::Autolock _l(mConnectionLock);
1487 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1488 const int handle = mSensorInfo.keyAt(i);
1489 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1490 return true;
1491 }
1492 }
1493 return false;
1494}
1495
Aravind Akella4949c502015-02-11 15:54:35 -08001496String8 SensorService::SensorEventConnection::getPackageName() const {
1497 return mPackageName;
1498}
1499
Aravind Akella4c8b9512013-09-05 17:03:38 -07001500void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1501 bool value) {
1502 Mutex::Autolock _l(mConnectionLock);
1503 ssize_t index = mSensorInfo.indexOfKey(handle);
1504 if (index >= 0) {
1505 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1506 flushInfo.mFirstFlushPending = value;
1507 }
1508}
1509
Aravind Akella8a969552014-09-28 17:52:41 -07001510void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1511 Mutex::Autolock _l(mConnectionLock);
1512 updateLooperRegistrationLocked(looper);
1513}
1514
1515void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1516 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001517 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1518 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001519 // If all sensors are unregistered OR Looper has encountered an error, we
1520 // can remove the Fd from the Looper if it has been previously added.
1521 if (!isConnectionActive || mDead) {
1522 if (mHasLooperCallbacks) {
1523 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1524 looper->removeFd(mChannel->getSendFd());
1525 mHasLooperCallbacks = false;
1526 }
1527 return;
1528 }
1529
1530 int looper_flags = 0;
1531 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001532 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001533 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1534 const int handle = mSensorInfo.keyAt(i);
1535 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1536 looper_flags |= ALOOPER_EVENT_INPUT;
1537 break;
1538 }
1539 }
1540 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1541 // the fd has already been added, remove it. This is likely to happen when ALL the
1542 // events stored in the cache have been sent to the corresponding app.
1543 if (looper_flags == 0) {
1544 if (mHasLooperCallbacks) {
1545 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1546 looper->removeFd(mChannel->getSendFd());
1547 mHasLooperCallbacks = false;
1548 }
1549 return;
1550 }
1551 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1552 // registered for wake-up sensors OR for sending events in the cache.
1553 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1554 if (ret == 1) {
1555 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1556 mHasLooperCallbacks = true;
1557 } else {
1558 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1559 }
1560}
1561
1562void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1563 Mutex::Autolock _l(mConnectionLock);
1564 ssize_t index = mSensorInfo.indexOfKey(handle);
1565 if (index >= 0) {
1566 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1567 flushInfo.mPendingFlushEventsToSend++;
1568 }
1569}
1570
Mathias Agopianfc328812010-07-14 23:41:37 -07001571status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001572 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001573 sensors_event_t* scratch,
1574 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001575 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001576 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001577 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001578 if (scratch) {
1579 size_t i=0;
1580 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001581 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001582 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1583 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001584 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001585 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1586 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1587 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001588 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001589 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001590 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001591 // Check if this connection has registered for this sensor. If not continue to the
1592 // next sensor_event.
1593 if (index < 0) {
1594 ++i;
1595 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001596 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001597
Aravind Akella56ae4262014-07-10 16:01:10 -07001598 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001599 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001600 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1601 this == mapFlushEventsToConnections[i]) {
1602 flushInfo.mFirstFlushPending = false;
1603 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1604 buffer[i].meta_data.sensor);
1605 ++i;
1606 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001607 }
1608
1609 // If there is a pending flush complete event for this sensor on this connection,
1610 // ignore the event and proceed to the next.
1611 if (flushInfo.mFirstFlushPending) {
1612 ++i;
1613 continue;
1614 }
1615
1616 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001617 // Keep copying events into the scratch buffer as long as they are regular
1618 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1619 // from the same sensor_handle AND the current connection is mapped to the
1620 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001621 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001622 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001623 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001624 }
1625 ++i;
1626 } else {
1627 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001628 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001629 }
Aravind Akella8493b792014-09-08 15:45:47 -07001630 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1631 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001632 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001633 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001634 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001635 } else {
1636 scratch = const_cast<sensors_event_t *>(buffer);
1637 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001638 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001639
Aravind Akella6c2664a2014-08-13 12:24:50 -07001640 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001641 // Early return if there are no events for this connection.
1642 if (count == 0) {
1643 return status_t(NO_ERROR);
1644 }
1645
1646#if DEBUG_CONNECTIONS
1647 mEventsReceived += count;
1648#endif
1649 if (mCacheSize != 0) {
1650 // There are some events in the cache which need to be sent first. Copy this buffer to
1651 // the end of cache.
1652 if (mCacheSize + count <= mMaxCacheSize) {
1653 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1654 mCacheSize += count;
1655 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001656 // Check if any new sensors have registered on this connection which may have increased
1657 // the max cache size that is desired.
1658 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1659 reAllocateCacheLocked(scratch, count);
1660 return status_t(NO_ERROR);
1661 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001662 // Some events need to be dropped.
1663 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1664 if (remaningCacheSize != 0) {
1665 memcpy(&mEventCache[mCacheSize], scratch,
1666 remaningCacheSize * sizeof(sensors_event_t));
1667 }
1668 int numEventsDropped = count - remaningCacheSize;
1669 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1670 // Drop the first "numEventsDropped" in the cache.
1671 memmove(mEventCache, &mEventCache[numEventsDropped],
1672 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1673
1674 // Copy the remainingEvents in scratch buffer to the end of cache.
1675 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1676 numEventsDropped * sizeof(sensors_event_t));
1677 }
1678 return status_t(NO_ERROR);
1679 }
1680
Aravind Akella6c2664a2014-08-13 12:24:50 -07001681 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1682 if (index_wake_up_event >= 0) {
1683 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1684 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001685#if DEBUG_CONNECTIONS
1686 ++mTotalAcksNeeded;
1687#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001688 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001689
1690 // NOTE: ASensorEvent and sensors_event_t are the same type.
1691 ssize_t size = SensorEventQueue::write(mChannel,
1692 reinterpret_cast<ASensorEvent const*>(scratch), count);
1693 if (size < 0) {
1694 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001695 if (index_wake_up_event >= 0) {
1696 // If there was a wake_up sensor_event, reset the flag.
1697 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001698 if (mWakeLockRefCount > 0) {
1699 --mWakeLockRefCount;
1700 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001701#if DEBUG_CONNECTIONS
1702 --mTotalAcksNeeded;
1703#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001704 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001705 if (mEventCache == NULL) {
1706 mMaxCacheSize = computeMaxCacheSizeLocked();
1707 mEventCache = new sensors_event_t[mMaxCacheSize];
1708 mCacheSize = 0;
1709 }
1710 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1711 mCacheSize += count;
1712
1713 // Add this file descriptor to the looper to get a callback when this fd is available for
1714 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001715 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001716 return size;
1717 }
1718
1719#if DEBUG_CONNECTIONS
1720 if (size > 0) {
1721 mEventsSent += count;
1722 }
1723#endif
1724
1725 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1726}
1727
Aravind Akella6c2664a2014-08-13 12:24:50 -07001728void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1729 int count) {
1730 sensors_event_t *eventCache_new;
1731 const int new_cache_size = computeMaxCacheSizeLocked();
1732 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1733 eventCache_new = new sensors_event_t[new_cache_size];
1734 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1735 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1736
1737 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1738 new_cache_size);
1739
1740 delete mEventCache;
1741 mEventCache = eventCache_new;
1742 mCacheSize += count;
1743 mMaxCacheSize = new_cache_size;
1744}
1745
1746void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1747 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001748 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001749 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001750 // Loop through all the sensors for this connection and check if there are any pending
1751 // flush complete events to be sent.
1752 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1753 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1754 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001755 const int sensor_handle = mSensorInfo.keyAt(i);
1756 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001757 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1758 if (wakeUpSensor) {
1759 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001760 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1761 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001762 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1763 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001764 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001765 return;
1766 }
1767 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1768 flushCompleteEvent.meta_data.sensor);
1769 flushInfo.mPendingFlushEventsToSend--;
1770 }
1771 }
1772}
1773
Aravind Akellab4373ac2014-10-29 17:55:20 -07001774void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001775 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1776 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1777 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1778 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001779 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001780 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001781 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001782 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001783 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001784 int index_wake_up_event =
1785 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1786 if (index_wake_up_event >= 0) {
1787 mEventCache[index_wake_up_event + numEventsSent].flags |=
1788 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1789 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001790#if DEBUG_CONNECTIONS
1791 ++mTotalAcksNeeded;
1792#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001793 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001794
Aravind Akella56ae4262014-07-10 16:01:10 -07001795 ssize_t size = SensorEventQueue::write(mChannel,
1796 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001797 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001798 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001799 if (index_wake_up_event >= 0) {
1800 // If there was a wake_up sensor_event, reset the flag.
1801 mEventCache[index_wake_up_event + numEventsSent].flags &=
1802 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001803 if (mWakeLockRefCount > 0) {
1804 --mWakeLockRefCount;
1805 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001806#if DEBUG_CONNECTIONS
1807 --mTotalAcksNeeded;
1808#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001809 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001810 memmove(mEventCache, &mEventCache[numEventsSent],
1811 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1812 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001813 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001814 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001815 return;
1816 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001817 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001818#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001819 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001820#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001821 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001822 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1823 // All events from the cache have been sent. Reset cache size to zero.
1824 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001825 // There are no more events in the cache. We don't need to poll for write on the fd.
1826 // Update Looper registration.
1827 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001828}
1829
Aravind Akellac551eac2013-10-14 17:04:42 -07001830void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001831 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001832 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001833 // Count flushComplete events in the events that are about to the dropped. These will be sent
1834 // separately before the next batch of events.
1835 for (int j = 0; j < numEventsDropped; ++j) {
1836 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1837 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1838 flushInfo.mPendingFlushEventsToSend++;
1839 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1840 flushInfo.mPendingFlushEventsToSend);
1841 }
1842 }
1843 return;
1844}
1845
Aravind Akella6c2664a2014-08-13 12:24:50 -07001846int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1847 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001848 for (int i = 0; i < count; ++i) {
1849 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001850 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001851 }
1852 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001853 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001854}
1855
Mathias Agopianb3989272011-10-20 18:42:02 -07001856sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001857{
1858 return mChannel;
1859}
1860
1861status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001862 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1863 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001864{
1865 status_t err;
1866 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001867 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001868 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001869
Mathias Agopianfc328812010-07-14 23:41:37 -07001870 } else {
1871 err = mService->disable(this, handle);
1872 }
1873 return err;
1874}
1875
1876status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001877 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001878{
Svetoslavb412f6e2015-04-29 16:50:41 -07001879 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001880}
1881
Aravind Akella701166d2013-10-08 14:59:26 -07001882status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001883 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001884}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001885
Aravind Akella8a969552014-09-28 17:52:41 -07001886int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001887 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001888 {
1889 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1890 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1891 // can release the wake-lock.
1892 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1893 Mutex::Autolock _l(mConnectionLock);
1894 mDead = true;
1895 mWakeLockRefCount = 0;
1896 updateLooperRegistrationLocked(mService->getLooper());
1897 }
1898 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001899 if (mDataInjectionMode) {
1900 // If the Looper has encountered some error in data injection mode, reset SensorService
1901 // back to normal mode.
1902 mService->resetToNormalMode();
1903 mDataInjectionMode = false;
1904 }
Aravind Akella8a969552014-09-28 17:52:41 -07001905 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001906 }
1907
1908 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001909 unsigned char buf[sizeof(sensors_event_t)];
1910 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001911 {
1912 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001913 if (numBytesRead == sizeof(sensors_event_t)) {
1914 if (!mDataInjectionMode) {
1915 ALOGE("Data injected in normal mode, dropping event"
1916 "package=%s uid=%d", mPackageName.string(), mUid);
1917 // Unregister call backs.
1918 return 0;
1919 }
1920 SensorDevice& dev(SensorDevice::getInstance());
1921 sensors_event_t sensor_event;
1922 memset(&sensor_event, 0, sizeof(sensor_event));
1923 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1924 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1925 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001926 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001927#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001928 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001929#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001930 } else if (numBytesRead == sizeof(uint32_t)) {
1931 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001932 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001933 // Sanity check to ensure there are no read errors in recv, numAcks is always
1934 // within the range and not zero. If any of the above don't hold reset
1935 // mWakeLockRefCount to zero.
1936 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1937 mWakeLockRefCount -= numAcks;
1938 } else {
1939 mWakeLockRefCount = 0;
1940 }
1941#if DEBUG_CONNECTIONS
1942 mTotalAcksReceived += numAcks;
1943#endif
1944 } else {
1945 // Read error, reset wakelock refcount.
1946 mWakeLockRefCount = 0;
1947 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001948 }
1949 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1950 // here as checkWakeLockState() will need it.
1951 if (mWakeLockRefCount == 0) {
1952 mService->checkWakeLockState();
1953 }
1954 // continue getting callbacks.
1955 return 1;
1956 }
1957
1958 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001959 // send sensor data that is stored in mEventCache for this connection.
1960 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001961 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001962 return 1;
1963}
1964
1965int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001966 size_t fifoWakeUpSensors = 0;
1967 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001968 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1969 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1970 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1971 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1972 // non wake_up sensors.
1973 if (sensor.isWakeUpSensor()) {
1974 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1975 } else {
1976 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1977 }
1978 } else {
1979 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1980 if (sensor.isWakeUpSensor()) {
1981 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1982 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1983
1984 } else {
1985 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1986 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1987
1988 }
1989 }
1990 }
1991 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1992 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001993 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001994 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001995 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001996 }
1997 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001998}
1999
Mathias Agopianfc328812010-07-14 23:41:37 -07002000// ---------------------------------------------------------------------------
2001}; // namespace android
2002