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 <sys/socket.h>
18#include <utils/threads.h>
19
20#include <sensor/SensorEventQueue.h>
21
22#include "vec.h"
23#include "SensorEventConnection.h"
24#include "SensorDevice.h"
25
26#define UNUSED(x) (void)(x)
27
28namespace android {
29
30SensorService::SensorEventConnection::SensorEventConnection(
31        const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
32        const String16& opPackageName)
33    : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
34      mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
35      mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName),
36      mDestroyed(false) {
37    mChannel = new BitTube(mService->mSocketBufferSize);
38#if DEBUG_CONNECTIONS
39    mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
40    mTotalAcksNeeded = mTotalAcksReceived = 0;
41#endif
42}
43
44SensorService::SensorEventConnection::~SensorEventConnection() {
45    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
46    destroy();
47}
48
49void SensorService::SensorEventConnection::destroy() {
50    Mutex::Autolock _l(mDestroyLock);
51
52    // destroy once only
53    if (mDestroyed) {
54        return;
55    }
56
57    mService->cleanupConnection(this);
58    if (mEventCache != NULL) {
59        delete mEventCache;
60    }
61    mDestroyed = true;
62}
63
64void SensorService::SensorEventConnection::onFirstRef() {
65    LooperCallback::onFirstRef();
66}
67
68bool SensorService::SensorEventConnection::needsWakeLock() {
69    Mutex::Autolock _l(mConnectionLock);
70    return !mDead && mWakeLockRefCount > 0;
71}
72
73void SensorService::SensorEventConnection::resetWakeLockRefCount() {
74    Mutex::Autolock _l(mConnectionLock);
75    mWakeLockRefCount = 0;
76}
77
78void SensorService::SensorEventConnection::dump(String8& result) {
79    Mutex::Autolock _l(mConnectionLock);
80    result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
81    result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
82            "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
83            mMaxCacheSize);
84    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
85        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
86        result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
87                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
88                            mSensorInfo.keyAt(i),
89                            flushInfo.mFirstFlushPending ? "First flush pending" :
90                                                           "active",
91                            flushInfo.mPendingFlushEventsToSend);
92    }
93#if DEBUG_CONNECTIONS
94    result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
95            " total_acks_needed %d | total_acks_recvd %d\n",
96            mEventsReceived,
97            mEventsSent,
98            mEventsSentFromCache,
99            mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
100            mTotalAcksNeeded,
101            mTotalAcksReceived);
102#endif
103}
104
105bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
106    Mutex::Autolock _l(mConnectionLock);
107    sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
108    if (si == nullptr ||
109        !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
110        mSensorInfo.indexOfKey(handle) >= 0) {
111        return false;
112    }
113    mSensorInfo.add(handle, FlushInfo());
114    return true;
115}
116
117bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
118    Mutex::Autolock _l(mConnectionLock);
119    if (mSensorInfo.removeItem(handle) >= 0) {
120        return true;
121    }
122    return false;
123}
124
125bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
126    Mutex::Autolock _l(mConnectionLock);
127    return mSensorInfo.indexOfKey(handle) >= 0;
128}
129
130bool SensorService::SensorEventConnection::hasAnySensor() const {
131    Mutex::Autolock _l(mConnectionLock);
132    return mSensorInfo.size() ? true : false;
133}
134
135bool SensorService::SensorEventConnection::hasOneShotSensors() const {
136    Mutex::Autolock _l(mConnectionLock);
137    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
138        const int handle = mSensorInfo.keyAt(i);
139        sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
140        if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
141            return true;
142        }
143    }
144    return false;
145}
146
147String8 SensorService::SensorEventConnection::getPackageName() const {
148    return mPackageName;
149}
150
151void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
152                                bool value) {
153    Mutex::Autolock _l(mConnectionLock);
154    ssize_t index = mSensorInfo.indexOfKey(handle);
155    if (index >= 0) {
156        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
157        flushInfo.mFirstFlushPending = value;
158    }
159}
160
161void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
162    Mutex::Autolock _l(mConnectionLock);
163    updateLooperRegistrationLocked(looper);
164}
165
166void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
167        const sp<Looper>& looper) {
168    bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
169                              mDataInjectionMode;
170    // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
171    // the Looper if it has been previously added.
172    if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
173        ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
174                 mChannel->getSendFd());
175        looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
176    return; }
177
178    int looper_flags = 0;
179    if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
180    if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
181    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
182        const int handle = mSensorInfo.keyAt(i);
183        sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
184        if (si != nullptr && si->getSensor().isWakeUpSensor()) {
185            looper_flags |= ALOOPER_EVENT_INPUT;
186        }
187    }
188
189    // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
190    // already been added, remove it. This is likely to happen when ALL the events stored in the
191    // cache have been sent to the corresponding app.
192    if (looper_flags == 0) {
193        if (mHasLooperCallbacks) {
194            ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
195            looper->removeFd(mChannel->getSendFd());
196            mHasLooperCallbacks = false;
197        }
198        return;
199    }
200
201    // Add the file descriptor to the Looper for receiving acknowledegments if the app has
202    // registered for wake-up sensors OR for sending events in the cache.
203    int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
204    if (ret == 1) {
205        ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
206        mHasLooperCallbacks = true;
207    } else {
208        ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
209    }
210}
211
212void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
213    Mutex::Autolock _l(mConnectionLock);
214    ssize_t index = mSensorInfo.indexOfKey(handle);
215    if (index >= 0) {
216        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
217        flushInfo.mPendingFlushEventsToSend++;
218    }
219}
220
221status_t SensorService::SensorEventConnection::sendEvents(
222        sensors_event_t const* buffer, size_t numEvents,
223        sensors_event_t* scratch,
224        wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
225    // filter out events not for this connection
226    int count = 0;
227    Mutex::Autolock _l(mConnectionLock);
228    if (scratch) {
229        size_t i=0;
230        while (i<numEvents) {
231            int32_t sensor_handle = buffer[i].sensor;
232            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
233                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
234                        buffer[i].meta_data.sensor);
235                // Setting sensor_handle to the correct sensor to ensure the sensor events per
236                // connection are filtered correctly.  buffer[i].sensor is zero for meta_data
237                // events.
238                sensor_handle = buffer[i].meta_data.sensor;
239            }
240
241            ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
242            // Check if this connection has registered for this sensor. If not continue to the
243            // next sensor_event.
244            if (index < 0) {
245                ++i;
246                continue;
247            }
248
249            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
250            // Check if there is a pending flush_complete event for this sensor on this connection.
251            if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
252                    mapFlushEventsToConnections[i] == this) {
253                flushInfo.mFirstFlushPending = false;
254                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
255                        buffer[i].meta_data.sensor);
256                ++i;
257                continue;
258            }
259
260            // If there is a pending flush complete event for this sensor on this connection,
261            // ignore the event and proceed to the next.
262            if (flushInfo.mFirstFlushPending) {
263                ++i;
264                continue;
265            }
266
267            do {
268                // Keep copying events into the scratch buffer as long as they are regular
269                // sensor_events are from the same sensor_handle OR they are flush_complete_events
270                // from the same sensor_handle AND the current connection is mapped to the
271                // corresponding flush_complete_event.
272                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
273                    if (mapFlushEventsToConnections[i] == this) {
274                        scratch[count++] = buffer[i];
275                    }
276                    ++i;
277                } else {
278                    // Regular sensor event, just copy it to the scratch buffer.
279                    scratch[count++] = buffer[i++];
280                }
281            } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
282                                        buffer[i].type != SENSOR_TYPE_META_DATA) ||
283                                       (buffer[i].type == SENSOR_TYPE_META_DATA  &&
284                                        buffer[i].meta_data.sensor == sensor_handle)));
285        }
286    } else {
287        scratch = const_cast<sensors_event_t *>(buffer);
288        count = numEvents;
289    }
290
291    sendPendingFlushEventsLocked();
292    // Early return if there are no events for this connection.
293    if (count == 0) {
294        return status_t(NO_ERROR);
295    }
296
297#if DEBUG_CONNECTIONS
298     mEventsReceived += count;
299#endif
300    if (mCacheSize != 0) {
301        // There are some events in the cache which need to be sent first. Copy this buffer to
302        // the end of cache.
303        if (mCacheSize + count <= mMaxCacheSize) {
304            memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
305            mCacheSize += count;
306        } else {
307            // Check if any new sensors have registered on this connection which may have increased
308            // the max cache size that is desired.
309            if (mCacheSize + count < computeMaxCacheSizeLocked()) {
310                reAllocateCacheLocked(scratch, count);
311                return status_t(NO_ERROR);
312            }
313            // Some events need to be dropped.
314            int remaningCacheSize = mMaxCacheSize - mCacheSize;
315            if (remaningCacheSize != 0) {
316                memcpy(&mEventCache[mCacheSize], scratch,
317                                                remaningCacheSize * sizeof(sensors_event_t));
318            }
319            int numEventsDropped = count - remaningCacheSize;
320            countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
321            // Drop the first "numEventsDropped" in the cache.
322            memmove(mEventCache, &mEventCache[numEventsDropped],
323                    (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
324
325            // Copy the remainingEvents in scratch buffer to the end of cache.
326            memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
327                                            numEventsDropped * sizeof(sensors_event_t));
328        }
329        return status_t(NO_ERROR);
330    }
331
332    int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
333    if (index_wake_up_event >= 0) {
334        scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
335        ++mWakeLockRefCount;
336#if DEBUG_CONNECTIONS
337        ++mTotalAcksNeeded;
338#endif
339    }
340
341    // NOTE: ASensorEvent and sensors_event_t are the same type.
342    ssize_t size = SensorEventQueue::write(mChannel,
343                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
344    if (size < 0) {
345        // Write error, copy events to local cache.
346        if (index_wake_up_event >= 0) {
347            // If there was a wake_up sensor_event, reset the flag.
348            scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
349            if (mWakeLockRefCount > 0) {
350                --mWakeLockRefCount;
351            }
352#if DEBUG_CONNECTIONS
353            --mTotalAcksNeeded;
354#endif
355        }
356        if (mEventCache == NULL) {
357            mMaxCacheSize = computeMaxCacheSizeLocked();
358            mEventCache = new sensors_event_t[mMaxCacheSize];
359            mCacheSize = 0;
360        }
361        memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
362        mCacheSize += count;
363
364        // Add this file descriptor to the looper to get a callback when this fd is available for
365        // writing.
366        updateLooperRegistrationLocked(mService->getLooper());
367        return size;
368    }
369
370#if DEBUG_CONNECTIONS
371    if (size > 0) {
372        mEventsSent += count;
373    }
374#endif
375
376    return size < 0 ? status_t(size) : status_t(NO_ERROR);
377}
378
379void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
380                                                                 int count) {
381    sensors_event_t *eventCache_new;
382    const int new_cache_size = computeMaxCacheSizeLocked();
383    // Allocate new cache, copy over events from the old cache & scratch, free up memory.
384    eventCache_new = new sensors_event_t[new_cache_size];
385    memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
386    memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
387
388    ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
389            new_cache_size);
390
391    delete mEventCache;
392    mEventCache = eventCache_new;
393    mCacheSize += count;
394    mMaxCacheSize = new_cache_size;
395}
396
397void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
398    ASensorEvent flushCompleteEvent;
399    memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
400    flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
401    // Loop through all the sensors for this connection and check if there are any pending
402    // flush complete events to be sent.
403    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
404        const int handle = mSensorInfo.keyAt(i);
405        sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
406        if (si == nullptr) {
407            continue;
408        }
409
410        FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
411        while (flushInfo.mPendingFlushEventsToSend > 0) {
412            flushCompleteEvent.meta_data.sensor = handle;
413            bool wakeUpSensor = si->getSensor().isWakeUpSensor();
414            if (wakeUpSensor) {
415               ++mWakeLockRefCount;
416               flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
417            }
418            ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
419            if (size < 0) {
420                if (wakeUpSensor) --mWakeLockRefCount;
421                return;
422            }
423            ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
424                    flushCompleteEvent.meta_data.sensor);
425            flushInfo.mPendingFlushEventsToSend--;
426        }
427    }
428}
429
430void SensorService::SensorEventConnection::writeToSocketFromCache() {
431    // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
432    // half the size of the socket buffer allocated in BitTube whichever is smaller.
433    const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
434            int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
435    Mutex::Autolock _l(mConnectionLock);
436    // Send pending flush complete events (if any)
437    sendPendingFlushEventsLocked();
438    for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
439        const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
440        int index_wake_up_event =
441                  findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
442        if (index_wake_up_event >= 0) {
443            mEventCache[index_wake_up_event + numEventsSent].flags |=
444                    WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
445            ++mWakeLockRefCount;
446#if DEBUG_CONNECTIONS
447            ++mTotalAcksNeeded;
448#endif
449        }
450
451        ssize_t size = SensorEventQueue::write(mChannel,
452                          reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
453                          numEventsToWrite);
454        if (size < 0) {
455            if (index_wake_up_event >= 0) {
456                // If there was a wake_up sensor_event, reset the flag.
457                mEventCache[index_wake_up_event + numEventsSent].flags  &=
458                        ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
459                if (mWakeLockRefCount > 0) {
460                    --mWakeLockRefCount;
461                }
462#if DEBUG_CONNECTIONS
463                --mTotalAcksNeeded;
464#endif
465            }
466            memmove(mEventCache, &mEventCache[numEventsSent],
467                                 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
468            ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
469                    numEventsSent, mCacheSize);
470            mCacheSize -= numEventsSent;
471            return;
472        }
473        numEventsSent += numEventsToWrite;
474#if DEBUG_CONNECTIONS
475        mEventsSentFromCache += numEventsToWrite;
476#endif
477    }
478    ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
479    // All events from the cache have been sent. Reset cache size to zero.
480    mCacheSize = 0;
481    // There are no more events in the cache. We don't need to poll for write on the fd.
482    // Update Looper registration.
483    updateLooperRegistrationLocked(mService->getLooper());
484}
485
486void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
487                sensors_event_t const* scratch, const int numEventsDropped) {
488    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
489    // Count flushComplete events in the events that are about to the dropped. These will be sent
490    // separately before the next batch of events.
491    for (int j = 0; j < numEventsDropped; ++j) {
492        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
493            ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
494            if (index < 0) {
495                ALOGW("%s: sensor 0x%x is not found in connection",
496                      __func__, scratch[j].meta_data.sensor);
497                continue;
498            }
499
500            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
501            flushInfo.mPendingFlushEventsToSend++;
502            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
503                     flushInfo.mPendingFlushEventsToSend);
504        }
505    }
506    return;
507}
508
509int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
510                       sensors_event_t const* scratch, const int count) {
511    for (int i = 0; i < count; ++i) {
512        if (mService->isWakeUpSensorEvent(scratch[i])) {
513            return i;
514        }
515    }
516    return -1;
517}
518
519sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
520{
521    return mChannel;
522}
523
524status_t SensorService::SensorEventConnection::enableDisable(
525        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
526        int reservedFlags)
527{
528    status_t err;
529    if (enabled) {
530        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
531                               reservedFlags, mOpPackageName);
532
533    } else {
534        err = mService->disable(this, handle);
535    }
536    return err;
537}
538
539status_t SensorService::SensorEventConnection::setEventRate(
540        int handle, nsecs_t samplingPeriodNs)
541{
542    return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
543}
544
545status_t  SensorService::SensorEventConnection::flush() {
546    return  mService->flushSensor(this, mOpPackageName);
547}
548
549int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
550    // SensorEventConnection does not support configureChannel, parameters not used
551    UNUSED(handle);
552    UNUSED(rateLevel);
553    return INVALID_OPERATION;
554}
555
556int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
557    if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
558        {
559            // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
560            // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
561            // can release the wake-lock.
562            ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
563            Mutex::Autolock _l(mConnectionLock);
564            mDead = true;
565            mWakeLockRefCount = 0;
566            updateLooperRegistrationLocked(mService->getLooper());
567        }
568        mService->checkWakeLockState();
569        if (mDataInjectionMode) {
570            // If the Looper has encountered some error in data injection mode, reset SensorService
571            // back to normal mode.
572            mService->resetToNormalMode();
573            mDataInjectionMode = false;
574        }
575        return 1;
576    }
577
578    if (events & ALOOPER_EVENT_INPUT) {
579        unsigned char buf[sizeof(sensors_event_t)];
580        ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
581        {
582            Mutex::Autolock _l(mConnectionLock);
583            if (numBytesRead == sizeof(sensors_event_t)) {
584                if (!mDataInjectionMode) {
585                    ALOGE("Data injected in normal mode, dropping event"
586                          "package=%s uid=%d", mPackageName.string(), mUid);
587                    // Unregister call backs.
588                    return 0;
589                }
590                sensors_event_t sensor_event;
591                memcpy(&sensor_event, buf, sizeof(sensors_event_t));
592                sp<SensorInterface> si =
593                        mService->getSensorInterfaceFromHandle(sensor_event.sensor);
594                if (si == nullptr) {
595                    return 1;
596                }
597
598                SensorDevice& dev(SensorDevice::getInstance());
599                sensor_event.type = si->getSensor().getType();
600                dev.injectSensorData(&sensor_event);
601#if DEBUG_CONNECTIONS
602                ++mEventsReceived;
603#endif
604            } else if (numBytesRead == sizeof(uint32_t)) {
605                uint32_t numAcks = 0;
606                memcpy(&numAcks, buf, numBytesRead);
607                // Sanity check to ensure  there are no read errors in recv, numAcks is always
608                // within the range and not zero. If any of the above don't hold reset
609                // mWakeLockRefCount to zero.
610                if (numAcks > 0 && numAcks < mWakeLockRefCount) {
611                    mWakeLockRefCount -= numAcks;
612                } else {
613                    mWakeLockRefCount = 0;
614                }
615#if DEBUG_CONNECTIONS
616                mTotalAcksReceived += numAcks;
617#endif
618           } else {
619               // Read error, reset wakelock refcount.
620               mWakeLockRefCount = 0;
621           }
622        }
623        // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
624        // here as checkWakeLockState() will need it.
625        if (mWakeLockRefCount == 0) {
626            mService->checkWakeLockState();
627        }
628        // continue getting callbacks.
629        return 1;
630    }
631
632    if (events & ALOOPER_EVENT_OUTPUT) {
633        // send sensor data that is stored in mEventCache for this connection.
634        mService->sendEventsFromCache(this);
635    }
636    return 1;
637}
638
639int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
640    size_t fifoWakeUpSensors = 0;
641    size_t fifoNonWakeUpSensors = 0;
642    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
643        sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
644        if (si == nullptr) {
645            continue;
646        }
647        const Sensor& sensor = si->getSensor();
648        if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
649            // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
650            // non wake_up sensors.
651            if (sensor.isWakeUpSensor()) {
652                fifoWakeUpSensors += sensor.getFifoReservedEventCount();
653            } else {
654                fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
655            }
656        } else {
657            // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
658            if (sensor.isWakeUpSensor()) {
659                fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
660                                          fifoWakeUpSensors : sensor.getFifoMaxEventCount();
661
662            } else {
663                fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
664                                          fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
665
666            }
667        }
668   }
669   if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
670       // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
671       // size that is equal to that of the batch mode.
672       // ALOGW("Write failure in non-batch mode");
673       return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
674   }
675   return fifoWakeUpSensors + fifoNonWakeUpSensors;
676}
677
678} // namespace android
679
680