SensorService.cpp revision 0ec2066e4774b851c66176b99b0a5aa5abe6ad00
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        Mutex::Autolock _l(mLock);
402        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
403        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
404        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
405        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
406        // releasing the wakelock.
407        bool bufferHasWakeUpEvent = false;
408        for (int i = 0; i < count; i++) {
409            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
410                bufferHasWakeUpEvent = true;
411                break;
412            }
413        }
414
415        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
416            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
417            mWakeLockAcquired = true;
418            ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
419        }
420        recordLastValueLocked(mSensorEventBuffer, count);
421
422        // handle virtual sensors
423        if (count && vcount) {
424            sensors_event_t const * const event = mSensorEventBuffer;
425            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
426            if (activeVirtualSensorCount) {
427                size_t k = 0;
428                SensorFusion& fusion(SensorFusion::getInstance());
429                if (fusion.isEnabled()) {
430                    for (size_t i=0 ; i<size_t(count) ; i++) {
431                        fusion.process(event[i]);
432                    }
433                }
434                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
435                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
436                        if (count + k >= minBufferSize) {
437                            ALOGE("buffer too small to hold all events: "
438                                    "count=%zd, k=%zu, size=%zu",
439                                    count, k, minBufferSize);
440                            break;
441                        }
442                        sensors_event_t out;
443                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
444                        if (si->process(&out, event[i])) {
445                            mSensorEventBuffer[count + k] = out;
446                            k++;
447                        }
448                    }
449                }
450                if (k) {
451                    // record the last synthesized values
452                    recordLastValueLocked(&mSensorEventBuffer[count], k);
453                    count += k;
454                    // sort the buffer by time-stamps
455                    sortEventBuffer(mSensorEventBuffer, count);
456                }
457            }
458        }
459
460        // handle backward compatibility for RotationVector sensor
461        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
462            for (int i = 0; i < count; i++) {
463                if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
464                    // All the 4 components of the quaternion should be available
465                    // No heading accuracy. Set it to -1
466                    mSensorEventBuffer[i].data[4] = -1;
467                }
468            }
469        }
470
471        // Map flush_complete_events in the buffer to SensorEventConnections which called
472        // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
473        // SensorEventConnection mapped to the corresponding flush_complete_event in
474        // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
475        for (int i = 0; i < count; ++i) {
476            mMapFlushEventsToConnections[i] = NULL;
477            if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
478                const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
479                SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
480                if (rec != NULL) {
481                    mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
482                    rec->removeFirstPendingFlushConnection();
483                }
484            }
485        }
486
487        // Send our events to clients. Check the state of wake lock for each client and release the
488        // lock if none of the clients need it.
489        bool needsWakeLock = false;
490        // Make a copy of the connection vector as some connections may be removed during the
491        // course of this loop (especially when one-shot sensor events are present in the
492        // sensor_event buffer).
493        const SortedVector< wp<SensorEventConnection> > activeConnections(mActiveConnections);
494        size_t numConnections = activeConnections.size();
495        for (size_t i=0 ; i < numConnections; ++i) {
496            sp<SensorEventConnection> connection(activeConnections[i].promote());
497            if (connection != 0) {
498                connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
499                        mMapFlushEventsToConnections);
500                needsWakeLock |= connection->needsWakeLock();
501                // If the connection has one-shot sensors, it may be cleaned up after first trigger.
502                // Early check for one-shot sensors.
503                if (connection->hasOneShotSensors()) {
504                    cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
505                }
506            }
507        }
508
509        if (mWakeLockAcquired && !needsWakeLock) {
510            release_wake_lock(WAKE_LOCK_NAME);
511            mWakeLockAcquired = false;
512            ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
513        }
514    } while (!Thread::exitPending());
515
516    ALOGW("Exiting SensorService::threadLoop => aborting...");
517    abort();
518    return false;
519}
520
521sp<Looper> SensorService::getLooper() const {
522    return mLooper;
523}
524
525bool SensorService::SensorEventAckReceiver::threadLoop() {
526    ALOGD("new thread SensorEventAckReceiver");
527    do {
528        sp<Looper> looper = mService->getLooper();
529        looper->pollOnce(-1);
530    } while(!Thread::exitPending());
531    return false;
532}
533
534void SensorService::recordLastValueLocked(
535        const sensors_event_t* buffer, size_t count) {
536    const sensors_event_t* last = NULL;
537    for (size_t i = 0; i < count; i++) {
538        const sensors_event_t* event = &buffer[i];
539        if (event->type != SENSOR_TYPE_META_DATA) {
540            if (last && event->sensor != last->sensor) {
541                mLastEventSeen.editValueFor(last->sensor) = *last;
542            }
543            last = event;
544        }
545    }
546    if (last) {
547        mLastEventSeen.editValueFor(last->sensor) = *last;
548    }
549}
550
551void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
552{
553    struct compar {
554        static int cmp(void const* lhs, void const* rhs) {
555            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
556            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
557            return l->timestamp - r->timestamp;
558        }
559    };
560    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
561}
562
563String8 SensorService::getSensorName(int handle) const {
564    size_t count = mUserSensorList.size();
565    for (size_t i=0 ; i<count ; i++) {
566        const Sensor& sensor(mUserSensorList[i]);
567        if (sensor.getHandle() == handle) {
568            return sensor.getName();
569        }
570    }
571    String8 result("unknown");
572    return result;
573}
574
575bool SensorService::isVirtualSensor(int handle) const {
576    SensorInterface* sensor = mSensorMap.valueFor(handle);
577    return sensor->isVirtual();
578}
579
580bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
581    int handle = event.sensor;
582    if (event.type == SENSOR_TYPE_META_DATA) {
583        handle = event.meta_data.sensor;
584    }
585    SensorInterface* sensor = mSensorMap.valueFor(handle);
586    return sensor != NULL && sensor->getSensor().isWakeUpSensor();
587}
588
589
590SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
591     return mActiveSensors.valueFor(handle);
592}
593
594Vector<Sensor> SensorService::getSensorList()
595{
596    char value[PROPERTY_VALUE_MAX];
597    property_get("debug.sensors", value, "0");
598    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
599            mUserSensorListDebug : mUserSensorList;
600    Vector<Sensor> accessibleSensorList;
601    for (size_t i = 0; i < initialSensorList.size(); i++) {
602        Sensor sensor = initialSensorList[i];
603        if (canAccessSensor(sensor)) {
604            accessibleSensorList.add(sensor);
605        } else {
606            String8 infoMessage;
607            infoMessage.appendFormat(
608                    "Skipped sensor %s because it requires permission %s",
609                    sensor.getName().string(),
610                    sensor.getRequiredPermission().string());
611            ALOGI(infoMessage.string());
612        }
613    }
614    return accessibleSensorList;
615}
616
617sp<ISensorEventConnection> SensorService::createSensorEventConnection()
618{
619    uid_t uid = IPCThreadState::self()->getCallingUid();
620    sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
621    return result;
622}
623
624void SensorService::cleanupConnection(SensorEventConnection* c)
625{
626    Mutex::Autolock _l(mLock);
627    const wp<SensorEventConnection> connection(c);
628    size_t size = mActiveSensors.size();
629    ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
630    for (size_t i=0 ; i<size ; ) {
631        int handle = mActiveSensors.keyAt(i);
632        if (c->hasSensor(handle)) {
633            ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
634            SensorInterface* sensor = mSensorMap.valueFor( handle );
635            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
636            if (sensor) {
637                sensor->activate(c, false);
638            }
639        }
640        SensorRecord* rec = mActiveSensors.valueAt(i);
641        ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
642        ALOGD_IF(DEBUG_CONNECTIONS,
643                "removing connection %p for sensor[%zu].handle=0x%08x",
644                c, i, handle);
645
646        if (rec && rec->removeConnection(connection)) {
647            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
648            mActiveSensors.removeItemsAt(i, 1);
649            mActiveVirtualSensors.removeItem(handle);
650            delete rec;
651            size--;
652        } else {
653            i++;
654        }
655    }
656    mActiveConnections.remove(connection);
657    BatteryService::cleanup(c->getUid());
658    if (c->needsWakeLock()) {
659        checkWakeLockStateLocked();
660    }
661}
662
663Sensor SensorService::getSensorFromHandle(int handle) const {
664    return mSensorMap.valueFor(handle)->getSensor();
665}
666
667status_t SensorService::enable(const sp<SensorEventConnection>& connection,
668        int handle, nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags)
669{
670    if (mInitCheck != NO_ERROR)
671        return mInitCheck;
672
673    SensorInterface* sensor = mSensorMap.valueFor(handle);
674    if (sensor == NULL) {
675        return BAD_VALUE;
676    }
677
678    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
679        return BAD_VALUE;
680    }
681
682    Mutex::Autolock _l(mLock);
683    SensorRecord* rec = mActiveSensors.valueFor(handle);
684    if (rec == 0) {
685        rec = new SensorRecord(connection);
686        mActiveSensors.add(handle, rec);
687        if (sensor->isVirtual()) {
688            mActiveVirtualSensors.add(handle, sensor);
689        }
690    } else {
691        if (rec->addConnection(connection)) {
692            // this sensor is already activated, but we are adding a connection that uses it.
693            // Immediately send down the last known value of the requested sensor if it's not a
694            // "continuous" sensor.
695            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
696                // NOTE: The wake_up flag of this event may get set to
697                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
698                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
699                if (event.version == sizeof(sensors_event_t)) {
700                    if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
701                        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
702                        mWakeLockAcquired = true;
703                        ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
704                                                        WAKE_LOCK_NAME);
705                    }
706                    connection->sendEvents(&event, 1, NULL);
707                    if (!connection->needsWakeLock() && mWakeLockAcquired) {
708                        checkWakeLockStateLocked();
709                    }
710                }
711            }
712        }
713    }
714
715    if (connection->addSensor(handle)) {
716        BatteryService::enableSensor(connection->getUid(), handle);
717        // the sensor was added (which means it wasn't already there)
718        // so, see if this connection becomes active
719        if (mActiveConnections.indexOf(connection) < 0) {
720            mActiveConnections.add(connection);
721        }
722    } else {
723        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
724            handle, connection.get());
725    }
726
727    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
728    if (samplingPeriodNs < minDelayNs) {
729        samplingPeriodNs = minDelayNs;
730    }
731
732    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
733                                "rate=%" PRId64 " timeout== %" PRId64"",
734             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
735
736    status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
737                                 maxBatchReportLatencyNs);
738
739    // Call flush() before calling activate() on the sensor. Wait for a first flush complete
740    // event before sending events on this connection. Ignore one-shot sensors which don't
741    // support flush(). Also if this sensor isn't already active, don't call flush().
742    if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
743            rec->getNumConnections() > 1) {
744        connection->setFirstFlushPending(handle, true);
745        status_t err_flush = sensor->flush(connection.get(), handle);
746        // Flush may return error if the underlying h/w sensor uses an older HAL.
747        if (err_flush == NO_ERROR) {
748            rec->addPendingFlushConnection(connection.get());
749        } else {
750            connection->setFirstFlushPending(handle, false);
751        }
752    }
753
754    if (err == NO_ERROR) {
755        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
756        err = sensor->activate(connection.get(), true);
757    }
758
759    if (err == NO_ERROR && sensor->getSensor().isWakeUpSensor()) {
760        // Add the file descriptor to the Looper for receiving acknowledgments;
761        int ret = mLooper->addFd(connection->getSensorChannel()->getSendFd(), 0,
762                                        ALOOPER_EVENT_INPUT, connection.get(), NULL);
763    }
764
765    if (err != NO_ERROR) {
766        // batch/activate has failed, reset our state.
767        cleanupWithoutDisableLocked(connection, handle);
768    }
769    return err;
770}
771
772status_t SensorService::disable(const sp<SensorEventConnection>& connection,
773        int handle)
774{
775    if (mInitCheck != NO_ERROR)
776        return mInitCheck;
777
778    Mutex::Autolock _l(mLock);
779    status_t err = cleanupWithoutDisableLocked(connection, handle);
780    if (err == NO_ERROR) {
781        SensorInterface* sensor = mSensorMap.valueFor(handle);
782        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
783    }
784    return err;
785}
786
787status_t SensorService::cleanupWithoutDisable(
788        const sp<SensorEventConnection>& connection, int handle) {
789    Mutex::Autolock _l(mLock);
790    return cleanupWithoutDisableLocked(connection, handle);
791}
792
793status_t SensorService::cleanupWithoutDisableLocked(
794        const sp<SensorEventConnection>& connection, int handle) {
795    SensorRecord* rec = mActiveSensors.valueFor(handle);
796    if (rec) {
797        // see if this connection becomes inactive
798        if (connection->removeSensor(handle)) {
799            BatteryService::disableSensor(connection->getUid(), handle);
800        }
801        if (connection->hasAnySensor() == false) {
802            mActiveConnections.remove(connection);
803        }
804        // see if this sensor becomes inactive
805        if (rec->removeConnection(connection)) {
806            mActiveSensors.removeItem(handle);
807            mActiveVirtualSensors.removeItem(handle);
808            delete rec;
809        }
810        return NO_ERROR;
811    }
812    return BAD_VALUE;
813}
814
815status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
816        int handle, nsecs_t ns)
817{
818    if (mInitCheck != NO_ERROR)
819        return mInitCheck;
820
821    SensorInterface* sensor = mSensorMap.valueFor(handle);
822    if (!sensor)
823        return BAD_VALUE;
824
825    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
826        return BAD_VALUE;
827    }
828
829    if (ns < 0)
830        return BAD_VALUE;
831
832    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
833    if (ns < minDelayNs) {
834        ns = minDelayNs;
835    }
836
837    return sensor->setDelay(connection.get(), handle, ns);
838}
839
840status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
841    if (mInitCheck != NO_ERROR) return mInitCheck;
842    SensorDevice& dev(SensorDevice::getInstance());
843    const int halVersion = dev.getHalDeviceVersion();
844    status_t err(NO_ERROR);
845    Mutex::Autolock _l(mLock);
846    // Loop through all sensors for this connection and call flush on each of them.
847    for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
848        const int handle = connection->mSensorInfo.keyAt(i);
849        SensorInterface* sensor = mSensorMap.valueFor(handle);
850        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
851            ALOGE("flush called on a one-shot sensor");
852            err = INVALID_OPERATION;
853            continue;
854        }
855        SensorEventConnection::FlushInfo& flushInfo = connection->mSensorInfo.editValueFor(handle);
856        if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
857            // For older devices just increment pending flush count which will send a trivial
858            // flush complete event.
859            flushInfo.mPendingFlushEventsToSend++;
860        } else {
861            status_t err_flush = sensor->flush(connection.get(), handle);
862            if (err_flush == NO_ERROR) {
863                SensorRecord* rec = mActiveSensors.valueFor(handle);
864                if (rec != NULL) rec->addPendingFlushConnection(connection);
865            }
866            err = (err_flush != NO_ERROR) ? err_flush : err;
867        }
868    }
869    return err;
870}
871
872bool SensorService::canAccessSensor(const Sensor& sensor) {
873    return (sensor.getRequiredPermission().isEmpty()) ||
874            PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
875}
876
877bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
878    if (canAccessSensor(sensor)) {
879        return true;
880    } else {
881        String8 errorMessage;
882        errorMessage.appendFormat(
883                "%s a sensor (%s) without holding its required permission: %s",
884                operation,
885                sensor.getName().string(),
886                sensor.getRequiredPermission().string());
887        return false;
888    }
889}
890
891void SensorService::checkWakeLockState() {
892    Mutex::Autolock _l(mLock);
893    checkWakeLockStateLocked();
894}
895
896void SensorService::checkWakeLockStateLocked() {
897    if (!mWakeLockAcquired) {
898        return;
899    }
900    bool releaseLock = true;
901    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
902        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
903        if (connection != 0) {
904            if (connection->needsWakeLock()) {
905                releaseLock = false;
906                break;
907            }
908        }
909    }
910    if (releaseLock) {
911        ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
912        release_wake_lock(WAKE_LOCK_NAME);
913        mWakeLockAcquired = false;
914    }
915}
916
917// ---------------------------------------------------------------------------
918SensorService::SensorRecord::SensorRecord(
919        const sp<SensorEventConnection>& connection)
920{
921    mConnections.add(connection);
922}
923
924bool SensorService::SensorRecord::addConnection(
925        const sp<SensorEventConnection>& connection)
926{
927    if (mConnections.indexOf(connection) < 0) {
928        mConnections.add(connection);
929        return true;
930    }
931    return false;
932}
933
934bool SensorService::SensorRecord::removeConnection(
935        const wp<SensorEventConnection>& connection)
936{
937    ssize_t index = mConnections.indexOf(connection);
938    if (index >= 0) {
939        mConnections.removeItemsAt(index, 1);
940    }
941    // Remove this connections from the queue of flush() calls made on this sensor.
942    for (Vector< wp<SensorEventConnection> >::iterator it =
943            mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
944        if (it->unsafe_get() == connection.unsafe_get()) {
945            it = mPendingFlushConnections.erase(it);
946        } else {
947            ++it;
948        }
949    }
950    return mConnections.size() ? false : true;
951}
952
953void SensorService::SensorRecord::addPendingFlushConnection(
954        const sp<SensorEventConnection>& connection) {
955    mPendingFlushConnections.add(connection);
956}
957
958void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
959    if (mPendingFlushConnections.size() > 0) {
960        mPendingFlushConnections.removeAt(0);
961    }
962}
963
964SensorService::SensorEventConnection *
965SensorService::SensorRecord::getFirstPendingFlushConnection() {
966   if (mPendingFlushConnections.size() > 0) {
967        return mPendingFlushConnections[0].unsafe_get();
968    }
969    return NULL;
970}
971
972// ---------------------------------------------------------------------------
973
974SensorService::SensorEventConnection::SensorEventConnection(
975        const sp<SensorService>& service, uid_t uid)
976    : mService(service), mUid(uid), mWakeLockRefCount(0), mEventCache(NULL), mCacheSize(0),
977      mMaxCacheSize(0) {
978    const SensorDevice& device(SensorDevice::getInstance());
979    mChannel = new BitTube(mService->mSocketBufferSize);
980#if DEBUG_CONNECTIONS
981    mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
982    mTotalAcksNeeded = mTotalAcksReceived = 0;
983#endif
984}
985
986SensorService::SensorEventConnection::~SensorEventConnection() {
987    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
988    if (mEventCache != NULL) {
989        delete mEventCache;
990    }
991    mService->cleanupConnection(this);
992}
993
994void SensorService::SensorEventConnection::onFirstRef() {
995    LooperCallback::onFirstRef();
996}
997
998bool SensorService::SensorEventConnection::needsWakeLock() {
999    Mutex::Autolock _l(mConnectionLock);
1000    return mWakeLockRefCount > 0;
1001}
1002
1003void SensorService::SensorEventConnection::dump(String8& result) {
1004    Mutex::Autolock _l(mConnectionLock);
1005    result.appendFormat("\t WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1006            mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
1007    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1008        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
1009        result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
1010                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
1011                            mSensorInfo.keyAt(i),
1012                            flushInfo.mFirstFlushPending ? "First flush pending" :
1013                                                           "active",
1014                            flushInfo.mPendingFlushEventsToSend);
1015    }
1016#if DEBUG_CONNECTIONS
1017    result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1018            " total_acks_needed %d | total_acks_recvd %d\n",
1019            mEventsReceived,
1020            mEventsSent,
1021            mEventsSentFromCache,
1022            mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1023            mTotalAcksNeeded,
1024            mTotalAcksReceived);
1025#endif
1026}
1027
1028bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
1029    Mutex::Autolock _l(mConnectionLock);
1030    if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1031        return false;
1032    }
1033    if (mSensorInfo.indexOfKey(handle) < 0) {
1034        mSensorInfo.add(handle, FlushInfo());
1035        return true;
1036    }
1037    return false;
1038}
1039
1040bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
1041    Mutex::Autolock _l(mConnectionLock);
1042    if (mSensorInfo.removeItem(handle) >= 0) {
1043        return true;
1044    }
1045    return false;
1046}
1047
1048bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
1049    Mutex::Autolock _l(mConnectionLock);
1050    return mSensorInfo.indexOfKey(handle) >= 0;
1051}
1052
1053bool SensorService::SensorEventConnection::hasAnySensor() const {
1054    Mutex::Autolock _l(mConnectionLock);
1055    return mSensorInfo.size() ? true : false;
1056}
1057
1058bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1059    Mutex::Autolock _l(mConnectionLock);
1060    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1061        const int handle = mSensorInfo.keyAt(i);
1062        if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1063            return true;
1064        }
1065    }
1066    return false;
1067}
1068
1069void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1070                                bool value) {
1071    Mutex::Autolock _l(mConnectionLock);
1072    ssize_t index = mSensorInfo.indexOfKey(handle);
1073    if (index >= 0) {
1074        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1075        flushInfo.mFirstFlushPending = value;
1076    }
1077}
1078
1079status_t SensorService::SensorEventConnection::sendEvents(
1080        sensors_event_t const* buffer, size_t numEvents,
1081        sensors_event_t* scratch,
1082        SensorEventConnection const * const * mapFlushEventsToConnections) {
1083    // filter out events not for this connection
1084    size_t count = 0;
1085    Mutex::Autolock _l(mConnectionLock);
1086    if (scratch) {
1087        size_t i=0;
1088        while (i<numEvents) {
1089            int32_t sensor_handle = buffer[i].sensor;
1090            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1091                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
1092                        buffer[i].meta_data.sensor);
1093                // Setting sensor_handle to the correct sensor to ensure the sensor events per connection are
1094                // filtered correctly. buffer[i].sensor is zero for meta_data events.
1095                sensor_handle = buffer[i].meta_data.sensor;
1096            }
1097            ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
1098            // Check if this connection has registered for this sensor. If not continue to the
1099            // next sensor_event.
1100            if (index < 0) {
1101                ++i;
1102                continue;
1103            }
1104
1105            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1106            // Check if there is a pending flush_complete event for this sensor on this connection.
1107            if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1108                    this == mapFlushEventsToConnections[i]) {
1109                flushInfo.mFirstFlushPending = false;
1110                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1111                        buffer[i].meta_data.sensor);
1112                ++i;
1113                continue;
1114            }
1115
1116            // If there is a pending flush complete event for this sensor on this connection,
1117            // ignore the event and proceed to the next.
1118            if (flushInfo.mFirstFlushPending) {
1119                ++i;
1120                continue;
1121            }
1122
1123            do {
1124                // Keep copying events into the scratch buffer as long as they are regular
1125                // sensor_events are from the same sensor_handle OR they are flush_complete_events
1126                // from the same sensor_handle AND the current connection is mapped to the
1127                // corresponding flush_complete_event.
1128                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1129                    if (this == mapFlushEventsToConnections[i]) {
1130                        scratch[count++] = buffer[i];
1131                    }
1132                    ++i;
1133                } else {
1134                    // Regular sensor event, just copy it to the scratch buffer.
1135                    scratch[count++] = buffer[i++];
1136                }
1137            } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1138                                        buffer[i].type != SENSOR_TYPE_META_DATA) ||
1139                                       (buffer[i].type == SENSOR_TYPE_META_DATA  &&
1140                                        buffer[i].meta_data.sensor == sensor_handle)));
1141        }
1142    } else {
1143        scratch = const_cast<sensors_event_t *>(buffer);
1144        count = numEvents;
1145    }
1146
1147    sendPendingFlushEventsLocked();
1148    // Early return if there are no events for this connection.
1149    if (count == 0) {
1150        return status_t(NO_ERROR);
1151    }
1152
1153#if DEBUG_CONNECTIONS
1154     mEventsReceived += count;
1155#endif
1156    if (mCacheSize != 0) {
1157        // There are some events in the cache which need to be sent first. Copy this buffer to
1158        // the end of cache.
1159        if (mCacheSize + count <= mMaxCacheSize) {
1160            memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1161            mCacheSize += count;
1162        } else {
1163            // Check if any new sensors have registered on this connection which may have increased
1164            // the max cache size that is desired.
1165            if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1166                reAllocateCacheLocked(scratch, count);
1167                return status_t(NO_ERROR);
1168            }
1169            // Some events need to be dropped.
1170            int remaningCacheSize = mMaxCacheSize - mCacheSize;
1171            if (remaningCacheSize != 0) {
1172                memcpy(&mEventCache[mCacheSize], scratch,
1173                                                remaningCacheSize * sizeof(sensors_event_t));
1174            }
1175            int numEventsDropped = count - remaningCacheSize;
1176            countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1177            // Drop the first "numEventsDropped" in the cache.
1178            memmove(mEventCache, &mEventCache[numEventsDropped],
1179                    (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1180
1181            // Copy the remainingEvents in scratch buffer to the end of cache.
1182            memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1183                                            numEventsDropped * sizeof(sensors_event_t));
1184        }
1185        return status_t(NO_ERROR);
1186    }
1187
1188    int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1189    if (index_wake_up_event >= 0) {
1190        scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1191        ++mWakeLockRefCount;
1192#if DEBUG_CONNECTIONS
1193        ++mTotalAcksNeeded;
1194#endif
1195    }
1196
1197    // NOTE: ASensorEvent and sensors_event_t are the same type.
1198    ssize_t size = SensorEventQueue::write(mChannel,
1199                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
1200    if (size < 0) {
1201        // Write error, copy events to local cache.
1202        if (index_wake_up_event >= 0) {
1203            // If there was a wake_up sensor_event, reset the flag.
1204            scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1205            if (mWakeLockRefCount > 0) {
1206                --mWakeLockRefCount;
1207            }
1208#if DEBUG_CONNECTIONS
1209            --mTotalAcksNeeded;
1210#endif
1211        }
1212        if (mEventCache == NULL) {
1213            mMaxCacheSize = computeMaxCacheSizeLocked();
1214            mEventCache = new sensors_event_t[mMaxCacheSize];
1215            mCacheSize = 0;
1216        }
1217        memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1218        mCacheSize += count;
1219
1220        // Add this file descriptor to the looper to get a callback when this fd is available for
1221        // writing.
1222        mService->getLooper()->addFd(mChannel->getSendFd(), 0,
1223                ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_INPUT, this, NULL);
1224        return size;
1225    }
1226
1227#if DEBUG_CONNECTIONS
1228    if (size > 0) {
1229        mEventsSent += count;
1230    }
1231#endif
1232
1233    return size < 0 ? status_t(size) : status_t(NO_ERROR);
1234}
1235
1236void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1237                                                                 int count) {
1238    sensors_event_t *eventCache_new;
1239    const int new_cache_size = computeMaxCacheSizeLocked();
1240    // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1241    eventCache_new = new sensors_event_t[new_cache_size];
1242    memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1243    memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1244
1245    ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1246            new_cache_size);
1247
1248    delete mEventCache;
1249    mEventCache = eventCache_new;
1250    mCacheSize += count;
1251    mMaxCacheSize = new_cache_size;
1252}
1253
1254void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1255    ASensorEvent flushCompleteEvent;
1256    memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
1257    flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
1258    // Loop through all the sensors for this connection and check if there are any pending
1259    // flush complete events to be sent.
1260    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1261        FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1262        while (flushInfo.mPendingFlushEventsToSend > 0) {
1263            const int sensor_handle = mSensorInfo.keyAt(i);
1264            flushCompleteEvent.meta_data.sensor = sensor_handle;
1265            if (mService->getSensorFromHandle(sensor_handle).isWakeUpSensor()) {
1266               flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1267            }
1268            ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1269            if (size < 0) {
1270                return;
1271            }
1272            ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1273                    flushCompleteEvent.meta_data.sensor);
1274            flushInfo.mPendingFlushEventsToSend--;
1275        }
1276    }
1277}
1278
1279void SensorService::SensorEventConnection::writeToSocketFromCacheLocked() {
1280    // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1281    // half the size of the socket buffer allocated in BitTube whichever is smaller.
1282    const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1283            int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
1284    // Send pending flush complete events (if any)
1285    sendPendingFlushEventsLocked();
1286    for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
1287        const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
1288        int index_wake_up_event =
1289                  findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1290        if (index_wake_up_event >= 0) {
1291            mEventCache[index_wake_up_event + numEventsSent].flags |=
1292                    WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1293            ++mWakeLockRefCount;
1294#if DEBUG_CONNECTIONS
1295            ++mTotalAcksNeeded;
1296#endif
1297        }
1298
1299        ssize_t size = SensorEventQueue::write(mChannel,
1300                          reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
1301                          numEventsToWrite);
1302        if (size < 0) {
1303            if (index_wake_up_event >= 0) {
1304                // If there was a wake_up sensor_event, reset the flag.
1305                mEventCache[index_wake_up_event + numEventsSent].flags  &=
1306                        ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1307                if (mWakeLockRefCount > 0) {
1308                    --mWakeLockRefCount;
1309                }
1310#if DEBUG_CONNECTIONS
1311                --mTotalAcksNeeded;
1312#endif
1313            }
1314            memmove(mEventCache, &mEventCache[numEventsSent],
1315                                 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1316            ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
1317                    numEventsSent, mCacheSize);
1318            mCacheSize -= numEventsSent;
1319            return;
1320        }
1321        numEventsSent += numEventsToWrite;
1322#if DEBUG_CONNECTIONS
1323        mEventsSentFromCache += numEventsToWrite;
1324#endif
1325    }
1326    ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1327    // All events from the cache have been sent. Reset cache size to zero.
1328    mCacheSize = 0;
1329    // Poll only for ALOOPER_EVENT_INPUT(read) on the file descriptor.
1330    mService->getLooper()->addFd(mChannel->getSendFd(), 0, ALOOPER_EVENT_INPUT, this, NULL);
1331}
1332
1333void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
1334                sensors_event_t const* scratch, const int numEventsDropped) {
1335    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
1336    // Count flushComplete events in the events that are about to the dropped. These will be sent
1337    // separately before the next batch of events.
1338    for (int j = 0; j < numEventsDropped; ++j) {
1339        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1340            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1341            flushInfo.mPendingFlushEventsToSend++;
1342            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1343                     flushInfo.mPendingFlushEventsToSend);
1344        }
1345    }
1346    return;
1347}
1348
1349int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1350                       sensors_event_t const* scratch, const int count) {
1351    for (int i = 0; i < count; ++i) {
1352        if (mService->isWakeUpSensorEvent(scratch[i])) {
1353            return i;
1354        }
1355    }
1356    return -1;
1357}
1358
1359sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
1360{
1361    return mChannel;
1362}
1363
1364status_t SensorService::SensorEventConnection::enableDisable(
1365        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1366        int reservedFlags)
1367{
1368    status_t err;
1369    if (enabled) {
1370        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1371                               reservedFlags);
1372
1373    } else {
1374        err = mService->disable(this, handle);
1375    }
1376    return err;
1377}
1378
1379status_t SensorService::SensorEventConnection::setEventRate(
1380        int handle, nsecs_t samplingPeriodNs)
1381{
1382    return mService->setEventRate(this, handle, samplingPeriodNs);
1383}
1384
1385status_t  SensorService::SensorEventConnection::flush() {
1386    return  mService->flushSensor(this);
1387}
1388
1389int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* data) {
1390    if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1391        return 0;
1392    }
1393
1394    if (events & ALOOPER_EVENT_INPUT) {
1395        char buf;
1396        ssize_t ret = ::recv(fd, &buf, sizeof(buf), MSG_DONTWAIT);
1397
1398        {
1399           Mutex::Autolock _l(mConnectionLock);
1400           if (mWakeLockRefCount > 0) {
1401               --mWakeLockRefCount;
1402           }
1403#if DEBUG_CONNECTIONS
1404           ++mTotalAcksReceived;
1405#endif
1406        }
1407        // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1408        // here as checkWakeLockState() will need it.
1409        if (mWakeLockRefCount == 0) {
1410            mService->checkWakeLockState();
1411        }
1412        // continue getting callbacks.
1413        return 1;
1414    }
1415
1416    if (events & ALOOPER_EVENT_OUTPUT) {
1417        // send sensor data that is stored in mEventCache.
1418        Mutex::Autolock _l(mConnectionLock);
1419        writeToSocketFromCacheLocked();
1420    }
1421    return 1;
1422}
1423
1424int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1425    int fifoWakeUpSensors = 0;
1426    int fifoNonWakeUpSensors = 0;
1427    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1428        const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1429        if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1430            // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1431            // non wake_up sensors.
1432            if (sensor.isWakeUpSensor()) {
1433                fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1434            } else {
1435                fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1436            }
1437        } else {
1438            // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1439            if (sensor.isWakeUpSensor()) {
1440                fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1441                                          fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1442
1443            } else {
1444                fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1445                                          fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1446
1447            }
1448        }
1449   }
1450   if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1451       // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
1452       // size that is equal to that of the batch mode.
1453       // ALOGW("Write failure in non-batch mode");
1454       return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
1455   }
1456   return fifoWakeUpSensors + fifoNonWakeUpSensors;
1457}
1458
1459// ---------------------------------------------------------------------------
1460}; // namespace android
1461
1462