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