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