blob: e5b6dcf750336135bdfc9225e30c1290ea59da98 [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 */
Svetoslavb412f6e2015-04-29 16:50:41 -070016#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070017#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070018#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070019#include <binder/PermissionCache.h>
Peng Xue36e3472016-11-03 11:57:10 -070020#include <cutils/ashmem.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070021#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070023#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080024#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070025#include <openssl/digest.h>
26#include <openssl/hmac.h>
27#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070028#include <sensor/SensorEventQueue.h>
29#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030
Mathias Agopian787ac1b2012-09-18 18:49:18 -070031#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070032#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080033#include "GravitySensor.h"
34#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080036#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070037#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070038#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080039
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070041#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080042#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080043#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080044#include "SensorRecord.h"
45#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080046
47#include <inttypes.h>
48#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070049#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080050#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080051#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070052#include <sys/stat.h>
53#include <sys/types.h>
54#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070055
56namespace android {
57// ---------------------------------------------------------------------------
58
Mathias Agopian33015422011-05-27 18:18:13 -070059/*
60 * Notes:
61 *
62 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070063 * - run mag sensor from time to time to force calibration
64 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
65 *
66 */
67
Aravind Akella8ef3c892015-07-10 11:24:28 -070068const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070069uint8_t SensorService::sHmacGlobalKey[128] = {};
70bool SensorService::sHmacGlobalKeyIsValid = false;
71
72#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
73#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070074#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070075
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070076// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070077static const String16 sDumpPermission("android.permission.DUMP");
78static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
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];
Peng Xueb059472016-08-12 16:39:44 -0700263 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [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;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700320 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
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 }
Peng Xue36e3472016-11-03 11:57:10 -0700340
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700341 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700342 // temporarily stop all sensor direct report
343 for (auto &i : mDirectConnections) {
344 sp<SensorDirectConnection> connection(i.promote());
345 if (connection != nullptr) {
346 connection->stopAll(true /* backupRecord */);
347 }
348 }
349
Aravind Akella4949c502015-02-11 15:54:35 -0800350 dev.disableAllSensors();
351 // Clear all pending flush connections for all active sensors. If one of the active
352 // connections has called flush() and the underlying sensor has been disabled before a
353 // flush complete event is returned, we need to remove the connection from this queue.
354 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
355 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
356 }
Aravind Akella841a5922015-06-29 12:37:48 -0700357 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700358 return status_t(NO_ERROR);
359 } else if (args.size() == 1 && args[0] == String16("enable")) {
360 // If currently in restricted mode, reset back to NORMAL mode else ignore.
361 if (mCurrentOperatingMode == RESTRICTED) {
362 mCurrentOperatingMode = NORMAL;
363 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700364 // recover all sensor direct report
365 for (auto &i : mDirectConnections) {
366 sp<SensorDirectConnection> connection(i.promote());
367 if (connection != nullptr) {
368 connection->recoverAll();
369 }
370 }
Aravind Akella444f2672015-05-07 12:40:52 -0700371 }
Aravind Akella841a5922015-06-29 12:37:48 -0700372 if (mCurrentOperatingMode == DATA_INJECTION) {
373 resetToNormalModeLocked();
374 }
375 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700376 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700377 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
378 if (mCurrentOperatingMode == NORMAL) {
379 dev.disableAllSensors();
380 status_t err = dev.setMode(DATA_INJECTION);
381 if (err == NO_ERROR) {
382 mCurrentOperatingMode = DATA_INJECTION;
383 } else {
384 // Re-enable sensors.
385 dev.enableAllSensors();
386 }
387 mWhiteListedPackage.setTo(String8(args[1]));
388 return NO_ERROR;
389 } else if (mCurrentOperatingMode == DATA_INJECTION) {
390 // Already in DATA_INJECTION mode. Treat this as a no_op.
391 return NO_ERROR;
392 } else {
393 // Transition to data injection mode supported only from NORMAL mode.
394 return INVALID_OPERATION;
395 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700396 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700397 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700398 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700399 } else {
400 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700401 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800402 result.append("Sensor Device:\n");
403 result.append(SensorDevice::getInstance().dump().c_str());
404
405 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700406 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700407
Peng Xu6a2d3a02015-12-21 12:00:23 -0800408 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700409 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700410
Peng Xu0cc8f802016-04-05 23:46:03 -0700411 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800412 for (auto&& i : mRecentEvent) {
413 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700414 if (!i.second->isEmpty()) {
415 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
416 i.second->setFormat("normal");
417 } else {
418 i.second->setFormat("mask_data");
419 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800420 // if there is events and sensor does not need special permission.
421 result.appendFormat("%s: ", s->getSensor().getName().string());
422 result.append(i.second->dump().c_str());
423 }
424 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700425
Aravind Akella444f2672015-05-07 12:40:52 -0700426 result.append("Active sensors:\n");
427 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
428 int handle = mActiveSensors.keyAt(i);
429 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
430 getSensorName(handle).string(),
431 handle,
432 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700433 }
434
Andreas Gamped4036b62015-07-28 13:49:04 -0700435 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700436 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700437 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
438 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700439 result.appendFormat("Mode :");
440 switch(mCurrentOperatingMode) {
441 case NORMAL:
442 result.appendFormat(" NORMAL\n");
443 break;
444 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700445 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700446 break;
447 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700448 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700449 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700450
Peng Xue36e3472016-11-03 11:57:10 -0700451 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700452 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
453 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
454 if (connection != 0) {
455 result.appendFormat("Connection Number: %zu \n", i);
456 connection->dump(result);
457 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700458 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700459
Peng Xue36e3472016-11-03 11:57:10 -0700460 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
461 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
462 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
463 if (connection != nullptr) {
464 result.appendFormat("Direct connection %zu:\n", i);
465 connection->dump(result);
466 }
467 }
468
Aravind Akella18d6d512015-06-18 14:18:28 -0700469 result.appendFormat("Previous Registrations:\n");
470 // Log in the reverse chronological order.
471 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
472 SENSOR_REGISTRATIONS_BUF_SIZE;
473 const int startIndex = currentIndex;
474 do {
475 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
476 if (SensorRegistrationInfo::isSentinel(reg_info)) {
477 // Ignore sentinel, proceed to next item.
478 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
479 SENSOR_REGISTRATIONS_BUF_SIZE;
480 continue;
481 }
Peng Xu51224682017-03-10 16:57:27 -0800482 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700483 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
484 SENSOR_REGISTRATIONS_BUF_SIZE;
485 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700486 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700487 }
488 write(fd, result.string(), result.size());
489 return NO_ERROR;
490}
491
Peng Xu0cc8f802016-04-05 23:46:03 -0700492//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800493void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700494 sensors_event_t const* buffer, const int count) {
495 for (int i=0 ; i<count ; i++) {
496 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700497 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
498 handle = buffer[i].meta_data.sensor;
499 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700500 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700501 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700502 // If this buffer has an event from a one_shot sensor and this connection is registered
503 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700504 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700505 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
506 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800507 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700508 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700509
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700510 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700511 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700512}
513
Peng Xu47e96012016-03-28 17:55:56 -0700514bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000515 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700516
Peng Xueb4d6282015-12-10 18:02:41 -0800517 // each virtual sensor could generate an event per "real" event, that's why we need to size
518 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
519 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700520 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700521 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700522 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700523
Mathias Agopianf001c922010-11-11 17:58:51 -0800524 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700525
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700526 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700527 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700528 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
529 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000530 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700531 break;
532 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700533
534 // Reset sensors_event_t.flags to zero for all events in the buffer.
535 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700536 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700537 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700538
Peng Xueb4d6282015-12-10 18:02:41 -0800539 // Make a copy of the connection vector as some connections may be removed during the course
540 // of this loop (especially when one-shot sensor events are present in the sensor_event
541 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
542 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
543 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
544 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700545 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700546 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800547
Aravind Akella9a844cf2014-02-11 18:58:52 -0800548 Mutex::Autolock _l(mLock);
549 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
550 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
551 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
552 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
553 // releasing the wakelock.
554 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700555 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700556 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800557 bufferHasWakeUpEvent = true;
558 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700559 }
560 }
561
Aravind Akella9a844cf2014-02-11 18:58:52 -0800562 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700563 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800564 }
Aravind Akella8493b792014-09-08 15:45:47 -0700565 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800566
Mathias Agopianf001c922010-11-11 17:58:51 -0800567 // handle virtual sensors
568 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700569 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700570 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800571 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700572 SensorFusion& fusion(SensorFusion::getInstance());
573 if (fusion.isEnabled()) {
574 for (size_t i=0 ; i<size_t(count) ; i++) {
575 fusion.process(event[i]);
576 }
577 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700578 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700579 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700580 if (count + k >= minBufferSize) {
581 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700582 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700583 count, k, minBufferSize);
584 break;
585 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800586 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700587 sp<SensorInterface> si = mSensors.getInterface(handle);
588 if (si == nullptr) {
589 ALOGE("handle %d is not an valid virtual sensor", handle);
590 continue;
591 }
592
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700593 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700594 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800595 k++;
596 }
597 }
598 }
599 if (k) {
600 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700601 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800602 count += k;
603 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700604 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700605 }
606 }
607 }
608
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700609 // handle backward compatibility for RotationVector sensor
610 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
611 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700612 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700613 // All the 4 components of the quaternion should be available
614 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700615 mSensorEventBuffer[i].data[4] = -1;
616 }
617 }
618 }
619
Aravind Akella8493b792014-09-08 15:45:47 -0700620 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700621 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
622 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
623 // SensorEventConnection mapped to the corresponding flush_complete_event in
624 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700625 mMapFlushEventsToConnections[i] = NULL;
626 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
627 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
628 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
629 if (rec != NULL) {
630 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
631 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700632 }
633 }
Peng Xu2576cb62016-01-20 00:22:09 -0800634
635 // handle dynamic sensor meta events, process registration and unregistration of dynamic
636 // sensor based on content of event.
637 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
638 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
639 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
640 const sensor_t& dynamicSensor =
641 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
642 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
643 handle, dynamicSensor.type, dynamicSensor.name);
644
Peng Xu0cc8f802016-04-05 23:46:03 -0700645 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800646 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700647 sensor_t s = dynamicSensor;
648 // make sure the dynamic sensor flag is set
649 s.flags |= DYNAMIC_SENSOR_MASK;
650 // force the handle to be consistent
651 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800652
653 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800654
Peng Xu0cc8f802016-04-05 23:46:03 -0700655 // This will release hold on dynamic sensor meta, so it should be called
656 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700657 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800658 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700659 } else {
660 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
661 }
Peng Xu2576cb62016-01-20 00:22:09 -0800662 } else {
663 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
664 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
665
666 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800667 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800668 ALOGE("Dynamic sensor release error.");
669 }
670
671 size_t numConnections = activeConnections.size();
672 for (size_t i=0 ; i < numConnections; ++i) {
673 if (activeConnections[i] != NULL) {
674 activeConnections[i]->removeSensor(handle);
675 }
676 }
677 }
678 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700679 }
680
Peng Xu2576cb62016-01-20 00:22:09 -0800681
Aravind Akella9a844cf2014-02-11 18:58:52 -0800682 // Send our events to clients. Check the state of wake lock for each client and release the
683 // lock if none of the clients need it.
684 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700685 size_t numConnections = activeConnections.size();
686 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700687 if (activeConnections[i] != 0) {
688 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700689 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700690 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700691 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
692 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700693 if (activeConnections[i]->hasOneShotSensors()) {
694 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
695 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700696 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800697 }
698 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700699
Aravind Akella9a844cf2014-02-11 18:58:52 -0800700 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700701 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800702 }
Aravind Akella8493b792014-09-08 15:45:47 -0700703 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700704
Steve Block3c20fbe2012-01-05 23:22:43 +0000705 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800706 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700707 return false;
708}
709
Aravind Akella56ae4262014-07-10 16:01:10 -0700710sp<Looper> SensorService::getLooper() const {
711 return mLooper;
712}
713
Aravind Akellab4373ac2014-10-29 17:55:20 -0700714void SensorService::resetAllWakeLockRefCounts() {
715 SortedVector< sp<SensorEventConnection> > activeConnections;
716 populateActiveConnections(&activeConnections);
717 {
718 Mutex::Autolock _l(mLock);
719 for (size_t i=0 ; i < activeConnections.size(); ++i) {
720 if (activeConnections[i] != 0) {
721 activeConnections[i]->resetWakeLockRefCount();
722 }
723 }
724 setWakeLockAcquiredLocked(false);
725 }
726}
727
728void SensorService::setWakeLockAcquiredLocked(bool acquire) {
729 if (acquire) {
730 if (!mWakeLockAcquired) {
731 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
732 mWakeLockAcquired = true;
733 }
734 mLooper->wake();
735 } else {
736 if (mWakeLockAcquired) {
737 release_wake_lock(WAKE_LOCK_NAME);
738 mWakeLockAcquired = false;
739 }
740 }
741}
742
Aravind Akellab4373ac2014-10-29 17:55:20 -0700743bool SensorService::isWakeLockAcquired() {
744 Mutex::Autolock _l(mLock);
745 return mWakeLockAcquired;
746}
747
Aravind Akella56ae4262014-07-10 16:01:10 -0700748bool SensorService::SensorEventAckReceiver::threadLoop() {
749 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700750 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700751 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700752 bool wakeLockAcquired = mService->isWakeLockAcquired();
753 int timeout = -1;
754 if (wakeLockAcquired) timeout = 5000;
755 int ret = looper->pollOnce(timeout);
756 if (ret == ALOOPER_POLL_TIMEOUT) {
757 mService->resetAllWakeLockRefCounts();
758 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700759 } while(!Thread::exitPending());
760 return false;
761}
762
Aravind Akella9a844cf2014-02-11 18:58:52 -0800763void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800764 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800765 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800766 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
767 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800768 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800769 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800770 }
Peng Xu2576cb62016-01-20 00:22:09 -0800771
Peng Xu6a2d3a02015-12-21 12:00:23 -0800772 auto logger = mRecentEvent.find(buffer[i].sensor);
773 if (logger != mRecentEvent.end()) {
774 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800775 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800776 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800777}
778
Peng Xu47e96012016-03-28 17:55:56 -0700779void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800780 struct compar {
781 static int cmp(void const* lhs, void const* rhs) {
782 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
783 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700784 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800785 }
786 };
787 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
788}
789
Mathias Agopian5d270722010-07-19 15:20:39 -0700790String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700791 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700792}
793
Aravind Akellab4099e72013-10-15 15:43:10 -0700794bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700795 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
796 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700797}
798
Aravind Akella9a844cf2014-02-11 18:58:52 -0800799bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700800 int handle = event.sensor;
801 if (event.type == SENSOR_TYPE_META_DATA) {
802 handle = event.meta_data.sensor;
803 }
Peng Xu755c4512016-04-07 23:15:14 -0700804 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
805 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800806}
807
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700808int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
809 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
810 // UUID is not supported for this device.
811 return 0;
812 }
813 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
814 // This sensor can be uniquely identified in the system by
815 // the combination of its type and name.
816 return -1;
817 }
818
819 // We have a dynamic sensor.
820
821 if (!sHmacGlobalKeyIsValid) {
822 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
823 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
824 return 0;
825 }
826
827 // We want each app author/publisher to get a different ID, so that the
828 // same dynamic sensor cannot be tracked across apps by multiple
829 // authors/publishers. So we use both our UUID and our User ID.
830 // Note potential confusion:
831 // UUID => Universally Unique Identifier.
832 // UID => User Identifier.
833 // We refrain from using "uid" except as needed by API to try to
834 // keep this distinction clear.
835
836 auto appUserId = IPCThreadState::self()->getCallingUid();
837 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
838 memcpy(uuidAndApp, &uuid, sizeof(uuid));
839 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
840
841 // Now we use our key on our UUID/app combo to get the hash.
842 uint8_t hash[EVP_MAX_MD_SIZE];
843 unsigned int hashLen;
844 if (HMAC(EVP_sha256(),
845 sHmacGlobalKey, sizeof(sHmacGlobalKey),
846 uuidAndApp, sizeof(uuidAndApp),
847 hash, &hashLen) == nullptr) {
848 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
849 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
850 return 0;
851 }
852
853 int32_t id = 0;
854 if (hashLen < sizeof(id)) {
855 // We never expect this case, but out of paranoia, we handle it.
856 // Our 'id' length is already quite small, we don't want the
857 // effective length of it to be even smaller.
858 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
859 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
860 return 0;
861 }
862
863 // This is almost certainly less than all of 'hash', but it's as secure
864 // as we can be with our current 'id' length.
865 memcpy(&id, hash, sizeof(id));
866
867 // Note at the beginning of the function that we return the values of
868 // 0 and -1 to represent special cases. As a result, we can't return
869 // those as dynamic sensor IDs. If we happened to hash to one of those
870 // values, we change 'id' so we report as a dynamic sensor, and not as
871 // one of those special cases.
872 if (id == -1) {
873 id = -2;
874 } else if (id == 0) {
875 id = 1;
876 }
877 return id;
878}
879
880void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
881 for (auto &sensor : sensorList) {
882 int32_t id = getIdFromUuid(sensor.getUuid());
883 sensor.setId(id);
884 }
885}
886
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800887Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700888 char value[PROPERTY_VALUE_MAX];
889 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000890 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700891 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000892 Vector<Sensor> accessibleSensorList;
893 for (size_t i = 0; i < initialSensorList.size(); i++) {
894 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800895 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700896 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700897 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000898 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700899}
900
Peng Xu47e96012016-03-28 17:55:56 -0700901Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800902 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700903 mSensors.forEachSensor(
904 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -0700905 if (sensor.isDynamicSensor()) {
906 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
907 accessibleSensorList.add(sensor);
908 } else {
909 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
910 sensor.getName().string(),
911 sensor.getRequiredPermission().string(),
912 sensor.getRequiredAppOp());
913 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700914 }
915 return true;
916 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700917 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -0800918 return accessibleSensorList;
919}
920
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700921sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700922 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700923 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
924 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
925 return NULL;
926 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700927
928 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700929 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
930 // operating in DI mode.
931 if (requestedMode == DATA_INJECTION) {
932 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
933 if (!isWhiteListedPackage(packageName)) return NULL;
934 }
935
Mathias Agopian5307d172012-09-18 17:02:43 -0700936 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -0700937 pid_t pid = IPCThreadState::self()->getCallingPid();
938
939 String8 connPackageName =
940 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
941 String16 connOpPackageName =
942 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
943 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
944 requestedMode == DATA_INJECTION, connOpPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700945 if (requestedMode == DATA_INJECTION) {
946 if (mActiveConnections.indexOf(result) < 0) {
947 mActiveConnections.add(result);
948 }
949 // Add the associated file descriptor to the Looper for polling whenever there is data to
950 // be injected.
951 result->updateLooperRegistration(mLooper);
952 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700953 return result;
954}
955
Aravind Akella841a5922015-06-29 12:37:48 -0700956int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700957 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700958 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700959}
960
Peng Xue36e3472016-11-03 11:57:10 -0700961sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
962 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
963 const native_handle *resource) {
964 Mutex::Autolock _l(mLock);
965
966 struct sensors_direct_mem_t mem = {
967 .type = type,
968 .format = format,
969 .size = size,
970 .handle = resource,
971 };
972 uid_t uid = IPCThreadState::self()->getCallingUid();
973
974 if (mem.handle == nullptr) {
975 ALOGE("Failed to clone resource handle");
976 return nullptr;
977 }
978
979 // check format
980 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
981 ALOGE("Direct channel format %d is unsupported!", format);
982 return nullptr;
983 }
984
985 // check for duplication
986 for (auto &i : mDirectConnections) {
987 sp<SensorDirectConnection> connection(i.promote());
988 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -0700989 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -0700990 return nullptr;
991 }
992 }
993
994 // check specific to memory type
995 switch(type) {
996 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -0800997 if (resource->numFds < 1) {
998 ALOGE("Ashmem direct channel requires a memory region to be supplied");
999 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1000 return nullptr;
1001 }
Peng Xue36e3472016-11-03 11:57:10 -07001002 int fd = resource->data[0];
1003 int size2 = ashmem_get_size_region(fd);
1004 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001005 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001006 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1007 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001008 return nullptr;
1009 }
1010 break;
1011 }
1012 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001013 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001014 break;
1015 default:
1016 ALOGE("Unknown direct connection memory type %d", type);
1017 return nullptr;
1018 }
1019
1020 native_handle_t *clone = native_handle_clone(resource);
1021 if (!clone) {
1022 return nullptr;
1023 }
1024
1025 SensorDirectConnection* conn = nullptr;
1026 SensorDevice& dev(SensorDevice::getInstance());
1027 int channelHandle = dev.registerDirectChannel(&mem);
1028
1029 if (channelHandle <= 0) {
1030 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1031 } else {
1032 mem.handle = clone;
1033 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1034 }
1035
1036 if (conn == nullptr) {
1037 native_handle_close(clone);
1038 native_handle_delete(clone);
1039 } else {
1040 // add to list of direct connections
1041 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1042 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1043 }
1044 return conn;
1045}
1046
Peng Xudd5c5cb2017-03-16 17:39:43 -07001047int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001048 int32_t handle, int32_t type,
1049 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001050 Mutex::Autolock _l(mLock);
1051
Alexey Polyudov88711e82017-05-23 19:54:04 -07001052 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001053 return PERMISSION_DENIED;
1054 }
1055
1056 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001057 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001058 size_t expectSize = INT32_MAX;
1059 switch (type) {
1060 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1061 isFloat = true;
1062 expectSize = 3;
1063 break;
1064 case AINFO_LOCAL_GRAVITY:
1065 isFloat = true;
1066 expectSize = 1;
1067 break;
1068 case AINFO_DOCK_STATE:
1069 case AINFO_HIGH_PERFORMANCE_MODE:
1070 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1071 isFloat = false;
1072 expectSize = 1;
1073 break;
1074 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001075 // CUSTOM events must only contain float data; it may have variable size
1076 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1077 ints.size() ||
1078 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1079 handle < 0) {
1080 return BAD_VALUE;
1081 }
1082 isFloat = true;
1083 isCustom = true;
1084 expectSize = floats.size();
1085 break;
1086 }
1087
1088 if (!isCustom && handle != -1) {
1089 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001090 }
1091
1092 // three events: first one is begin tag, last one is end tag, the one in the middle
1093 // is the payload.
1094 sensors_event_t event[3];
1095 int64_t timestamp = elapsedRealtimeNano();
1096 for (sensors_event_t* i = event; i < event + 3; i++) {
1097 *i = (sensors_event_t) {
1098 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001099 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001100 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1101 .timestamp = timestamp++,
1102 .additional_info = (additional_info_event_t) {
1103 .serial = 0
1104 }
1105 };
1106 }
1107
1108 event[0].additional_info.type = AINFO_BEGIN;
1109 event[1].additional_info.type = type;
1110 event[2].additional_info.type = AINFO_END;
1111
1112 if (isFloat) {
1113 if (floats.size() != expectSize) {
1114 return BAD_VALUE;
1115 }
1116 for (size_t i = 0; i < expectSize; ++i) {
1117 event[1].additional_info.data_float[i] = floats[i];
1118 }
1119 } else {
1120 if (ints.size() != expectSize) {
1121 return BAD_VALUE;
1122 }
1123 for (size_t i = 0; i < expectSize; ++i) {
1124 event[1].additional_info.data_int32[i] = ints[i];
1125 }
1126 }
1127
1128 SensorDevice& dev(SensorDevice::getInstance());
1129 for (sensors_event_t* i = event; i < event + 3; i++) {
1130 int ret = dev.injectSensorData(i);
1131 if (ret != NO_ERROR) {
1132 return ret;
1133 }
1134 }
1135 return NO_ERROR;
1136}
1137
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001138status_t SensorService::resetToNormalMode() {
1139 Mutex::Autolock _l(mLock);
1140 return resetToNormalModeLocked();
1141}
1142
1143status_t SensorService::resetToNormalModeLocked() {
1144 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001145 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301146 if (err == NO_ERROR) {
1147 mCurrentOperatingMode = NORMAL;
1148 dev.enableAllSensors();
1149 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001150 return err;
1151}
1152
Peng Xu47e96012016-03-28 17:55:56 -07001153void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001154 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001155 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001156 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001157 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001158 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001159 int handle = mActiveSensors.keyAt(i);
1160 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001161 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001162 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1163 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001164 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001165 } else {
1166 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001167 }
Aravind Akella8a969552014-09-28 17:52:41 -07001168 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001169 }
1170 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001171 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001172 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001173 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001174 c, i, handle);
1175
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001176 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001177 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001178 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001179 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001180 delete rec;
1181 size--;
1182 } else {
1183 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001184 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001185 }
Aravind Akella8a969552014-09-28 17:52:41 -07001186 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001187 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001188 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001189 if (c->needsWakeLock()) {
1190 checkWakeLockStateLocked();
1191 }
Peng Xu4f707f82016-09-26 11:28:32 -07001192
1193 SensorDevice& dev(SensorDevice::getInstance());
1194 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001195}
1196
Peng Xue36e3472016-11-03 11:57:10 -07001197void SensorService::cleanupConnection(SensorDirectConnection* c) {
1198 Mutex::Autolock _l(mLock);
1199
1200 SensorDevice& dev(SensorDevice::getInstance());
1201 dev.unregisterDirectChannel(c->getHalChannelHandle());
1202 mDirectConnections.remove(c);
1203}
1204
Peng Xu755c4512016-04-07 23:15:14 -07001205sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001206 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001207}
1208
Mathias Agopianfc328812010-07-14 23:41:37 -07001209status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001210 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001211 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001212 if (mInitCheck != NO_ERROR)
1213 return mInitCheck;
1214
Peng Xu755c4512016-04-07 23:15:14 -07001215 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1216 if (sensor == nullptr ||
1217 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001218 return BAD_VALUE;
1219 }
1220
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001221 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001222 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001223 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001224 return INVALID_OPERATION;
1225 }
1226
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001227 SensorRecord* rec = mActiveSensors.valueFor(handle);
1228 if (rec == 0) {
1229 rec = new SensorRecord(connection);
1230 mActiveSensors.add(handle, rec);
1231 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001232 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001233 }
1234 } else {
1235 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001236 // this sensor is already activated, but we are adding a connection that uses it.
1237 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001238 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001239 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001240 // NOTE: The wake_up flag of this event may get set to
1241 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001242
1243 auto logger = mRecentEvent.find(handle);
1244 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001245 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001246 // It is unlikely that this buffer is empty as the sensor is already active.
1247 // One possible corner case may be two applications activating an on-change
1248 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001249 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001250 event.sensor = handle;
1251 if (event.version == sizeof(sensors_event_t)) {
1252 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1253 setWakeLockAcquiredLocked(true);
1254 }
1255 connection->sendEvents(&event, 1, NULL);
1256 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1257 checkWakeLockStateLocked();
1258 }
1259 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001260 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001261 }
1262 }
1263 }
1264 }
1265
1266 if (connection->addSensor(handle)) {
1267 BatteryService::enableSensor(connection->getUid(), handle);
1268 // the sensor was added (which means it wasn't already there)
1269 // so, see if this connection becomes active
1270 if (mActiveConnections.indexOf(connection) < 0) {
1271 mActiveConnections.add(connection);
1272 }
1273 } else {
1274 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1275 handle, connection.get());
1276 }
1277
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301278 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001279 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301280 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1281 samplingPeriodNs = maxDelayNs;
1282 }
1283
Aravind Akella724d91d2013-06-27 12:04:23 -07001284 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1285 if (samplingPeriodNs < minDelayNs) {
1286 samplingPeriodNs = minDelayNs;
1287 }
1288
Aravind Akella6c2664a2014-08-13 12:24:50 -07001289 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1290 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001291 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1292
Aravind Akella4949c502015-02-11 15:54:35 -08001293 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001294 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001295
Peng Xu20483c42015-10-26 15:14:43 -07001296 // Call flush() before calling activate() on the sensor. Wait for a first
1297 // flush complete event before sending events on this connection. Ignore
1298 // one-shot sensors which don't support flush(). Ignore on-change sensors
1299 // to maintain the on-change logic (any on-change events except the initial
1300 // one should be trigger by a change in value). Also if this sensor isn't
1301 // already active, don't call flush().
1302 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001303 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001304 rec->getNumConnections() > 1) {
1305 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001306 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001307 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001308 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001309 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001310 } else {
1311 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001312 }
1313 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001314
1315 if (err == NO_ERROR) {
1316 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1317 err = sensor->activate(connection.get(), true);
1318 }
1319
Aravind Akella8a969552014-09-28 17:52:41 -07001320 if (err == NO_ERROR) {
1321 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001322
1323 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1324 SensorRegistrationInfo(handle, connection->getPackageName(),
1325 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001326 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001327 }
1328
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001329 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001330 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001331 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001332 }
1333 return err;
1334}
1335
Peng Xu47e96012016-03-28 17:55:56 -07001336status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001337 if (mInitCheck != NO_ERROR)
1338 return mInitCheck;
1339
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001340 Mutex::Autolock _l(mLock);
1341 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001342 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001343 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1344 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001345
1346 }
1347 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001348 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1349 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001350 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001351 }
1352 return err;
1353}
1354
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001355status_t SensorService::cleanupWithoutDisable(
1356 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001357 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001358 return cleanupWithoutDisableLocked(connection, handle);
1359}
1360
1361status_t SensorService::cleanupWithoutDisableLocked(
1362 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001363 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001364 if (rec) {
1365 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001366 if (connection->removeSensor(handle)) {
1367 BatteryService::disableSensor(connection->getUid(), handle);
1368 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001369 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001370 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001371 mActiveConnections.remove(connection);
1372 }
1373 // see if this sensor becomes inactive
1374 if (rec->removeConnection(connection)) {
1375 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001376 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001377 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001378 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001379 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001380 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001381 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001382}
1383
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001384status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001385 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001386 if (mInitCheck != NO_ERROR)
1387 return mInitCheck;
1388
Peng Xu755c4512016-04-07 23:15:14 -07001389 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1390 if (sensor == nullptr ||
1391 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001392 return BAD_VALUE;
1393 }
1394
Mathias Agopian1cd70002010-07-21 15:59:50 -07001395 if (ns < 0)
1396 return BAD_VALUE;
1397
Mathias Agopian62569ec2011-11-07 21:21:47 -08001398 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1399 if (ns < minDelayNs) {
1400 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001401 }
1402
Mathias Agopianf001c922010-11-11 17:58:51 -08001403 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001404}
1405
Svetoslavb412f6e2015-04-29 16:50:41 -07001406status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1407 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001408 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001409 SensorDevice& dev(SensorDevice::getInstance());
1410 const int halVersion = dev.getHalDeviceVersion();
1411 status_t err(NO_ERROR);
1412 Mutex::Autolock _l(mLock);
1413 // Loop through all sensors for this connection and call flush on each of them.
1414 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1415 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001416 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1417 if (sensor == nullptr) {
1418 continue;
1419 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001420 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1421 ALOGE("flush called on a one-shot sensor");
1422 err = INVALID_OPERATION;
1423 continue;
1424 }
Aravind Akella8493b792014-09-08 15:45:47 -07001425 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001426 // For older devices just increment pending flush count which will send a trivial
1427 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001428 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001429 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001430 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1431 err = INVALID_OPERATION;
1432 continue;
1433 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001434 status_t err_flush = sensor->flush(connection.get(), handle);
1435 if (err_flush == NO_ERROR) {
1436 SensorRecord* rec = mActiveSensors.valueFor(handle);
1437 if (rec != NULL) rec->addPendingFlushConnection(connection);
1438 }
1439 err = (err_flush != NO_ERROR) ? err_flush : err;
1440 }
Aravind Akella70018042014-04-07 22:52:37 +00001441 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001442 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001443}
Aravind Akella70018042014-04-07 22:52:37 +00001444
Svetoslavb412f6e2015-04-29 16:50:41 -07001445bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1446 const String16& opPackageName) {
1447 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001448
Svetoslavb412f6e2015-04-29 16:50:41 -07001449 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001450 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001451 }
1452
1453 bool hasPermission = false;
1454
1455 // Runtime permissions can't use the cache as they may change.
1456 if (sensor.isRequiredPermissionRuntime()) {
1457 hasPermission = checkPermission(String16(requiredPermission),
1458 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001459 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001460 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1461 }
1462
1463 if (!hasPermission) {
1464 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1465 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001466 return false;
1467 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001468
1469 const int32_t opCode = sensor.getRequiredAppOp();
1470 if (opCode >= 0) {
1471 AppOpsManager appOps;
1472 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1473 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001474 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001475 operation, sensor.getName().string(), opCode);
1476 return false;
1477 }
1478 }
1479
1480 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001481}
1482
Aravind Akella9a844cf2014-02-11 18:58:52 -08001483void SensorService::checkWakeLockState() {
1484 Mutex::Autolock _l(mLock);
1485 checkWakeLockStateLocked();
1486}
1487
1488void SensorService::checkWakeLockStateLocked() {
1489 if (!mWakeLockAcquired) {
1490 return;
1491 }
1492 bool releaseLock = true;
1493 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1494 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1495 if (connection != 0) {
1496 if (connection->needsWakeLock()) {
1497 releaseLock = false;
1498 break;
1499 }
1500 }
1501 }
1502 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001503 setWakeLockAcquiredLocked(false);
1504 }
1505}
1506
1507void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1508 Mutex::Autolock _l(mLock);
1509 connection->writeToSocketFromCache();
1510 if (connection->needsWakeLock()) {
1511 setWakeLockAcquiredLocked(true);
1512 }
1513}
1514
1515void SensorService::populateActiveConnections(
1516 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1517 Mutex::Autolock _l(mLock);
1518 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1519 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1520 if (connection != 0) {
1521 activeConnections->add(connection);
1522 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001523 }
1524}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001525
Aravind Akella4949c502015-02-11 15:54:35 -08001526bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001527 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001528}
1529
Peng Xue36e3472016-11-03 11:57:10 -07001530bool SensorService::isOperationRestricted(const String16& opPackageName) {
1531 Mutex::Autolock _l(mLock);
1532 if (mCurrentOperatingMode != RESTRICTED) {
1533 String8 package(opPackageName);
1534 return !isWhiteListedPackage(package);
1535 }
1536 return false;
1537}
1538
Mathias Agopianfc328812010-07-14 23:41:37 -07001539}; // namespace android