SensorService.cpp revision b7beb52d622f901d2c2efd3b8ebd1879514d3e88
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/AppOpsManager.h>
35#include <binder/BinderService.h>
36#include <binder/IServiceManager.h>
37#include <binder/PermissionCache.h>
38
39#include <gui/ISensorServer.h>
40#include <gui/ISensorEventConnection.h>
41#include <gui/SensorEventQueue.h>
42
43#include <hardware/sensors.h>
44#include <hardware_legacy/power.h>
45
46#include "BatteryService.h"
47#include "CorrectedGyroSensor.h"
48#include "GravitySensor.h"
49#include "LinearAccelerationSensor.h"
50#include "OrientationSensor.h"
51#include "RotationVectorSensor.h"
52#include "SensorFusion.h"
53#include "SensorService.h"
54
55namespace android {
56// ---------------------------------------------------------------------------
57
58/*
59 * Notes:
60 *
61 * - what about a gyro-corrected magnetic-field sensor?
62 * - run mag sensor from time to time to force calibration
63 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
64 *
65 */
66
67const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
68// Permissions.
69static const String16 sDump("android.permission.DUMP");
70
71SensorService::SensorService()
72    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
73      mWakeLockAcquired(false)
74{
75}
76
77void SensorService::onFirstRef()
78{
79    ALOGD("nuSensorService starting...");
80    SensorDevice& dev(SensorDevice::getInstance());
81
82    if (dev.initCheck() == NO_ERROR) {
83        sensor_t const* list;
84        ssize_t count = dev.getSensorList(&list);
85        if (count > 0) {
86            ssize_t orientationIndex = -1;
87            bool hasGyro = false, hasAccel = false, hasMag = false;
88            uint32_t virtualSensorsNeeds =
89                    (1<<SENSOR_TYPE_GRAVITY) |
90                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
91                    (1<<SENSOR_TYPE_ROTATION_VECTOR);
92
93            mLastEventSeen.setCapacity(count);
94            for (ssize_t i=0 ; i<count ; i++) {
95                registerSensor( new HardwareSensor(list[i]) );
96                switch (list[i].type) {
97                    case SENSOR_TYPE_ACCELEROMETER:
98                        hasAccel = true;
99                        break;
100                    case SENSOR_TYPE_MAGNETIC_FIELD:
101                        hasMag = true;
102                        break;
103                    case SENSOR_TYPE_ORIENTATION:
104                        orientationIndex = i;
105                        break;
106                    case SENSOR_TYPE_GYROSCOPE:
107                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
108                        hasGyro = true;
109                        break;
110                    case SENSOR_TYPE_GRAVITY:
111                    case SENSOR_TYPE_LINEAR_ACCELERATION:
112                    case SENSOR_TYPE_ROTATION_VECTOR:
113                        virtualSensorsNeeds &= ~(1<<list[i].type);
114                        break;
115                }
116            }
117
118            // it's safe to instantiate the SensorFusion object here
119            // (it wants to be instantiated after h/w sensors have been
120            // registered)
121            const SensorFusion& fusion(SensorFusion::getInstance());
122
123            // build the sensor list returned to users
124            mUserSensorList = mSensorList;
125
126            if (hasGyro && hasAccel && hasMag) {
127                Sensor aSensor;
128
129                // Add Android virtual sensors if they're not already
130                // available in the HAL
131
132                aSensor = registerVirtualSensor( new RotationVectorSensor() );
133                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
134                    mUserSensorList.add(aSensor);
135                }
136
137                aSensor = registerVirtualSensor( new GravitySensor(list, count) );
138                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
139                    mUserSensorList.add(aSensor);
140                }
141
142                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
143                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
144                    mUserSensorList.add(aSensor);
145                }
146
147                aSensor = registerVirtualSensor( new OrientationSensor() );
148                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
149                    // if we are doing our own rotation-vector, also add
150                    // the orientation sensor and remove the HAL provided one.
151                    mUserSensorList.replaceAt(aSensor, orientationIndex);
152                }
153
154                // virtual debugging sensors are not added to mUserSensorList
155                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
156                registerVirtualSensor( new GyroDriftSensor() );
157            }
158
159            // debugging sensor list
160            mUserSensorListDebug = mSensorList;
161
162            // Check if the device really supports batching by looking at the FIFO event
163            // counts for each sensor.
164            bool batchingSupported = false;
165            for (size_t i = 0; i < mSensorList.size(); ++i) {
166                if (mSensorList[i].getFifoMaxEventCount() > 0) {
167                    batchingSupported = true;
168                    break;
169                }
170            }
171
172            if (batchingSupported) {
173                // Increase socket buffer size to a max of 100 KB for batching capabilities.
174                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
175            } else {
176                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
177            }
178
179            // Compare the socketBufferSize value against the system limits and limit
180            // it to maxSystemSocketBufferSize if necessary.
181            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
182            char line[128];
183            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
184                line[sizeof(line) - 1] = '\0';
185                size_t maxSystemSocketBufferSize;
186                sscanf(line, "%zu", &maxSystemSocketBufferSize);
187                if (mSocketBufferSize > maxSystemSocketBufferSize) {
188                    mSocketBufferSize = maxSystemSocketBufferSize;
189                }
190            }
191            if (fp) {
192                fclose(fp);
193            }
194
195            mWakeLockAcquired = false;
196            mLooper = new Looper(false);
197            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
198            mSensorEventBuffer = new sensors_event_t[minBufferSize];
199            mSensorEventScratch = new sensors_event_t[minBufferSize];
200            mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
201            mCurrentOperatingMode = NORMAL;
202
203            mNextSensorRegIndex = 0;
204            for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
205                mLastNSensorRegistrations.push();
206            }
207
208            mInitCheck = NO_ERROR;
209            mAckReceiver = new SensorEventAckReceiver(this);
210            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
211            run("SensorService", PRIORITY_URGENT_DISPLAY);
212        }
213    }
214}
215
216Sensor SensorService::registerSensor(SensorInterface* s)
217{
218    sensors_event_t event;
219    memset(&event, 0, sizeof(event));
220
221    const Sensor sensor(s->getSensor());
222    // add to the sensor list (returned to clients)
223    mSensorList.add(sensor);
224    // add to our handle->SensorInterface mapping
225    mSensorMap.add(sensor.getHandle(), s);
226    // create an entry in the mLastEventSeen array
227    mLastEventSeen.add(sensor.getHandle(), NULL);
228
229    return sensor;
230}
231
232Sensor SensorService::registerVirtualSensor(SensorInterface* s)
233{
234    Sensor sensor = registerSensor(s);
235    mVirtualSensorList.add( s );
236    return sensor;
237}
238
239SensorService::~SensorService()
240{
241    for (size_t i=0 ; i<mSensorMap.size() ; i++)
242        delete mSensorMap.valueAt(i);
243}
244
245status_t SensorService::dump(int fd, const Vector<String16>& args)
246{
247    String8 result;
248    if (!PermissionCache::checkCallingPermission(sDump)) {
249        result.appendFormat("Permission Denial: "
250                "can't dump SensorService from pid=%d, uid=%d\n",
251                IPCThreadState::self()->getCallingPid(),
252                IPCThreadState::self()->getCallingUid());
253    } else {
254        if (args.size() > 2) {
255           return INVALID_OPERATION;
256        }
257        Mutex::Autolock _l(mLock);
258        SensorDevice& dev(SensorDevice::getInstance());
259        if (args.size() == 2 && args[0] == String16("restrict")) {
260            // If already in restricted mode. Ignore.
261            if (mCurrentOperatingMode == RESTRICTED) {
262                return status_t(NO_ERROR);
263            }
264            // If in any mode other than normal, ignore.
265            if (mCurrentOperatingMode != NORMAL) {
266                return INVALID_OPERATION;
267            }
268            mCurrentOperatingMode = RESTRICTED;
269            dev.disableAllSensors();
270            // Clear all pending flush connections for all active sensors. If one of the active
271            // connections has called flush() and the underlying sensor has been disabled before a
272            // flush complete event is returned, we need to remove the connection from this queue.
273            for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
274                mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
275            }
276            mWhiteListedPackage.setTo(String8(args[1]));
277            return status_t(NO_ERROR);
278        } else if (args.size() == 1 && args[0] == String16("enable")) {
279            // If currently in restricted mode, reset back to NORMAL mode else ignore.
280            if (mCurrentOperatingMode == RESTRICTED) {
281                mCurrentOperatingMode = NORMAL;
282                dev.enableAllSensors();
283            }
284            if (mCurrentOperatingMode == DATA_INJECTION) {
285               resetToNormalModeLocked();
286            }
287            mWhiteListedPackage.clear();
288            return status_t(NO_ERROR);
289        } else if (args.size() == 2 && args[0] == String16("data_injection")) {
290            if (mCurrentOperatingMode == NORMAL) {
291                dev.disableAllSensors();
292                status_t err = dev.setMode(DATA_INJECTION);
293                if (err == NO_ERROR) {
294                    mCurrentOperatingMode = DATA_INJECTION;
295                } else {
296                    // Re-enable sensors.
297                    dev.enableAllSensors();
298                }
299                mWhiteListedPackage.setTo(String8(args[1]));
300                return NO_ERROR;
301            } else if (mCurrentOperatingMode == DATA_INJECTION) {
302                // Already in DATA_INJECTION mode. Treat this as a no_op.
303                return NO_ERROR;
304            } else {
305                // Transition to data injection mode supported only from NORMAL mode.
306                return INVALID_OPERATION;
307            }
308        } else if (mSensorList.size() == 0) {
309            result.append("No Sensors on the device\n");
310        } else {
311            // Default dump the sensor list and debugging information.
312            result.append("Sensor List:\n");
313            for (size_t i=0 ; i<mSensorList.size() ; i++) {
314                const Sensor& s(mSensorList[i]);
315                result.appendFormat(
316                        "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
317                        s.getName().string(),
318                        s.getVendor().string(),
319                        s.getVersion(),
320                        s.getStringType().string(),
321                        s.getHandle(),
322                        s.getRequiredPermission().string(),
323                        s.getType());
324
325                const int reportingMode = s.getReportingMode();
326                if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
327                    result.append(" continuous | ");
328                } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
329                    result.append(" on-change | ");
330                } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
331                    result.append(" one-shot | ");
332                } else {
333                    result.append(" special-trigger | ");
334                }
335
336                if (s.getMaxDelay() > 0) {
337                    result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
338                } else {
339                    result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
340                }
341
342                if (s.getMinDelay() > 0) {
343                    result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
344                } else {
345                    result.appendFormat("minDelay=%dus |", s.getMinDelay());
346                }
347
348                if (s.getFifoMaxEventCount() > 0) {
349                    result.appendFormat("FifoMax=%d events | ",
350                            s.getFifoMaxEventCount());
351                } else {
352                    result.append("no batching | ");
353                }
354
355                if (s.isWakeUpSensor()) {
356                    result.appendFormat("wakeUp | ");
357                } else {
358                    result.appendFormat("non-wakeUp | ");
359                }
360
361                int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
362                if (bufIndex >= 0) {
363                    const CircularBuffer* buf = mLastEventSeen.valueAt(bufIndex);
364                    if (buf != NULL && s.getRequiredPermission().isEmpty()) {
365                        buf->printBuffer(result);
366                    } else {
367                        result.append("last=<> \n");
368                    }
369                }
370                result.append("\n");
371            }
372            SensorFusion::getInstance().dump(result);
373            SensorDevice::getInstance().dump(result);
374
375            result.append("Active sensors:\n");
376            for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
377                int handle = mActiveSensors.keyAt(i);
378                result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
379                        getSensorName(handle).string(),
380                        handle,
381                        mActiveSensors.valueAt(i)->getNumConnections());
382            }
383
384            result.appendFormat("Socket Buffer size = %d events\n",
385                                mSocketBufferSize/sizeof(sensors_event_t));
386            result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
387                    "not held");
388            result.appendFormat("Mode :");
389            switch(mCurrentOperatingMode) {
390               case NORMAL:
391                   result.appendFormat(" NORMAL\n");
392                   break;
393               case RESTRICTED:
394                   result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
395                   break;
396               case DATA_INJECTION:
397                   result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
398            }
399            result.appendFormat("%zd active connections\n", mActiveConnections.size());
400
401            for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
402                sp<SensorEventConnection> connection(mActiveConnections[i].promote());
403                if (connection != 0) {
404                    result.appendFormat("Connection Number: %zu \n", i);
405                    connection->dump(result);
406                }
407            }
408
409            result.appendFormat("Previous Registrations:\n");
410            // Log in the reverse chronological order.
411            int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
412                SENSOR_REGISTRATIONS_BUF_SIZE;
413            const int startIndex = currentIndex;
414            do {
415                const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
416                if (SensorRegistrationInfo::isSentinel(reg_info)) {
417                    // Ignore sentinel, proceed to next item.
418                    currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
419                        SENSOR_REGISTRATIONS_BUF_SIZE;
420                    continue;
421                }
422                if (reg_info.mActivated) {
423                   result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
424                           "samplingRate=%dus maxReportLatency=%dus\n",
425                           reg_info.mHour, reg_info.mMin, reg_info.mSec,
426                           reg_info.mPackageName.string(), reg_info.mSensorHandle,
427                           reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
428                } else {
429                   result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
430                           reg_info.mHour, reg_info.mMin, reg_info.mSec,
431                           reg_info.mPackageName.string(), reg_info.mSensorHandle);
432                }
433                currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
434                        SENSOR_REGISTRATIONS_BUF_SIZE;
435            } while(startIndex != currentIndex);
436        }
437    }
438    write(fd, result.string(), result.size());
439    return NO_ERROR;
440}
441
442void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
443        sensors_event_t const* buffer, const int count) {
444    for (int i=0 ; i<count ; i++) {
445        int handle = buffer[i].sensor;
446        if (buffer[i].type == SENSOR_TYPE_META_DATA) {
447            handle = buffer[i].meta_data.sensor;
448        }
449        if (connection->hasSensor(handle)) {
450            SensorInterface* sensor = mSensorMap.valueFor(handle);
451            // If this buffer has an event from a one_shot sensor and this connection is registered
452            // for this particular one_shot sensor, try cleaning up the connection.
453            if (sensor != NULL &&
454                sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
455                sensor->autoDisable(connection.get(), handle);
456                cleanupWithoutDisableLocked(connection, handle);
457            }
458
459        }
460   }
461}
462
463bool SensorService::threadLoop()
464{
465    ALOGD("nuSensorService thread starting...");
466
467    // each virtual sensor could generate an event per "real" event, that's why we need
468    // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
469    // in practice, this is too aggressive, but guaranteed to be enough.
470    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
471    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
472
473    SensorDevice& device(SensorDevice::getInstance());
474    const size_t vcount = mVirtualSensorList.size();
475
476    const int halVersion = device.getHalDeviceVersion();
477    do {
478        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
479        if (count < 0) {
480            ALOGE("sensor poll failed (%s)", strerror(-count));
481            break;
482        }
483
484        // Reset sensors_event_t.flags to zero for all events in the buffer.
485        for (int i = 0; i < count; i++) {
486             mSensorEventBuffer[i].flags = 0;
487        }
488
489        // Make a copy of the connection vector as some connections may be removed during the
490        // course of this loop (especially when one-shot sensor events are present in the
491        // sensor_event buffer). Promote all connections to StrongPointers before the lock is
492        // acquired. If the destructor of the sp gets called when the lock is acquired, it may
493        // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
494        // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
495        SortedVector< sp<SensorEventConnection> > activeConnections;
496        populateActiveConnections(&activeConnections);
497        Mutex::Autolock _l(mLock);
498        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
499        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
500        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
501        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
502        // releasing the wakelock.
503        bool bufferHasWakeUpEvent = false;
504        for (int i = 0; i < count; i++) {
505            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
506                bufferHasWakeUpEvent = true;
507                break;
508            }
509        }
510
511        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
512            setWakeLockAcquiredLocked(true);
513        }
514        recordLastValueLocked(mSensorEventBuffer, count);
515
516        // handle virtual sensors
517        if (count && vcount) {
518            sensors_event_t const * const event = mSensorEventBuffer;
519            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
520            if (activeVirtualSensorCount) {
521                size_t k = 0;
522                SensorFusion& fusion(SensorFusion::getInstance());
523                if (fusion.isEnabled()) {
524                    for (size_t i=0 ; i<size_t(count) ; i++) {
525                        fusion.process(event[i]);
526                    }
527                }
528                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
529                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
530                        if (count + k >= minBufferSize) {
531                            ALOGE("buffer too small to hold all events: "
532                                    "count=%zd, k=%zu, size=%zu",
533                                    count, k, minBufferSize);
534                            break;
535                        }
536                        sensors_event_t out;
537                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
538                        if (si->process(&out, event[i])) {
539                            mSensorEventBuffer[count + k] = out;
540                            k++;
541                        }
542                    }
543                }
544                if (k) {
545                    // record the last synthesized values
546                    recordLastValueLocked(&mSensorEventBuffer[count], k);
547                    count += k;
548                    // sort the buffer by time-stamps
549                    sortEventBuffer(mSensorEventBuffer, count);
550                }
551            }
552        }
553
554        // handle backward compatibility for RotationVector sensor
555        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
556            for (int i = 0; i < count; i++) {
557                if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
558                    // All the 4 components of the quaternion should be available
559                    // No heading accuracy. Set it to -1
560                    mSensorEventBuffer[i].data[4] = -1;
561                }
562            }
563        }
564
565        // Map flush_complete_events in the buffer to SensorEventConnections which called
566        // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
567        // SensorEventConnection mapped to the corresponding flush_complete_event in
568        // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
569        for (int i = 0; i < count; ++i) {
570            mMapFlushEventsToConnections[i] = NULL;
571            if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
572                const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
573                SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
574                if (rec != NULL) {
575                    mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
576                    rec->removeFirstPendingFlushConnection();
577                }
578            }
579        }
580
581        // Send our events to clients. Check the state of wake lock for each client and release the
582        // lock if none of the clients need it.
583        bool needsWakeLock = false;
584        size_t numConnections = activeConnections.size();
585        for (size_t i=0 ; i < numConnections; ++i) {
586            if (activeConnections[i] != 0) {
587                activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
588                        mMapFlushEventsToConnections);
589                needsWakeLock |= activeConnections[i]->needsWakeLock();
590                // If the connection has one-shot sensors, it may be cleaned up after first trigger.
591                // Early check for one-shot sensors.
592                if (activeConnections[i]->hasOneShotSensors()) {
593                    cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
594                            count);
595                }
596            }
597        }
598
599        if (mWakeLockAcquired && !needsWakeLock) {
600            setWakeLockAcquiredLocked(false);
601        }
602    } while (!Thread::exitPending());
603
604    ALOGW("Exiting SensorService::threadLoop => aborting...");
605    abort();
606    return false;
607}
608
609sp<Looper> SensorService::getLooper() const {
610    return mLooper;
611}
612
613void SensorService::resetAllWakeLockRefCounts() {
614    SortedVector< sp<SensorEventConnection> > activeConnections;
615    populateActiveConnections(&activeConnections);
616    {
617        Mutex::Autolock _l(mLock);
618        for (size_t i=0 ; i < activeConnections.size(); ++i) {
619            if (activeConnections[i] != 0) {
620                activeConnections[i]->resetWakeLockRefCount();
621            }
622        }
623        setWakeLockAcquiredLocked(false);
624    }
625}
626
627void SensorService::setWakeLockAcquiredLocked(bool acquire) {
628    if (acquire) {
629        if (!mWakeLockAcquired) {
630            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
631            mWakeLockAcquired = true;
632        }
633        mLooper->wake();
634    } else {
635        if (mWakeLockAcquired) {
636            release_wake_lock(WAKE_LOCK_NAME);
637            mWakeLockAcquired = false;
638        }
639    }
640}
641
642bool SensorService::isWakeLockAcquired() {
643    Mutex::Autolock _l(mLock);
644    return mWakeLockAcquired;
645}
646
647bool SensorService::SensorEventAckReceiver::threadLoop() {
648    ALOGD("new thread SensorEventAckReceiver");
649    sp<Looper> looper = mService->getLooper();
650    do {
651        bool wakeLockAcquired = mService->isWakeLockAcquired();
652        int timeout = -1;
653        if (wakeLockAcquired) timeout = 5000;
654        int ret = looper->pollOnce(timeout);
655        if (ret == ALOOPER_POLL_TIMEOUT) {
656           mService->resetAllWakeLockRefCounts();
657        }
658    } while(!Thread::exitPending());
659    return false;
660}
661
662void SensorService::recordLastValueLocked(
663        const sensors_event_t* buffer, size_t count) {
664    for (size_t i = 0; i < count; i++) {
665        if (buffer[i].type != SENSOR_TYPE_META_DATA) {
666            CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
667            if (circular_buf == NULL) {
668                circular_buf = new CircularBuffer(buffer[i].type);
669            }
670            circular_buf->addEvent(buffer[i]);
671        }
672    }
673}
674
675void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
676{
677    struct compar {
678        static int cmp(void const* lhs, void const* rhs) {
679            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
680            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
681            return l->timestamp - r->timestamp;
682        }
683    };
684    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
685}
686
687String8 SensorService::getSensorName(int handle) const {
688    size_t count = mUserSensorList.size();
689    for (size_t i=0 ; i<count ; i++) {
690        const Sensor& sensor(mUserSensorList[i]);
691        if (sensor.getHandle() == handle) {
692            return sensor.getName();
693        }
694    }
695    String8 result("unknown");
696    return result;
697}
698
699bool SensorService::isVirtualSensor(int handle) const {
700    SensorInterface* sensor = mSensorMap.valueFor(handle);
701    return sensor->isVirtual();
702}
703
704bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
705    int handle = event.sensor;
706    if (event.type == SENSOR_TYPE_META_DATA) {
707        handle = event.meta_data.sensor;
708    }
709    SensorInterface* sensor = mSensorMap.valueFor(handle);
710    return sensor != NULL && sensor->getSensor().isWakeUpSensor();
711}
712
713SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
714     return mActiveSensors.valueFor(handle);
715}
716
717Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
718{
719    char value[PROPERTY_VALUE_MAX];
720    property_get("debug.sensors", value, "0");
721    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
722            mUserSensorListDebug : mUserSensorList;
723    Vector<Sensor> accessibleSensorList;
724    for (size_t i = 0; i < initialSensorList.size(); i++) {
725        Sensor sensor = initialSensorList[i];
726        accessibleSensorList.add(sensor);
727    }
728    return accessibleSensorList;
729}
730
731sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
732        int requestedMode, const String16& opPackageName) {
733    // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
734    if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
735        return NULL;
736    }
737
738    Mutex::Autolock _l(mLock);
739    // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
740    // operating in DI mode.
741    if (requestedMode == DATA_INJECTION) {
742        if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
743        if (!isWhiteListedPackage(packageName)) return NULL;
744    }
745
746    uid_t uid = IPCThreadState::self()->getCallingUid();
747    sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
748            requestedMode == DATA_INJECTION, opPackageName));
749    if (requestedMode == DATA_INJECTION) {
750        if (mActiveConnections.indexOf(result) < 0) {
751            mActiveConnections.add(result);
752        }
753        // Add the associated file descriptor to the Looper for polling whenever there is data to
754        // be injected.
755        result->updateLooperRegistration(mLooper);
756    }
757    return result;
758}
759
760int SensorService::isDataInjectionEnabled() {
761    Mutex::Autolock _l(mLock);
762    return (mCurrentOperatingMode == DATA_INJECTION);
763}
764
765status_t SensorService::resetToNormalMode() {
766    Mutex::Autolock _l(mLock);
767    return resetToNormalModeLocked();
768}
769
770status_t SensorService::resetToNormalModeLocked() {
771    SensorDevice& dev(SensorDevice::getInstance());
772    dev.enableAllSensors();
773    status_t err = dev.setMode(NORMAL);
774    mCurrentOperatingMode = NORMAL;
775    return err;
776}
777
778void SensorService::cleanupConnection(SensorEventConnection* c)
779{
780    Mutex::Autolock _l(mLock);
781    const wp<SensorEventConnection> connection(c);
782    size_t size = mActiveSensors.size();
783    ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
784    for (size_t i=0 ; i<size ; ) {
785        int handle = mActiveSensors.keyAt(i);
786        if (c->hasSensor(handle)) {
787            ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
788            SensorInterface* sensor = mSensorMap.valueFor( handle );
789            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
790            if (sensor) {
791                sensor->activate(c, false);
792            }
793            c->removeSensor(handle);
794        }
795        SensorRecord* rec = mActiveSensors.valueAt(i);
796        ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
797        ALOGD_IF(DEBUG_CONNECTIONS,
798                "removing connection %p for sensor[%zu].handle=0x%08x",
799                c, i, handle);
800
801        if (rec && rec->removeConnection(connection)) {
802            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
803            mActiveSensors.removeItemsAt(i, 1);
804            mActiveVirtualSensors.removeItem(handle);
805            delete rec;
806            size--;
807        } else {
808            i++;
809        }
810    }
811    c->updateLooperRegistration(mLooper);
812    mActiveConnections.remove(connection);
813    BatteryService::cleanup(c->getUid());
814    if (c->needsWakeLock()) {
815        checkWakeLockStateLocked();
816    }
817}
818
819Sensor SensorService::getSensorFromHandle(int handle) const {
820    return mSensorMap.valueFor(handle)->getSensor();
821}
822
823status_t SensorService::enable(const sp<SensorEventConnection>& connection,
824        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
825        const String16& opPackageName)
826{
827    if (mInitCheck != NO_ERROR)
828        return mInitCheck;
829
830    SensorInterface* sensor = mSensorMap.valueFor(handle);
831    if (sensor == NULL) {
832        return BAD_VALUE;
833    }
834
835    if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
836        return BAD_VALUE;
837    }
838
839    Mutex::Autolock _l(mLock);
840    if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
841           && !isWhiteListedPackage(connection->getPackageName())) {
842        return INVALID_OPERATION;
843    }
844
845    SensorRecord* rec = mActiveSensors.valueFor(handle);
846    if (rec == 0) {
847        rec = new SensorRecord(connection);
848        mActiveSensors.add(handle, rec);
849        if (sensor->isVirtual()) {
850            mActiveVirtualSensors.add(handle, sensor);
851        }
852    } else {
853        if (rec->addConnection(connection)) {
854            // this sensor is already activated, but we are adding a connection that uses it.
855            // Immediately send down the last known value of the requested sensor if it's not a
856            // "continuous" sensor.
857            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
858                // NOTE: The wake_up flag of this event may get set to
859                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
860                CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
861                if (circular_buf) {
862                    sensors_event_t event;
863                    memset(&event, 0, sizeof(event));
864                    // It is unlikely that this buffer is empty as the sensor is already active.
865                    // One possible corner case may be two applications activating an on-change
866                    // sensor at the same time.
867                    if(circular_buf->populateLastEvent(&event)) {
868                        event.sensor = handle;
869                        if (event.version == sizeof(sensors_event_t)) {
870                            if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
871                                setWakeLockAcquiredLocked(true);
872                            }
873                            connection->sendEvents(&event, 1, NULL);
874                            if (!connection->needsWakeLock() && mWakeLockAcquired) {
875                                checkWakeLockStateLocked();
876                            }
877                        }
878                    }
879                }
880            }
881        }
882    }
883
884    if (connection->addSensor(handle)) {
885        BatteryService::enableSensor(connection->getUid(), handle);
886        // the sensor was added (which means it wasn't already there)
887        // so, see if this connection becomes active
888        if (mActiveConnections.indexOf(connection) < 0) {
889            mActiveConnections.add(connection);
890        }
891    } else {
892        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
893            handle, connection.get());
894    }
895
896    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
897    if (samplingPeriodNs < minDelayNs) {
898        samplingPeriodNs = minDelayNs;
899    }
900
901    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
902                                "rate=%" PRId64 " timeout== %" PRId64"",
903             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
904
905    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
906                                 maxBatchReportLatencyNs);
907
908    // Call flush() before calling activate() on the sensor. Wait for a first
909    // flush complete event before sending events on this connection. Ignore
910    // one-shot sensors which don't support flush(). Ignore on-change sensors
911    // to maintain the on-change logic (any on-change events except the initial
912    // one should be trigger by a change in value). Also if this sensor isn't
913    // already active, don't call flush().
914    if (err == NO_ERROR &&
915            sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
916            sensor->getSensor().getReportingMode() != AREPORTING_MODE_ON_CHANGE &&
917            rec->getNumConnections() > 1) {
918        connection->setFirstFlushPending(handle, true);
919        status_t err_flush = sensor->flush(connection.get(), handle);
920        // Flush may return error if the underlying h/w sensor uses an older HAL.
921        if (err_flush == NO_ERROR) {
922            rec->addPendingFlushConnection(connection.get());
923        } else {
924            connection->setFirstFlushPending(handle, false);
925        }
926    }
927
928    if (err == NO_ERROR) {
929        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
930        err = sensor->activate(connection.get(), true);
931    }
932
933    if (err == NO_ERROR) {
934        connection->updateLooperRegistration(mLooper);
935        SensorRegistrationInfo &reg_info =
936            mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
937        reg_info.mSensorHandle = handle;
938        reg_info.mSamplingRateUs = samplingPeriodNs/1000;
939        reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
940        reg_info.mActivated = true;
941        reg_info.mPackageName = connection->getPackageName();
942        time_t rawtime = time(NULL);
943        struct tm * timeinfo = localtime(&rawtime);
944        reg_info.mHour = timeinfo->tm_hour;
945        reg_info.mMin = timeinfo->tm_min;
946        reg_info.mSec = timeinfo->tm_sec;
947        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
948    }
949
950    if (err != NO_ERROR) {
951        // batch/activate has failed, reset our state.
952        cleanupWithoutDisableLocked(connection, handle);
953    }
954    return err;
955}
956
957status_t SensorService::disable(const sp<SensorEventConnection>& connection,
958        int handle)
959{
960    if (mInitCheck != NO_ERROR)
961        return mInitCheck;
962
963    Mutex::Autolock _l(mLock);
964    status_t err = cleanupWithoutDisableLocked(connection, handle);
965    if (err == NO_ERROR) {
966        SensorInterface* sensor = mSensorMap.valueFor(handle);
967        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
968
969    }
970    if (err == NO_ERROR) {
971        SensorRegistrationInfo &reg_info =
972            mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
973        reg_info.mActivated = false;
974        reg_info.mPackageName= connection->getPackageName();
975        reg_info.mSensorHandle = handle;
976        time_t rawtime = time(NULL);
977        struct tm * timeinfo = localtime(&rawtime);
978        reg_info.mHour = timeinfo->tm_hour;
979        reg_info.mMin = timeinfo->tm_min;
980        reg_info.mSec = timeinfo->tm_sec;
981        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
982    }
983    return err;
984}
985
986status_t SensorService::cleanupWithoutDisable(
987        const sp<SensorEventConnection>& connection, int handle) {
988    Mutex::Autolock _l(mLock);
989    return cleanupWithoutDisableLocked(connection, handle);
990}
991
992status_t SensorService::cleanupWithoutDisableLocked(
993        const sp<SensorEventConnection>& connection, int handle) {
994    SensorRecord* rec = mActiveSensors.valueFor(handle);
995    if (rec) {
996        // see if this connection becomes inactive
997        if (connection->removeSensor(handle)) {
998            BatteryService::disableSensor(connection->getUid(), handle);
999        }
1000        if (connection->hasAnySensor() == false) {
1001            connection->updateLooperRegistration(mLooper);
1002            mActiveConnections.remove(connection);
1003        }
1004        // see if this sensor becomes inactive
1005        if (rec->removeConnection(connection)) {
1006            mActiveSensors.removeItem(handle);
1007            mActiveVirtualSensors.removeItem(handle);
1008            delete rec;
1009        }
1010        return NO_ERROR;
1011    }
1012    return BAD_VALUE;
1013}
1014
1015status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1016        int handle, nsecs_t ns, const String16& opPackageName)
1017{
1018    if (mInitCheck != NO_ERROR)
1019        return mInitCheck;
1020
1021    SensorInterface* sensor = mSensorMap.valueFor(handle);
1022    if (!sensor)
1023        return BAD_VALUE;
1024
1025    if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1026        return BAD_VALUE;
1027    }
1028
1029    if (ns < 0)
1030        return BAD_VALUE;
1031
1032    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1033    if (ns < minDelayNs) {
1034        ns = minDelayNs;
1035    }
1036
1037    return sensor->setDelay(connection.get(), handle, ns);
1038}
1039
1040status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1041        const String16& opPackageName) {
1042    if (mInitCheck != NO_ERROR) return mInitCheck;
1043    SensorDevice& dev(SensorDevice::getInstance());
1044    const int halVersion = dev.getHalDeviceVersion();
1045    status_t err(NO_ERROR);
1046    Mutex::Autolock _l(mLock);
1047    // Loop through all sensors for this connection and call flush on each of them.
1048    for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1049        const int handle = connection->mSensorInfo.keyAt(i);
1050        SensorInterface* sensor = mSensorMap.valueFor(handle);
1051        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1052            ALOGE("flush called on a one-shot sensor");
1053            err = INVALID_OPERATION;
1054            continue;
1055        }
1056        if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1057            // For older devices just increment pending flush count which will send a trivial
1058            // flush complete event.
1059            connection->incrementPendingFlushCount(handle);
1060        } else {
1061            if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1062                err = INVALID_OPERATION;
1063                continue;
1064            }
1065            status_t err_flush = sensor->flush(connection.get(), handle);
1066            if (err_flush == NO_ERROR) {
1067                SensorRecord* rec = mActiveSensors.valueFor(handle);
1068                if (rec != NULL) rec->addPendingFlushConnection(connection);
1069            }
1070            err = (err_flush != NO_ERROR) ? err_flush : err;
1071        }
1072    }
1073    return err;
1074}
1075
1076bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1077        const String16& opPackageName) {
1078    const String8& requiredPermission = sensor.getRequiredPermission();
1079
1080    if (requiredPermission.length() <= 0) {
1081        return true;
1082    }
1083
1084    bool hasPermission = false;
1085
1086    // Runtime permissions can't use the cache as they may change.
1087    if (sensor.isRequiredPermissionRuntime()) {
1088        hasPermission = checkPermission(String16(requiredPermission),
1089                IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1090    } else {
1091        hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1092    }
1093
1094    if (!hasPermission) {
1095        ALOGE("%s a sensor (%s) without holding its required permission: %s",
1096                operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1097        return false;
1098    }
1099
1100    const int32_t opCode = sensor.getRequiredAppOp();
1101    if (opCode >= 0) {
1102        AppOpsManager appOps;
1103        if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1104                        != AppOpsManager::MODE_ALLOWED) {
1105            ALOGE("%s a sensor (%s) without enabled required app op: %D",
1106                    operation, sensor.getName().string(), opCode);
1107            return false;
1108        }
1109    }
1110
1111    return true;
1112}
1113
1114void SensorService::checkWakeLockState() {
1115    Mutex::Autolock _l(mLock);
1116    checkWakeLockStateLocked();
1117}
1118
1119void SensorService::checkWakeLockStateLocked() {
1120    if (!mWakeLockAcquired) {
1121        return;
1122    }
1123    bool releaseLock = true;
1124    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1125        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1126        if (connection != 0) {
1127            if (connection->needsWakeLock()) {
1128                releaseLock = false;
1129                break;
1130            }
1131        }
1132    }
1133    if (releaseLock) {
1134        setWakeLockAcquiredLocked(false);
1135    }
1136}
1137
1138void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1139    Mutex::Autolock _l(mLock);
1140    connection->writeToSocketFromCache();
1141    if (connection->needsWakeLock()) {
1142        setWakeLockAcquiredLocked(true);
1143    }
1144}
1145
1146void SensorService::populateActiveConnections(
1147        SortedVector< sp<SensorEventConnection> >* activeConnections) {
1148    Mutex::Autolock _l(mLock);
1149    for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1150        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1151        if (connection != 0) {
1152            activeConnections->add(connection);
1153        }
1154    }
1155}
1156
1157bool SensorService::isWhiteListedPackage(const String8& packageName) {
1158    return (packageName.contains(mWhiteListedPackage.string()));
1159}
1160
1161int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1162    switch (sensor_event_type) {
1163        case SENSOR_TYPE_ROTATION_VECTOR:
1164        case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1165            return 5;
1166
1167        case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1168        case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1169            return 6;
1170
1171        case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1172            return 4;
1173
1174        case SENSOR_TYPE_SIGNIFICANT_MOTION:
1175        case SENSOR_TYPE_STEP_DETECTOR:
1176        case SENSOR_TYPE_STEP_COUNTER:
1177            return 1;
1178
1179         default:
1180            return 3;
1181    }
1182}
1183
1184// ---------------------------------------------------------------------------
1185SensorService::SensorRecord::SensorRecord(
1186        const sp<SensorEventConnection>& connection)
1187{
1188    mConnections.add(connection);
1189}
1190
1191bool SensorService::SensorRecord::addConnection(
1192        const sp<SensorEventConnection>& connection)
1193{
1194    if (mConnections.indexOf(connection) < 0) {
1195        mConnections.add(connection);
1196        return true;
1197    }
1198    return false;
1199}
1200
1201bool SensorService::SensorRecord::removeConnection(
1202        const wp<SensorEventConnection>& connection)
1203{
1204    ssize_t index = mConnections.indexOf(connection);
1205    if (index >= 0) {
1206        mConnections.removeItemsAt(index, 1);
1207    }
1208    // Remove this connections from the queue of flush() calls made on this sensor.
1209    for (Vector< wp<SensorEventConnection> >::iterator it =
1210            mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
1211
1212        if (it->unsafe_get() == connection.unsafe_get()) {
1213            it = mPendingFlushConnections.erase(it);
1214        } else {
1215            ++it;
1216        }
1217    }
1218    return mConnections.size() ? false : true;
1219}
1220
1221void SensorService::SensorRecord::addPendingFlushConnection(
1222        const sp<SensorEventConnection>& connection) {
1223    mPendingFlushConnections.add(connection);
1224}
1225
1226void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1227    if (mPendingFlushConnections.size() > 0) {
1228        mPendingFlushConnections.removeAt(0);
1229    }
1230}
1231
1232SensorService::SensorEventConnection *
1233SensorService::SensorRecord::getFirstPendingFlushConnection() {
1234   if (mPendingFlushConnections.size() > 0) {
1235        return mPendingFlushConnections[0].unsafe_get();
1236    }
1237    return NULL;
1238}
1239
1240void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1241    mPendingFlushConnections.clear();
1242}
1243
1244
1245// ---------------------------------------------------------------------------
1246SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
1247    mTimestamp = -1;
1248    const int numData = SensorService::getNumEventsForSensorType(sensorType);
1249    if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
1250        mStepCounter = 0;
1251    } else {
1252        mData = new float[numData];
1253        for (int i = 0; i < numData; ++i) {
1254            mData[i] = -1.0;
1255        }
1256    }
1257    mHour = mMin = mSec = INT32_MIN;
1258}
1259
1260bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
1261    return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
1262}
1263// --------------------------------------------------------------------------
1264SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1265    mNextInd = 0;
1266    mBufSize = CIRCULAR_BUF_SIZE;
1267    if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
1268            sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
1269            sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
1270        mBufSize = CIRCULAR_BUF_SIZE * 5;
1271    }
1272    mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
1273    mSensorType = sensor_event_type;
1274    for (int i = 0; i < mBufSize; ++i) {
1275        mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
1276    }
1277}
1278
1279void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1280    TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1281    curr_event->mTimestamp = sensor_event.timestamp;
1282    if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1283        curr_event->mStepCounter = sensor_event.u64.step_counter;
1284    } else {
1285        memcpy(curr_event->mData, sensor_event.data,
1286                 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1287    }
1288    time_t rawtime = time(NULL);
1289    struct tm * timeinfo = localtime(&rawtime);
1290    curr_event->mHour = timeinfo->tm_hour;
1291    curr_event->mMin = timeinfo->tm_min;
1292    curr_event->mSec = timeinfo->tm_sec;
1293    mNextInd = (mNextInd + 1) % mBufSize;
1294}
1295
1296void SensorService::CircularBuffer::printBuffer(String8& result) const {
1297    const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1298    int i = mNextInd, eventNum = 1;
1299    result.appendFormat("last %d events = < ", mBufSize);
1300    do {
1301        if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
1302            // Sentinel, ignore.
1303            i = (i + 1) % mBufSize;
1304            continue;
1305        }
1306        result.appendFormat("%d) ", eventNum++);
1307        if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1308            result.appendFormat("%llu,", mTrimmedSensorEventArr[i]->mStepCounter);
1309        } else {
1310            for (int j = 0; j < numData; ++j) {
1311                result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1312            }
1313        }
1314        result.appendFormat("%lld %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
1315                mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1316                mTrimmedSensorEventArr[i]->mSec);
1317        i = (i + 1) % mBufSize;
1318    } while (i != mNextInd);
1319    result.appendFormat(">\n");
1320}
1321
1322bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
1323    int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
1324    // Check if the buffer is empty.
1325    if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
1326        return false;
1327    }
1328    event->version = sizeof(sensors_event_t);
1329    event->type = mSensorType;
1330    event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1331    if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1332          event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1333    } else {
1334        memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1335                 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1336    }
1337    return true;
1338}
1339
1340SensorService::CircularBuffer::~CircularBuffer() {
1341    for (int i = 0; i < mBufSize; ++i) {
1342        delete mTrimmedSensorEventArr[i];
1343    }
1344    delete [] mTrimmedSensorEventArr;
1345}
1346
1347// ---------------------------------------------------------------------------
1348
1349SensorService::SensorEventConnection::SensorEventConnection(
1350        const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1351        const String16& opPackageName)
1352    : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
1353      mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1354      mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
1355    mChannel = new BitTube(mService->mSocketBufferSize);
1356#if DEBUG_CONNECTIONS
1357    mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
1358    mTotalAcksNeeded = mTotalAcksReceived = 0;
1359#endif
1360}
1361
1362SensorService::SensorEventConnection::~SensorEventConnection() {
1363    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
1364    mService->cleanupConnection(this);
1365    if (mEventCache != NULL) {
1366        delete mEventCache;
1367    }
1368}
1369
1370void SensorService::SensorEventConnection::onFirstRef() {
1371    LooperCallback::onFirstRef();
1372}
1373
1374bool SensorService::SensorEventConnection::needsWakeLock() {
1375    Mutex::Autolock _l(mConnectionLock);
1376    return !mDead && mWakeLockRefCount > 0;
1377}
1378
1379void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1380    Mutex::Autolock _l(mConnectionLock);
1381    mWakeLockRefCount = 0;
1382}
1383
1384void SensorService::SensorEventConnection::dump(String8& result) {
1385    Mutex::Autolock _l(mConnectionLock);
1386    result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
1387    result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
1388            "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
1389            mMaxCacheSize);
1390    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1391        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
1392        result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
1393                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
1394                            mSensorInfo.keyAt(i),
1395                            flushInfo.mFirstFlushPending ? "First flush pending" :
1396                                                           "active",
1397                            flushInfo.mPendingFlushEventsToSend);
1398    }
1399#if DEBUG_CONNECTIONS
1400    result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1401            " total_acks_needed %d | total_acks_recvd %d\n",
1402            mEventsReceived,
1403            mEventsSent,
1404            mEventsSentFromCache,
1405            mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1406            mTotalAcksNeeded,
1407            mTotalAcksReceived);
1408#endif
1409}
1410
1411bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
1412    Mutex::Autolock _l(mConnectionLock);
1413    if (!canAccessSensor(mService->getSensorFromHandle(handle),
1414            "Tried adding", mOpPackageName)) {
1415        return false;
1416    }
1417    if (mSensorInfo.indexOfKey(handle) < 0) {
1418        mSensorInfo.add(handle, FlushInfo());
1419        return true;
1420    }
1421    return false;
1422}
1423
1424bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
1425    Mutex::Autolock _l(mConnectionLock);
1426    if (mSensorInfo.removeItem(handle) >= 0) {
1427        return true;
1428    }
1429    return false;
1430}
1431
1432bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
1433    Mutex::Autolock _l(mConnectionLock);
1434    return mSensorInfo.indexOfKey(handle) >= 0;
1435}
1436
1437bool SensorService::SensorEventConnection::hasAnySensor() const {
1438    Mutex::Autolock _l(mConnectionLock);
1439    return mSensorInfo.size() ? true : false;
1440}
1441
1442bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1443    Mutex::Autolock _l(mConnectionLock);
1444    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1445        const int handle = mSensorInfo.keyAt(i);
1446        if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1447            return true;
1448        }
1449    }
1450    return false;
1451}
1452
1453String8 SensorService::SensorEventConnection::getPackageName() const {
1454    return mPackageName;
1455}
1456
1457void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1458                                bool value) {
1459    Mutex::Autolock _l(mConnectionLock);
1460    ssize_t index = mSensorInfo.indexOfKey(handle);
1461    if (index >= 0) {
1462        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1463        flushInfo.mFirstFlushPending = value;
1464    }
1465}
1466
1467void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1468    Mutex::Autolock _l(mConnectionLock);
1469    updateLooperRegistrationLocked(looper);
1470}
1471
1472void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1473        const sp<Looper>& looper) {
1474    bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1475                              mDataInjectionMode;
1476    // If all sensors are unregistered OR Looper has encountered an error, we
1477    // can remove the Fd from the Looper if it has been previously added.
1478    if (!isConnectionActive || mDead) {
1479        if (mHasLooperCallbacks) {
1480            ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1481            looper->removeFd(mChannel->getSendFd());
1482            mHasLooperCallbacks = false;
1483        }
1484        return;
1485    }
1486
1487    int looper_flags = 0;
1488    if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
1489    if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
1490    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1491        const int handle = mSensorInfo.keyAt(i);
1492        if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1493            looper_flags |= ALOOPER_EVENT_INPUT;
1494            break;
1495        }
1496    }
1497    // If flags is still set to zero, we don't need to add this fd to the Looper, if
1498    // the fd has already been added, remove it. This is likely to happen when ALL the
1499    // events stored in the cache have been sent to the corresponding app.
1500    if (looper_flags == 0) {
1501        if (mHasLooperCallbacks) {
1502            ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1503            looper->removeFd(mChannel->getSendFd());
1504            mHasLooperCallbacks = false;
1505        }
1506        return;
1507    }
1508    // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1509    // registered for wake-up sensors OR for sending events in the cache.
1510    int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1511    if (ret == 1) {
1512        ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1513        mHasLooperCallbacks = true;
1514    } else {
1515        ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1516    }
1517}
1518
1519void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1520    Mutex::Autolock _l(mConnectionLock);
1521    ssize_t index = mSensorInfo.indexOfKey(handle);
1522    if (index >= 0) {
1523        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1524        flushInfo.mPendingFlushEventsToSend++;
1525    }
1526}
1527
1528status_t SensorService::SensorEventConnection::sendEvents(
1529        sensors_event_t const* buffer, size_t numEvents,
1530        sensors_event_t* scratch,
1531        SensorEventConnection const * const * mapFlushEventsToConnections) {
1532    // filter out events not for this connection
1533    int count = 0;
1534    Mutex::Autolock _l(mConnectionLock);
1535    if (scratch) {
1536        size_t i=0;
1537        while (i<numEvents) {
1538            int32_t sensor_handle = buffer[i].sensor;
1539            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1540                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
1541                        buffer[i].meta_data.sensor);
1542                // Setting sensor_handle to the correct sensor to ensure the sensor events per
1543                // connection are filtered correctly.  buffer[i].sensor is zero for meta_data
1544                // events.
1545                sensor_handle = buffer[i].meta_data.sensor;
1546            }
1547            ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
1548            // Check if this connection has registered for this sensor. If not continue to the
1549            // next sensor_event.
1550            if (index < 0) {
1551                ++i;
1552                continue;
1553            }
1554
1555            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1556            // Check if there is a pending flush_complete event for this sensor on this connection.
1557            if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1558                    this == mapFlushEventsToConnections[i]) {
1559                flushInfo.mFirstFlushPending = false;
1560                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1561                        buffer[i].meta_data.sensor);
1562                ++i;
1563                continue;
1564            }
1565
1566            // If there is a pending flush complete event for this sensor on this connection,
1567            // ignore the event and proceed to the next.
1568            if (flushInfo.mFirstFlushPending) {
1569                ++i;
1570                continue;
1571            }
1572
1573            do {
1574                // Keep copying events into the scratch buffer as long as they are regular
1575                // sensor_events are from the same sensor_handle OR they are flush_complete_events
1576                // from the same sensor_handle AND the current connection is mapped to the
1577                // corresponding flush_complete_event.
1578                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1579                    if (this == mapFlushEventsToConnections[i]) {
1580                        scratch[count++] = buffer[i];
1581                    }
1582                    ++i;
1583                } else {
1584                    // Regular sensor event, just copy it to the scratch buffer.
1585                    scratch[count++] = buffer[i++];
1586                }
1587            } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1588                                        buffer[i].type != SENSOR_TYPE_META_DATA) ||
1589                                       (buffer[i].type == SENSOR_TYPE_META_DATA  &&
1590                                        buffer[i].meta_data.sensor == sensor_handle)));
1591        }
1592    } else {
1593        scratch = const_cast<sensors_event_t *>(buffer);
1594        count = numEvents;
1595    }
1596
1597    sendPendingFlushEventsLocked();
1598    // Early return if there are no events for this connection.
1599    if (count == 0) {
1600        return status_t(NO_ERROR);
1601    }
1602
1603#if DEBUG_CONNECTIONS
1604     mEventsReceived += count;
1605#endif
1606    if (mCacheSize != 0) {
1607        // There are some events in the cache which need to be sent first. Copy this buffer to
1608        // the end of cache.
1609        if (mCacheSize + count <= mMaxCacheSize) {
1610            memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1611            mCacheSize += count;
1612        } else {
1613            // Check if any new sensors have registered on this connection which may have increased
1614            // the max cache size that is desired.
1615            if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1616                reAllocateCacheLocked(scratch, count);
1617                return status_t(NO_ERROR);
1618            }
1619            // Some events need to be dropped.
1620            int remaningCacheSize = mMaxCacheSize - mCacheSize;
1621            if (remaningCacheSize != 0) {
1622                memcpy(&mEventCache[mCacheSize], scratch,
1623                                                remaningCacheSize * sizeof(sensors_event_t));
1624            }
1625            int numEventsDropped = count - remaningCacheSize;
1626            countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1627            // Drop the first "numEventsDropped" in the cache.
1628            memmove(mEventCache, &mEventCache[numEventsDropped],
1629                    (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1630
1631            // Copy the remainingEvents in scratch buffer to the end of cache.
1632            memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1633                                            numEventsDropped * sizeof(sensors_event_t));
1634        }
1635        return status_t(NO_ERROR);
1636    }
1637
1638    int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1639    if (index_wake_up_event >= 0) {
1640        scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1641        ++mWakeLockRefCount;
1642#if DEBUG_CONNECTIONS
1643        ++mTotalAcksNeeded;
1644#endif
1645    }
1646
1647    // NOTE: ASensorEvent and sensors_event_t are the same type.
1648    ssize_t size = SensorEventQueue::write(mChannel,
1649                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
1650    if (size < 0) {
1651        // Write error, copy events to local cache.
1652        if (index_wake_up_event >= 0) {
1653            // If there was a wake_up sensor_event, reset the flag.
1654            scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1655            if (mWakeLockRefCount > 0) {
1656                --mWakeLockRefCount;
1657            }
1658#if DEBUG_CONNECTIONS
1659            --mTotalAcksNeeded;
1660#endif
1661        }
1662        if (mEventCache == NULL) {
1663            mMaxCacheSize = computeMaxCacheSizeLocked();
1664            mEventCache = new sensors_event_t[mMaxCacheSize];
1665            mCacheSize = 0;
1666        }
1667        memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1668        mCacheSize += count;
1669
1670        // Add this file descriptor to the looper to get a callback when this fd is available for
1671        // writing.
1672        updateLooperRegistrationLocked(mService->getLooper());
1673        return size;
1674    }
1675
1676#if DEBUG_CONNECTIONS
1677    if (size > 0) {
1678        mEventsSent += count;
1679    }
1680#endif
1681
1682    return size < 0 ? status_t(size) : status_t(NO_ERROR);
1683}
1684
1685void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1686                                                                 int count) {
1687    sensors_event_t *eventCache_new;
1688    const int new_cache_size = computeMaxCacheSizeLocked();
1689    // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1690    eventCache_new = new sensors_event_t[new_cache_size];
1691    memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1692    memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1693
1694    ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1695            new_cache_size);
1696
1697    delete mEventCache;
1698    mEventCache = eventCache_new;
1699    mCacheSize += count;
1700    mMaxCacheSize = new_cache_size;
1701}
1702
1703void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1704    ASensorEvent flushCompleteEvent;
1705    memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
1706    flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
1707    // Loop through all the sensors for this connection and check if there are any pending
1708    // flush complete events to be sent.
1709    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1710        FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1711        while (flushInfo.mPendingFlushEventsToSend > 0) {
1712            const int sensor_handle = mSensorInfo.keyAt(i);
1713            flushCompleteEvent.meta_data.sensor = sensor_handle;
1714            bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1715            if (wakeUpSensor) {
1716               ++mWakeLockRefCount;
1717               flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1718            }
1719            ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1720            if (size < 0) {
1721                if (wakeUpSensor) --mWakeLockRefCount;
1722                return;
1723            }
1724            ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1725                    flushCompleteEvent.meta_data.sensor);
1726            flushInfo.mPendingFlushEventsToSend--;
1727        }
1728    }
1729}
1730
1731void SensorService::SensorEventConnection::writeToSocketFromCache() {
1732    // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1733    // half the size of the socket buffer allocated in BitTube whichever is smaller.
1734    const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1735            int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
1736    Mutex::Autolock _l(mConnectionLock);
1737    // Send pending flush complete events (if any)
1738    sendPendingFlushEventsLocked();
1739    for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
1740        const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
1741        int index_wake_up_event =
1742                  findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1743        if (index_wake_up_event >= 0) {
1744            mEventCache[index_wake_up_event + numEventsSent].flags |=
1745                    WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1746            ++mWakeLockRefCount;
1747#if DEBUG_CONNECTIONS
1748            ++mTotalAcksNeeded;
1749#endif
1750        }
1751
1752        ssize_t size = SensorEventQueue::write(mChannel,
1753                          reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
1754                          numEventsToWrite);
1755        if (size < 0) {
1756            if (index_wake_up_event >= 0) {
1757                // If there was a wake_up sensor_event, reset the flag.
1758                mEventCache[index_wake_up_event + numEventsSent].flags  &=
1759                        ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1760                if (mWakeLockRefCount > 0) {
1761                    --mWakeLockRefCount;
1762                }
1763#if DEBUG_CONNECTIONS
1764                --mTotalAcksNeeded;
1765#endif
1766            }
1767            memmove(mEventCache, &mEventCache[numEventsSent],
1768                                 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1769            ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
1770                    numEventsSent, mCacheSize);
1771            mCacheSize -= numEventsSent;
1772            return;
1773        }
1774        numEventsSent += numEventsToWrite;
1775#if DEBUG_CONNECTIONS
1776        mEventsSentFromCache += numEventsToWrite;
1777#endif
1778    }
1779    ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1780    // All events from the cache have been sent. Reset cache size to zero.
1781    mCacheSize = 0;
1782    // There are no more events in the cache. We don't need to poll for write on the fd.
1783    // Update Looper registration.
1784    updateLooperRegistrationLocked(mService->getLooper());
1785}
1786
1787void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
1788                sensors_event_t const* scratch, const int numEventsDropped) {
1789    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
1790    // Count flushComplete events in the events that are about to the dropped. These will be sent
1791    // separately before the next batch of events.
1792    for (int j = 0; j < numEventsDropped; ++j) {
1793        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1794            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1795            flushInfo.mPendingFlushEventsToSend++;
1796            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1797                     flushInfo.mPendingFlushEventsToSend);
1798        }
1799    }
1800    return;
1801}
1802
1803int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1804                       sensors_event_t const* scratch, const int count) {
1805    for (int i = 0; i < count; ++i) {
1806        if (mService->isWakeUpSensorEvent(scratch[i])) {
1807            return i;
1808        }
1809    }
1810    return -1;
1811}
1812
1813sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
1814{
1815    return mChannel;
1816}
1817
1818status_t SensorService::SensorEventConnection::enableDisable(
1819        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1820        int reservedFlags)
1821{
1822    status_t err;
1823    if (enabled) {
1824        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1825                               reservedFlags, mOpPackageName);
1826
1827    } else {
1828        err = mService->disable(this, handle);
1829    }
1830    return err;
1831}
1832
1833status_t SensorService::SensorEventConnection::setEventRate(
1834        int handle, nsecs_t samplingPeriodNs)
1835{
1836    return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
1837}
1838
1839status_t  SensorService::SensorEventConnection::flush() {
1840    return  mService->flushSensor(this, mOpPackageName);
1841}
1842
1843int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
1844    if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1845        {
1846            // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1847            // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1848            // can release the wake-lock.
1849            ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1850            Mutex::Autolock _l(mConnectionLock);
1851            mDead = true;
1852            mWakeLockRefCount = 0;
1853            updateLooperRegistrationLocked(mService->getLooper());
1854        }
1855        mService->checkWakeLockState();
1856        if (mDataInjectionMode) {
1857            // If the Looper has encountered some error in data injection mode, reset SensorService
1858            // back to normal mode.
1859            mService->resetToNormalMode();
1860            mDataInjectionMode = false;
1861        }
1862        return 1;
1863    }
1864
1865    if (events & ALOOPER_EVENT_INPUT) {
1866        unsigned char buf[sizeof(sensors_event_t)];
1867        ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
1868        {
1869           Mutex::Autolock _l(mConnectionLock);
1870           if (numBytesRead == sizeof(sensors_event_t)) {
1871               if (!mDataInjectionMode) {
1872                   ALOGE("Data injected in normal mode, dropping event"
1873                         "package=%s uid=%d", mPackageName.string(), mUid);
1874                   // Unregister call backs.
1875                   return 0;
1876               }
1877               SensorDevice& dev(SensorDevice::getInstance());
1878               sensors_event_t sensor_event;
1879               memset(&sensor_event, 0, sizeof(sensor_event));
1880               memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1881               Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1882               sensor_event.type = sensor.getType();
1883               dev.injectSensorData(&sensor_event);
1884#if DEBUG_CONNECTIONS
1885               ++mEventsReceived;
1886#endif
1887           } else if (numBytesRead == sizeof(uint32_t)) {
1888               uint32_t numAcks = 0;
1889               memcpy(&numAcks, buf, numBytesRead);
1890               // Sanity check to ensure  there are no read errors in recv, numAcks is always
1891               // within the range and not zero. If any of the above don't hold reset
1892               // mWakeLockRefCount to zero.
1893               if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1894                   mWakeLockRefCount -= numAcks;
1895               } else {
1896                   mWakeLockRefCount = 0;
1897               }
1898#if DEBUG_CONNECTIONS
1899               mTotalAcksReceived += numAcks;
1900#endif
1901           } else {
1902               // Read error, reset wakelock refcount.
1903               mWakeLockRefCount = 0;
1904           }
1905        }
1906        // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1907        // here as checkWakeLockState() will need it.
1908        if (mWakeLockRefCount == 0) {
1909            mService->checkWakeLockState();
1910        }
1911        // continue getting callbacks.
1912        return 1;
1913    }
1914
1915    if (events & ALOOPER_EVENT_OUTPUT) {
1916        // send sensor data that is stored in mEventCache for this connection.
1917        mService->sendEventsFromCache(this);
1918    }
1919    return 1;
1920}
1921
1922int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1923    size_t fifoWakeUpSensors = 0;
1924    size_t fifoNonWakeUpSensors = 0;
1925    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1926        const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1927        if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1928            // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1929            // non wake_up sensors.
1930            if (sensor.isWakeUpSensor()) {
1931                fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1932            } else {
1933                fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1934            }
1935        } else {
1936            // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1937            if (sensor.isWakeUpSensor()) {
1938                fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1939                                          fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1940
1941            } else {
1942                fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1943                                          fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1944
1945            }
1946        }
1947   }
1948   if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1949       // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
1950       // size that is equal to that of the batch mode.
1951       // ALOGW("Write failure in non-batch mode");
1952       return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
1953   }
1954   return fifoWakeUpSensors + fifoNonWakeUpSensors;
1955}
1956
1957// ---------------------------------------------------------------------------
1958}; // namespace android
1959
1960