SensorService.cpp revision 9a844cf78f09953145200b4074d47589257a408c
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
22#include <cutils/properties.h>
23
24#include <utils/SortedVector.h>
25#include <utils/KeyedVector.h>
26#include <utils/threads.h>
27#include <utils/Atomic.h>
28#include <utils/Errors.h>
29#include <utils/RefBase.h>
30#include <utils/Singleton.h>
31#include <utils/String16.h>
32
33#include <binder/BinderService.h>
34#include <binder/IServiceManager.h>
35#include <binder/PermissionCache.h>
36
37#include <gui/ISensorServer.h>
38#include <gui/ISensorEventConnection.h>
39#include <gui/SensorEventQueue.h>
40
41#include <hardware/sensors.h>
42#include <hardware_legacy/power.h>
43
44#include "BatteryService.h"
45#include "CorrectedGyroSensor.h"
46#include "GravitySensor.h"
47#include "LinearAccelerationSensor.h"
48#include "OrientationSensor.h"
49#include "RotationVectorSensor.h"
50#include "SensorFusion.h"
51#include "SensorService.h"
52
53namespace android {
54// ---------------------------------------------------------------------------
55
56/*
57 * Notes:
58 *
59 * - what about a gyro-corrected magnetic-field sensor?
60 * - run mag sensor from time to time to force calibration
61 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
62 *
63 */
64
65const char* SensorService::WAKE_LOCK_NAME = "SensorService";
66
67SensorService::SensorService()
68    : mInitCheck(NO_INIT)
69{
70}
71
72void SensorService::onFirstRef()
73{
74    ALOGD("nuSensorService starting...");
75
76    SensorDevice& dev(SensorDevice::getInstance());
77
78    if (dev.initCheck() == NO_ERROR) {
79        sensor_t const* list;
80        ssize_t count = dev.getSensorList(&list);
81        if (count > 0) {
82            ssize_t orientationIndex = -1;
83            bool hasGyro = false;
84            uint32_t virtualSensorsNeeds =
85                    (1<<SENSOR_TYPE_GRAVITY) |
86                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
87                    (1<<SENSOR_TYPE_ROTATION_VECTOR);
88
89            mLastEventSeen.setCapacity(count);
90            for (ssize_t i=0 ; i<count ; i++) {
91                registerSensor( new HardwareSensor(list[i]) );
92                switch (list[i].type) {
93                    case SENSOR_TYPE_ORIENTATION:
94                        orientationIndex = i;
95                        break;
96                    case SENSOR_TYPE_GYROSCOPE:
97                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
98                        hasGyro = true;
99                        break;
100                    case SENSOR_TYPE_GRAVITY:
101                    case SENSOR_TYPE_LINEAR_ACCELERATION:
102                    case SENSOR_TYPE_ROTATION_VECTOR:
103                        virtualSensorsNeeds &= ~(1<<list[i].type);
104                        break;
105                }
106            }
107
108            // it's safe to instantiate the SensorFusion object here
109            // (it wants to be instantiated after h/w sensors have been
110            // registered)
111            const SensorFusion& fusion(SensorFusion::getInstance());
112
113            // build the sensor list returned to users
114            mUserSensorList = mSensorList;
115
116            if (hasGyro) {
117                Sensor aSensor;
118
119                // Add Android virtual sensors if they're not already
120                // available in the HAL
121
122                aSensor = registerVirtualSensor( new RotationVectorSensor() );
123                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
124                    mUserSensorList.add(aSensor);
125                }
126
127                aSensor = registerVirtualSensor( new GravitySensor(list, count) );
128                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
129                    mUserSensorList.add(aSensor);
130                }
131
132                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
133                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
134                    mUserSensorList.add(aSensor);
135                }
136
137                aSensor = registerVirtualSensor( new OrientationSensor() );
138                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
139                    // if we are doing our own rotation-vector, also add
140                    // the orientation sensor and remove the HAL provided one.
141                    mUserSensorList.replaceAt(aSensor, orientationIndex);
142                }
143
144                // virtual debugging sensors are not added to mUserSensorList
145                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
146                registerVirtualSensor( new GyroDriftSensor() );
147            }
148
149            // debugging sensor list
150            mUserSensorListDebug = mSensorList;
151
152            mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
153            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
154            char line[128];
155            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
156                line[sizeof(line) - 1] = '\0';
157                sscanf(line, "%zu", &mSocketBufferSize);
158                if (mSocketBufferSize > MAX_SOCKET_BUFFER_SIZE_BATCHED) {
159                    mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
160                }
161            }
162            ALOGD("Max socket buffer size %u", mSocketBufferSize);
163            if (fp) {
164                fclose(fp);
165            }
166
167            mWakeLockAcquired = false;
168            run("SensorService", PRIORITY_URGENT_DISPLAY);
169            mInitCheck = NO_ERROR;
170        }
171    }
172}
173
174Sensor SensorService::registerSensor(SensorInterface* s)
175{
176    sensors_event_t event;
177    memset(&event, 0, sizeof(event));
178
179    const Sensor sensor(s->getSensor());
180    // add to the sensor list (returned to clients)
181    mSensorList.add(sensor);
182    // add to our handle->SensorInterface mapping
183    mSensorMap.add(sensor.getHandle(), s);
184    // create an entry in the mLastEventSeen array
185    mLastEventSeen.add(sensor.getHandle(), event);
186
187    return sensor;
188}
189
190Sensor SensorService::registerVirtualSensor(SensorInterface* s)
191{
192    Sensor sensor = registerSensor(s);
193    mVirtualSensorList.add( s );
194    return sensor;
195}
196
197SensorService::~SensorService()
198{
199    for (size_t i=0 ; i<mSensorMap.size() ; i++)
200        delete mSensorMap.valueAt(i);
201}
202
203static const String16 sDump("android.permission.DUMP");
204
205status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
206{
207    String8 result;
208    if (!PermissionCache::checkCallingPermission(sDump)) {
209        result.appendFormat("Permission Denial: "
210                "can't dump SensorService from pid=%d, uid=%d\n",
211                IPCThreadState::self()->getCallingPid(),
212                IPCThreadState::self()->getCallingUid());
213    } else {
214        Mutex::Autolock _l(mLock);
215        result.append("Sensor List:\n");
216        for (size_t i=0 ; i<mSensorList.size() ; i++) {
217            const Sensor& s(mSensorList[i]);
218            const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
219            result.appendFormat(
220                    "%-48s| %-32s| %-48s| 0x%08x | \"%s\"\n\t",
221                    s.getName().string(),
222                    s.getVendor().string(),
223                    s.getStringType().string(),
224                    s.getHandle(),
225                    s.getRequiredPermission().string());
226
227            if (s.getMinDelay() > 0) {
228                result.appendFormat(
229                        "maxRate=%7.2fHz | ", 1e6f / s.getMinDelay());
230            } else {
231                result.append(s.getMinDelay() == 0
232                        ? "on-demand         | "
233                        : "one-shot          | ");
234            }
235            if (s.getFifoMaxEventCount() > 0) {
236                result.appendFormat("FifoMax=%d events | ",
237                        s.getFifoMaxEventCount());
238            } else {
239                result.append("no batching support | ");
240            }
241
242            switch (s.getType()) {
243                case SENSOR_TYPE_ROTATION_VECTOR:
244                case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
245                    result.appendFormat(
246                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
247                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]);
248                    break;
249                case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
250                case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
251                    result.appendFormat(
252                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
253                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]);
254                    break;
255                case SENSOR_TYPE_GAME_ROTATION_VECTOR:
256                    result.appendFormat(
257                            "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n",
258                            e.data[0], e.data[1], e.data[2], e.data[3]);
259                    break;
260                case SENSOR_TYPE_SIGNIFICANT_MOTION:
261                case SENSOR_TYPE_STEP_DETECTOR:
262                    result.appendFormat( "last=<%f>\n", e.data[0]);
263                    break;
264                case SENSOR_TYPE_STEP_COUNTER:
265                    result.appendFormat( "last=<%" PRIu64 ">\n", e.u64.step_counter);
266                    break;
267                default:
268                    // default to 3 values
269                    result.appendFormat(
270                            "last=<%5.1f,%5.1f,%5.1f>\n",
271                            e.data[0], e.data[1], e.data[2]);
272                    break;
273            }
274        }
275        SensorFusion::getInstance().dump(result);
276        SensorDevice::getInstance().dump(result);
277
278        result.append("Active sensors:\n");
279        for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
280            int handle = mActiveSensors.keyAt(i);
281            result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
282                    getSensorName(handle).string(),
283                    handle,
284                    mActiveSensors.valueAt(i)->getNumConnections());
285        }
286
287        result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
288        result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
289        result.appendFormat("%zd active connections\n", mActiveConnections.size());
290
291        for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
292            sp<SensorEventConnection> connection(mActiveConnections[i].promote());
293            if (connection != 0) {
294                result.appendFormat("Connection Number: %zu \n", i);
295                connection->dump(result);
296            }
297        }
298    }
299    write(fd, result.string(), result.size());
300    return NO_ERROR;
301}
302
303void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
304        sensors_event_t const* buffer, const int count) {
305    SensorInterface* sensor;
306    status_t err = NO_ERROR;
307    for (int i=0 ; i<count ; i++) {
308        int handle = buffer[i].sensor;
309        int type = buffer[i].type;
310        if (type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
311            if (connection->hasSensor(handle)) {
312                sensor = mSensorMap.valueFor(handle);
313                if (sensor != NULL) {
314                    sensor->autoDisable(connection.get(), handle);
315                }
316                cleanupWithoutDisableLocked(connection, handle);
317            }
318        }
319    }
320}
321
322bool SensorService::threadLoop()
323{
324    ALOGD("nuSensorService thread starting...");
325
326    // each virtual sensor could generate an event per "real" event, that's why we need
327    // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
328    // in practice, this is too aggressive, but guaranteed to be enough.
329    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
330    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
331
332    sensors_event_t buffer[minBufferSize];
333    sensors_event_t scratch[minBufferSize];
334    SensorDevice& device(SensorDevice::getInstance());
335    const size_t vcount = mVirtualSensorList.size();
336
337    ssize_t count;
338    const int halVersion = device.getHalDeviceVersion();
339    do {
340        count = device.poll(buffer, numEventMax);
341        if (count<0) {
342            ALOGE("sensor poll failed (%s)", strerror(-count));
343            break;
344        }
345        Mutex::Autolock _l(mLock);
346        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
347        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
348        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
349        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
350        // releasing the wakelock.
351        bool bufferHasWakeUpEvent = false;
352        for (int i = 0; i < count; i++) {
353            if (isWakeUpSensorEvent(buffer[i])) {
354                bufferHasWakeUpEvent = true;
355                break;
356            }
357        }
358
359        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
360            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
361            mWakeLockAcquired = true;
362            ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
363        }
364        recordLastValueLocked(buffer, count);
365
366        // handle virtual sensors
367        if (count && vcount) {
368            sensors_event_t const * const event = buffer;
369            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
370            if (activeVirtualSensorCount) {
371                size_t k = 0;
372                SensorFusion& fusion(SensorFusion::getInstance());
373                if (fusion.isEnabled()) {
374                    for (size_t i=0 ; i<size_t(count) ; i++) {
375                        fusion.process(event[i]);
376                    }
377                }
378                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
379                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
380                        if (count + k >= minBufferSize) {
381                            ALOGE("buffer too small to hold all events: "
382                                    "count=%u, k=%u, size=%u",
383                                    count, k, minBufferSize);
384                            break;
385                        }
386                        sensors_event_t out;
387                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
388                        if (si->process(&out, event[i])) {
389                            buffer[count + k] = out;
390                            k++;
391                        }
392                    }
393                }
394                if (k) {
395                    // record the last synthesized values
396                    recordLastValueLocked(&buffer[count], k);
397                    count += k;
398                    // sort the buffer by time-stamps
399                    sortEventBuffer(buffer, count);
400                }
401            }
402        }
403
404        // handle backward compatibility for RotationVector sensor
405        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
406            for (int i = 0; i < count; i++) {
407                if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
408                    // All the 4 components of the quaternion should be available
409                    // No heading accuracy. Set it to -1
410                    buffer[i].data[4] = -1;
411                }
412            }
413        }
414
415        // Send our events to clients. Check the state of wake lock for each client and release the
416        // lock if none of the clients need it.
417        bool needsWakeLock = false;
418        for (size_t i=0 ; i < mActiveConnections.size(); i++) {
419            sp<SensorEventConnection> connection(mActiveConnections[i].promote());
420            if (connection != 0) {
421                connection->sendEvents(buffer, count, scratch);
422                needsWakeLock |= connection->needsWakeLock();
423                // Some sensors need to be auto disabled after the trigger
424                cleanupAutoDisabledSensorLocked(connection, buffer, count);
425            }
426        }
427
428        if (mWakeLockAcquired && !needsWakeLock) {
429            release_wake_lock(WAKE_LOCK_NAME);
430            mWakeLockAcquired = false;
431            ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
432        }
433    } while (count >= 0 || Thread::exitPending());
434
435    ALOGW("Exiting SensorService::threadLoop => aborting...");
436    abort();
437    return false;
438}
439
440void SensorService::recordLastValueLocked(
441        const sensors_event_t* buffer, size_t count) {
442    const sensors_event_t* last = NULL;
443    for (size_t i = 0; i < count; i++) {
444        const sensors_event_t* event = &buffer[i];
445        if (event->type != SENSOR_TYPE_META_DATA) {
446            if (last && event->sensor != last->sensor) {
447                mLastEventSeen.editValueFor(last->sensor) = *last;
448            }
449            last = event;
450        }
451    }
452    if (last) {
453        mLastEventSeen.editValueFor(last->sensor) = *last;
454    }
455}
456
457void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
458{
459    struct compar {
460        static int cmp(void const* lhs, void const* rhs) {
461            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
462            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
463            return l->timestamp - r->timestamp;
464        }
465    };
466    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
467}
468
469String8 SensorService::getSensorName(int handle) const {
470    size_t count = mUserSensorList.size();
471    for (size_t i=0 ; i<count ; i++) {
472        const Sensor& sensor(mUserSensorList[i]);
473        if (sensor.getHandle() == handle) {
474            return sensor.getName();
475        }
476    }
477    String8 result("unknown");
478    return result;
479}
480
481bool SensorService::isVirtualSensor(int handle) const {
482    SensorInterface* sensor = mSensorMap.valueFor(handle);
483    return sensor->isVirtual();
484}
485
486bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
487    SensorInterface* sensor = mSensorMap.valueFor(event.sensor);
488    return sensor->getSensor().isWakeUpSensor();
489}
490
491Vector<Sensor> SensorService::getSensorList()
492{
493    char value[PROPERTY_VALUE_MAX];
494    property_get("debug.sensors", value, "0");
495    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
496            mUserSensorListDebug : mUserSensorList;
497    Vector<Sensor> accessibleSensorList;
498    for (size_t i = 0; i < initialSensorList.size(); i++) {
499        Sensor sensor = initialSensorList[i];
500        if (canAccessSensor(sensor)) {
501            accessibleSensorList.add(sensor);
502        } else {
503            String8 infoMessage;
504            infoMessage.appendFormat(
505                    "Skipped sensor %s because it requires permission %s",
506                    sensor.getName().string(),
507                    sensor.getRequiredPermission().string());
508            ALOGI(infoMessage.string());
509        }
510    }
511    return accessibleSensorList;
512}
513
514sp<ISensorEventConnection> SensorService::createSensorEventConnection()
515{
516    uid_t uid = IPCThreadState::self()->getCallingUid();
517    sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
518    return result;
519}
520
521void SensorService::cleanupConnection(SensorEventConnection* c)
522{
523    Mutex::Autolock _l(mLock);
524    const wp<SensorEventConnection> connection(c);
525    size_t size = mActiveSensors.size();
526    ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
527    for (size_t i=0 ; i<size ; ) {
528        int handle = mActiveSensors.keyAt(i);
529        if (c->hasSensor(handle)) {
530            ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
531            SensorInterface* sensor = mSensorMap.valueFor( handle );
532            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
533            if (sensor) {
534                sensor->activate(c, false);
535            }
536        }
537        SensorRecord* rec = mActiveSensors.valueAt(i);
538        ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
539        ALOGD_IF(DEBUG_CONNECTIONS,
540                "removing connection %p for sensor[%d].handle=0x%08x",
541                c, i, handle);
542
543        if (rec && rec->removeConnection(connection)) {
544            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
545            mActiveSensors.removeItemsAt(i, 1);
546            mActiveVirtualSensors.removeItem(handle);
547            delete rec;
548            size--;
549        } else {
550            i++;
551        }
552    }
553    mActiveConnections.remove(connection);
554    BatteryService::cleanup(c->getUid());
555    if (c->needsWakeLock()) {
556        checkWakeLockStateLocked();
557    }
558}
559
560Sensor SensorService::getSensorFromHandle(int handle) const {
561    return mSensorMap.valueFor(handle)->getSensor();
562}
563
564status_t SensorService::enable(const sp<SensorEventConnection>& connection,
565        int handle, nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags)
566{
567    if (mInitCheck != NO_ERROR)
568        return mInitCheck;
569
570    SensorInterface* sensor = mSensorMap.valueFor(handle);
571    if (sensor == NULL) {
572        return BAD_VALUE;
573    }
574
575    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
576        return BAD_VALUE;
577    }
578
579    Mutex::Autolock _l(mLock);
580    SensorRecord* rec = mActiveSensors.valueFor(handle);
581    if (rec == 0) {
582        rec = new SensorRecord(connection);
583        mActiveSensors.add(handle, rec);
584        if (sensor->isVirtual()) {
585            mActiveVirtualSensors.add(handle, sensor);
586        }
587    } else {
588        if (rec->addConnection(connection)) {
589            // this sensor is already activated, but we are adding a connection that uses it.
590            // Immediately send down the last known value of the requested sensor if it's not a
591            // "continuous" sensor.
592            if (sensor->getSensor().getMinDelay() == 0) {
593                // NOTE: The wake_up flag of this event may get set to
594                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
595                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
596                if (event.version == sizeof(sensors_event_t)) {
597                    if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
598                        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
599                        mWakeLockAcquired = true;
600                        ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
601                                                        WAKE_LOCK_NAME);
602                    }
603                    connection->sendEvents(&event, 1, NULL);
604                    if (!connection->needsWakeLock() && mWakeLockAcquired) {
605                        checkWakeLockStateLocked();
606                    }
607                }
608            }
609        }
610    }
611
612    if (connection->addSensor(handle)) {
613        BatteryService::enableSensor(connection->getUid(), handle);
614        // the sensor was added (which means it wasn't already there)
615        // so, see if this connection becomes active
616        if (mActiveConnections.indexOf(connection) < 0) {
617            mActiveConnections.add(connection);
618        }
619    } else {
620        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
621            handle, connection.get());
622    }
623
624    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
625    if (samplingPeriodNs < minDelayNs) {
626        samplingPeriodNs = minDelayNs;
627    }
628
629    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld",
630             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
631
632    status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
633                                 maxBatchReportLatencyNs);
634    if (err == NO_ERROR) {
635        connection->setFirstFlushPending(handle, true);
636        status_t err_flush = sensor->flush(connection.get(), handle);
637        // Flush may return error if the sensor is not activated or the underlying h/w sensor does
638        // not support flush.
639        if (err_flush != NO_ERROR) {
640            connection->setFirstFlushPending(handle, false);
641        }
642    }
643
644    if (err == NO_ERROR) {
645        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
646        err = sensor->activate(connection.get(), true);
647    }
648
649    if (err != NO_ERROR) {
650        // batch/activate has failed, reset our state.
651        cleanupWithoutDisableLocked(connection, handle);
652    }
653    return err;
654}
655
656status_t SensorService::disable(const sp<SensorEventConnection>& connection,
657        int handle)
658{
659    if (mInitCheck != NO_ERROR)
660        return mInitCheck;
661
662    Mutex::Autolock _l(mLock);
663    status_t err = cleanupWithoutDisableLocked(connection, handle);
664    if (err == NO_ERROR) {
665        SensorInterface* sensor = mSensorMap.valueFor(handle);
666        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
667    }
668    return err;
669}
670
671status_t SensorService::cleanupWithoutDisable(
672        const sp<SensorEventConnection>& connection, int handle) {
673    Mutex::Autolock _l(mLock);
674    return cleanupWithoutDisableLocked(connection, handle);
675}
676
677status_t SensorService::cleanupWithoutDisableLocked(
678        const sp<SensorEventConnection>& connection, int handle) {
679    SensorRecord* rec = mActiveSensors.valueFor(handle);
680    if (rec) {
681        // see if this connection becomes inactive
682        if (connection->removeSensor(handle)) {
683            BatteryService::disableSensor(connection->getUid(), handle);
684        }
685        if (connection->hasAnySensor() == false) {
686            mActiveConnections.remove(connection);
687        }
688        // see if this sensor becomes inactive
689        if (rec->removeConnection(connection)) {
690            mActiveSensors.removeItem(handle);
691            mActiveVirtualSensors.removeItem(handle);
692            delete rec;
693        }
694        return NO_ERROR;
695    }
696    return BAD_VALUE;
697}
698
699status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
700        int handle, nsecs_t ns)
701{
702    if (mInitCheck != NO_ERROR)
703        return mInitCheck;
704
705    SensorInterface* sensor = mSensorMap.valueFor(handle);
706    if (!sensor)
707        return BAD_VALUE;
708
709    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
710        return BAD_VALUE;
711    }
712
713    if (ns < 0)
714        return BAD_VALUE;
715
716    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
717    if (ns < minDelayNs) {
718        ns = minDelayNs;
719    }
720
721    return sensor->setDelay(connection.get(), handle, ns);
722}
723
724status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
725                                    int handle) {
726    if (mInitCheck != NO_ERROR) return mInitCheck;
727    SensorInterface* sensor = mSensorMap.valueFor(handle);
728    if (sensor == NULL) {
729        return BAD_VALUE;
730    }
731
732    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried flushing")) {
733        return BAD_VALUE;
734    }
735
736    if (sensor->getSensor().getType() == SENSOR_TYPE_SIGNIFICANT_MOTION) {
737        ALOGE("flush called on Significant Motion sensor");
738        return INVALID_OPERATION;
739    }
740    return sensor->flush(connection.get(), handle);
741}
742
743
744bool SensorService::canAccessSensor(const Sensor& sensor) {
745    String16 permissionString(sensor.getRequiredPermission());
746    return permissionString.size() == 0 ||
747            PermissionCache::checkCallingPermission(permissionString);
748}
749
750bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
751    if (canAccessSensor(sensor)) {
752        return true;
753    } else {
754        String8 errorMessage;
755        errorMessage.appendFormat(
756                "%s a sensor (%s) without holding its required permission: %s",
757                operation,
758                sensor.getName().string(),
759                sensor.getRequiredPermission().string());
760        return false;
761    }
762}
763
764void SensorService::checkWakeLockState() {
765    Mutex::Autolock _l(mLock);
766    checkWakeLockStateLocked();
767}
768
769void SensorService::checkWakeLockStateLocked() {
770    if (!mWakeLockAcquired) {
771        return;
772    }
773    bool releaseLock = true;
774    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
775        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
776        if (connection != 0) {
777            if (connection->needsWakeLock()) {
778                releaseLock = false;
779                break;
780            }
781        }
782    }
783    if (releaseLock) {
784        ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
785        release_wake_lock(WAKE_LOCK_NAME);
786        mWakeLockAcquired = false;
787    }
788}
789// ---------------------------------------------------------------------------
790
791SensorService::SensorRecord::SensorRecord(
792        const sp<SensorEventConnection>& connection)
793{
794    mConnections.add(connection);
795}
796
797bool SensorService::SensorRecord::addConnection(
798        const sp<SensorEventConnection>& connection)
799{
800    if (mConnections.indexOf(connection) < 0) {
801        mConnections.add(connection);
802        return true;
803    }
804    return false;
805}
806
807bool SensorService::SensorRecord::removeConnection(
808        const wp<SensorEventConnection>& connection)
809{
810    ssize_t index = mConnections.indexOf(connection);
811    if (index >= 0) {
812        mConnections.removeItemsAt(index, 1);
813    }
814    return mConnections.size() ? false : true;
815}
816
817// ---------------------------------------------------------------------------
818
819SensorService::SensorEventConnection::SensorEventConnection(
820        const sp<SensorService>& service, uid_t uid)
821    : mService(service), mUid(uid), mWakeLockRefCount(0)
822{
823    const SensorDevice& device(SensorDevice::getInstance());
824    if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
825        // Increase socket buffer size to 1MB for batching capabilities.
826        mChannel = new BitTube(service->mSocketBufferSize);
827    } else {
828        mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED);
829    }
830}
831
832SensorService::SensorEventConnection::~SensorEventConnection()
833{
834    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
835    mService->cleanupConnection(this);
836}
837
838void SensorService::SensorEventConnection::onFirstRef()
839{
840}
841
842bool SensorService::SensorEventConnection::needsWakeLock() {
843    Mutex::Autolock _l(mConnectionLock);
844    return mWakeLockRefCount > 0;
845}
846
847void SensorService::SensorEventConnection::dump(String8& result) {
848    Mutex::Autolock _l(mConnectionLock);
849    result.appendFormat("%d WakeLockRefCount\n", mWakeLockRefCount);
850    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
851        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
852        result.appendFormat("\t %s | status: %s | pending flush events %d | uid %d\n",
853                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
854                            flushInfo.mFirstFlushPending ? "First flush pending" :
855                                                           "active",
856                            flushInfo.mPendingFlushEventsToSend,
857                            mUid);
858    }
859}
860
861bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
862    Mutex::Autolock _l(mConnectionLock);
863    if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
864        return false;
865    }
866    if (mSensorInfo.indexOfKey(handle) < 0) {
867        mSensorInfo.add(handle, FlushInfo());
868        return true;
869    }
870    return false;
871}
872
873bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
874    Mutex::Autolock _l(mConnectionLock);
875    if (mSensorInfo.removeItem(handle) >= 0) {
876        return true;
877    }
878    return false;
879}
880
881bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
882    Mutex::Autolock _l(mConnectionLock);
883    return mSensorInfo.indexOfKey(handle) >= 0;
884}
885
886bool SensorService::SensorEventConnection::hasAnySensor() const {
887    Mutex::Autolock _l(mConnectionLock);
888    return mSensorInfo.size() ? true : false;
889}
890
891void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
892                                bool value) {
893    Mutex::Autolock _l(mConnectionLock);
894    ssize_t index = mSensorInfo.indexOfKey(handle);
895    if (index >= 0) {
896        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
897        flushInfo.mFirstFlushPending = value;
898    }
899}
900
901status_t SensorService::SensorEventConnection::sendEvents(
902        sensors_event_t const* buffer, size_t numEvents,
903        sensors_event_t* scratch)
904{
905    // filter out events not for this connection
906    size_t count = 0;
907    Mutex::Autolock _l(mConnectionLock);
908    if (scratch) {
909        size_t i=0;
910        while (i<numEvents) {
911            int32_t curr = buffer[i].sensor;
912            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
913                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
914                         buffer[i].meta_data.sensor);
915                // Setting curr to the correct sensor to ensure the sensor events per connection are
916                // filtered correctly. buffer[i].sensor is zero for meta_data events.
917                curr = buffer[i].meta_data.sensor;
918            }
919            ssize_t index = mSensorInfo.indexOfKey(curr);
920            if (index >= 0 && mSensorInfo[index].mFirstFlushPending == true &&
921                buffer[i].type == SENSOR_TYPE_META_DATA) {
922                // This is the first flush before activate is called. Events can now be sent for
923                // this sensor on this connection.
924                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
925                         buffer[i].meta_data.sensor);
926                mSensorInfo.editValueAt(index).mFirstFlushPending = false;
927            }
928            if (index >= 0 && mSensorInfo[index].mFirstFlushPending == false)  {
929                do {
930                    scratch[count++] = buffer[i++];
931                } while ((i<numEvents) && ((buffer[i].sensor == curr) ||
932                         (buffer[i].type == SENSOR_TYPE_META_DATA  &&
933                          buffer[i].meta_data.sensor == curr)));
934            } else {
935                i++;
936            }
937        }
938    } else {
939        scratch = const_cast<sensors_event_t *>(buffer);
940        count = numEvents;
941    }
942
943    // Send pending flush events (if any) before sending events from the cache.
944    {
945        ASensorEvent flushCompleteEvent;
946        flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
947        flushCompleteEvent.sensor = 0;
948        // Loop through all the sensors for this connection and check if there are any pending
949        // flush complete events to be sent.
950        for (size_t i = 0; i < mSensorInfo.size(); ++i) {
951            FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
952            while (flushInfo.mPendingFlushEventsToSend > 0) {
953                flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
954                ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
955                if (size < 0) {
956                    // ALOGW("dropping %d events on the floor", count);
957                    countFlushCompleteEventsLocked(scratch, count);
958                    return size;
959                }
960                ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
961                         flushCompleteEvent.meta_data.sensor);
962                flushInfo.mPendingFlushEventsToSend--;
963            }
964        }
965    }
966
967    // Early return if there are no events for this connection.
968    if (count == 0) {
969        return status_t(NO_ERROR);
970    }
971
972    int numWakeUpSensorEvents = countWakeUpSensorEventsLocked(scratch, count);
973    // NOTE: ASensorEvent and sensors_event_t are the same type
974    ssize_t size = SensorEventQueue::write(mChannel,
975            reinterpret_cast<ASensorEvent const*>(scratch), count);
976    if (size == -EAGAIN) {
977        // the destination doesn't accept events anymore, it's probably
978        // full. For now, we just drop the events on the floor.
979        // ALOGW("dropping %d events on the floor", count);
980        countFlushCompleteEventsLocked(scratch, count);
981        mWakeLockRefCount -= numWakeUpSensorEvents;
982        return size;
983    }
984    return size < 0 ? status_t(size) : status_t(NO_ERROR);
985}
986
987void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
988                sensors_event_t* scratch, const int numEventsDropped) {
989    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
990    // Count flushComplete events in the events that are about to the dropped. These will be sent
991    // separately before the next batch of events.
992    for (int j = 0; j < numEventsDropped; ++j) {
993        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
994            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
995            flushInfo.mPendingFlushEventsToSend++;
996            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
997                     flushInfo.mPendingFlushEventsToSend);
998        }
999    }
1000    return;
1001}
1002
1003int SensorService::SensorEventConnection::countWakeUpSensorEventsLocked(
1004                       sensors_event_t* scratch, const int count) {
1005    for (int i = 0; i < count; ++i) {
1006        if (mService->isWakeUpSensorEvent(scratch[i])) {
1007            scratch[i].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1008            ++mWakeLockRefCount;
1009            return 1;
1010        }
1011    }
1012    return 0;
1013}
1014
1015sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
1016{
1017    return mChannel;
1018}
1019
1020status_t SensorService::SensorEventConnection::enableDisable(
1021        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1022        int reservedFlags)
1023{
1024    status_t err;
1025    if (enabled) {
1026        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1027                               reservedFlags);
1028    } else {
1029        err = mService->disable(this, handle);
1030    }
1031    return err;
1032}
1033
1034status_t SensorService::SensorEventConnection::setEventRate(
1035        int handle, nsecs_t samplingPeriodNs)
1036{
1037    return mService->setEventRate(this, handle, samplingPeriodNs);
1038}
1039
1040status_t  SensorService::SensorEventConnection::flush() {
1041    SensorDevice& dev(SensorDevice::getInstance());
1042    const int halVersion = dev.getHalDeviceVersion();
1043    Mutex::Autolock _l(mConnectionLock);
1044    status_t err(NO_ERROR);
1045    // Loop through all sensors for this connection and call flush on each of them.
1046    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1047        const int handle = mSensorInfo.keyAt(i);
1048        if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
1049            // For older devices just increment pending flush count which will send a trivial
1050            // flush complete event.
1051            FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
1052            flushInfo.mPendingFlushEventsToSend++;
1053        } else {
1054            status_t err_flush = mService->flushSensor(this, handle);
1055            if (err_flush != NO_ERROR) {
1056                ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
1057            }
1058            err = (err_flush != NO_ERROR) ? err_flush : err;
1059        }
1060    }
1061    return err;
1062}
1063
1064void SensorService::SensorEventConnection::decreaseWakeLockRefCount() {
1065    {
1066        Mutex::Autolock _l(mConnectionLock);
1067        --mWakeLockRefCount;
1068    }
1069    // Release the lock before calling checkWakeLockState which also needs the same connectionLock.
1070    if (mWakeLockRefCount == 0) {
1071        mService->checkWakeLockState();
1072    }
1073}
1074
1075// ---------------------------------------------------------------------------
1076}; // namespace android
1077
1078