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