OSDN Git Service

e5b6dcf750336135bdfc9225e30c1290ea59da98
[android-x86/frameworks-native.git] / services / sensorservice / SensorService.cpp
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 #include <binder/AppOpsManager.h>
17 #include <binder/BinderService.h>
18 #include <binder/IServiceManager.h>
19 #include <binder/PermissionCache.h>
20 #include <cutils/ashmem.h>
21 #include <cutils/properties.h>
22 #include <hardware/sensors.h>
23 #include <hardware_legacy/power.h>
24 #include <log/log.h>
25 #include <openssl/digest.h>
26 #include <openssl/hmac.h>
27 #include <openssl/rand.h>
28 #include <sensor/SensorEventQueue.h>
29 #include <utils/SystemClock.h>
30
31 #include "BatteryService.h"
32 #include "CorrectedGyroSensor.h"
33 #include "GravitySensor.h"
34 #include "LinearAccelerationSensor.h"
35 #include "OrientationSensor.h"
36 #include "RotationVectorSensor.h"
37 #include "SensorFusion.h"
38 #include "SensorInterface.h"
39
40 #include "SensorService.h"
41 #include "SensorDirectConnection.h"
42 #include "SensorEventAckReceiver.h"
43 #include "SensorEventConnection.h"
44 #include "SensorRecord.h"
45 #include "SensorRegistrationInfo.h"
46
47 #include <inttypes.h>
48 #include <math.h>
49 #include <sched.h>
50 #include <stdint.h>
51 #include <sys/socket.h>
52 #include <sys/stat.h>
53 #include <sys/types.h>
54 #include <unistd.h>
55
56 namespace android {
57 // ---------------------------------------------------------------------------
58
59 /*
60  * Notes:
61  *
62  * - what about a gyro-corrected magnetic-field sensor?
63  * - run mag sensor from time to time to force calibration
64  * - gravity sensor length is wrong (=> drift in linear-acc sensor)
65  *
66  */
67
68 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
69 uint8_t SensorService::sHmacGlobalKey[128] = {};
70 bool SensorService::sHmacGlobalKeyIsValid = false;
71
72 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
73 #define SENSOR_SERVICE_HMAC_KEY_FILE  SENSOR_SERVICE_DIR "/hmac_key"
74 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
75
76 // Permissions.
77 static const String16 sDumpPermission("android.permission.DUMP");
78 static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
79
80 SensorService::SensorService()
81     : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
82       mWakeLockAcquired(false) {
83 }
84
85 bool SensorService::initializeHmacKey() {
86     int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
87     if (fd != -1) {
88         int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
89         close(fd);
90         if (result == sizeof(sHmacGlobalKey)) {
91             return true;
92         }
93         ALOGW("Unable to read HMAC key; generating new one.");
94     }
95
96     if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
97         ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
98         return false;
99     }
100
101     // We need to make sure this is only readable to us.
102     bool wroteKey = false;
103     mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
104     fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
105               S_IRUSR|S_IWUSR);
106     if (fd != -1) {
107         int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
108         close(fd);
109         wroteKey = (result == sizeof(sHmacGlobalKey));
110     }
111     if (wroteKey) {
112         ALOGI("Generated new HMAC key.");
113     } else {
114         ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
115               "after reboot.");
116     }
117     // Even if we failed to write the key we return true, because we did
118     // initialize the HMAC key.
119     return true;
120 }
121
122 // Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
123 void SensorService::enableSchedFifoMode() {
124     struct sched_param param = {0};
125     param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
126     if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
127         ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
128     }
129 }
130
131 void SensorService::onFirstRef() {
132     ALOGD("nuSensorService starting...");
133     SensorDevice& dev(SensorDevice::getInstance());
134
135     sHmacGlobalKeyIsValid = initializeHmacKey();
136
137     if (dev.initCheck() == NO_ERROR) {
138         sensor_t const* list;
139         ssize_t count = dev.getSensorList(&list);
140         if (count > 0) {
141             ssize_t orientationIndex = -1;
142             bool hasGyro = false, hasAccel = false, hasMag = false;
143             uint32_t virtualSensorsNeeds =
144                     (1<<SENSOR_TYPE_GRAVITY) |
145                     (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
146                     (1<<SENSOR_TYPE_ROTATION_VECTOR) |
147                     (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
148                     (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
149
150             for (ssize_t i=0 ; i<count ; i++) {
151                 bool useThisSensor=true;
152
153                 switch (list[i].type) {
154                     case SENSOR_TYPE_ACCELEROMETER:
155                         hasAccel = true;
156                         break;
157                     case SENSOR_TYPE_MAGNETIC_FIELD:
158                         hasMag = true;
159                         break;
160                     case SENSOR_TYPE_ORIENTATION:
161                         orientationIndex = i;
162                         break;
163                     case SENSOR_TYPE_GYROSCOPE:
164                     case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
165                         hasGyro = true;
166                         break;
167                     case SENSOR_TYPE_GRAVITY:
168                     case SENSOR_TYPE_LINEAR_ACCELERATION:
169                     case SENSOR_TYPE_ROTATION_VECTOR:
170                     case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
171                     case SENSOR_TYPE_GAME_ROTATION_VECTOR:
172                         if (IGNORE_HARDWARE_FUSION) {
173                             useThisSensor = false;
174                         } else {
175                             virtualSensorsNeeds &= ~(1<<list[i].type);
176                         }
177                         break;
178                 }
179                 if (useThisSensor) {
180                     registerSensor( new HardwareSensor(list[i]) );
181                 }
182             }
183
184             // it's safe to instantiate the SensorFusion object here
185             // (it wants to be instantiated after h/w sensors have been
186             // registered)
187             SensorFusion::getInstance();
188
189             if (hasGyro && hasAccel && hasMag) {
190                 // Add Android virtual sensors if they're not already
191                 // available in the HAL
192                 bool needRotationVector =
193                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
194
195                 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
196                 registerSensor(new OrientationSensor(), !needRotationVector, true);
197
198                 bool needLinearAcceleration =
199                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
200
201                 registerSensor(new LinearAccelerationSensor(list, count),
202                                !needLinearAcceleration, true);
203
204                 // virtual debugging sensors are not for user
205                 registerSensor( new CorrectedGyroSensor(list, count), true, true);
206                 registerSensor( new GyroDriftSensor(), true, true);
207             }
208
209             if (hasAccel && hasGyro) {
210                 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
211                 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
212
213                 bool needGameRotationVector =
214                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
215                 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
216             }
217
218             if (hasAccel && hasMag) {
219                 bool needGeoMagRotationVector =
220                         (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
221                 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
222             }
223
224             // Check if the device really supports batching by looking at the FIFO event
225             // counts for each sensor.
226             bool batchingSupported = false;
227             mSensors.forEachSensor(
228                     [&batchingSupported] (const Sensor& s) -> bool {
229                         if (s.getFifoMaxEventCount() > 0) {
230                             batchingSupported = true;
231                         }
232                         return !batchingSupported;
233                     });
234
235             if (batchingSupported) {
236                 // Increase socket buffer size to a max of 100 KB for batching capabilities.
237                 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
238             } else {
239                 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
240             }
241
242             // Compare the socketBufferSize value against the system limits and limit
243             // it to maxSystemSocketBufferSize if necessary.
244             FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
245             char line[128];
246             if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
247                 line[sizeof(line) - 1] = '\0';
248                 size_t maxSystemSocketBufferSize;
249                 sscanf(line, "%zu", &maxSystemSocketBufferSize);
250                 if (mSocketBufferSize > maxSystemSocketBufferSize) {
251                     mSocketBufferSize = maxSystemSocketBufferSize;
252                 }
253             }
254             if (fp) {
255                 fclose(fp);
256             }
257
258             mWakeLockAcquired = false;
259             mLooper = new Looper(false);
260             const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
261             mSensorEventBuffer = new sensors_event_t[minBufferSize];
262             mSensorEventScratch = new sensors_event_t[minBufferSize];
263             mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
264             mCurrentOperatingMode = NORMAL;
265
266             mNextSensorRegIndex = 0;
267             for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
268                 mLastNSensorRegistrations.push();
269             }
270
271             mInitCheck = NO_ERROR;
272             mAckReceiver = new SensorEventAckReceiver(this);
273             mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
274             run("SensorService", PRIORITY_URGENT_DISPLAY);
275
276             // priority can only be changed after run
277             enableSchedFifoMode();
278         }
279     }
280 }
281
282 const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
283     int handle = s->getSensor().getHandle();
284     int type = s->getSensor().getType();
285     if (mSensors.add(handle, s, isDebug, isVirtual)){
286         mRecentEvent.emplace(handle, new RecentEventLogger(type));
287         return s->getSensor();
288     } else {
289         return mSensors.getNonSensor();
290     }
291 }
292
293 const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
294     return registerSensor(s, isDebug);
295 }
296
297 bool SensorService::unregisterDynamicSensorLocked(int handle) {
298     bool ret = mSensors.remove(handle);
299
300     const auto i = mRecentEvent.find(handle);
301     if (i != mRecentEvent.end()) {
302         delete i->second;
303         mRecentEvent.erase(i);
304     }
305     return ret;
306 }
307
308 const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
309     return registerSensor(s, isDebug, true);
310 }
311
312 SensorService::~SensorService() {
313     for (auto && entry : mRecentEvent) {
314         delete entry.second;
315     }
316 }
317
318 status_t SensorService::dump(int fd, const Vector<String16>& args) {
319     String8 result;
320     if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
321         result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
322                 IPCThreadState::self()->getCallingPid(),
323                 IPCThreadState::self()->getCallingUid());
324     } else {
325         bool privileged = IPCThreadState::self()->getCallingUid() == 0;
326         if (args.size() > 2) {
327            return INVALID_OPERATION;
328         }
329         Mutex::Autolock _l(mLock);
330         SensorDevice& dev(SensorDevice::getInstance());
331         if (args.size() == 2 && args[0] == String16("restrict")) {
332             // If already in restricted mode. Ignore.
333             if (mCurrentOperatingMode == RESTRICTED) {
334                 return status_t(NO_ERROR);
335             }
336             // If in any mode other than normal, ignore.
337             if (mCurrentOperatingMode != NORMAL) {
338                 return INVALID_OPERATION;
339             }
340
341             mCurrentOperatingMode = RESTRICTED;
342             // temporarily stop all sensor direct report
343             for (auto &i : mDirectConnections) {
344                 sp<SensorDirectConnection> connection(i.promote());
345                 if (connection != nullptr) {
346                     connection->stopAll(true /* backupRecord */);
347                 }
348             }
349
350             dev.disableAllSensors();
351             // Clear all pending flush connections for all active sensors. If one of the active
352             // connections has called flush() and the underlying sensor has been disabled before a
353             // flush complete event is returned, we need to remove the connection from this queue.
354             for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
355                 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
356             }
357             mWhiteListedPackage.setTo(String8(args[1]));
358             return status_t(NO_ERROR);
359         } else if (args.size() == 1 && args[0] == String16("enable")) {
360             // If currently in restricted mode, reset back to NORMAL mode else ignore.
361             if (mCurrentOperatingMode == RESTRICTED) {
362                 mCurrentOperatingMode = NORMAL;
363                 dev.enableAllSensors();
364                 // recover all sensor direct report
365                 for (auto &i : mDirectConnections) {
366                     sp<SensorDirectConnection> connection(i.promote());
367                     if (connection != nullptr) {
368                         connection->recoverAll();
369                     }
370                 }
371             }
372             if (mCurrentOperatingMode == DATA_INJECTION) {
373                resetToNormalModeLocked();
374             }
375             mWhiteListedPackage.clear();
376             return status_t(NO_ERROR);
377         } else if (args.size() == 2 && args[0] == String16("data_injection")) {
378             if (mCurrentOperatingMode == NORMAL) {
379                 dev.disableAllSensors();
380                 status_t err = dev.setMode(DATA_INJECTION);
381                 if (err == NO_ERROR) {
382                     mCurrentOperatingMode = DATA_INJECTION;
383                 } else {
384                     // Re-enable sensors.
385                     dev.enableAllSensors();
386                 }
387                 mWhiteListedPackage.setTo(String8(args[1]));
388                 return NO_ERROR;
389             } else if (mCurrentOperatingMode == DATA_INJECTION) {
390                 // Already in DATA_INJECTION mode. Treat this as a no_op.
391                 return NO_ERROR;
392             } else {
393                 // Transition to data injection mode supported only from NORMAL mode.
394                 return INVALID_OPERATION;
395             }
396         } else if (!mSensors.hasAnySensor()) {
397             result.append("No Sensors on the device\n");
398             result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
399         } else {
400             // Default dump the sensor list and debugging information.
401             //
402             result.append("Sensor Device:\n");
403             result.append(SensorDevice::getInstance().dump().c_str());
404
405             result.append("Sensor List:\n");
406             result.append(mSensors.dump().c_str());
407
408             result.append("Fusion States:\n");
409             SensorFusion::getInstance().dump(result);
410
411             result.append("Recent Sensor events:\n");
412             for (auto&& i : mRecentEvent) {
413                 sp<SensorInterface> s = mSensors.getInterface(i.first);
414                 if (!i.second->isEmpty()) {
415                     if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
416                         i.second->setFormat("normal");
417                     } else {
418                         i.second->setFormat("mask_data");
419                     }
420                     // if there is events and sensor does not need special permission.
421                     result.appendFormat("%s: ", s->getSensor().getName().string());
422                     result.append(i.second->dump().c_str());
423                 }
424             }
425
426             result.append("Active sensors:\n");
427             for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
428                 int handle = mActiveSensors.keyAt(i);
429                 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
430                         getSensorName(handle).string(),
431                         handle,
432                         mActiveSensors.valueAt(i)->getNumConnections());
433             }
434
435             result.appendFormat("Socket Buffer size = %zd events\n",
436                                 mSocketBufferSize/sizeof(sensors_event_t));
437             result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
438                     "not held");
439             result.appendFormat("Mode :");
440             switch(mCurrentOperatingMode) {
441                case NORMAL:
442                    result.appendFormat(" NORMAL\n");
443                    break;
444                case RESTRICTED:
445                    result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
446                    break;
447                case DATA_INJECTION:
448                    result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
449             }
450
451             result.appendFormat("%zd active connections\n", mActiveConnections.size());
452             for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
453                 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
454                 if (connection != 0) {
455                     result.appendFormat("Connection Number: %zu \n", i);
456                     connection->dump(result);
457                 }
458             }
459
460             result.appendFormat("%zd direct connections\n", mDirectConnections.size());
461             for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
462                 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
463                 if (connection != nullptr) {
464                     result.appendFormat("Direct connection %zu:\n", i);
465                     connection->dump(result);
466                 }
467             }
468
469             result.appendFormat("Previous Registrations:\n");
470             // Log in the reverse chronological order.
471             int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
472                 SENSOR_REGISTRATIONS_BUF_SIZE;
473             const int startIndex = currentIndex;
474             do {
475                 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
476                 if (SensorRegistrationInfo::isSentinel(reg_info)) {
477                     // Ignore sentinel, proceed to next item.
478                     currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
479                         SENSOR_REGISTRATIONS_BUF_SIZE;
480                     continue;
481                 }
482                 result.appendFormat("%s\n", reg_info.dump().c_str());
483                 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
484                         SENSOR_REGISTRATIONS_BUF_SIZE;
485             } while(startIndex != currentIndex);
486         }
487     }
488     write(fd, result.string(), result.size());
489     return NO_ERROR;
490 }
491
492 //TODO: move to SensorEventConnection later
493 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
494         sensors_event_t const* buffer, const int count) {
495     for (int i=0 ; i<count ; i++) {
496         int handle = buffer[i].sensor;
497         if (buffer[i].type == SENSOR_TYPE_META_DATA) {
498             handle = buffer[i].meta_data.sensor;
499         }
500         if (connection->hasSensor(handle)) {
501             sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
502             // If this buffer has an event from a one_shot sensor and this connection is registered
503             // for this particular one_shot sensor, try cleaning up the connection.
504             if (si != nullptr &&
505                 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
506                 si->autoDisable(connection.get(), handle);
507                 cleanupWithoutDisableLocked(connection, handle);
508             }
509
510         }
511    }
512 }
513
514 bool SensorService::threadLoop() {
515     ALOGD("nuSensorService thread starting...");
516
517     // each virtual sensor could generate an event per "real" event, that's why we need to size
518     // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
519     // aggressive, but guaranteed to be enough.
520     const size_t vcount = mSensors.getVirtualSensors().size();
521     const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
522     const size_t numEventMax = minBufferSize / (1 + vcount);
523
524     SensorDevice& device(SensorDevice::getInstance());
525
526     const int halVersion = device.getHalDeviceVersion();
527     do {
528         ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
529         if (count < 0) {
530             ALOGE("sensor poll failed (%s)", strerror(-count));
531             break;
532         }
533
534         // Reset sensors_event_t.flags to zero for all events in the buffer.
535         for (int i = 0; i < count; i++) {
536              mSensorEventBuffer[i].flags = 0;
537         }
538
539         // Make a copy of the connection vector as some connections may be removed during the course
540         // of this loop (especially when one-shot sensor events are present in the sensor_event
541         // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
542         // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
543         // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
544         // strongPointers to a vector before the lock is acquired.
545         SortedVector< sp<SensorEventConnection> > activeConnections;
546         populateActiveConnections(&activeConnections);
547
548         Mutex::Autolock _l(mLock);
549         // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
550         // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
551         // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
552         // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
553         // releasing the wakelock.
554         bool bufferHasWakeUpEvent = false;
555         for (int i = 0; i < count; i++) {
556             if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
557                 bufferHasWakeUpEvent = true;
558                 break;
559             }
560         }
561
562         if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
563             setWakeLockAcquiredLocked(true);
564         }
565         recordLastValueLocked(mSensorEventBuffer, count);
566
567         // handle virtual sensors
568         if (count && vcount) {
569             sensors_event_t const * const event = mSensorEventBuffer;
570             if (!mActiveVirtualSensors.empty()) {
571                 size_t k = 0;
572                 SensorFusion& fusion(SensorFusion::getInstance());
573                 if (fusion.isEnabled()) {
574                     for (size_t i=0 ; i<size_t(count) ; i++) {
575                         fusion.process(event[i]);
576                     }
577                 }
578                 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
579                     for (int handle : mActiveVirtualSensors) {
580                         if (count + k >= minBufferSize) {
581                             ALOGE("buffer too small to hold all events: "
582                                     "count=%zd, k=%zu, size=%zu",
583                                     count, k, minBufferSize);
584                             break;
585                         }
586                         sensors_event_t out;
587                         sp<SensorInterface> si = mSensors.getInterface(handle);
588                         if (si == nullptr) {
589                             ALOGE("handle %d is not an valid virtual sensor", handle);
590                             continue;
591                         }
592
593                         if (si->process(&out, event[i])) {
594                             mSensorEventBuffer[count + k] = out;
595                             k++;
596                         }
597                     }
598                 }
599                 if (k) {
600                     // record the last synthesized values
601                     recordLastValueLocked(&mSensorEventBuffer[count], k);
602                     count += k;
603                     // sort the buffer by time-stamps
604                     sortEventBuffer(mSensorEventBuffer, count);
605                 }
606             }
607         }
608
609         // handle backward compatibility for RotationVector sensor
610         if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
611             for (int i = 0; i < count; i++) {
612                 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
613                     // All the 4 components of the quaternion should be available
614                     // No heading accuracy. Set it to -1
615                     mSensorEventBuffer[i].data[4] = -1;
616                 }
617             }
618         }
619
620         for (int i = 0; i < count; ++i) {
621             // Map flush_complete_events in the buffer to SensorEventConnections which called flush
622             // on the hardware sensor. mapFlushEventsToConnections[i] will be the
623             // SensorEventConnection mapped to the corresponding flush_complete_event in
624             // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
625             mMapFlushEventsToConnections[i] = NULL;
626             if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
627                 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
628                 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
629                 if (rec != NULL) {
630                     mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
631                     rec->removeFirstPendingFlushConnection();
632                 }
633             }
634
635             // handle dynamic sensor meta events, process registration and unregistration of dynamic
636             // sensor based on content of event.
637             if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
638                 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
639                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
640                     const sensor_t& dynamicSensor =
641                             *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
642                     ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
643                           handle, dynamicSensor.type, dynamicSensor.name);
644
645                     if (mSensors.isNewHandle(handle)) {
646                         const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
647                         sensor_t s = dynamicSensor;
648                         // make sure the dynamic sensor flag is set
649                         s.flags |= DYNAMIC_SENSOR_MASK;
650                         // force the handle to be consistent
651                         s.handle = handle;
652
653                         SensorInterface *si = new HardwareSensor(s, uuid);
654
655                         // This will release hold on dynamic sensor meta, so it should be called
656                         // after Sensor object is created.
657                         device.handleDynamicSensorConnection(handle, true /*connected*/);
658                         registerDynamicSensorLocked(si);
659                     } else {
660                         ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
661                     }
662                 } else {
663                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
664                     ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
665
666                     device.handleDynamicSensorConnection(handle, false /*connected*/);
667                     if (!unregisterDynamicSensorLocked(handle)) {
668                         ALOGE("Dynamic sensor release error.");
669                     }
670
671                     size_t numConnections = activeConnections.size();
672                     for (size_t i=0 ; i < numConnections; ++i) {
673                         if (activeConnections[i] != NULL) {
674                             activeConnections[i]->removeSensor(handle);
675                         }
676                     }
677                 }
678             }
679         }
680
681
682         // Send our events to clients. Check the state of wake lock for each client and release the
683         // lock if none of the clients need it.
684         bool needsWakeLock = false;
685         size_t numConnections = activeConnections.size();
686         for (size_t i=0 ; i < numConnections; ++i) {
687             if (activeConnections[i] != 0) {
688                 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
689                         mMapFlushEventsToConnections);
690                 needsWakeLock |= activeConnections[i]->needsWakeLock();
691                 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
692                 // Early check for one-shot sensors.
693                 if (activeConnections[i]->hasOneShotSensors()) {
694                     cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
695                             count);
696                 }
697             }
698         }
699
700         if (mWakeLockAcquired && !needsWakeLock) {
701             setWakeLockAcquiredLocked(false);
702         }
703     } while (!Thread::exitPending());
704
705     ALOGW("Exiting SensorService::threadLoop => aborting...");
706     abort();
707     return false;
708 }
709
710 sp<Looper> SensorService::getLooper() const {
711     return mLooper;
712 }
713
714 void SensorService::resetAllWakeLockRefCounts() {
715     SortedVector< sp<SensorEventConnection> > activeConnections;
716     populateActiveConnections(&activeConnections);
717     {
718         Mutex::Autolock _l(mLock);
719         for (size_t i=0 ; i < activeConnections.size(); ++i) {
720             if (activeConnections[i] != 0) {
721                 activeConnections[i]->resetWakeLockRefCount();
722             }
723         }
724         setWakeLockAcquiredLocked(false);
725     }
726 }
727
728 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
729     if (acquire) {
730         if (!mWakeLockAcquired) {
731             acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
732             mWakeLockAcquired = true;
733         }
734         mLooper->wake();
735     } else {
736         if (mWakeLockAcquired) {
737             release_wake_lock(WAKE_LOCK_NAME);
738             mWakeLockAcquired = false;
739         }
740     }
741 }
742
743 bool SensorService::isWakeLockAcquired() {
744     Mutex::Autolock _l(mLock);
745     return mWakeLockAcquired;
746 }
747
748 bool SensorService::SensorEventAckReceiver::threadLoop() {
749     ALOGD("new thread SensorEventAckReceiver");
750     sp<Looper> looper = mService->getLooper();
751     do {
752         bool wakeLockAcquired = mService->isWakeLockAcquired();
753         int timeout = -1;
754         if (wakeLockAcquired) timeout = 5000;
755         int ret = looper->pollOnce(timeout);
756         if (ret == ALOOPER_POLL_TIMEOUT) {
757            mService->resetAllWakeLockRefCounts();
758         }
759     } while(!Thread::exitPending());
760     return false;
761 }
762
763 void SensorService::recordLastValueLocked(
764         const sensors_event_t* buffer, size_t count) {
765     for (size_t i = 0; i < count; i++) {
766         if (buffer[i].type == SENSOR_TYPE_META_DATA ||
767             buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
768             buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
769             continue;
770         }
771
772         auto logger = mRecentEvent.find(buffer[i].sensor);
773         if (logger != mRecentEvent.end()) {
774             logger->second->addEvent(buffer[i]);
775         }
776     }
777 }
778
779 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
780     struct compar {
781         static int cmp(void const* lhs, void const* rhs) {
782             sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
783             sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
784             return l->timestamp - r->timestamp;
785         }
786     };
787     qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
788 }
789
790 String8 SensorService::getSensorName(int handle) const {
791     return mSensors.getName(handle);
792 }
793
794 bool SensorService::isVirtualSensor(int handle) const {
795     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
796     return sensor != nullptr && sensor->isVirtual();
797 }
798
799 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
800     int handle = event.sensor;
801     if (event.type == SENSOR_TYPE_META_DATA) {
802         handle = event.meta_data.sensor;
803     }
804     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
805     return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
806 }
807
808 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
809     if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
810         // UUID is not supported for this device.
811         return 0;
812     }
813     if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
814         // This sensor can be uniquely identified in the system by
815         // the combination of its type and name.
816         return -1;
817     }
818
819     // We have a dynamic sensor.
820
821     if (!sHmacGlobalKeyIsValid) {
822         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
823         ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
824         return 0;
825     }
826
827     // We want each app author/publisher to get a different ID, so that the
828     // same dynamic sensor cannot be tracked across apps by multiple
829     // authors/publishers.  So we use both our UUID and our User ID.
830     // Note potential confusion:
831     //     UUID => Universally Unique Identifier.
832     //     UID  => User Identifier.
833     // We refrain from using "uid" except as needed by API to try to
834     // keep this distinction clear.
835
836     auto appUserId = IPCThreadState::self()->getCallingUid();
837     uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
838     memcpy(uuidAndApp, &uuid, sizeof(uuid));
839     memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
840
841     // Now we use our key on our UUID/app combo to get the hash.
842     uint8_t hash[EVP_MAX_MD_SIZE];
843     unsigned int hashLen;
844     if (HMAC(EVP_sha256(),
845              sHmacGlobalKey, sizeof(sHmacGlobalKey),
846              uuidAndApp, sizeof(uuidAndApp),
847              hash, &hashLen) == nullptr) {
848         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
849         ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
850         return 0;
851     }
852
853     int32_t id = 0;
854     if (hashLen < sizeof(id)) {
855         // We never expect this case, but out of paranoia, we handle it.
856         // Our 'id' length is already quite small, we don't want the
857         // effective length of it to be even smaller.
858         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
859         ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
860         return 0;
861     }
862
863     // This is almost certainly less than all of 'hash', but it's as secure
864     // as we can be with our current 'id' length.
865     memcpy(&id, hash, sizeof(id));
866
867     // Note at the beginning of the function that we return the values of
868     // 0 and -1 to represent special cases.  As a result, we can't return
869     // those as dynamic sensor IDs.  If we happened to hash to one of those
870     // values, we change 'id' so we report as a dynamic sensor, and not as
871     // one of those special cases.
872     if (id == -1) {
873         id = -2;
874     } else if (id == 0) {
875         id = 1;
876     }
877     return id;
878 }
879
880 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
881     for (auto &sensor : sensorList) {
882         int32_t id = getIdFromUuid(sensor.getUuid());
883         sensor.setId(id);
884     }
885 }
886
887 Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
888     char value[PROPERTY_VALUE_MAX];
889     property_get("debug.sensors", value, "0");
890     const Vector<Sensor>& initialSensorList = (atoi(value)) ?
891             mSensors.getUserDebugSensors() : mSensors.getUserSensors();
892     Vector<Sensor> accessibleSensorList;
893     for (size_t i = 0; i < initialSensorList.size(); i++) {
894         Sensor sensor = initialSensorList[i];
895         accessibleSensorList.add(sensor);
896     }
897     makeUuidsIntoIdsForSensorList(accessibleSensorList);
898     return accessibleSensorList;
899 }
900
901 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
902     Vector<Sensor> accessibleSensorList;
903     mSensors.forEachSensor(
904             [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
905                 if (sensor.isDynamicSensor()) {
906                     if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
907                         accessibleSensorList.add(sensor);
908                     } else {
909                         ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
910                               sensor.getName().string(),
911                               sensor.getRequiredPermission().string(),
912                               sensor.getRequiredAppOp());
913                     }
914                 }
915                 return true;
916             });
917     makeUuidsIntoIdsForSensorList(accessibleSensorList);
918     return accessibleSensorList;
919 }
920
921 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
922         int requestedMode, const String16& opPackageName) {
923     // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
924     if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
925         return NULL;
926     }
927
928     Mutex::Autolock _l(mLock);
929     // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
930     // operating in DI mode.
931     if (requestedMode == DATA_INJECTION) {
932         if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
933         if (!isWhiteListedPackage(packageName)) return NULL;
934     }
935
936     uid_t uid = IPCThreadState::self()->getCallingUid();
937     pid_t pid = IPCThreadState::self()->getCallingPid();
938
939     String8 connPackageName =
940             (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
941     String16 connOpPackageName =
942             (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
943     sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
944             requestedMode == DATA_INJECTION, connOpPackageName));
945     if (requestedMode == DATA_INJECTION) {
946         if (mActiveConnections.indexOf(result) < 0) {
947             mActiveConnections.add(result);
948         }
949         // Add the associated file descriptor to the Looper for polling whenever there is data to
950         // be injected.
951         result->updateLooperRegistration(mLooper);
952     }
953     return result;
954 }
955
956 int SensorService::isDataInjectionEnabled() {
957     Mutex::Autolock _l(mLock);
958     return (mCurrentOperatingMode == DATA_INJECTION);
959 }
960
961 sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
962         const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
963         const native_handle *resource) {
964     Mutex::Autolock _l(mLock);
965
966     struct sensors_direct_mem_t mem = {
967         .type = type,
968         .format = format,
969         .size = size,
970         .handle = resource,
971     };
972     uid_t uid = IPCThreadState::self()->getCallingUid();
973
974     if (mem.handle == nullptr) {
975         ALOGE("Failed to clone resource handle");
976         return nullptr;
977     }
978
979     // check format
980     if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
981         ALOGE("Direct channel format %d is unsupported!", format);
982         return nullptr;
983     }
984
985     // check for duplication
986     for (auto &i : mDirectConnections) {
987         sp<SensorDirectConnection> connection(i.promote());
988         if (connection != nullptr && connection->isEquivalent(&mem)) {
989             ALOGE("Duplicate create channel request for the same share memory");
990             return nullptr;
991         }
992     }
993
994     // check specific to memory type
995     switch(type) {
996         case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
997             if (resource->numFds < 1) {
998                 ALOGE("Ashmem direct channel requires a memory region to be supplied");
999                 android_errorWriteLog(0x534e4554, "70986337");  // SafetyNet
1000                 return nullptr;
1001             }
1002             int fd = resource->data[0];
1003             int size2 = ashmem_get_size_region(fd);
1004             // check size consistency
1005             if (size2 < static_cast<int64_t>(size)) {
1006                 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1007                       size, size2);
1008                 return nullptr;
1009             }
1010             break;
1011         }
1012         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1013             // no specific checks for gralloc
1014             break;
1015         default:
1016             ALOGE("Unknown direct connection memory type %d", type);
1017             return nullptr;
1018     }
1019
1020     native_handle_t *clone = native_handle_clone(resource);
1021     if (!clone) {
1022         return nullptr;
1023     }
1024
1025     SensorDirectConnection* conn = nullptr;
1026     SensorDevice& dev(SensorDevice::getInstance());
1027     int channelHandle = dev.registerDirectChannel(&mem);
1028
1029     if (channelHandle <= 0) {
1030         ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1031     } else {
1032         mem.handle = clone;
1033         conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1034     }
1035
1036     if (conn == nullptr) {
1037         native_handle_close(clone);
1038         native_handle_delete(clone);
1039     } else {
1040         // add to list of direct connections
1041         // sensor service should never hold pointer or sp of SensorDirectConnection object.
1042         mDirectConnections.add(wp<SensorDirectConnection>(conn));
1043     }
1044     return conn;
1045 }
1046
1047 int SensorService::setOperationParameter(
1048             int32_t handle, int32_t type,
1049             const Vector<float> &floats, const Vector<int32_t> &ints) {
1050     Mutex::Autolock _l(mLock);
1051
1052     if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
1053         return PERMISSION_DENIED;
1054     }
1055
1056     bool isFloat = true;
1057     bool isCustom = false;
1058     size_t expectSize = INT32_MAX;
1059     switch (type) {
1060         case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1061             isFloat = true;
1062             expectSize = 3;
1063             break;
1064         case AINFO_LOCAL_GRAVITY:
1065             isFloat = true;
1066             expectSize = 1;
1067             break;
1068         case AINFO_DOCK_STATE:
1069         case AINFO_HIGH_PERFORMANCE_MODE:
1070         case AINFO_MAGNETIC_FIELD_CALIBRATION:
1071             isFloat = false;
1072             expectSize = 1;
1073             break;
1074         default:
1075             // CUSTOM events must only contain float data; it may have variable size
1076             if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1077                     ints.size() ||
1078                     sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1079                     handle < 0) {
1080                 return BAD_VALUE;
1081             }
1082             isFloat = true;
1083             isCustom = true;
1084             expectSize = floats.size();
1085             break;
1086     }
1087
1088     if (!isCustom && handle != -1) {
1089         return BAD_VALUE;
1090     }
1091
1092     // three events: first one is begin tag, last one is end tag, the one in the middle
1093     // is the payload.
1094     sensors_event_t event[3];
1095     int64_t timestamp = elapsedRealtimeNano();
1096     for (sensors_event_t* i = event; i < event + 3; i++) {
1097         *i = (sensors_event_t) {
1098             .version = sizeof(sensors_event_t),
1099             .sensor = handle,
1100             .type = SENSOR_TYPE_ADDITIONAL_INFO,
1101             .timestamp = timestamp++,
1102             .additional_info = (additional_info_event_t) {
1103                 .serial = 0
1104             }
1105         };
1106     }
1107
1108     event[0].additional_info.type = AINFO_BEGIN;
1109     event[1].additional_info.type = type;
1110     event[2].additional_info.type = AINFO_END;
1111
1112     if (isFloat) {
1113         if (floats.size() != expectSize) {
1114             return BAD_VALUE;
1115         }
1116         for (size_t i = 0; i < expectSize; ++i) {
1117             event[1].additional_info.data_float[i] = floats[i];
1118         }
1119     } else {
1120         if (ints.size() != expectSize) {
1121             return BAD_VALUE;
1122         }
1123         for (size_t i = 0; i < expectSize; ++i) {
1124             event[1].additional_info.data_int32[i] = ints[i];
1125         }
1126     }
1127
1128     SensorDevice& dev(SensorDevice::getInstance());
1129     for (sensors_event_t* i = event; i < event + 3; i++) {
1130         int ret = dev.injectSensorData(i);
1131         if (ret != NO_ERROR) {
1132             return ret;
1133         }
1134     }
1135     return NO_ERROR;
1136 }
1137
1138 status_t SensorService::resetToNormalMode() {
1139     Mutex::Autolock _l(mLock);
1140     return resetToNormalModeLocked();
1141 }
1142
1143 status_t SensorService::resetToNormalModeLocked() {
1144     SensorDevice& dev(SensorDevice::getInstance());
1145     status_t err = dev.setMode(NORMAL);
1146     if (err == NO_ERROR) {
1147         mCurrentOperatingMode = NORMAL;
1148         dev.enableAllSensors();
1149     }
1150     return err;
1151 }
1152
1153 void SensorService::cleanupConnection(SensorEventConnection* c) {
1154     Mutex::Autolock _l(mLock);
1155     const wp<SensorEventConnection> connection(c);
1156     size_t size = mActiveSensors.size();
1157     ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
1158     for (size_t i=0 ; i<size ; ) {
1159         int handle = mActiveSensors.keyAt(i);
1160         if (c->hasSensor(handle)) {
1161             ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
1162             sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1163             if (sensor != nullptr) {
1164                 sensor->activate(c, false);
1165             } else {
1166                 ALOGE("sensor interface of handle=0x%08x is null!", handle);
1167             }
1168             c->removeSensor(handle);
1169         }
1170         SensorRecord* rec = mActiveSensors.valueAt(i);
1171         ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
1172         ALOGD_IF(DEBUG_CONNECTIONS,
1173                 "removing connection %p for sensor[%zu].handle=0x%08x",
1174                 c, i, handle);
1175
1176         if (rec && rec->removeConnection(connection)) {
1177             ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
1178             mActiveSensors.removeItemsAt(i, 1);
1179             mActiveVirtualSensors.erase(handle);
1180             delete rec;
1181             size--;
1182         } else {
1183             i++;
1184         }
1185     }
1186     c->updateLooperRegistration(mLooper);
1187     mActiveConnections.remove(connection);
1188     BatteryService::cleanup(c->getUid());
1189     if (c->needsWakeLock()) {
1190         checkWakeLockStateLocked();
1191     }
1192
1193     SensorDevice& dev(SensorDevice::getInstance());
1194     dev.notifyConnectionDestroyed(c);
1195 }
1196
1197 void SensorService::cleanupConnection(SensorDirectConnection* c) {
1198     Mutex::Autolock _l(mLock);
1199
1200     SensorDevice& dev(SensorDevice::getInstance());
1201     dev.unregisterDirectChannel(c->getHalChannelHandle());
1202     mDirectConnections.remove(c);
1203 }
1204
1205 sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
1206     return mSensors.getInterface(handle);
1207 }
1208
1209 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
1210         int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
1211         const String16& opPackageName) {
1212     if (mInitCheck != NO_ERROR)
1213         return mInitCheck;
1214
1215     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1216     if (sensor == nullptr ||
1217         !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
1218         return BAD_VALUE;
1219     }
1220
1221     Mutex::Autolock _l(mLock);
1222     if (mCurrentOperatingMode != NORMAL
1223            && !isWhiteListedPackage(connection->getPackageName())) {
1224         return INVALID_OPERATION;
1225     }
1226
1227     SensorRecord* rec = mActiveSensors.valueFor(handle);
1228     if (rec == 0) {
1229         rec = new SensorRecord(connection);
1230         mActiveSensors.add(handle, rec);
1231         if (sensor->isVirtual()) {
1232             mActiveVirtualSensors.emplace(handle);
1233         }
1234     } else {
1235         if (rec->addConnection(connection)) {
1236             // this sensor is already activated, but we are adding a connection that uses it.
1237             // Immediately send down the last known value of the requested sensor if it's not a
1238             // "continuous" sensor.
1239             if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1240                 // NOTE: The wake_up flag of this event may get set to
1241                 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
1242
1243                 auto logger = mRecentEvent.find(handle);
1244                 if (logger != mRecentEvent.end()) {
1245                     sensors_event_t event;
1246                     // It is unlikely that this buffer is empty as the sensor is already active.
1247                     // One possible corner case may be two applications activating an on-change
1248                     // sensor at the same time.
1249                     if(logger->second->populateLastEvent(&event)) {
1250                         event.sensor = handle;
1251                         if (event.version == sizeof(sensors_event_t)) {
1252                             if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1253                                 setWakeLockAcquiredLocked(true);
1254                             }
1255                             connection->sendEvents(&event, 1, NULL);
1256                             if (!connection->needsWakeLock() && mWakeLockAcquired) {
1257                                 checkWakeLockStateLocked();
1258                             }
1259                         }
1260                     }
1261                 }
1262             }
1263         }
1264     }
1265
1266     if (connection->addSensor(handle)) {
1267         BatteryService::enableSensor(connection->getUid(), handle);
1268         // the sensor was added (which means it wasn't already there)
1269         // so, see if this connection becomes active
1270         if (mActiveConnections.indexOf(connection) < 0) {
1271             mActiveConnections.add(connection);
1272         }
1273     } else {
1274         ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1275             handle, connection.get());
1276     }
1277
1278     // Check maximum delay for the sensor.
1279     nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
1280     if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1281         samplingPeriodNs = maxDelayNs;
1282     }
1283
1284     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1285     if (samplingPeriodNs < minDelayNs) {
1286         samplingPeriodNs = minDelayNs;
1287     }
1288
1289     ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1290                                 "rate=%" PRId64 " timeout== %" PRId64"",
1291              handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1292
1293     status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
1294                                  maxBatchReportLatencyNs);
1295
1296     // Call flush() before calling activate() on the sensor. Wait for a first
1297     // flush complete event before sending events on this connection. Ignore
1298     // one-shot sensors which don't support flush(). Ignore on-change sensors
1299     // to maintain the on-change logic (any on-change events except the initial
1300     // one should be trigger by a change in value). Also if this sensor isn't
1301     // already active, don't call flush().
1302     if (err == NO_ERROR &&
1303             sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
1304             rec->getNumConnections() > 1) {
1305         connection->setFirstFlushPending(handle, true);
1306         status_t err_flush = sensor->flush(connection.get(), handle);
1307         // Flush may return error if the underlying h/w sensor uses an older HAL.
1308         if (err_flush == NO_ERROR) {
1309             rec->addPendingFlushConnection(connection.get());
1310         } else {
1311             connection->setFirstFlushPending(handle, false);
1312         }
1313     }
1314
1315     if (err == NO_ERROR) {
1316         ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1317         err = sensor->activate(connection.get(), true);
1318     }
1319
1320     if (err == NO_ERROR) {
1321         connection->updateLooperRegistration(mLooper);
1322
1323         mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1324                 SensorRegistrationInfo(handle, connection->getPackageName(),
1325                                        samplingPeriodNs, maxBatchReportLatencyNs, true);
1326         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1327     }
1328
1329     if (err != NO_ERROR) {
1330         // batch/activate has failed, reset our state.
1331         cleanupWithoutDisableLocked(connection, handle);
1332     }
1333     return err;
1334 }
1335
1336 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
1337     if (mInitCheck != NO_ERROR)
1338         return mInitCheck;
1339
1340     Mutex::Autolock _l(mLock);
1341     status_t err = cleanupWithoutDisableLocked(connection, handle);
1342     if (err == NO_ERROR) {
1343         sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1344         err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
1345
1346     }
1347     if (err == NO_ERROR) {
1348         mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1349                 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
1350         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1351     }
1352     return err;
1353 }
1354
1355 status_t SensorService::cleanupWithoutDisable(
1356         const sp<SensorEventConnection>& connection, int handle) {
1357     Mutex::Autolock _l(mLock);
1358     return cleanupWithoutDisableLocked(connection, handle);
1359 }
1360
1361 status_t SensorService::cleanupWithoutDisableLocked(
1362         const sp<SensorEventConnection>& connection, int handle) {
1363     SensorRecord* rec = mActiveSensors.valueFor(handle);
1364     if (rec) {
1365         // see if this connection becomes inactive
1366         if (connection->removeSensor(handle)) {
1367             BatteryService::disableSensor(connection->getUid(), handle);
1368         }
1369         if (connection->hasAnySensor() == false) {
1370             connection->updateLooperRegistration(mLooper);
1371             mActiveConnections.remove(connection);
1372         }
1373         // see if this sensor becomes inactive
1374         if (rec->removeConnection(connection)) {
1375             mActiveSensors.removeItem(handle);
1376             mActiveVirtualSensors.erase(handle);
1377             delete rec;
1378         }
1379         return NO_ERROR;
1380     }
1381     return BAD_VALUE;
1382 }
1383
1384 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1385         int handle, nsecs_t ns, const String16& opPackageName) {
1386     if (mInitCheck != NO_ERROR)
1387         return mInitCheck;
1388
1389     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1390     if (sensor == nullptr ||
1391         !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1392         return BAD_VALUE;
1393     }
1394
1395     if (ns < 0)
1396         return BAD_VALUE;
1397
1398     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1399     if (ns < minDelayNs) {
1400         ns = minDelayNs;
1401     }
1402
1403     return sensor->setDelay(connection.get(), handle, ns);
1404 }
1405
1406 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1407         const String16& opPackageName) {
1408     if (mInitCheck != NO_ERROR) return mInitCheck;
1409     SensorDevice& dev(SensorDevice::getInstance());
1410     const int halVersion = dev.getHalDeviceVersion();
1411     status_t err(NO_ERROR);
1412     Mutex::Autolock _l(mLock);
1413     // Loop through all sensors for this connection and call flush on each of them.
1414     for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1415         const int handle = connection->mSensorInfo.keyAt(i);
1416         sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1417         if (sensor == nullptr) {
1418             continue;
1419         }
1420         if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1421             ALOGE("flush called on a one-shot sensor");
1422             err = INVALID_OPERATION;
1423             continue;
1424         }
1425         if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1426             // For older devices just increment pending flush count which will send a trivial
1427             // flush complete event.
1428             connection->incrementPendingFlushCount(handle);
1429         } else {
1430             if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1431                 err = INVALID_OPERATION;
1432                 continue;
1433             }
1434             status_t err_flush = sensor->flush(connection.get(), handle);
1435             if (err_flush == NO_ERROR) {
1436                 SensorRecord* rec = mActiveSensors.valueFor(handle);
1437                 if (rec != NULL) rec->addPendingFlushConnection(connection);
1438             }
1439             err = (err_flush != NO_ERROR) ? err_flush : err;
1440         }
1441     }
1442     return err;
1443 }
1444
1445 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1446         const String16& opPackageName) {
1447     const String8& requiredPermission = sensor.getRequiredPermission();
1448
1449     if (requiredPermission.length() <= 0) {
1450         return true;
1451     }
1452
1453     bool hasPermission = false;
1454
1455     // Runtime permissions can't use the cache as they may change.
1456     if (sensor.isRequiredPermissionRuntime()) {
1457         hasPermission = checkPermission(String16(requiredPermission),
1458                 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1459     } else {
1460         hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1461     }
1462
1463     if (!hasPermission) {
1464         ALOGE("%s a sensor (%s) without holding its required permission: %s",
1465                 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1466         return false;
1467     }
1468
1469     const int32_t opCode = sensor.getRequiredAppOp();
1470     if (opCode >= 0) {
1471         AppOpsManager appOps;
1472         if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1473                         != AppOpsManager::MODE_ALLOWED) {
1474             ALOGE("%s a sensor (%s) without enabled required app op: %d",
1475                     operation, sensor.getName().string(), opCode);
1476             return false;
1477         }
1478     }
1479
1480     return true;
1481 }
1482
1483 void SensorService::checkWakeLockState() {
1484     Mutex::Autolock _l(mLock);
1485     checkWakeLockStateLocked();
1486 }
1487
1488 void SensorService::checkWakeLockStateLocked() {
1489     if (!mWakeLockAcquired) {
1490         return;
1491     }
1492     bool releaseLock = true;
1493     for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1494         sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1495         if (connection != 0) {
1496             if (connection->needsWakeLock()) {
1497                 releaseLock = false;
1498                 break;
1499             }
1500         }
1501     }
1502     if (releaseLock) {
1503         setWakeLockAcquiredLocked(false);
1504     }
1505 }
1506
1507 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1508     Mutex::Autolock _l(mLock);
1509     connection->writeToSocketFromCache();
1510     if (connection->needsWakeLock()) {
1511         setWakeLockAcquiredLocked(true);
1512     }
1513 }
1514
1515 void SensorService::populateActiveConnections(
1516         SortedVector< sp<SensorEventConnection> >* activeConnections) {
1517     Mutex::Autolock _l(mLock);
1518     for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1519         sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1520         if (connection != 0) {
1521             activeConnections->add(connection);
1522         }
1523     }
1524 }
1525
1526 bool SensorService::isWhiteListedPackage(const String8& packageName) {
1527     return (packageName.contains(mWhiteListedPackage.string()));
1528 }
1529
1530 bool SensorService::isOperationRestricted(const String16& opPackageName) {
1531     Mutex::Autolock _l(mLock);
1532     if (mCurrentOperatingMode != RESTRICTED) {
1533         String8 package(opPackageName);
1534         return !isWhiteListedPackage(package);
1535     }
1536     return false;
1537 }
1538
1539 }; // namespace android