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