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>
25 #include <openssl/digest.h>
26 #include <openssl/hmac.h>
27 #include <openssl/rand.h>
28 #include <sensor/SensorEventQueue.h>
29 #include <utils/SystemClock.h>
31 #include "BatteryService.h"
32 #include "CorrectedGyroSensor.h"
33 #include "GravitySensor.h"
34 #include "LinearAccelerationSensor.h"
35 #include "OrientationSensor.h"
36 #include "RotationVectorSensor.h"
37 #include "SensorFusion.h"
38 #include "SensorInterface.h"
40 #include "SensorService.h"
41 #include "SensorDirectConnection.h"
42 #include "SensorEventAckReceiver.h"
43 #include "SensorEventConnection.h"
44 #include "SensorRecord.h"
45 #include "SensorRegistrationInfo.h"
51 #include <sys/socket.h>
53 #include <sys/types.h>
57 // ---------------------------------------------------------------------------
62 * - what about a gyro-corrected magnetic-field sensor?
63 * - run mag sensor from time to time to force calibration
64 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
68 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
69 uint8_t SensorService::sHmacGlobalKey[128] = {};
70 bool SensorService::sHmacGlobalKeyIsValid = false;
72 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
73 #define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
74 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
77 static const String16 sDumpPermission("android.permission.DUMP");
78 static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
80 SensorService::SensorService()
81 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
82 mWakeLockAcquired(false) {
85 bool SensorService::initializeHmacKey() {
86 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
88 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
90 if (result == sizeof(sHmacGlobalKey)) {
93 ALOGW("Unable to read HMAC key; generating new one.");
96 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
97 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
101 // We need to make sure this is only readable to us.
102 bool wroteKey = false;
103 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
104 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
107 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
109 wroteKey = (result == sizeof(sHmacGlobalKey));
112 ALOGI("Generated new HMAC key.");
114 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
117 // Even if we failed to write the key we return true, because we did
118 // initialize the HMAC key.
122 // Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
123 void SensorService::enableSchedFifoMode() {
124 struct sched_param param = {0};
125 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
126 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m) != 0) {
127 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
131 void SensorService::onFirstRef() {
132 ALOGD("nuSensorService starting...");
133 SensorDevice& dev(SensorDevice::getInstance());
135 sHmacGlobalKeyIsValid = initializeHmacKey();
137 if (dev.initCheck() == NO_ERROR) {
138 sensor_t const* list;
139 ssize_t count = dev.getSensorList(&list);
141 ssize_t orientationIndex = -1;
142 bool hasGyro = false, hasAccel = false, hasMag = false;
143 uint32_t virtualSensorsNeeds =
144 (1<<SENSOR_TYPE_GRAVITY) |
145 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
146 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
147 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
148 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
150 for (ssize_t i=0 ; i<count ; i++) {
151 bool useThisSensor=true;
153 switch (list[i].type) {
154 case SENSOR_TYPE_ACCELEROMETER:
157 case SENSOR_TYPE_MAGNETIC_FIELD:
160 case SENSOR_TYPE_ORIENTATION:
161 orientationIndex = i;
163 case SENSOR_TYPE_GYROSCOPE:
164 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
167 case SENSOR_TYPE_GRAVITY:
168 case SENSOR_TYPE_LINEAR_ACCELERATION:
169 case SENSOR_TYPE_ROTATION_VECTOR:
170 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
171 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
172 if (IGNORE_HARDWARE_FUSION) {
173 useThisSensor = false;
175 virtualSensorsNeeds &= ~(1<<list[i].type);
180 registerSensor( new HardwareSensor(list[i]) );
184 // it's safe to instantiate the SensorFusion object here
185 // (it wants to be instantiated after h/w sensors have been
187 SensorFusion::getInstance();
189 if (hasGyro && hasAccel && hasMag) {
190 // Add Android virtual sensors if they're not already
191 // available in the HAL
192 bool needRotationVector =
193 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
195 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
196 registerSensor(new OrientationSensor(), !needRotationVector, true);
198 bool needLinearAcceleration =
199 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
201 registerSensor(new LinearAccelerationSensor(list, count),
202 !needLinearAcceleration, true);
204 // virtual debugging sensors are not for user
205 registerSensor( new CorrectedGyroSensor(list, count), true, true);
206 registerSensor( new GyroDriftSensor(), true, true);
209 if (hasAccel && hasGyro) {
210 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
211 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
213 bool needGameRotationVector =
214 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
215 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
218 if (hasAccel && hasMag) {
219 bool needGeoMagRotationVector =
220 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
221 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
224 // Check if the device really supports batching by looking at the FIFO event
225 // counts for each sensor.
226 bool batchingSupported = false;
227 mSensors.forEachSensor(
228 [&batchingSupported] (const Sensor& s) -> bool {
229 if (s.getFifoMaxEventCount() > 0) {
230 batchingSupported = true;
232 return !batchingSupported;
235 if (batchingSupported) {
236 // Increase socket buffer size to a max of 100 KB for batching capabilities.
237 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
239 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
242 // Compare the socketBufferSize value against the system limits and limit
243 // it to maxSystemSocketBufferSize if necessary.
244 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
246 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
247 line[sizeof(line) - 1] = '\0';
248 size_t maxSystemSocketBufferSize;
249 sscanf(line, "%zu", &maxSystemSocketBufferSize);
250 if (mSocketBufferSize > maxSystemSocketBufferSize) {
251 mSocketBufferSize = maxSystemSocketBufferSize;
258 mWakeLockAcquired = false;
259 mLooper = new Looper(false);
260 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
261 mSensorEventBuffer = new sensors_event_t[minBufferSize];
262 mSensorEventScratch = new sensors_event_t[minBufferSize];
263 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
264 mCurrentOperatingMode = NORMAL;
266 mNextSensorRegIndex = 0;
267 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
268 mLastNSensorRegistrations.push();
271 mInitCheck = NO_ERROR;
272 mAckReceiver = new SensorEventAckReceiver(this);
273 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
274 run("SensorService", PRIORITY_URGENT_DISPLAY);
276 // priority can only be changed after run
277 enableSchedFifoMode();
282 const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
283 int handle = s->getSensor().getHandle();
284 int type = s->getSensor().getType();
285 if (mSensors.add(handle, s, isDebug, isVirtual)){
286 mRecentEvent.emplace(handle, new RecentEventLogger(type));
287 return s->getSensor();
289 return mSensors.getNonSensor();
293 const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
294 return registerSensor(s, isDebug);
297 bool SensorService::unregisterDynamicSensorLocked(int handle) {
298 bool ret = mSensors.remove(handle);
300 const auto i = mRecentEvent.find(handle);
301 if (i != mRecentEvent.end()) {
303 mRecentEvent.erase(i);
308 const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
309 return registerSensor(s, isDebug, true);
312 SensorService::~SensorService() {
313 for (auto && entry : mRecentEvent) {
318 status_t SensorService::dump(int fd, const Vector<String16>& args) {
320 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
321 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
322 IPCThreadState::self()->getCallingPid(),
323 IPCThreadState::self()->getCallingUid());
325 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
326 if (args.size() > 2) {
327 return INVALID_OPERATION;
329 Mutex::Autolock _l(mLock);
330 SensorDevice& dev(SensorDevice::getInstance());
331 if (args.size() == 2 && args[0] == String16("restrict")) {
332 // If already in restricted mode. Ignore.
333 if (mCurrentOperatingMode == RESTRICTED) {
334 return status_t(NO_ERROR);
336 // If in any mode other than normal, ignore.
337 if (mCurrentOperatingMode != NORMAL) {
338 return INVALID_OPERATION;
341 mCurrentOperatingMode = RESTRICTED;
342 // temporarily stop all sensor direct report
343 for (auto &i : mDirectConnections) {
344 sp<SensorDirectConnection> connection(i.promote());
345 if (connection != nullptr) {
346 connection->stopAll(true /* backupRecord */);
350 dev.disableAllSensors();
351 // Clear all pending flush connections for all active sensors. If one of the active
352 // connections has called flush() and the underlying sensor has been disabled before a
353 // flush complete event is returned, we need to remove the connection from this queue.
354 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
355 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
357 mWhiteListedPackage.setTo(String8(args[1]));
358 return status_t(NO_ERROR);
359 } else if (args.size() == 1 && args[0] == String16("enable")) {
360 // If currently in restricted mode, reset back to NORMAL mode else ignore.
361 if (mCurrentOperatingMode == RESTRICTED) {
362 mCurrentOperatingMode = NORMAL;
363 dev.enableAllSensors();
364 // recover all sensor direct report
365 for (auto &i : mDirectConnections) {
366 sp<SensorDirectConnection> connection(i.promote());
367 if (connection != nullptr) {
368 connection->recoverAll();
372 if (mCurrentOperatingMode == DATA_INJECTION) {
373 resetToNormalModeLocked();
375 mWhiteListedPackage.clear();
376 return status_t(NO_ERROR);
377 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
378 if (mCurrentOperatingMode == NORMAL) {
379 dev.disableAllSensors();
380 status_t err = dev.setMode(DATA_INJECTION);
381 if (err == NO_ERROR) {
382 mCurrentOperatingMode = DATA_INJECTION;
384 // Re-enable sensors.
385 dev.enableAllSensors();
387 mWhiteListedPackage.setTo(String8(args[1]));
389 } else if (mCurrentOperatingMode == DATA_INJECTION) {
390 // Already in DATA_INJECTION mode. Treat this as a no_op.
393 // Transition to data injection mode supported only from NORMAL mode.
394 return INVALID_OPERATION;
396 } else if (!mSensors.hasAnySensor()) {
397 result.append("No Sensors on the device\n");
398 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
400 // Default dump the sensor list and debugging information.
402 result.append("Sensor Device:\n");
403 result.append(SensorDevice::getInstance().dump().c_str());
405 result.append("Sensor List:\n");
406 result.append(mSensors.dump().c_str());
408 result.append("Fusion States:\n");
409 SensorFusion::getInstance().dump(result);
411 result.append("Recent Sensor events:\n");
412 for (auto&& i : mRecentEvent) {
413 sp<SensorInterface> s = mSensors.getInterface(i.first);
414 if (!i.second->isEmpty()) {
415 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
416 i.second->setFormat("normal");
418 i.second->setFormat("mask_data");
420 // if there is events and sensor does not need special permission.
421 result.appendFormat("%s: ", s->getSensor().getName().string());
422 result.append(i.second->dump().c_str());
426 result.append("Active sensors:\n");
427 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
428 int handle = mActiveSensors.keyAt(i);
429 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
430 getSensorName(handle).string(),
432 mActiveSensors.valueAt(i)->getNumConnections());
435 result.appendFormat("Socket Buffer size = %zd events\n",
436 mSocketBufferSize/sizeof(sensors_event_t));
437 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
439 result.appendFormat("Mode :");
440 switch(mCurrentOperatingMode) {
442 result.appendFormat(" NORMAL\n");
445 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
448 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
451 result.appendFormat("%zd active connections\n", mActiveConnections.size());
452 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
453 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
454 if (connection != 0) {
455 result.appendFormat("Connection Number: %zu \n", i);
456 connection->dump(result);
460 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
461 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
462 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
463 if (connection != nullptr) {
464 result.appendFormat("Direct connection %zu:\n", i);
465 connection->dump(result);
469 result.appendFormat("Previous Registrations:\n");
470 // Log in the reverse chronological order.
471 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
472 SENSOR_REGISTRATIONS_BUF_SIZE;
473 const int startIndex = currentIndex;
475 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
476 if (SensorRegistrationInfo::isSentinel(reg_info)) {
477 // Ignore sentinel, proceed to next item.
478 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
479 SENSOR_REGISTRATIONS_BUF_SIZE;
482 result.appendFormat("%s\n", reg_info.dump().c_str());
483 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
484 SENSOR_REGISTRATIONS_BUF_SIZE;
485 } while(startIndex != currentIndex);
488 write(fd, result.string(), result.size());
492 //TODO: move to SensorEventConnection later
493 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
494 sensors_event_t const* buffer, const int count) {
495 for (int i=0 ; i<count ; i++) {
496 int handle = buffer[i].sensor;
497 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
498 handle = buffer[i].meta_data.sensor;
500 if (connection->hasSensor(handle)) {
501 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
502 // If this buffer has an event from a one_shot sensor and this connection is registered
503 // for this particular one_shot sensor, try cleaning up the connection.
505 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
506 si->autoDisable(connection.get(), handle);
507 cleanupWithoutDisableLocked(connection, handle);
514 bool SensorService::threadLoop() {
515 ALOGD("nuSensorService thread starting...");
517 // each virtual sensor could generate an event per "real" event, that's why we need to size
518 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
519 // aggressive, but guaranteed to be enough.
520 const size_t vcount = mSensors.getVirtualSensors().size();
521 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
522 const size_t numEventMax = minBufferSize / (1 + vcount);
524 SensorDevice& device(SensorDevice::getInstance());
526 const int halVersion = device.getHalDeviceVersion();
528 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
530 ALOGE("sensor poll failed (%s)", strerror(-count));
534 // Reset sensors_event_t.flags to zero for all events in the buffer.
535 for (int i = 0; i < count; i++) {
536 mSensorEventBuffer[i].flags = 0;
539 // Make a copy of the connection vector as some connections may be removed during the course
540 // of this loop (especially when one-shot sensor events are present in the sensor_event
541 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
542 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
543 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
544 // strongPointers to a vector before the lock is acquired.
545 SortedVector< sp<SensorEventConnection> > activeConnections;
546 populateActiveConnections(&activeConnections);
548 Mutex::Autolock _l(mLock);
549 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
550 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
551 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
552 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
553 // releasing the wakelock.
554 bool bufferHasWakeUpEvent = false;
555 for (int i = 0; i < count; i++) {
556 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
557 bufferHasWakeUpEvent = true;
562 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
563 setWakeLockAcquiredLocked(true);
565 recordLastValueLocked(mSensorEventBuffer, count);
567 // handle virtual sensors
568 if (count && vcount) {
569 sensors_event_t const * const event = mSensorEventBuffer;
570 if (!mActiveVirtualSensors.empty()) {
572 SensorFusion& fusion(SensorFusion::getInstance());
573 if (fusion.isEnabled()) {
574 for (size_t i=0 ; i<size_t(count) ; i++) {
575 fusion.process(event[i]);
578 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
579 for (int handle : mActiveVirtualSensors) {
580 if (count + k >= minBufferSize) {
581 ALOGE("buffer too small to hold all events: "
582 "count=%zd, k=%zu, size=%zu",
583 count, k, minBufferSize);
587 sp<SensorInterface> si = mSensors.getInterface(handle);
589 ALOGE("handle %d is not an valid virtual sensor", handle);
593 if (si->process(&out, event[i])) {
594 mSensorEventBuffer[count + k] = out;
600 // record the last synthesized values
601 recordLastValueLocked(&mSensorEventBuffer[count], k);
603 // sort the buffer by time-stamps
604 sortEventBuffer(mSensorEventBuffer, count);
609 // handle backward compatibility for RotationVector sensor
610 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
611 for (int i = 0; i < count; i++) {
612 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
613 // All the 4 components of the quaternion should be available
614 // No heading accuracy. Set it to -1
615 mSensorEventBuffer[i].data[4] = -1;
620 for (int i = 0; i < count; ++i) {
621 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
622 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
623 // SensorEventConnection mapped to the corresponding flush_complete_event in
624 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
625 mMapFlushEventsToConnections[i] = NULL;
626 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
627 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
628 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
630 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
631 rec->removeFirstPendingFlushConnection();
635 // handle dynamic sensor meta events, process registration and unregistration of dynamic
636 // sensor based on content of event.
637 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
638 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
639 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
640 const sensor_t& dynamicSensor =
641 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
642 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
643 handle, dynamicSensor.type, dynamicSensor.name);
645 if (mSensors.isNewHandle(handle)) {
646 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
647 sensor_t s = dynamicSensor;
648 // make sure the dynamic sensor flag is set
649 s.flags |= DYNAMIC_SENSOR_MASK;
650 // force the handle to be consistent
653 SensorInterface *si = new HardwareSensor(s, uuid);
655 // This will release hold on dynamic sensor meta, so it should be called
656 // after Sensor object is created.
657 device.handleDynamicSensorConnection(handle, true /*connected*/);
658 registerDynamicSensorLocked(si);
660 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
663 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
664 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
666 device.handleDynamicSensorConnection(handle, false /*connected*/);
667 if (!unregisterDynamicSensorLocked(handle)) {
668 ALOGE("Dynamic sensor release error.");
671 size_t numConnections = activeConnections.size();
672 for (size_t i=0 ; i < numConnections; ++i) {
673 if (activeConnections[i] != NULL) {
674 activeConnections[i]->removeSensor(handle);
682 // Send our events to clients. Check the state of wake lock for each client and release the
683 // lock if none of the clients need it.
684 bool needsWakeLock = false;
685 size_t numConnections = activeConnections.size();
686 for (size_t i=0 ; i < numConnections; ++i) {
687 if (activeConnections[i] != 0) {
688 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
689 mMapFlushEventsToConnections);
690 needsWakeLock |= activeConnections[i]->needsWakeLock();
691 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
692 // Early check for one-shot sensors.
693 if (activeConnections[i]->hasOneShotSensors()) {
694 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
700 if (mWakeLockAcquired && !needsWakeLock) {
701 setWakeLockAcquiredLocked(false);
703 } while (!Thread::exitPending());
705 ALOGW("Exiting SensorService::threadLoop => aborting...");
710 sp<Looper> SensorService::getLooper() const {
714 void SensorService::resetAllWakeLockRefCounts() {
715 SortedVector< sp<SensorEventConnection> > activeConnections;
716 populateActiveConnections(&activeConnections);
718 Mutex::Autolock _l(mLock);
719 for (size_t i=0 ; i < activeConnections.size(); ++i) {
720 if (activeConnections[i] != 0) {
721 activeConnections[i]->resetWakeLockRefCount();
724 setWakeLockAcquiredLocked(false);
728 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
730 if (!mWakeLockAcquired) {
731 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
732 mWakeLockAcquired = true;
736 if (mWakeLockAcquired) {
737 release_wake_lock(WAKE_LOCK_NAME);
738 mWakeLockAcquired = false;
743 bool SensorService::isWakeLockAcquired() {
744 Mutex::Autolock _l(mLock);
745 return mWakeLockAcquired;
748 bool SensorService::SensorEventAckReceiver::threadLoop() {
749 ALOGD("new thread SensorEventAckReceiver");
750 sp<Looper> looper = mService->getLooper();
752 bool wakeLockAcquired = mService->isWakeLockAcquired();
754 if (wakeLockAcquired) timeout = 5000;
755 int ret = looper->pollOnce(timeout);
756 if (ret == ALOOPER_POLL_TIMEOUT) {
757 mService->resetAllWakeLockRefCounts();
759 } while(!Thread::exitPending());
763 void SensorService::recordLastValueLocked(
764 const sensors_event_t* buffer, size_t count) {
765 for (size_t i = 0; i < count; i++) {
766 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
767 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
768 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
772 auto logger = mRecentEvent.find(buffer[i].sensor);
773 if (logger != mRecentEvent.end()) {
774 logger->second->addEvent(buffer[i]);
779 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
781 static int cmp(void const* lhs, void const* rhs) {
782 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
783 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
784 return l->timestamp - r->timestamp;
787 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
790 String8 SensorService::getSensorName(int handle) const {
791 return mSensors.getName(handle);
794 bool SensorService::isVirtualSensor(int handle) const {
795 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
796 return sensor != nullptr && sensor->isVirtual();
799 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
800 int handle = event.sensor;
801 if (event.type == SENSOR_TYPE_META_DATA) {
802 handle = event.meta_data.sensor;
804 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
805 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
808 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
809 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
810 // UUID is not supported for this device.
813 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
814 // This sensor can be uniquely identified in the system by
815 // the combination of its type and name.
819 // We have a dynamic sensor.
821 if (!sHmacGlobalKeyIsValid) {
822 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
823 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
827 // We want each app author/publisher to get a different ID, so that the
828 // same dynamic sensor cannot be tracked across apps by multiple
829 // authors/publishers. So we use both our UUID and our User ID.
830 // Note potential confusion:
831 // UUID => Universally Unique Identifier.
832 // UID => User Identifier.
833 // We refrain from using "uid" except as needed by API to try to
834 // keep this distinction clear.
836 auto appUserId = IPCThreadState::self()->getCallingUid();
837 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
838 memcpy(uuidAndApp, &uuid, sizeof(uuid));
839 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
841 // Now we use our key on our UUID/app combo to get the hash.
842 uint8_t hash[EVP_MAX_MD_SIZE];
843 unsigned int hashLen;
844 if (HMAC(EVP_sha256(),
845 sHmacGlobalKey, sizeof(sHmacGlobalKey),
846 uuidAndApp, sizeof(uuidAndApp),
847 hash, &hashLen) == nullptr) {
848 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
849 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
854 if (hashLen < sizeof(id)) {
855 // We never expect this case, but out of paranoia, we handle it.
856 // Our 'id' length is already quite small, we don't want the
857 // effective length of it to be even smaller.
858 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
859 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
863 // This is almost certainly less than all of 'hash', but it's as secure
864 // as we can be with our current 'id' length.
865 memcpy(&id, hash, sizeof(id));
867 // Note at the beginning of the function that we return the values of
868 // 0 and -1 to represent special cases. As a result, we can't return
869 // those as dynamic sensor IDs. If we happened to hash to one of those
870 // values, we change 'id' so we report as a dynamic sensor, and not as
871 // one of those special cases.
874 } else if (id == 0) {
880 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
881 for (auto &sensor : sensorList) {
882 int32_t id = getIdFromUuid(sensor.getUuid());
887 Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
888 char value[PROPERTY_VALUE_MAX];
889 property_get("debug.sensors", value, "0");
890 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
891 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
892 Vector<Sensor> accessibleSensorList;
893 for (size_t i = 0; i < initialSensorList.size(); i++) {
894 Sensor sensor = initialSensorList[i];
895 accessibleSensorList.add(sensor);
897 makeUuidsIntoIdsForSensorList(accessibleSensorList);
898 return accessibleSensorList;
901 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
902 Vector<Sensor> accessibleSensorList;
903 mSensors.forEachSensor(
904 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
905 if (sensor.isDynamicSensor()) {
906 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
907 accessibleSensorList.add(sensor);
909 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
910 sensor.getName().string(),
911 sensor.getRequiredPermission().string(),
912 sensor.getRequiredAppOp());
917 makeUuidsIntoIdsForSensorList(accessibleSensorList);
918 return accessibleSensorList;
921 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
922 int requestedMode, const String16& opPackageName) {
923 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
924 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
928 Mutex::Autolock _l(mLock);
929 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
930 // operating in DI mode.
931 if (requestedMode == DATA_INJECTION) {
932 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
933 if (!isWhiteListedPackage(packageName)) return NULL;
936 uid_t uid = IPCThreadState::self()->getCallingUid();
937 pid_t pid = IPCThreadState::self()->getCallingPid();
939 String8 connPackageName =
940 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
941 String16 connOpPackageName =
942 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
943 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
944 requestedMode == DATA_INJECTION, connOpPackageName));
945 if (requestedMode == DATA_INJECTION) {
946 if (mActiveConnections.indexOf(result) < 0) {
947 mActiveConnections.add(result);
949 // Add the associated file descriptor to the Looper for polling whenever there is data to
951 result->updateLooperRegistration(mLooper);
956 int SensorService::isDataInjectionEnabled() {
957 Mutex::Autolock _l(mLock);
958 return (mCurrentOperatingMode == DATA_INJECTION);
961 sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
962 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
963 const native_handle *resource) {
964 Mutex::Autolock _l(mLock);
966 struct sensors_direct_mem_t mem = {
972 uid_t uid = IPCThreadState::self()->getCallingUid();
974 if (mem.handle == nullptr) {
975 ALOGE("Failed to clone resource handle");
980 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
981 ALOGE("Direct channel format %d is unsupported!", format);
985 // check for duplication
986 for (auto &i : mDirectConnections) {
987 sp<SensorDirectConnection> connection(i.promote());
988 if (connection != nullptr && connection->isEquivalent(&mem)) {
989 ALOGE("Duplicate create channel request for the same share memory");
994 // check specific to memory type
996 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
997 if (resource->numFds < 1) {
998 ALOGE("Ashmem direct channel requires a memory region to be supplied");
999 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1002 int fd = resource->data[0];
1003 int size2 = ashmem_get_size_region(fd);
1004 // check size consistency
1005 if (size2 < static_cast<int64_t>(size)) {
1006 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1012 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1013 // no specific checks for gralloc
1016 ALOGE("Unknown direct connection memory type %d", type);
1020 native_handle_t *clone = native_handle_clone(resource);
1025 SensorDirectConnection* conn = nullptr;
1026 SensorDevice& dev(SensorDevice::getInstance());
1027 int channelHandle = dev.registerDirectChannel(&mem);
1029 if (channelHandle <= 0) {
1030 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1033 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1036 if (conn == nullptr) {
1037 native_handle_close(clone);
1038 native_handle_delete(clone);
1040 // add to list of direct connections
1041 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1042 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1047 int SensorService::setOperationParameter(
1048 int32_t handle, int32_t type,
1049 const Vector<float> &floats, const Vector<int32_t> &ints) {
1050 Mutex::Autolock _l(mLock);
1052 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
1053 return PERMISSION_DENIED;
1056 bool isFloat = true;
1057 bool isCustom = false;
1058 size_t expectSize = INT32_MAX;
1060 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1064 case AINFO_LOCAL_GRAVITY:
1068 case AINFO_DOCK_STATE:
1069 case AINFO_HIGH_PERFORMANCE_MODE:
1070 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1075 // CUSTOM events must only contain float data; it may have variable size
1076 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1078 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1084 expectSize = floats.size();
1088 if (!isCustom && handle != -1) {
1092 // three events: first one is begin tag, last one is end tag, the one in the middle
1094 sensors_event_t event[3];
1095 int64_t timestamp = elapsedRealtimeNano();
1096 for (sensors_event_t* i = event; i < event + 3; i++) {
1097 *i = (sensors_event_t) {
1098 .version = sizeof(sensors_event_t),
1100 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1101 .timestamp = timestamp++,
1102 .additional_info = (additional_info_event_t) {
1108 event[0].additional_info.type = AINFO_BEGIN;
1109 event[1].additional_info.type = type;
1110 event[2].additional_info.type = AINFO_END;
1113 if (floats.size() != expectSize) {
1116 for (size_t i = 0; i < expectSize; ++i) {
1117 event[1].additional_info.data_float[i] = floats[i];
1120 if (ints.size() != expectSize) {
1123 for (size_t i = 0; i < expectSize; ++i) {
1124 event[1].additional_info.data_int32[i] = ints[i];
1128 SensorDevice& dev(SensorDevice::getInstance());
1129 for (sensors_event_t* i = event; i < event + 3; i++) {
1130 int ret = dev.injectSensorData(i);
1131 if (ret != NO_ERROR) {
1138 status_t SensorService::resetToNormalMode() {
1139 Mutex::Autolock _l(mLock);
1140 return resetToNormalModeLocked();
1143 status_t SensorService::resetToNormalModeLocked() {
1144 SensorDevice& dev(SensorDevice::getInstance());
1145 status_t err = dev.setMode(NORMAL);
1146 if (err == NO_ERROR) {
1147 mCurrentOperatingMode = NORMAL;
1148 dev.enableAllSensors();
1153 void SensorService::cleanupConnection(SensorEventConnection* c) {
1154 Mutex::Autolock _l(mLock);
1155 const wp<SensorEventConnection> connection(c);
1156 size_t size = mActiveSensors.size();
1157 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
1158 for (size_t i=0 ; i<size ; ) {
1159 int handle = mActiveSensors.keyAt(i);
1160 if (c->hasSensor(handle)) {
1161 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
1162 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1163 if (sensor != nullptr) {
1164 sensor->activate(c, false);
1166 ALOGE("sensor interface of handle=0x%08x is null!", handle);
1168 c->removeSensor(handle);
1170 SensorRecord* rec = mActiveSensors.valueAt(i);
1171 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
1172 ALOGD_IF(DEBUG_CONNECTIONS,
1173 "removing connection %p for sensor[%zu].handle=0x%08x",
1176 if (rec && rec->removeConnection(connection)) {
1177 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
1178 mActiveSensors.removeItemsAt(i, 1);
1179 mActiveVirtualSensors.erase(handle);
1186 c->updateLooperRegistration(mLooper);
1187 mActiveConnections.remove(connection);
1188 BatteryService::cleanup(c->getUid());
1189 if (c->needsWakeLock()) {
1190 checkWakeLockStateLocked();
1193 SensorDevice& dev(SensorDevice::getInstance());
1194 dev.notifyConnectionDestroyed(c);
1197 void SensorService::cleanupConnection(SensorDirectConnection* c) {
1198 Mutex::Autolock _l(mLock);
1200 SensorDevice& dev(SensorDevice::getInstance());
1201 dev.unregisterDirectChannel(c->getHalChannelHandle());
1202 mDirectConnections.remove(c);
1205 sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
1206 return mSensors.getInterface(handle);
1209 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
1210 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
1211 const String16& opPackageName) {
1212 if (mInitCheck != NO_ERROR)
1215 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1216 if (sensor == nullptr ||
1217 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
1221 Mutex::Autolock _l(mLock);
1222 if (mCurrentOperatingMode != NORMAL
1223 && !isWhiteListedPackage(connection->getPackageName())) {
1224 return INVALID_OPERATION;
1227 SensorRecord* rec = mActiveSensors.valueFor(handle);
1229 rec = new SensorRecord(connection);
1230 mActiveSensors.add(handle, rec);
1231 if (sensor->isVirtual()) {
1232 mActiveVirtualSensors.emplace(handle);
1235 if (rec->addConnection(connection)) {
1236 // this sensor is already activated, but we are adding a connection that uses it.
1237 // Immediately send down the last known value of the requested sensor if it's not a
1238 // "continuous" sensor.
1239 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1240 // NOTE: The wake_up flag of this event may get set to
1241 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
1243 auto logger = mRecentEvent.find(handle);
1244 if (logger != mRecentEvent.end()) {
1245 sensors_event_t event;
1246 // It is unlikely that this buffer is empty as the sensor is already active.
1247 // One possible corner case may be two applications activating an on-change
1248 // sensor at the same time.
1249 if(logger->second->populateLastEvent(&event)) {
1250 event.sensor = handle;
1251 if (event.version == sizeof(sensors_event_t)) {
1252 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1253 setWakeLockAcquiredLocked(true);
1255 connection->sendEvents(&event, 1, NULL);
1256 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1257 checkWakeLockStateLocked();
1266 if (connection->addSensor(handle)) {
1267 BatteryService::enableSensor(connection->getUid(), handle);
1268 // the sensor was added (which means it wasn't already there)
1269 // so, see if this connection becomes active
1270 if (mActiveConnections.indexOf(connection) < 0) {
1271 mActiveConnections.add(connection);
1274 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1275 handle, connection.get());
1278 // Check maximum delay for the sensor.
1279 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
1280 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1281 samplingPeriodNs = maxDelayNs;
1284 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1285 if (samplingPeriodNs < minDelayNs) {
1286 samplingPeriodNs = minDelayNs;
1289 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1290 "rate=%" PRId64 " timeout== %" PRId64"",
1291 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1293 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
1294 maxBatchReportLatencyNs);
1296 // Call flush() before calling activate() on the sensor. Wait for a first
1297 // flush complete event before sending events on this connection. Ignore
1298 // one-shot sensors which don't support flush(). Ignore on-change sensors
1299 // to maintain the on-change logic (any on-change events except the initial
1300 // one should be trigger by a change in value). Also if this sensor isn't
1301 // already active, don't call flush().
1302 if (err == NO_ERROR &&
1303 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
1304 rec->getNumConnections() > 1) {
1305 connection->setFirstFlushPending(handle, true);
1306 status_t err_flush = sensor->flush(connection.get(), handle);
1307 // Flush may return error if the underlying h/w sensor uses an older HAL.
1308 if (err_flush == NO_ERROR) {
1309 rec->addPendingFlushConnection(connection.get());
1311 connection->setFirstFlushPending(handle, false);
1315 if (err == NO_ERROR) {
1316 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1317 err = sensor->activate(connection.get(), true);
1320 if (err == NO_ERROR) {
1321 connection->updateLooperRegistration(mLooper);
1323 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1324 SensorRegistrationInfo(handle, connection->getPackageName(),
1325 samplingPeriodNs, maxBatchReportLatencyNs, true);
1326 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1329 if (err != NO_ERROR) {
1330 // batch/activate has failed, reset our state.
1331 cleanupWithoutDisableLocked(connection, handle);
1336 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
1337 if (mInitCheck != NO_ERROR)
1340 Mutex::Autolock _l(mLock);
1341 status_t err = cleanupWithoutDisableLocked(connection, handle);
1342 if (err == NO_ERROR) {
1343 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1344 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
1347 if (err == NO_ERROR) {
1348 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1349 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
1350 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1355 status_t SensorService::cleanupWithoutDisable(
1356 const sp<SensorEventConnection>& connection, int handle) {
1357 Mutex::Autolock _l(mLock);
1358 return cleanupWithoutDisableLocked(connection, handle);
1361 status_t SensorService::cleanupWithoutDisableLocked(
1362 const sp<SensorEventConnection>& connection, int handle) {
1363 SensorRecord* rec = mActiveSensors.valueFor(handle);
1365 // see if this connection becomes inactive
1366 if (connection->removeSensor(handle)) {
1367 BatteryService::disableSensor(connection->getUid(), handle);
1369 if (connection->hasAnySensor() == false) {
1370 connection->updateLooperRegistration(mLooper);
1371 mActiveConnections.remove(connection);
1373 // see if this sensor becomes inactive
1374 if (rec->removeConnection(connection)) {
1375 mActiveSensors.removeItem(handle);
1376 mActiveVirtualSensors.erase(handle);
1384 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1385 int handle, nsecs_t ns, const String16& opPackageName) {
1386 if (mInitCheck != NO_ERROR)
1389 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1390 if (sensor == nullptr ||
1391 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1398 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1399 if (ns < minDelayNs) {
1403 return sensor->setDelay(connection.get(), handle, ns);
1406 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1407 const String16& opPackageName) {
1408 if (mInitCheck != NO_ERROR) return mInitCheck;
1409 SensorDevice& dev(SensorDevice::getInstance());
1410 const int halVersion = dev.getHalDeviceVersion();
1411 status_t err(NO_ERROR);
1412 Mutex::Autolock _l(mLock);
1413 // Loop through all sensors for this connection and call flush on each of them.
1414 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1415 const int handle = connection->mSensorInfo.keyAt(i);
1416 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1417 if (sensor == nullptr) {
1420 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1421 ALOGE("flush called on a one-shot sensor");
1422 err = INVALID_OPERATION;
1425 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1426 // For older devices just increment pending flush count which will send a trivial
1427 // flush complete event.
1428 connection->incrementPendingFlushCount(handle);
1430 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1431 err = INVALID_OPERATION;
1434 status_t err_flush = sensor->flush(connection.get(), handle);
1435 if (err_flush == NO_ERROR) {
1436 SensorRecord* rec = mActiveSensors.valueFor(handle);
1437 if (rec != NULL) rec->addPendingFlushConnection(connection);
1439 err = (err_flush != NO_ERROR) ? err_flush : err;
1445 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1446 const String16& opPackageName) {
1447 const String8& requiredPermission = sensor.getRequiredPermission();
1449 if (requiredPermission.length() <= 0) {
1453 bool hasPermission = false;
1455 // Runtime permissions can't use the cache as they may change.
1456 if (sensor.isRequiredPermissionRuntime()) {
1457 hasPermission = checkPermission(String16(requiredPermission),
1458 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1460 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1463 if (!hasPermission) {
1464 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1465 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1469 const int32_t opCode = sensor.getRequiredAppOp();
1471 AppOpsManager appOps;
1472 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1473 != AppOpsManager::MODE_ALLOWED) {
1474 ALOGE("%s a sensor (%s) without enabled required app op: %d",
1475 operation, sensor.getName().string(), opCode);
1483 void SensorService::checkWakeLockState() {
1484 Mutex::Autolock _l(mLock);
1485 checkWakeLockStateLocked();
1488 void SensorService::checkWakeLockStateLocked() {
1489 if (!mWakeLockAcquired) {
1492 bool releaseLock = true;
1493 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1494 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1495 if (connection != 0) {
1496 if (connection->needsWakeLock()) {
1497 releaseLock = false;
1503 setWakeLockAcquiredLocked(false);
1507 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1508 Mutex::Autolock _l(mLock);
1509 connection->writeToSocketFromCache();
1510 if (connection->needsWakeLock()) {
1511 setWakeLockAcquiredLocked(true);
1515 void SensorService::populateActiveConnections(
1516 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1517 Mutex::Autolock _l(mLock);
1518 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1519 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1520 if (connection != 0) {
1521 activeConnections->add(connection);
1526 bool SensorService::isWhiteListedPackage(const String8& packageName) {
1527 return (packageName.contains(mWhiteListedPackage.string()));
1530 bool SensorService::isOperationRestricted(const String16& opPackageName) {
1531 Mutex::Autolock _l(mLock);
1532 if (mCurrentOperatingMode != RESTRICTED) {
1533 String8 package(opPackageName);
1534 return !isWhiteListedPackage(package);
1539 }; // namespace android