OSDN Git Service

[automerger] DO NOT MERGE Remove window obscurement information. am: edac95e737 am...
[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
17 #include <cutils/properties.h>
18
19 #include <binder/AppOpsManager.h>
20 #include <binder/BinderService.h>
21 #include <binder/IServiceManager.h>
22 #include <binder/PermissionCache.h>
23
24 #include <gui/SensorEventQueue.h>
25
26 #include <hardware/sensors.h>
27 #include <hardware_legacy/power.h>
28
29 #include <openssl/digest.h>
30 #include <openssl/hmac.h>
31 #include <openssl/rand.h>
32
33 #include "BatteryService.h"
34 #include "CorrectedGyroSensor.h"
35 #include "GravitySensor.h"
36 #include "LinearAccelerationSensor.h"
37 #include "OrientationSensor.h"
38 #include "RotationVectorSensor.h"
39 #include "SensorFusion.h"
40 #include "SensorInterface.h"
41
42 #include "SensorService.h"
43 #include "SensorEventAckReceiver.h"
44 #include "SensorEventConnection.h"
45 #include "SensorRecord.h"
46 #include "SensorRegistrationInfo.h"
47
48 #include <inttypes.h>
49 #include <math.h>
50 #include <sched.h>
51 #include <stdint.h>
52 #include <sys/socket.h>
53 #include <sys/stat.h>
54 #include <sys/types.h>
55 #include <unistd.h>
56
57 namespace android {
58 // ---------------------------------------------------------------------------
59
60 /*
61  * Notes:
62  *
63  * - what about a gyro-corrected magnetic-field sensor?
64  * - run mag sensor from time to time to force calibration
65  * - gravity sensor length is wrong (=> drift in linear-acc sensor)
66  *
67  */
68
69 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
70 uint8_t SensorService::sHmacGlobalKey[128] = {};
71 bool SensorService::sHmacGlobalKeyIsValid = false;
72
73 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
74 #define SENSOR_SERVICE_HMAC_KEY_FILE  SENSOR_SERVICE_DIR "/hmac_key"
75 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
76
77 // Permissions.
78 static const String16 sDump("android.permission.DUMP");
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(sDump)) {
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             mCurrentOperatingMode = RESTRICTED;
341             dev.disableAllSensors();
342             // Clear all pending flush connections for all active sensors. If one of the active
343             // connections has called flush() and the underlying sensor has been disabled before a
344             // flush complete event is returned, we need to remove the connection from this queue.
345             for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
346                 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
347             }
348             mWhiteListedPackage.setTo(String8(args[1]));
349             return status_t(NO_ERROR);
350         } else if (args.size() == 1 && args[0] == String16("enable")) {
351             // If currently in restricted mode, reset back to NORMAL mode else ignore.
352             if (mCurrentOperatingMode == RESTRICTED) {
353                 mCurrentOperatingMode = NORMAL;
354                 dev.enableAllSensors();
355             }
356             if (mCurrentOperatingMode == DATA_INJECTION) {
357                resetToNormalModeLocked();
358             }
359             mWhiteListedPackage.clear();
360             return status_t(NO_ERROR);
361         } else if (args.size() == 2 && args[0] == String16("data_injection")) {
362             if (mCurrentOperatingMode == NORMAL) {
363                 dev.disableAllSensors();
364                 status_t err = dev.setMode(DATA_INJECTION);
365                 if (err == NO_ERROR) {
366                     mCurrentOperatingMode = DATA_INJECTION;
367                 } else {
368                     // Re-enable sensors.
369                     dev.enableAllSensors();
370                 }
371                 mWhiteListedPackage.setTo(String8(args[1]));
372                 return NO_ERROR;
373             } else if (mCurrentOperatingMode == DATA_INJECTION) {
374                 // Already in DATA_INJECTION mode. Treat this as a no_op.
375                 return NO_ERROR;
376             } else {
377                 // Transition to data injection mode supported only from NORMAL mode.
378                 return INVALID_OPERATION;
379             }
380         } else if (!mSensors.hasAnySensor()) {
381             result.append("No Sensors on the device\n");
382         } else {
383             // Default dump the sensor list and debugging information.
384             //
385             result.append("Sensor Device:\n");
386             result.append(SensorDevice::getInstance().dump().c_str());
387
388             result.append("Sensor List:\n");
389             result.append(mSensors.dump().c_str());
390
391             result.append("Fusion States:\n");
392             SensorFusion::getInstance().dump(result);
393
394             result.append("Recent Sensor events:\n");
395             for (auto&& i : mRecentEvent) {
396                 sp<SensorInterface> s = mSensors.getInterface(i.first);
397                 if (!i.second->isEmpty()) {
398                     if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
399                         i.second->setFormat("normal");
400                     } else {
401                         i.second->setFormat("mask_data");
402                     }
403                     // if there is events and sensor does not need special permission.
404                     result.appendFormat("%s: ", s->getSensor().getName().string());
405                     result.append(i.second->dump().c_str());
406                 }
407             }
408
409             result.append("Active sensors:\n");
410             for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
411                 int handle = mActiveSensors.keyAt(i);
412                 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
413                         getSensorName(handle).string(),
414                         handle,
415                         mActiveSensors.valueAt(i)->getNumConnections());
416             }
417
418             result.appendFormat("Socket Buffer size = %zd events\n",
419                                 mSocketBufferSize/sizeof(sensors_event_t));
420             result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
421                     "not held");
422             result.appendFormat("Mode :");
423             switch(mCurrentOperatingMode) {
424                case NORMAL:
425                    result.appendFormat(" NORMAL\n");
426                    break;
427                case RESTRICTED:
428                    result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
429                    break;
430                case DATA_INJECTION:
431                    result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
432             }
433             result.appendFormat("%zd active connections\n", mActiveConnections.size());
434
435             for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
436                 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
437                 if (connection != 0) {
438                     result.appendFormat("Connection Number: %zu \n", i);
439                     connection->dump(result);
440                 }
441             }
442
443             result.appendFormat("Previous Registrations:\n");
444             // Log in the reverse chronological order.
445             int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
446                 SENSOR_REGISTRATIONS_BUF_SIZE;
447             const int startIndex = currentIndex;
448             do {
449                 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
450                 if (SensorRegistrationInfo::isSentinel(reg_info)) {
451                     // Ignore sentinel, proceed to next item.
452                     currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
453                         SENSOR_REGISTRATIONS_BUF_SIZE;
454                     continue;
455                 }
456                 if (reg_info.mActivated) {
457                    result.appendFormat("%02d:%02d:%02d activated handle=0x%08x "
458                            "samplingRate=%dus maxReportLatency=%dus package=%s\n",
459                            reg_info.mHour, reg_info.mMin, reg_info.mSec, reg_info.mSensorHandle,
460                            reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs,
461                            reg_info.mPackageName.string());
462                 } else {
463                    result.appendFormat("%02d:%02d:%02d de-activated handle=0x%08x package=%s\n",
464                            reg_info.mHour, reg_info.mMin, reg_info.mSec,
465                            reg_info.mSensorHandle, reg_info.mPackageName.string());
466                 }
467                 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
468                         SENSOR_REGISTRATIONS_BUF_SIZE;
469             } while(startIndex != currentIndex);
470         }
471     }
472     write(fd, result.string(), result.size());
473     return NO_ERROR;
474 }
475
476 //TODO: move to SensorEventConnection later
477 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
478         sensors_event_t const* buffer, const int count) {
479     for (int i=0 ; i<count ; i++) {
480         int handle = buffer[i].sensor;
481         if (buffer[i].type == SENSOR_TYPE_META_DATA) {
482             handle = buffer[i].meta_data.sensor;
483         }
484         if (connection->hasSensor(handle)) {
485             sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
486             // If this buffer has an event from a one_shot sensor and this connection is registered
487             // for this particular one_shot sensor, try cleaning up the connection.
488             if (si != nullptr &&
489                 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
490                 si->autoDisable(connection.get(), handle);
491                 cleanupWithoutDisableLocked(connection, handle);
492             }
493
494         }
495    }
496 }
497
498 bool SensorService::threadLoop() {
499     ALOGD("nuSensorService thread starting...");
500
501     // each virtual sensor could generate an event per "real" event, that's why we need to size
502     // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
503     // aggressive, but guaranteed to be enough.
504     const size_t vcount = mSensors.getVirtualSensors().size();
505     const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
506     const size_t numEventMax = minBufferSize / (1 + vcount);
507
508     SensorDevice& device(SensorDevice::getInstance());
509
510     const int halVersion = device.getHalDeviceVersion();
511     do {
512         ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
513         if (count < 0) {
514             ALOGE("sensor poll failed (%s)", strerror(-count));
515             break;
516         }
517
518         // Reset sensors_event_t.flags to zero for all events in the buffer.
519         for (int i = 0; i < count; i++) {
520              mSensorEventBuffer[i].flags = 0;
521         }
522
523         // Make a copy of the connection vector as some connections may be removed during the course
524         // of this loop (especially when one-shot sensor events are present in the sensor_event
525         // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
526         // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
527         // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
528         // strongPointers to a vector before the lock is acquired.
529         SortedVector< sp<SensorEventConnection> > activeConnections;
530         populateActiveConnections(&activeConnections);
531
532         Mutex::Autolock _l(mLock);
533         // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
534         // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
535         // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
536         // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
537         // releasing the wakelock.
538         bool bufferHasWakeUpEvent = false;
539         for (int i = 0; i < count; i++) {
540             if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
541                 bufferHasWakeUpEvent = true;
542                 break;
543             }
544         }
545
546         if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
547             setWakeLockAcquiredLocked(true);
548         }
549         recordLastValueLocked(mSensorEventBuffer, count);
550
551         // handle virtual sensors
552         if (count && vcount) {
553             sensors_event_t const * const event = mSensorEventBuffer;
554             if (!mActiveVirtualSensors.empty()) {
555                 size_t k = 0;
556                 SensorFusion& fusion(SensorFusion::getInstance());
557                 if (fusion.isEnabled()) {
558                     for (size_t i=0 ; i<size_t(count) ; i++) {
559                         fusion.process(event[i]);
560                     }
561                 }
562                 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
563                     for (int handle : mActiveVirtualSensors) {
564                         if (count + k >= minBufferSize) {
565                             ALOGE("buffer too small to hold all events: "
566                                     "count=%zd, k=%zu, size=%zu",
567                                     count, k, minBufferSize);
568                             break;
569                         }
570                         sensors_event_t out;
571                         sp<SensorInterface> si = mSensors.getInterface(handle);
572                         if (si == nullptr) {
573                             ALOGE("handle %d is not an valid virtual sensor", handle);
574                             continue;
575                         }
576
577                         if (si->process(&out, event[i])) {
578                             mSensorEventBuffer[count + k] = out;
579                             k++;
580                         }
581                     }
582                 }
583                 if (k) {
584                     // record the last synthesized values
585                     recordLastValueLocked(&mSensorEventBuffer[count], k);
586                     count += k;
587                     // sort the buffer by time-stamps
588                     sortEventBuffer(mSensorEventBuffer, count);
589                 }
590             }
591         }
592
593         // handle backward compatibility for RotationVector sensor
594         if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
595             for (int i = 0; i < count; i++) {
596                 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
597                     // All the 4 components of the quaternion should be available
598                     // No heading accuracy. Set it to -1
599                     mSensorEventBuffer[i].data[4] = -1;
600                 }
601             }
602         }
603
604         for (int i = 0; i < count; ++i) {
605             // Map flush_complete_events in the buffer to SensorEventConnections which called flush
606             // on the hardware sensor. mapFlushEventsToConnections[i] will be the
607             // SensorEventConnection mapped to the corresponding flush_complete_event in
608             // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
609             mMapFlushEventsToConnections[i] = NULL;
610             if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
611                 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
612                 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
613                 if (rec != NULL) {
614                     mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
615                     rec->removeFirstPendingFlushConnection();
616                 }
617             }
618
619             // handle dynamic sensor meta events, process registration and unregistration of dynamic
620             // sensor based on content of event.
621             if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
622                 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
623                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
624                     const sensor_t& dynamicSensor =
625                             *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
626                     ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
627                           handle, dynamicSensor.type, dynamicSensor.name);
628
629                     if (mSensors.isNewHandle(handle)) {
630                         const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
631                         sensor_t s = dynamicSensor;
632                         // make sure the dynamic sensor flag is set
633                         s.flags |= DYNAMIC_SENSOR_MASK;
634                         // force the handle to be consistent
635                         s.handle = handle;
636
637                         SensorInterface *si = new HardwareSensor(s, uuid);
638
639                         // This will release hold on dynamic sensor meta, so it should be called
640                         // after Sensor object is created.
641                         device.handleDynamicSensorConnection(handle, true /*connected*/);
642                         registerDynamicSensorLocked(si);
643                     } else {
644                         ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
645                     }
646                 } else {
647                     int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
648                     ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
649
650                     device.handleDynamicSensorConnection(handle, false /*connected*/);
651                     if (!unregisterDynamicSensorLocked(handle)) {
652                         ALOGE("Dynamic sensor release error.");
653                     }
654
655                     size_t numConnections = activeConnections.size();
656                     for (size_t i=0 ; i < numConnections; ++i) {
657                         if (activeConnections[i] != NULL) {
658                             activeConnections[i]->removeSensor(handle);
659                         }
660                     }
661                 }
662             }
663         }
664
665
666         // Send our events to clients. Check the state of wake lock for each client and release the
667         // lock if none of the clients need it.
668         bool needsWakeLock = false;
669         size_t numConnections = activeConnections.size();
670         for (size_t i=0 ; i < numConnections; ++i) {
671             if (activeConnections[i] != 0) {
672                 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
673                         mMapFlushEventsToConnections);
674                 needsWakeLock |= activeConnections[i]->needsWakeLock();
675                 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
676                 // Early check for one-shot sensors.
677                 if (activeConnections[i]->hasOneShotSensors()) {
678                     cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
679                             count);
680                 }
681             }
682         }
683
684         if (mWakeLockAcquired && !needsWakeLock) {
685             setWakeLockAcquiredLocked(false);
686         }
687     } while (!Thread::exitPending());
688
689     ALOGW("Exiting SensorService::threadLoop => aborting...");
690     abort();
691     return false;
692 }
693
694 sp<Looper> SensorService::getLooper() const {
695     return mLooper;
696 }
697
698 void SensorService::resetAllWakeLockRefCounts() {
699     SortedVector< sp<SensorEventConnection> > activeConnections;
700     populateActiveConnections(&activeConnections);
701     {
702         Mutex::Autolock _l(mLock);
703         for (size_t i=0 ; i < activeConnections.size(); ++i) {
704             if (activeConnections[i] != 0) {
705                 activeConnections[i]->resetWakeLockRefCount();
706             }
707         }
708         setWakeLockAcquiredLocked(false);
709     }
710 }
711
712 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
713     if (acquire) {
714         if (!mWakeLockAcquired) {
715             acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
716             mWakeLockAcquired = true;
717         }
718         mLooper->wake();
719     } else {
720         if (mWakeLockAcquired) {
721             release_wake_lock(WAKE_LOCK_NAME);
722             mWakeLockAcquired = false;
723         }
724     }
725 }
726
727 bool SensorService::isWakeLockAcquired() {
728     Mutex::Autolock _l(mLock);
729     return mWakeLockAcquired;
730 }
731
732 bool SensorService::SensorEventAckReceiver::threadLoop() {
733     ALOGD("new thread SensorEventAckReceiver");
734     sp<Looper> looper = mService->getLooper();
735     do {
736         bool wakeLockAcquired = mService->isWakeLockAcquired();
737         int timeout = -1;
738         if (wakeLockAcquired) timeout = 5000;
739         int ret = looper->pollOnce(timeout);
740         if (ret == ALOOPER_POLL_TIMEOUT) {
741            mService->resetAllWakeLockRefCounts();
742         }
743     } while(!Thread::exitPending());
744     return false;
745 }
746
747 void SensorService::recordLastValueLocked(
748         const sensors_event_t* buffer, size_t count) {
749     for (size_t i = 0; i < count; i++) {
750         if (buffer[i].type == SENSOR_TYPE_META_DATA ||
751             buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
752             buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
753             continue;
754         }
755
756         auto logger = mRecentEvent.find(buffer[i].sensor);
757         if (logger != mRecentEvent.end()) {
758             logger->second->addEvent(buffer[i]);
759         }
760     }
761 }
762
763 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
764     struct compar {
765         static int cmp(void const* lhs, void const* rhs) {
766             sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
767             sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
768             return l->timestamp - r->timestamp;
769         }
770     };
771     qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
772 }
773
774 String8 SensorService::getSensorName(int handle) const {
775     return mSensors.getName(handle);
776 }
777
778 bool SensorService::isVirtualSensor(int handle) const {
779     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
780     return sensor != nullptr && sensor->isVirtual();
781 }
782
783 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
784     int handle = event.sensor;
785     if (event.type == SENSOR_TYPE_META_DATA) {
786         handle = event.meta_data.sensor;
787     }
788     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
789     return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
790 }
791
792 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
793     if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
794         // UUID is not supported for this device.
795         return 0;
796     }
797     if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
798         // This sensor can be uniquely identified in the system by
799         // the combination of its type and name.
800         return -1;
801     }
802
803     // We have a dynamic sensor.
804
805     if (!sHmacGlobalKeyIsValid) {
806         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
807         ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
808         return 0;
809     }
810
811     // We want each app author/publisher to get a different ID, so that the
812     // same dynamic sensor cannot be tracked across apps by multiple
813     // authors/publishers.  So we use both our UUID and our User ID.
814     // Note potential confusion:
815     //     UUID => Universally Unique Identifier.
816     //     UID  => User Identifier.
817     // We refrain from using "uid" except as needed by API to try to
818     // keep this distinction clear.
819
820     auto appUserId = IPCThreadState::self()->getCallingUid();
821     uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
822     memcpy(uuidAndApp, &uuid, sizeof(uuid));
823     memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
824
825     // Now we use our key on our UUID/app combo to get the hash.
826     uint8_t hash[EVP_MAX_MD_SIZE];
827     unsigned int hashLen;
828     if (HMAC(EVP_sha256(),
829              sHmacGlobalKey, sizeof(sHmacGlobalKey),
830              uuidAndApp, sizeof(uuidAndApp),
831              hash, &hashLen) == nullptr) {
832         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
833         ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
834         return 0;
835     }
836
837     int32_t id = 0;
838     if (hashLen < sizeof(id)) {
839         // We never expect this case, but out of paranoia, we handle it.
840         // Our 'id' length is already quite small, we don't want the
841         // effective length of it to be even smaller.
842         // Rather than risk exposing UUIDs, we cripple dynamic sensors.
843         ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
844         return 0;
845     }
846
847     // This is almost certainly less than all of 'hash', but it's as secure
848     // as we can be with our current 'id' length.
849     memcpy(&id, hash, sizeof(id));
850
851     // Note at the beginning of the function that we return the values of
852     // 0 and -1 to represent special cases.  As a result, we can't return
853     // those as dynamic sensor IDs.  If we happened to hash to one of those
854     // values, we change 'id' so we report as a dynamic sensor, and not as
855     // one of those special cases.
856     if (id == -1) {
857         id = -2;
858     } else if (id == 0) {
859         id = 1;
860     }
861     return id;
862 }
863
864 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
865     for (auto &sensor : sensorList) {
866         int32_t id = getIdFromUuid(sensor.getUuid());
867         sensor.setId(id);
868     }
869 }
870
871 Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
872     char value[PROPERTY_VALUE_MAX];
873     property_get("debug.sensors", value, "0");
874     const Vector<Sensor>& initialSensorList = (atoi(value)) ?
875             mSensors.getUserDebugSensors() : mSensors.getUserSensors();
876     Vector<Sensor> accessibleSensorList;
877     for (size_t i = 0; i < initialSensorList.size(); i++) {
878         Sensor sensor = initialSensorList[i];
879         if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
880             accessibleSensorList.add(sensor);
881         } else {
882             ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
883                   sensor.getName().string(),
884                   sensor.getRequiredPermission().string(),
885                   sensor.getRequiredAppOp());
886         }
887     }
888     makeUuidsIntoIdsForSensorList(accessibleSensorList);
889     return accessibleSensorList;
890 }
891
892 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
893     Vector<Sensor> accessibleSensorList;
894     mSensors.forEachSensor(
895             [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
896                 if (sensor.isDynamicSensor()) {
897                     if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
898                         accessibleSensorList.add(sensor);
899                     } else {
900                         ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
901                               sensor.getName().string(),
902                               sensor.getRequiredPermission().string(),
903                               sensor.getRequiredAppOp());
904                     }
905                 }
906                 return true;
907             });
908     makeUuidsIntoIdsForSensorList(accessibleSensorList);
909     return accessibleSensorList;
910 }
911
912 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
913         int requestedMode, const String16& opPackageName) {
914     // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
915     if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
916         return NULL;
917     }
918
919     Mutex::Autolock _l(mLock);
920     // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
921     // operating in DI mode.
922     if (requestedMode == DATA_INJECTION) {
923         if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
924         if (!isWhiteListedPackage(packageName)) return NULL;
925     }
926
927     uid_t uid = IPCThreadState::self()->getCallingUid();
928     sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
929             requestedMode == DATA_INJECTION, opPackageName));
930     if (requestedMode == DATA_INJECTION) {
931         if (mActiveConnections.indexOf(result) < 0) {
932             mActiveConnections.add(result);
933         }
934         // Add the associated file descriptor to the Looper for polling whenever there is data to
935         // be injected.
936         result->updateLooperRegistration(mLooper);
937     }
938     return result;
939 }
940
941 int SensorService::isDataInjectionEnabled() {
942     Mutex::Autolock _l(mLock);
943     return (mCurrentOperatingMode == DATA_INJECTION);
944 }
945
946 status_t SensorService::resetToNormalMode() {
947     Mutex::Autolock _l(mLock);
948     return resetToNormalModeLocked();
949 }
950
951 status_t SensorService::resetToNormalModeLocked() {
952     SensorDevice& dev(SensorDevice::getInstance());
953     dev.enableAllSensors();
954     status_t err = dev.setMode(NORMAL);
955     mCurrentOperatingMode = NORMAL;
956     return err;
957 }
958
959 void SensorService::cleanupConnection(SensorEventConnection* c) {
960     Mutex::Autolock _l(mLock);
961     const wp<SensorEventConnection> connection(c);
962     size_t size = mActiveSensors.size();
963     ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
964     for (size_t i=0 ; i<size ; ) {
965         int handle = mActiveSensors.keyAt(i);
966         if (c->hasSensor(handle)) {
967             ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
968             sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
969             if (sensor != nullptr) {
970                 sensor->activate(c, false);
971             } else {
972                 ALOGE("sensor interface of handle=0x%08x is null!", handle);
973             }
974             c->removeSensor(handle);
975         }
976         SensorRecord* rec = mActiveSensors.valueAt(i);
977         ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
978         ALOGD_IF(DEBUG_CONNECTIONS,
979                 "removing connection %p for sensor[%zu].handle=0x%08x",
980                 c, i, handle);
981
982         if (rec && rec->removeConnection(connection)) {
983             ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
984             mActiveSensors.removeItemsAt(i, 1);
985             mActiveVirtualSensors.erase(handle);
986             delete rec;
987             size--;
988         } else {
989             i++;
990         }
991     }
992     c->updateLooperRegistration(mLooper);
993     mActiveConnections.remove(connection);
994     BatteryService::cleanup(c->getUid());
995     if (c->needsWakeLock()) {
996         checkWakeLockStateLocked();
997     }
998
999     SensorDevice& dev(SensorDevice::getInstance());
1000     dev.notifyConnectionDestroyed(c);
1001 }
1002
1003 sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
1004     return mSensors.getInterface(handle);
1005 }
1006
1007
1008 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
1009         int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
1010         const String16& opPackageName) {
1011     if (mInitCheck != NO_ERROR)
1012         return mInitCheck;
1013
1014     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1015     if (sensor == nullptr ||
1016         !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
1017         return BAD_VALUE;
1018     }
1019
1020     Mutex::Autolock _l(mLock);
1021     if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
1022            && !isWhiteListedPackage(connection->getPackageName())) {
1023         return INVALID_OPERATION;
1024     }
1025
1026     SensorRecord* rec = mActiveSensors.valueFor(handle);
1027     if (rec == 0) {
1028         rec = new SensorRecord(connection);
1029         mActiveSensors.add(handle, rec);
1030         if (sensor->isVirtual()) {
1031             mActiveVirtualSensors.emplace(handle);
1032         }
1033     } else {
1034         if (rec->addConnection(connection)) {
1035             // this sensor is already activated, but we are adding a connection that uses it.
1036             // Immediately send down the last known value of the requested sensor if it's not a
1037             // "continuous" sensor.
1038             if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1039                 // NOTE: The wake_up flag of this event may get set to
1040                 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
1041
1042                 auto logger = mRecentEvent.find(handle);
1043                 if (logger != mRecentEvent.end()) {
1044                     sensors_event_t event;
1045                     // It is unlikely that this buffer is empty as the sensor is already active.
1046                     // One possible corner case may be two applications activating an on-change
1047                     // sensor at the same time.
1048                     if(logger->second->populateLastEvent(&event)) {
1049                         event.sensor = handle;
1050                         if (event.version == sizeof(sensors_event_t)) {
1051                             if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1052                                 setWakeLockAcquiredLocked(true);
1053                             }
1054                             connection->sendEvents(&event, 1, NULL);
1055                             if (!connection->needsWakeLock() && mWakeLockAcquired) {
1056                                 checkWakeLockStateLocked();
1057                             }
1058                         }
1059                     }
1060                 }
1061             }
1062         }
1063     }
1064
1065     if (connection->addSensor(handle)) {
1066         BatteryService::enableSensor(connection->getUid(), handle);
1067         // the sensor was added (which means it wasn't already there)
1068         // so, see if this connection becomes active
1069         if (mActiveConnections.indexOf(connection) < 0) {
1070             mActiveConnections.add(connection);
1071         }
1072     } else {
1073         ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1074             handle, connection.get());
1075     }
1076
1077     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1078     if (samplingPeriodNs < minDelayNs) {
1079         samplingPeriodNs = minDelayNs;
1080     }
1081
1082     ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1083                                 "rate=%" PRId64 " timeout== %" PRId64"",
1084              handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1085
1086     status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
1087                                  maxBatchReportLatencyNs);
1088
1089     // Call flush() before calling activate() on the sensor. Wait for a first
1090     // flush complete event before sending events on this connection. Ignore
1091     // one-shot sensors which don't support flush(). Ignore on-change sensors
1092     // to maintain the on-change logic (any on-change events except the initial
1093     // one should be trigger by a change in value). Also if this sensor isn't
1094     // already active, don't call flush().
1095     if (err == NO_ERROR &&
1096             sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
1097             rec->getNumConnections() > 1) {
1098         connection->setFirstFlushPending(handle, true);
1099         status_t err_flush = sensor->flush(connection.get(), handle);
1100         // Flush may return error if the underlying h/w sensor uses an older HAL.
1101         if (err_flush == NO_ERROR) {
1102             rec->addPendingFlushConnection(connection.get());
1103         } else {
1104             connection->setFirstFlushPending(handle, false);
1105         }
1106     }
1107
1108     if (err == NO_ERROR) {
1109         ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1110         err = sensor->activate(connection.get(), true);
1111     }
1112
1113     if (err == NO_ERROR) {
1114         connection->updateLooperRegistration(mLooper);
1115         SensorRegistrationInfo &reg_info =
1116             mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1117         reg_info.mSensorHandle = handle;
1118         reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1119         reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1120         reg_info.mActivated = true;
1121         reg_info.mPackageName = connection->getPackageName();
1122         time_t rawtime = time(NULL);
1123         struct tm * timeinfo = localtime(&rawtime);
1124         reg_info.mHour = timeinfo->tm_hour;
1125         reg_info.mMin = timeinfo->tm_min;
1126         reg_info.mSec = timeinfo->tm_sec;
1127         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1128     }
1129
1130     if (err != NO_ERROR) {
1131         // batch/activate has failed, reset our state.
1132         cleanupWithoutDisableLocked(connection, handle);
1133     }
1134     return err;
1135 }
1136
1137 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
1138     if (mInitCheck != NO_ERROR)
1139         return mInitCheck;
1140
1141     Mutex::Autolock _l(mLock);
1142     status_t err = cleanupWithoutDisableLocked(connection, handle);
1143     if (err == NO_ERROR) {
1144         sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1145         err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
1146
1147     }
1148     if (err == NO_ERROR) {
1149         SensorRegistrationInfo &reg_info =
1150             mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1151         reg_info.mActivated = false;
1152         reg_info.mPackageName= connection->getPackageName();
1153         reg_info.mSensorHandle = handle;
1154         time_t rawtime = time(NULL);
1155         struct tm * timeinfo = localtime(&rawtime);
1156         reg_info.mHour = timeinfo->tm_hour;
1157         reg_info.mMin = timeinfo->tm_min;
1158         reg_info.mSec = timeinfo->tm_sec;
1159         mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1160     }
1161     return err;
1162 }
1163
1164 status_t SensorService::cleanupWithoutDisable(
1165         const sp<SensorEventConnection>& connection, int handle) {
1166     Mutex::Autolock _l(mLock);
1167     return cleanupWithoutDisableLocked(connection, handle);
1168 }
1169
1170 status_t SensorService::cleanupWithoutDisableLocked(
1171         const sp<SensorEventConnection>& connection, int handle) {
1172     SensorRecord* rec = mActiveSensors.valueFor(handle);
1173     if (rec) {
1174         // see if this connection becomes inactive
1175         if (connection->removeSensor(handle)) {
1176             BatteryService::disableSensor(connection->getUid(), handle);
1177         }
1178         if (connection->hasAnySensor() == false) {
1179             connection->updateLooperRegistration(mLooper);
1180             mActiveConnections.remove(connection);
1181         }
1182         // see if this sensor becomes inactive
1183         if (rec->removeConnection(connection)) {
1184             mActiveSensors.removeItem(handle);
1185             mActiveVirtualSensors.erase(handle);
1186             delete rec;
1187         }
1188         return NO_ERROR;
1189     }
1190     return BAD_VALUE;
1191 }
1192
1193 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1194         int handle, nsecs_t ns, const String16& opPackageName) {
1195     if (mInitCheck != NO_ERROR)
1196         return mInitCheck;
1197
1198     sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1199     if (sensor == nullptr ||
1200         !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1201         return BAD_VALUE;
1202     }
1203
1204     if (ns < 0)
1205         return BAD_VALUE;
1206
1207     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1208     if (ns < minDelayNs) {
1209         ns = minDelayNs;
1210     }
1211
1212     return sensor->setDelay(connection.get(), handle, ns);
1213 }
1214
1215 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1216         const String16& opPackageName) {
1217     if (mInitCheck != NO_ERROR) return mInitCheck;
1218     SensorDevice& dev(SensorDevice::getInstance());
1219     const int halVersion = dev.getHalDeviceVersion();
1220     status_t err(NO_ERROR);
1221     Mutex::Autolock _l(mLock);
1222     // Loop through all sensors for this connection and call flush on each of them.
1223     for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1224         const int handle = connection->mSensorInfo.keyAt(i);
1225         sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1226         if (sensor == nullptr) {
1227             continue;
1228         }
1229         if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1230             ALOGE("flush called on a one-shot sensor");
1231             err = INVALID_OPERATION;
1232             continue;
1233         }
1234         if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1235             // For older devices just increment pending flush count which will send a trivial
1236             // flush complete event.
1237             connection->incrementPendingFlushCount(handle);
1238         } else {
1239             if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1240                 err = INVALID_OPERATION;
1241                 continue;
1242             }
1243             status_t err_flush = sensor->flush(connection.get(), handle);
1244             if (err_flush == NO_ERROR) {
1245                 SensorRecord* rec = mActiveSensors.valueFor(handle);
1246                 if (rec != NULL) rec->addPendingFlushConnection(connection);
1247             }
1248             err = (err_flush != NO_ERROR) ? err_flush : err;
1249         }
1250     }
1251     return err;
1252 }
1253
1254 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1255         const String16& opPackageName) {
1256     const String8& requiredPermission = sensor.getRequiredPermission();
1257
1258     if (requiredPermission.length() <= 0) {
1259         return true;
1260     }
1261
1262     bool hasPermission = false;
1263
1264     // Runtime permissions can't use the cache as they may change.
1265     if (sensor.isRequiredPermissionRuntime()) {
1266         hasPermission = checkPermission(String16(requiredPermission),
1267                 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1268     } else {
1269         hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1270     }
1271
1272     if (!hasPermission) {
1273         ALOGE("%s a sensor (%s) without holding its required permission: %s",
1274                 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1275         return false;
1276     }
1277
1278     const int32_t opCode = sensor.getRequiredAppOp();
1279     if (opCode >= 0) {
1280         AppOpsManager appOps;
1281         if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1282                         != AppOpsManager::MODE_ALLOWED) {
1283             ALOGE("%s a sensor (%s) without enabled required app op: %d",
1284                     operation, sensor.getName().string(), opCode);
1285             return false;
1286         }
1287     }
1288
1289     return true;
1290 }
1291
1292 void SensorService::checkWakeLockState() {
1293     Mutex::Autolock _l(mLock);
1294     checkWakeLockStateLocked();
1295 }
1296
1297 void SensorService::checkWakeLockStateLocked() {
1298     if (!mWakeLockAcquired) {
1299         return;
1300     }
1301     bool releaseLock = true;
1302     for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1303         sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1304         if (connection != 0) {
1305             if (connection->needsWakeLock()) {
1306                 releaseLock = false;
1307                 break;
1308             }
1309         }
1310     }
1311     if (releaseLock) {
1312         setWakeLockAcquiredLocked(false);
1313     }
1314 }
1315
1316 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1317     Mutex::Autolock _l(mLock);
1318     connection->writeToSocketFromCache();
1319     if (connection->needsWakeLock()) {
1320         setWakeLockAcquiredLocked(true);
1321     }
1322 }
1323
1324 void SensorService::populateActiveConnections(
1325         SortedVector< sp<SensorEventConnection> >* activeConnections) {
1326     Mutex::Autolock _l(mLock);
1327     for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1328         sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1329         if (connection != 0) {
1330             activeConnections->add(connection);
1331         }
1332     }
1333 }
1334
1335 bool SensorService::isWhiteListedPackage(const String8& packageName) {
1336     return (packageName.contains(mWhiteListedPackage.string()));
1337 }
1338
1339 }; // namespace android
1340