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