SensorService.cpp revision 4949c50372de4c7fdb57de1dc0c1f5bb3ac463eb
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
68SensorService::SensorService()
69    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
70      mWakeLockAcquired(false)
71{
72}
73
74void SensorService::onFirstRef()
75{
76    ALOGD("nuSensorService starting...");
77
78    SensorDevice& dev(SensorDevice::getInstance());
79
80    if (dev.initCheck() == NO_ERROR) {
81        sensor_t const* list;
82        ssize_t count = dev.getSensorList(&list);
83        if (count > 0) {
84            ssize_t orientationIndex = -1;
85            bool hasGyro = false;
86            uint32_t virtualSensorsNeeds =
87                    (1<<SENSOR_TYPE_GRAVITY) |
88                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
89                    (1<<SENSOR_TYPE_ROTATION_VECTOR);
90
91            mLastEventSeen.setCapacity(count);
92            for (ssize_t i=0 ; i<count ; i++) {
93                registerSensor( new HardwareSensor(list[i]) );
94                switch (list[i].type) {
95                    case SENSOR_TYPE_ORIENTATION:
96                        orientationIndex = i;
97                        break;
98                    case SENSOR_TYPE_GYROSCOPE:
99                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
100                        hasGyro = true;
101                        break;
102                    case SENSOR_TYPE_GRAVITY:
103                    case SENSOR_TYPE_LINEAR_ACCELERATION:
104                    case SENSOR_TYPE_ROTATION_VECTOR:
105                        virtualSensorsNeeds &= ~(1<<list[i].type);
106                        break;
107                }
108            }
109
110            // it's safe to instantiate the SensorFusion object here
111            // (it wants to be instantiated after h/w sensors have been
112            // registered)
113            const SensorFusion& fusion(SensorFusion::getInstance());
114
115            // build the sensor list returned to users
116            mUserSensorList = mSensorList;
117
118            if (hasGyro) {
119                Sensor aSensor;
120
121                // Add Android virtual sensors if they're not already
122                // available in the HAL
123
124                aSensor = registerVirtualSensor( new RotationVectorSensor() );
125                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
126                    mUserSensorList.add(aSensor);
127                }
128
129                aSensor = registerVirtualSensor( new GravitySensor(list, count) );
130                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
131                    mUserSensorList.add(aSensor);
132                }
133
134                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
135                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
136                    mUserSensorList.add(aSensor);
137                }
138
139                aSensor = registerVirtualSensor( new OrientationSensor() );
140                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
141                    // if we are doing our own rotation-vector, also add
142                    // the orientation sensor and remove the HAL provided one.
143                    mUserSensorList.replaceAt(aSensor, orientationIndex);
144                }
145
146                // virtual debugging sensors are not added to mUserSensorList
147                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
148                registerVirtualSensor( new GyroDriftSensor() );
149            }
150
151            // debugging sensor list
152            mUserSensorListDebug = mSensorList;
153
154            // Check if the device really supports batching by looking at the FIFO event
155            // counts for each sensor.
156            bool batchingSupported = false;
157            for (int i = 0; i < mSensorList.size(); ++i) {
158                if (mSensorList[i].getFifoMaxEventCount() > 0) {
159                    batchingSupported = true;
160                    break;
161                }
162            }
163
164            if (batchingSupported) {
165                // Increase socket buffer size to a max of 100 KB for batching capabilities.
166                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
167            } else {
168                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
169            }
170
171            // Compare the socketBufferSize value against the system limits and limit
172            // it to maxSystemSocketBufferSize if necessary.
173            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
174            char line[128];
175            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
176                line[sizeof(line) - 1] = '\0';
177                size_t maxSystemSocketBufferSize;
178                sscanf(line, "%zu", &maxSystemSocketBufferSize);
179                if (mSocketBufferSize > maxSystemSocketBufferSize) {
180                    mSocketBufferSize = maxSystemSocketBufferSize;
181                }
182            }
183            if (fp) {
184                fclose(fp);
185            }
186
187            mWakeLockAcquired = false;
188            mLooper = new Looper(false);
189            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
190            mSensorEventBuffer = new sensors_event_t[minBufferSize];
191            mSensorEventScratch = new sensors_event_t[minBufferSize];
192            mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
193            mMode = NORMAL;
194
195            mAckReceiver = new SensorEventAckReceiver(this);
196            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
197            mInitCheck = NO_ERROR;
198            run("SensorService", PRIORITY_URGENT_DISPLAY);
199        }
200    }
201}
202
203Sensor SensorService::registerSensor(SensorInterface* s)
204{
205    sensors_event_t event;
206    memset(&event, 0, sizeof(event));
207
208    const Sensor sensor(s->getSensor());
209    // add to the sensor list (returned to clients)
210    mSensorList.add(sensor);
211    // add to our handle->SensorInterface mapping
212    mSensorMap.add(sensor.getHandle(), s);
213    // create an entry in the mLastEventSeen array
214    mLastEventSeen.add(sensor.getHandle(), event);
215
216    return sensor;
217}
218
219Sensor SensorService::registerVirtualSensor(SensorInterface* s)
220{
221    Sensor sensor = registerSensor(s);
222    mVirtualSensorList.add( s );
223    return sensor;
224}
225
226SensorService::~SensorService()
227{
228    for (size_t i=0 ; i<mSensorMap.size() ; i++)
229        delete mSensorMap.valueAt(i);
230}
231
232static const String16 sDump("android.permission.DUMP");
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") && mMode == NORMAL) {
249            mMode = 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") && mMode == RESTRICTED) {
258            mMode = 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(mMode) {
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
410bool SensorService::threadLoop()
411{
412    ALOGD("nuSensorService thread starting...");
413
414    // each virtual sensor could generate an event per "real" event, that's why we need
415    // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
416    // in practice, this is too aggressive, but guaranteed to be enough.
417    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
418    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
419
420    SensorDevice& device(SensorDevice::getInstance());
421    const size_t vcount = mVirtualSensorList.size();
422
423    const int halVersion = device.getHalDeviceVersion();
424    do {
425        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
426        if (count < 0) {
427            ALOGE("sensor poll failed (%s)", strerror(-count));
428            break;
429        }
430
431        // Reset sensors_event_t.flags to zero for all events in the buffer.
432        for (int i = 0; i < count; i++) {
433             mSensorEventBuffer[i].flags = 0;
434        }
435
436        // Make a copy of the connection vector as some connections may be removed during the
437        // course of this loop (especially when one-shot sensor events are present in the
438        // sensor_event buffer). Promote all connections to StrongPointers before the lock is
439        // acquired. If the destructor of the sp gets called when the lock is acquired, it may
440        // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
441        // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
442        SortedVector< sp<SensorEventConnection> > activeConnections;
443        populateActiveConnections(&activeConnections);
444        Mutex::Autolock _l(mLock);
445        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
446        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
447        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
448        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
449        // releasing the wakelock.
450        bool bufferHasWakeUpEvent = false;
451        for (int i = 0; i < count; i++) {
452            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
453                bufferHasWakeUpEvent = true;
454                break;
455            }
456        }
457
458        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
459            setWakeLockAcquiredLocked(true);
460        }
461        recordLastValueLocked(mSensorEventBuffer, count);
462
463        // handle virtual sensors
464        if (count && vcount) {
465            sensors_event_t const * const event = mSensorEventBuffer;
466            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
467            if (activeVirtualSensorCount) {
468                size_t k = 0;
469                SensorFusion& fusion(SensorFusion::getInstance());
470                if (fusion.isEnabled()) {
471                    for (size_t i=0 ; i<size_t(count) ; i++) {
472                        fusion.process(event[i]);
473                    }
474                }
475                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
476                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
477                        if (count + k >= minBufferSize) {
478                            ALOGE("buffer too small to hold all events: "
479                                    "count=%zd, k=%zu, size=%zu",
480                                    count, k, minBufferSize);
481                            break;
482                        }
483                        sensors_event_t out;
484                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
485                        if (si->process(&out, event[i])) {
486                            mSensorEventBuffer[count + k] = out;
487                            k++;
488                        }
489                    }
490                }
491                if (k) {
492                    // record the last synthesized values
493                    recordLastValueLocked(&mSensorEventBuffer[count], k);
494                    count += k;
495                    // sort the buffer by time-stamps
496                    sortEventBuffer(mSensorEventBuffer, count);
497                }
498            }
499        }
500
501        // handle backward compatibility for RotationVector sensor
502        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
503            for (int i = 0; i < count; i++) {
504                if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
505                    // All the 4 components of the quaternion should be available
506                    // No heading accuracy. Set it to -1
507                    mSensorEventBuffer[i].data[4] = -1;
508                }
509            }
510        }
511
512        // Map flush_complete_events in the buffer to SensorEventConnections which called
513        // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
514        // SensorEventConnection mapped to the corresponding flush_complete_event in
515        // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
516        for (int i = 0; i < count; ++i) {
517            mMapFlushEventsToConnections[i] = NULL;
518            if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
519                const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
520                SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
521                if (rec != NULL) {
522                    mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
523                    rec->removeFirstPendingFlushConnection();
524                }
525            }
526        }
527
528        // Send our events to clients. Check the state of wake lock for each client and release the
529        // lock if none of the clients need it.
530        bool needsWakeLock = false;
531        size_t numConnections = activeConnections.size();
532        for (size_t i=0 ; i < numConnections; ++i) {
533            if (activeConnections[i] != 0) {
534                activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
535                        mMapFlushEventsToConnections);
536                needsWakeLock |= activeConnections[i]->needsWakeLock();
537                // If the connection has one-shot sensors, it may be cleaned up after first trigger.
538                // Early check for one-shot sensors.
539                if (activeConnections[i]->hasOneShotSensors()) {
540                    cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
541                            count);
542                }
543            }
544        }
545
546        if (mWakeLockAcquired && !needsWakeLock) {
547            setWakeLockAcquiredLocked(false);
548        }
549    } while (!Thread::exitPending());
550
551    ALOGW("Exiting SensorService::threadLoop => aborting...");
552    abort();
553    return false;
554}
555
556sp<Looper> SensorService::getLooper() const {
557    return mLooper;
558}
559
560void SensorService::resetAllWakeLockRefCounts() {
561    SortedVector< sp<SensorEventConnection> > activeConnections;
562    populateActiveConnections(&activeConnections);
563    {
564        Mutex::Autolock _l(mLock);
565        for (size_t i=0 ; i < activeConnections.size(); ++i) {
566            if (activeConnections[i] != 0) {
567                activeConnections[i]->resetWakeLockRefCount();
568            }
569        }
570        setWakeLockAcquiredLocked(false);
571    }
572}
573
574void SensorService::setWakeLockAcquiredLocked(bool acquire) {
575    if (acquire) {
576        if (!mWakeLockAcquired) {
577            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
578            mWakeLockAcquired = true;
579        }
580        mLooper->wake();
581    } else {
582        if (mWakeLockAcquired) {
583            release_wake_lock(WAKE_LOCK_NAME);
584            mWakeLockAcquired = false;
585        }
586    }
587}
588
589bool SensorService::isWakeLockAcquired() {
590    Mutex::Autolock _l(mLock);
591    return mWakeLockAcquired;
592}
593
594bool SensorService::SensorEventAckReceiver::threadLoop() {
595    ALOGD("new thread SensorEventAckReceiver");
596    sp<Looper> looper = mService->getLooper();
597    do {
598        bool wakeLockAcquired = mService->isWakeLockAcquired();
599        int timeout = -1;
600        if (wakeLockAcquired) timeout = 5000;
601        int ret = looper->pollOnce(timeout);
602        if (ret == ALOOPER_POLL_TIMEOUT) {
603           mService->resetAllWakeLockRefCounts();
604        }
605    } while(!Thread::exitPending());
606    return false;
607}
608
609void SensorService::recordLastValueLocked(
610        const sensors_event_t* buffer, size_t count) {
611    const sensors_event_t* last = NULL;
612    for (size_t i = 0; i < count; i++) {
613        const sensors_event_t* event = &buffer[i];
614        if (event->type != SENSOR_TYPE_META_DATA) {
615            if (last && event->sensor != last->sensor) {
616                mLastEventSeen.editValueFor(last->sensor) = *last;
617            }
618            last = event;
619        }
620    }
621    if (last) {
622        mLastEventSeen.editValueFor(last->sensor) = *last;
623    }
624}
625
626void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
627{
628    struct compar {
629        static int cmp(void const* lhs, void const* rhs) {
630            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
631            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
632            return l->timestamp - r->timestamp;
633        }
634    };
635    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
636}
637
638String8 SensorService::getSensorName(int handle) const {
639    size_t count = mUserSensorList.size();
640    for (size_t i=0 ; i<count ; i++) {
641        const Sensor& sensor(mUserSensorList[i]);
642        if (sensor.getHandle() == handle) {
643            return sensor.getName();
644        }
645    }
646    String8 result("unknown");
647    return result;
648}
649
650bool SensorService::isVirtualSensor(int handle) const {
651    SensorInterface* sensor = mSensorMap.valueFor(handle);
652    return sensor->isVirtual();
653}
654
655bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
656    int handle = event.sensor;
657    if (event.type == SENSOR_TYPE_META_DATA) {
658        handle = event.meta_data.sensor;
659    }
660    SensorInterface* sensor = mSensorMap.valueFor(handle);
661    return sensor != NULL && sensor->getSensor().isWakeUpSensor();
662}
663
664SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
665     return mActiveSensors.valueFor(handle);
666}
667
668Vector<Sensor> SensorService::getSensorList()
669{
670    char value[PROPERTY_VALUE_MAX];
671    property_get("debug.sensors", value, "0");
672    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
673            mUserSensorListDebug : mUserSensorList;
674    Vector<Sensor> accessibleSensorList;
675    for (size_t i = 0; i < initialSensorList.size(); i++) {
676        Sensor sensor = initialSensorList[i];
677        if (canAccessSensor(sensor)) {
678            accessibleSensorList.add(sensor);
679        } else {
680            ALOGI("Skipped sensor %s because it requires permission %s",
681                  sensor.getName().string(),
682                  sensor.getRequiredPermission().string());
683        }
684    }
685    return accessibleSensorList;
686}
687
688sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName)
689{
690    uid_t uid = IPCThreadState::self()->getCallingUid();
691    sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName));
692    return result;
693}
694
695void SensorService::cleanupConnection(SensorEventConnection* c)
696{
697    Mutex::Autolock _l(mLock);
698    const wp<SensorEventConnection> connection(c);
699    size_t size = mActiveSensors.size();
700    ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
701    for (size_t i=0 ; i<size ; ) {
702        int handle = mActiveSensors.keyAt(i);
703        if (c->hasSensor(handle)) {
704            ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
705            SensorInterface* sensor = mSensorMap.valueFor( handle );
706            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
707            if (sensor) {
708                sensor->activate(c, false);
709            }
710            c->removeSensor(handle);
711        }
712        SensorRecord* rec = mActiveSensors.valueAt(i);
713        ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
714        ALOGD_IF(DEBUG_CONNECTIONS,
715                "removing connection %p for sensor[%zu].handle=0x%08x",
716                c, i, handle);
717
718        if (rec && rec->removeConnection(connection)) {
719            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
720            mActiveSensors.removeItemsAt(i, 1);
721            mActiveVirtualSensors.removeItem(handle);
722            delete rec;
723            size--;
724        } else {
725            i++;
726        }
727    }
728    c->updateLooperRegistration(mLooper);
729    mActiveConnections.remove(connection);
730    BatteryService::cleanup(c->getUid());
731    if (c->needsWakeLock()) {
732        checkWakeLockStateLocked();
733    }
734}
735
736Sensor SensorService::getSensorFromHandle(int handle) const {
737    return mSensorMap.valueFor(handle)->getSensor();
738}
739
740status_t SensorService::enable(const sp<SensorEventConnection>& connection,
741        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
742{
743    if (mInitCheck != NO_ERROR)
744        return mInitCheck;
745
746    SensorInterface* sensor = mSensorMap.valueFor(handle);
747    if (sensor == NULL) {
748        return BAD_VALUE;
749    }
750
751    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
752        return BAD_VALUE;
753    }
754
755    Mutex::Autolock _l(mLock);
756    if (mMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
757        return INVALID_OPERATION;
758    }
759
760    SensorRecord* rec = mActiveSensors.valueFor(handle);
761    if (rec == 0) {
762        rec = new SensorRecord(connection);
763        mActiveSensors.add(handle, rec);
764        if (sensor->isVirtual()) {
765            mActiveVirtualSensors.add(handle, sensor);
766        }
767    } else {
768        if (rec->addConnection(connection)) {
769            // this sensor is already activated, but we are adding a connection that uses it.
770            // Immediately send down the last known value of the requested sensor if it's not a
771            // "continuous" sensor.
772            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
773                // NOTE: The wake_up flag of this event may get set to
774                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
775                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
776                if (event.version == sizeof(sensors_event_t)) {
777                    if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
778                        setWakeLockAcquiredLocked(true);
779                    }
780                    connection->sendEvents(&event, 1, NULL);
781                    if (!connection->needsWakeLock() && mWakeLockAcquired) {
782                        checkWakeLockStateLocked();
783                    }
784                }
785            }
786        }
787    }
788
789    if (connection->addSensor(handle)) {
790        BatteryService::enableSensor(connection->getUid(), handle);
791        // the sensor was added (which means it wasn't already there)
792        // so, see if this connection becomes active
793        if (mActiveConnections.indexOf(connection) < 0) {
794            mActiveConnections.add(connection);
795        }
796    } else {
797        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
798            handle, connection.get());
799    }
800
801    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
802    if (samplingPeriodNs < minDelayNs) {
803        samplingPeriodNs = minDelayNs;
804    }
805
806    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
807                                "rate=%" PRId64 " timeout== %" PRId64"",
808             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
809
810    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
811                                 maxBatchReportLatencyNs);
812
813    // Call flush() before calling activate() on the sensor. Wait for a first flush complete
814    // event before sending events on this connection. Ignore one-shot sensors which don't
815    // support flush(). Also if this sensor isn't already active, don't call flush().
816    if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
817            rec->getNumConnections() > 1) {
818        connection->setFirstFlushPending(handle, true);
819        status_t err_flush = sensor->flush(connection.get(), handle);
820        // Flush may return error if the underlying h/w sensor uses an older HAL.
821        if (err_flush == NO_ERROR) {
822            rec->addPendingFlushConnection(connection.get());
823        } else {
824            connection->setFirstFlushPending(handle, false);
825        }
826    }
827
828    if (err == NO_ERROR) {
829        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
830        err = sensor->activate(connection.get(), true);
831    }
832
833    if (err == NO_ERROR) {
834        connection->updateLooperRegistration(mLooper);
835    }
836
837    if (err != NO_ERROR) {
838        // batch/activate has failed, reset our state.
839        cleanupWithoutDisableLocked(connection, handle);
840    }
841    return err;
842}
843
844status_t SensorService::disable(const sp<SensorEventConnection>& connection,
845        int handle)
846{
847    if (mInitCheck != NO_ERROR)
848        return mInitCheck;
849
850    Mutex::Autolock _l(mLock);
851    status_t err = cleanupWithoutDisableLocked(connection, handle);
852    if (err == NO_ERROR) {
853        SensorInterface* sensor = mSensorMap.valueFor(handle);
854        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
855    }
856    return err;
857}
858
859status_t SensorService::cleanupWithoutDisable(
860        const sp<SensorEventConnection>& connection, int handle) {
861    Mutex::Autolock _l(mLock);
862    return cleanupWithoutDisableLocked(connection, handle);
863}
864
865status_t SensorService::cleanupWithoutDisableLocked(
866        const sp<SensorEventConnection>& connection, int handle) {
867    SensorRecord* rec = mActiveSensors.valueFor(handle);
868    if (rec) {
869        // see if this connection becomes inactive
870        if (connection->removeSensor(handle)) {
871            BatteryService::disableSensor(connection->getUid(), handle);
872        }
873        if (connection->hasAnySensor() == false) {
874            connection->updateLooperRegistration(mLooper);
875            mActiveConnections.remove(connection);
876        }
877        // see if this sensor becomes inactive
878        if (rec->removeConnection(connection)) {
879            mActiveSensors.removeItem(handle);
880            mActiveVirtualSensors.removeItem(handle);
881            delete rec;
882        }
883        return NO_ERROR;
884    }
885    return BAD_VALUE;
886}
887
888status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
889        int handle, nsecs_t ns)
890{
891    if (mInitCheck != NO_ERROR)
892        return mInitCheck;
893
894    SensorInterface* sensor = mSensorMap.valueFor(handle);
895    if (!sensor)
896        return BAD_VALUE;
897
898    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
899        return BAD_VALUE;
900    }
901
902    if (ns < 0)
903        return BAD_VALUE;
904
905    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
906    if (ns < minDelayNs) {
907        ns = minDelayNs;
908    }
909
910    return sensor->setDelay(connection.get(), handle, ns);
911}
912
913status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
914    if (mInitCheck != NO_ERROR) return mInitCheck;
915    SensorDevice& dev(SensorDevice::getInstance());
916    const int halVersion = dev.getHalDeviceVersion();
917    status_t err(NO_ERROR);
918    Mutex::Autolock _l(mLock);
919    // Loop through all sensors for this connection and call flush on each of them.
920    for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
921        const int handle = connection->mSensorInfo.keyAt(i);
922        SensorInterface* sensor = mSensorMap.valueFor(handle);
923        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
924            ALOGE("flush called on a one-shot sensor");
925            err = INVALID_OPERATION;
926            continue;
927        }
928        if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
929            // For older devices just increment pending flush count which will send a trivial
930            // flush complete event.
931            connection->incrementPendingFlushCount(handle);
932        } else {
933            status_t err_flush = sensor->flush(connection.get(), handle);
934            if (err_flush == NO_ERROR) {
935                SensorRecord* rec = mActiveSensors.valueFor(handle);
936                if (rec != NULL) rec->addPendingFlushConnection(connection);
937            }
938            err = (err_flush != NO_ERROR) ? err_flush : err;
939        }
940    }
941    return err;
942}
943
944bool SensorService::canAccessSensor(const Sensor& sensor) {
945    return (sensor.getRequiredPermission().isEmpty()) ||
946            PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
947}
948
949bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
950    if (canAccessSensor(sensor)) {
951        return true;
952    } else {
953        String8 errorMessage;
954        errorMessage.appendFormat(
955                "%s a sensor (%s) without holding its required permission: %s",
956                operation,
957                sensor.getName().string(),
958                sensor.getRequiredPermission().string());
959        return false;
960    }
961}
962
963void SensorService::checkWakeLockState() {
964    Mutex::Autolock _l(mLock);
965    checkWakeLockStateLocked();
966}
967
968void SensorService::checkWakeLockStateLocked() {
969    if (!mWakeLockAcquired) {
970        return;
971    }
972    bool releaseLock = true;
973    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
974        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
975        if (connection != 0) {
976            if (connection->needsWakeLock()) {
977                releaseLock = false;
978                break;
979            }
980        }
981    }
982    if (releaseLock) {
983        setWakeLockAcquiredLocked(false);
984    }
985}
986
987void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
988    Mutex::Autolock _l(mLock);
989    connection->writeToSocketFromCache();
990    if (connection->needsWakeLock()) {
991        setWakeLockAcquiredLocked(true);
992    }
993}
994
995void SensorService::populateActiveConnections(
996        SortedVector< sp<SensorEventConnection> >* activeConnections) {
997    Mutex::Autolock _l(mLock);
998    for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
999        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1000        if (connection != 0) {
1001            activeConnections->add(connection);
1002        }
1003    }
1004}
1005
1006bool SensorService::isWhiteListedPackage(const String8& packageName) {
1007    // TODO: Come up with a list of packages.
1008    return (packageName.find(".cts.") != -1);
1009}
1010
1011// ---------------------------------------------------------------------------
1012SensorService::SensorRecord::SensorRecord(
1013        const sp<SensorEventConnection>& connection)
1014{
1015    mConnections.add(connection);
1016}
1017
1018bool SensorService::SensorRecord::addConnection(
1019        const sp<SensorEventConnection>& connection)
1020{
1021    if (mConnections.indexOf(connection) < 0) {
1022        mConnections.add(connection);
1023        return true;
1024    }
1025    return false;
1026}
1027
1028bool SensorService::SensorRecord::removeConnection(
1029        const wp<SensorEventConnection>& connection)
1030{
1031    ssize_t index = mConnections.indexOf(connection);
1032    if (index >= 0) {
1033        mConnections.removeItemsAt(index, 1);
1034    }
1035    // Remove this connections from the queue of flush() calls made on this sensor.
1036    for (Vector< wp<SensorEventConnection> >::iterator it =
1037            mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
1038
1039        if (it->unsafe_get() == connection.unsafe_get()) {
1040            it = mPendingFlushConnections.erase(it);
1041        } else {
1042            ++it;
1043        }
1044    }
1045    return mConnections.size() ? false : true;
1046}
1047
1048void SensorService::SensorRecord::addPendingFlushConnection(
1049        const sp<SensorEventConnection>& connection) {
1050    mPendingFlushConnections.add(connection);
1051}
1052
1053void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1054    if (mPendingFlushConnections.size() > 0) {
1055        mPendingFlushConnections.removeAt(0);
1056    }
1057}
1058
1059SensorService::SensorEventConnection *
1060SensorService::SensorRecord::getFirstPendingFlushConnection() {
1061   if (mPendingFlushConnections.size() > 0) {
1062        return mPendingFlushConnections[0].unsafe_get();
1063    }
1064    return NULL;
1065}
1066
1067void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1068    mPendingFlushConnections.clear();
1069}
1070
1071// ---------------------------------------------------------------------------
1072
1073SensorService::SensorEventConnection::SensorEventConnection(
1074        const sp<SensorService>& service, uid_t uid, String8 packageName)
1075    : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
1076      mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName) {
1077    mChannel = new BitTube(mService->mSocketBufferSize);
1078#if DEBUG_CONNECTIONS
1079    mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
1080    mTotalAcksNeeded = mTotalAcksReceived = 0;
1081#endif
1082}
1083
1084SensorService::SensorEventConnection::~SensorEventConnection() {
1085    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
1086    mService->cleanupConnection(this);
1087    if (mEventCache != NULL) {
1088        delete mEventCache;
1089    }
1090}
1091
1092void SensorService::SensorEventConnection::onFirstRef() {
1093    LooperCallback::onFirstRef();
1094}
1095
1096bool SensorService::SensorEventConnection::needsWakeLock() {
1097    Mutex::Autolock _l(mConnectionLock);
1098    return !mDead && mWakeLockRefCount > 0;
1099}
1100
1101void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1102    Mutex::Autolock _l(mConnectionLock);
1103    mWakeLockRefCount = 0;
1104}
1105
1106void SensorService::SensorEventConnection::dump(String8& result) {
1107    Mutex::Autolock _l(mConnectionLock);
1108    result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1109            mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
1110    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1111        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
1112        result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
1113                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
1114                            mSensorInfo.keyAt(i),
1115                            flushInfo.mFirstFlushPending ? "First flush pending" :
1116                                                           "active",
1117                            flushInfo.mPendingFlushEventsToSend);
1118    }
1119#if DEBUG_CONNECTIONS
1120    result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1121            " total_acks_needed %d | total_acks_recvd %d\n",
1122            mEventsReceived,
1123            mEventsSent,
1124            mEventsSentFromCache,
1125            mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1126            mTotalAcksNeeded,
1127            mTotalAcksReceived);
1128#endif
1129}
1130
1131bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
1132    Mutex::Autolock _l(mConnectionLock);
1133    if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1134        return false;
1135    }
1136    if (mSensorInfo.indexOfKey(handle) < 0) {
1137        mSensorInfo.add(handle, FlushInfo());
1138        return true;
1139    }
1140    return false;
1141}
1142
1143bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
1144    Mutex::Autolock _l(mConnectionLock);
1145    if (mSensorInfo.removeItem(handle) >= 0) {
1146        return true;
1147    }
1148    return false;
1149}
1150
1151bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
1152    Mutex::Autolock _l(mConnectionLock);
1153    return mSensorInfo.indexOfKey(handle) >= 0;
1154}
1155
1156bool SensorService::SensorEventConnection::hasAnySensor() const {
1157    Mutex::Autolock _l(mConnectionLock);
1158    return mSensorInfo.size() ? true : false;
1159}
1160
1161bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1162    Mutex::Autolock _l(mConnectionLock);
1163    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1164        const int handle = mSensorInfo.keyAt(i);
1165        if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1166            return true;
1167        }
1168    }
1169    return false;
1170}
1171
1172String8 SensorService::SensorEventConnection::getPackageName() const {
1173    return mPackageName;
1174}
1175
1176void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1177                                bool value) {
1178    Mutex::Autolock _l(mConnectionLock);
1179    ssize_t index = mSensorInfo.indexOfKey(handle);
1180    if (index >= 0) {
1181        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1182        flushInfo.mFirstFlushPending = value;
1183    }
1184}
1185
1186void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1187    Mutex::Autolock _l(mConnectionLock);
1188    updateLooperRegistrationLocked(looper);
1189}
1190
1191void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1192        const sp<Looper>& looper) {
1193    bool isConnectionActive = mSensorInfo.size() > 0;
1194    // If all sensors are unregistered OR Looper has encountered an error, we
1195    // can remove the Fd from the Looper if it has been previously added.
1196    if (!isConnectionActive || mDead) {
1197        if (mHasLooperCallbacks) {
1198            ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1199            looper->removeFd(mChannel->getSendFd());
1200            mHasLooperCallbacks = false;
1201        }
1202        return;
1203    }
1204
1205    int looper_flags = 0;
1206    if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
1207    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1208        const int handle = mSensorInfo.keyAt(i);
1209        if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1210            looper_flags |= ALOOPER_EVENT_INPUT;
1211            break;
1212        }
1213    }
1214    // If flags is still set to zero, we don't need to add this fd to the Looper, if
1215    // the fd has already been added, remove it. This is likely to happen when ALL the
1216    // events stored in the cache have been sent to the corresponding app.
1217    if (looper_flags == 0) {
1218        if (mHasLooperCallbacks) {
1219            ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1220            looper->removeFd(mChannel->getSendFd());
1221            mHasLooperCallbacks = false;
1222        }
1223        return;
1224    }
1225    // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1226    // registered for wake-up sensors OR for sending events in the cache.
1227    int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1228    if (ret == 1) {
1229        ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1230        mHasLooperCallbacks = true;
1231    } else {
1232        ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1233    }
1234}
1235
1236void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1237    Mutex::Autolock _l(mConnectionLock);
1238    ssize_t index = mSensorInfo.indexOfKey(handle);
1239    if (index >= 0) {
1240        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1241        flushInfo.mPendingFlushEventsToSend++;
1242    }
1243}
1244
1245status_t SensorService::SensorEventConnection::sendEvents(
1246        sensors_event_t const* buffer, size_t numEvents,
1247        sensors_event_t* scratch,
1248        SensorEventConnection const * const * mapFlushEventsToConnections) {
1249    // filter out events not for this connection
1250    size_t count = 0;
1251    Mutex::Autolock _l(mConnectionLock);
1252    if (scratch) {
1253        size_t i=0;
1254        while (i<numEvents) {
1255            int32_t sensor_handle = buffer[i].sensor;
1256            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1257                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
1258                        buffer[i].meta_data.sensor);
1259                // Setting sensor_handle to the correct sensor to ensure the sensor events per
1260                // connection are filtered correctly.  buffer[i].sensor is zero for meta_data
1261                // events.
1262                sensor_handle = buffer[i].meta_data.sensor;
1263            }
1264            ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
1265            // Check if this connection has registered for this sensor. If not continue to the
1266            // next sensor_event.
1267            if (index < 0) {
1268                ++i;
1269                continue;
1270            }
1271
1272            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1273            // Check if there is a pending flush_complete event for this sensor on this connection.
1274            if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1275                    this == mapFlushEventsToConnections[i]) {
1276                flushInfo.mFirstFlushPending = false;
1277                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1278                        buffer[i].meta_data.sensor);
1279                ++i;
1280                continue;
1281            }
1282
1283            // If there is a pending flush complete event for this sensor on this connection,
1284            // ignore the event and proceed to the next.
1285            if (flushInfo.mFirstFlushPending) {
1286                ++i;
1287                continue;
1288            }
1289
1290            do {
1291                // Keep copying events into the scratch buffer as long as they are regular
1292                // sensor_events are from the same sensor_handle OR they are flush_complete_events
1293                // from the same sensor_handle AND the current connection is mapped to the
1294                // corresponding flush_complete_event.
1295                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1296                    if (this == mapFlushEventsToConnections[i]) {
1297                        scratch[count++] = buffer[i];
1298                    }
1299                    ++i;
1300                } else {
1301                    // Regular sensor event, just copy it to the scratch buffer.
1302                    scratch[count++] = buffer[i++];
1303                }
1304            } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1305                                        buffer[i].type != SENSOR_TYPE_META_DATA) ||
1306                                       (buffer[i].type == SENSOR_TYPE_META_DATA  &&
1307                                        buffer[i].meta_data.sensor == sensor_handle)));
1308        }
1309    } else {
1310        scratch = const_cast<sensors_event_t *>(buffer);
1311        count = numEvents;
1312    }
1313
1314    sendPendingFlushEventsLocked();
1315    // Early return if there are no events for this connection.
1316    if (count == 0) {
1317        return status_t(NO_ERROR);
1318    }
1319
1320#if DEBUG_CONNECTIONS
1321     mEventsReceived += count;
1322#endif
1323    if (mCacheSize != 0) {
1324        // There are some events in the cache which need to be sent first. Copy this buffer to
1325        // the end of cache.
1326        if (mCacheSize + count <= mMaxCacheSize) {
1327            memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1328            mCacheSize += count;
1329        } else {
1330            // Check if any new sensors have registered on this connection which may have increased
1331            // the max cache size that is desired.
1332            if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1333                reAllocateCacheLocked(scratch, count);
1334                return status_t(NO_ERROR);
1335            }
1336            // Some events need to be dropped.
1337            int remaningCacheSize = mMaxCacheSize - mCacheSize;
1338            if (remaningCacheSize != 0) {
1339                memcpy(&mEventCache[mCacheSize], scratch,
1340                                                remaningCacheSize * sizeof(sensors_event_t));
1341            }
1342            int numEventsDropped = count - remaningCacheSize;
1343            countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1344            // Drop the first "numEventsDropped" in the cache.
1345            memmove(mEventCache, &mEventCache[numEventsDropped],
1346                    (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1347
1348            // Copy the remainingEvents in scratch buffer to the end of cache.
1349            memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1350                                            numEventsDropped * sizeof(sensors_event_t));
1351        }
1352        return status_t(NO_ERROR);
1353    }
1354
1355    int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1356    if (index_wake_up_event >= 0) {
1357        scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1358        ++mWakeLockRefCount;
1359#if DEBUG_CONNECTIONS
1360        ++mTotalAcksNeeded;
1361#endif
1362    }
1363
1364    // NOTE: ASensorEvent and sensors_event_t are the same type.
1365    ssize_t size = SensorEventQueue::write(mChannel,
1366                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
1367    if (size < 0) {
1368        // Write error, copy events to local cache.
1369        if (index_wake_up_event >= 0) {
1370            // If there was a wake_up sensor_event, reset the flag.
1371            scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1372            if (mWakeLockRefCount > 0) {
1373                --mWakeLockRefCount;
1374            }
1375#if DEBUG_CONNECTIONS
1376            --mTotalAcksNeeded;
1377#endif
1378        }
1379        if (mEventCache == NULL) {
1380            mMaxCacheSize = computeMaxCacheSizeLocked();
1381            mEventCache = new sensors_event_t[mMaxCacheSize];
1382            mCacheSize = 0;
1383        }
1384        memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1385        mCacheSize += count;
1386
1387        // Add this file descriptor to the looper to get a callback when this fd is available for
1388        // writing.
1389        updateLooperRegistrationLocked(mService->getLooper());
1390        return size;
1391    }
1392
1393#if DEBUG_CONNECTIONS
1394    if (size > 0) {
1395        mEventsSent += count;
1396    }
1397#endif
1398
1399    return size < 0 ? status_t(size) : status_t(NO_ERROR);
1400}
1401
1402void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1403                                                                 int count) {
1404    sensors_event_t *eventCache_new;
1405    const int new_cache_size = computeMaxCacheSizeLocked();
1406    // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1407    eventCache_new = new sensors_event_t[new_cache_size];
1408    memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1409    memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1410
1411    ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1412            new_cache_size);
1413
1414    delete mEventCache;
1415    mEventCache = eventCache_new;
1416    mCacheSize += count;
1417    mMaxCacheSize = new_cache_size;
1418}
1419
1420void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1421    ASensorEvent flushCompleteEvent;
1422    memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
1423    flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
1424    // Loop through all the sensors for this connection and check if there are any pending
1425    // flush complete events to be sent.
1426    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1427        FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1428        while (flushInfo.mPendingFlushEventsToSend > 0) {
1429            const int sensor_handle = mSensorInfo.keyAt(i);
1430            flushCompleteEvent.meta_data.sensor = sensor_handle;
1431            bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1432            if (wakeUpSensor) {
1433               ++mWakeLockRefCount;
1434               flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1435            }
1436            ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1437            if (size < 0) {
1438                if (wakeUpSensor) --mWakeLockRefCount;
1439                return;
1440            }
1441            ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1442                    flushCompleteEvent.meta_data.sensor);
1443            flushInfo.mPendingFlushEventsToSend--;
1444        }
1445    }
1446}
1447
1448void SensorService::SensorEventConnection::writeToSocketFromCache() {
1449    // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1450    // half the size of the socket buffer allocated in BitTube whichever is smaller.
1451    const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1452            int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
1453    Mutex::Autolock _l(mConnectionLock);
1454    // Send pending flush complete events (if any)
1455    sendPendingFlushEventsLocked();
1456    for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
1457        const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
1458        int index_wake_up_event =
1459                  findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1460        if (index_wake_up_event >= 0) {
1461            mEventCache[index_wake_up_event + numEventsSent].flags |=
1462                    WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1463            ++mWakeLockRefCount;
1464#if DEBUG_CONNECTIONS
1465            ++mTotalAcksNeeded;
1466#endif
1467        }
1468
1469        ssize_t size = SensorEventQueue::write(mChannel,
1470                          reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
1471                          numEventsToWrite);
1472        if (size < 0) {
1473            if (index_wake_up_event >= 0) {
1474                // If there was a wake_up sensor_event, reset the flag.
1475                mEventCache[index_wake_up_event + numEventsSent].flags  &=
1476                        ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1477                if (mWakeLockRefCount > 0) {
1478                    --mWakeLockRefCount;
1479                }
1480#if DEBUG_CONNECTIONS
1481                --mTotalAcksNeeded;
1482#endif
1483            }
1484            memmove(mEventCache, &mEventCache[numEventsSent],
1485                                 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1486            ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
1487                    numEventsSent, mCacheSize);
1488            mCacheSize -= numEventsSent;
1489            return;
1490        }
1491        numEventsSent += numEventsToWrite;
1492#if DEBUG_CONNECTIONS
1493        mEventsSentFromCache += numEventsToWrite;
1494#endif
1495    }
1496    ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1497    // All events from the cache have been sent. Reset cache size to zero.
1498    mCacheSize = 0;
1499    // There are no more events in the cache. We don't need to poll for write on the fd.
1500    // Update Looper registration.
1501    updateLooperRegistrationLocked(mService->getLooper());
1502}
1503
1504void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
1505                sensors_event_t const* scratch, const int numEventsDropped) {
1506    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
1507    // Count flushComplete events in the events that are about to the dropped. These will be sent
1508    // separately before the next batch of events.
1509    for (int j = 0; j < numEventsDropped; ++j) {
1510        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1511            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1512            flushInfo.mPendingFlushEventsToSend++;
1513            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1514                     flushInfo.mPendingFlushEventsToSend);
1515        }
1516    }
1517    return;
1518}
1519
1520int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1521                       sensors_event_t const* scratch, const int count) {
1522    for (int i = 0; i < count; ++i) {
1523        if (mService->isWakeUpSensorEvent(scratch[i])) {
1524            return i;
1525        }
1526    }
1527    return -1;
1528}
1529
1530sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
1531{
1532    return mChannel;
1533}
1534
1535status_t SensorService::SensorEventConnection::enableDisable(
1536        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1537        int reservedFlags)
1538{
1539    status_t err;
1540    if (enabled) {
1541        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1542                               reservedFlags);
1543
1544    } else {
1545        err = mService->disable(this, handle);
1546    }
1547    return err;
1548}
1549
1550status_t SensorService::SensorEventConnection::setEventRate(
1551        int handle, nsecs_t samplingPeriodNs)
1552{
1553    return mService->setEventRate(this, handle, samplingPeriodNs);
1554}
1555
1556status_t  SensorService::SensorEventConnection::flush() {
1557    return  mService->flushSensor(this);
1558}
1559
1560int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
1561    if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1562        {
1563            // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1564            // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1565            // can release the wake-lock.
1566            ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1567            Mutex::Autolock _l(mConnectionLock);
1568            mDead = true;
1569            mWakeLockRefCount = 0;
1570            updateLooperRegistrationLocked(mService->getLooper());
1571        }
1572        mService->checkWakeLockState();
1573        return 1;
1574    }
1575
1576    if (events & ALOOPER_EVENT_INPUT) {
1577        uint32_t numAcks = 0;
1578        ssize_t ret = ::recv(fd, &numAcks, sizeof(numAcks), MSG_DONTWAIT);
1579        {
1580           Mutex::Autolock _l(mConnectionLock);
1581           // Sanity check to ensure  there are no read errors in recv, numAcks is always
1582           // within the range and not zero. If any of the above don't hold reset mWakeLockRefCount
1583           // to zero.
1584           if (ret != sizeof(numAcks) || numAcks > mWakeLockRefCount || numAcks == 0) {
1585               ALOGE("Looper read error ret=%d numAcks=%d", ret, numAcks);
1586               mWakeLockRefCount = 0;
1587           } else {
1588               mWakeLockRefCount -= numAcks;
1589           }
1590#if DEBUG_CONNECTIONS
1591           mTotalAcksReceived += numAcks;
1592#endif
1593        }
1594        // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1595        // here as checkWakeLockState() will need it.
1596        if (mWakeLockRefCount == 0) {
1597            mService->checkWakeLockState();
1598        }
1599        // continue getting callbacks.
1600        return 1;
1601    }
1602
1603    if (events & ALOOPER_EVENT_OUTPUT) {
1604        // send sensor data that is stored in mEventCache for this connection.
1605        mService->sendEventsFromCache(this);
1606    }
1607    return 1;
1608}
1609
1610int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1611    int fifoWakeUpSensors = 0;
1612    int fifoNonWakeUpSensors = 0;
1613    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1614        const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1615        if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1616            // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1617            // non wake_up sensors.
1618            if (sensor.isWakeUpSensor()) {
1619                fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1620            } else {
1621                fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1622            }
1623        } else {
1624            // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1625            if (sensor.isWakeUpSensor()) {
1626                fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1627                                          fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1628
1629            } else {
1630                fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1631                                          fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1632
1633            }
1634        }
1635   }
1636   if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1637       // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
1638       // size that is equal to that of the batch mode.
1639       // ALOGW("Write failure in non-batch mode");
1640       return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
1641   }
1642   return fifoWakeUpSensors + fifoNonWakeUpSensors;
1643}
1644
1645// ---------------------------------------------------------------------------
1646}; // namespace android
1647
1648