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