blob: 209eea52027a95916f292e45a0e7640cf0777248 [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>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070024#include <openssl/digest.h>
25#include <openssl/hmac.h>
26#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070027#include <sensor/SensorEventQueue.h>
28#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070029
Mathias Agopian787ac1b2012-09-18 18:49:18 -070030#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070031#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080032#include "GravitySensor.h"
33#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070034#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080035#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070036#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070037#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080038
Mathias Agopian984826c2011-05-17 22:54:42 -070039#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070040#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080041#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080042#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080043#include "SensorRecord.h"
44#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045
46#include <inttypes.h>
47#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070048#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080049#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080050#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070051#include <sys/stat.h>
52#include <sys/types.h>
53#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070054
55namespace android {
56// ---------------------------------------------------------------------------
57
Mathias Agopian33015422011-05-27 18:18:13 -070058/*
59 * Notes:
60 *
61 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070062 * - run mag sensor from time to time to force calibration
63 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
64 *
65 */
66
Aravind Akella8ef3c892015-07-10 11:24:28 -070067const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070068uint8_t SensorService::sHmacGlobalKey[128] = {};
69bool SensorService::sHmacGlobalKeyIsValid = false;
70
71#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
72#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070073#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070074
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070075// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070076static const String16 sDumpPermission("android.permission.DUMP");
77static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070078
Mathias Agopianfc328812010-07-14 23:41:37 -070079SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070080 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070081 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070082}
83
Greg Kaiser53ca2e02016-06-21 16:11:14 -070084bool SensorService::initializeHmacKey() {
85 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
86 if (fd != -1) {
87 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
88 close(fd);
89 if (result == sizeof(sHmacGlobalKey)) {
90 return true;
91 }
92 ALOGW("Unable to read HMAC key; generating new one.");
93 }
94
95 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
96 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
97 return false;
98 }
99
100 // We need to make sure this is only readable to us.
101 bool wroteKey = false;
102 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
103 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
104 S_IRUSR|S_IWUSR);
105 if (fd != -1) {
106 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
107 close(fd);
108 wroteKey = (result == sizeof(sHmacGlobalKey));
109 }
110 if (wroteKey) {
111 ALOGI("Generated new HMAC key.");
112 } else {
113 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
114 "after reboot.");
115 }
116 // Even if we failed to write the key we return true, because we did
117 // initialize the HMAC key.
118 return true;
119}
120
Peng Xu98d30f62016-08-01 18:12:11 -0700121// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
122void SensorService::enableSchedFifoMode() {
123 struct sched_param param = {0};
124 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
125 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
126 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
127 }
128}
129
Peng Xu47e96012016-03-28 17:55:56 -0700130void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000131 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800132 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700133
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700134 sHmacGlobalKeyIsValid = initializeHmacKey();
135
Mathias Agopianf001c922010-11-11 17:58:51 -0800136 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800137 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700138 ssize_t count = dev.getSensorList(&list);
139 if (count > 0) {
140 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700141 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700142 uint32_t virtualSensorsNeeds =
143 (1<<SENSOR_TYPE_GRAVITY) |
144 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700145 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
146 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
147 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700148
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700149 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700150 bool useThisSensor=true;
151
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700152 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700153 case SENSOR_TYPE_ACCELEROMETER:
154 hasAccel = true;
155 break;
156 case SENSOR_TYPE_MAGNETIC_FIELD:
157 hasMag = true;
158 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700159 case SENSOR_TYPE_ORIENTATION:
160 orientationIndex = i;
161 break;
162 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700163 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700164 hasGyro = true;
165 break;
166 case SENSOR_TYPE_GRAVITY:
167 case SENSOR_TYPE_LINEAR_ACCELERATION:
168 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700169 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
170 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
171 if (IGNORE_HARDWARE_FUSION) {
172 useThisSensor = false;
173 } else {
174 virtualSensorsNeeds &= ~(1<<list[i].type);
175 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700176 break;
177 }
Peng Xuf66684a2015-07-23 11:41:53 -0700178 if (useThisSensor) {
179 registerSensor( new HardwareSensor(list[i]) );
180 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700181 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700182
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700183 // it's safe to instantiate the SensorFusion object here
184 // (it wants to be instantiated after h/w sensors have been
185 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700186 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700187
Aravind Akellaf5047892015-07-20 17:29:33 -0700188 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700189 // Add Android virtual sensors if they're not already
190 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700191 bool needRotationVector =
192 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700193
Peng Xu0cc8f802016-04-05 23:46:03 -0700194 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
195 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700196
Peng Xu0cc8f802016-04-05 23:46:03 -0700197 bool needLinearAcceleration =
198 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700199
Peng Xu0cc8f802016-04-05 23:46:03 -0700200 registerSensor(new LinearAccelerationSensor(list, count),
201 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700202
Peng Xu0cc8f802016-04-05 23:46:03 -0700203 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700204 registerSensor( new CorrectedGyroSensor(list, count), true, true);
205 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700206 }
207
Peng Xuf66684a2015-07-23 11:41:53 -0700208 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700209 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
210 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700211
Peng Xu0cc8f802016-04-05 23:46:03 -0700212 bool needGameRotationVector =
213 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
214 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700215 }
216
217 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700218 bool needGeoMagRotationVector =
219 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
220 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700221 }
222
Aravind Akella5466c3d2014-08-22 16:11:10 -0700223 // Check if the device really supports batching by looking at the FIFO event
224 // counts for each sensor.
225 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700226 mSensors.forEachSensor(
227 [&batchingSupported] (const Sensor& s) -> bool {
228 if (s.getFifoMaxEventCount() > 0) {
229 batchingSupported = true;
230 }
231 return !batchingSupported;
232 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700233
234 if (batchingSupported) {
235 // Increase socket buffer size to a max of 100 KB for batching capabilities.
236 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
237 } else {
238 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
239 }
240
241 // Compare the socketBufferSize value against the system limits and limit
242 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700243 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
244 char line[128];
245 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
246 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700247 size_t maxSystemSocketBufferSize;
248 sscanf(line, "%zu", &maxSystemSocketBufferSize);
249 if (mSocketBufferSize > maxSystemSocketBufferSize) {
250 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700251 }
252 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700253 if (fp) {
254 fclose(fp);
255 }
256
Aravind Akella9a844cf2014-02-11 18:58:52 -0800257 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700258 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700259 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
260 mSensorEventBuffer = new sensors_event_t[minBufferSize];
261 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700262 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700263 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700264
Aravind Akella18d6d512015-06-18 14:18:28 -0700265 mNextSensorRegIndex = 0;
266 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
267 mLastNSensorRegistrations.push();
268 }
269
270 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700271 mAckReceiver = new SensorEventAckReceiver(this);
272 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700273 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700274
275 // priority can only be changed after run
276 enableSchedFifoMode();
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700277 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700278 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700279}
280
Peng Xu0cc8f802016-04-05 23:46:03 -0700281const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
282 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800283 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700284 if (mSensors.add(handle, s, isDebug, isVirtual)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800285 mRecentEvent.emplace(handle, new RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700286 return s->getSensor();
287 } else {
288 return mSensors.getNonSensor();
289 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800290}
291
Peng Xu6a2d3a02015-12-21 12:00:23 -0800292const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700293 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800294}
295
Peng Xu6a2d3a02015-12-21 12:00:23 -0800296bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700297 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800298
299 const auto i = mRecentEvent.find(handle);
300 if (i != mRecentEvent.end()) {
301 delete i->second;
302 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800303 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700304 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800305}
306
Peng Xu0cc8f802016-04-05 23:46:03 -0700307const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
308 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700309}
310
Peng Xu47e96012016-03-28 17:55:56 -0700311SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800312 for (auto && entry : mRecentEvent) {
313 delete entry.second;
314 }
Peng Xu47e96012016-03-28 17:55:56 -0700315}
316
317status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700318 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700319 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800320 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700321 IPCThreadState::self()->getCallingPid(),
322 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700323 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700324 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700325 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800326 return INVALID_OPERATION;
327 }
328 Mutex::Autolock _l(mLock);
329 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700330 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700331 // If already in restricted mode. Ignore.
332 if (mCurrentOperatingMode == RESTRICTED) {
333 return status_t(NO_ERROR);
334 }
335 // If in any mode other than normal, ignore.
336 if (mCurrentOperatingMode != NORMAL) {
337 return INVALID_OPERATION;
338 }
Peng Xue36e3472016-11-03 11:57:10 -0700339
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700340 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700341 // temporarily stop all sensor direct report
342 for (auto &i : mDirectConnections) {
343 sp<SensorDirectConnection> connection(i.promote());
344 if (connection != nullptr) {
345 connection->stopAll(true /* backupRecord */);
346 }
347 }
348
Aravind Akella4949c502015-02-11 15:54:35 -0800349 dev.disableAllSensors();
350 // Clear all pending flush connections for all active sensors. If one of the active
351 // connections has called flush() and the underlying sensor has been disabled before a
352 // flush complete event is returned, we need to remove the connection from this queue.
353 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
354 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
355 }
Aravind Akella841a5922015-06-29 12:37:48 -0700356 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700357 return status_t(NO_ERROR);
358 } else if (args.size() == 1 && args[0] == String16("enable")) {
359 // If currently in restricted mode, reset back to NORMAL mode else ignore.
360 if (mCurrentOperatingMode == RESTRICTED) {
361 mCurrentOperatingMode = NORMAL;
362 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700363 // recover all sensor direct report
364 for (auto &i : mDirectConnections) {
365 sp<SensorDirectConnection> connection(i.promote());
366 if (connection != nullptr) {
367 connection->recoverAll();
368 }
369 }
Aravind Akella444f2672015-05-07 12:40:52 -0700370 }
Aravind Akella841a5922015-06-29 12:37:48 -0700371 if (mCurrentOperatingMode == DATA_INJECTION) {
372 resetToNormalModeLocked();
373 }
374 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700375 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700376 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
377 if (mCurrentOperatingMode == NORMAL) {
378 dev.disableAllSensors();
379 status_t err = dev.setMode(DATA_INJECTION);
380 if (err == NO_ERROR) {
381 mCurrentOperatingMode = DATA_INJECTION;
382 } else {
383 // Re-enable sensors.
384 dev.enableAllSensors();
385 }
386 mWhiteListedPackage.setTo(String8(args[1]));
387 return NO_ERROR;
388 } else if (mCurrentOperatingMode == DATA_INJECTION) {
389 // Already in DATA_INJECTION mode. Treat this as a no_op.
390 return NO_ERROR;
391 } else {
392 // Transition to data injection mode supported only from NORMAL mode.
393 return INVALID_OPERATION;
394 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700395 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700396 result.append("No Sensors on the device\n");
Ashutosh Joshia5d566e2017-05-04 17:17:45 -0700397 result.append("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700398 } else {
399 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700400 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800401 result.append("Sensor Device:\n");
402 result.append(SensorDevice::getInstance().dump().c_str());
403
404 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700405 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700406
Peng Xu6a2d3a02015-12-21 12:00:23 -0800407 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700408 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700409
Peng Xu0cc8f802016-04-05 23:46:03 -0700410 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800411 for (auto&& i : mRecentEvent) {
412 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700413 if (!i.second->isEmpty()) {
414 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
415 i.second->setFormat("normal");
416 } else {
417 i.second->setFormat("mask_data");
418 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800419 // if there is events and sensor does not need special permission.
420 result.appendFormat("%s: ", s->getSensor().getName().string());
421 result.append(i.second->dump().c_str());
422 }
423 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700424
Aravind Akella444f2672015-05-07 12:40:52 -0700425 result.append("Active sensors:\n");
426 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
427 int handle = mActiveSensors.keyAt(i);
428 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
429 getSensorName(handle).string(),
430 handle,
431 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700432 }
433
Andreas Gamped4036b62015-07-28 13:49:04 -0700434 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700435 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700436 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
437 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700438 result.appendFormat("Mode :");
439 switch(mCurrentOperatingMode) {
440 case NORMAL:
441 result.appendFormat(" NORMAL\n");
442 break;
443 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700444 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700445 break;
446 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700447 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700448 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700449
Peng Xue36e3472016-11-03 11:57:10 -0700450 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700451 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
452 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
453 if (connection != 0) {
454 result.appendFormat("Connection Number: %zu \n", i);
455 connection->dump(result);
456 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700457 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700458
Peng Xue36e3472016-11-03 11:57:10 -0700459 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
460 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
461 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
462 if (connection != nullptr) {
463 result.appendFormat("Direct connection %zu:\n", i);
464 connection->dump(result);
465 }
466 }
467
Aravind Akella18d6d512015-06-18 14:18:28 -0700468 result.appendFormat("Previous Registrations:\n");
469 // Log in the reverse chronological order.
470 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
471 SENSOR_REGISTRATIONS_BUF_SIZE;
472 const int startIndex = currentIndex;
473 do {
474 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
475 if (SensorRegistrationInfo::isSentinel(reg_info)) {
476 // Ignore sentinel, proceed to next item.
477 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
478 SENSOR_REGISTRATIONS_BUF_SIZE;
479 continue;
480 }
Peng Xu51224682017-03-10 16:57:27 -0800481 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700482 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
483 SENSOR_REGISTRATIONS_BUF_SIZE;
484 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700485 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700486 }
487 write(fd, result.string(), result.size());
488 return NO_ERROR;
489}
490
Peng Xu0cc8f802016-04-05 23:46:03 -0700491//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800492void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700493 sensors_event_t const* buffer, const int count) {
494 for (int i=0 ; i<count ; i++) {
495 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700496 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
497 handle = buffer[i].meta_data.sensor;
498 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700499 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700500 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700501 // If this buffer has an event from a one_shot sensor and this connection is registered
502 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700503 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700504 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
505 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800506 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700507 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700508
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700509 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700510 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700511}
512
Peng Xu47e96012016-03-28 17:55:56 -0700513bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000514 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700515
Peng Xueb4d6282015-12-10 18:02:41 -0800516 // each virtual sensor could generate an event per "real" event, that's why we need to size
517 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
518 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700519 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700520 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700521 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700522
Mathias Agopianf001c922010-11-11 17:58:51 -0800523 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700524
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700525 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700526 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700527 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
528 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000529 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700530 break;
531 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700532
533 // Reset sensors_event_t.flags to zero for all events in the buffer.
534 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700535 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700536 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700537
Peng Xueb4d6282015-12-10 18:02:41 -0800538 // Make a copy of the connection vector as some connections may be removed during the course
539 // of this loop (especially when one-shot sensor events are present in the sensor_event
540 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
541 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
542 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
543 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700544 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700545 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800546
Aravind Akella9a844cf2014-02-11 18:58:52 -0800547 Mutex::Autolock _l(mLock);
548 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
549 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
550 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
551 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
552 // releasing the wakelock.
553 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700554 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700555 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800556 bufferHasWakeUpEvent = true;
557 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700558 }
559 }
560
Aravind Akella9a844cf2014-02-11 18:58:52 -0800561 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700562 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800563 }
Aravind Akella8493b792014-09-08 15:45:47 -0700564 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800565
Mathias Agopianf001c922010-11-11 17:58:51 -0800566 // handle virtual sensors
567 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700568 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700569 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800570 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700571 SensorFusion& fusion(SensorFusion::getInstance());
572 if (fusion.isEnabled()) {
573 for (size_t i=0 ; i<size_t(count) ; i++) {
574 fusion.process(event[i]);
575 }
576 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700577 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700578 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700579 if (count + k >= minBufferSize) {
580 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700581 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700582 count, k, minBufferSize);
583 break;
584 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800585 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700586 sp<SensorInterface> si = mSensors.getInterface(handle);
587 if (si == nullptr) {
588 ALOGE("handle %d is not an valid virtual sensor", handle);
589 continue;
590 }
591
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700592 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700593 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800594 k++;
595 }
596 }
597 }
598 if (k) {
599 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700600 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800601 count += k;
602 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700603 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700604 }
605 }
606 }
607
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700608 // handle backward compatibility for RotationVector sensor
609 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
610 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700611 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700612 // All the 4 components of the quaternion should be available
613 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700614 mSensorEventBuffer[i].data[4] = -1;
615 }
616 }
617 }
618
Aravind Akella8493b792014-09-08 15:45:47 -0700619 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700620 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
621 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
622 // SensorEventConnection mapped to the corresponding flush_complete_event in
623 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700624 mMapFlushEventsToConnections[i] = NULL;
625 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
626 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
627 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
628 if (rec != NULL) {
629 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
630 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700631 }
632 }
Peng Xu2576cb62016-01-20 00:22:09 -0800633
634 // handle dynamic sensor meta events, process registration and unregistration of dynamic
635 // sensor based on content of event.
636 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
637 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
638 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
639 const sensor_t& dynamicSensor =
640 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
641 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
642 handle, dynamicSensor.type, dynamicSensor.name);
643
Peng Xu0cc8f802016-04-05 23:46:03 -0700644 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800645 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700646 sensor_t s = dynamicSensor;
647 // make sure the dynamic sensor flag is set
648 s.flags |= DYNAMIC_SENSOR_MASK;
649 // force the handle to be consistent
650 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800651
652 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800653
Peng Xu0cc8f802016-04-05 23:46:03 -0700654 // This will release hold on dynamic sensor meta, so it should be called
655 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700656 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800657 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700658 } else {
659 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
660 }
Peng Xu2576cb62016-01-20 00:22:09 -0800661 } else {
662 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
663 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
664
665 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800666 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800667 ALOGE("Dynamic sensor release error.");
668 }
669
670 size_t numConnections = activeConnections.size();
671 for (size_t i=0 ; i < numConnections; ++i) {
672 if (activeConnections[i] != NULL) {
673 activeConnections[i]->removeSensor(handle);
674 }
675 }
676 }
677 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700678 }
679
Peng Xu2576cb62016-01-20 00:22:09 -0800680
Aravind Akella9a844cf2014-02-11 18:58:52 -0800681 // Send our events to clients. Check the state of wake lock for each client and release the
682 // lock if none of the clients need it.
683 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700684 size_t numConnections = activeConnections.size();
685 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700686 if (activeConnections[i] != 0) {
687 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700688 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700689 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700690 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
691 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700692 if (activeConnections[i]->hasOneShotSensors()) {
693 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
694 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700695 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800696 }
697 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700698
Aravind Akella9a844cf2014-02-11 18:58:52 -0800699 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700700 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800701 }
Aravind Akella8493b792014-09-08 15:45:47 -0700702 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700703
Steve Block3c20fbe2012-01-05 23:22:43 +0000704 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800705 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700706 return false;
707}
708
Aravind Akella56ae4262014-07-10 16:01:10 -0700709sp<Looper> SensorService::getLooper() const {
710 return mLooper;
711}
712
Aravind Akellab4373ac2014-10-29 17:55:20 -0700713void SensorService::resetAllWakeLockRefCounts() {
714 SortedVector< sp<SensorEventConnection> > activeConnections;
715 populateActiveConnections(&activeConnections);
716 {
717 Mutex::Autolock _l(mLock);
718 for (size_t i=0 ; i < activeConnections.size(); ++i) {
719 if (activeConnections[i] != 0) {
720 activeConnections[i]->resetWakeLockRefCount();
721 }
722 }
723 setWakeLockAcquiredLocked(false);
724 }
725}
726
727void SensorService::setWakeLockAcquiredLocked(bool acquire) {
728 if (acquire) {
729 if (!mWakeLockAcquired) {
730 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
731 mWakeLockAcquired = true;
732 }
733 mLooper->wake();
734 } else {
735 if (mWakeLockAcquired) {
736 release_wake_lock(WAKE_LOCK_NAME);
737 mWakeLockAcquired = false;
738 }
739 }
740}
741
Aravind Akellab4373ac2014-10-29 17:55:20 -0700742bool SensorService::isWakeLockAcquired() {
743 Mutex::Autolock _l(mLock);
744 return mWakeLockAcquired;
745}
746
Aravind Akella56ae4262014-07-10 16:01:10 -0700747bool SensorService::SensorEventAckReceiver::threadLoop() {
748 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700749 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700750 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700751 bool wakeLockAcquired = mService->isWakeLockAcquired();
752 int timeout = -1;
753 if (wakeLockAcquired) timeout = 5000;
754 int ret = looper->pollOnce(timeout);
755 if (ret == ALOOPER_POLL_TIMEOUT) {
756 mService->resetAllWakeLockRefCounts();
757 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700758 } while(!Thread::exitPending());
759 return false;
760}
761
Aravind Akella9a844cf2014-02-11 18:58:52 -0800762void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800763 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800764 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800765 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
766 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800767 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800768 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800769 }
Peng Xu2576cb62016-01-20 00:22:09 -0800770
Peng Xu6a2d3a02015-12-21 12:00:23 -0800771 auto logger = mRecentEvent.find(buffer[i].sensor);
772 if (logger != mRecentEvent.end()) {
773 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800774 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800775 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800776}
777
Peng Xu47e96012016-03-28 17:55:56 -0700778void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800779 struct compar {
780 static int cmp(void const* lhs, void const* rhs) {
781 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
782 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700783 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800784 }
785 };
786 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
787}
788
Mathias Agopian5d270722010-07-19 15:20:39 -0700789String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700790 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700791}
792
Aravind Akellab4099e72013-10-15 15:43:10 -0700793bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700794 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
795 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700796}
797
Aravind Akella9a844cf2014-02-11 18:58:52 -0800798bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700799 int handle = event.sensor;
800 if (event.type == SENSOR_TYPE_META_DATA) {
801 handle = event.meta_data.sensor;
802 }
Peng Xu755c4512016-04-07 23:15:14 -0700803 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
804 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800805}
806
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700807int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
808 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
809 // UUID is not supported for this device.
810 return 0;
811 }
812 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
813 // This sensor can be uniquely identified in the system by
814 // the combination of its type and name.
815 return -1;
816 }
817
818 // We have a dynamic sensor.
819
820 if (!sHmacGlobalKeyIsValid) {
821 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
822 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
823 return 0;
824 }
825
826 // We want each app author/publisher to get a different ID, so that the
827 // same dynamic sensor cannot be tracked across apps by multiple
828 // authors/publishers. So we use both our UUID and our User ID.
829 // Note potential confusion:
830 // UUID => Universally Unique Identifier.
831 // UID => User Identifier.
832 // We refrain from using "uid" except as needed by API to try to
833 // keep this distinction clear.
834
835 auto appUserId = IPCThreadState::self()->getCallingUid();
836 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
837 memcpy(uuidAndApp, &uuid, sizeof(uuid));
838 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
839
840 // Now we use our key on our UUID/app combo to get the hash.
841 uint8_t hash[EVP_MAX_MD_SIZE];
842 unsigned int hashLen;
843 if (HMAC(EVP_sha256(),
844 sHmacGlobalKey, sizeof(sHmacGlobalKey),
845 uuidAndApp, sizeof(uuidAndApp),
846 hash, &hashLen) == nullptr) {
847 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
848 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
849 return 0;
850 }
851
852 int32_t id = 0;
853 if (hashLen < sizeof(id)) {
854 // We never expect this case, but out of paranoia, we handle it.
855 // Our 'id' length is already quite small, we don't want the
856 // effective length of it to be even smaller.
857 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
858 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
859 return 0;
860 }
861
862 // This is almost certainly less than all of 'hash', but it's as secure
863 // as we can be with our current 'id' length.
864 memcpy(&id, hash, sizeof(id));
865
866 // Note at the beginning of the function that we return the values of
867 // 0 and -1 to represent special cases. As a result, we can't return
868 // those as dynamic sensor IDs. If we happened to hash to one of those
869 // values, we change 'id' so we report as a dynamic sensor, and not as
870 // one of those special cases.
871 if (id == -1) {
872 id = -2;
873 } else if (id == 0) {
874 id = 1;
875 }
876 return id;
877}
878
879void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
880 for (auto &sensor : sensorList) {
881 int32_t id = getIdFromUuid(sensor.getUuid());
882 sensor.setId(id);
883 }
884}
885
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800886Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700887 char value[PROPERTY_VALUE_MAX];
888 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000889 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700890 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000891 Vector<Sensor> accessibleSensorList;
892 for (size_t i = 0; i < initialSensorList.size(); i++) {
893 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800894 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700895 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700896 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000897 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700898}
899
Peng Xu47e96012016-03-28 17:55:56 -0700900Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800901 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700902 mSensors.forEachSensor(
903 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -0700904 if (sensor.isDynamicSensor()) {
905 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
906 accessibleSensorList.add(sensor);
907 } else {
908 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
909 sensor.getName().string(),
910 sensor.getRequiredPermission().string(),
911 sensor.getRequiredAppOp());
912 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700913 }
914 return true;
915 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700916 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -0800917 return accessibleSensorList;
918}
919
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700920sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700921 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700922 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
923 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
924 return NULL;
925 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700926
927 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700928 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
929 // operating in DI mode.
930 if (requestedMode == DATA_INJECTION) {
931 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
932 if (!isWhiteListedPackage(packageName)) return NULL;
933 }
934
Mathias Agopian5307d172012-09-18 17:02:43 -0700935 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700936 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700937 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700938 if (requestedMode == DATA_INJECTION) {
939 if (mActiveConnections.indexOf(result) < 0) {
940 mActiveConnections.add(result);
941 }
942 // Add the associated file descriptor to the Looper for polling whenever there is data to
943 // be injected.
944 result->updateLooperRegistration(mLooper);
945 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700946 return result;
947}
948
Aravind Akella841a5922015-06-29 12:37:48 -0700949int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700950 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700951 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700952}
953
Peng Xue36e3472016-11-03 11:57:10 -0700954sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
955 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
956 const native_handle *resource) {
957 Mutex::Autolock _l(mLock);
958
959 struct sensors_direct_mem_t mem = {
960 .type = type,
961 .format = format,
962 .size = size,
963 .handle = resource,
964 };
965 uid_t uid = IPCThreadState::self()->getCallingUid();
966
967 if (mem.handle == nullptr) {
968 ALOGE("Failed to clone resource handle");
969 return nullptr;
970 }
971
972 // check format
973 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
974 ALOGE("Direct channel format %d is unsupported!", format);
975 return nullptr;
976 }
977
978 // check for duplication
979 for (auto &i : mDirectConnections) {
980 sp<SensorDirectConnection> connection(i.promote());
981 if (connection != nullptr && connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -0700982 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -0700983 return nullptr;
984 }
985 }
986
987 // check specific to memory type
988 switch(type) {
989 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
990 int fd = resource->data[0];
991 int size2 = ashmem_get_size_region(fd);
992 // check size consistency
Peng Xuf88e2b92017-04-10 15:52:58 -0700993 if (size2 < static_cast<int>(size)) {
994 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
995 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -0700996 return nullptr;
997 }
998 break;
999 }
1000 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001001 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001002 break;
1003 default:
1004 ALOGE("Unknown direct connection memory type %d", type);
1005 return nullptr;
1006 }
1007
1008 native_handle_t *clone = native_handle_clone(resource);
1009 if (!clone) {
1010 return nullptr;
1011 }
1012
1013 SensorDirectConnection* conn = nullptr;
1014 SensorDevice& dev(SensorDevice::getInstance());
1015 int channelHandle = dev.registerDirectChannel(&mem);
1016
1017 if (channelHandle <= 0) {
1018 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1019 } else {
1020 mem.handle = clone;
1021 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1022 }
1023
1024 if (conn == nullptr) {
1025 native_handle_close(clone);
1026 native_handle_delete(clone);
1027 } else {
1028 // add to list of direct connections
1029 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1030 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1031 }
1032 return conn;
1033}
1034
Peng Xudd5c5cb2017-03-16 17:39:43 -07001035int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001036 int32_t handle, int32_t type,
1037 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001038 Mutex::Autolock _l(mLock);
1039
Alexey Polyudov88711e82017-05-23 19:54:04 -07001040 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001041 return PERMISSION_DENIED;
1042 }
1043
1044 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001045 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001046 size_t expectSize = INT32_MAX;
1047 switch (type) {
1048 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1049 isFloat = true;
1050 expectSize = 3;
1051 break;
1052 case AINFO_LOCAL_GRAVITY:
1053 isFloat = true;
1054 expectSize = 1;
1055 break;
1056 case AINFO_DOCK_STATE:
1057 case AINFO_HIGH_PERFORMANCE_MODE:
1058 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1059 isFloat = false;
1060 expectSize = 1;
1061 break;
1062 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001063 // CUSTOM events must only contain float data; it may have variable size
1064 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1065 ints.size() ||
1066 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1067 handle < 0) {
1068 return BAD_VALUE;
1069 }
1070 isFloat = true;
1071 isCustom = true;
1072 expectSize = floats.size();
1073 break;
1074 }
1075
1076 if (!isCustom && handle != -1) {
1077 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001078 }
1079
1080 // three events: first one is begin tag, last one is end tag, the one in the middle
1081 // is the payload.
1082 sensors_event_t event[3];
1083 int64_t timestamp = elapsedRealtimeNano();
1084 for (sensors_event_t* i = event; i < event + 3; i++) {
1085 *i = (sensors_event_t) {
1086 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001087 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001088 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1089 .timestamp = timestamp++,
1090 .additional_info = (additional_info_event_t) {
1091 .serial = 0
1092 }
1093 };
1094 }
1095
1096 event[0].additional_info.type = AINFO_BEGIN;
1097 event[1].additional_info.type = type;
1098 event[2].additional_info.type = AINFO_END;
1099
1100 if (isFloat) {
1101 if (floats.size() != expectSize) {
1102 return BAD_VALUE;
1103 }
1104 for (size_t i = 0; i < expectSize; ++i) {
1105 event[1].additional_info.data_float[i] = floats[i];
1106 }
1107 } else {
1108 if (ints.size() != expectSize) {
1109 return BAD_VALUE;
1110 }
1111 for (size_t i = 0; i < expectSize; ++i) {
1112 event[1].additional_info.data_int32[i] = ints[i];
1113 }
1114 }
1115
1116 SensorDevice& dev(SensorDevice::getInstance());
1117 for (sensors_event_t* i = event; i < event + 3; i++) {
1118 int ret = dev.injectSensorData(i);
1119 if (ret != NO_ERROR) {
1120 return ret;
1121 }
1122 }
1123 return NO_ERROR;
1124}
1125
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001126status_t SensorService::resetToNormalMode() {
1127 Mutex::Autolock _l(mLock);
1128 return resetToNormalModeLocked();
1129}
1130
1131status_t SensorService::resetToNormalModeLocked() {
1132 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001133 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301134 if (err == NO_ERROR) {
1135 mCurrentOperatingMode = NORMAL;
1136 dev.enableAllSensors();
1137 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001138 return err;
1139}
1140
Peng Xu47e96012016-03-28 17:55:56 -07001141void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001142 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001143 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001144 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001145 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001146 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001147 int handle = mActiveSensors.keyAt(i);
1148 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001149 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001150 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1151 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001152 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001153 } else {
1154 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001155 }
Aravind Akella8a969552014-09-28 17:52:41 -07001156 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001157 }
1158 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001159 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001160 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001161 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001162 c, i, handle);
1163
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001164 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001165 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001166 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001167 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001168 delete rec;
1169 size--;
1170 } else {
1171 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001172 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001173 }
Aravind Akella8a969552014-09-28 17:52:41 -07001174 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001175 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001176 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001177 if (c->needsWakeLock()) {
1178 checkWakeLockStateLocked();
1179 }
Peng Xu4f707f82016-09-26 11:28:32 -07001180
1181 SensorDevice& dev(SensorDevice::getInstance());
1182 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001183}
1184
Peng Xue36e3472016-11-03 11:57:10 -07001185void SensorService::cleanupConnection(SensorDirectConnection* c) {
1186 Mutex::Autolock _l(mLock);
1187
1188 SensorDevice& dev(SensorDevice::getInstance());
1189 dev.unregisterDirectChannel(c->getHalChannelHandle());
1190 mDirectConnections.remove(c);
1191}
1192
Peng Xu755c4512016-04-07 23:15:14 -07001193sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001194 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001195}
1196
Mathias Agopianfc328812010-07-14 23:41:37 -07001197status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001198 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001199 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001200 if (mInitCheck != NO_ERROR)
1201 return mInitCheck;
1202
Peng Xu755c4512016-04-07 23:15:14 -07001203 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1204 if (sensor == nullptr ||
1205 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001206 return BAD_VALUE;
1207 }
1208
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001209 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001210 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001211 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001212 return INVALID_OPERATION;
1213 }
1214
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001215 SensorRecord* rec = mActiveSensors.valueFor(handle);
1216 if (rec == 0) {
1217 rec = new SensorRecord(connection);
1218 mActiveSensors.add(handle, rec);
1219 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001220 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001221 }
1222 } else {
1223 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001224 // this sensor is already activated, but we are adding a connection that uses it.
1225 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001226 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001227 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001228 // NOTE: The wake_up flag of this event may get set to
1229 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001230
1231 auto logger = mRecentEvent.find(handle);
1232 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001233 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001234 // It is unlikely that this buffer is empty as the sensor is already active.
1235 // One possible corner case may be two applications activating an on-change
1236 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001237 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001238 event.sensor = handle;
1239 if (event.version == sizeof(sensors_event_t)) {
1240 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1241 setWakeLockAcquiredLocked(true);
1242 }
1243 connection->sendEvents(&event, 1, NULL);
1244 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1245 checkWakeLockStateLocked();
1246 }
1247 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001248 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001249 }
1250 }
1251 }
1252 }
1253
1254 if (connection->addSensor(handle)) {
1255 BatteryService::enableSensor(connection->getUid(), handle);
1256 // the sensor was added (which means it wasn't already there)
1257 // so, see if this connection becomes active
1258 if (mActiveConnections.indexOf(connection) < 0) {
1259 mActiveConnections.add(connection);
1260 }
1261 } else {
1262 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1263 handle, connection.get());
1264 }
1265
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301266 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001267 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301268 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1269 samplingPeriodNs = maxDelayNs;
1270 }
1271
Aravind Akella724d91d2013-06-27 12:04:23 -07001272 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1273 if (samplingPeriodNs < minDelayNs) {
1274 samplingPeriodNs = minDelayNs;
1275 }
1276
Aravind Akella6c2664a2014-08-13 12:24:50 -07001277 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1278 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001279 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1280
Aravind Akella4949c502015-02-11 15:54:35 -08001281 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001282 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001283
Peng Xu20483c42015-10-26 15:14:43 -07001284 // Call flush() before calling activate() on the sensor. Wait for a first
1285 // flush complete event before sending events on this connection. Ignore
1286 // one-shot sensors which don't support flush(). Ignore on-change sensors
1287 // to maintain the on-change logic (any on-change events except the initial
1288 // one should be trigger by a change in value). Also if this sensor isn't
1289 // already active, don't call flush().
1290 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001291 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001292 rec->getNumConnections() > 1) {
1293 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001294 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001295 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001296 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001297 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001298 } else {
1299 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001300 }
1301 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001302
1303 if (err == NO_ERROR) {
1304 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1305 err = sensor->activate(connection.get(), true);
1306 }
1307
Aravind Akella8a969552014-09-28 17:52:41 -07001308 if (err == NO_ERROR) {
1309 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001310
1311 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1312 SensorRegistrationInfo(handle, connection->getPackageName(),
1313 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001314 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001315 }
1316
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001317 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001318 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001319 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001320 }
1321 return err;
1322}
1323
Peng Xu47e96012016-03-28 17:55:56 -07001324status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001325 if (mInitCheck != NO_ERROR)
1326 return mInitCheck;
1327
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001328 Mutex::Autolock _l(mLock);
1329 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001330 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001331 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1332 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001333
1334 }
1335 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001336 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1337 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001338 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001339 }
1340 return err;
1341}
1342
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001343status_t SensorService::cleanupWithoutDisable(
1344 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001345 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001346 return cleanupWithoutDisableLocked(connection, handle);
1347}
1348
1349status_t SensorService::cleanupWithoutDisableLocked(
1350 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001351 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001352 if (rec) {
1353 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001354 if (connection->removeSensor(handle)) {
1355 BatteryService::disableSensor(connection->getUid(), handle);
1356 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001357 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001358 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001359 mActiveConnections.remove(connection);
1360 }
1361 // see if this sensor becomes inactive
1362 if (rec->removeConnection(connection)) {
1363 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001364 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001365 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001366 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001367 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001368 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001369 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001370}
1371
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001372status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001373 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001374 if (mInitCheck != NO_ERROR)
1375 return mInitCheck;
1376
Peng Xu755c4512016-04-07 23:15:14 -07001377 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1378 if (sensor == nullptr ||
1379 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001380 return BAD_VALUE;
1381 }
1382
Mathias Agopian1cd70002010-07-21 15:59:50 -07001383 if (ns < 0)
1384 return BAD_VALUE;
1385
Mathias Agopian62569ec2011-11-07 21:21:47 -08001386 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1387 if (ns < minDelayNs) {
1388 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001389 }
1390
Mathias Agopianf001c922010-11-11 17:58:51 -08001391 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001392}
1393
Svetoslavb412f6e2015-04-29 16:50:41 -07001394status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1395 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001396 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001397 SensorDevice& dev(SensorDevice::getInstance());
1398 const int halVersion = dev.getHalDeviceVersion();
1399 status_t err(NO_ERROR);
1400 Mutex::Autolock _l(mLock);
1401 // Loop through all sensors for this connection and call flush on each of them.
1402 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1403 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001404 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1405 if (sensor == nullptr) {
1406 continue;
1407 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001408 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1409 ALOGE("flush called on a one-shot sensor");
1410 err = INVALID_OPERATION;
1411 continue;
1412 }
Aravind Akella8493b792014-09-08 15:45:47 -07001413 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001414 // For older devices just increment pending flush count which will send a trivial
1415 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001416 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001417 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001418 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1419 err = INVALID_OPERATION;
1420 continue;
1421 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001422 status_t err_flush = sensor->flush(connection.get(), handle);
1423 if (err_flush == NO_ERROR) {
1424 SensorRecord* rec = mActiveSensors.valueFor(handle);
1425 if (rec != NULL) rec->addPendingFlushConnection(connection);
1426 }
1427 err = (err_flush != NO_ERROR) ? err_flush : err;
1428 }
Aravind Akella70018042014-04-07 22:52:37 +00001429 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001430 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001431}
Aravind Akella70018042014-04-07 22:52:37 +00001432
Svetoslavb412f6e2015-04-29 16:50:41 -07001433bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1434 const String16& opPackageName) {
1435 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001436
Svetoslavb412f6e2015-04-29 16:50:41 -07001437 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001438 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001439 }
1440
1441 bool hasPermission = false;
1442
1443 // Runtime permissions can't use the cache as they may change.
1444 if (sensor.isRequiredPermissionRuntime()) {
1445 hasPermission = checkPermission(String16(requiredPermission),
1446 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001447 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001448 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1449 }
1450
1451 if (!hasPermission) {
1452 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1453 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001454 return false;
1455 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001456
1457 const int32_t opCode = sensor.getRequiredAppOp();
1458 if (opCode >= 0) {
1459 AppOpsManager appOps;
1460 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1461 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001462 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001463 operation, sensor.getName().string(), opCode);
1464 return false;
1465 }
1466 }
1467
1468 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001469}
1470
Aravind Akella9a844cf2014-02-11 18:58:52 -08001471void SensorService::checkWakeLockState() {
1472 Mutex::Autolock _l(mLock);
1473 checkWakeLockStateLocked();
1474}
1475
1476void SensorService::checkWakeLockStateLocked() {
1477 if (!mWakeLockAcquired) {
1478 return;
1479 }
1480 bool releaseLock = true;
1481 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1482 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1483 if (connection != 0) {
1484 if (connection->needsWakeLock()) {
1485 releaseLock = false;
1486 break;
1487 }
1488 }
1489 }
1490 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001491 setWakeLockAcquiredLocked(false);
1492 }
1493}
1494
1495void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1496 Mutex::Autolock _l(mLock);
1497 connection->writeToSocketFromCache();
1498 if (connection->needsWakeLock()) {
1499 setWakeLockAcquiredLocked(true);
1500 }
1501}
1502
1503void SensorService::populateActiveConnections(
1504 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1505 Mutex::Autolock _l(mLock);
1506 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1507 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1508 if (connection != 0) {
1509 activeConnections->add(connection);
1510 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001511 }
1512}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001513
Aravind Akella4949c502015-02-11 15:54:35 -08001514bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001515 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001516}
1517
Peng Xue36e3472016-11-03 11:57:10 -07001518bool SensorService::isOperationRestricted(const String16& opPackageName) {
1519 Mutex::Autolock _l(mLock);
1520 if (mCurrentOperatingMode != RESTRICTED) {
1521 String8 package(opPackageName);
1522 return !isWhiteListedPackage(package);
1523 }
1524 return false;
1525}
1526
Mathias Agopianfc328812010-07-14 23:41:37 -07001527}; // namespace android