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