2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #include <binder/AppOpsManager.h>
17 #include <binder/BinderService.h>
18 #include <binder/IServiceManager.h>
19 #include <binder/PermissionCache.h>
20 #include <cutils/ashmem.h>
21 #include <cutils/properties.h>
22 #include <hardware/sensors.h>
23 #include <hardware_legacy/power.h>
24 #include <openssl/digest.h>
25 #include <openssl/hmac.h>
26 #include <openssl/rand.h>
27 #include <sensor/SensorEventQueue.h>
28 #include <utils/SystemClock.h>
30 #include "BatteryService.h"
31 #include "CorrectedGyroSensor.h"
32 #include "GravitySensor.h"
33 #include "LinearAccelerationSensor.h"
34 #include "OrientationSensor.h"
35 #include "RotationVectorSensor.h"
36 #include "SensorFusion.h"
37 #include "SensorInterface.h"
39 #include "SensorService.h"
40 #include "SensorDirectConnection.h"
41 #include "SensorEventAckReceiver.h"
42 #include "SensorEventConnection.h"
43 #include "SensorRecord.h"
44 #include "SensorRegistrationInfo.h"
50 #include <sys/socket.h>
52 #include <sys/types.h>
56 // ---------------------------------------------------------------------------
61 * - what about a gyro-corrected magnetic-field sensor?
62 * - run mag sensor from time to time to force calibration
63 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
67 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
68 uint8_t SensorService::sHmacGlobalKey[128] = {};
69 bool SensorService::sHmacGlobalKeyIsValid = false;
71 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
72 #define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
73 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
76 static const String16 sDumpPermission("android.permission.DUMP");
77 static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
79 SensorService::SensorService()
80 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
81 mWakeLockAcquired(false) {
84 bool SensorService::initializeHmacKey() {
85 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
87 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
89 if (result == sizeof(sHmacGlobalKey)) {
92 ALOGW("Unable to read HMAC key; generating new one.");
95 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
96 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
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,
106 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
108 wroteKey = (result == sizeof(sHmacGlobalKey));
111 ALOGI("Generated new HMAC key.");
113 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
116 // Even if we failed to write the key we return true, because we did
117 // initialize the HMAC key.
121 // Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
122 void 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, ¶m) != 0) {
126 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
130 void SensorService::onFirstRef() {
131 ALOGD("nuSensorService starting...");
132 SensorDevice& dev(SensorDevice::getInstance());
134 sHmacGlobalKeyIsValid = initializeHmacKey();
136 if (dev.initCheck() == NO_ERROR) {
137 sensor_t const* list;
138 ssize_t count = dev.getSensorList(&list);
140 ssize_t orientationIndex = -1;
141 bool hasGyro = false, hasAccel = false, hasMag = false;
142 uint32_t virtualSensorsNeeds =
143 (1<<SENSOR_TYPE_GRAVITY) |
144 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
145 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
146 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
147 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
149 for (ssize_t i=0 ; i<count ; i++) {
150 bool useThisSensor=true;
152 switch (list[i].type) {
153 case SENSOR_TYPE_ACCELEROMETER:
156 case SENSOR_TYPE_MAGNETIC_FIELD:
159 case SENSOR_TYPE_ORIENTATION:
160 orientationIndex = i;
162 case SENSOR_TYPE_GYROSCOPE:
163 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
166 case SENSOR_TYPE_GRAVITY:
167 case SENSOR_TYPE_LINEAR_ACCELERATION:
168 case SENSOR_TYPE_ROTATION_VECTOR:
169 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
170 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
171 if (IGNORE_HARDWARE_FUSION) {
172 useThisSensor = false;
174 virtualSensorsNeeds &= ~(1<<list[i].type);
179 registerSensor( new HardwareSensor(list[i]) );
183 // it's safe to instantiate the SensorFusion object here
184 // (it wants to be instantiated after h/w sensors have been
186 SensorFusion::getInstance();
188 if (hasGyro && hasAccel && hasMag) {
189 // Add Android virtual sensors if they're not already
190 // available in the HAL
191 bool needRotationVector =
192 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
194 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
195 registerSensor(new OrientationSensor(), !needRotationVector, true);
197 bool needLinearAcceleration =
198 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
200 registerSensor(new LinearAccelerationSensor(list, count),
201 !needLinearAcceleration, true);
203 // virtual debugging sensors are not for user
204 registerSensor( new CorrectedGyroSensor(list, count), true, true);
205 registerSensor( new GyroDriftSensor(), true, true);
208 if (hasAccel && hasGyro) {
209 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
210 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
212 bool needGameRotationVector =
213 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
214 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
217 if (hasAccel && hasMag) {
218 bool needGeoMagRotationVector =
219 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
220 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
223 // Check if the device really supports batching by looking at the FIFO event
224 // counts for each sensor.
225 bool batchingSupported = false;
226 mSensors.forEachSensor(
227 [&batchingSupported] (const Sensor& s) -> bool {
228 if (s.getFifoMaxEventCount() > 0) {
229 batchingSupported = true;
231 return !batchingSupported;
234 if (batchingSupported) {
235 // Increase socket buffer size to a max of 100 KB for batching capabilities.
236 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
238 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
241 // Compare the socketBufferSize value against the system limits and limit
242 // it to maxSystemSocketBufferSize if necessary.
243 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
245 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
246 line[sizeof(line) - 1] = '\0';
247 size_t maxSystemSocketBufferSize;
248 sscanf(line, "%zu", &maxSystemSocketBufferSize);
249 if (mSocketBufferSize > maxSystemSocketBufferSize) {
250 mSocketBufferSize = maxSystemSocketBufferSize;
257 mWakeLockAcquired = false;
258 mLooper = new Looper(false);
259 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
260 mSensorEventBuffer = new sensors_event_t[minBufferSize];
261 mSensorEventScratch = new sensors_event_t[minBufferSize];
262 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
263 mCurrentOperatingMode = NORMAL;
265 mNextSensorRegIndex = 0;
266 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
267 mLastNSensorRegistrations.push();
270 mInitCheck = NO_ERROR;
271 mAckReceiver = new SensorEventAckReceiver(this);
272 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
273 run("SensorService", PRIORITY_URGENT_DISPLAY);
275 // priority can only be changed after run
276 enableSchedFifoMode();
281 const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
282 int handle = s->getSensor().getHandle();
283 int type = s->getSensor().getType();
284 if (mSensors.add(handle, s, isDebug, isVirtual)){
285 mRecentEvent.emplace(handle, new RecentEventLogger(type));
286 return s->getSensor();
288 return mSensors.getNonSensor();
292 const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
293 return registerSensor(s, isDebug);
296 bool SensorService::unregisterDynamicSensorLocked(int handle) {
297 bool ret = mSensors.remove(handle);
299 const auto i = mRecentEvent.find(handle);
300 if (i != mRecentEvent.end()) {
302 mRecentEvent.erase(i);
307 const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
308 return registerSensor(s, isDebug, true);
311 SensorService::~SensorService() {
312 for (auto && entry : mRecentEvent) {
317 status_t SensorService::dump(int fd, const Vector<String16>& args) {
319 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
320 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
321 IPCThreadState::self()->getCallingPid(),
322 IPCThreadState::self()->getCallingUid());
324 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
325 if (args.size() > 2) {
326 return INVALID_OPERATION;
328 Mutex::Autolock _l(mLock);
329 SensorDevice& dev(SensorDevice::getInstance());
330 if (args.size() == 2 && args[0] == String16("restrict")) {
331 // If already in restricted mode. Ignore.
332 if (mCurrentOperatingMode == RESTRICTED) {
333 return status_t(NO_ERROR);
335 // If in any mode other than normal, ignore.
336 if (mCurrentOperatingMode != NORMAL) {
337 return INVALID_OPERATION;
340 mCurrentOperatingMode = RESTRICTED;
341 // 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 */);
349 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();
356 mWhiteListedPackage.setTo(String8(args[1]));
357 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();
363 // recover all sensor direct report
364 for (auto &i : mDirectConnections) {
365 sp<SensorDirectConnection> connection(i.promote());
366 if (connection != nullptr) {
367 connection->recoverAll();
371 if (mCurrentOperatingMode == DATA_INJECTION) {
372 resetToNormalModeLocked();
374 mWhiteListedPackage.clear();
375 return status_t(NO_ERROR);
376 } 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;
383 // Re-enable sensors.
384 dev.enableAllSensors();
386 mWhiteListedPackage.setTo(String8(args[1]));
388 } else if (mCurrentOperatingMode == DATA_INJECTION) {
389 // Already in DATA_INJECTION mode. Treat this as a no_op.
392 // Transition to data injection mode supported only from NORMAL mode.
393 return INVALID_OPERATION;
395 } else if (!mSensors.hasAnySensor()) {
396 result.append("No Sensors on the device\n");
398 // Default dump the sensor list and debugging information.
400 result.append("Sensor Device:\n");
401 result.append(SensorDevice::getInstance().dump().c_str());
403 result.append("Sensor List:\n");
404 result.append(mSensors.dump().c_str());
406 result.append("Fusion States:\n");
407 SensorFusion::getInstance().dump(result);
409 result.append("Recent Sensor events:\n");
410 for (auto&& i : mRecentEvent) {
411 sp<SensorInterface> s = mSensors.getInterface(i.first);
412 if (!i.second->isEmpty()) {
413 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
414 i.second->setFormat("normal");
416 i.second->setFormat("mask_data");
418 // if there is events and sensor does not need special permission.
419 result.appendFormat("%s: ", s->getSensor().getName().string());
420 result.append(i.second->dump().c_str());
424 result.append("Active sensors:\n");
425 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
426 int handle = mActiveSensors.keyAt(i);
427 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
428 getSensorName(handle).string(),
430 mActiveSensors.valueAt(i)->getNumConnections());
433 result.appendFormat("Socket Buffer size = %zd events\n",
434 mSocketBufferSize/sizeof(sensors_event_t));
435 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
437 result.appendFormat("Mode :");
438 switch(mCurrentOperatingMode) {
440 result.appendFormat(" NORMAL\n");
443 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
446 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
449 result.appendFormat("%zd active connections\n", mActiveConnections.size());
450 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
451 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
452 if (connection != 0) {
453 result.appendFormat("Connection Number: %zu \n", i);
454 connection->dump(result);
458 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
459 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
460 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
461 if (connection != nullptr) {
462 result.appendFormat("Direct connection %zu:\n", i);
463 connection->dump(result);
467 result.appendFormat("Previous Registrations:\n");
468 // Log in the reverse chronological order.
469 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
470 SENSOR_REGISTRATIONS_BUF_SIZE;
471 const int startIndex = currentIndex;
473 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
474 if (SensorRegistrationInfo::isSentinel(reg_info)) {
475 // Ignore sentinel, proceed to next item.
476 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
477 SENSOR_REGISTRATIONS_BUF_SIZE;
480 result.appendFormat("%s\n", reg_info.dump().c_str());
481 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
482 SENSOR_REGISTRATIONS_BUF_SIZE;
483 } while(startIndex != currentIndex);
486 write(fd, result.string(), result.size());
490 //TODO: move to SensorEventConnection later
491 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
492 sensors_event_t const* buffer, const int count) {
493 for (int i=0 ; i<count ; i++) {
494 int handle = buffer[i].sensor;
495 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
496 handle = buffer[i].meta_data.sensor;
498 if (connection->hasSensor(handle)) {
499 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
500 // If this buffer has an event from a one_shot sensor and this connection is registered
501 // for this particular one_shot sensor, try cleaning up the connection.
503 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
504 si->autoDisable(connection.get(), handle);
505 cleanupWithoutDisableLocked(connection, handle);
512 bool SensorService::threadLoop() {
513 ALOGD("nuSensorService thread starting...");
515 // each virtual sensor could generate an event per "real" event, that's why we need to size
516 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
517 // aggressive, but guaranteed to be enough.
518 const size_t vcount = mSensors.getVirtualSensors().size();
519 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
520 const size_t numEventMax = minBufferSize / (1 + vcount);
522 SensorDevice& device(SensorDevice::getInstance());
524 const int halVersion = device.getHalDeviceVersion();
526 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
528 ALOGE("sensor poll failed (%s)", strerror(-count));
532 // Reset sensors_event_t.flags to zero for all events in the buffer.
533 for (int i = 0; i < count; i++) {
534 mSensorEventBuffer[i].flags = 0;
537 // Make a copy of the connection vector as some connections may be removed during the course
538 // of this loop (especially when one-shot sensor events are present in the sensor_event
539 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
540 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
541 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
542 // strongPointers to a vector before the lock is acquired.
543 SortedVector< sp<SensorEventConnection> > activeConnections;
544 populateActiveConnections(&activeConnections);
546 Mutex::Autolock _l(mLock);
547 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
548 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
549 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
550 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
551 // releasing the wakelock.
552 bool bufferHasWakeUpEvent = false;
553 for (int i = 0; i < count; i++) {
554 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
555 bufferHasWakeUpEvent = true;
560 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
561 setWakeLockAcquiredLocked(true);
563 recordLastValueLocked(mSensorEventBuffer, count);
565 // handle virtual sensors
566 if (count && vcount) {
567 sensors_event_t const * const event = mSensorEventBuffer;
568 if (!mActiveVirtualSensors.empty()) {
570 SensorFusion& fusion(SensorFusion::getInstance());
571 if (fusion.isEnabled()) {
572 for (size_t i=0 ; i<size_t(count) ; i++) {
573 fusion.process(event[i]);
576 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
577 for (int handle : mActiveVirtualSensors) {
578 if (count + k >= minBufferSize) {
579 ALOGE("buffer too small to hold all events: "
580 "count=%zd, k=%zu, size=%zu",
581 count, k, minBufferSize);
585 sp<SensorInterface> si = mSensors.getInterface(handle);
587 ALOGE("handle %d is not an valid virtual sensor", handle);
591 if (si->process(&out, event[i])) {
592 mSensorEventBuffer[count + k] = out;
598 // record the last synthesized values
599 recordLastValueLocked(&mSensorEventBuffer[count], k);
601 // sort the buffer by time-stamps
602 sortEventBuffer(mSensorEventBuffer, count);
607 // handle backward compatibility for RotationVector sensor
608 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
609 for (int i = 0; i < count; i++) {
610 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
611 // All the 4 components of the quaternion should be available
612 // No heading accuracy. Set it to -1
613 mSensorEventBuffer[i].data[4] = -1;
618 for (int i = 0; i < count; ++i) {
619 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
620 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
621 // SensorEventConnection mapped to the corresponding flush_complete_event in
622 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
623 mMapFlushEventsToConnections[i] = NULL;
624 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
625 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
626 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
628 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
629 rec->removeFirstPendingFlushConnection();
633 // handle dynamic sensor meta events, process registration and unregistration of dynamic
634 // sensor based on content of event.
635 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
636 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
637 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
638 const sensor_t& dynamicSensor =
639 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
640 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
641 handle, dynamicSensor.type, dynamicSensor.name);
643 if (mSensors.isNewHandle(handle)) {
644 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
645 sensor_t s = dynamicSensor;
646 // make sure the dynamic sensor flag is set
647 s.flags |= DYNAMIC_SENSOR_MASK;
648 // force the handle to be consistent
651 SensorInterface *si = new HardwareSensor(s, uuid);
653 // This will release hold on dynamic sensor meta, so it should be called
654 // after Sensor object is created.
655 device.handleDynamicSensorConnection(handle, true /*connected*/);
656 registerDynamicSensorLocked(si);
658 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
661 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
662 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
664 device.handleDynamicSensorConnection(handle, false /*connected*/);
665 if (!unregisterDynamicSensorLocked(handle)) {
666 ALOGE("Dynamic sensor release error.");
669 size_t numConnections = activeConnections.size();
670 for (size_t i=0 ; i < numConnections; ++i) {
671 if (activeConnections[i] != NULL) {
672 activeConnections[i]->removeSensor(handle);
680 // Send our events to clients. Check the state of wake lock for each client and release the
681 // lock if none of the clients need it.
682 bool needsWakeLock = false;
683 size_t numConnections = activeConnections.size();
684 for (size_t i=0 ; i < numConnections; ++i) {
685 if (activeConnections[i] != 0) {
686 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
687 mMapFlushEventsToConnections);
688 needsWakeLock |= activeConnections[i]->needsWakeLock();
689 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
690 // Early check for one-shot sensors.
691 if (activeConnections[i]->hasOneShotSensors()) {
692 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
698 if (mWakeLockAcquired && !needsWakeLock) {
699 setWakeLockAcquiredLocked(false);
701 } while (!Thread::exitPending());
703 ALOGW("Exiting SensorService::threadLoop => aborting...");
708 sp<Looper> SensorService::getLooper() const {
712 void SensorService::resetAllWakeLockRefCounts() {
713 SortedVector< sp<SensorEventConnection> > activeConnections;
714 populateActiveConnections(&activeConnections);
716 Mutex::Autolock _l(mLock);
717 for (size_t i=0 ; i < activeConnections.size(); ++i) {
718 if (activeConnections[i] != 0) {
719 activeConnections[i]->resetWakeLockRefCount();
722 setWakeLockAcquiredLocked(false);
726 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
728 if (!mWakeLockAcquired) {
729 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
730 mWakeLockAcquired = true;
734 if (mWakeLockAcquired) {
735 release_wake_lock(WAKE_LOCK_NAME);
736 mWakeLockAcquired = false;
741 bool SensorService::isWakeLockAcquired() {
742 Mutex::Autolock _l(mLock);
743 return mWakeLockAcquired;
746 bool SensorService::SensorEventAckReceiver::threadLoop() {
747 ALOGD("new thread SensorEventAckReceiver");
748 sp<Looper> looper = mService->getLooper();
750 bool wakeLockAcquired = mService->isWakeLockAcquired();
752 if (wakeLockAcquired) timeout = 5000;
753 int ret = looper->pollOnce(timeout);
754 if (ret == ALOOPER_POLL_TIMEOUT) {
755 mService->resetAllWakeLockRefCounts();
757 } while(!Thread::exitPending());
761 void SensorService::recordLastValueLocked(
762 const sensors_event_t* buffer, size_t count) {
763 for (size_t i = 0; i < count; i++) {
764 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
765 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
766 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
770 auto logger = mRecentEvent.find(buffer[i].sensor);
771 if (logger != mRecentEvent.end()) {
772 logger->second->addEvent(buffer[i]);
777 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
779 static int cmp(void const* lhs, void const* rhs) {
780 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
781 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
782 return l->timestamp - r->timestamp;
785 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
788 String8 SensorService::getSensorName(int handle) const {
789 return mSensors.getName(handle);
792 bool SensorService::isVirtualSensor(int handle) const {
793 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
794 return sensor != nullptr && sensor->isVirtual();
797 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
798 int handle = event.sensor;
799 if (event.type == SENSOR_TYPE_META_DATA) {
800 handle = event.meta_data.sensor;
802 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
803 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
806 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
807 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
808 // UUID is not supported for this device.
811 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
812 // This sensor can be uniquely identified in the system by
813 // the combination of its type and name.
817 // We have a dynamic sensor.
819 if (!sHmacGlobalKeyIsValid) {
820 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
821 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
825 // We want each app author/publisher to get a different ID, so that the
826 // same dynamic sensor cannot be tracked across apps by multiple
827 // authors/publishers. So we use both our UUID and our User ID.
828 // Note potential confusion:
829 // UUID => Universally Unique Identifier.
830 // UID => User Identifier.
831 // We refrain from using "uid" except as needed by API to try to
832 // keep this distinction clear.
834 auto appUserId = IPCThreadState::self()->getCallingUid();
835 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
836 memcpy(uuidAndApp, &uuid, sizeof(uuid));
837 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
839 // Now we use our key on our UUID/app combo to get the hash.
840 uint8_t hash[EVP_MAX_MD_SIZE];
841 unsigned int hashLen;
842 if (HMAC(EVP_sha256(),
843 sHmacGlobalKey, sizeof(sHmacGlobalKey),
844 uuidAndApp, sizeof(uuidAndApp),
845 hash, &hashLen) == nullptr) {
846 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
847 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
852 if (hashLen < sizeof(id)) {
853 // We never expect this case, but out of paranoia, we handle it.
854 // Our 'id' length is already quite small, we don't want the
855 // effective length of it to be even smaller.
856 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
857 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
861 // This is almost certainly less than all of 'hash', but it's as secure
862 // as we can be with our current 'id' length.
863 memcpy(&id, hash, sizeof(id));
865 // Note at the beginning of the function that we return the values of
866 // 0 and -1 to represent special cases. As a result, we can't return
867 // those as dynamic sensor IDs. If we happened to hash to one of those
868 // values, we change 'id' so we report as a dynamic sensor, and not as
869 // one of those special cases.
872 } else if (id == 0) {
878 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
879 for (auto &sensor : sensorList) {
880 int32_t id = getIdFromUuid(sensor.getUuid());
885 Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
886 char value[PROPERTY_VALUE_MAX];
887 property_get("debug.sensors", value, "0");
888 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
889 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
890 Vector<Sensor> accessibleSensorList;
891 for (size_t i = 0; i < initialSensorList.size(); i++) {
892 Sensor sensor = initialSensorList[i];
893 accessibleSensorList.add(sensor);
895 makeUuidsIntoIdsForSensorList(accessibleSensorList);
896 return accessibleSensorList;
899 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
900 Vector<Sensor> accessibleSensorList;
901 mSensors.forEachSensor(
902 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
903 if (sensor.isDynamicSensor()) {
904 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
905 accessibleSensorList.add(sensor);
907 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
908 sensor.getName().string(),
909 sensor.getRequiredPermission().string(),
910 sensor.getRequiredAppOp());
915 makeUuidsIntoIdsForSensorList(accessibleSensorList);
916 return accessibleSensorList;
919 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
920 int requestedMode, const String16& opPackageName) {
921 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
922 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
926 Mutex::Autolock _l(mLock);
927 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
928 // operating in DI mode.
929 if (requestedMode == DATA_INJECTION) {
930 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
931 if (!isWhiteListedPackage(packageName)) return NULL;
934 uid_t uid = IPCThreadState::self()->getCallingUid();
935 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
936 requestedMode == DATA_INJECTION, opPackageName));
937 if (requestedMode == DATA_INJECTION) {
938 if (mActiveConnections.indexOf(result) < 0) {
939 mActiveConnections.add(result);
941 // Add the associated file descriptor to the Looper for polling whenever there is data to
943 result->updateLooperRegistration(mLooper);
948 int SensorService::isDataInjectionEnabled() {
949 Mutex::Autolock _l(mLock);
950 return (mCurrentOperatingMode == DATA_INJECTION);
953 sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
954 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
955 const native_handle *resource) {
956 Mutex::Autolock _l(mLock);
958 struct sensors_direct_mem_t mem = {
964 uid_t uid = IPCThreadState::self()->getCallingUid();
966 if (mem.handle == nullptr) {
967 ALOGE("Failed to clone resource handle");
972 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
973 ALOGE("Direct channel format %d is unsupported!", format);
977 // check for duplication
978 for (auto &i : mDirectConnections) {
979 sp<SensorDirectConnection> connection(i.promote());
980 if (connection != nullptr && connection->isEquivalent(&mem)) {
981 ALOGE("Duplicate create channel request for the same share memory");
986 // check specific to memory type
988 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
989 int fd = resource->data[0];
990 int size2 = ashmem_get_size_region(fd);
991 // check size consistency
992 if (size2 < static_cast<int>(size)) {
993 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
999 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1000 // no specific checks for gralloc
1003 ALOGE("Unknown direct connection memory type %d", type);
1007 native_handle_t *clone = native_handle_clone(resource);
1012 SensorDirectConnection* conn = nullptr;
1013 SensorDevice& dev(SensorDevice::getInstance());
1014 int channelHandle = dev.registerDirectChannel(&mem);
1016 if (channelHandle <= 0) {
1017 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1020 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1023 if (conn == nullptr) {
1024 native_handle_close(clone);
1025 native_handle_delete(clone);
1027 // add to list of direct connections
1028 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1029 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1034 int SensorService::setOperationParameter(
1035 int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints) {
1036 Mutex::Autolock _l(mLock);
1040 bool hasPermission = checkCallingPermission(sLocationHardwarePermission, nullptr, &uid);
1041 if (!hasPermission || (uid != 1000 && uid != 0)) {
1042 return PERMISSION_DENIED;
1045 bool isFloat = true;
1046 size_t expectSize = INT32_MAX;
1048 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1052 case AINFO_LOCAL_GRAVITY:
1056 case AINFO_DOCK_STATE:
1057 case AINFO_HIGH_PERFORMANCE_MODE:
1058 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1066 // three events: first one is begin tag, last one is end tag, the one in the middle
1068 sensors_event_t event[3];
1069 int64_t timestamp = elapsedRealtimeNano();
1070 for (sensors_event_t* i = event; i < event + 3; i++) {
1071 *i = (sensors_event_t) {
1072 .version = sizeof(sensors_event_t),
1073 .sensor = SENSORS_HANDLE_BASE - 1, // sensor that never exists
1074 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1075 .timestamp = timestamp++,
1076 .additional_info = (additional_info_event_t) {
1082 event[0].additional_info.type = AINFO_BEGIN;
1083 event[1].additional_info.type = type;
1084 event[2].additional_info.type = AINFO_END;
1087 if (floats.size() != expectSize) {
1090 for (size_t i = 0; i < expectSize; ++i) {
1091 event[1].additional_info.data_float[i] = floats[i];
1094 if (ints.size() != expectSize) {
1097 for (size_t i = 0; i < expectSize; ++i) {
1098 event[1].additional_info.data_int32[i] = ints[i];
1102 SensorDevice& dev(SensorDevice::getInstance());
1103 for (sensors_event_t* i = event; i < event + 3; i++) {
1104 int ret = dev.injectSensorData(i);
1105 if (ret != NO_ERROR) {
1112 status_t SensorService::resetToNormalMode() {
1113 Mutex::Autolock _l(mLock);
1114 return resetToNormalModeLocked();
1117 status_t SensorService::resetToNormalModeLocked() {
1118 SensorDevice& dev(SensorDevice::getInstance());
1119 status_t err = dev.setMode(NORMAL);
1120 if (err == NO_ERROR) {
1121 mCurrentOperatingMode = NORMAL;
1122 dev.enableAllSensors();
1127 void SensorService::cleanupConnection(SensorEventConnection* c) {
1128 Mutex::Autolock _l(mLock);
1129 const wp<SensorEventConnection> connection(c);
1130 size_t size = mActiveSensors.size();
1131 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
1132 for (size_t i=0 ; i<size ; ) {
1133 int handle = mActiveSensors.keyAt(i);
1134 if (c->hasSensor(handle)) {
1135 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
1136 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1137 if (sensor != nullptr) {
1138 sensor->activate(c, false);
1140 ALOGE("sensor interface of handle=0x%08x is null!", handle);
1142 c->removeSensor(handle);
1144 SensorRecord* rec = mActiveSensors.valueAt(i);
1145 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
1146 ALOGD_IF(DEBUG_CONNECTIONS,
1147 "removing connection %p for sensor[%zu].handle=0x%08x",
1150 if (rec && rec->removeConnection(connection)) {
1151 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
1152 mActiveSensors.removeItemsAt(i, 1);
1153 mActiveVirtualSensors.erase(handle);
1160 c->updateLooperRegistration(mLooper);
1161 mActiveConnections.remove(connection);
1162 BatteryService::cleanup(c->getUid());
1163 if (c->needsWakeLock()) {
1164 checkWakeLockStateLocked();
1167 SensorDevice& dev(SensorDevice::getInstance());
1168 dev.notifyConnectionDestroyed(c);
1171 void SensorService::cleanupConnection(SensorDirectConnection* c) {
1172 Mutex::Autolock _l(mLock);
1174 SensorDevice& dev(SensorDevice::getInstance());
1175 dev.unregisterDirectChannel(c->getHalChannelHandle());
1176 mDirectConnections.remove(c);
1179 sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
1180 return mSensors.getInterface(handle);
1183 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
1184 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
1185 const String16& opPackageName) {
1186 if (mInitCheck != NO_ERROR)
1189 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1190 if (sensor == nullptr ||
1191 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
1195 Mutex::Autolock _l(mLock);
1196 if (mCurrentOperatingMode != NORMAL
1197 && !isWhiteListedPackage(connection->getPackageName())) {
1198 return INVALID_OPERATION;
1201 SensorRecord* rec = mActiveSensors.valueFor(handle);
1203 rec = new SensorRecord(connection);
1204 mActiveSensors.add(handle, rec);
1205 if (sensor->isVirtual()) {
1206 mActiveVirtualSensors.emplace(handle);
1209 if (rec->addConnection(connection)) {
1210 // this sensor is already activated, but we are adding a connection that uses it.
1211 // Immediately send down the last known value of the requested sensor if it's not a
1212 // "continuous" sensor.
1213 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1214 // NOTE: The wake_up flag of this event may get set to
1215 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
1217 auto logger = mRecentEvent.find(handle);
1218 if (logger != mRecentEvent.end()) {
1219 sensors_event_t event;
1220 // It is unlikely that this buffer is empty as the sensor is already active.
1221 // One possible corner case may be two applications activating an on-change
1222 // sensor at the same time.
1223 if(logger->second->populateLastEvent(&event)) {
1224 event.sensor = handle;
1225 if (event.version == sizeof(sensors_event_t)) {
1226 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1227 setWakeLockAcquiredLocked(true);
1229 connection->sendEvents(&event, 1, NULL);
1230 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1231 checkWakeLockStateLocked();
1240 if (connection->addSensor(handle)) {
1241 BatteryService::enableSensor(connection->getUid(), handle);
1242 // the sensor was added (which means it wasn't already there)
1243 // so, see if this connection becomes active
1244 if (mActiveConnections.indexOf(connection) < 0) {
1245 mActiveConnections.add(connection);
1248 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1249 handle, connection.get());
1252 // Check maximum delay for the sensor.
1253 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
1254 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1255 samplingPeriodNs = maxDelayNs;
1258 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1259 if (samplingPeriodNs < minDelayNs) {
1260 samplingPeriodNs = minDelayNs;
1263 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1264 "rate=%" PRId64 " timeout== %" PRId64"",
1265 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1267 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
1268 maxBatchReportLatencyNs);
1270 // Call flush() before calling activate() on the sensor. Wait for a first
1271 // flush complete event before sending events on this connection. Ignore
1272 // one-shot sensors which don't support flush(). Ignore on-change sensors
1273 // to maintain the on-change logic (any on-change events except the initial
1274 // one should be trigger by a change in value). Also if this sensor isn't
1275 // already active, don't call flush().
1276 if (err == NO_ERROR &&
1277 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
1278 rec->getNumConnections() > 1) {
1279 connection->setFirstFlushPending(handle, true);
1280 status_t err_flush = sensor->flush(connection.get(), handle);
1281 // Flush may return error if the underlying h/w sensor uses an older HAL.
1282 if (err_flush == NO_ERROR) {
1283 rec->addPendingFlushConnection(connection.get());
1285 connection->setFirstFlushPending(handle, false);
1289 if (err == NO_ERROR) {
1290 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1291 err = sensor->activate(connection.get(), true);
1294 if (err == NO_ERROR) {
1295 connection->updateLooperRegistration(mLooper);
1297 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1298 SensorRegistrationInfo(handle, connection->getPackageName(),
1299 samplingPeriodNs, maxBatchReportLatencyNs, true);
1300 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1303 if (err != NO_ERROR) {
1304 // batch/activate has failed, reset our state.
1305 cleanupWithoutDisableLocked(connection, handle);
1310 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
1311 if (mInitCheck != NO_ERROR)
1314 Mutex::Autolock _l(mLock);
1315 status_t err = cleanupWithoutDisableLocked(connection, handle);
1316 if (err == NO_ERROR) {
1317 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1318 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
1321 if (err == NO_ERROR) {
1322 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1323 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
1324 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1329 status_t SensorService::cleanupWithoutDisable(
1330 const sp<SensorEventConnection>& connection, int handle) {
1331 Mutex::Autolock _l(mLock);
1332 return cleanupWithoutDisableLocked(connection, handle);
1335 status_t SensorService::cleanupWithoutDisableLocked(
1336 const sp<SensorEventConnection>& connection, int handle) {
1337 SensorRecord* rec = mActiveSensors.valueFor(handle);
1339 // see if this connection becomes inactive
1340 if (connection->removeSensor(handle)) {
1341 BatteryService::disableSensor(connection->getUid(), handle);
1343 if (connection->hasAnySensor() == false) {
1344 connection->updateLooperRegistration(mLooper);
1345 mActiveConnections.remove(connection);
1347 // see if this sensor becomes inactive
1348 if (rec->removeConnection(connection)) {
1349 mActiveSensors.removeItem(handle);
1350 mActiveVirtualSensors.erase(handle);
1358 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1359 int handle, nsecs_t ns, const String16& opPackageName) {
1360 if (mInitCheck != NO_ERROR)
1363 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1364 if (sensor == nullptr ||
1365 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1372 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1373 if (ns < minDelayNs) {
1377 return sensor->setDelay(connection.get(), handle, ns);
1380 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1381 const String16& opPackageName) {
1382 if (mInitCheck != NO_ERROR) return mInitCheck;
1383 SensorDevice& dev(SensorDevice::getInstance());
1384 const int halVersion = dev.getHalDeviceVersion();
1385 status_t err(NO_ERROR);
1386 Mutex::Autolock _l(mLock);
1387 // Loop through all sensors for this connection and call flush on each of them.
1388 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1389 const int handle = connection->mSensorInfo.keyAt(i);
1390 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1391 if (sensor == nullptr) {
1394 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1395 ALOGE("flush called on a one-shot sensor");
1396 err = INVALID_OPERATION;
1399 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1400 // For older devices just increment pending flush count which will send a trivial
1401 // flush complete event.
1402 connection->incrementPendingFlushCount(handle);
1404 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1405 err = INVALID_OPERATION;
1408 status_t err_flush = sensor->flush(connection.get(), handle);
1409 if (err_flush == NO_ERROR) {
1410 SensorRecord* rec = mActiveSensors.valueFor(handle);
1411 if (rec != NULL) rec->addPendingFlushConnection(connection);
1413 err = (err_flush != NO_ERROR) ? err_flush : err;
1419 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1420 const String16& opPackageName) {
1421 const String8& requiredPermission = sensor.getRequiredPermission();
1423 if (requiredPermission.length() <= 0) {
1427 bool hasPermission = false;
1429 // Runtime permissions can't use the cache as they may change.
1430 if (sensor.isRequiredPermissionRuntime()) {
1431 hasPermission = checkPermission(String16(requiredPermission),
1432 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1434 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1437 if (!hasPermission) {
1438 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1439 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1443 const int32_t opCode = sensor.getRequiredAppOp();
1445 AppOpsManager appOps;
1446 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1447 != AppOpsManager::MODE_ALLOWED) {
1448 ALOGE("%s a sensor (%s) without enabled required app op: %d",
1449 operation, sensor.getName().string(), opCode);
1457 void SensorService::checkWakeLockState() {
1458 Mutex::Autolock _l(mLock);
1459 checkWakeLockStateLocked();
1462 void SensorService::checkWakeLockStateLocked() {
1463 if (!mWakeLockAcquired) {
1466 bool releaseLock = true;
1467 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1468 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1469 if (connection != 0) {
1470 if (connection->needsWakeLock()) {
1471 releaseLock = false;
1477 setWakeLockAcquiredLocked(false);
1481 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1482 Mutex::Autolock _l(mLock);
1483 connection->writeToSocketFromCache();
1484 if (connection->needsWakeLock()) {
1485 setWakeLockAcquiredLocked(true);
1489 void SensorService::populateActiveConnections(
1490 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1491 Mutex::Autolock _l(mLock);
1492 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1493 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1494 if (connection != 0) {
1495 activeConnections->add(connection);
1500 bool SensorService::isWhiteListedPackage(const String8& packageName) {
1501 return (packageName.contains(mWhiteListedPackage.string()));
1504 bool SensorService::isOperationRestricted(const String16& opPackageName) {
1505 Mutex::Autolock _l(mLock);
1506 if (mCurrentOperatingMode != RESTRICTED) {
1507 String8 package(opPackageName);
1508 return !isWhiteListedPackage(package);
1513 }; // namespace android