SensorService.cpp revision ee155cadb23e84542cbf445c2aac89ae63df4cc7
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 <inttypes.h> 18#include <math.h> 19#include <stdint.h> 20#include <sys/types.h> 21#include <sys/socket.h> 22 23#include <cutils/properties.h> 24 25#include <utils/SortedVector.h> 26#include <utils/KeyedVector.h> 27#include <utils/threads.h> 28#include <utils/Atomic.h> 29#include <utils/Errors.h> 30#include <utils/RefBase.h> 31#include <utils/Singleton.h> 32#include <utils/String16.h> 33 34#include <binder/AppOpsManager.h> 35#include <binder/BinderService.h> 36#include <binder/IServiceManager.h> 37#include <binder/PermissionCache.h> 38 39#include <gui/ISensorServer.h> 40#include <gui/ISensorEventConnection.h> 41#include <gui/SensorEventQueue.h> 42 43#include <hardware/sensors.h> 44#include <hardware_legacy/power.h> 45 46#include "BatteryService.h" 47#include "CorrectedGyroSensor.h" 48#include "GravitySensor.h" 49#include "LinearAccelerationSensor.h" 50#include "OrientationSensor.h" 51#include "RotationVectorSensor.h" 52#include "SensorFusion.h" 53#include "SensorService.h" 54 55namespace android { 56// --------------------------------------------------------------------------- 57 58/* 59 * Notes: 60 * 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) 64 * 65 */ 66 67const char* SensorService::WAKE_LOCK_NAME = "SensorService"; 68// Permissions. 69static const String16 sDataInjectionPermission("android.permission.LOCATION_HARDWARE"); 70static const String16 sDump("android.permission.DUMP"); 71 72SensorService::SensorService() 73 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED), 74 mWakeLockAcquired(false) 75{ 76} 77 78void SensorService::onFirstRef() 79{ 80 ALOGD("nuSensorService starting..."); 81 SensorDevice& dev(SensorDevice::getInstance()); 82 83 if (dev.initCheck() == NO_ERROR) { 84 sensor_t const* list; 85 ssize_t count = dev.getSensorList(&list); 86 if (count > 0) { 87 ssize_t orientationIndex = -1; 88 bool hasGyro = false; 89 uint32_t virtualSensorsNeeds = 90 (1<<SENSOR_TYPE_GRAVITY) | 91 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) | 92 (1<<SENSOR_TYPE_ROTATION_VECTOR); 93 94 mLastEventSeen.setCapacity(count); 95 for (ssize_t i=0 ; i<count ; i++) { 96 registerSensor( new HardwareSensor(list[i]) ); 97 switch (list[i].type) { 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 virtualSensorsNeeds &= ~(1<<list[i].type); 109 break; 110 } 111 } 112 113 // it's safe to instantiate the SensorFusion object here 114 // (it wants to be instantiated after h/w sensors have been 115 // registered) 116 const SensorFusion& fusion(SensorFusion::getInstance()); 117 118 // build the sensor list returned to users 119 mUserSensorList = mSensorList; 120 121 if (hasGyro) { 122 Sensor aSensor; 123 124 // Add Android virtual sensors if they're not already 125 // available in the HAL 126 127 aSensor = registerVirtualSensor( new RotationVectorSensor() ); 128 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { 129 mUserSensorList.add(aSensor); 130 } 131 132 aSensor = registerVirtualSensor( new GravitySensor(list, count) ); 133 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) { 134 mUserSensorList.add(aSensor); 135 } 136 137 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) ); 138 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) { 139 mUserSensorList.add(aSensor); 140 } 141 142 aSensor = registerVirtualSensor( new OrientationSensor() ); 143 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { 144 // if we are doing our own rotation-vector, also add 145 // the orientation sensor and remove the HAL provided one. 146 mUserSensorList.replaceAt(aSensor, orientationIndex); 147 } 148 149 // virtual debugging sensors are not added to mUserSensorList 150 registerVirtualSensor( new CorrectedGyroSensor(list, count) ); 151 registerVirtualSensor( new GyroDriftSensor() ); 152 } 153 154 // debugging sensor list 155 mUserSensorListDebug = mSensorList; 156 157 // Check if the device really supports batching by looking at the FIFO event 158 // counts for each sensor. 159 bool batchingSupported = false; 160 for (size_t i = 0; i < mSensorList.size(); ++i) { 161 if (mSensorList[i].getFifoMaxEventCount() > 0) { 162 batchingSupported = true; 163 break; 164 } 165 } 166 167 if (batchingSupported) { 168 // Increase socket buffer size to a max of 100 KB for batching capabilities. 169 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED; 170 } else { 171 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED; 172 } 173 174 // Compare the socketBufferSize value against the system limits and limit 175 // it to maxSystemSocketBufferSize if necessary. 176 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r"); 177 char line[128]; 178 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) { 179 line[sizeof(line) - 1] = '\0'; 180 size_t maxSystemSocketBufferSize; 181 sscanf(line, "%zu", &maxSystemSocketBufferSize); 182 if (mSocketBufferSize > maxSystemSocketBufferSize) { 183 mSocketBufferSize = maxSystemSocketBufferSize; 184 } 185 } 186 if (fp) { 187 fclose(fp); 188 } 189 190 mWakeLockAcquired = false; 191 mLooper = new Looper(false); 192 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 193 mSensorEventBuffer = new sensors_event_t[minBufferSize]; 194 mSensorEventScratch = new sensors_event_t[minBufferSize]; 195 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize]; 196 mCurrentOperatingMode = NORMAL; 197 198 mAckReceiver = new SensorEventAckReceiver(this); 199 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY); 200 mInitCheck = NO_ERROR; 201 run("SensorService", PRIORITY_URGENT_DISPLAY); 202 } 203 } 204} 205 206Sensor SensorService::registerSensor(SensorInterface* s) 207{ 208 sensors_event_t event; 209 memset(&event, 0, sizeof(event)); 210 211 const Sensor sensor(s->getSensor()); 212 // add to the sensor list (returned to clients) 213 mSensorList.add(sensor); 214 // add to our handle->SensorInterface mapping 215 mSensorMap.add(sensor.getHandle(), s); 216 // create an entry in the mLastEventSeen array 217 mLastEventSeen.add(sensor.getHandle(), NULL); 218 219 return sensor; 220} 221 222Sensor SensorService::registerVirtualSensor(SensorInterface* s) 223{ 224 Sensor sensor = registerSensor(s); 225 mVirtualSensorList.add( s ); 226 return sensor; 227} 228 229SensorService::~SensorService() 230{ 231 for (size_t i=0 ; i<mSensorMap.size() ; i++) 232 delete mSensorMap.valueAt(i); 233} 234 235status_t SensorService::dump(int fd, const Vector<String16>& args) 236{ 237 String8 result; 238 if (!PermissionCache::checkCallingPermission(sDump)) { 239 result.appendFormat("Permission Denial: " 240 "can't dump SensorService from pid=%d, uid=%d\n", 241 IPCThreadState::self()->getCallingPid(), 242 IPCThreadState::self()->getCallingUid()); 243 } else { 244 if (args.size() > 1) { 245 return INVALID_OPERATION; 246 } 247 Mutex::Autolock _l(mLock); 248 SensorDevice& dev(SensorDevice::getInstance()); 249 if (args.size() == 1 && args[0] == String16("restrict")) { 250 // If already in restricted mode. Ignore. 251 if (mCurrentOperatingMode == RESTRICTED) { 252 return status_t(NO_ERROR); 253 } 254 // If in any mode other than normal, ignore. 255 if (mCurrentOperatingMode != NORMAL) { 256 return INVALID_OPERATION; 257 } 258 mCurrentOperatingMode = RESTRICTED; 259 dev.disableAllSensors(); 260 // Clear all pending flush connections for all active sensors. If one of the active 261 // connections has called flush() and the underlying sensor has been disabled before a 262 // flush complete event is returned, we need to remove the connection from this queue. 263 for (size_t i=0 ; i< mActiveSensors.size(); ++i) { 264 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections(); 265 } 266 return status_t(NO_ERROR); 267 } else if (args.size() == 1 && args[0] == String16("enable")) { 268 // If currently in restricted mode, reset back to NORMAL mode else ignore. 269 if (mCurrentOperatingMode == RESTRICTED) { 270 mCurrentOperatingMode = NORMAL; 271 dev.enableAllSensors(); 272 } 273 return status_t(NO_ERROR); 274 } else if (mSensorList.size() == 0) { 275 result.append("No Sensors on the device\n"); 276 } else { 277 // Default dump the sensor list and debugging information. 278 result.append("Sensor List:\n"); 279 for (size_t i=0 ; i<mSensorList.size() ; i++) { 280 const Sensor& s(mSensorList[i]); 281 result.appendFormat( 282 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |", 283 s.getName().string(), 284 s.getVendor().string(), 285 s.getVersion(), 286 s.getStringType().string(), 287 s.getHandle(), 288 s.getRequiredPermission().string(), 289 s.getType()); 290 291 const int reportingMode = s.getReportingMode(); 292 if (reportingMode == AREPORTING_MODE_CONTINUOUS) { 293 result.append(" continuous | "); 294 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) { 295 result.append(" on-change | "); 296 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) { 297 result.append(" one-shot | "); 298 } else { 299 result.append(" special-trigger | "); 300 } 301 302 if (s.getMaxDelay() > 0) { 303 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay()); 304 } else { 305 result.appendFormat("maxDelay=%dus |", s.getMaxDelay()); 306 } 307 308 if (s.getMinDelay() > 0) { 309 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay()); 310 } else { 311 result.appendFormat("minDelay=%dus |", s.getMinDelay()); 312 } 313 314 if (s.getFifoMaxEventCount() > 0) { 315 result.appendFormat("FifoMax=%d events | ", 316 s.getFifoMaxEventCount()); 317 } else { 318 result.append("no batching | "); 319 } 320 321 if (s.isWakeUpSensor()) { 322 result.appendFormat("wakeUp | "); 323 } else { 324 result.appendFormat("non-wakeUp | "); 325 } 326 327 const CircularBuffer* buf = mLastEventSeen.valueFor(s.getHandle()); 328 if (buf != NULL && s.getRequiredPermission().isEmpty()) { 329 buf->printBuffer(result); 330 } else { 331 result.append("last=<> \n"); 332 } 333 result.append("\n"); 334 } 335 SensorFusion::getInstance().dump(result); 336 SensorDevice::getInstance().dump(result); 337 338 result.append("Active sensors:\n"); 339 for (size_t i=0 ; i<mActiveSensors.size() ; i++) { 340 int handle = mActiveSensors.keyAt(i); 341 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n", 342 getSensorName(handle).string(), 343 handle, 344 mActiveSensors.valueAt(i)->getNumConnections()); 345 } 346 347 result.appendFormat("Socket Buffer size = %d events\n", 348 mSocketBufferSize/sizeof(sensors_event_t)); 349 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held"); 350 result.appendFormat("Mode :"); 351 switch(mCurrentOperatingMode) { 352 case NORMAL: 353 result.appendFormat(" NORMAL\n"); 354 break; 355 case RESTRICTED: 356 result.appendFormat(" RESTRICTED\n"); 357 break; 358 case DATA_INJECTION: 359 result.appendFormat(" DATA_INJECTION\n"); 360 } 361 result.appendFormat("%zd active connections\n", mActiveConnections.size()); 362 363 for (size_t i=0 ; i < mActiveConnections.size() ; i++) { 364 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 365 if (connection != 0) { 366 result.appendFormat("Connection Number: %zu \n", i); 367 connection->dump(result); 368 } 369 } 370 } 371 } 372 write(fd, result.string(), result.size()); 373 return NO_ERROR; 374} 375 376void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection, 377 sensors_event_t const* buffer, const int count) { 378 for (int i=0 ; i<count ; i++) { 379 int handle = buffer[i].sensor; 380 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 381 handle = buffer[i].meta_data.sensor; 382 } 383 if (connection->hasSensor(handle)) { 384 SensorInterface* sensor = mSensorMap.valueFor(handle); 385 // If this buffer has an event from a one_shot sensor and this connection is registered 386 // for this particular one_shot sensor, try cleaning up the connection. 387 if (sensor != NULL && 388 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) { 389 sensor->autoDisable(connection.get(), handle); 390 cleanupWithoutDisableLocked(connection, handle); 391 } 392 393 } 394 } 395} 396 397bool SensorService::threadLoop() 398{ 399 ALOGD("nuSensorService thread starting..."); 400 401 // each virtual sensor could generate an event per "real" event, that's why we need 402 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. 403 // in practice, this is too aggressive, but guaranteed to be enough. 404 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 405 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size()); 406 407 SensorDevice& device(SensorDevice::getInstance()); 408 const size_t vcount = mVirtualSensorList.size(); 409 410 const int halVersion = device.getHalDeviceVersion(); 411 do { 412 ssize_t count = device.poll(mSensorEventBuffer, numEventMax); 413 if (count < 0) { 414 ALOGE("sensor poll failed (%s)", strerror(-count)); 415 break; 416 } 417 418 // Reset sensors_event_t.flags to zero for all events in the buffer. 419 for (int i = 0; i < count; i++) { 420 mSensorEventBuffer[i].flags = 0; 421 } 422 423 // Make a copy of the connection vector as some connections may be removed during the 424 // course of this loop (especially when one-shot sensor events are present in the 425 // sensor_event buffer). Promote all connections to StrongPointers before the lock is 426 // acquired. If the destructor of the sp gets called when the lock is acquired, it may 427 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for 428 // cleanup. So copy all the strongPointers to a vector before the lock is acquired. 429 SortedVector< sp<SensorEventConnection> > activeConnections; 430 populateActiveConnections(&activeConnections); 431 Mutex::Autolock _l(mLock); 432 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The 433 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock, 434 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should 435 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and 436 // releasing the wakelock. 437 bool bufferHasWakeUpEvent = false; 438 for (int i = 0; i < count; i++) { 439 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) { 440 bufferHasWakeUpEvent = true; 441 break; 442 } 443 } 444 445 if (bufferHasWakeUpEvent && !mWakeLockAcquired) { 446 setWakeLockAcquiredLocked(true); 447 } 448 recordLastValueLocked(mSensorEventBuffer, count); 449 450 // handle virtual sensors 451 if (count && vcount) { 452 sensors_event_t const * const event = mSensorEventBuffer; 453 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size(); 454 if (activeVirtualSensorCount) { 455 size_t k = 0; 456 SensorFusion& fusion(SensorFusion::getInstance()); 457 if (fusion.isEnabled()) { 458 for (size_t i=0 ; i<size_t(count) ; i++) { 459 fusion.process(event[i]); 460 } 461 } 462 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) { 463 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) { 464 if (count + k >= minBufferSize) { 465 ALOGE("buffer too small to hold all events: " 466 "count=%zd, k=%zu, size=%zu", 467 count, k, minBufferSize); 468 break; 469 } 470 sensors_event_t out; 471 SensorInterface* si = mActiveVirtualSensors.valueAt(j); 472 if (si->process(&out, event[i])) { 473 mSensorEventBuffer[count + k] = out; 474 k++; 475 } 476 } 477 } 478 if (k) { 479 // record the last synthesized values 480 recordLastValueLocked(&mSensorEventBuffer[count], k); 481 count += k; 482 // sort the buffer by time-stamps 483 sortEventBuffer(mSensorEventBuffer, count); 484 } 485 } 486 } 487 488 // handle backward compatibility for RotationVector sensor 489 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) { 490 for (int i = 0; i < count; i++) { 491 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) { 492 // All the 4 components of the quaternion should be available 493 // No heading accuracy. Set it to -1 494 mSensorEventBuffer[i].data[4] = -1; 495 } 496 } 497 } 498 499 // Map flush_complete_events in the buffer to SensorEventConnections which called 500 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the 501 // SensorEventConnection mapped to the corresponding flush_complete_event in 502 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise). 503 for (int i = 0; i < count; ++i) { 504 mMapFlushEventsToConnections[i] = NULL; 505 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) { 506 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor; 507 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle); 508 if (rec != NULL) { 509 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection(); 510 rec->removeFirstPendingFlushConnection(); 511 } 512 } 513 } 514 515 // Send our events to clients. Check the state of wake lock for each client and release the 516 // lock if none of the clients need it. 517 bool needsWakeLock = false; 518 size_t numConnections = activeConnections.size(); 519 for (size_t i=0 ; i < numConnections; ++i) { 520 if (activeConnections[i] != 0) { 521 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch, 522 mMapFlushEventsToConnections); 523 needsWakeLock |= activeConnections[i]->needsWakeLock(); 524 // If the connection has one-shot sensors, it may be cleaned up after first trigger. 525 // Early check for one-shot sensors. 526 if (activeConnections[i]->hasOneShotSensors()) { 527 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer, 528 count); 529 } 530 } 531 } 532 533 if (mWakeLockAcquired && !needsWakeLock) { 534 setWakeLockAcquiredLocked(false); 535 } 536 } while (!Thread::exitPending()); 537 538 ALOGW("Exiting SensorService::threadLoop => aborting..."); 539 abort(); 540 return false; 541} 542 543sp<Looper> SensorService::getLooper() const { 544 return mLooper; 545} 546 547void SensorService::resetAllWakeLockRefCounts() { 548 SortedVector< sp<SensorEventConnection> > activeConnections; 549 populateActiveConnections(&activeConnections); 550 { 551 Mutex::Autolock _l(mLock); 552 for (size_t i=0 ; i < activeConnections.size(); ++i) { 553 if (activeConnections[i] != 0) { 554 activeConnections[i]->resetWakeLockRefCount(); 555 } 556 } 557 setWakeLockAcquiredLocked(false); 558 } 559} 560 561void SensorService::setWakeLockAcquiredLocked(bool acquire) { 562 if (acquire) { 563 if (!mWakeLockAcquired) { 564 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME); 565 mWakeLockAcquired = true; 566 } 567 mLooper->wake(); 568 } else { 569 if (mWakeLockAcquired) { 570 release_wake_lock(WAKE_LOCK_NAME); 571 mWakeLockAcquired = false; 572 } 573 } 574} 575 576bool SensorService::isWakeLockAcquired() { 577 Mutex::Autolock _l(mLock); 578 return mWakeLockAcquired; 579} 580 581bool SensorService::SensorEventAckReceiver::threadLoop() { 582 ALOGD("new thread SensorEventAckReceiver"); 583 sp<Looper> looper = mService->getLooper(); 584 do { 585 bool wakeLockAcquired = mService->isWakeLockAcquired(); 586 int timeout = -1; 587 if (wakeLockAcquired) timeout = 5000; 588 int ret = looper->pollOnce(timeout); 589 if (ret == ALOOPER_POLL_TIMEOUT) { 590 mService->resetAllWakeLockRefCounts(); 591 } 592 } while(!Thread::exitPending()); 593 return false; 594} 595 596void SensorService::recordLastValueLocked( 597 const sensors_event_t* buffer, size_t count) { 598 for (size_t i = 0; i < count; i++) { 599 if (buffer[i].type != SENSOR_TYPE_META_DATA) { 600 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor); 601 if (circular_buf == NULL) { 602 circular_buf = new CircularBuffer(buffer[i].type); 603 } 604 circular_buf->addEvent(buffer[i]); 605 } 606 } 607} 608 609void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) 610{ 611 struct compar { 612 static int cmp(void const* lhs, void const* rhs) { 613 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs); 614 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs); 615 return l->timestamp - r->timestamp; 616 } 617 }; 618 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp); 619} 620 621String8 SensorService::getSensorName(int handle) const { 622 size_t count = mUserSensorList.size(); 623 for (size_t i=0 ; i<count ; i++) { 624 const Sensor& sensor(mUserSensorList[i]); 625 if (sensor.getHandle() == handle) { 626 return sensor.getName(); 627 } 628 } 629 String8 result("unknown"); 630 return result; 631} 632 633bool SensorService::isVirtualSensor(int handle) const { 634 SensorInterface* sensor = mSensorMap.valueFor(handle); 635 return sensor->isVirtual(); 636} 637 638bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const { 639 int handle = event.sensor; 640 if (event.type == SENSOR_TYPE_META_DATA) { 641 handle = event.meta_data.sensor; 642 } 643 SensorInterface* sensor = mSensorMap.valueFor(handle); 644 return sensor != NULL && sensor->getSensor().isWakeUpSensor(); 645} 646 647SensorService::SensorRecord * SensorService::getSensorRecord(int handle) { 648 return mActiveSensors.valueFor(handle); 649} 650 651Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) 652{ 653 char value[PROPERTY_VALUE_MAX]; 654 property_get("debug.sensors", value, "0"); 655 const Vector<Sensor>& initialSensorList = (atoi(value)) ? 656 mUserSensorListDebug : mUserSensorList; 657 Vector<Sensor> accessibleSensorList; 658 for (size_t i = 0; i < initialSensorList.size(); i++) { 659 Sensor sensor = initialSensorList[i]; 660 if (canAccessSensor(sensor, "getSensorList", opPackageName)) { 661 accessibleSensorList.add(sensor); 662 } else { 663 ALOGI("Skipped sensor %s because it requires permission %s and app op %d", 664 sensor.getName().string(), 665 sensor.getRequiredPermission().string(), 666 sensor.getRequiredAppOp()); 667 } 668 } 669 return accessibleSensorList; 670} 671 672sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName, 673 int requestedMode, const String16& opPackageName) { 674 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION. 675 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) { 676 return NULL; 677 } 678 // DATA_INJECTION mode needs to have the required permissions set. 679 if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) { 680 return NULL; 681 } 682 683 Mutex::Autolock _l(mLock); 684 uid_t uid = IPCThreadState::self()->getCallingUid(); 685 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName, 686 requestedMode == DATA_INJECTION, opPackageName)); 687 if (requestedMode == DATA_INJECTION) { 688 if (mActiveConnections.indexOf(result) < 0) { 689 mActiveConnections.add(result); 690 } 691 // Add the associated file descriptor to the Looper for polling whenever there is data to 692 // be injected. 693 result->updateLooperRegistration(mLooper); 694 } 695 return result; 696} 697 698status_t SensorService::enableDataInjection(int requestedMode) { 699 if (!hasDataInjectionPermissions()) { 700 return INVALID_OPERATION; 701 } 702 Mutex::Autolock _l(mLock); 703 ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode); 704 SensorDevice& dev(SensorDevice::getInstance()); 705 status_t err(NO_ERROR); 706 if (requestedMode == DATA_INJECTION) { 707 if (mCurrentOperatingMode == NORMAL) { 708 dev.disableAllSensors(); 709 err = dev.setMode(requestedMode); 710 if (err == NO_ERROR) { 711 mCurrentOperatingMode = DATA_INJECTION; 712 } else { 713 // Re-enable sensors. 714 dev.enableAllSensors(); 715 } 716 } else if (mCurrentOperatingMode == DATA_INJECTION) { 717 // Already in DATA_INJECTION mode. Treat this as a no_op. 718 return NO_ERROR; 719 } else { 720 // Transition to data injection mode supported only from NORMAL mode. 721 return INVALID_OPERATION; 722 } 723 } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) { 724 err = resetToNormalModeLocked(); 725 } 726 return err; 727} 728 729status_t SensorService::resetToNormalMode() { 730 Mutex::Autolock _l(mLock); 731 return resetToNormalModeLocked(); 732} 733 734status_t SensorService::resetToNormalModeLocked() { 735 SensorDevice& dev(SensorDevice::getInstance()); 736 dev.enableAllSensors(); 737 status_t err = dev.setMode(NORMAL); 738 mCurrentOperatingMode = NORMAL; 739 return err; 740} 741 742void SensorService::cleanupConnection(SensorEventConnection* c) 743{ 744 Mutex::Autolock _l(mLock); 745 const wp<SensorEventConnection> connection(c); 746 size_t size = mActiveSensors.size(); 747 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size); 748 for (size_t i=0 ; i<size ; ) { 749 int handle = mActiveSensors.keyAt(i); 750 if (c->hasSensor(handle)) { 751 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle); 752 SensorInterface* sensor = mSensorMap.valueFor( handle ); 753 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle); 754 if (sensor) { 755 sensor->activate(c, false); 756 } 757 c->removeSensor(handle); 758 } 759 SensorRecord* rec = mActiveSensors.valueAt(i); 760 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle); 761 ALOGD_IF(DEBUG_CONNECTIONS, 762 "removing connection %p for sensor[%zu].handle=0x%08x", 763 c, i, handle); 764 765 if (rec && rec->removeConnection(connection)) { 766 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection"); 767 mActiveSensors.removeItemsAt(i, 1); 768 mActiveVirtualSensors.removeItem(handle); 769 delete rec; 770 size--; 771 } else { 772 i++; 773 } 774 } 775 c->updateLooperRegistration(mLooper); 776 mActiveConnections.remove(connection); 777 BatteryService::cleanup(c->getUid()); 778 if (c->needsWakeLock()) { 779 checkWakeLockStateLocked(); 780 } 781} 782 783Sensor SensorService::getSensorFromHandle(int handle) const { 784 return mSensorMap.valueFor(handle)->getSensor(); 785} 786 787status_t SensorService::enable(const sp<SensorEventConnection>& connection, 788 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags, 789 const String16& opPackageName) 790{ 791 if (mInitCheck != NO_ERROR) 792 return mInitCheck; 793 794 SensorInterface* sensor = mSensorMap.valueFor(handle); 795 if (sensor == NULL) { 796 return BAD_VALUE; 797 } 798 799 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) { 800 return BAD_VALUE; 801 } 802 803 Mutex::Autolock _l(mLock); 804 if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) { 805 return INVALID_OPERATION; 806 } 807 808 SensorRecord* rec = mActiveSensors.valueFor(handle); 809 if (rec == 0) { 810 rec = new SensorRecord(connection); 811 mActiveSensors.add(handle, rec); 812 if (sensor->isVirtual()) { 813 mActiveVirtualSensors.add(handle, sensor); 814 } 815 } else { 816 if (rec->addConnection(connection)) { 817 // this sensor is already activated, but we are adding a connection that uses it. 818 // Immediately send down the last known value of the requested sensor if it's not a 819 // "continuous" sensor. 820 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) { 821 // NOTE: The wake_up flag of this event may get set to 822 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event. 823 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle); 824 if (circular_buf) { 825 sensors_event_t event; 826 memset(&event, 0, sizeof(event)); 827 // It is unlikely that this buffer is empty as the sensor is already active. 828 // One possible corner case may be two applications activating an on-change 829 // sensor at the same time. 830 if(circular_buf->populateLastEvent(&event)) { 831 event.sensor = handle; 832 if (event.version == sizeof(sensors_event_t)) { 833 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) { 834 setWakeLockAcquiredLocked(true); 835 } 836 connection->sendEvents(&event, 1, NULL); 837 if (!connection->needsWakeLock() && mWakeLockAcquired) { 838 checkWakeLockStateLocked(); 839 } 840 } 841 } 842 } 843 } 844 } 845 } 846 847 if (connection->addSensor(handle)) { 848 BatteryService::enableSensor(connection->getUid(), handle); 849 // the sensor was added (which means it wasn't already there) 850 // so, see if this connection becomes active 851 if (mActiveConnections.indexOf(connection) < 0) { 852 mActiveConnections.add(connection); 853 } 854 } else { 855 ALOGW("sensor %08x already enabled in connection %p (ignoring)", 856 handle, connection.get()); 857 } 858 859 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 860 if (samplingPeriodNs < minDelayNs) { 861 samplingPeriodNs = minDelayNs; 862 } 863 864 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d" 865 "rate=%" PRId64 " timeout== %" PRId64"", 866 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs); 867 868 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs, 869 maxBatchReportLatencyNs); 870 871 // Call flush() before calling activate() on the sensor. Wait for a first flush complete 872 // event before sending events on this connection. Ignore one-shot sensors which don't 873 // support flush(). Also if this sensor isn't already active, don't call flush(). 874 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT && 875 rec->getNumConnections() > 1) { 876 connection->setFirstFlushPending(handle, true); 877 status_t err_flush = sensor->flush(connection.get(), handle); 878 // Flush may return error if the underlying h/w sensor uses an older HAL. 879 if (err_flush == NO_ERROR) { 880 rec->addPendingFlushConnection(connection.get()); 881 } else { 882 connection->setFirstFlushPending(handle, false); 883 } 884 } 885 886 if (err == NO_ERROR) { 887 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle); 888 err = sensor->activate(connection.get(), true); 889 } 890 891 if (err == NO_ERROR) { 892 connection->updateLooperRegistration(mLooper); 893 } 894 895 if (err != NO_ERROR) { 896 // batch/activate has failed, reset our state. 897 cleanupWithoutDisableLocked(connection, handle); 898 } 899 return err; 900} 901 902status_t SensorService::disable(const sp<SensorEventConnection>& connection, 903 int handle) 904{ 905 if (mInitCheck != NO_ERROR) 906 return mInitCheck; 907 908 Mutex::Autolock _l(mLock); 909 status_t err = cleanupWithoutDisableLocked(connection, handle); 910 if (err == NO_ERROR) { 911 SensorInterface* sensor = mSensorMap.valueFor(handle); 912 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE); 913 } 914 return err; 915} 916 917status_t SensorService::cleanupWithoutDisable( 918 const sp<SensorEventConnection>& connection, int handle) { 919 Mutex::Autolock _l(mLock); 920 return cleanupWithoutDisableLocked(connection, handle); 921} 922 923status_t SensorService::cleanupWithoutDisableLocked( 924 const sp<SensorEventConnection>& connection, int handle) { 925 SensorRecord* rec = mActiveSensors.valueFor(handle); 926 if (rec) { 927 // see if this connection becomes inactive 928 if (connection->removeSensor(handle)) { 929 BatteryService::disableSensor(connection->getUid(), handle); 930 } 931 if (connection->hasAnySensor() == false) { 932 connection->updateLooperRegistration(mLooper); 933 mActiveConnections.remove(connection); 934 } 935 // see if this sensor becomes inactive 936 if (rec->removeConnection(connection)) { 937 mActiveSensors.removeItem(handle); 938 mActiveVirtualSensors.removeItem(handle); 939 delete rec; 940 } 941 return NO_ERROR; 942 } 943 return BAD_VALUE; 944} 945 946status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection, 947 int handle, nsecs_t ns, const String16& opPackageName) 948{ 949 if (mInitCheck != NO_ERROR) 950 return mInitCheck; 951 952 SensorInterface* sensor = mSensorMap.valueFor(handle); 953 if (!sensor) 954 return BAD_VALUE; 955 956 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) { 957 return BAD_VALUE; 958 } 959 960 if (ns < 0) 961 return BAD_VALUE; 962 963 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 964 if (ns < minDelayNs) { 965 ns = minDelayNs; 966 } 967 968 return sensor->setDelay(connection.get(), handle, ns); 969} 970 971status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection, 972 const String16& opPackageName) { 973 if (mInitCheck != NO_ERROR) return mInitCheck; 974 SensorDevice& dev(SensorDevice::getInstance()); 975 const int halVersion = dev.getHalDeviceVersion(); 976 status_t err(NO_ERROR); 977 Mutex::Autolock _l(mLock); 978 // Loop through all sensors for this connection and call flush on each of them. 979 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) { 980 const int handle = connection->mSensorInfo.keyAt(i); 981 SensorInterface* sensor = mSensorMap.valueFor(handle); 982 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) { 983 ALOGE("flush called on a one-shot sensor"); 984 err = INVALID_OPERATION; 985 continue; 986 } 987 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) { 988 // For older devices just increment pending flush count which will send a trivial 989 // flush complete event. 990 connection->incrementPendingFlushCount(handle); 991 } else { 992 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) { 993 err = INVALID_OPERATION; 994 continue; 995 } 996 status_t err_flush = sensor->flush(connection.get(), handle); 997 if (err_flush == NO_ERROR) { 998 SensorRecord* rec = mActiveSensors.valueFor(handle); 999 if (rec != NULL) rec->addPendingFlushConnection(connection); 1000 } 1001 err = (err_flush != NO_ERROR) ? err_flush : err; 1002 } 1003 } 1004 return err; 1005} 1006 1007bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation, 1008 const String16& opPackageName) { 1009 const String8& requiredPermission = sensor.getRequiredPermission(); 1010 1011 if (requiredPermission.length() <= 0) { 1012 return true; 1013 } 1014 1015 bool hasPermission = false; 1016 1017 // Runtime permissions can't use the cache as they may change. 1018 if (sensor.isRequiredPermissionRuntime()) { 1019 hasPermission = checkPermission(String16(requiredPermission), 1020 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid()); 1021 } else { 1022 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission)); 1023 } 1024 1025 if (!hasPermission) { 1026 ALOGE("%s a sensor (%s) without holding its required permission: %s", 1027 operation, sensor.getName().string(), sensor.getRequiredPermission().string()); 1028 return false; 1029 } 1030 1031 const int32_t opCode = sensor.getRequiredAppOp(); 1032 if (opCode >= 0) { 1033 AppOpsManager appOps; 1034 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName) 1035 != AppOpsManager::MODE_ALLOWED) { 1036 ALOGE("%s a sensor (%s) without enabled required app op: %D", 1037 operation, sensor.getName().string(), opCode); 1038 return false; 1039 } 1040 } 1041 1042 return true; 1043} 1044 1045bool SensorService::hasDataInjectionPermissions() { 1046 if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) { 1047 ALOGE("Permission Denial trying to activate data injection without" 1048 " the required permission"); 1049 return false; 1050 } 1051 return true; 1052} 1053 1054void SensorService::checkWakeLockState() { 1055 Mutex::Autolock _l(mLock); 1056 checkWakeLockStateLocked(); 1057} 1058 1059void SensorService::checkWakeLockStateLocked() { 1060 if (!mWakeLockAcquired) { 1061 return; 1062 } 1063 bool releaseLock = true; 1064 for (size_t i=0 ; i<mActiveConnections.size() ; i++) { 1065 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 1066 if (connection != 0) { 1067 if (connection->needsWakeLock()) { 1068 releaseLock = false; 1069 break; 1070 } 1071 } 1072 } 1073 if (releaseLock) { 1074 setWakeLockAcquiredLocked(false); 1075 } 1076} 1077 1078void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) { 1079 Mutex::Autolock _l(mLock); 1080 connection->writeToSocketFromCache(); 1081 if (connection->needsWakeLock()) { 1082 setWakeLockAcquiredLocked(true); 1083 } 1084} 1085 1086void SensorService::populateActiveConnections( 1087 SortedVector< sp<SensorEventConnection> >* activeConnections) { 1088 Mutex::Autolock _l(mLock); 1089 for (size_t i=0 ; i < mActiveConnections.size(); ++i) { 1090 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 1091 if (connection != 0) { 1092 activeConnections->add(connection); 1093 } 1094 } 1095} 1096 1097bool SensorService::isWhiteListedPackage(const String8& packageName) { 1098 // TODO: Come up with a list of packages. 1099 return (packageName.find(".cts.") != -1); 1100} 1101 1102int SensorService::getNumEventsForSensorType(int sensor_event_type) { 1103 switch (sensor_event_type) { 1104 case SENSOR_TYPE_ROTATION_VECTOR: 1105 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR: 1106 return 5; 1107 1108 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: 1109 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 1110 return 6; 1111 1112 case SENSOR_TYPE_GAME_ROTATION_VECTOR: 1113 return 4; 1114 1115 case SENSOR_TYPE_SIGNIFICANT_MOTION: 1116 case SENSOR_TYPE_STEP_DETECTOR: 1117 case SENSOR_TYPE_STEP_COUNTER: 1118 return 1; 1119 1120 default: 1121 return 3; 1122 } 1123} 1124 1125// --------------------------------------------------------------------------- 1126SensorService::SensorRecord::SensorRecord( 1127 const sp<SensorEventConnection>& connection) 1128{ 1129 mConnections.add(connection); 1130} 1131 1132bool SensorService::SensorRecord::addConnection( 1133 const sp<SensorEventConnection>& connection) 1134{ 1135 if (mConnections.indexOf(connection) < 0) { 1136 mConnections.add(connection); 1137 return true; 1138 } 1139 return false; 1140} 1141 1142bool SensorService::SensorRecord::removeConnection( 1143 const wp<SensorEventConnection>& connection) 1144{ 1145 ssize_t index = mConnections.indexOf(connection); 1146 if (index >= 0) { 1147 mConnections.removeItemsAt(index, 1); 1148 } 1149 // Remove this connections from the queue of flush() calls made on this sensor. 1150 for (Vector< wp<SensorEventConnection> >::iterator it = 1151 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) { 1152 1153 if (it->unsafe_get() == connection.unsafe_get()) { 1154 it = mPendingFlushConnections.erase(it); 1155 } else { 1156 ++it; 1157 } 1158 } 1159 return mConnections.size() ? false : true; 1160} 1161 1162void SensorService::SensorRecord::addPendingFlushConnection( 1163 const sp<SensorEventConnection>& connection) { 1164 mPendingFlushConnections.add(connection); 1165} 1166 1167void SensorService::SensorRecord::removeFirstPendingFlushConnection() { 1168 if (mPendingFlushConnections.size() > 0) { 1169 mPendingFlushConnections.removeAt(0); 1170 } 1171} 1172 1173SensorService::SensorEventConnection * 1174SensorService::SensorRecord::getFirstPendingFlushConnection() { 1175 if (mPendingFlushConnections.size() > 0) { 1176 return mPendingFlushConnections[0].unsafe_get(); 1177 } 1178 return NULL; 1179} 1180 1181void SensorService::SensorRecord::clearAllPendingFlushConnections() { 1182 mPendingFlushConnections.clear(); 1183} 1184 1185// -------------------------------------------------------------------------- 1186SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) { 1187 mNextInd = 0; 1188 mTrimmedSensorEventArr = new TrimmedSensorEvent *[CIRCULAR_BUF_SIZE]; 1189 mSensorType = sensor_event_type; 1190 const int numData = SensorService::getNumEventsForSensorType(mSensorType); 1191 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) { 1192 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(numData, mSensorType); 1193 } 1194} 1195 1196void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) { 1197 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd]; 1198 curr_event->mTimestamp = sensor_event.timestamp; 1199 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) { 1200 curr_event->mStepCounter = sensor_event.u64.step_counter; 1201 } else { 1202 memcpy(curr_event->mData, sensor_event.data, 1203 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType)); 1204 } 1205 time_t rawtime = time(NULL); 1206 struct tm * timeinfo = localtime(&rawtime); 1207 curr_event->mHour = timeinfo->tm_hour; 1208 curr_event->mMin = timeinfo->tm_min; 1209 curr_event->mSec = timeinfo->tm_sec; 1210 mNextInd = (mNextInd + 1) % CIRCULAR_BUF_SIZE; 1211} 1212 1213void SensorService::CircularBuffer::printBuffer(String8& result) const { 1214 const int numData = SensorService::getNumEventsForSensorType(mSensorType); 1215 int i = mNextInd, eventNum = 1; 1216 result.appendFormat("last %d events = < ", CIRCULAR_BUF_SIZE); 1217 do { 1218 if (mTrimmedSensorEventArr[i]->mTimestamp == -1) { 1219 // Sentinel, ignore. 1220 i = (i + 1) % CIRCULAR_BUF_SIZE; 1221 continue; 1222 } 1223 result.appendFormat("%d) ", eventNum++); 1224 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) { 1225 result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter); 1226 } else { 1227 for (int j = 0; j < numData; ++j) { 1228 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]); 1229 } 1230 } 1231 result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp, 1232 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin, 1233 mTrimmedSensorEventArr[i]->mSec); 1234 i = (i + 1) % CIRCULAR_BUF_SIZE; 1235 } while (i != mNextInd); 1236 result.appendFormat(">\n"); 1237} 1238 1239bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) { 1240 int lastEventInd = (mNextInd - 1 + CIRCULAR_BUF_SIZE) % CIRCULAR_BUF_SIZE; 1241 // Check if the buffer is empty. 1242 if (mTrimmedSensorEventArr[lastEventInd]->mTimestamp == -1) { 1243 return false; 1244 } 1245 event->version = sizeof(sensors_event_t); 1246 event->type = mSensorType; 1247 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp; 1248 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) { 1249 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter; 1250 } else { 1251 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData, 1252 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType)); 1253 } 1254 return true; 1255} 1256 1257SensorService::CircularBuffer::~CircularBuffer() { 1258 for (int i = 0; i < CIRCULAR_BUF_SIZE; ++i) { 1259 delete mTrimmedSensorEventArr[i]; 1260 } 1261 delete [] mTrimmedSensorEventArr; 1262} 1263 1264// --------------------------------------------------------------------------- 1265 1266SensorService::SensorEventConnection::SensorEventConnection( 1267 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode, 1268 const String16& opPackageName) 1269 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false), 1270 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL), 1271 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) { 1272 mChannel = new BitTube(mService->mSocketBufferSize); 1273#if DEBUG_CONNECTIONS 1274 mEventsReceived = mEventsSentFromCache = mEventsSent = 0; 1275 mTotalAcksNeeded = mTotalAcksReceived = 0; 1276#endif 1277} 1278 1279SensorService::SensorEventConnection::~SensorEventConnection() { 1280 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this); 1281 mService->cleanupConnection(this); 1282 if (mEventCache != NULL) { 1283 delete mEventCache; 1284 } 1285} 1286 1287void SensorService::SensorEventConnection::onFirstRef() { 1288 LooperCallback::onFirstRef(); 1289} 1290 1291bool SensorService::SensorEventConnection::needsWakeLock() { 1292 Mutex::Autolock _l(mConnectionLock); 1293 return !mDead && mWakeLockRefCount > 0; 1294} 1295 1296void SensorService::SensorEventConnection::resetWakeLockRefCount() { 1297 Mutex::Autolock _l(mConnectionLock); 1298 mWakeLockRefCount = 0; 1299} 1300 1301void SensorService::SensorEventConnection::dump(String8& result) { 1302 Mutex::Autolock _l(mConnectionLock); 1303 result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL"); 1304 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n", 1305 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize); 1306 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 1307 const FlushInfo& flushInfo = mSensorInfo.valueAt(i); 1308 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n", 1309 mService->getSensorName(mSensorInfo.keyAt(i)).string(), 1310 mSensorInfo.keyAt(i), 1311 flushInfo.mFirstFlushPending ? "First flush pending" : 1312 "active", 1313 flushInfo.mPendingFlushEventsToSend); 1314 } 1315#if DEBUG_CONNECTIONS 1316 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |" 1317 " total_acks_needed %d | total_acks_recvd %d\n", 1318 mEventsReceived, 1319 mEventsSent, 1320 mEventsSentFromCache, 1321 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize), 1322 mTotalAcksNeeded, 1323 mTotalAcksReceived); 1324#endif 1325} 1326 1327bool SensorService::SensorEventConnection::addSensor(int32_t handle) { 1328 Mutex::Autolock _l(mConnectionLock); 1329 if (!canAccessSensor(mService->getSensorFromHandle(handle), 1330 "Tried adding", mOpPackageName)) { 1331 return false; 1332 } 1333 if (mSensorInfo.indexOfKey(handle) < 0) { 1334 mSensorInfo.add(handle, FlushInfo()); 1335 return true; 1336 } 1337 return false; 1338} 1339 1340bool SensorService::SensorEventConnection::removeSensor(int32_t handle) { 1341 Mutex::Autolock _l(mConnectionLock); 1342 if (mSensorInfo.removeItem(handle) >= 0) { 1343 return true; 1344 } 1345 return false; 1346} 1347 1348bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const { 1349 Mutex::Autolock _l(mConnectionLock); 1350 return mSensorInfo.indexOfKey(handle) >= 0; 1351} 1352 1353bool SensorService::SensorEventConnection::hasAnySensor() const { 1354 Mutex::Autolock _l(mConnectionLock); 1355 return mSensorInfo.size() ? true : false; 1356} 1357 1358bool SensorService::SensorEventConnection::hasOneShotSensors() const { 1359 Mutex::Autolock _l(mConnectionLock); 1360 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 1361 const int handle = mSensorInfo.keyAt(i); 1362 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) { 1363 return true; 1364 } 1365 } 1366 return false; 1367} 1368 1369String8 SensorService::SensorEventConnection::getPackageName() const { 1370 return mPackageName; 1371} 1372 1373void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle, 1374 bool value) { 1375 Mutex::Autolock _l(mConnectionLock); 1376 ssize_t index = mSensorInfo.indexOfKey(handle); 1377 if (index >= 0) { 1378 FlushInfo& flushInfo = mSensorInfo.editValueAt(index); 1379 flushInfo.mFirstFlushPending = value; 1380 } 1381} 1382 1383void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) { 1384 Mutex::Autolock _l(mConnectionLock); 1385 updateLooperRegistrationLocked(looper); 1386} 1387 1388void SensorService::SensorEventConnection::updateLooperRegistrationLocked( 1389 const sp<Looper>& looper) { 1390 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) || 1391 mDataInjectionMode; 1392 // If all sensors are unregistered OR Looper has encountered an error, we 1393 // can remove the Fd from the Looper if it has been previously added. 1394 if (!isConnectionActive || mDead) { 1395 if (mHasLooperCallbacks) { 1396 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd()); 1397 looper->removeFd(mChannel->getSendFd()); 1398 mHasLooperCallbacks = false; 1399 } 1400 return; 1401 } 1402 1403 int looper_flags = 0; 1404 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT; 1405 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT; 1406 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 1407 const int handle = mSensorInfo.keyAt(i); 1408 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) { 1409 looper_flags |= ALOOPER_EVENT_INPUT; 1410 break; 1411 } 1412 } 1413 // If flags is still set to zero, we don't need to add this fd to the Looper, if 1414 // the fd has already been added, remove it. This is likely to happen when ALL the 1415 // events stored in the cache have been sent to the corresponding app. 1416 if (looper_flags == 0) { 1417 if (mHasLooperCallbacks) { 1418 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd()); 1419 looper->removeFd(mChannel->getSendFd()); 1420 mHasLooperCallbacks = false; 1421 } 1422 return; 1423 } 1424 // Add the file descriptor to the Looper for receiving acknowledegments if the app has 1425 // registered for wake-up sensors OR for sending events in the cache. 1426 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL); 1427 if (ret == 1) { 1428 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd()); 1429 mHasLooperCallbacks = true; 1430 } else { 1431 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd()); 1432 } 1433} 1434 1435void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) { 1436 Mutex::Autolock _l(mConnectionLock); 1437 ssize_t index = mSensorInfo.indexOfKey(handle); 1438 if (index >= 0) { 1439 FlushInfo& flushInfo = mSensorInfo.editValueAt(index); 1440 flushInfo.mPendingFlushEventsToSend++; 1441 } 1442} 1443 1444status_t SensorService::SensorEventConnection::sendEvents( 1445 sensors_event_t const* buffer, size_t numEvents, 1446 sensors_event_t* scratch, 1447 SensorEventConnection const * const * mapFlushEventsToConnections) { 1448 // filter out events not for this connection 1449 int count = 0; 1450 Mutex::Autolock _l(mConnectionLock); 1451 if (scratch) { 1452 size_t i=0; 1453 while (i<numEvents) { 1454 int32_t sensor_handle = buffer[i].sensor; 1455 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 1456 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ", 1457 buffer[i].meta_data.sensor); 1458 // Setting sensor_handle to the correct sensor to ensure the sensor events per 1459 // connection are filtered correctly. buffer[i].sensor is zero for meta_data 1460 // events. 1461 sensor_handle = buffer[i].meta_data.sensor; 1462 } 1463 ssize_t index = mSensorInfo.indexOfKey(sensor_handle); 1464 // Check if this connection has registered for this sensor. If not continue to the 1465 // next sensor_event. 1466 if (index < 0) { 1467 ++i; 1468 continue; 1469 } 1470 1471 FlushInfo& flushInfo = mSensorInfo.editValueAt(index); 1472 // Check if there is a pending flush_complete event for this sensor on this connection. 1473 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true && 1474 this == mapFlushEventsToConnections[i]) { 1475 flushInfo.mFirstFlushPending = false; 1476 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ", 1477 buffer[i].meta_data.sensor); 1478 ++i; 1479 continue; 1480 } 1481 1482 // If there is a pending flush complete event for this sensor on this connection, 1483 // ignore the event and proceed to the next. 1484 if (flushInfo.mFirstFlushPending) { 1485 ++i; 1486 continue; 1487 } 1488 1489 do { 1490 // Keep copying events into the scratch buffer as long as they are regular 1491 // sensor_events are from the same sensor_handle OR they are flush_complete_events 1492 // from the same sensor_handle AND the current connection is mapped to the 1493 // corresponding flush_complete_event. 1494 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 1495 if (this == mapFlushEventsToConnections[i]) { 1496 scratch[count++] = buffer[i]; 1497 } 1498 ++i; 1499 } else { 1500 // Regular sensor event, just copy it to the scratch buffer. 1501 scratch[count++] = buffer[i++]; 1502 } 1503 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle && 1504 buffer[i].type != SENSOR_TYPE_META_DATA) || 1505 (buffer[i].type == SENSOR_TYPE_META_DATA && 1506 buffer[i].meta_data.sensor == sensor_handle))); 1507 } 1508 } else { 1509 scratch = const_cast<sensors_event_t *>(buffer); 1510 count = numEvents; 1511 } 1512 1513 sendPendingFlushEventsLocked(); 1514 // Early return if there are no events for this connection. 1515 if (count == 0) { 1516 return status_t(NO_ERROR); 1517 } 1518 1519#if DEBUG_CONNECTIONS 1520 mEventsReceived += count; 1521#endif 1522 if (mCacheSize != 0) { 1523 // There are some events in the cache which need to be sent first. Copy this buffer to 1524 // the end of cache. 1525 if (mCacheSize + count <= mMaxCacheSize) { 1526 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t)); 1527 mCacheSize += count; 1528 } else { 1529 // Check if any new sensors have registered on this connection which may have increased 1530 // the max cache size that is desired. 1531 if (mCacheSize + count < computeMaxCacheSizeLocked()) { 1532 reAllocateCacheLocked(scratch, count); 1533 return status_t(NO_ERROR); 1534 } 1535 // Some events need to be dropped. 1536 int remaningCacheSize = mMaxCacheSize - mCacheSize; 1537 if (remaningCacheSize != 0) { 1538 memcpy(&mEventCache[mCacheSize], scratch, 1539 remaningCacheSize * sizeof(sensors_event_t)); 1540 } 1541 int numEventsDropped = count - remaningCacheSize; 1542 countFlushCompleteEventsLocked(mEventCache, numEventsDropped); 1543 // Drop the first "numEventsDropped" in the cache. 1544 memmove(mEventCache, &mEventCache[numEventsDropped], 1545 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t)); 1546 1547 // Copy the remainingEvents in scratch buffer to the end of cache. 1548 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize, 1549 numEventsDropped * sizeof(sensors_event_t)); 1550 } 1551 return status_t(NO_ERROR); 1552 } 1553 1554 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count); 1555 if (index_wake_up_event >= 0) { 1556 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK; 1557 ++mWakeLockRefCount; 1558#if DEBUG_CONNECTIONS 1559 ++mTotalAcksNeeded; 1560#endif 1561 } 1562 1563 // NOTE: ASensorEvent and sensors_event_t are the same type. 1564 ssize_t size = SensorEventQueue::write(mChannel, 1565 reinterpret_cast<ASensorEvent const*>(scratch), count); 1566 if (size < 0) { 1567 // Write error, copy events to local cache. 1568 if (index_wake_up_event >= 0) { 1569 // If there was a wake_up sensor_event, reset the flag. 1570 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK; 1571 if (mWakeLockRefCount > 0) { 1572 --mWakeLockRefCount; 1573 } 1574#if DEBUG_CONNECTIONS 1575 --mTotalAcksNeeded; 1576#endif 1577 } 1578 if (mEventCache == NULL) { 1579 mMaxCacheSize = computeMaxCacheSizeLocked(); 1580 mEventCache = new sensors_event_t[mMaxCacheSize]; 1581 mCacheSize = 0; 1582 } 1583 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t)); 1584 mCacheSize += count; 1585 1586 // Add this file descriptor to the looper to get a callback when this fd is available for 1587 // writing. 1588 updateLooperRegistrationLocked(mService->getLooper()); 1589 return size; 1590 } 1591 1592#if DEBUG_CONNECTIONS 1593 if (size > 0) { 1594 mEventsSent += count; 1595 } 1596#endif 1597 1598 return size < 0 ? status_t(size) : status_t(NO_ERROR); 1599} 1600 1601void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch, 1602 int count) { 1603 sensors_event_t *eventCache_new; 1604 const int new_cache_size = computeMaxCacheSizeLocked(); 1605 // Allocate new cache, copy over events from the old cache & scratch, free up memory. 1606 eventCache_new = new sensors_event_t[new_cache_size]; 1607 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t)); 1608 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t)); 1609 1610 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize, 1611 new_cache_size); 1612 1613 delete mEventCache; 1614 mEventCache = eventCache_new; 1615 mCacheSize += count; 1616 mMaxCacheSize = new_cache_size; 1617} 1618 1619void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() { 1620 ASensorEvent flushCompleteEvent; 1621 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent)); 1622 flushCompleteEvent.type = SENSOR_TYPE_META_DATA; 1623 // Loop through all the sensors for this connection and check if there are any pending 1624 // flush complete events to be sent. 1625 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 1626 FlushInfo& flushInfo = mSensorInfo.editValueAt(i); 1627 while (flushInfo.mPendingFlushEventsToSend > 0) { 1628 const int sensor_handle = mSensorInfo.keyAt(i); 1629 flushCompleteEvent.meta_data.sensor = sensor_handle; 1630 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor(); 1631 if (wakeUpSensor) { 1632 ++mWakeLockRefCount; 1633 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK; 1634 } 1635 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1); 1636 if (size < 0) { 1637 if (wakeUpSensor) --mWakeLockRefCount; 1638 return; 1639 } 1640 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ", 1641 flushCompleteEvent.meta_data.sensor); 1642 flushInfo.mPendingFlushEventsToSend--; 1643 } 1644 } 1645} 1646 1647void SensorService::SensorEventConnection::writeToSocketFromCache() { 1648 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR 1649 // half the size of the socket buffer allocated in BitTube whichever is smaller. 1650 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2, 1651 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2))); 1652 Mutex::Autolock _l(mConnectionLock); 1653 // Send pending flush complete events (if any) 1654 sendPendingFlushEventsLocked(); 1655 for (int numEventsSent = 0; numEventsSent < mCacheSize;) { 1656 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize); 1657 int index_wake_up_event = 1658 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite); 1659 if (index_wake_up_event >= 0) { 1660 mEventCache[index_wake_up_event + numEventsSent].flags |= 1661 WAKE_UP_SENSOR_EVENT_NEEDS_ACK; 1662 ++mWakeLockRefCount; 1663#if DEBUG_CONNECTIONS 1664 ++mTotalAcksNeeded; 1665#endif 1666 } 1667 1668 ssize_t size = SensorEventQueue::write(mChannel, 1669 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent), 1670 numEventsToWrite); 1671 if (size < 0) { 1672 if (index_wake_up_event >= 0) { 1673 // If there was a wake_up sensor_event, reset the flag. 1674 mEventCache[index_wake_up_event + numEventsSent].flags &= 1675 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK; 1676 if (mWakeLockRefCount > 0) { 1677 --mWakeLockRefCount; 1678 } 1679#if DEBUG_CONNECTIONS 1680 --mTotalAcksNeeded; 1681#endif 1682 } 1683 memmove(mEventCache, &mEventCache[numEventsSent], 1684 (mCacheSize - numEventsSent) * sizeof(sensors_event_t)); 1685 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ", 1686 numEventsSent, mCacheSize); 1687 mCacheSize -= numEventsSent; 1688 return; 1689 } 1690 numEventsSent += numEventsToWrite; 1691#if DEBUG_CONNECTIONS 1692 mEventsSentFromCache += numEventsToWrite; 1693#endif 1694 } 1695 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize); 1696 // All events from the cache have been sent. Reset cache size to zero. 1697 mCacheSize = 0; 1698 // There are no more events in the cache. We don't need to poll for write on the fd. 1699 // Update Looper registration. 1700 updateLooperRegistrationLocked(mService->getLooper()); 1701} 1702 1703void SensorService::SensorEventConnection::countFlushCompleteEventsLocked( 1704 sensors_event_t const* scratch, const int numEventsDropped) { 1705 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped); 1706 // Count flushComplete events in the events that are about to the dropped. These will be sent 1707 // separately before the next batch of events. 1708 for (int j = 0; j < numEventsDropped; ++j) { 1709 if (scratch[j].type == SENSOR_TYPE_META_DATA) { 1710 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor); 1711 flushInfo.mPendingFlushEventsToSend++; 1712 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d", 1713 flushInfo.mPendingFlushEventsToSend); 1714 } 1715 } 1716 return; 1717} 1718 1719int SensorService::SensorEventConnection::findWakeUpSensorEventLocked( 1720 sensors_event_t const* scratch, const int count) { 1721 for (int i = 0; i < count; ++i) { 1722 if (mService->isWakeUpSensorEvent(scratch[i])) { 1723 return i; 1724 } 1725 } 1726 return -1; 1727} 1728 1729sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const 1730{ 1731 return mChannel; 1732} 1733 1734status_t SensorService::SensorEventConnection::enableDisable( 1735 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, 1736 int reservedFlags) 1737{ 1738 status_t err; 1739 if (enabled) { 1740 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs, 1741 reservedFlags, mOpPackageName); 1742 1743 } else { 1744 err = mService->disable(this, handle); 1745 } 1746 return err; 1747} 1748 1749status_t SensorService::SensorEventConnection::setEventRate( 1750 int handle, nsecs_t samplingPeriodNs) 1751{ 1752 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName); 1753} 1754 1755status_t SensorService::SensorEventConnection::flush() { 1756 return mService->flushSensor(this, mOpPackageName); 1757} 1758 1759int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) { 1760 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) { 1761 { 1762 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount, 1763 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService 1764 // can release the wake-lock. 1765 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd); 1766 Mutex::Autolock _l(mConnectionLock); 1767 mDead = true; 1768 mWakeLockRefCount = 0; 1769 updateLooperRegistrationLocked(mService->getLooper()); 1770 } 1771 mService->checkWakeLockState(); 1772 if (mDataInjectionMode) { 1773 // If the Looper has encountered some error in data injection mode, reset SensorService 1774 // back to normal mode. 1775 mService->resetToNormalMode(); 1776 mDataInjectionMode = false; 1777 } 1778 return 1; 1779 } 1780 1781 if (events & ALOOPER_EVENT_INPUT) { 1782 unsigned char buf[sizeof(sensors_event_t)]; 1783 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT); 1784 { 1785 Mutex::Autolock _l(mConnectionLock); 1786 if (numBytesRead == sizeof(sensors_event_t)) { 1787 if (!mDataInjectionMode) { 1788 ALOGE("Data injected in normal mode, dropping event" 1789 "package=%s uid=%d", mPackageName.string(), mUid); 1790 // Unregister call backs. 1791 return 0; 1792 } 1793 SensorDevice& dev(SensorDevice::getInstance()); 1794 sensors_event_t sensor_event; 1795 memset(&sensor_event, 0, sizeof(sensor_event)); 1796 memcpy(&sensor_event, buf, sizeof(sensors_event_t)); 1797 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor); 1798 sensor_event.type = sensor.getType(); 1799 dev.injectSensorData(&sensor_event); 1800#if DEBUG_CONNECTIONS 1801 ++mEventsReceived; 1802#endif 1803 } else if (numBytesRead == sizeof(uint32_t)) { 1804 uint32_t numAcks = 0; 1805 memcpy(&numAcks, buf, numBytesRead); 1806 // Sanity check to ensure there are no read errors in recv, numAcks is always 1807 // within the range and not zero. If any of the above don't hold reset 1808 // mWakeLockRefCount to zero. 1809 if (numAcks > 0 && numAcks < mWakeLockRefCount) { 1810 mWakeLockRefCount -= numAcks; 1811 } else { 1812 mWakeLockRefCount = 0; 1813 } 1814#if DEBUG_CONNECTIONS 1815 mTotalAcksReceived += numAcks; 1816#endif 1817 } else { 1818 // Read error, reset wakelock refcount. 1819 mWakeLockRefCount = 0; 1820 } 1821 } 1822 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released 1823 // here as checkWakeLockState() will need it. 1824 if (mWakeLockRefCount == 0) { 1825 mService->checkWakeLockState(); 1826 } 1827 // continue getting callbacks. 1828 return 1; 1829 } 1830 1831 if (events & ALOOPER_EVENT_OUTPUT) { 1832 // send sensor data that is stored in mEventCache for this connection. 1833 mService->sendEventsFromCache(this); 1834 } 1835 return 1; 1836} 1837 1838int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const { 1839 size_t fifoWakeUpSensors = 0; 1840 size_t fifoNonWakeUpSensors = 0; 1841 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 1842 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i)); 1843 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) { 1844 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and 1845 // non wake_up sensors. 1846 if (sensor.isWakeUpSensor()) { 1847 fifoWakeUpSensors += sensor.getFifoReservedEventCount(); 1848 } else { 1849 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount(); 1850 } 1851 } else { 1852 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors. 1853 if (sensor.isWakeUpSensor()) { 1854 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ? 1855 fifoWakeUpSensors : sensor.getFifoMaxEventCount(); 1856 1857 } else { 1858 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ? 1859 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount(); 1860 1861 } 1862 } 1863 } 1864 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) { 1865 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache 1866 // size that is equal to that of the batch mode. 1867 // ALOGW("Write failure in non-batch mode"); 1868 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t); 1869 } 1870 return fifoWakeUpSensors + fifoNonWakeUpSensors; 1871} 1872 1873// --------------------------------------------------------------------------- 1874}; // namespace android 1875 1876