blob: d9753acaaa578bf9cef7d366900d67450af3cd5e [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
Mathias Agopian33015422011-05-27 18:18:13 -070017#include <cutils/properties.h>
18
Svetoslavb412f6e2015-04-29 16:50:41 -070019#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070023
Mathias Agopian907103b2012-04-02 18:38:02 -070024#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025
26#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070027#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070028
Greg Kaiser53ca2e02016-06-21 16:11:14 -070029#include <openssl/digest.h>
30#include <openssl/hmac.h>
31#include <openssl/rand.h>
32
Mathias Agopian787ac1b2012-09-18 18:49:18 -070033#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070034#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080035#include "GravitySensor.h"
36#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070037#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080038#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070040#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080041
Mathias Agopian984826c2011-05-17 22:54:42 -070042#include "SensorService.h"
Peng Xueb4d6282015-12-10 18:02:41 -080043#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080044#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045#include "SensorRecord.h"
46#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080047
48#include <inttypes.h>
49#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070050#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080051#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080052#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070053#include <sys/stat.h>
54#include <sys/types.h>
55#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070056
57namespace android {
58// ---------------------------------------------------------------------------
59
Mathias Agopian33015422011-05-27 18:18:13 -070060/*
61 * Notes:
62 *
63 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070064 * - run mag sensor from time to time to force calibration
65 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
66 *
67 */
68
Aravind Akella8ef3c892015-07-10 11:24:28 -070069const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070070uint8_t SensorService::sHmacGlobalKey[128] = {};
71bool SensorService::sHmacGlobalKeyIsValid = false;
72
73#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
74#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070075#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070076
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070077// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070078static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070079
Mathias Agopianfc328812010-07-14 23:41:37 -070080SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070081 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070082 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070083}
84
Greg Kaiser53ca2e02016-06-21 16:11:14 -070085bool SensorService::initializeHmacKey() {
86 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
87 if (fd != -1) {
88 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
89 close(fd);
90 if (result == sizeof(sHmacGlobalKey)) {
91 return true;
92 }
93 ALOGW("Unable to read HMAC key; generating new one.");
94 }
95
96 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
97 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
98 return false;
99 }
100
101 // We need to make sure this is only readable to us.
102 bool wroteKey = false;
103 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
104 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
105 S_IRUSR|S_IWUSR);
106 if (fd != -1) {
107 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
108 close(fd);
109 wroteKey = (result == sizeof(sHmacGlobalKey));
110 }
111 if (wroteKey) {
112 ALOGI("Generated new HMAC key.");
113 } else {
114 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
115 "after reboot.");
116 }
117 // Even if we failed to write the key we return true, because we did
118 // initialize the HMAC key.
119 return true;
120}
121
Peng Xu98d30f62016-08-01 18:12:11 -0700122// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
123void SensorService::enableSchedFifoMode() {
124 struct sched_param param = {0};
125 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
126 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
127 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
128 }
129}
130
Peng Xu47e96012016-03-28 17:55:56 -0700131void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000132 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800133 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700134
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700135 sHmacGlobalKeyIsValid = initializeHmacKey();
136
Mathias Agopianf001c922010-11-11 17:58:51 -0800137 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800138 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700139 ssize_t count = dev.getSensorList(&list);
140 if (count > 0) {
141 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700142 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700143 uint32_t virtualSensorsNeeds =
144 (1<<SENSOR_TYPE_GRAVITY) |
145 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700146 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
147 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
148 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700149
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700150 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700151 bool useThisSensor=true;
152
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700153 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700154 case SENSOR_TYPE_ACCELEROMETER:
155 hasAccel = true;
156 break;
157 case SENSOR_TYPE_MAGNETIC_FIELD:
158 hasMag = true;
159 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700160 case SENSOR_TYPE_ORIENTATION:
161 orientationIndex = i;
162 break;
163 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700164 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 hasGyro = true;
166 break;
167 case SENSOR_TYPE_GRAVITY:
168 case SENSOR_TYPE_LINEAR_ACCELERATION:
169 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700170 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
171 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
172 if (IGNORE_HARDWARE_FUSION) {
173 useThisSensor = false;
174 } else {
175 virtualSensorsNeeds &= ~(1<<list[i].type);
176 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700177 break;
178 }
Peng Xuf66684a2015-07-23 11:41:53 -0700179 if (useThisSensor) {
180 registerSensor( new HardwareSensor(list[i]) );
181 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700182 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700183
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700184 // it's safe to instantiate the SensorFusion object here
185 // (it wants to be instantiated after h/w sensors have been
186 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700187 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700188
Aravind Akellaf5047892015-07-20 17:29:33 -0700189 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700190 // Add Android virtual sensors if they're not already
191 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700192 bool needRotationVector =
193 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700194
Peng Xu0cc8f802016-04-05 23:46:03 -0700195 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
196 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700197
Peng Xu0cc8f802016-04-05 23:46:03 -0700198 bool needLinearAcceleration =
199 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700200
Peng Xu0cc8f802016-04-05 23:46:03 -0700201 registerSensor(new LinearAccelerationSensor(list, count),
202 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700203
Peng Xu0cc8f802016-04-05 23:46:03 -0700204 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700205 registerSensor( new CorrectedGyroSensor(list, count), true, true);
206 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700207 }
208
Peng Xuf66684a2015-07-23 11:41:53 -0700209 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700210 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
211 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700212
Peng Xu0cc8f802016-04-05 23:46:03 -0700213 bool needGameRotationVector =
214 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
215 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700216 }
217
218 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700219 bool needGeoMagRotationVector =
220 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
221 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700222 }
223
Aravind Akella5466c3d2014-08-22 16:11:10 -0700224 // Check if the device really supports batching by looking at the FIFO event
225 // counts for each sensor.
226 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700227 mSensors.forEachSensor(
228 [&batchingSupported] (const Sensor& s) -> bool {
229 if (s.getFifoMaxEventCount() > 0) {
230 batchingSupported = true;
231 }
232 return !batchingSupported;
233 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700234
235 if (batchingSupported) {
236 // Increase socket buffer size to a max of 100 KB for batching capabilities.
237 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
238 } else {
239 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
240 }
241
242 // Compare the socketBufferSize value against the system limits and limit
243 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700244 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
245 char line[128];
246 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
247 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700248 size_t maxSystemSocketBufferSize;
249 sscanf(line, "%zu", &maxSystemSocketBufferSize);
250 if (mSocketBufferSize > maxSystemSocketBufferSize) {
251 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700252 }
253 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700254 if (fp) {
255 fclose(fp);
256 }
257
Aravind Akella9a844cf2014-02-11 18:58:52 -0800258 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700259 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700260 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
261 mSensorEventBuffer = new sensors_event_t[minBufferSize];
262 mSensorEventScratch = new sensors_event_t[minBufferSize];
263 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700264 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700265
Aravind Akella18d6d512015-06-18 14:18:28 -0700266 mNextSensorRegIndex = 0;
267 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
268 mLastNSensorRegistrations.push();
269 }
270
271 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700272 mAckReceiver = new SensorEventAckReceiver(this);
273 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700274 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700275
276 // priority can only be changed after run
277 enableSchedFifoMode();
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700278 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700279 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700280}
281
Peng Xu0cc8f802016-04-05 23:46:03 -0700282const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
283 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800284 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700285 if (mSensors.add(handle, s, isDebug, isVirtual)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800286 mRecentEvent.emplace(handle, new RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700287 return s->getSensor();
288 } else {
289 return mSensors.getNonSensor();
290 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800291}
292
Peng Xu6a2d3a02015-12-21 12:00:23 -0800293const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700294 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800295}
296
Peng Xu6a2d3a02015-12-21 12:00:23 -0800297bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700298 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800299
300 const auto i = mRecentEvent.find(handle);
301 if (i != mRecentEvent.end()) {
302 delete i->second;
303 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800304 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700305 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800306}
307
Peng Xu0cc8f802016-04-05 23:46:03 -0700308const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
309 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700310}
311
Peng Xu47e96012016-03-28 17:55:56 -0700312SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800313 for (auto && entry : mRecentEvent) {
314 delete entry.second;
315 }
Peng Xu47e96012016-03-28 17:55:56 -0700316}
317
318status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700319 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700320 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800321 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700322 IPCThreadState::self()->getCallingPid(),
323 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700324 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700325 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700326 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800327 return INVALID_OPERATION;
328 }
329 Mutex::Autolock _l(mLock);
330 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700331 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700332 // If already in restricted mode. Ignore.
333 if (mCurrentOperatingMode == RESTRICTED) {
334 return status_t(NO_ERROR);
335 }
336 // If in any mode other than normal, ignore.
337 if (mCurrentOperatingMode != NORMAL) {
338 return INVALID_OPERATION;
339 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700340 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800341 dev.disableAllSensors();
342 // Clear all pending flush connections for all active sensors. If one of the active
343 // connections has called flush() and the underlying sensor has been disabled before a
344 // flush complete event is returned, we need to remove the connection from this queue.
345 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
346 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
347 }
Aravind Akella841a5922015-06-29 12:37:48 -0700348 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700349 return status_t(NO_ERROR);
350 } else if (args.size() == 1 && args[0] == String16("enable")) {
351 // If currently in restricted mode, reset back to NORMAL mode else ignore.
352 if (mCurrentOperatingMode == RESTRICTED) {
353 mCurrentOperatingMode = NORMAL;
354 dev.enableAllSensors();
355 }
Aravind Akella841a5922015-06-29 12:37:48 -0700356 if (mCurrentOperatingMode == DATA_INJECTION) {
357 resetToNormalModeLocked();
358 }
359 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700360 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700361 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
362 if (mCurrentOperatingMode == NORMAL) {
363 dev.disableAllSensors();
364 status_t err = dev.setMode(DATA_INJECTION);
365 if (err == NO_ERROR) {
366 mCurrentOperatingMode = DATA_INJECTION;
367 } else {
368 // Re-enable sensors.
369 dev.enableAllSensors();
370 }
371 mWhiteListedPackage.setTo(String8(args[1]));
372 return NO_ERROR;
373 } else if (mCurrentOperatingMode == DATA_INJECTION) {
374 // Already in DATA_INJECTION mode. Treat this as a no_op.
375 return NO_ERROR;
376 } else {
377 // Transition to data injection mode supported only from NORMAL mode.
378 return INVALID_OPERATION;
379 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700380 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700381 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700382 } else {
383 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700384 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800385 result.append("Sensor Device:\n");
386 result.append(SensorDevice::getInstance().dump().c_str());
387
388 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700389 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700390
Peng Xu6a2d3a02015-12-21 12:00:23 -0800391 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700392 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700393
Peng Xu0cc8f802016-04-05 23:46:03 -0700394 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800395 for (auto&& i : mRecentEvent) {
396 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700397 if (!i.second->isEmpty()) {
398 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
399 i.second->setFormat("normal");
400 } else {
401 i.second->setFormat("mask_data");
402 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800403 // if there is events and sensor does not need special permission.
404 result.appendFormat("%s: ", s->getSensor().getName().string());
405 result.append(i.second->dump().c_str());
406 }
407 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700408
Aravind Akella444f2672015-05-07 12:40:52 -0700409 result.append("Active sensors:\n");
410 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
411 int handle = mActiveSensors.keyAt(i);
412 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
413 getSensorName(handle).string(),
414 handle,
415 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700416 }
417
Andreas Gamped4036b62015-07-28 13:49:04 -0700418 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700419 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700420 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
421 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700422 result.appendFormat("Mode :");
423 switch(mCurrentOperatingMode) {
424 case NORMAL:
425 result.appendFormat(" NORMAL\n");
426 break;
427 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700428 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700429 break;
430 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700431 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700432 }
Aravind Akella444f2672015-05-07 12:40:52 -0700433 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700434
Aravind Akella444f2672015-05-07 12:40:52 -0700435 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
436 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
437 if (connection != 0) {
438 result.appendFormat("Connection Number: %zu \n", i);
439 connection->dump(result);
440 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700441 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700442
443 result.appendFormat("Previous Registrations:\n");
444 // Log in the reverse chronological order.
445 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
446 SENSOR_REGISTRATIONS_BUF_SIZE;
447 const int startIndex = currentIndex;
448 do {
449 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
450 if (SensorRegistrationInfo::isSentinel(reg_info)) {
451 // Ignore sentinel, proceed to next item.
452 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
453 SENSOR_REGISTRATIONS_BUF_SIZE;
454 continue;
455 }
456 if (reg_info.mActivated) {
Peng Xu363b3fd2016-07-07 15:40:08 -0700457 result.appendFormat("%02d:%02d:%02d activated handle=0x%08x "
458 "samplingRate=%dus maxReportLatency=%dus package=%s\n",
459 reg_info.mHour, reg_info.mMin, reg_info.mSec, reg_info.mSensorHandle,
460 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs,
461 reg_info.mPackageName.string());
Aravind Akella18d6d512015-06-18 14:18:28 -0700462 } else {
Peng Xu363b3fd2016-07-07 15:40:08 -0700463 result.appendFormat("%02d:%02d:%02d de-activated handle=0x%08x package=%s\n",
Aravind Akella18d6d512015-06-18 14:18:28 -0700464 reg_info.mHour, reg_info.mMin, reg_info.mSec,
Peng Xu363b3fd2016-07-07 15:40:08 -0700465 reg_info.mSensorHandle, reg_info.mPackageName.string());
Aravind Akella18d6d512015-06-18 14:18:28 -0700466 }
467 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
468 SENSOR_REGISTRATIONS_BUF_SIZE;
469 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700470 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700471 }
472 write(fd, result.string(), result.size());
473 return NO_ERROR;
474}
475
Peng Xu0cc8f802016-04-05 23:46:03 -0700476//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800477void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700478 sensors_event_t const* buffer, const int count) {
479 for (int i=0 ; i<count ; i++) {
480 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700481 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
482 handle = buffer[i].meta_data.sensor;
483 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700484 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700485 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700486 // If this buffer has an event from a one_shot sensor and this connection is registered
487 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700488 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700489 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
490 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800491 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700492 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700493
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700494 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700495 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700496}
497
Peng Xu47e96012016-03-28 17:55:56 -0700498bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000499 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700500
Peng Xueb4d6282015-12-10 18:02:41 -0800501 // each virtual sensor could generate an event per "real" event, that's why we need to size
502 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
503 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700504 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700505 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700506 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700507
Mathias Agopianf001c922010-11-11 17:58:51 -0800508 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700509
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700510 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700511 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700512 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
513 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000514 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700515 break;
516 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700517
518 // Reset sensors_event_t.flags to zero for all events in the buffer.
519 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700520 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700521 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700522
Peng Xueb4d6282015-12-10 18:02:41 -0800523 // Make a copy of the connection vector as some connections may be removed during the course
524 // of this loop (especially when one-shot sensor events are present in the sensor_event
525 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
526 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
527 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
528 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700529 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700530 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800531
Aravind Akella9a844cf2014-02-11 18:58:52 -0800532 Mutex::Autolock _l(mLock);
533 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
534 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
535 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
536 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
537 // releasing the wakelock.
538 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700539 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700540 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800541 bufferHasWakeUpEvent = true;
542 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700543 }
544 }
545
Aravind Akella9a844cf2014-02-11 18:58:52 -0800546 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700547 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800548 }
Aravind Akella8493b792014-09-08 15:45:47 -0700549 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800550
Mathias Agopianf001c922010-11-11 17:58:51 -0800551 // handle virtual sensors
552 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700553 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700554 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800555 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700556 SensorFusion& fusion(SensorFusion::getInstance());
557 if (fusion.isEnabled()) {
558 for (size_t i=0 ; i<size_t(count) ; i++) {
559 fusion.process(event[i]);
560 }
561 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700562 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700563 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700564 if (count + k >= minBufferSize) {
565 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700566 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700567 count, k, minBufferSize);
568 break;
569 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800570 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700571 sp<SensorInterface> si = mSensors.getInterface(handle);
572 if (si == nullptr) {
573 ALOGE("handle %d is not an valid virtual sensor", handle);
574 continue;
575 }
576
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700577 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700578 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800579 k++;
580 }
581 }
582 }
583 if (k) {
584 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700585 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800586 count += k;
587 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700588 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700589 }
590 }
591 }
592
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700593 // handle backward compatibility for RotationVector sensor
594 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
595 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700596 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700597 // All the 4 components of the quaternion should be available
598 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700599 mSensorEventBuffer[i].data[4] = -1;
600 }
601 }
602 }
603
Aravind Akella8493b792014-09-08 15:45:47 -0700604 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700605 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
606 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
607 // SensorEventConnection mapped to the corresponding flush_complete_event in
608 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700609 mMapFlushEventsToConnections[i] = NULL;
610 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
611 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
612 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
613 if (rec != NULL) {
614 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
615 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700616 }
617 }
Peng Xu2576cb62016-01-20 00:22:09 -0800618
619 // handle dynamic sensor meta events, process registration and unregistration of dynamic
620 // sensor based on content of event.
621 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
622 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
623 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
624 const sensor_t& dynamicSensor =
625 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
626 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
627 handle, dynamicSensor.type, dynamicSensor.name);
628
Peng Xu0cc8f802016-04-05 23:46:03 -0700629 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800630 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700631 sensor_t s = dynamicSensor;
632 // make sure the dynamic sensor flag is set
633 s.flags |= DYNAMIC_SENSOR_MASK;
634 // force the handle to be consistent
635 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800636
637 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800638
Peng Xu0cc8f802016-04-05 23:46:03 -0700639 // This will release hold on dynamic sensor meta, so it should be called
640 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700641 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800642 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700643 } else {
644 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
645 }
Peng Xu2576cb62016-01-20 00:22:09 -0800646 } else {
647 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
648 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
649
650 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800651 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800652 ALOGE("Dynamic sensor release error.");
653 }
654
655 size_t numConnections = activeConnections.size();
656 for (size_t i=0 ; i < numConnections; ++i) {
657 if (activeConnections[i] != NULL) {
658 activeConnections[i]->removeSensor(handle);
659 }
660 }
661 }
662 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700663 }
664
Peng Xu2576cb62016-01-20 00:22:09 -0800665
Aravind Akella9a844cf2014-02-11 18:58:52 -0800666 // Send our events to clients. Check the state of wake lock for each client and release the
667 // lock if none of the clients need it.
668 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700669 size_t numConnections = activeConnections.size();
670 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700671 if (activeConnections[i] != 0) {
672 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700673 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700674 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700675 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
676 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700677 if (activeConnections[i]->hasOneShotSensors()) {
678 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
679 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700680 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800681 }
682 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700683
Aravind Akella9a844cf2014-02-11 18:58:52 -0800684 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700685 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800686 }
Aravind Akella8493b792014-09-08 15:45:47 -0700687 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700688
Steve Block3c20fbe2012-01-05 23:22:43 +0000689 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800690 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700691 return false;
692}
693
Aravind Akella56ae4262014-07-10 16:01:10 -0700694sp<Looper> SensorService::getLooper() const {
695 return mLooper;
696}
697
Aravind Akellab4373ac2014-10-29 17:55:20 -0700698void SensorService::resetAllWakeLockRefCounts() {
699 SortedVector< sp<SensorEventConnection> > activeConnections;
700 populateActiveConnections(&activeConnections);
701 {
702 Mutex::Autolock _l(mLock);
703 for (size_t i=0 ; i < activeConnections.size(); ++i) {
704 if (activeConnections[i] != 0) {
705 activeConnections[i]->resetWakeLockRefCount();
706 }
707 }
708 setWakeLockAcquiredLocked(false);
709 }
710}
711
712void SensorService::setWakeLockAcquiredLocked(bool acquire) {
713 if (acquire) {
714 if (!mWakeLockAcquired) {
715 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
716 mWakeLockAcquired = true;
717 }
718 mLooper->wake();
719 } else {
720 if (mWakeLockAcquired) {
721 release_wake_lock(WAKE_LOCK_NAME);
722 mWakeLockAcquired = false;
723 }
724 }
725}
726
Aravind Akellab4373ac2014-10-29 17:55:20 -0700727bool SensorService::isWakeLockAcquired() {
728 Mutex::Autolock _l(mLock);
729 return mWakeLockAcquired;
730}
731
Aravind Akella56ae4262014-07-10 16:01:10 -0700732bool SensorService::SensorEventAckReceiver::threadLoop() {
733 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700734 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700735 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700736 bool wakeLockAcquired = mService->isWakeLockAcquired();
737 int timeout = -1;
738 if (wakeLockAcquired) timeout = 5000;
739 int ret = looper->pollOnce(timeout);
740 if (ret == ALOOPER_POLL_TIMEOUT) {
741 mService->resetAllWakeLockRefCounts();
742 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700743 } while(!Thread::exitPending());
744 return false;
745}
746
Aravind Akella9a844cf2014-02-11 18:58:52 -0800747void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800748 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800749 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800750 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
751 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800752 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800753 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800754 }
Peng Xu2576cb62016-01-20 00:22:09 -0800755
Peng Xu6a2d3a02015-12-21 12:00:23 -0800756 auto logger = mRecentEvent.find(buffer[i].sensor);
757 if (logger != mRecentEvent.end()) {
758 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800759 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800760 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800761}
762
Peng Xu47e96012016-03-28 17:55:56 -0700763void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800764 struct compar {
765 static int cmp(void const* lhs, void const* rhs) {
766 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
767 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700768 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800769 }
770 };
771 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
772}
773
Mathias Agopian5d270722010-07-19 15:20:39 -0700774String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700775 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700776}
777
Aravind Akellab4099e72013-10-15 15:43:10 -0700778bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700779 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
780 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700781}
782
Aravind Akella9a844cf2014-02-11 18:58:52 -0800783bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700784 int handle = event.sensor;
785 if (event.type == SENSOR_TYPE_META_DATA) {
786 handle = event.meta_data.sensor;
787 }
Peng Xu755c4512016-04-07 23:15:14 -0700788 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
789 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800790}
791
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700792int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
793 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
794 // UUID is not supported for this device.
795 return 0;
796 }
797 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
798 // This sensor can be uniquely identified in the system by
799 // the combination of its type and name.
800 return -1;
801 }
802
803 // We have a dynamic sensor.
804
805 if (!sHmacGlobalKeyIsValid) {
806 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
807 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
808 return 0;
809 }
810
811 // We want each app author/publisher to get a different ID, so that the
812 // same dynamic sensor cannot be tracked across apps by multiple
813 // authors/publishers. So we use both our UUID and our User ID.
814 // Note potential confusion:
815 // UUID => Universally Unique Identifier.
816 // UID => User Identifier.
817 // We refrain from using "uid" except as needed by API to try to
818 // keep this distinction clear.
819
820 auto appUserId = IPCThreadState::self()->getCallingUid();
821 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
822 memcpy(uuidAndApp, &uuid, sizeof(uuid));
823 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
824
825 // Now we use our key on our UUID/app combo to get the hash.
826 uint8_t hash[EVP_MAX_MD_SIZE];
827 unsigned int hashLen;
828 if (HMAC(EVP_sha256(),
829 sHmacGlobalKey, sizeof(sHmacGlobalKey),
830 uuidAndApp, sizeof(uuidAndApp),
831 hash, &hashLen) == nullptr) {
832 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
833 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
834 return 0;
835 }
836
837 int32_t id = 0;
838 if (hashLen < sizeof(id)) {
839 // We never expect this case, but out of paranoia, we handle it.
840 // Our 'id' length is already quite small, we don't want the
841 // effective length of it to be even smaller.
842 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
843 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
844 return 0;
845 }
846
847 // This is almost certainly less than all of 'hash', but it's as secure
848 // as we can be with our current 'id' length.
849 memcpy(&id, hash, sizeof(id));
850
851 // Note at the beginning of the function that we return the values of
852 // 0 and -1 to represent special cases. As a result, we can't return
853 // those as dynamic sensor IDs. If we happened to hash to one of those
854 // values, we change 'id' so we report as a dynamic sensor, and not as
855 // one of those special cases.
856 if (id == -1) {
857 id = -2;
858 } else if (id == 0) {
859 id = 1;
860 }
861 return id;
862}
863
864void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
865 for (auto &sensor : sensorList) {
866 int32_t id = getIdFromUuid(sensor.getUuid());
867 sensor.setId(id);
868 }
869}
870
Peng Xu47e96012016-03-28 17:55:56 -0700871Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -0700872 char value[PROPERTY_VALUE_MAX];
873 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000874 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700875 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000876 Vector<Sensor> accessibleSensorList;
877 for (size_t i = 0; i < initialSensorList.size(); i++) {
878 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700879 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000880 accessibleSensorList.add(sensor);
881 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700882 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100883 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700884 sensor.getRequiredPermission().string(),
885 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000886 }
Mathias Agopian33264862012-06-28 19:46:54 -0700887 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700888 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000889 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700890}
891
Peng Xu47e96012016-03-28 17:55:56 -0700892Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800893 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700894 mSensors.forEachSensor(
895 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -0700896 if (sensor.isDynamicSensor()) {
897 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
898 accessibleSensorList.add(sensor);
899 } else {
900 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
901 sensor.getName().string(),
902 sensor.getRequiredPermission().string(),
903 sensor.getRequiredAppOp());
904 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700905 }
906 return true;
907 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700908 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -0800909 return accessibleSensorList;
910}
911
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700912sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700913 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700914 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
915 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
916 return NULL;
917 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700918
919 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700920 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
921 // operating in DI mode.
922 if (requestedMode == DATA_INJECTION) {
923 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
924 if (!isWhiteListedPackage(packageName)) return NULL;
925 }
926
Mathias Agopian5307d172012-09-18 17:02:43 -0700927 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700928 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700929 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700930 if (requestedMode == DATA_INJECTION) {
931 if (mActiveConnections.indexOf(result) < 0) {
932 mActiveConnections.add(result);
933 }
934 // Add the associated file descriptor to the Looper for polling whenever there is data to
935 // be injected.
936 result->updateLooperRegistration(mLooper);
937 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700938 return result;
939}
940
Aravind Akella841a5922015-06-29 12:37:48 -0700941int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700942 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700943 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700944}
945
946status_t SensorService::resetToNormalMode() {
947 Mutex::Autolock _l(mLock);
948 return resetToNormalModeLocked();
949}
950
951status_t SensorService::resetToNormalModeLocked() {
952 SensorDevice& dev(SensorDevice::getInstance());
953 dev.enableAllSensors();
954 status_t err = dev.setMode(NORMAL);
955 mCurrentOperatingMode = NORMAL;
956 return err;
957}
958
Peng Xu47e96012016-03-28 17:55:56 -0700959void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700960 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800961 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700962 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700963 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700964 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800965 int handle = mActiveSensors.keyAt(i);
966 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700967 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -0700968 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
969 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800970 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -0700971 } else {
972 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800973 }
Aravind Akella8a969552014-09-28 17:52:41 -0700974 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800975 }
976 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700977 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000978 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700979 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700980 c, i, handle);
981
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800982 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000983 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700984 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -0700985 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700986 delete rec;
987 size--;
988 } else {
989 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700990 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700991 }
Aravind Akella8a969552014-09-28 17:52:41 -0700992 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700993 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700994 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800995 if (c->needsWakeLock()) {
996 checkWakeLockStateLocked();
997 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700998}
999
Peng Xu755c4512016-04-07 23:15:14 -07001000sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001001 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001002}
1003
Aravind Akella70018042014-04-07 22:52:37 +00001004
Mathias Agopianfc328812010-07-14 23:41:37 -07001005status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001006 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001007 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001008 if (mInitCheck != NO_ERROR)
1009 return mInitCheck;
1010
Peng Xu755c4512016-04-07 23:15:14 -07001011 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1012 if (sensor == nullptr ||
1013 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001014 return BAD_VALUE;
1015 }
1016
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001017 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001018 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
1019 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001020 return INVALID_OPERATION;
1021 }
1022
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001023 SensorRecord* rec = mActiveSensors.valueFor(handle);
1024 if (rec == 0) {
1025 rec = new SensorRecord(connection);
1026 mActiveSensors.add(handle, rec);
1027 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001028 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001029 }
1030 } else {
1031 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001032 // this sensor is already activated, but we are adding a connection that uses it.
1033 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001034 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001035 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001036 // NOTE: The wake_up flag of this event may get set to
1037 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001038
1039 auto logger = mRecentEvent.find(handle);
1040 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001041 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001042 // It is unlikely that this buffer is empty as the sensor is already active.
1043 // One possible corner case may be two applications activating an on-change
1044 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001045 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001046 event.sensor = handle;
1047 if (event.version == sizeof(sensors_event_t)) {
1048 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1049 setWakeLockAcquiredLocked(true);
1050 }
1051 connection->sendEvents(&event, 1, NULL);
1052 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1053 checkWakeLockStateLocked();
1054 }
1055 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001056 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001057 }
1058 }
1059 }
1060 }
1061
1062 if (connection->addSensor(handle)) {
1063 BatteryService::enableSensor(connection->getUid(), handle);
1064 // the sensor was added (which means it wasn't already there)
1065 // so, see if this connection becomes active
1066 if (mActiveConnections.indexOf(connection) < 0) {
1067 mActiveConnections.add(connection);
1068 }
1069 } else {
1070 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1071 handle, connection.get());
1072 }
1073
Aravind Akella724d91d2013-06-27 12:04:23 -07001074 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1075 if (samplingPeriodNs < minDelayNs) {
1076 samplingPeriodNs = minDelayNs;
1077 }
1078
Aravind Akella6c2664a2014-08-13 12:24:50 -07001079 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1080 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001081 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1082
Aravind Akella4949c502015-02-11 15:54:35 -08001083 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001084 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001085
Peng Xu20483c42015-10-26 15:14:43 -07001086 // Call flush() before calling activate() on the sensor. Wait for a first
1087 // flush complete event before sending events on this connection. Ignore
1088 // one-shot sensors which don't support flush(). Ignore on-change sensors
1089 // to maintain the on-change logic (any on-change events except the initial
1090 // one should be trigger by a change in value). Also if this sensor isn't
1091 // already active, don't call flush().
1092 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001093 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001094 rec->getNumConnections() > 1) {
1095 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001096 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001097 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001098 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001099 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001100 } else {
1101 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001102 }
1103 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001104
1105 if (err == NO_ERROR) {
1106 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1107 err = sensor->activate(connection.get(), true);
1108 }
1109
Aravind Akella8a969552014-09-28 17:52:41 -07001110 if (err == NO_ERROR) {
1111 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -07001112 SensorRegistrationInfo &reg_info =
1113 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1114 reg_info.mSensorHandle = handle;
1115 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1116 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1117 reg_info.mActivated = true;
1118 reg_info.mPackageName = connection->getPackageName();
1119 time_t rawtime = time(NULL);
1120 struct tm * timeinfo = localtime(&rawtime);
1121 reg_info.mHour = timeinfo->tm_hour;
1122 reg_info.mMin = timeinfo->tm_min;
1123 reg_info.mSec = timeinfo->tm_sec;
1124 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001125 }
1126
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001127 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001128 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001129 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001130 }
1131 return err;
1132}
1133
Peng Xu47e96012016-03-28 17:55:56 -07001134status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001135 if (mInitCheck != NO_ERROR)
1136 return mInitCheck;
1137
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001138 Mutex::Autolock _l(mLock);
1139 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001140 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001141 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1142 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001143
1144 }
1145 if (err == NO_ERROR) {
1146 SensorRegistrationInfo &reg_info =
1147 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1148 reg_info.mActivated = false;
1149 reg_info.mPackageName= connection->getPackageName();
1150 reg_info.mSensorHandle = handle;
1151 time_t rawtime = time(NULL);
1152 struct tm * timeinfo = localtime(&rawtime);
1153 reg_info.mHour = timeinfo->tm_hour;
1154 reg_info.mMin = timeinfo->tm_min;
1155 reg_info.mSec = timeinfo->tm_sec;
1156 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001157 }
1158 return err;
1159}
1160
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001161status_t SensorService::cleanupWithoutDisable(
1162 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001163 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001164 return cleanupWithoutDisableLocked(connection, handle);
1165}
1166
1167status_t SensorService::cleanupWithoutDisableLocked(
1168 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001169 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001170 if (rec) {
1171 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001172 if (connection->removeSensor(handle)) {
1173 BatteryService::disableSensor(connection->getUid(), handle);
1174 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001175 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001176 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001177 mActiveConnections.remove(connection);
1178 }
1179 // see if this sensor becomes inactive
1180 if (rec->removeConnection(connection)) {
1181 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001182 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001183 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001184 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001185 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001186 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001187 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001188}
1189
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001190status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001191 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001192 if (mInitCheck != NO_ERROR)
1193 return mInitCheck;
1194
Peng Xu755c4512016-04-07 23:15:14 -07001195 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1196 if (sensor == nullptr ||
1197 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001198 return BAD_VALUE;
1199 }
1200
Mathias Agopian1cd70002010-07-21 15:59:50 -07001201 if (ns < 0)
1202 return BAD_VALUE;
1203
Mathias Agopian62569ec2011-11-07 21:21:47 -08001204 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1205 if (ns < minDelayNs) {
1206 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001207 }
1208
Mathias Agopianf001c922010-11-11 17:58:51 -08001209 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001210}
1211
Svetoslavb412f6e2015-04-29 16:50:41 -07001212status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1213 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001214 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001215 SensorDevice& dev(SensorDevice::getInstance());
1216 const int halVersion = dev.getHalDeviceVersion();
1217 status_t err(NO_ERROR);
1218 Mutex::Autolock _l(mLock);
1219 // Loop through all sensors for this connection and call flush on each of them.
1220 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1221 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001222 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1223 if (sensor == nullptr) {
1224 continue;
1225 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001226 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1227 ALOGE("flush called on a one-shot sensor");
1228 err = INVALID_OPERATION;
1229 continue;
1230 }
Aravind Akella8493b792014-09-08 15:45:47 -07001231 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001232 // For older devices just increment pending flush count which will send a trivial
1233 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001234 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001235 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001236 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1237 err = INVALID_OPERATION;
1238 continue;
1239 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001240 status_t err_flush = sensor->flush(connection.get(), handle);
1241 if (err_flush == NO_ERROR) {
1242 SensorRecord* rec = mActiveSensors.valueFor(handle);
1243 if (rec != NULL) rec->addPendingFlushConnection(connection);
1244 }
1245 err = (err_flush != NO_ERROR) ? err_flush : err;
1246 }
Aravind Akella70018042014-04-07 22:52:37 +00001247 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001248 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001249}
Aravind Akella70018042014-04-07 22:52:37 +00001250
Svetoslavb412f6e2015-04-29 16:50:41 -07001251bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1252 const String16& opPackageName) {
1253 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001254
Svetoslavb412f6e2015-04-29 16:50:41 -07001255 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001256 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001257 }
1258
1259 bool hasPermission = false;
1260
1261 // Runtime permissions can't use the cache as they may change.
1262 if (sensor.isRequiredPermissionRuntime()) {
1263 hasPermission = checkPermission(String16(requiredPermission),
1264 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001265 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001266 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1267 }
1268
1269 if (!hasPermission) {
1270 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1271 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001272 return false;
1273 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001274
1275 const int32_t opCode = sensor.getRequiredAppOp();
1276 if (opCode >= 0) {
1277 AppOpsManager appOps;
1278 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1279 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001280 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001281 operation, sensor.getName().string(), opCode);
1282 return false;
1283 }
1284 }
1285
1286 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001287}
1288
Aravind Akella9a844cf2014-02-11 18:58:52 -08001289void SensorService::checkWakeLockState() {
1290 Mutex::Autolock _l(mLock);
1291 checkWakeLockStateLocked();
1292}
1293
1294void SensorService::checkWakeLockStateLocked() {
1295 if (!mWakeLockAcquired) {
1296 return;
1297 }
1298 bool releaseLock = true;
1299 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1300 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1301 if (connection != 0) {
1302 if (connection->needsWakeLock()) {
1303 releaseLock = false;
1304 break;
1305 }
1306 }
1307 }
1308 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001309 setWakeLockAcquiredLocked(false);
1310 }
1311}
1312
1313void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1314 Mutex::Autolock _l(mLock);
1315 connection->writeToSocketFromCache();
1316 if (connection->needsWakeLock()) {
1317 setWakeLockAcquiredLocked(true);
1318 }
1319}
1320
1321void SensorService::populateActiveConnections(
1322 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1323 Mutex::Autolock _l(mLock);
1324 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1325 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1326 if (connection != 0) {
1327 activeConnections->add(connection);
1328 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001329 }
1330}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001331
Aravind Akella4949c502015-02-11 15:54:35 -08001332bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001333 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001334}
1335
Mathias Agopianfc328812010-07-14 23:41:37 -07001336}; // namespace android
1337