blob: 8fc49214d035f75fc0c8223ad0b722023ccc0ade [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mathias Agopian33015422011-05-27 18:18:13 -070017#include <cutils/properties.h>
18
Svetoslavb412f6e2015-04-29 16:50:41 -070019#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070023
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080025#include <sensor/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070026
27#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070028#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070029
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030#include <openssl/digest.h>
31#include <openssl/hmac.h>
32#include <openssl/rand.h>
33
Mathias Agopian787ac1b2012-09-18 18:49:18 -070034#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080036#include "GravitySensor.h"
37#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070040#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070041#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080042
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070044#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080046#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080047#include "SensorRecord.h"
48#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080049
50#include <inttypes.h>
51#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070052#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080053#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070055#include <sys/stat.h>
56#include <sys/types.h>
57#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070058
59namespace android {
60// ---------------------------------------------------------------------------
61
Mathias Agopian33015422011-05-27 18:18:13 -070062/*
63 * Notes:
64 *
65 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070066 * - run mag sensor from time to time to force calibration
67 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
68 *
69 */
70
Aravind Akella8ef3c892015-07-10 11:24:28 -070071const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070072uint8_t SensorService::sHmacGlobalKey[128] = {};
73bool SensorService::sHmacGlobalKeyIsValid = false;
74
75#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
76#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070077#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070078
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070079// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070080static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070081
Mathias Agopianfc328812010-07-14 23:41:37 -070082SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070083 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070084 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070085}
86
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087bool SensorService::initializeHmacKey() {
88 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
89 if (fd != -1) {
90 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
91 close(fd);
92 if (result == sizeof(sHmacGlobalKey)) {
93 return true;
94 }
95 ALOGW("Unable to read HMAC key; generating new one.");
96 }
97
98 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
99 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
100 return false;
101 }
102
103 // We need to make sure this is only readable to us.
104 bool wroteKey = false;
105 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
106 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
107 S_IRUSR|S_IWUSR);
108 if (fd != -1) {
109 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
110 close(fd);
111 wroteKey = (result == sizeof(sHmacGlobalKey));
112 }
113 if (wroteKey) {
114 ALOGI("Generated new HMAC key.");
115 } else {
116 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
117 "after reboot.");
118 }
119 // Even if we failed to write the key we return true, because we did
120 // initialize the HMAC key.
121 return true;
122}
123
Peng Xu98d30f62016-08-01 18:12:11 -0700124// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
125void SensorService::enableSchedFifoMode() {
126 struct sched_param param = {0};
127 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
128 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
129 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
130 }
131}
132
Peng Xu47e96012016-03-28 17:55:56 -0700133void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000134 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800135 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700136
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700137 sHmacGlobalKeyIsValid = initializeHmacKey();
138
Mathias Agopianf001c922010-11-11 17:58:51 -0800139 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800140 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700141 ssize_t count = dev.getSensorList(&list);
142 if (count > 0) {
143 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700144 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700145 uint32_t virtualSensorsNeeds =
146 (1<<SENSOR_TYPE_GRAVITY) |
147 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700148 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
149 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
150 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700151
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700152 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700153 bool useThisSensor=true;
154
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700155 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700156 case SENSOR_TYPE_ACCELEROMETER:
157 hasAccel = true;
158 break;
159 case SENSOR_TYPE_MAGNETIC_FIELD:
160 hasMag = true;
161 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700162 case SENSOR_TYPE_ORIENTATION:
163 orientationIndex = i;
164 break;
165 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700166 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700167 hasGyro = true;
168 break;
169 case SENSOR_TYPE_GRAVITY:
170 case SENSOR_TYPE_LINEAR_ACCELERATION:
171 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700172 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
173 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
174 if (IGNORE_HARDWARE_FUSION) {
175 useThisSensor = false;
176 } else {
177 virtualSensorsNeeds &= ~(1<<list[i].type);
178 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700179 break;
180 }
Peng Xuf66684a2015-07-23 11:41:53 -0700181 if (useThisSensor) {
182 registerSensor( new HardwareSensor(list[i]) );
183 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700184 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700185
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700186 // it's safe to instantiate the SensorFusion object here
187 // (it wants to be instantiated after h/w sensors have been
188 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700189 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700190
Aravind Akellaf5047892015-07-20 17:29:33 -0700191 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700192 // Add Android virtual sensors if they're not already
193 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700194 bool needRotationVector =
195 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700196
Peng Xu0cc8f802016-04-05 23:46:03 -0700197 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
198 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700199
Peng Xu0cc8f802016-04-05 23:46:03 -0700200 bool needLinearAcceleration =
201 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700202
Peng Xu0cc8f802016-04-05 23:46:03 -0700203 registerSensor(new LinearAccelerationSensor(list, count),
204 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700205
Peng Xu0cc8f802016-04-05 23:46:03 -0700206 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700207 registerSensor( new CorrectedGyroSensor(list, count), true, true);
208 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700209 }
210
Peng Xuf66684a2015-07-23 11:41:53 -0700211 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700212 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
213 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700214
Peng Xu0cc8f802016-04-05 23:46:03 -0700215 bool needGameRotationVector =
216 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
217 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700218 }
219
220 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700221 bool needGeoMagRotationVector =
222 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
223 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700224 }
225
Aravind Akella5466c3d2014-08-22 16:11:10 -0700226 // Check if the device really supports batching by looking at the FIFO event
227 // counts for each sensor.
228 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700229 mSensors.forEachSensor(
230 [&batchingSupported] (const Sensor& s) -> bool {
231 if (s.getFifoMaxEventCount() > 0) {
232 batchingSupported = true;
233 }
234 return !batchingSupported;
235 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700236
237 if (batchingSupported) {
238 // Increase socket buffer size to a max of 100 KB for batching capabilities.
239 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
240 } else {
241 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
242 }
243
244 // Compare the socketBufferSize value against the system limits and limit
245 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700246 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
247 char line[128];
248 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
249 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700250 size_t maxSystemSocketBufferSize;
251 sscanf(line, "%zu", &maxSystemSocketBufferSize);
252 if (mSocketBufferSize > maxSystemSocketBufferSize) {
253 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700254 }
255 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700256 if (fp) {
257 fclose(fp);
258 }
259
Aravind Akella9a844cf2014-02-11 18:58:52 -0800260 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700261 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700262 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
263 mSensorEventBuffer = new sensors_event_t[minBufferSize];
264 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700265 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700266 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700267
Aravind Akella18d6d512015-06-18 14:18:28 -0700268 mNextSensorRegIndex = 0;
269 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
270 mLastNSensorRegistrations.push();
271 }
272
273 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700274 mAckReceiver = new SensorEventAckReceiver(this);
275 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700276 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700277
278 // priority can only be changed after run
279 enableSchedFifoMode();
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700280 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700281 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700282}
283
Peng Xu0cc8f802016-04-05 23:46:03 -0700284const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
285 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800286 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700287 if (mSensors.add(handle, s, isDebug, isVirtual)){
Peng Xu6a2d3a02015-12-21 12:00:23 -0800288 mRecentEvent.emplace(handle, new RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700289 return s->getSensor();
290 } else {
291 return mSensors.getNonSensor();
292 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800293}
294
Peng Xu6a2d3a02015-12-21 12:00:23 -0800295const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700296 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800297}
298
Peng Xu6a2d3a02015-12-21 12:00:23 -0800299bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700300 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800301
302 const auto i = mRecentEvent.find(handle);
303 if (i != mRecentEvent.end()) {
304 delete i->second;
305 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800306 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700307 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800308}
309
Peng Xu0cc8f802016-04-05 23:46:03 -0700310const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
311 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700312}
313
Peng Xu47e96012016-03-28 17:55:56 -0700314SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800315 for (auto && entry : mRecentEvent) {
316 delete entry.second;
317 }
Peng Xu47e96012016-03-28 17:55:56 -0700318}
319
320status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700321 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700322 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800323 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700324 IPCThreadState::self()->getCallingPid(),
325 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700326 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700327 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700328 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800329 return INVALID_OPERATION;
330 }
331 Mutex::Autolock _l(mLock);
332 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700333 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700334 // If already in restricted mode. Ignore.
335 if (mCurrentOperatingMode == RESTRICTED) {
336 return status_t(NO_ERROR);
337 }
338 // If in any mode other than normal, ignore.
339 if (mCurrentOperatingMode != NORMAL) {
340 return INVALID_OPERATION;
341 }
Peng Xue36e3472016-11-03 11:57:10 -0700342
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700343 mCurrentOperatingMode = RESTRICTED;
Peng Xue36e3472016-11-03 11:57:10 -0700344 // temporarily stop all sensor direct report
345 for (auto &i : mDirectConnections) {
346 sp<SensorDirectConnection> connection(i.promote());
347 if (connection != nullptr) {
348 connection->stopAll(true /* backupRecord */);
349 }
350 }
351
Aravind Akella4949c502015-02-11 15:54:35 -0800352 dev.disableAllSensors();
353 // Clear all pending flush connections for all active sensors. If one of the active
354 // connections has called flush() and the underlying sensor has been disabled before a
355 // flush complete event is returned, we need to remove the connection from this queue.
356 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
357 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
358 }
Aravind Akella841a5922015-06-29 12:37:48 -0700359 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700360 return status_t(NO_ERROR);
361 } else if (args.size() == 1 && args[0] == String16("enable")) {
362 // If currently in restricted mode, reset back to NORMAL mode else ignore.
363 if (mCurrentOperatingMode == RESTRICTED) {
364 mCurrentOperatingMode = NORMAL;
365 dev.enableAllSensors();
Peng Xue36e3472016-11-03 11:57:10 -0700366 // recover all sensor direct report
367 for (auto &i : mDirectConnections) {
368 sp<SensorDirectConnection> connection(i.promote());
369 if (connection != nullptr) {
370 connection->recoverAll();
371 }
372 }
Aravind Akella444f2672015-05-07 12:40:52 -0700373 }
Aravind Akella841a5922015-06-29 12:37:48 -0700374 if (mCurrentOperatingMode == DATA_INJECTION) {
375 resetToNormalModeLocked();
376 }
377 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700378 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700379 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
380 if (mCurrentOperatingMode == NORMAL) {
381 dev.disableAllSensors();
382 status_t err = dev.setMode(DATA_INJECTION);
383 if (err == NO_ERROR) {
384 mCurrentOperatingMode = DATA_INJECTION;
385 } else {
386 // Re-enable sensors.
387 dev.enableAllSensors();
388 }
389 mWhiteListedPackage.setTo(String8(args[1]));
390 return NO_ERROR;
391 } else if (mCurrentOperatingMode == DATA_INJECTION) {
392 // Already in DATA_INJECTION mode. Treat this as a no_op.
393 return NO_ERROR;
394 } else {
395 // Transition to data injection mode supported only from NORMAL mode.
396 return INVALID_OPERATION;
397 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700398 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700399 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700400 } else {
401 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700402 //
Peng Xu6a2d3a02015-12-21 12:00:23 -0800403 result.append("Sensor Device:\n");
404 result.append(SensorDevice::getInstance().dump().c_str());
405
406 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700407 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700408
Peng Xu6a2d3a02015-12-21 12:00:23 -0800409 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700410 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700411
Peng Xu0cc8f802016-04-05 23:46:03 -0700412 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800413 for (auto&& i : mRecentEvent) {
414 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700415 if (!i.second->isEmpty()) {
416 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
417 i.second->setFormat("normal");
418 } else {
419 i.second->setFormat("mask_data");
420 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800421 // if there is events and sensor does not need special permission.
422 result.appendFormat("%s: ", s->getSensor().getName().string());
423 result.append(i.second->dump().c_str());
424 }
425 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700426
Aravind Akella444f2672015-05-07 12:40:52 -0700427 result.append("Active sensors:\n");
428 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
429 int handle = mActiveSensors.keyAt(i);
430 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
431 getSensorName(handle).string(),
432 handle,
433 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700434 }
435
Andreas Gamped4036b62015-07-28 13:49:04 -0700436 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700437 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700438 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
439 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700440 result.appendFormat("Mode :");
441 switch(mCurrentOperatingMode) {
442 case NORMAL:
443 result.appendFormat(" NORMAL\n");
444 break;
445 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700446 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700447 break;
448 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700449 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700450 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700451
Peng Xue36e3472016-11-03 11:57:10 -0700452 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella444f2672015-05-07 12:40:52 -0700453 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
454 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
455 if (connection != 0) {
456 result.appendFormat("Connection Number: %zu \n", i);
457 connection->dump(result);
458 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700459 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700460
Peng Xue36e3472016-11-03 11:57:10 -0700461 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
462 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
463 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
464 if (connection != nullptr) {
465 result.appendFormat("Direct connection %zu:\n", i);
466 connection->dump(result);
467 }
468 }
469
Aravind Akella18d6d512015-06-18 14:18:28 -0700470 result.appendFormat("Previous Registrations:\n");
471 // Log in the reverse chronological order.
472 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
473 SENSOR_REGISTRATIONS_BUF_SIZE;
474 const int startIndex = currentIndex;
475 do {
476 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
477 if (SensorRegistrationInfo::isSentinel(reg_info)) {
478 // Ignore sentinel, proceed to next item.
479 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
480 SENSOR_REGISTRATIONS_BUF_SIZE;
481 continue;
482 }
Peng Xu51224682017-03-10 16:57:27 -0800483 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700484 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
485 SENSOR_REGISTRATIONS_BUF_SIZE;
486 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700487 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700488 }
489 write(fd, result.string(), result.size());
490 return NO_ERROR;
491}
492
Peng Xu0cc8f802016-04-05 23:46:03 -0700493//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800494void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700495 sensors_event_t const* buffer, const int count) {
496 for (int i=0 ; i<count ; i++) {
497 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700498 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
499 handle = buffer[i].meta_data.sensor;
500 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700501 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700502 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700503 // If this buffer has an event from a one_shot sensor and this connection is registered
504 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700505 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700506 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
507 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800508 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700509 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700510
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700511 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700512 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700513}
514
Peng Xu47e96012016-03-28 17:55:56 -0700515bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000516 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700517
Peng Xueb4d6282015-12-10 18:02:41 -0800518 // each virtual sensor could generate an event per "real" event, that's why we need to size
519 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
520 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700521 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700522 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700523 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700524
Mathias Agopianf001c922010-11-11 17:58:51 -0800525 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700526
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700527 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700528 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700529 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
530 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000531 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700532 break;
533 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700534
535 // Reset sensors_event_t.flags to zero for all events in the buffer.
536 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700537 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700538 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700539
Peng Xueb4d6282015-12-10 18:02:41 -0800540 // Make a copy of the connection vector as some connections may be removed during the course
541 // of this loop (especially when one-shot sensor events are present in the sensor_event
542 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
543 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
544 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
545 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700546 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700547 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800548
Aravind Akella9a844cf2014-02-11 18:58:52 -0800549 Mutex::Autolock _l(mLock);
550 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
551 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
552 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
553 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
554 // releasing the wakelock.
555 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700556 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700557 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800558 bufferHasWakeUpEvent = true;
559 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700560 }
561 }
562
Aravind Akella9a844cf2014-02-11 18:58:52 -0800563 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700564 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800565 }
Aravind Akella8493b792014-09-08 15:45:47 -0700566 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800567
Mathias Agopianf001c922010-11-11 17:58:51 -0800568 // handle virtual sensors
569 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700570 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700571 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800572 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700573 SensorFusion& fusion(SensorFusion::getInstance());
574 if (fusion.isEnabled()) {
575 for (size_t i=0 ; i<size_t(count) ; i++) {
576 fusion.process(event[i]);
577 }
578 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700579 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700580 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700581 if (count + k >= minBufferSize) {
582 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700583 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700584 count, k, minBufferSize);
585 break;
586 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800587 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700588 sp<SensorInterface> si = mSensors.getInterface(handle);
589 if (si == nullptr) {
590 ALOGE("handle %d is not an valid virtual sensor", handle);
591 continue;
592 }
593
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700594 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700595 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800596 k++;
597 }
598 }
599 }
600 if (k) {
601 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700602 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800603 count += k;
604 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700605 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700606 }
607 }
608 }
609
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700610 // handle backward compatibility for RotationVector sensor
611 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
612 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700613 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700614 // All the 4 components of the quaternion should be available
615 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700616 mSensorEventBuffer[i].data[4] = -1;
617 }
618 }
619 }
620
Aravind Akella8493b792014-09-08 15:45:47 -0700621 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700622 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
623 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
624 // SensorEventConnection mapped to the corresponding flush_complete_event in
625 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700626 mMapFlushEventsToConnections[i] = NULL;
627 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
628 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
629 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
630 if (rec != NULL) {
631 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
632 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700633 }
634 }
Peng Xu2576cb62016-01-20 00:22:09 -0800635
636 // handle dynamic sensor meta events, process registration and unregistration of dynamic
637 // sensor based on content of event.
638 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
639 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
640 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
641 const sensor_t& dynamicSensor =
642 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
643 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
644 handle, dynamicSensor.type, dynamicSensor.name);
645
Peng Xu0cc8f802016-04-05 23:46:03 -0700646 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800647 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700648 sensor_t s = dynamicSensor;
649 // make sure the dynamic sensor flag is set
650 s.flags |= DYNAMIC_SENSOR_MASK;
651 // force the handle to be consistent
652 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800653
654 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800655
Peng Xu0cc8f802016-04-05 23:46:03 -0700656 // This will release hold on dynamic sensor meta, so it should be called
657 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700658 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800659 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700660 } else {
661 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
662 }
Peng Xu2576cb62016-01-20 00:22:09 -0800663 } else {
664 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
665 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
666
667 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800668 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800669 ALOGE("Dynamic sensor release error.");
670 }
671
672 size_t numConnections = activeConnections.size();
673 for (size_t i=0 ; i < numConnections; ++i) {
674 if (activeConnections[i] != NULL) {
675 activeConnections[i]->removeSensor(handle);
676 }
677 }
678 }
679 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700680 }
681
Peng Xu2576cb62016-01-20 00:22:09 -0800682
Aravind Akella9a844cf2014-02-11 18:58:52 -0800683 // Send our events to clients. Check the state of wake lock for each client and release the
684 // lock if none of the clients need it.
685 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700686 size_t numConnections = activeConnections.size();
687 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700688 if (activeConnections[i] != 0) {
689 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700690 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700691 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700692 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
693 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700694 if (activeConnections[i]->hasOneShotSensors()) {
695 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
696 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700697 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800698 }
699 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700700
Aravind Akella9a844cf2014-02-11 18:58:52 -0800701 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700702 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800703 }
Aravind Akella8493b792014-09-08 15:45:47 -0700704 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700705
Steve Block3c20fbe2012-01-05 23:22:43 +0000706 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800707 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700708 return false;
709}
710
Aravind Akella56ae4262014-07-10 16:01:10 -0700711sp<Looper> SensorService::getLooper() const {
712 return mLooper;
713}
714
Aravind Akellab4373ac2014-10-29 17:55:20 -0700715void SensorService::resetAllWakeLockRefCounts() {
716 SortedVector< sp<SensorEventConnection> > activeConnections;
717 populateActiveConnections(&activeConnections);
718 {
719 Mutex::Autolock _l(mLock);
720 for (size_t i=0 ; i < activeConnections.size(); ++i) {
721 if (activeConnections[i] != 0) {
722 activeConnections[i]->resetWakeLockRefCount();
723 }
724 }
725 setWakeLockAcquiredLocked(false);
726 }
727}
728
729void SensorService::setWakeLockAcquiredLocked(bool acquire) {
730 if (acquire) {
731 if (!mWakeLockAcquired) {
732 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
733 mWakeLockAcquired = true;
734 }
735 mLooper->wake();
736 } else {
737 if (mWakeLockAcquired) {
738 release_wake_lock(WAKE_LOCK_NAME);
739 mWakeLockAcquired = false;
740 }
741 }
742}
743
Aravind Akellab4373ac2014-10-29 17:55:20 -0700744bool SensorService::isWakeLockAcquired() {
745 Mutex::Autolock _l(mLock);
746 return mWakeLockAcquired;
747}
748
Aravind Akella56ae4262014-07-10 16:01:10 -0700749bool SensorService::SensorEventAckReceiver::threadLoop() {
750 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700751 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700752 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700753 bool wakeLockAcquired = mService->isWakeLockAcquired();
754 int timeout = -1;
755 if (wakeLockAcquired) timeout = 5000;
756 int ret = looper->pollOnce(timeout);
757 if (ret == ALOOPER_POLL_TIMEOUT) {
758 mService->resetAllWakeLockRefCounts();
759 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700760 } while(!Thread::exitPending());
761 return false;
762}
763
Aravind Akella9a844cf2014-02-11 18:58:52 -0800764void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800765 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800766 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800767 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
768 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -0800769 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -0800770 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800771 }
Peng Xu2576cb62016-01-20 00:22:09 -0800772
Peng Xu6a2d3a02015-12-21 12:00:23 -0800773 auto logger = mRecentEvent.find(buffer[i].sensor);
774 if (logger != mRecentEvent.end()) {
775 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -0800776 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800777 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800778}
779
Peng Xu47e96012016-03-28 17:55:56 -0700780void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800781 struct compar {
782 static int cmp(void const* lhs, void const* rhs) {
783 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
784 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700785 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800786 }
787 };
788 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
789}
790
Mathias Agopian5d270722010-07-19 15:20:39 -0700791String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700792 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700793}
794
Aravind Akellab4099e72013-10-15 15:43:10 -0700795bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -0700796 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
797 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700798}
799
Aravind Akella9a844cf2014-02-11 18:58:52 -0800800bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700801 int handle = event.sensor;
802 if (event.type == SENSOR_TYPE_META_DATA) {
803 handle = event.meta_data.sensor;
804 }
Peng Xu755c4512016-04-07 23:15:14 -0700805 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
806 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800807}
808
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700809int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
810 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
811 // UUID is not supported for this device.
812 return 0;
813 }
814 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
815 // This sensor can be uniquely identified in the system by
816 // the combination of its type and name.
817 return -1;
818 }
819
820 // We have a dynamic sensor.
821
822 if (!sHmacGlobalKeyIsValid) {
823 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
824 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
825 return 0;
826 }
827
828 // We want each app author/publisher to get a different ID, so that the
829 // same dynamic sensor cannot be tracked across apps by multiple
830 // authors/publishers. So we use both our UUID and our User ID.
831 // Note potential confusion:
832 // UUID => Universally Unique Identifier.
833 // UID => User Identifier.
834 // We refrain from using "uid" except as needed by API to try to
835 // keep this distinction clear.
836
837 auto appUserId = IPCThreadState::self()->getCallingUid();
838 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
839 memcpy(uuidAndApp, &uuid, sizeof(uuid));
840 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
841
842 // Now we use our key on our UUID/app combo to get the hash.
843 uint8_t hash[EVP_MAX_MD_SIZE];
844 unsigned int hashLen;
845 if (HMAC(EVP_sha256(),
846 sHmacGlobalKey, sizeof(sHmacGlobalKey),
847 uuidAndApp, sizeof(uuidAndApp),
848 hash, &hashLen) == nullptr) {
849 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
850 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
851 return 0;
852 }
853
854 int32_t id = 0;
855 if (hashLen < sizeof(id)) {
856 // We never expect this case, but out of paranoia, we handle it.
857 // Our 'id' length is already quite small, we don't want the
858 // effective length of it to be even smaller.
859 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
860 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
861 return 0;
862 }
863
864 // This is almost certainly less than all of 'hash', but it's as secure
865 // as we can be with our current 'id' length.
866 memcpy(&id, hash, sizeof(id));
867
868 // Note at the beginning of the function that we return the values of
869 // 0 and -1 to represent special cases. As a result, we can't return
870 // those as dynamic sensor IDs. If we happened to hash to one of those
871 // values, we change 'id' so we report as a dynamic sensor, and not as
872 // one of those special cases.
873 if (id == -1) {
874 id = -2;
875 } else if (id == 0) {
876 id = 1;
877 }
878 return id;
879}
880
881void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
882 for (auto &sensor : sensorList) {
883 int32_t id = getIdFromUuid(sensor.getUuid());
884 sensor.setId(id);
885 }
886}
887
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800888Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -0700889 char value[PROPERTY_VALUE_MAX];
890 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000891 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700892 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000893 Vector<Sensor> accessibleSensorList;
894 for (size_t i = 0; i < initialSensorList.size(); i++) {
895 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -0800896 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -0700897 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700898 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +0000899 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700900}
901
Peng Xu47e96012016-03-28 17:55:56 -0700902Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800903 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700904 mSensors.forEachSensor(
905 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -0700906 if (sensor.isDynamicSensor()) {
907 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
908 accessibleSensorList.add(sensor);
909 } else {
910 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
911 sensor.getName().string(),
912 sensor.getRequiredPermission().string(),
913 sensor.getRequiredAppOp());
914 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700915 }
916 return true;
917 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700918 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -0800919 return accessibleSensorList;
920}
921
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700922sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700923 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700924 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
925 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
926 return NULL;
927 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700928
929 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700930 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
931 // operating in DI mode.
932 if (requestedMode == DATA_INJECTION) {
933 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
934 if (!isWhiteListedPackage(packageName)) return NULL;
935 }
936
Mathias Agopian5307d172012-09-18 17:02:43 -0700937 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700938 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700939 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700940 if (requestedMode == DATA_INJECTION) {
941 if (mActiveConnections.indexOf(result) < 0) {
942 mActiveConnections.add(result);
943 }
944 // Add the associated file descriptor to the Looper for polling whenever there is data to
945 // be injected.
946 result->updateLooperRegistration(mLooper);
947 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700948 return result;
949}
950
Aravind Akella841a5922015-06-29 12:37:48 -0700951int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700952 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700953 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700954}
955
Peng Xue36e3472016-11-03 11:57:10 -0700956sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
957 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
958 const native_handle *resource) {
959 Mutex::Autolock _l(mLock);
960
961 struct sensors_direct_mem_t mem = {
962 .type = type,
963 .format = format,
964 .size = size,
965 .handle = resource,
966 };
967 uid_t uid = IPCThreadState::self()->getCallingUid();
968
969 if (mem.handle == nullptr) {
970 ALOGE("Failed to clone resource handle");
971 return nullptr;
972 }
973
974 // check format
975 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
976 ALOGE("Direct channel format %d is unsupported!", format);
977 return nullptr;
978 }
979
980 // check for duplication
981 for (auto &i : mDirectConnections) {
982 sp<SensorDirectConnection> connection(i.promote());
983 if (connection != nullptr && connection->isEquivalent(&mem)) {
984 return nullptr;
985 }
986 }
987
988 // check specific to memory type
989 switch(type) {
990 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
991 int fd = resource->data[0];
992 int size2 = ashmem_get_size_region(fd);
993 // check size consistency
994 if (size2 != static_cast<int>(size)) {
995 ALOGE("Ashmem direct channel size mismatch, %" PRIu32 " vs %d", size, size2);
996 return nullptr;
997 }
998 break;
999 }
1000 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1001 LOG_FATAL("%s: Finish implementation of ION and GRALLOC or remove", __FUNCTION__);
1002 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
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001035status_t SensorService::resetToNormalMode() {
1036 Mutex::Autolock _l(mLock);
1037 return resetToNormalModeLocked();
1038}
1039
1040status_t SensorService::resetToNormalModeLocked() {
1041 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001042 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301043 if (err == NO_ERROR) {
1044 mCurrentOperatingMode = NORMAL;
1045 dev.enableAllSensors();
1046 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001047 return err;
1048}
1049
Peng Xu47e96012016-03-28 17:55:56 -07001050void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001051 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001052 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001053 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001054 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001055 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001056 int handle = mActiveSensors.keyAt(i);
1057 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001058 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001059 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1060 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001061 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001062 } else {
1063 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001064 }
Aravind Akella8a969552014-09-28 17:52:41 -07001065 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001066 }
1067 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001068 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001069 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001070 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001071 c, i, handle);
1072
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001073 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001074 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001075 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001076 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001077 delete rec;
1078 size--;
1079 } else {
1080 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001081 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001082 }
Aravind Akella8a969552014-09-28 17:52:41 -07001083 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001084 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001085 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001086 if (c->needsWakeLock()) {
1087 checkWakeLockStateLocked();
1088 }
Peng Xu4f707f82016-09-26 11:28:32 -07001089
1090 SensorDevice& dev(SensorDevice::getInstance());
1091 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001092}
1093
Peng Xue36e3472016-11-03 11:57:10 -07001094void SensorService::cleanupConnection(SensorDirectConnection* c) {
1095 Mutex::Autolock _l(mLock);
1096
1097 SensorDevice& dev(SensorDevice::getInstance());
1098 dev.unregisterDirectChannel(c->getHalChannelHandle());
1099 mDirectConnections.remove(c);
1100}
1101
Peng Xu755c4512016-04-07 23:15:14 -07001102sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001103 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001104}
1105
Mathias Agopianfc328812010-07-14 23:41:37 -07001106status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001107 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001108 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001109 if (mInitCheck != NO_ERROR)
1110 return mInitCheck;
1111
Peng Xu755c4512016-04-07 23:15:14 -07001112 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1113 if (sensor == nullptr ||
1114 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001115 return BAD_VALUE;
1116 }
1117
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001118 Mutex::Autolock _l(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001119 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001120 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001121 return INVALID_OPERATION;
1122 }
1123
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001124 SensorRecord* rec = mActiveSensors.valueFor(handle);
1125 if (rec == 0) {
1126 rec = new SensorRecord(connection);
1127 mActiveSensors.add(handle, rec);
1128 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001129 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001130 }
1131 } else {
1132 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001133 // this sensor is already activated, but we are adding a connection that uses it.
1134 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001135 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001136 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001137 // NOTE: The wake_up flag of this event may get set to
1138 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001139
1140 auto logger = mRecentEvent.find(handle);
1141 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001142 sensors_event_t event;
Aravind Akella444f2672015-05-07 12:40:52 -07001143 // It is unlikely that this buffer is empty as the sensor is already active.
1144 // One possible corner case may be two applications activating an on-change
1145 // sensor at the same time.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001146 if(logger->second->populateLastEvent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001147 event.sensor = handle;
1148 if (event.version == sizeof(sensors_event_t)) {
1149 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1150 setWakeLockAcquiredLocked(true);
1151 }
1152 connection->sendEvents(&event, 1, NULL);
1153 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1154 checkWakeLockStateLocked();
1155 }
1156 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001157 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001158 }
1159 }
1160 }
1161 }
1162
1163 if (connection->addSensor(handle)) {
1164 BatteryService::enableSensor(connection->getUid(), handle);
1165 // the sensor was added (which means it wasn't already there)
1166 // so, see if this connection becomes active
1167 if (mActiveConnections.indexOf(connection) < 0) {
1168 mActiveConnections.add(connection);
1169 }
1170 } else {
1171 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1172 handle, connection.get());
1173 }
1174
Aravind Akella724d91d2013-06-27 12:04:23 -07001175 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1176 if (samplingPeriodNs < minDelayNs) {
1177 samplingPeriodNs = minDelayNs;
1178 }
1179
Aravind Akella6c2664a2014-08-13 12:24:50 -07001180 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1181 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001182 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1183
Aravind Akella4949c502015-02-11 15:54:35 -08001184 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001185 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001186
Peng Xu20483c42015-10-26 15:14:43 -07001187 // Call flush() before calling activate() on the sensor. Wait for a first
1188 // flush complete event before sending events on this connection. Ignore
1189 // one-shot sensors which don't support flush(). Ignore on-change sensors
1190 // to maintain the on-change logic (any on-change events except the initial
1191 // one should be trigger by a change in value). Also if this sensor isn't
1192 // already active, don't call flush().
1193 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001194 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001195 rec->getNumConnections() > 1) {
1196 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001197 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001198 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001199 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001200 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001201 } else {
1202 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001203 }
1204 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001205
1206 if (err == NO_ERROR) {
1207 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1208 err = sensor->activate(connection.get(), true);
1209 }
1210
Aravind Akella8a969552014-09-28 17:52:41 -07001211 if (err == NO_ERROR) {
1212 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001213
1214 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1215 SensorRegistrationInfo(handle, connection->getPackageName(),
1216 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001217 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001218 }
1219
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001220 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001221 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001222 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001223 }
1224 return err;
1225}
1226
Peng Xu47e96012016-03-28 17:55:56 -07001227status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001228 if (mInitCheck != NO_ERROR)
1229 return mInitCheck;
1230
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001231 Mutex::Autolock _l(mLock);
1232 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001233 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001234 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1235 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001236
1237 }
1238 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001239 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1240 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001241 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001242 }
1243 return err;
1244}
1245
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001246status_t SensorService::cleanupWithoutDisable(
1247 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001248 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001249 return cleanupWithoutDisableLocked(connection, handle);
1250}
1251
1252status_t SensorService::cleanupWithoutDisableLocked(
1253 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001254 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001255 if (rec) {
1256 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001257 if (connection->removeSensor(handle)) {
1258 BatteryService::disableSensor(connection->getUid(), handle);
1259 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001260 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001261 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001262 mActiveConnections.remove(connection);
1263 }
1264 // see if this sensor becomes inactive
1265 if (rec->removeConnection(connection)) {
1266 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001267 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001268 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001269 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001270 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001271 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001272 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001273}
1274
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001275status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001276 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001277 if (mInitCheck != NO_ERROR)
1278 return mInitCheck;
1279
Peng Xu755c4512016-04-07 23:15:14 -07001280 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1281 if (sensor == nullptr ||
1282 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001283 return BAD_VALUE;
1284 }
1285
Mathias Agopian1cd70002010-07-21 15:59:50 -07001286 if (ns < 0)
1287 return BAD_VALUE;
1288
Mathias Agopian62569ec2011-11-07 21:21:47 -08001289 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1290 if (ns < minDelayNs) {
1291 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001292 }
1293
Mathias Agopianf001c922010-11-11 17:58:51 -08001294 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001295}
1296
Svetoslavb412f6e2015-04-29 16:50:41 -07001297status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1298 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001299 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001300 SensorDevice& dev(SensorDevice::getInstance());
1301 const int halVersion = dev.getHalDeviceVersion();
1302 status_t err(NO_ERROR);
1303 Mutex::Autolock _l(mLock);
1304 // Loop through all sensors for this connection and call flush on each of them.
1305 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1306 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001307 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1308 if (sensor == nullptr) {
1309 continue;
1310 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001311 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1312 ALOGE("flush called on a one-shot sensor");
1313 err = INVALID_OPERATION;
1314 continue;
1315 }
Aravind Akella8493b792014-09-08 15:45:47 -07001316 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001317 // For older devices just increment pending flush count which will send a trivial
1318 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001319 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001320 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001321 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1322 err = INVALID_OPERATION;
1323 continue;
1324 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001325 status_t err_flush = sensor->flush(connection.get(), handle);
1326 if (err_flush == NO_ERROR) {
1327 SensorRecord* rec = mActiveSensors.valueFor(handle);
1328 if (rec != NULL) rec->addPendingFlushConnection(connection);
1329 }
1330 err = (err_flush != NO_ERROR) ? err_flush : err;
1331 }
Aravind Akella70018042014-04-07 22:52:37 +00001332 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001333 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001334}
Aravind Akella70018042014-04-07 22:52:37 +00001335
Svetoslavb412f6e2015-04-29 16:50:41 -07001336bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1337 const String16& opPackageName) {
1338 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001339
Svetoslavb412f6e2015-04-29 16:50:41 -07001340 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001341 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001342 }
1343
1344 bool hasPermission = false;
1345
1346 // Runtime permissions can't use the cache as they may change.
1347 if (sensor.isRequiredPermissionRuntime()) {
1348 hasPermission = checkPermission(String16(requiredPermission),
1349 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001350 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001351 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1352 }
1353
1354 if (!hasPermission) {
1355 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1356 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001357 return false;
1358 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001359
1360 const int32_t opCode = sensor.getRequiredAppOp();
1361 if (opCode >= 0) {
1362 AppOpsManager appOps;
1363 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1364 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001365 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001366 operation, sensor.getName().string(), opCode);
1367 return false;
1368 }
1369 }
1370
1371 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001372}
1373
Aravind Akella9a844cf2014-02-11 18:58:52 -08001374void SensorService::checkWakeLockState() {
1375 Mutex::Autolock _l(mLock);
1376 checkWakeLockStateLocked();
1377}
1378
1379void SensorService::checkWakeLockStateLocked() {
1380 if (!mWakeLockAcquired) {
1381 return;
1382 }
1383 bool releaseLock = true;
1384 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1385 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1386 if (connection != 0) {
1387 if (connection->needsWakeLock()) {
1388 releaseLock = false;
1389 break;
1390 }
1391 }
1392 }
1393 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001394 setWakeLockAcquiredLocked(false);
1395 }
1396}
1397
1398void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1399 Mutex::Autolock _l(mLock);
1400 connection->writeToSocketFromCache();
1401 if (connection->needsWakeLock()) {
1402 setWakeLockAcquiredLocked(true);
1403 }
1404}
1405
1406void SensorService::populateActiveConnections(
1407 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1408 Mutex::Autolock _l(mLock);
1409 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1410 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1411 if (connection != 0) {
1412 activeConnections->add(connection);
1413 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001414 }
1415}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001416
Aravind Akella4949c502015-02-11 15:54:35 -08001417bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001418 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001419}
1420
Peng Xue36e3472016-11-03 11:57:10 -07001421bool SensorService::isOperationRestricted(const String16& opPackageName) {
1422 Mutex::Autolock _l(mLock);
1423 if (mCurrentOperatingMode != RESTRICTED) {
1424 String8 package(opPackageName);
1425 return !isWhiteListedPackage(package);
1426 }
1427 return false;
1428}
1429
Mathias Agopianfc328812010-07-14 23:41:37 -07001430}; // namespace android
1431