SensorService.cpp revision 33458f72e17be8e71f50e1f8843f7821d90934f5
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            run("SensorService", PRIORITY_URGENT_DISPLAY);
168            mInitCheck = NO_ERROR;
169        }
170    }
171}
172
173Sensor SensorService::registerSensor(SensorInterface* s)
174{
175    sensors_event_t event;
176    memset(&event, 0, sizeof(event));
177
178    const Sensor sensor(s->getSensor());
179    // add to the sensor list (returned to clients)
180    mSensorList.add(sensor);
181    // add to our handle->SensorInterface mapping
182    mSensorMap.add(sensor.getHandle(), s);
183    // create an entry in the mLastEventSeen array
184    mLastEventSeen.add(sensor.getHandle(), event);
185
186    return sensor;
187}
188
189Sensor SensorService::registerVirtualSensor(SensorInterface* s)
190{
191    Sensor sensor = registerSensor(s);
192    mVirtualSensorList.add( s );
193    return sensor;
194}
195
196SensorService::~SensorService()
197{
198    for (size_t i=0 ; i<mSensorMap.size() ; i++)
199        delete mSensorMap.valueAt(i);
200}
201
202static const String16 sDump("android.permission.DUMP");
203
204status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
205{
206    String8 result;
207    if (!PermissionCache::checkCallingPermission(sDump)) {
208        result.appendFormat("Permission Denial: "
209                "can't dump SensorService from pid=%d, uid=%d\n",
210                IPCThreadState::self()->getCallingPid(),
211                IPCThreadState::self()->getCallingUid());
212    } else {
213        Mutex::Autolock _l(mLock);
214        result.append("Sensor List:\n");
215        for (size_t i=0 ; i<mSensorList.size() ; i++) {
216            const Sensor& s(mSensorList[i]);
217            const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
218            result.appendFormat(
219                    "%-48s| %-32s| %-48s| 0x%08x | \"%s\"\n\t",
220                    s.getName().string(),
221                    s.getVendor().string(),
222                    s.getStringType().string(),
223                    s.getHandle(),
224                    s.getRequiredPermission().string());
225
226            if (s.getMinDelay() > 0) {
227                result.appendFormat(
228                        "maxRate=%7.2fHz | ", 1e6f / s.getMinDelay());
229            } else {
230                result.append(s.getMinDelay() == 0
231                        ? "on-demand         | "
232                        : "one-shot          | ");
233            }
234            if (s.getFifoMaxEventCount() > 0) {
235                result.appendFormat("FifoMax=%d events | ",
236                        s.getFifoMaxEventCount());
237            } else {
238                result.append("no batching support | ");
239            }
240
241            switch (s.getType()) {
242                case SENSOR_TYPE_ROTATION_VECTOR:
243                case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
244                    result.appendFormat(
245                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
246                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]);
247                    break;
248                case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
249                case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
250                    result.appendFormat(
251                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
252                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]);
253                    break;
254                case SENSOR_TYPE_GAME_ROTATION_VECTOR:
255                    result.appendFormat(
256                            "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n",
257                            e.data[0], e.data[1], e.data[2], e.data[3]);
258                    break;
259                case SENSOR_TYPE_SIGNIFICANT_MOTION:
260                case SENSOR_TYPE_STEP_DETECTOR:
261                    result.appendFormat( "last=<%f>\n", e.data[0]);
262                    break;
263                case SENSOR_TYPE_STEP_COUNTER:
264                    result.appendFormat( "last=<%" PRIu64 ">\n", e.u64.step_counter);
265                    break;
266                default:
267                    // default to 3 values
268                    result.appendFormat(
269                            "last=<%5.1f,%5.1f,%5.1f>\n",
270                            e.data[0], e.data[1], e.data[2]);
271                    break;
272            }
273        }
274        SensorFusion::getInstance().dump(result);
275        SensorDevice::getInstance().dump(result);
276
277        result.append("Active sensors:\n");
278        for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
279            int handle = mActiveSensors.keyAt(i);
280            result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
281                    getSensorName(handle).string(),
282                    handle,
283                    mActiveSensors.valueAt(i)->getNumConnections());
284        }
285
286        result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
287        result.appendFormat("%zd active connections\n", mActiveConnections.size());
288
289        for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
290            sp<SensorEventConnection> connection(mActiveConnections[i].promote());
291            if (connection != 0) {
292                result.appendFormat("Connection Number: %zu \n", i);
293                connection->dump(result);
294            }
295        }
296    }
297    write(fd, result.string(), result.size());
298    return NO_ERROR;
299}
300
301void SensorService::cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection,
302        sensors_event_t const* buffer, const int count) {
303    SensorInterface* sensor;
304    status_t err = NO_ERROR;
305    for (int i=0 ; i<count ; i++) {
306        int handle = buffer[i].sensor;
307        int type = buffer[i].type;
308        if (type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
309            if (connection->hasSensor(handle)) {
310                sensor = mSensorMap.valueFor(handle);
311                if (sensor != NULL) {
312                    sensor->autoDisable(connection.get(), handle);
313                }
314                cleanupWithoutDisable(connection, handle);
315            }
316        }
317    }
318}
319
320bool SensorService::threadLoop()
321{
322    ALOGD("nuSensorService thread starting...");
323
324    // each virtual sensor could generate an event per "real" event, that's why we need
325    // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
326    // in practice, this is too aggressive, but guaranteed to be enough.
327    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
328    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
329
330    sensors_event_t buffer[minBufferSize];
331    sensors_event_t scratch[minBufferSize];
332    SensorDevice& device(SensorDevice::getInstance());
333    const size_t vcount = mVirtualSensorList.size();
334
335    ssize_t count;
336    bool wakeLockAcquired = false;
337    const int halVersion = device.getHalDeviceVersion();
338    do {
339        count = device.poll(buffer, numEventMax);
340        if (count<0) {
341            ALOGE("sensor poll failed (%s)", strerror(-count));
342            break;
343        }
344
345        // Poll has returned. Hold a wakelock.
346        // Todo(): add a flag to the sensors definitions to indicate
347        // the sensors which can wake up the AP
348        for (int i = 0; i < count; i++) {
349            if (buffer[i].type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
350                 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
351                 wakeLockAcquired = true;
352                 break;
353            }
354        }
355
356        recordLastValue(buffer, count);
357
358        // handle virtual sensors
359        if (count && vcount) {
360            sensors_event_t const * const event = buffer;
361            const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
362                    getActiveVirtualSensors());
363            const size_t activeVirtualSensorCount = virtualSensors.size();
364            if (activeVirtualSensorCount) {
365                size_t k = 0;
366                SensorFusion& fusion(SensorFusion::getInstance());
367                if (fusion.isEnabled()) {
368                    for (size_t i=0 ; i<size_t(count) ; i++) {
369                        fusion.process(event[i]);
370                    }
371                }
372                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
373                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
374                        if (count + k >= minBufferSize) {
375                            ALOGE("buffer too small to hold all events: "
376                                    "count=%u, k=%u, size=%u",
377                                    count, k, minBufferSize);
378                            break;
379                        }
380                        sensors_event_t out;
381                        SensorInterface* si = virtualSensors.valueAt(j);
382                        if (si->process(&out, event[i])) {
383                            buffer[count + k] = out;
384                            k++;
385                        }
386                    }
387                }
388                if (k) {
389                    // record the last synthesized values
390                    recordLastValue(&buffer[count], k);
391                    count += k;
392                    // sort the buffer by time-stamps
393                    sortEventBuffer(buffer, count);
394                }
395            }
396        }
397
398        // handle backward compatibility for RotationVector sensor
399        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
400            for (int i = 0; i < count; i++) {
401                if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
402                    // All the 4 components of the quaternion should be available
403                    // No heading accuracy. Set it to -1
404                    buffer[i].data[4] = -1;
405                }
406            }
407        }
408
409        // send our events to clients...
410        const SortedVector< wp<SensorEventConnection> > activeConnections(
411                getActiveConnections());
412        size_t numConnections = activeConnections.size();
413        for (size_t i=0 ; i<numConnections ; i++) {
414            sp<SensorEventConnection> connection(
415                    activeConnections[i].promote());
416            if (connection != 0) {
417                connection->sendEvents(buffer, count, scratch);
418                // Some sensors need to be auto disabled after the trigger
419                cleanupAutoDisabledSensor(connection, buffer, count);
420            }
421        }
422
423        // We have read the data, upper layers should hold the wakelock.
424        if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME);
425    } while (count >= 0 || Thread::exitPending());
426
427    ALOGW("Exiting SensorService::threadLoop => aborting...");
428    abort();
429    return false;
430}
431
432void SensorService::recordLastValue(
433        const sensors_event_t* buffer, size_t count) {
434    Mutex::Autolock _l(mLock);
435    const sensors_event_t* last = NULL;
436    for (size_t i = 0; i < count; i++) {
437        const sensors_event_t* event = &buffer[i];
438        if (event->type != SENSOR_TYPE_META_DATA) {
439            if (last && event->sensor != last->sensor) {
440                mLastEventSeen.editValueFor(last->sensor) = *last;
441            }
442            last = event;
443        }
444    }
445    if (last) {
446        mLastEventSeen.editValueFor(last->sensor) = *last;
447    }
448}
449
450void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
451{
452    struct compar {
453        static int cmp(void const* lhs, void const* rhs) {
454            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
455            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
456            return l->timestamp - r->timestamp;
457        }
458    };
459    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
460}
461
462SortedVector< wp<SensorService::SensorEventConnection> >
463SensorService::getActiveConnections() const
464{
465    Mutex::Autolock _l(mLock);
466    return mActiveConnections;
467}
468
469DefaultKeyedVector<int, SensorInterface*>
470SensorService::getActiveVirtualSensors() const
471{
472    Mutex::Autolock _l(mLock);
473    return mActiveVirtualSensors;
474}
475
476String8 SensorService::getSensorName(int handle) const {
477    size_t count = mUserSensorList.size();
478    for (size_t i=0 ; i<count ; i++) {
479        const Sensor& sensor(mUserSensorList[i]);
480        if (sensor.getHandle() == handle) {
481            return sensor.getName();
482        }
483    }
484    String8 result("unknown");
485    return result;
486}
487
488bool SensorService::isVirtualSensor(int handle) const {
489    SensorInterface* sensor = mSensorMap.valueFor(handle);
490    return sensor->isVirtual();
491}
492
493Vector<Sensor> SensorService::getSensorList()
494{
495    char value[PROPERTY_VALUE_MAX];
496    property_get("debug.sensors", value, "0");
497    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
498            mUserSensorListDebug : mUserSensorList;
499    Vector<Sensor> accessibleSensorList;
500    for (size_t i = 0; i < initialSensorList.size(); i++) {
501        Sensor sensor = initialSensorList[i];
502        if (canAccessSensor(sensor)) {
503            accessibleSensorList.add(sensor);
504        } else {
505            String8 infoMessage;
506            infoMessage.appendFormat(
507                    "Skipped sensor %s because it requires permission %s",
508                    sensor.getName().string(),
509                    sensor.getRequiredPermission().string());
510            ALOGI(infoMessage.string());
511        }
512    }
513    return accessibleSensorList;
514}
515
516sp<ISensorEventConnection> SensorService::createSensorEventConnection()
517{
518    uid_t uid = IPCThreadState::self()->getCallingUid();
519    sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
520    return result;
521}
522
523void SensorService::cleanupConnection(SensorEventConnection* c)
524{
525    Mutex::Autolock _l(mLock);
526    const wp<SensorEventConnection> connection(c);
527    size_t size = mActiveSensors.size();
528    ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
529    for (size_t i=0 ; i<size ; ) {
530        int handle = mActiveSensors.keyAt(i);
531        if (c->hasSensor(handle)) {
532            ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
533            SensorInterface* sensor = mSensorMap.valueFor( handle );
534            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
535            if (sensor) {
536                sensor->activate(c, false);
537            }
538        }
539        SensorRecord* rec = mActiveSensors.valueAt(i);
540        ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
541        ALOGD_IF(DEBUG_CONNECTIONS,
542                "removing connection %p for sensor[%d].handle=0x%08x",
543                c, i, handle);
544
545        if (rec && rec->removeConnection(connection)) {
546            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
547            mActiveSensors.removeItemsAt(i, 1);
548            mActiveVirtualSensors.removeItem(handle);
549            delete rec;
550            size--;
551        } else {
552            i++;
553        }
554    }
555    mActiveConnections.remove(connection);
556    BatteryService::cleanup(c->getUid());
557}
558
559Sensor SensorService::getSensorFromHandle(int handle) const {
560    return mSensorMap.valueFor(handle)->getSensor();
561}
562
563status_t SensorService::enable(const sp<SensorEventConnection>& connection,
564        int handle, nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags)
565{
566    if (mInitCheck != NO_ERROR)
567        return mInitCheck;
568
569    SensorInterface* sensor = mSensorMap.valueFor(handle);
570    if (sensor == NULL) {
571        return BAD_VALUE;
572    }
573
574    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
575        return BAD_VALUE;
576    }
577
578    Mutex::Autolock _l(mLock);
579    SensorRecord* rec = mActiveSensors.valueFor(handle);
580    if (rec == 0) {
581        rec = new SensorRecord(connection);
582        mActiveSensors.add(handle, rec);
583        if (sensor->isVirtual()) {
584            mActiveVirtualSensors.add(handle, sensor);
585        }
586    } else {
587        if (rec->addConnection(connection)) {
588            // this sensor is already activated, but we are adding a
589            // connection that uses it. Immediately send down the last
590            // known value of the requested sensor if it's not a
591            // "continuous" sensor.
592            if (sensor->getSensor().getMinDelay() == 0) {
593                sensors_event_t scratch;
594                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
595                if (event.version == sizeof(sensors_event_t)) {
596                    connection->sendEvents(&event, 1);
597                }
598            }
599        }
600    }
601
602    if (connection->addSensor(handle)) {
603        BatteryService::enableSensor(connection->getUid(), handle);
604        // the sensor was added (which means it wasn't already there)
605        // so, see if this connection becomes active
606        if (mActiveConnections.indexOf(connection) < 0) {
607            mActiveConnections.add(connection);
608        }
609    } else {
610        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
611            handle, connection.get());
612    }
613
614    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
615    if (samplingPeriodNs < minDelayNs) {
616        samplingPeriodNs = minDelayNs;
617    }
618
619    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld",
620             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
621
622    status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
623                                 maxBatchReportLatencyNs);
624    if (err == NO_ERROR) {
625        connection->setFirstFlushPending(handle, true);
626        status_t err_flush = sensor->flush(connection.get(), handle);
627        // Flush may return error if the sensor is not activated or the underlying h/w sensor does
628        // not support flush.
629        if (err_flush != NO_ERROR) {
630            connection->setFirstFlushPending(handle, false);
631        }
632    }
633
634    if (err == NO_ERROR) {
635        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
636        err = sensor->activate(connection.get(), true);
637    }
638
639    if (err != NO_ERROR) {
640        // batch/activate has failed, reset our state.
641        cleanupWithoutDisableLocked(connection, handle);
642    }
643    return err;
644}
645
646status_t SensorService::disable(const sp<SensorEventConnection>& connection,
647        int handle)
648{
649    if (mInitCheck != NO_ERROR)
650        return mInitCheck;
651
652    Mutex::Autolock _l(mLock);
653    status_t err = cleanupWithoutDisableLocked(connection, handle);
654    if (err == NO_ERROR) {
655        SensorInterface* sensor = mSensorMap.valueFor(handle);
656        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
657    }
658    return err;
659}
660
661status_t SensorService::cleanupWithoutDisable(
662        const sp<SensorEventConnection>& connection, int handle) {
663    Mutex::Autolock _l(mLock);
664    return cleanupWithoutDisableLocked(connection, handle);
665}
666
667status_t SensorService::cleanupWithoutDisableLocked(
668        const sp<SensorEventConnection>& connection, int handle) {
669    SensorRecord* rec = mActiveSensors.valueFor(handle);
670    if (rec) {
671        // see if this connection becomes inactive
672        if (connection->removeSensor(handle)) {
673            BatteryService::disableSensor(connection->getUid(), handle);
674        }
675        if (connection->hasAnySensor() == false) {
676            mActiveConnections.remove(connection);
677        }
678        // see if this sensor becomes inactive
679        if (rec->removeConnection(connection)) {
680            mActiveSensors.removeItem(handle);
681            mActiveVirtualSensors.removeItem(handle);
682            delete rec;
683        }
684        return NO_ERROR;
685    }
686    return BAD_VALUE;
687}
688
689status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
690        int handle, nsecs_t ns)
691{
692    if (mInitCheck != NO_ERROR)
693        return mInitCheck;
694
695    SensorInterface* sensor = mSensorMap.valueFor(handle);
696    if (!sensor)
697        return BAD_VALUE;
698
699    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
700        return BAD_VALUE;
701    }
702
703    if (ns < 0)
704        return BAD_VALUE;
705
706    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
707    if (ns < minDelayNs) {
708        ns = minDelayNs;
709    }
710
711    return sensor->setDelay(connection.get(), handle, ns);
712}
713
714status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
715                                    int handle) {
716    if (mInitCheck != NO_ERROR) return mInitCheck;
717    SensorInterface* sensor = mSensorMap.valueFor(handle);
718    if (sensor == NULL) {
719        return BAD_VALUE;
720    }
721
722    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried flushing")) {
723        return BAD_VALUE;
724    }
725
726    if (sensor->getSensor().getType() == SENSOR_TYPE_SIGNIFICANT_MOTION) {
727        ALOGE("flush called on Significant Motion sensor");
728        return INVALID_OPERATION;
729    }
730    return sensor->flush(connection.get(), handle);
731}
732
733
734bool SensorService::canAccessSensor(const Sensor& sensor) {
735    String16 permissionString(sensor.getRequiredPermission());
736    return permissionString.size() == 0 ||
737            PermissionCache::checkCallingPermission(permissionString);
738}
739
740bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
741    if (canAccessSensor(sensor)) {
742        return true;
743    } else {
744        String8 errorMessage;
745        errorMessage.appendFormat(
746                "%s a sensor (%s) without holding its required permission: %s",
747                operation,
748                sensor.getName().string(),
749                sensor.getRequiredPermission().string());
750        return false;
751    }
752}
753
754// ---------------------------------------------------------------------------
755
756SensorService::SensorRecord::SensorRecord(
757        const sp<SensorEventConnection>& connection)
758{
759    mConnections.add(connection);
760}
761
762bool SensorService::SensorRecord::addConnection(
763        const sp<SensorEventConnection>& connection)
764{
765    if (mConnections.indexOf(connection) < 0) {
766        mConnections.add(connection);
767        return true;
768    }
769    return false;
770}
771
772bool SensorService::SensorRecord::removeConnection(
773        const wp<SensorEventConnection>& connection)
774{
775    ssize_t index = mConnections.indexOf(connection);
776    if (index >= 0) {
777        mConnections.removeItemsAt(index, 1);
778    }
779    return mConnections.size() ? false : true;
780}
781
782// ---------------------------------------------------------------------------
783
784SensorService::SensorEventConnection::SensorEventConnection(
785        const sp<SensorService>& service, uid_t uid)
786    : mService(service), mUid(uid)
787{
788    const SensorDevice& device(SensorDevice::getInstance());
789    if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
790        // Increase socket buffer size to 1MB for batching capabilities.
791        mChannel = new BitTube(service->mSocketBufferSize);
792    } else {
793        mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED);
794    }
795}
796
797SensorService::SensorEventConnection::~SensorEventConnection()
798{
799    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
800    mService->cleanupConnection(this);
801}
802
803void SensorService::SensorEventConnection::onFirstRef()
804{
805}
806
807void SensorService::SensorEventConnection::dump(String8& result) {
808    Mutex::Autolock _l(mConnectionLock);
809    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
810        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
811        result.appendFormat("\t %s | status: %s | pending flush events %d | uid %d\n",
812                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
813                            flushInfo.mFirstFlushPending ? "First flush pending" :
814                                                           "active",
815                            flushInfo.mPendingFlushEventsToSend,
816                            mUid);
817    }
818}
819
820bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
821    Mutex::Autolock _l(mConnectionLock);
822    if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
823        return false;
824    }
825    if (mSensorInfo.indexOfKey(handle) < 0) {
826        mSensorInfo.add(handle, FlushInfo());
827        return true;
828    }
829    return false;
830}
831
832bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
833    Mutex::Autolock _l(mConnectionLock);
834    if (mSensorInfo.removeItem(handle) >= 0) {
835        return true;
836    }
837    return false;
838}
839
840bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
841    Mutex::Autolock _l(mConnectionLock);
842    return mSensorInfo.indexOfKey(handle) >= 0;
843}
844
845bool SensorService::SensorEventConnection::hasAnySensor() const {
846    Mutex::Autolock _l(mConnectionLock);
847    return mSensorInfo.size() ? true : false;
848}
849
850void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
851                                bool value) {
852    Mutex::Autolock _l(mConnectionLock);
853    ssize_t index = mSensorInfo.indexOfKey(handle);
854    if (index >= 0) {
855        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
856        flushInfo.mFirstFlushPending = value;
857    }
858}
859
860status_t SensorService::SensorEventConnection::sendEvents(
861        sensors_event_t const* buffer, size_t numEvents,
862        sensors_event_t* scratch)
863{
864    // filter out events not for this connection
865    size_t count = 0;
866
867    if (scratch) {
868        Mutex::Autolock _l(mConnectionLock);
869        size_t i=0;
870        while (i<numEvents) {
871            int32_t curr = buffer[i].sensor;
872            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
873                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
874                         buffer[i].meta_data.sensor);
875                // Setting curr to the correct sensor to ensure the sensor events per connection are
876                // filtered correctly. buffer[i].sensor is zero for meta_data events.
877                curr = buffer[i].meta_data.sensor;
878            }
879            ssize_t index = mSensorInfo.indexOfKey(curr);
880            if (index >= 0 && mSensorInfo[index].mFirstFlushPending == true &&
881                buffer[i].type == SENSOR_TYPE_META_DATA) {
882                // This is the first flush before activate is called. Events can now be sent for
883                // this sensor on this connection.
884                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
885                         buffer[i].meta_data.sensor);
886                mSensorInfo.editValueAt(index).mFirstFlushPending = false;
887            }
888            if (index >= 0 && mSensorInfo[index].mFirstFlushPending == false)  {
889                do {
890                    scratch[count++] = buffer[i++];
891                } while ((i<numEvents) && ((buffer[i].sensor == curr) ||
892                         (buffer[i].type == SENSOR_TYPE_META_DATA  &&
893                          buffer[i].meta_data.sensor == curr)));
894            } else {
895                i++;
896            }
897        }
898    } else {
899        scratch = const_cast<sensors_event_t *>(buffer);
900        count = numEvents;
901    }
902
903    // Send pending flush events (if any) before sending events from the cache.
904    {
905        ASensorEvent flushCompleteEvent;
906        flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
907        flushCompleteEvent.sensor = 0;
908        Mutex::Autolock _l(mConnectionLock);
909        // Loop through all the sensors for this connection and check if there are any pending
910        // flush complete events to be sent.
911        for (size_t i = 0; i < mSensorInfo.size(); ++i) {
912            FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
913            while (flushInfo.mPendingFlushEventsToSend > 0) {
914                flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
915                ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
916                if (size < 0) {
917                    // ALOGW("dropping %d events on the floor", count);
918                    countFlushCompleteEventsLocked(scratch, count);
919                    return size;
920                }
921                ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
922                         flushCompleteEvent.meta_data.sensor);
923                flushInfo.mPendingFlushEventsToSend--;
924            }
925        }
926    }
927
928    // Early return if there are no events for this connection.
929    if (count == 0) {
930        return status_t(NO_ERROR);
931    }
932
933    // NOTE: ASensorEvent and sensors_event_t are the same type
934    ssize_t size = SensorEventQueue::write(mChannel,
935            reinterpret_cast<ASensorEvent const*>(scratch), count);
936    if (size == -EAGAIN) {
937        // the destination doesn't accept events anymore, it's probably
938        // full. For now, we just drop the events on the floor.
939        // ALOGW("dropping %d events on the floor", count);
940        Mutex::Autolock _l(mConnectionLock);
941        countFlushCompleteEventsLocked(scratch, count);
942        return size;
943    }
944
945    return size < 0 ? status_t(size) : status_t(NO_ERROR);
946}
947
948void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
949                sensors_event_t* scratch, const int numEventsDropped) {
950    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
951    // Count flushComplete events in the events that are about to the dropped. These will be sent
952    // separately before the next batch of events.
953    for (int j = 0; j < numEventsDropped; ++j) {
954        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
955            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
956            flushInfo.mPendingFlushEventsToSend++;
957            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
958                     flushInfo.mPendingFlushEventsToSend);
959        }
960    }
961    return;
962}
963
964sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
965{
966    return mChannel;
967}
968
969status_t SensorService::SensorEventConnection::enableDisable(
970        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
971        int reservedFlags)
972{
973    status_t err;
974    if (enabled) {
975        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
976                               reservedFlags);
977    } else {
978        err = mService->disable(this, handle);
979    }
980    return err;
981}
982
983status_t SensorService::SensorEventConnection::setEventRate(
984        int handle, nsecs_t samplingPeriodNs)
985{
986    return mService->setEventRate(this, handle, samplingPeriodNs);
987}
988
989status_t  SensorService::SensorEventConnection::flush() {
990    SensorDevice& dev(SensorDevice::getInstance());
991    const int halVersion = dev.getHalDeviceVersion();
992    Mutex::Autolock _l(mConnectionLock);
993    status_t err(NO_ERROR);
994    // Loop through all sensors for this connection and call flush on each of them.
995    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
996        const int handle = mSensorInfo.keyAt(i);
997        if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
998            // For older devices just increment pending flush count which will send a trivial
999            // flush complete event.
1000            FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
1001            flushInfo.mPendingFlushEventsToSend++;
1002        } else {
1003            status_t err_flush = mService->flushSensor(this, handle);
1004            if (err_flush != NO_ERROR) {
1005                ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
1006            }
1007            err = (err_flush != NO_ERROR) ? err_flush : err;
1008        }
1009    }
1010    return err;
1011}
1012
1013// ---------------------------------------------------------------------------
1014}; // namespace android
1015
1016