SensorService.cpp revision 6a2d3a06caa337857cf60cfc70a9a78909ad3608
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <cutils/properties.h> 18 19#include <binder/AppOpsManager.h> 20#include <binder/BinderService.h> 21#include <binder/IServiceManager.h> 22#include <binder/PermissionCache.h> 23 24#include <gui/SensorEventQueue.h> 25 26#include <hardware/sensors.h> 27#include <hardware_legacy/power.h> 28 29#include "BatteryService.h" 30#include "CorrectedGyroSensor.h" 31#include "GravitySensor.h" 32#include "LinearAccelerationSensor.h" 33#include "OrientationSensor.h" 34#include "RotationVectorSensor.h" 35#include "SensorFusion.h" 36#include "SensorInterface.h" 37 38#include "SensorService.h" 39#include "SensorEventAckReceiver.h" 40#include "SensorEventConnection.h" 41#include "SensorRecord.h" 42#include "SensorRegistrationInfo.h" 43 44#include <inttypes.h> 45#include <math.h> 46#include <stdint.h> 47#include <sys/types.h> 48#include <sys/socket.h> 49 50namespace android { 51// --------------------------------------------------------------------------- 52 53/* 54 * Notes: 55 * 56 * - what about a gyro-corrected magnetic-field sensor? 57 * - run mag sensor from time to time to force calibration 58 * - gravity sensor length is wrong (=> drift in linear-acc sensor) 59 * 60 */ 61 62const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock"; 63// Permissions. 64static const String16 sDump("android.permission.DUMP"); 65 66SensorService::SensorService() 67 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED), 68 mWakeLockAcquired(false) { 69} 70 71void SensorService::onFirstRef() { 72 ALOGD("nuSensorService starting..."); 73 SensorDevice& dev(SensorDevice::getInstance()); 74 75 if (dev.initCheck() == NO_ERROR) { 76 sensor_t const* list; 77 ssize_t count = dev.getSensorList(&list); 78 if (count > 0) { 79 ssize_t orientationIndex = -1; 80 bool hasGyro = false, hasAccel = false, hasMag = false; 81 uint32_t virtualSensorsNeeds = 82 (1<<SENSOR_TYPE_GRAVITY) | 83 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) | 84 (1<<SENSOR_TYPE_ROTATION_VECTOR) | 85 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) | 86 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR); 87 88 for (ssize_t i=0 ; i<count ; i++) { 89 bool useThisSensor=true; 90 91 switch (list[i].type) { 92 case SENSOR_TYPE_ACCELEROMETER: 93 hasAccel = true; 94 break; 95 case SENSOR_TYPE_MAGNETIC_FIELD: 96 hasMag = true; 97 break; 98 case SENSOR_TYPE_ORIENTATION: 99 orientationIndex = i; 100 break; 101 case SENSOR_TYPE_GYROSCOPE: 102 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 103 hasGyro = true; 104 break; 105 case SENSOR_TYPE_GRAVITY: 106 case SENSOR_TYPE_LINEAR_ACCELERATION: 107 case SENSOR_TYPE_ROTATION_VECTOR: 108 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR: 109 case SENSOR_TYPE_GAME_ROTATION_VECTOR: 110 if (IGNORE_HARDWARE_FUSION) { 111 useThisSensor = false; 112 } else { 113 virtualSensorsNeeds &= ~(1<<list[i].type); 114 } 115 break; 116 } 117 if (useThisSensor) { 118 registerSensor( new HardwareSensor(list[i]) ); 119 } 120 } 121 122 // it's safe to instantiate the SensorFusion object here 123 // (it wants to be instantiated after h/w sensors have been 124 // registered) 125 SensorFusion::getInstance(); 126 127 if (hasGyro && hasAccel && hasMag) { 128 // Add Android virtual sensors if they're not already 129 // available in the HAL 130 bool needRotationVector = 131 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0; 132 133 registerSensor(new RotationVectorSensor(), !needRotationVector, true); 134 registerSensor(new OrientationSensor(), !needRotationVector, true); 135 136 bool needLinearAcceleration = 137 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0; 138 139 registerSensor(new LinearAccelerationSensor(list, count), 140 !needLinearAcceleration, true); 141 142 // virtual debugging sensors are not for user 143 registerSensor( new CorrectedGyroSensor(list, count), true, true); 144 registerSensor( new GyroDriftSensor(), true, true); 145 } 146 147 if (hasAccel && hasGyro) { 148 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0; 149 registerSensor(new GravitySensor(list, count), !needGravitySensor, true); 150 151 bool needGameRotationVector = 152 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0; 153 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true); 154 } 155 156 if (hasAccel && hasMag) { 157 bool needGeoMagRotationVector = 158 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0; 159 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true); 160 } 161 162 // Check if the device really supports batching by looking at the FIFO event 163 // counts for each sensor. 164 bool batchingSupported = false; 165 mSensors.forEachSensor( 166 [&batchingSupported] (const Sensor& s) -> bool { 167 if (s.getFifoMaxEventCount() > 0) { 168 batchingSupported = true; 169 } 170 return !batchingSupported; 171 }); 172 173 if (batchingSupported) { 174 // Increase socket buffer size to a max of 100 KB for batching capabilities. 175 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED; 176 } else { 177 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED; 178 } 179 180 // Compare the socketBufferSize value against the system limits and limit 181 // it to maxSystemSocketBufferSize if necessary. 182 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r"); 183 char line[128]; 184 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) { 185 line[sizeof(line) - 1] = '\0'; 186 size_t maxSystemSocketBufferSize; 187 sscanf(line, "%zu", &maxSystemSocketBufferSize); 188 if (mSocketBufferSize > maxSystemSocketBufferSize) { 189 mSocketBufferSize = maxSystemSocketBufferSize; 190 } 191 } 192 if (fp) { 193 fclose(fp); 194 } 195 196 mWakeLockAcquired = false; 197 mLooper = new Looper(false); 198 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 199 mSensorEventBuffer = new sensors_event_t[minBufferSize]; 200 mSensorEventScratch = new sensors_event_t[minBufferSize]; 201 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize]; 202 mCurrentOperatingMode = NORMAL; 203 204 mNextSensorRegIndex = 0; 205 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) { 206 mLastNSensorRegistrations.push(); 207 } 208 209 mInitCheck = NO_ERROR; 210 mAckReceiver = new SensorEventAckReceiver(this); 211 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY); 212 run("SensorService", PRIORITY_URGENT_DISPLAY); 213 } 214 } 215} 216 217const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) { 218 int handle = s->getSensor().getHandle(); 219 int type = s->getSensor().getType(); 220 if (mSensors.add(handle, s, isDebug, isVirtual)){ 221 mRecentEvent.emplace(handle, new RecentEventLogger(type)); 222 return s->getSensor(); 223 } else { 224 return mSensors.getNonSensor(); 225 } 226} 227 228const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) { 229 return registerSensor(s, isDebug); 230} 231 232bool SensorService::unregisterDynamicSensorLocked(int handle) { 233 bool ret = mSensors.remove(handle); 234 235 const auto i = mRecentEvent.find(handle); 236 if (i != mRecentEvent.end()) { 237 delete i->second; 238 mRecentEvent.erase(i); 239 } 240 return ret; 241} 242 243const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) { 244 return registerSensor(s, isDebug, true); 245} 246 247SensorService::~SensorService() { 248 for (auto && entry : mRecentEvent) { 249 delete entry.second; 250 } 251} 252 253status_t SensorService::dump(int fd, const Vector<String16>& args) { 254 String8 result; 255 if (!PermissionCache::checkCallingPermission(sDump)) { 256 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n", 257 IPCThreadState::self()->getCallingPid(), 258 IPCThreadState::self()->getCallingUid()); 259 } else { 260 if (args.size() > 2) { 261 return INVALID_OPERATION; 262 } 263 Mutex::Autolock _l(mLock); 264 SensorDevice& dev(SensorDevice::getInstance()); 265 if (args.size() == 2 && args[0] == String16("restrict")) { 266 // If already in restricted mode. Ignore. 267 if (mCurrentOperatingMode == RESTRICTED) { 268 return status_t(NO_ERROR); 269 } 270 // If in any mode other than normal, ignore. 271 if (mCurrentOperatingMode != NORMAL) { 272 return INVALID_OPERATION; 273 } 274 mCurrentOperatingMode = RESTRICTED; 275 dev.disableAllSensors(); 276 // Clear all pending flush connections for all active sensors. If one of the active 277 // connections has called flush() and the underlying sensor has been disabled before a 278 // flush complete event is returned, we need to remove the connection from this queue. 279 for (size_t i=0 ; i< mActiveSensors.size(); ++i) { 280 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections(); 281 } 282 mWhiteListedPackage.setTo(String8(args[1])); 283 return status_t(NO_ERROR); 284 } else if (args.size() == 1 && args[0] == String16("enable")) { 285 // If currently in restricted mode, reset back to NORMAL mode else ignore. 286 if (mCurrentOperatingMode == RESTRICTED) { 287 mCurrentOperatingMode = NORMAL; 288 dev.enableAllSensors(); 289 } 290 if (mCurrentOperatingMode == DATA_INJECTION) { 291 resetToNormalModeLocked(); 292 } 293 mWhiteListedPackage.clear(); 294 return status_t(NO_ERROR); 295 } else if (args.size() == 2 && args[0] == String16("data_injection")) { 296 if (mCurrentOperatingMode == NORMAL) { 297 dev.disableAllSensors(); 298 status_t err = dev.setMode(DATA_INJECTION); 299 if (err == NO_ERROR) { 300 mCurrentOperatingMode = DATA_INJECTION; 301 } else { 302 // Re-enable sensors. 303 dev.enableAllSensors(); 304 } 305 mWhiteListedPackage.setTo(String8(args[1])); 306 return NO_ERROR; 307 } else if (mCurrentOperatingMode == DATA_INJECTION) { 308 // Already in DATA_INJECTION mode. Treat this as a no_op. 309 return NO_ERROR; 310 } else { 311 // Transition to data injection mode supported only from NORMAL mode. 312 return INVALID_OPERATION; 313 } 314 } else if (!mSensors.hasAnySensor()) { 315 result.append("No Sensors on the device\n"); 316 } else { 317 // Default dump the sensor list and debugging information. 318 // 319 result.append("Sensor Device:\n"); 320 result.append(SensorDevice::getInstance().dump().c_str()); 321 322 result.append("Sensor List:\n"); 323 result.append(mSensors.dump().c_str()); 324 325 result.append("Fusion States:\n"); 326 SensorFusion::getInstance().dump(result); 327 328 result.append("Recent Sensor events:\n"); 329 for (auto&& i : mRecentEvent) { 330 sp<SensorInterface> s = mSensors.getInterface(i.first); 331 if (!i.second->isEmpty() && 332 s->getSensor().getRequiredPermission().isEmpty()) { 333 // if there is events and sensor does not need special permission. 334 result.appendFormat("%s: ", s->getSensor().getName().string()); 335 result.append(i.second->dump().c_str()); 336 } 337 } 338 339 result.append("Active sensors:\n"); 340 for (size_t i=0 ; i<mActiveSensors.size() ; i++) { 341 int handle = mActiveSensors.keyAt(i); 342 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n", 343 getSensorName(handle).string(), 344 handle, 345 mActiveSensors.valueAt(i)->getNumConnections()); 346 } 347 348 result.appendFormat("Socket Buffer size = %zd events\n", 349 mSocketBufferSize/sizeof(sensors_event_t)); 350 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : 351 "not held"); 352 result.appendFormat("Mode :"); 353 switch(mCurrentOperatingMode) { 354 case NORMAL: 355 result.appendFormat(" NORMAL\n"); 356 break; 357 case RESTRICTED: 358 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string()); 359 break; 360 case DATA_INJECTION: 361 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string()); 362 } 363 result.appendFormat("%zd active connections\n", mActiveConnections.size()); 364 365 for (size_t i=0 ; i < mActiveConnections.size() ; i++) { 366 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 367 if (connection != 0) { 368 result.appendFormat("Connection Number: %zu \n", i); 369 connection->dump(result); 370 } 371 } 372 373 result.appendFormat("Previous Registrations:\n"); 374 // Log in the reverse chronological order. 375 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % 376 SENSOR_REGISTRATIONS_BUF_SIZE; 377 const int startIndex = currentIndex; 378 do { 379 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex]; 380 if (SensorRegistrationInfo::isSentinel(reg_info)) { 381 // Ignore sentinel, proceed to next item. 382 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % 383 SENSOR_REGISTRATIONS_BUF_SIZE; 384 continue; 385 } 386 if (reg_info.mActivated) { 387 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x " 388 "samplingRate=%dus maxReportLatency=%dus\n", 389 reg_info.mHour, reg_info.mMin, reg_info.mSec, 390 reg_info.mPackageName.string(), reg_info.mSensorHandle, 391 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs); 392 } else { 393 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n", 394 reg_info.mHour, reg_info.mMin, reg_info.mSec, 395 reg_info.mPackageName.string(), reg_info.mSensorHandle); 396 } 397 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % 398 SENSOR_REGISTRATIONS_BUF_SIZE; 399 } while(startIndex != currentIndex); 400 } 401 } 402 write(fd, result.string(), result.size()); 403 return NO_ERROR; 404} 405 406//TODO: move to SensorEventConnection later 407void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection, 408 sensors_event_t const* buffer, const int count) { 409 for (int i=0 ; i<count ; i++) { 410 int handle = buffer[i].sensor; 411 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 412 handle = buffer[i].meta_data.sensor; 413 } 414 if (connection->hasSensor(handle)) { 415 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle); 416 // If this buffer has an event from a one_shot sensor and this connection is registered 417 // for this particular one_shot sensor, try cleaning up the connection. 418 if (si != nullptr && 419 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) { 420 si->autoDisable(connection.get(), handle); 421 cleanupWithoutDisableLocked(connection, handle); 422 } 423 424 } 425 } 426} 427 428bool SensorService::threadLoop() { 429 ALOGD("nuSensorService thread starting..."); 430 431 // each virtual sensor could generate an event per "real" event, that's why we need to size 432 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too 433 // aggressive, but guaranteed to be enough. 434 const size_t vcount = mSensors.getVirtualSensors().size(); 435 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 436 const size_t numEventMax = minBufferSize / (1 + vcount); 437 438 SensorDevice& device(SensorDevice::getInstance()); 439 440 const int halVersion = device.getHalDeviceVersion(); 441 do { 442 ssize_t count = device.poll(mSensorEventBuffer, numEventMax); 443 if (count < 0) { 444 ALOGE("sensor poll failed (%s)", strerror(-count)); 445 break; 446 } 447 448 // Reset sensors_event_t.flags to zero for all events in the buffer. 449 for (int i = 0; i < count; i++) { 450 mSensorEventBuffer[i].flags = 0; 451 } 452 453 // Make a copy of the connection vector as some connections may be removed during the course 454 // of this loop (especially when one-shot sensor events are present in the sensor_event 455 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the 456 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock 457 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the 458 // strongPointers to a vector before the lock is acquired. 459 SortedVector< sp<SensorEventConnection> > activeConnections; 460 populateActiveConnections(&activeConnections); 461 462 Mutex::Autolock _l(mLock); 463 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The 464 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock, 465 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should 466 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and 467 // releasing the wakelock. 468 bool bufferHasWakeUpEvent = false; 469 for (int i = 0; i < count; i++) { 470 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) { 471 bufferHasWakeUpEvent = true; 472 break; 473 } 474 } 475 476 if (bufferHasWakeUpEvent && !mWakeLockAcquired) { 477 setWakeLockAcquiredLocked(true); 478 } 479 recordLastValueLocked(mSensorEventBuffer, count); 480 481 // handle virtual sensors 482 if (count && vcount) { 483 sensors_event_t const * const event = mSensorEventBuffer; 484 if (!mActiveVirtualSensors.empty()) { 485 size_t k = 0; 486 SensorFusion& fusion(SensorFusion::getInstance()); 487 if (fusion.isEnabled()) { 488 for (size_t i=0 ; i<size_t(count) ; i++) { 489 fusion.process(event[i]); 490 } 491 } 492 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) { 493 for (int handle : mActiveVirtualSensors) { 494 if (count + k >= minBufferSize) { 495 ALOGE("buffer too small to hold all events: " 496 "count=%zd, k=%zu, size=%zu", 497 count, k, minBufferSize); 498 break; 499 } 500 sensors_event_t out; 501 sp<SensorInterface> si = mSensors.getInterface(handle); 502 if (si == nullptr) { 503 ALOGE("handle %d is not an valid virtual sensor", handle); 504 continue; 505 } 506 507 if (si->process(&out, event[i])) { 508 mSensorEventBuffer[count + k] = out; 509 k++; 510 } 511 } 512 } 513 if (k) { 514 // record the last synthesized values 515 recordLastValueLocked(&mSensorEventBuffer[count], k); 516 count += k; 517 // sort the buffer by time-stamps 518 sortEventBuffer(mSensorEventBuffer, count); 519 } 520 } 521 } 522 523 // handle backward compatibility for RotationVector sensor 524 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) { 525 for (int i = 0; i < count; i++) { 526 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) { 527 // All the 4 components of the quaternion should be available 528 // No heading accuracy. Set it to -1 529 mSensorEventBuffer[i].data[4] = -1; 530 } 531 } 532 } 533 534 for (int i = 0; i < count; ++i) { 535 // Map flush_complete_events in the buffer to SensorEventConnections which called flush 536 // on the hardware sensor. mapFlushEventsToConnections[i] will be the 537 // SensorEventConnection mapped to the corresponding flush_complete_event in 538 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise). 539 mMapFlushEventsToConnections[i] = NULL; 540 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) { 541 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor; 542 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle); 543 if (rec != NULL) { 544 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection(); 545 rec->removeFirstPendingFlushConnection(); 546 } 547 } 548 549 // handle dynamic sensor meta events, process registration and unregistration of dynamic 550 // sensor based on content of event. 551 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) { 552 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) { 553 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle; 554 const sensor_t& dynamicSensor = 555 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor); 556 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s", 557 handle, dynamicSensor.type, dynamicSensor.name); 558 559 if (mSensors.isNewHandle(handle)) { 560 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid; 561 sensor_t s = dynamicSensor; 562 // make sure the dynamic sensor flag is set 563 s.flags |= DYNAMIC_SENSOR_MASK; 564 // force the handle to be consistent 565 s.handle = handle; 566 567 SensorInterface *si = new HardwareSensor(s, uuid); 568 569 // This will release hold on dynamic sensor meta, so it should be called 570 // after Sensor object is created. 571 device.handleDynamicSensorConnection(handle, true /*connected*/); 572 registerDynamicSensorLocked(si); 573 } else { 574 ALOGE("Handle %d has been used, cannot use again before reboot.", handle); 575 } 576 } else { 577 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle; 578 ALOGI("Dynamic sensor handle 0x%x disconnected", handle); 579 580 device.handleDynamicSensorConnection(handle, false /*connected*/); 581 if (!unregisterDynamicSensorLocked(handle)) { 582 ALOGE("Dynamic sensor release error."); 583 } 584 585 size_t numConnections = activeConnections.size(); 586 for (size_t i=0 ; i < numConnections; ++i) { 587 if (activeConnections[i] != NULL) { 588 activeConnections[i]->removeSensor(handle); 589 } 590 } 591 } 592 } 593 } 594 595 596 // Send our events to clients. Check the state of wake lock for each client and release the 597 // lock if none of the clients need it. 598 bool needsWakeLock = false; 599 size_t numConnections = activeConnections.size(); 600 for (size_t i=0 ; i < numConnections; ++i) { 601 if (activeConnections[i] != 0) { 602 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch, 603 mMapFlushEventsToConnections); 604 needsWakeLock |= activeConnections[i]->needsWakeLock(); 605 // If the connection has one-shot sensors, it may be cleaned up after first trigger. 606 // Early check for one-shot sensors. 607 if (activeConnections[i]->hasOneShotSensors()) { 608 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer, 609 count); 610 } 611 } 612 } 613 614 if (mWakeLockAcquired && !needsWakeLock) { 615 setWakeLockAcquiredLocked(false); 616 } 617 } while (!Thread::exitPending()); 618 619 ALOGW("Exiting SensorService::threadLoop => aborting..."); 620 abort(); 621 return false; 622} 623 624sp<Looper> SensorService::getLooper() const { 625 return mLooper; 626} 627 628void SensorService::resetAllWakeLockRefCounts() { 629 SortedVector< sp<SensorEventConnection> > activeConnections; 630 populateActiveConnections(&activeConnections); 631 { 632 Mutex::Autolock _l(mLock); 633 for (size_t i=0 ; i < activeConnections.size(); ++i) { 634 if (activeConnections[i] != 0) { 635 activeConnections[i]->resetWakeLockRefCount(); 636 } 637 } 638 setWakeLockAcquiredLocked(false); 639 } 640} 641 642void SensorService::setWakeLockAcquiredLocked(bool acquire) { 643 if (acquire) { 644 if (!mWakeLockAcquired) { 645 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME); 646 mWakeLockAcquired = true; 647 } 648 mLooper->wake(); 649 } else { 650 if (mWakeLockAcquired) { 651 release_wake_lock(WAKE_LOCK_NAME); 652 mWakeLockAcquired = false; 653 } 654 } 655} 656 657bool SensorService::isWakeLockAcquired() { 658 Mutex::Autolock _l(mLock); 659 return mWakeLockAcquired; 660} 661 662bool SensorService::SensorEventAckReceiver::threadLoop() { 663 ALOGD("new thread SensorEventAckReceiver"); 664 sp<Looper> looper = mService->getLooper(); 665 do { 666 bool wakeLockAcquired = mService->isWakeLockAcquired(); 667 int timeout = -1; 668 if (wakeLockAcquired) timeout = 5000; 669 int ret = looper->pollOnce(timeout); 670 if (ret == ALOOPER_POLL_TIMEOUT) { 671 mService->resetAllWakeLockRefCounts(); 672 } 673 } while(!Thread::exitPending()); 674 return false; 675} 676 677void SensorService::recordLastValueLocked( 678 const sensors_event_t* buffer, size_t count) { 679 for (size_t i = 0; i < count; i++) { 680 if (buffer[i].type == SENSOR_TYPE_META_DATA || 681 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META || 682 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) { 683 continue; 684 } 685 686 auto logger = mRecentEvent.find(buffer[i].sensor); 687 if (logger != mRecentEvent.end()) { 688 logger->second->addEvent(buffer[i]); 689 } 690 } 691} 692 693void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) { 694 struct compar { 695 static int cmp(void const* lhs, void const* rhs) { 696 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs); 697 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs); 698 return l->timestamp - r->timestamp; 699 } 700 }; 701 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp); 702} 703 704String8 SensorService::getSensorName(int handle) const { 705 return mSensors.getName(handle); 706} 707 708bool SensorService::isVirtualSensor(int handle) const { 709 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 710 return sensor != nullptr && sensor->isVirtual(); 711} 712 713bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const { 714 int handle = event.sensor; 715 if (event.type == SENSOR_TYPE_META_DATA) { 716 handle = event.meta_data.sensor; 717 } 718 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 719 return sensor != nullptr && sensor->getSensor().isWakeUpSensor(); 720} 721 722Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) { 723 char value[PROPERTY_VALUE_MAX]; 724 property_get("debug.sensors", value, "0"); 725 const Vector<Sensor>& initialSensorList = (atoi(value)) ? 726 mSensors.getUserDebugSensors() : mSensors.getUserSensors(); 727 Vector<Sensor> accessibleSensorList; 728 for (size_t i = 0; i < initialSensorList.size(); i++) { 729 Sensor sensor = initialSensorList[i]; 730 if (canAccessSensor(sensor, "getSensorList", opPackageName)) { 731 accessibleSensorList.add(sensor); 732 } else { 733 ALOGI("Skipped sensor %s because it requires permission %s and app op %d", 734 sensor.getName().string(), 735 sensor.getRequiredPermission().string(), 736 sensor.getRequiredAppOp()); 737 } 738 } 739 return accessibleSensorList; 740} 741 742Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) { 743 Vector<Sensor> accessibleSensorList; 744 mSensors.forEachSensor( 745 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool { 746 if (sensor.isDynamicSensor()) { 747 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) { 748 accessibleSensorList.add(sensor); 749 } else { 750 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32, 751 sensor.getName().string(), 752 sensor.getRequiredPermission().string(), 753 sensor.getRequiredAppOp()); 754 } 755 } 756 return true; 757 }); 758 return accessibleSensorList; 759} 760 761sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName, 762 int requestedMode, const String16& opPackageName) { 763 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION. 764 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) { 765 return NULL; 766 } 767 768 Mutex::Autolock _l(mLock); 769 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be 770 // operating in DI mode. 771 if (requestedMode == DATA_INJECTION) { 772 if (mCurrentOperatingMode != DATA_INJECTION) return NULL; 773 if (!isWhiteListedPackage(packageName)) return NULL; 774 } 775 776 uid_t uid = IPCThreadState::self()->getCallingUid(); 777 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName, 778 requestedMode == DATA_INJECTION, opPackageName)); 779 if (requestedMode == DATA_INJECTION) { 780 if (mActiveConnections.indexOf(result) < 0) { 781 mActiveConnections.add(result); 782 } 783 // Add the associated file descriptor to the Looper for polling whenever there is data to 784 // be injected. 785 result->updateLooperRegistration(mLooper); 786 } 787 return result; 788} 789 790int SensorService::isDataInjectionEnabled() { 791 Mutex::Autolock _l(mLock); 792 return (mCurrentOperatingMode == DATA_INJECTION); 793} 794 795status_t SensorService::resetToNormalMode() { 796 Mutex::Autolock _l(mLock); 797 return resetToNormalModeLocked(); 798} 799 800status_t SensorService::resetToNormalModeLocked() { 801 SensorDevice& dev(SensorDevice::getInstance()); 802 dev.enableAllSensors(); 803 status_t err = dev.setMode(NORMAL); 804 mCurrentOperatingMode = NORMAL; 805 return err; 806} 807 808void SensorService::cleanupConnection(SensorEventConnection* c) { 809 Mutex::Autolock _l(mLock); 810 const wp<SensorEventConnection> connection(c); 811 size_t size = mActiveSensors.size(); 812 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size); 813 for (size_t i=0 ; i<size ; ) { 814 int handle = mActiveSensors.keyAt(i); 815 if (c->hasSensor(handle)) { 816 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle); 817 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 818 if (sensor != nullptr) { 819 sensor->activate(c, false); 820 } else { 821 ALOGE("sensor interface of handle=0x%08x is null!", handle); 822 } 823 c->removeSensor(handle); 824 } 825 SensorRecord* rec = mActiveSensors.valueAt(i); 826 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle); 827 ALOGD_IF(DEBUG_CONNECTIONS, 828 "removing connection %p for sensor[%zu].handle=0x%08x", 829 c, i, handle); 830 831 if (rec && rec->removeConnection(connection)) { 832 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection"); 833 mActiveSensors.removeItemsAt(i, 1); 834 mActiveVirtualSensors.erase(handle); 835 delete rec; 836 size--; 837 } else { 838 i++; 839 } 840 } 841 c->updateLooperRegistration(mLooper); 842 mActiveConnections.remove(connection); 843 BatteryService::cleanup(c->getUid()); 844 if (c->needsWakeLock()) { 845 checkWakeLockStateLocked(); 846 } 847} 848 849sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const { 850 return mSensors.getInterface(handle); 851} 852 853 854status_t SensorService::enable(const sp<SensorEventConnection>& connection, 855 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags, 856 const String16& opPackageName) { 857 if (mInitCheck != NO_ERROR) 858 return mInitCheck; 859 860 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 861 if (sensor == nullptr || 862 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) { 863 return BAD_VALUE; 864 } 865 866 Mutex::Autolock _l(mLock); 867 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION) 868 && !isWhiteListedPackage(connection->getPackageName())) { 869 return INVALID_OPERATION; 870 } 871 872 SensorRecord* rec = mActiveSensors.valueFor(handle); 873 if (rec == 0) { 874 rec = new SensorRecord(connection); 875 mActiveSensors.add(handle, rec); 876 if (sensor->isVirtual()) { 877 mActiveVirtualSensors.emplace(handle); 878 } 879 } else { 880 if (rec->addConnection(connection)) { 881 // this sensor is already activated, but we are adding a connection that uses it. 882 // Immediately send down the last known value of the requested sensor if it's not a 883 // "continuous" sensor. 884 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) { 885 // NOTE: The wake_up flag of this event may get set to 886 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event. 887 888 auto logger = mRecentEvent.find(handle); 889 if (logger != mRecentEvent.end()) { 890 sensors_event_t event; 891 // It is unlikely that this buffer is empty as the sensor is already active. 892 // One possible corner case may be two applications activating an on-change 893 // sensor at the same time. 894 if(logger->second->populateLastEvent(&event)) { 895 event.sensor = handle; 896 if (event.version == sizeof(sensors_event_t)) { 897 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) { 898 setWakeLockAcquiredLocked(true); 899 } 900 connection->sendEvents(&event, 1, NULL); 901 if (!connection->needsWakeLock() && mWakeLockAcquired) { 902 checkWakeLockStateLocked(); 903 } 904 } 905 } 906 } 907 } 908 } 909 } 910 911 if (connection->addSensor(handle)) { 912 BatteryService::enableSensor(connection->getUid(), handle); 913 // the sensor was added (which means it wasn't already there) 914 // so, see if this connection becomes active 915 if (mActiveConnections.indexOf(connection) < 0) { 916 mActiveConnections.add(connection); 917 } 918 } else { 919 ALOGW("sensor %08x already enabled in connection %p (ignoring)", 920 handle, connection.get()); 921 } 922 923 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 924 if (samplingPeriodNs < minDelayNs) { 925 samplingPeriodNs = minDelayNs; 926 } 927 928 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d" 929 "rate=%" PRId64 " timeout== %" PRId64"", 930 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs); 931 932 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs, 933 maxBatchReportLatencyNs); 934 935 // Call flush() before calling activate() on the sensor. Wait for a first 936 // flush complete event before sending events on this connection. Ignore 937 // one-shot sensors which don't support flush(). Ignore on-change sensors 938 // to maintain the on-change logic (any on-change events except the initial 939 // one should be trigger by a change in value). Also if this sensor isn't 940 // already active, don't call flush(). 941 if (err == NO_ERROR && 942 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS && 943 rec->getNumConnections() > 1) { 944 connection->setFirstFlushPending(handle, true); 945 status_t err_flush = sensor->flush(connection.get(), handle); 946 // Flush may return error if the underlying h/w sensor uses an older HAL. 947 if (err_flush == NO_ERROR) { 948 rec->addPendingFlushConnection(connection.get()); 949 } else { 950 connection->setFirstFlushPending(handle, false); 951 } 952 } 953 954 if (err == NO_ERROR) { 955 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle); 956 err = sensor->activate(connection.get(), true); 957 } 958 959 if (err == NO_ERROR) { 960 connection->updateLooperRegistration(mLooper); 961 SensorRegistrationInfo ®_info = 962 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex); 963 reg_info.mSensorHandle = handle; 964 reg_info.mSamplingRateUs = samplingPeriodNs/1000; 965 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000; 966 reg_info.mActivated = true; 967 reg_info.mPackageName = connection->getPackageName(); 968 time_t rawtime = time(NULL); 969 struct tm * timeinfo = localtime(&rawtime); 970 reg_info.mHour = timeinfo->tm_hour; 971 reg_info.mMin = timeinfo->tm_min; 972 reg_info.mSec = timeinfo->tm_sec; 973 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE; 974 } 975 976 if (err != NO_ERROR) { 977 // batch/activate has failed, reset our state. 978 cleanupWithoutDisableLocked(connection, handle); 979 } 980 return err; 981} 982 983status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) { 984 if (mInitCheck != NO_ERROR) 985 return mInitCheck; 986 987 Mutex::Autolock _l(mLock); 988 status_t err = cleanupWithoutDisableLocked(connection, handle); 989 if (err == NO_ERROR) { 990 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 991 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE); 992 993 } 994 if (err == NO_ERROR) { 995 SensorRegistrationInfo ®_info = 996 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex); 997 reg_info.mActivated = false; 998 reg_info.mPackageName= connection->getPackageName(); 999 reg_info.mSensorHandle = handle; 1000 time_t rawtime = time(NULL); 1001 struct tm * timeinfo = localtime(&rawtime); 1002 reg_info.mHour = timeinfo->tm_hour; 1003 reg_info.mMin = timeinfo->tm_min; 1004 reg_info.mSec = timeinfo->tm_sec; 1005 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE; 1006 } 1007 return err; 1008} 1009 1010status_t SensorService::cleanupWithoutDisable( 1011 const sp<SensorEventConnection>& connection, int handle) { 1012 Mutex::Autolock _l(mLock); 1013 return cleanupWithoutDisableLocked(connection, handle); 1014} 1015 1016status_t SensorService::cleanupWithoutDisableLocked( 1017 const sp<SensorEventConnection>& connection, int handle) { 1018 SensorRecord* rec = mActiveSensors.valueFor(handle); 1019 if (rec) { 1020 // see if this connection becomes inactive 1021 if (connection->removeSensor(handle)) { 1022 BatteryService::disableSensor(connection->getUid(), handle); 1023 } 1024 if (connection->hasAnySensor() == false) { 1025 connection->updateLooperRegistration(mLooper); 1026 mActiveConnections.remove(connection); 1027 } 1028 // see if this sensor becomes inactive 1029 if (rec->removeConnection(connection)) { 1030 mActiveSensors.removeItem(handle); 1031 mActiveVirtualSensors.erase(handle); 1032 delete rec; 1033 } 1034 return NO_ERROR; 1035 } 1036 return BAD_VALUE; 1037} 1038 1039status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection, 1040 int handle, nsecs_t ns, const String16& opPackageName) { 1041 if (mInitCheck != NO_ERROR) 1042 return mInitCheck; 1043 1044 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 1045 if (sensor == nullptr || 1046 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) { 1047 return BAD_VALUE; 1048 } 1049 1050 if (ns < 0) 1051 return BAD_VALUE; 1052 1053 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 1054 if (ns < minDelayNs) { 1055 ns = minDelayNs; 1056 } 1057 1058 return sensor->setDelay(connection.get(), handle, ns); 1059} 1060 1061status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection, 1062 const String16& opPackageName) { 1063 if (mInitCheck != NO_ERROR) return mInitCheck; 1064 SensorDevice& dev(SensorDevice::getInstance()); 1065 const int halVersion = dev.getHalDeviceVersion(); 1066 status_t err(NO_ERROR); 1067 Mutex::Autolock _l(mLock); 1068 // Loop through all sensors for this connection and call flush on each of them. 1069 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) { 1070 const int handle = connection->mSensorInfo.keyAt(i); 1071 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle); 1072 if (sensor == nullptr) { 1073 continue; 1074 } 1075 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) { 1076 ALOGE("flush called on a one-shot sensor"); 1077 err = INVALID_OPERATION; 1078 continue; 1079 } 1080 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) { 1081 // For older devices just increment pending flush count which will send a trivial 1082 // flush complete event. 1083 connection->incrementPendingFlushCount(handle); 1084 } else { 1085 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) { 1086 err = INVALID_OPERATION; 1087 continue; 1088 } 1089 status_t err_flush = sensor->flush(connection.get(), handle); 1090 if (err_flush == NO_ERROR) { 1091 SensorRecord* rec = mActiveSensors.valueFor(handle); 1092 if (rec != NULL) rec->addPendingFlushConnection(connection); 1093 } 1094 err = (err_flush != NO_ERROR) ? err_flush : err; 1095 } 1096 } 1097 return err; 1098} 1099 1100bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation, 1101 const String16& opPackageName) { 1102 const String8& requiredPermission = sensor.getRequiredPermission(); 1103 1104 if (requiredPermission.length() <= 0) { 1105 return true; 1106 } 1107 1108 bool hasPermission = false; 1109 1110 // Runtime permissions can't use the cache as they may change. 1111 if (sensor.isRequiredPermissionRuntime()) { 1112 hasPermission = checkPermission(String16(requiredPermission), 1113 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid()); 1114 } else { 1115 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission)); 1116 } 1117 1118 if (!hasPermission) { 1119 ALOGE("%s a sensor (%s) without holding its required permission: %s", 1120 operation, sensor.getName().string(), sensor.getRequiredPermission().string()); 1121 return false; 1122 } 1123 1124 const int32_t opCode = sensor.getRequiredAppOp(); 1125 if (opCode >= 0) { 1126 AppOpsManager appOps; 1127 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName) 1128 != AppOpsManager::MODE_ALLOWED) { 1129 ALOGE("%s a sensor (%s) without enabled required app op: %d", 1130 operation, sensor.getName().string(), opCode); 1131 return false; 1132 } 1133 } 1134 1135 return true; 1136} 1137 1138void SensorService::checkWakeLockState() { 1139 Mutex::Autolock _l(mLock); 1140 checkWakeLockStateLocked(); 1141} 1142 1143void SensorService::checkWakeLockStateLocked() { 1144 if (!mWakeLockAcquired) { 1145 return; 1146 } 1147 bool releaseLock = true; 1148 for (size_t i=0 ; i<mActiveConnections.size() ; i++) { 1149 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 1150 if (connection != 0) { 1151 if (connection->needsWakeLock()) { 1152 releaseLock = false; 1153 break; 1154 } 1155 } 1156 } 1157 if (releaseLock) { 1158 setWakeLockAcquiredLocked(false); 1159 } 1160} 1161 1162void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) { 1163 Mutex::Autolock _l(mLock); 1164 connection->writeToSocketFromCache(); 1165 if (connection->needsWakeLock()) { 1166 setWakeLockAcquiredLocked(true); 1167 } 1168} 1169 1170void SensorService::populateActiveConnections( 1171 SortedVector< sp<SensorEventConnection> >* activeConnections) { 1172 Mutex::Autolock _l(mLock); 1173 for (size_t i=0 ; i < mActiveConnections.size(); ++i) { 1174 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 1175 if (connection != 0) { 1176 activeConnections->add(connection); 1177 } 1178 } 1179} 1180 1181bool SensorService::isWhiteListedPackage(const String8& packageName) { 1182 return (packageName.contains(mWhiteListedPackage.string())); 1183} 1184 1185}; // namespace android 1186 1187