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