blob: c73af3a4270dcda3a1239f7e0fd406987a3aba8c [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 Xu33a004b2015-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 Xu33a004b2015-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 Xu33a004b2015-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 Xu33a004b2015-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)
133 const SensorFusion& fusion(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 Xu33a004b2015-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 Xu33a004b2015-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 Xu33a004b2015-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
Aravind Akella444f2672015-05-07 12:40:52 -0700420 result.appendFormat("Socket Buffer size = %d events\n",
421 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];
Peng Xub7beb522016-01-21 23:15:04 -0800762 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700763 }
Aravind Akella70018042014-04-07 22:52:37 +0000764 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700765}
766
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700767sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700768 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700769 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
770 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
771 return NULL;
772 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700773
774 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700775 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
776 // operating in DI mode.
777 if (requestedMode == DATA_INJECTION) {
778 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
779 if (!isWhiteListedPackage(packageName)) return NULL;
780 }
781
Mathias Agopian5307d172012-09-18 17:02:43 -0700782 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700783 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700784 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700785 if (requestedMode == DATA_INJECTION) {
786 if (mActiveConnections.indexOf(result) < 0) {
787 mActiveConnections.add(result);
788 }
789 // Add the associated file descriptor to the Looper for polling whenever there is data to
790 // be injected.
791 result->updateLooperRegistration(mLooper);
792 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700793 return result;
794}
795
Aravind Akella841a5922015-06-29 12:37:48 -0700796int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700797 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700798 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700799}
800
801status_t SensorService::resetToNormalMode() {
802 Mutex::Autolock _l(mLock);
803 return resetToNormalModeLocked();
804}
805
806status_t SensorService::resetToNormalModeLocked() {
807 SensorDevice& dev(SensorDevice::getInstance());
808 dev.enableAllSensors();
809 status_t err = dev.setMode(NORMAL);
810 mCurrentOperatingMode = NORMAL;
811 return err;
812}
813
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800814void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700815{
816 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800817 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700818 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700819 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700820 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800821 int handle = mActiveSensors.keyAt(i);
822 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700823 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800824 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000825 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800826 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800827 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800828 }
Aravind Akella8a969552014-09-28 17:52:41 -0700829 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800830 }
831 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700832 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000833 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700834 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700835 c, i, handle);
836
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800837 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000838 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700839 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800840 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700841 delete rec;
842 size--;
843 } else {
844 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700845 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700846 }
Aravind Akella8a969552014-09-28 17:52:41 -0700847 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700848 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700849 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800850 if (c->needsWakeLock()) {
851 checkWakeLockStateLocked();
852 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700853}
854
Aravind Akella70018042014-04-07 22:52:37 +0000855Sensor SensorService::getSensorFromHandle(int handle) const {
856 return mSensorMap.valueFor(handle)->getSensor();
857}
858
Mathias Agopianfc328812010-07-14 23:41:37 -0700859status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700860 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
861 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700862{
Mathias Agopian50df2952010-07-19 19:09:10 -0700863 if (mInitCheck != NO_ERROR)
864 return mInitCheck;
865
Mathias Agopianf001c922010-11-11 17:58:51 -0800866 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700867 if (sensor == NULL) {
868 return BAD_VALUE;
869 }
Aravind Akella70018042014-04-07 22:52:37 +0000870
Svetoslavb412f6e2015-04-29 16:50:41 -0700871 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000872 return BAD_VALUE;
873 }
874
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700875 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700876 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
877 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800878 return INVALID_OPERATION;
879 }
880
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700881 SensorRecord* rec = mActiveSensors.valueFor(handle);
882 if (rec == 0) {
883 rec = new SensorRecord(connection);
884 mActiveSensors.add(handle, rec);
885 if (sensor->isVirtual()) {
886 mActiveVirtualSensors.add(handle, sensor);
887 }
888 } else {
889 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800890 // this sensor is already activated, but we are adding a connection that uses it.
891 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700892 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700893 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800894 // NOTE: The wake_up flag of this event may get set to
895 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700896 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
897 if (circular_buf) {
898 sensors_event_t event;
899 memset(&event, 0, sizeof(event));
900 // It is unlikely that this buffer is empty as the sensor is already active.
901 // One possible corner case may be two applications activating an on-change
902 // sensor at the same time.
903 if(circular_buf->populateLastEvent(&event)) {
904 event.sensor = handle;
905 if (event.version == sizeof(sensors_event_t)) {
906 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
907 setWakeLockAcquiredLocked(true);
908 }
909 connection->sendEvents(&event, 1, NULL);
910 if (!connection->needsWakeLock() && mWakeLockAcquired) {
911 checkWakeLockStateLocked();
912 }
913 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800914 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700915 }
916 }
917 }
918 }
919
920 if (connection->addSensor(handle)) {
921 BatteryService::enableSensor(connection->getUid(), handle);
922 // the sensor was added (which means it wasn't already there)
923 // so, see if this connection becomes active
924 if (mActiveConnections.indexOf(connection) < 0) {
925 mActiveConnections.add(connection);
926 }
927 } else {
928 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
929 handle, connection.get());
930 }
931
Aravind Akella724d91d2013-06-27 12:04:23 -0700932 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
933 if (samplingPeriodNs < minDelayNs) {
934 samplingPeriodNs = minDelayNs;
935 }
936
Aravind Akella6c2664a2014-08-13 12:24:50 -0700937 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
938 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700939 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
940
Aravind Akella4949c502015-02-11 15:54:35 -0800941 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700942 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700943
Peng Xu20483c42015-10-26 15:14:43 -0700944 // Call flush() before calling activate() on the sensor. Wait for a first
945 // flush complete event before sending events on this connection. Ignore
946 // one-shot sensors which don't support flush(). Ignore on-change sensors
947 // to maintain the on-change logic (any on-change events except the initial
948 // one should be trigger by a change in value). Also if this sensor isn't
949 // already active, don't call flush().
950 if (err == NO_ERROR &&
951 sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
952 sensor->getSensor().getReportingMode() != AREPORTING_MODE_ON_CHANGE &&
Aravind Akella5466c3d2014-08-22 16:11:10 -0700953 rec->getNumConnections() > 1) {
954 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700955 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700956 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700957 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700958 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700959 } else {
960 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700961 }
962 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700963
964 if (err == NO_ERROR) {
965 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
966 err = sensor->activate(connection.get(), true);
967 }
968
Aravind Akella8a969552014-09-28 17:52:41 -0700969 if (err == NO_ERROR) {
970 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700971 SensorRegistrationInfo &reg_info =
972 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
973 reg_info.mSensorHandle = handle;
974 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
975 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
976 reg_info.mActivated = true;
977 reg_info.mPackageName = connection->getPackageName();
978 time_t rawtime = time(NULL);
979 struct tm * timeinfo = localtime(&rawtime);
980 reg_info.mHour = timeinfo->tm_hour;
981 reg_info.mMin = timeinfo->tm_min;
982 reg_info.mSec = timeinfo->tm_sec;
983 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700984 }
985
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700986 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700987 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700988 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700989 }
990 return err;
991}
992
993status_t SensorService::disable(const sp<SensorEventConnection>& connection,
994 int handle)
995{
Mathias Agopian50df2952010-07-19 19:09:10 -0700996 if (mInitCheck != NO_ERROR)
997 return mInitCheck;
998
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700999 Mutex::Autolock _l(mLock);
1000 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001001 if (err == NO_ERROR) {
1002 SensorInterface* sensor = mSensorMap.valueFor(handle);
1003 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001004
1005 }
1006 if (err == NO_ERROR) {
1007 SensorRegistrationInfo &reg_info =
1008 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1009 reg_info.mActivated = false;
1010 reg_info.mPackageName= connection->getPackageName();
1011 reg_info.mSensorHandle = handle;
1012 time_t rawtime = time(NULL);
1013 struct tm * timeinfo = localtime(&rawtime);
1014 reg_info.mHour = timeinfo->tm_hour;
1015 reg_info.mMin = timeinfo->tm_min;
1016 reg_info.mSec = timeinfo->tm_sec;
1017 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001018 }
1019 return err;
1020}
1021
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001022status_t SensorService::cleanupWithoutDisable(
1023 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001024 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001025 return cleanupWithoutDisableLocked(connection, handle);
1026}
1027
1028status_t SensorService::cleanupWithoutDisableLocked(
1029 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001030 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001031 if (rec) {
1032 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001033 if (connection->removeSensor(handle)) {
1034 BatteryService::disableSensor(connection->getUid(), handle);
1035 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001036 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001037 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001038 mActiveConnections.remove(connection);
1039 }
1040 // see if this sensor becomes inactive
1041 if (rec->removeConnection(connection)) {
1042 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001043 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001044 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001045 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001046 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001047 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001048 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001049}
1050
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001051status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001052 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001053{
Mathias Agopian50df2952010-07-19 19:09:10 -07001054 if (mInitCheck != NO_ERROR)
1055 return mInitCheck;
1056
Mathias Agopianae09d652011-11-01 17:37:49 -07001057 SensorInterface* sensor = mSensorMap.valueFor(handle);
1058 if (!sensor)
1059 return BAD_VALUE;
1060
Svetoslavb412f6e2015-04-29 16:50:41 -07001061 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001062 return BAD_VALUE;
1063 }
1064
Mathias Agopian1cd70002010-07-21 15:59:50 -07001065 if (ns < 0)
1066 return BAD_VALUE;
1067
Mathias Agopian62569ec2011-11-07 21:21:47 -08001068 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1069 if (ns < minDelayNs) {
1070 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001071 }
1072
Mathias Agopianf001c922010-11-11 17:58:51 -08001073 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001074}
1075
Svetoslavb412f6e2015-04-29 16:50:41 -07001076status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1077 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001078 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001079 SensorDevice& dev(SensorDevice::getInstance());
1080 const int halVersion = dev.getHalDeviceVersion();
1081 status_t err(NO_ERROR);
1082 Mutex::Autolock _l(mLock);
1083 // Loop through all sensors for this connection and call flush on each of them.
1084 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1085 const int handle = connection->mSensorInfo.keyAt(i);
1086 SensorInterface* sensor = mSensorMap.valueFor(handle);
1087 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1088 ALOGE("flush called on a one-shot sensor");
1089 err = INVALID_OPERATION;
1090 continue;
1091 }
Aravind Akella8493b792014-09-08 15:45:47 -07001092 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001093 // For older devices just increment pending flush count which will send a trivial
1094 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001095 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001096 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001097 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1098 err = INVALID_OPERATION;
1099 continue;
1100 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001101 status_t err_flush = sensor->flush(connection.get(), handle);
1102 if (err_flush == NO_ERROR) {
1103 SensorRecord* rec = mActiveSensors.valueFor(handle);
1104 if (rec != NULL) rec->addPendingFlushConnection(connection);
1105 }
1106 err = (err_flush != NO_ERROR) ? err_flush : err;
1107 }
Aravind Akella70018042014-04-07 22:52:37 +00001108 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001109 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001110}
Aravind Akella70018042014-04-07 22:52:37 +00001111
Svetoslavb412f6e2015-04-29 16:50:41 -07001112bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1113 const String16& opPackageName) {
1114 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001115
Svetoslavb412f6e2015-04-29 16:50:41 -07001116 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001117 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001118 }
1119
1120 bool hasPermission = false;
1121
1122 // Runtime permissions can't use the cache as they may change.
1123 if (sensor.isRequiredPermissionRuntime()) {
1124 hasPermission = checkPermission(String16(requiredPermission),
1125 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001126 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001127 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1128 }
1129
1130 if (!hasPermission) {
1131 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1132 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001133 return false;
1134 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001135
1136 const int32_t opCode = sensor.getRequiredAppOp();
1137 if (opCode >= 0) {
1138 AppOpsManager appOps;
1139 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1140 != AppOpsManager::MODE_ALLOWED) {
1141 ALOGE("%s a sensor (%s) without enabled required app op: %D",
1142 operation, sensor.getName().string(), opCode);
1143 return false;
1144 }
1145 }
1146
1147 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001148}
1149
Aravind Akella9a844cf2014-02-11 18:58:52 -08001150void SensorService::checkWakeLockState() {
1151 Mutex::Autolock _l(mLock);
1152 checkWakeLockStateLocked();
1153}
1154
1155void SensorService::checkWakeLockStateLocked() {
1156 if (!mWakeLockAcquired) {
1157 return;
1158 }
1159 bool releaseLock = true;
1160 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1161 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1162 if (connection != 0) {
1163 if (connection->needsWakeLock()) {
1164 releaseLock = false;
1165 break;
1166 }
1167 }
1168 }
1169 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001170 setWakeLockAcquiredLocked(false);
1171 }
1172}
1173
1174void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1175 Mutex::Autolock _l(mLock);
1176 connection->writeToSocketFromCache();
1177 if (connection->needsWakeLock()) {
1178 setWakeLockAcquiredLocked(true);
1179 }
1180}
1181
1182void SensorService::populateActiveConnections(
1183 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1184 Mutex::Autolock _l(mLock);
1185 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1186 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1187 if (connection != 0) {
1188 activeConnections->add(connection);
1189 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001190 }
1191}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001192
Aravind Akella4949c502015-02-11 15:54:35 -08001193bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001194 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001195}
1196
Aravind Akella444f2672015-05-07 12:40:52 -07001197int SensorService::getNumEventsForSensorType(int sensor_event_type) {
Nick Vaccaro95f13902016-03-01 15:49:08 -08001198 if (sensor_event_type >= SENSOR_TYPE_DEVICE_PRIVATE_BASE) {
1199 return 16;
1200 }
Aravind Akella444f2672015-05-07 12:40:52 -07001201 switch (sensor_event_type) {
1202 case SENSOR_TYPE_ROTATION_VECTOR:
1203 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1204 return 5;
1205
1206 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1207 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1208 return 6;
1209
1210 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1211 return 4;
1212
1213 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1214 case SENSOR_TYPE_STEP_DETECTOR:
1215 case SENSOR_TYPE_STEP_COUNTER:
1216 return 1;
1217
1218 default:
1219 return 3;
1220 }
1221}
1222
Mathias Agopianfc328812010-07-14 23:41:37 -07001223// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001224SensorService::SensorRecord::SensorRecord(
1225 const sp<SensorEventConnection>& connection)
1226{
1227 mConnections.add(connection);
1228}
1229
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001230bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001231 const sp<SensorEventConnection>& connection)
1232{
1233 if (mConnections.indexOf(connection) < 0) {
1234 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001235 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001236 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001237 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001238}
1239
1240bool SensorService::SensorRecord::removeConnection(
1241 const wp<SensorEventConnection>& connection)
1242{
1243 ssize_t index = mConnections.indexOf(connection);
1244 if (index >= 0) {
1245 mConnections.removeItemsAt(index, 1);
1246 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001247 // Remove this connections from the queue of flush() calls made on this sensor.
1248 for (Vector< wp<SensorEventConnection> >::iterator it =
1249 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001250
Aravind Akella6c2664a2014-08-13 12:24:50 -07001251 if (it->unsafe_get() == connection.unsafe_get()) {
1252 it = mPendingFlushConnections.erase(it);
1253 } else {
1254 ++it;
1255 }
1256 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001257 return mConnections.size() ? false : true;
1258}
1259
Aravind Akella6c2664a2014-08-13 12:24:50 -07001260void SensorService::SensorRecord::addPendingFlushConnection(
1261 const sp<SensorEventConnection>& connection) {
1262 mPendingFlushConnections.add(connection);
1263}
1264
1265void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1266 if (mPendingFlushConnections.size() > 0) {
1267 mPendingFlushConnections.removeAt(0);
1268 }
1269}
1270
1271SensorService::SensorEventConnection *
1272SensorService::SensorRecord::getFirstPendingFlushConnection() {
1273 if (mPendingFlushConnections.size() > 0) {
1274 return mPendingFlushConnections[0].unsafe_get();
1275 }
1276 return NULL;
1277}
1278
Aravind Akella4949c502015-02-11 15:54:35 -08001279void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1280 mPendingFlushConnections.clear();
1281}
1282
Aravind Akella18d6d512015-06-18 14:18:28 -07001283
1284// ---------------------------------------------------------------------------
1285SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
1286 mTimestamp = -1;
1287 const int numData = SensorService::getNumEventsForSensorType(sensorType);
1288 if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
1289 mStepCounter = 0;
1290 } else {
1291 mData = new float[numData];
1292 for (int i = 0; i < numData; ++i) {
1293 mData[i] = -1.0;
1294 }
1295 }
1296 mHour = mMin = mSec = INT32_MIN;
1297}
1298
1299bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
1300 return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
1301}
Aravind Akella444f2672015-05-07 12:40:52 -07001302// --------------------------------------------------------------------------
1303SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1304 mNextInd = 0;
Aravind Akella18d6d512015-06-18 14:18:28 -07001305 mBufSize = CIRCULAR_BUF_SIZE;
1306 if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
1307 sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
1308 sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
1309 mBufSize = CIRCULAR_BUF_SIZE * 5;
1310 }
1311 mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
Aravind Akella444f2672015-05-07 12:40:52 -07001312 mSensorType = sensor_event_type;
Aravind Akella18d6d512015-06-18 14:18:28 -07001313 for (int i = 0; i < mBufSize; ++i) {
1314 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
Aravind Akella444f2672015-05-07 12:40:52 -07001315 }
1316}
1317
1318void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1319 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1320 curr_event->mTimestamp = sensor_event.timestamp;
1321 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1322 curr_event->mStepCounter = sensor_event.u64.step_counter;
1323 } else {
1324 memcpy(curr_event->mData, sensor_event.data,
1325 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1326 }
1327 time_t rawtime = time(NULL);
1328 struct tm * timeinfo = localtime(&rawtime);
1329 curr_event->mHour = timeinfo->tm_hour;
1330 curr_event->mMin = timeinfo->tm_min;
1331 curr_event->mSec = timeinfo->tm_sec;
Aravind Akella18d6d512015-06-18 14:18:28 -07001332 mNextInd = (mNextInd + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001333}
1334
1335void SensorService::CircularBuffer::printBuffer(String8& result) const {
1336 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1337 int i = mNextInd, eventNum = 1;
Aravind Akella18d6d512015-06-18 14:18:28 -07001338 result.appendFormat("last %d events = < ", mBufSize);
Aravind Akella444f2672015-05-07 12:40:52 -07001339 do {
Aravind Akella18d6d512015-06-18 14:18:28 -07001340 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001341 // Sentinel, ignore.
Aravind Akella18d6d512015-06-18 14:18:28 -07001342 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001343 continue;
1344 }
1345 result.appendFormat("%d) ", eventNum++);
1346 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1347 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1348 } else {
1349 for (int j = 0; j < numData; ++j) {
1350 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1351 }
1352 }
1353 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1354 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1355 mTrimmedSensorEventArr[i]->mSec);
Aravind Akella18d6d512015-06-18 14:18:28 -07001356 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001357 } while (i != mNextInd);
1358 result.appendFormat(">\n");
1359}
1360
1361bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
Aravind Akella18d6d512015-06-18 14:18:28 -07001362 int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001363 // Check if the buffer is empty.
Aravind Akella18d6d512015-06-18 14:18:28 -07001364 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001365 return false;
1366 }
1367 event->version = sizeof(sensors_event_t);
1368 event->type = mSensorType;
1369 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1370 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1371 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1372 } else {
1373 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1374 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1375 }
1376 return true;
1377}
1378
1379SensorService::CircularBuffer::~CircularBuffer() {
Aravind Akella18d6d512015-06-18 14:18:28 -07001380 for (int i = 0; i < mBufSize; ++i) {
Aravind Akella444f2672015-05-07 12:40:52 -07001381 delete mTrimmedSensorEventArr[i];
1382 }
1383 delete [] mTrimmedSensorEventArr;
1384}
1385
Mathias Agopianfc328812010-07-14 23:41:37 -07001386// ---------------------------------------------------------------------------
1387
1388SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001389 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1390 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001391 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001392 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1393 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001394 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001395#if DEBUG_CONNECTIONS
1396 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001397 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001398#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001399}
1400
Aravind Akella56ae4262014-07-10 16:01:10 -07001401SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001402 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001403 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001404 if (mEventCache != NULL) {
1405 delete mEventCache;
1406 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001407}
1408
Aravind Akella56ae4262014-07-10 16:01:10 -07001409void SensorService::SensorEventConnection::onFirstRef() {
1410 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001411}
1412
Aravind Akella9a844cf2014-02-11 18:58:52 -08001413bool SensorService::SensorEventConnection::needsWakeLock() {
1414 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001415 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001416}
1417
Aravind Akellab4373ac2014-10-29 17:55:20 -07001418void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1419 Mutex::Autolock _l(mConnectionLock);
1420 mWakeLockRefCount = 0;
1421}
1422
Aravind Akella4c8b9512013-09-05 17:03:38 -07001423void SensorService::SensorEventConnection::dump(String8& result) {
1424 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8ef3c892015-07-10 11:24:28 -07001425 result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella18d6d512015-06-18 14:18:28 -07001426 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
1427 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
1428 mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001429 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1430 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001431 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001432 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001433 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001434 flushInfo.mFirstFlushPending ? "First flush pending" :
1435 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001436 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001437 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001438#if DEBUG_CONNECTIONS
1439 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1440 " total_acks_needed %d | total_acks_recvd %d\n",
1441 mEventsReceived,
1442 mEventsSent,
1443 mEventsSentFromCache,
1444 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1445 mTotalAcksNeeded,
1446 mTotalAcksReceived);
1447#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001448}
1449
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001450bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001451 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001452 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1453 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001454 return false;
1455 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001456 if (mSensorInfo.indexOfKey(handle) < 0) {
1457 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001458 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001459 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001460 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001461}
1462
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001463bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001464 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001465 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001466 return true;
1467 }
1468 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001469}
1470
1471bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001472 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001473 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001474}
1475
1476bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001477 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001478 return mSensorInfo.size() ? true : false;
1479}
1480
Aravind Akella8493b792014-09-08 15:45:47 -07001481bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1482 Mutex::Autolock _l(mConnectionLock);
1483 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1484 const int handle = mSensorInfo.keyAt(i);
1485 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1486 return true;
1487 }
1488 }
1489 return false;
1490}
1491
Aravind Akella4949c502015-02-11 15:54:35 -08001492String8 SensorService::SensorEventConnection::getPackageName() const {
1493 return mPackageName;
1494}
1495
Aravind Akella4c8b9512013-09-05 17:03:38 -07001496void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1497 bool value) {
1498 Mutex::Autolock _l(mConnectionLock);
1499 ssize_t index = mSensorInfo.indexOfKey(handle);
1500 if (index >= 0) {
1501 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1502 flushInfo.mFirstFlushPending = value;
1503 }
1504}
1505
Aravind Akella8a969552014-09-28 17:52:41 -07001506void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1507 Mutex::Autolock _l(mConnectionLock);
1508 updateLooperRegistrationLocked(looper);
1509}
1510
1511void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1512 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001513 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1514 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001515 // If all sensors are unregistered OR Looper has encountered an error, we
1516 // can remove the Fd from the Looper if it has been previously added.
1517 if (!isConnectionActive || mDead) {
1518 if (mHasLooperCallbacks) {
1519 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1520 looper->removeFd(mChannel->getSendFd());
1521 mHasLooperCallbacks = false;
1522 }
1523 return;
1524 }
1525
1526 int looper_flags = 0;
1527 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001528 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001529 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1530 const int handle = mSensorInfo.keyAt(i);
1531 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1532 looper_flags |= ALOOPER_EVENT_INPUT;
1533 break;
1534 }
1535 }
1536 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1537 // the fd has already been added, remove it. This is likely to happen when ALL the
1538 // events stored in the cache have been sent to the corresponding app.
1539 if (looper_flags == 0) {
1540 if (mHasLooperCallbacks) {
1541 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1542 looper->removeFd(mChannel->getSendFd());
1543 mHasLooperCallbacks = false;
1544 }
1545 return;
1546 }
1547 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1548 // registered for wake-up sensors OR for sending events in the cache.
1549 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1550 if (ret == 1) {
1551 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1552 mHasLooperCallbacks = true;
1553 } else {
1554 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1555 }
1556}
1557
1558void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1559 Mutex::Autolock _l(mConnectionLock);
1560 ssize_t index = mSensorInfo.indexOfKey(handle);
1561 if (index >= 0) {
1562 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1563 flushInfo.mPendingFlushEventsToSend++;
1564 }
1565}
1566
Mathias Agopianfc328812010-07-14 23:41:37 -07001567status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001568 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001569 sensors_event_t* scratch,
1570 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001571 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001572 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001573 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001574 if (scratch) {
1575 size_t i=0;
1576 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001577 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001578 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1579 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001580 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001581 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1582 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1583 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001584 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001585 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001586 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001587 // Check if this connection has registered for this sensor. If not continue to the
1588 // next sensor_event.
1589 if (index < 0) {
1590 ++i;
1591 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001592 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001593
Aravind Akella56ae4262014-07-10 16:01:10 -07001594 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001595 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001596 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1597 this == mapFlushEventsToConnections[i]) {
1598 flushInfo.mFirstFlushPending = false;
1599 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1600 buffer[i].meta_data.sensor);
1601 ++i;
1602 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001603 }
1604
1605 // If there is a pending flush complete event for this sensor on this connection,
1606 // ignore the event and proceed to the next.
1607 if (flushInfo.mFirstFlushPending) {
1608 ++i;
1609 continue;
1610 }
1611
1612 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001613 // Keep copying events into the scratch buffer as long as they are regular
1614 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1615 // from the same sensor_handle AND the current connection is mapped to the
1616 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001617 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001618 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001619 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001620 }
1621 ++i;
1622 } else {
1623 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001624 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001625 }
Aravind Akella8493b792014-09-08 15:45:47 -07001626 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1627 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001628 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001629 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001630 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001631 } else {
1632 scratch = const_cast<sensors_event_t *>(buffer);
1633 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001634 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001635
Aravind Akella6c2664a2014-08-13 12:24:50 -07001636 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001637 // Early return if there are no events for this connection.
1638 if (count == 0) {
1639 return status_t(NO_ERROR);
1640 }
1641
1642#if DEBUG_CONNECTIONS
1643 mEventsReceived += count;
1644#endif
1645 if (mCacheSize != 0) {
1646 // There are some events in the cache which need to be sent first. Copy this buffer to
1647 // the end of cache.
1648 if (mCacheSize + count <= mMaxCacheSize) {
1649 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1650 mCacheSize += count;
1651 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001652 // Check if any new sensors have registered on this connection which may have increased
1653 // the max cache size that is desired.
1654 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1655 reAllocateCacheLocked(scratch, count);
1656 return status_t(NO_ERROR);
1657 }
Lianchao Songd89d29d2016-04-12 21:58:32 +08001658 if (count >= mMaxCacheSize) {
1659 //count is larger than MaxCacheSize,
1660 //so copy the end MaxCacheSize data in scratch buffer to cache
1661 countFlushCompleteEventsLocked(mEventCache, mCacheSize);
1662 countFlushCompleteEventsLocked(scratch, count - mMaxCacheSize);
1663 memcpy(&mEventCache[0], &scratch[count-mMaxCacheSize],
1664 mMaxCacheSize * sizeof(sensors_event_t));
1665 mCacheSize = mMaxCacheSize;
1666 } else {
1667 //count is smaller than MaxCacheSize, so numEventsDropped data in cache
1668 //should be dropped, then copy the scratch to the end of cache
1669 int numEventsDropped = count + mCacheSize - mMaxCacheSize;
1670 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1671 memmove(mEventCache, &mEventCache[numEventsDropped],
Aravind Akella56ae4262014-07-10 16:01:10 -07001672 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1673
Lianchao Songd89d29d2016-04-12 21:58:32 +08001674 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch,
1675 count * sizeof(sensors_event_t));
1676 mCacheSize = mMaxCacheSize;
1677 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001678 }
1679 return status_t(NO_ERROR);
1680 }
1681
Aravind Akella6c2664a2014-08-13 12:24:50 -07001682 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1683 if (index_wake_up_event >= 0) {
1684 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1685 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001686#if DEBUG_CONNECTIONS
1687 ++mTotalAcksNeeded;
1688#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001689 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001690
1691 // NOTE: ASensorEvent and sensors_event_t are the same type.
1692 ssize_t size = SensorEventQueue::write(mChannel,
1693 reinterpret_cast<ASensorEvent const*>(scratch), count);
1694 if (size < 0) {
1695 // Write error, copy events to local cache.
Lianchao Songd89d29d2016-04-12 21:58:32 +08001696 ALOGE("write failed, size=%d err=%d:%s ", size, errno, strerror(errno));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001697 if (index_wake_up_event >= 0) {
1698 // If there was a wake_up sensor_event, reset the flag.
1699 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001700 if (mWakeLockRefCount > 0) {
1701 --mWakeLockRefCount;
1702 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001703#if DEBUG_CONNECTIONS
1704 --mTotalAcksNeeded;
1705#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001706 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001707 if (mEventCache == NULL) {
1708 mMaxCacheSize = computeMaxCacheSizeLocked();
1709 mEventCache = new sensors_event_t[mMaxCacheSize];
1710 mCacheSize = 0;
1711 }
Lianchao Songd89d29d2016-04-12 21:58:32 +08001712 //here mCacheSize must be 0 because if (mCacheSize != 0) has been executed above
1713 if (count <= mMaxCacheSize) {
1714 //count is no more than free size of cache,
1715 //copy the scratch to the end of cache
1716 memcpy(&mEventCache[0], scratch, count * sizeof(sensors_event_t));
1717 mCacheSize = count;
1718 } else {
1719 //count is larger than free size of cache,
1720 //so just copy the free size of scratch to the end of cache
1721 ALOGI("count > MaxCache count=%d mMaxCacheSize=%d", count, mMaxCacheSize);
1722 countFlushCompleteEventsLocked(scratch, count - mMaxCacheSize);
1723 memcpy(&mEventCache[0], &scratch[count - mMaxCacheSize],
1724 mMaxCacheSize * sizeof(sensors_event_t));
1725 mCacheSize = mMaxCacheSize;
1726 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001727
1728 // Add this file descriptor to the looper to get a callback when this fd is available for
1729 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001730 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001731 return size;
1732 }
1733
1734#if DEBUG_CONNECTIONS
1735 if (size > 0) {
1736 mEventsSent += count;
1737 }
1738#endif
1739
1740 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1741}
1742
Aravind Akella6c2664a2014-08-13 12:24:50 -07001743void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1744 int count) {
1745 sensors_event_t *eventCache_new;
1746 const int new_cache_size = computeMaxCacheSizeLocked();
1747 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1748 eventCache_new = new sensors_event_t[new_cache_size];
1749 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1750 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1751
1752 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1753 new_cache_size);
1754
1755 delete mEventCache;
1756 mEventCache = eventCache_new;
1757 mCacheSize += count;
1758 mMaxCacheSize = new_cache_size;
1759}
1760
1761void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1762 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001763 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001764 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001765 // Loop through all the sensors for this connection and check if there are any pending
1766 // flush complete events to be sent.
1767 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1768 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1769 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001770 const int sensor_handle = mSensorInfo.keyAt(i);
1771 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001772 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1773 if (wakeUpSensor) {
1774 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001775 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1776 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001777 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1778 if (size < 0) {
Lianchao Songd89d29d2016-04-12 21:58:32 +08001779 ALOGE("write failed, size=%d err=%d:%s ", size, errno, strerror(errno));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001780 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001781 return;
1782 }
1783 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1784 flushCompleteEvent.meta_data.sensor);
1785 flushInfo.mPendingFlushEventsToSend--;
1786 }
1787 }
1788}
1789
Aravind Akellab4373ac2014-10-29 17:55:20 -07001790void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001791 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1792 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1793 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1794 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001795 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001796 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001797 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001798 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001799 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001800 int index_wake_up_event =
1801 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1802 if (index_wake_up_event >= 0) {
1803 mEventCache[index_wake_up_event + numEventsSent].flags |=
1804 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1805 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001806#if DEBUG_CONNECTIONS
1807 ++mTotalAcksNeeded;
1808#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001809 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001810
Aravind Akella56ae4262014-07-10 16:01:10 -07001811 ssize_t size = SensorEventQueue::write(mChannel,
1812 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001813 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001814 if (size < 0) {
Lianchao Songd89d29d2016-04-12 21:58:32 +08001815 ALOGE("write failed, size=%d err=%d:%s ", size, errno, strerror(errno));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001816 if (index_wake_up_event >= 0) {
1817 // If there was a wake_up sensor_event, reset the flag.
1818 mEventCache[index_wake_up_event + numEventsSent].flags &=
1819 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001820 if (mWakeLockRefCount > 0) {
1821 --mWakeLockRefCount;
1822 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001823#if DEBUG_CONNECTIONS
1824 --mTotalAcksNeeded;
1825#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001826 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001827 memmove(mEventCache, &mEventCache[numEventsSent],
1828 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1829 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001830 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001831 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001832 return;
1833 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001834 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001835#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001836 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001837#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001838 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001839 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1840 // All events from the cache have been sent. Reset cache size to zero.
1841 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001842 // There are no more events in the cache. We don't need to poll for write on the fd.
1843 // Update Looper registration.
1844 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001845}
1846
Aravind Akellac551eac2013-10-14 17:04:42 -07001847void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001848 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001849 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001850 // Count flushComplete events in the events that are about to the dropped. These will be sent
1851 // separately before the next batch of events.
1852 for (int j = 0; j < numEventsDropped; ++j) {
1853 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1854 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1855 flushInfo.mPendingFlushEventsToSend++;
1856 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1857 flushInfo.mPendingFlushEventsToSend);
1858 }
1859 }
1860 return;
1861}
1862
Aravind Akella6c2664a2014-08-13 12:24:50 -07001863int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1864 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001865 for (int i = 0; i < count; ++i) {
1866 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001867 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001868 }
1869 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001870 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001871}
1872
Mathias Agopianb3989272011-10-20 18:42:02 -07001873sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001874{
1875 return mChannel;
1876}
1877
1878status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001879 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1880 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001881{
1882 status_t err;
1883 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001884 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001885 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001886
Mathias Agopianfc328812010-07-14 23:41:37 -07001887 } else {
1888 err = mService->disable(this, handle);
1889 }
1890 return err;
1891}
1892
1893status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001894 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001895{
Svetoslavb412f6e2015-04-29 16:50:41 -07001896 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001897}
1898
Aravind Akella701166d2013-10-08 14:59:26 -07001899status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001900 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001901}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001902
Aravind Akella8a969552014-09-28 17:52:41 -07001903int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001904 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001905 {
1906 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1907 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1908 // can release the wake-lock.
1909 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1910 Mutex::Autolock _l(mConnectionLock);
1911 mDead = true;
1912 mWakeLockRefCount = 0;
1913 updateLooperRegistrationLocked(mService->getLooper());
1914 }
1915 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001916 if (mDataInjectionMode) {
1917 // If the Looper has encountered some error in data injection mode, reset SensorService
1918 // back to normal mode.
1919 mService->resetToNormalMode();
1920 mDataInjectionMode = false;
1921 }
Aravind Akella8a969552014-09-28 17:52:41 -07001922 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001923 }
1924
1925 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001926 unsigned char buf[sizeof(sensors_event_t)];
1927 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001928 {
1929 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001930 if (numBytesRead == sizeof(sensors_event_t)) {
1931 if (!mDataInjectionMode) {
1932 ALOGE("Data injected in normal mode, dropping event"
1933 "package=%s uid=%d", mPackageName.string(), mUid);
1934 // Unregister call backs.
1935 return 0;
1936 }
1937 SensorDevice& dev(SensorDevice::getInstance());
1938 sensors_event_t sensor_event;
1939 memset(&sensor_event, 0, sizeof(sensor_event));
1940 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1941 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1942 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001943 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001944#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001945 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001946#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001947 } else if (numBytesRead == sizeof(uint32_t)) {
1948 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001949 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001950 // Sanity check to ensure there are no read errors in recv, numAcks is always
1951 // within the range and not zero. If any of the above don't hold reset
1952 // mWakeLockRefCount to zero.
1953 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1954 mWakeLockRefCount -= numAcks;
1955 } else {
1956 mWakeLockRefCount = 0;
1957 }
1958#if DEBUG_CONNECTIONS
1959 mTotalAcksReceived += numAcks;
1960#endif
1961 } else {
1962 // Read error, reset wakelock refcount.
1963 mWakeLockRefCount = 0;
1964 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001965 }
1966 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1967 // here as checkWakeLockState() will need it.
1968 if (mWakeLockRefCount == 0) {
1969 mService->checkWakeLockState();
1970 }
1971 // continue getting callbacks.
1972 return 1;
1973 }
1974
1975 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001976 // send sensor data that is stored in mEventCache for this connection.
1977 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001978 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001979 return 1;
1980}
1981
1982int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001983 size_t fifoWakeUpSensors = 0;
1984 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001985 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1986 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1987 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1988 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1989 // non wake_up sensors.
1990 if (sensor.isWakeUpSensor()) {
1991 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1992 } else {
1993 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1994 }
1995 } else {
1996 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1997 if (sensor.isWakeUpSensor()) {
1998 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1999 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
2000
2001 } else {
2002 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
2003 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
2004
2005 }
2006 }
2007 }
2008 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
2009 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07002010 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07002011 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07002012 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07002013 }
2014 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08002015}
2016
Mathias Agopianfc328812010-07-14 23:41:37 -07002017// ---------------------------------------------------------------------------
2018}; // namespace android
2019