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