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