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, bool hasSensorAccess)
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), mHasSensorAccess(hasSensorAccess) {
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
227    sensors_event_t* sanitizedBuffer = nullptr;
228
229    int count = 0;
230    Mutex::Autolock _l(mConnectionLock);
231    if (scratch) {
232        size_t i=0;
233        while (i<numEvents) {
234            int32_t sensor_handle = buffer[i].sensor;
235            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
236                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
237                        buffer[i].meta_data.sensor);
238                // Setting sensor_handle to the correct sensor to ensure the sensor events per
239                // connection are filtered correctly.  buffer[i].sensor is zero for meta_data
240                // events.
241                sensor_handle = buffer[i].meta_data.sensor;
242            }
243
244            ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
245            // Check if this connection has registered for this sensor. If not continue to the
246            // next sensor_event.
247            if (index < 0) {
248                ++i;
249                continue;
250            }
251
252            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
253            // Check if there is a pending flush_complete event for this sensor on this connection.
254            if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
255                    mapFlushEventsToConnections[i] == this) {
256                flushInfo.mFirstFlushPending = false;
257                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
258                        buffer[i].meta_data.sensor);
259                ++i;
260                continue;
261            }
262
263            // If there is a pending flush complete event for this sensor on this connection,
264            // ignore the event and proceed to the next.
265            if (flushInfo.mFirstFlushPending) {
266                ++i;
267                continue;
268            }
269
270            do {
271                // Keep copying events into the scratch buffer as long as they are regular
272                // sensor_events are from the same sensor_handle OR they are flush_complete_events
273                // from the same sensor_handle AND the current connection is mapped to the
274                // corresponding flush_complete_event.
275                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
276                    if (mapFlushEventsToConnections[i] == this) {
277                        scratch[count++] = buffer[i];
278                    }
279                } else {
280                    // Regular sensor event, just copy it to the scratch buffer.
281                    if (mHasSensorAccess) {
282                        scratch[count++] = buffer[i];
283                    }
284                }
285                i++;
286            } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
287                                        buffer[i].type != SENSOR_TYPE_META_DATA) ||
288                                       (buffer[i].type == SENSOR_TYPE_META_DATA  &&
289                                        buffer[i].meta_data.sensor == sensor_handle)));
290        }
291    } else {
292        if (mHasSensorAccess) {
293            scratch = const_cast<sensors_event_t *>(buffer);
294            count = numEvents;
295        } else {
296            scratch = sanitizedBuffer = new sensors_event_t[numEvents];
297            for (size_t i = 0; i < numEvents; i++) {
298                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
299                    scratch[count++] = buffer[i++];
300                }
301            }
302        }
303    }
304
305    sendPendingFlushEventsLocked();
306    // Early return if there are no events for this connection.
307    if (count == 0) {
308        delete sanitizedBuffer;
309        return status_t(NO_ERROR);
310    }
311
312#if DEBUG_CONNECTIONS
313     mEventsReceived += count;
314#endif
315    if (mCacheSize != 0) {
316        // There are some events in the cache which need to be sent first. Copy this buffer to
317        // the end of cache.
318        if (mCacheSize + count <= mMaxCacheSize) {
319            memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
320            mCacheSize += count;
321        } else {
322            // Check if any new sensors have registered on this connection which may have increased
323            // the max cache size that is desired.
324            if (mCacheSize + count < computeMaxCacheSizeLocked()) {
325                reAllocateCacheLocked(scratch, count);
326                delete sanitizedBuffer;
327                return status_t(NO_ERROR);
328            }
329            // Some events need to be dropped.
330            int remaningCacheSize = mMaxCacheSize - mCacheSize;
331            if (remaningCacheSize != 0) {
332                memcpy(&mEventCache[mCacheSize], scratch,
333                                                remaningCacheSize * sizeof(sensors_event_t));
334            }
335            int numEventsDropped = count - remaningCacheSize;
336            countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
337            // Drop the first "numEventsDropped" in the cache.
338            memmove(mEventCache, &mEventCache[numEventsDropped],
339                    (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
340
341            // Copy the remainingEvents in scratch buffer to the end of cache.
342            memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
343                                            numEventsDropped * sizeof(sensors_event_t));
344        }
345        delete sanitizedBuffer;
346        return status_t(NO_ERROR);
347    }
348
349    int index_wake_up_event = -1;
350    if (mHasSensorAccess) {
351        index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
352        if (index_wake_up_event >= 0) {
353            scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
354            ++mWakeLockRefCount;
355#if DEBUG_CONNECTIONS
356            ++mTotalAcksNeeded;
357#endif
358        }
359    }
360
361    // NOTE: ASensorEvent and sensors_event_t are the same type.
362    ssize_t size = SensorEventQueue::write(mChannel,
363                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
364    if (size < 0) {
365        // Write error, copy events to local cache.
366        if (index_wake_up_event >= 0) {
367            // If there was a wake_up sensor_event, reset the flag.
368            scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
369            if (mWakeLockRefCount > 0) {
370                --mWakeLockRefCount;
371            }
372#if DEBUG_CONNECTIONS
373            --mTotalAcksNeeded;
374#endif
375        }
376        if (mEventCache == NULL) {
377            mMaxCacheSize = computeMaxCacheSizeLocked();
378            mEventCache = new sensors_event_t[mMaxCacheSize];
379            mCacheSize = 0;
380        }
381        memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
382        mCacheSize += count;
383
384        // Add this file descriptor to the looper to get a callback when this fd is available for
385        // writing.
386        updateLooperRegistrationLocked(mService->getLooper());
387        delete sanitizedBuffer;
388        return size;
389    }
390
391#if DEBUG_CONNECTIONS
392    if (size > 0) {
393        mEventsSent += count;
394    }
395#endif
396
397    delete sanitizedBuffer;
398    return size < 0 ? status_t(size) : status_t(NO_ERROR);
399}
400
401void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
402    Mutex::Autolock _l(mConnectionLock);
403    mHasSensorAccess = hasAccess;
404}
405
406void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
407                                                                 int count) {
408    sensors_event_t *eventCache_new;
409    const int new_cache_size = computeMaxCacheSizeLocked();
410    // Allocate new cache, copy over events from the old cache & scratch, free up memory.
411    eventCache_new = new sensors_event_t[new_cache_size];
412    memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
413    memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
414
415    ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
416            new_cache_size);
417
418    delete mEventCache;
419    mEventCache = eventCache_new;
420    mCacheSize += count;
421    mMaxCacheSize = new_cache_size;
422}
423
424void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
425    ASensorEvent flushCompleteEvent;
426    memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
427    flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
428    // Loop through all the sensors for this connection and check if there are any pending
429    // flush complete events to be sent.
430    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
431        const int handle = mSensorInfo.keyAt(i);
432        sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
433        if (si == nullptr) {
434            continue;
435        }
436
437        FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
438        while (flushInfo.mPendingFlushEventsToSend > 0) {
439            flushCompleteEvent.meta_data.sensor = handle;
440            bool wakeUpSensor = si->getSensor().isWakeUpSensor();
441            if (wakeUpSensor) {
442               ++mWakeLockRefCount;
443               flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
444            }
445            ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
446            if (size < 0) {
447                if (wakeUpSensor) --mWakeLockRefCount;
448                return;
449            }
450            ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
451                    flushCompleteEvent.meta_data.sensor);
452            flushInfo.mPendingFlushEventsToSend--;
453        }
454    }
455}
456
457void SensorService::SensorEventConnection::writeToSocketFromCache() {
458    // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
459    // half the size of the socket buffer allocated in BitTube whichever is smaller.
460    const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
461            int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
462    Mutex::Autolock _l(mConnectionLock);
463    // Send pending flush complete events (if any)
464    sendPendingFlushEventsLocked();
465    for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
466        const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
467        int index_wake_up_event = -1;
468        if (mHasSensorAccess) {
469            index_wake_up_event =
470                      findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
471            if (index_wake_up_event >= 0) {
472                mEventCache[index_wake_up_event + numEventsSent].flags |=
473                        WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
474                ++mWakeLockRefCount;
475#if DEBUG_CONNECTIONS
476                ++mTotalAcksNeeded;
477#endif
478            }
479        }
480
481        ssize_t size = SensorEventQueue::write(mChannel,
482                          reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
483                          numEventsToWrite);
484        if (size < 0) {
485            if (index_wake_up_event >= 0) {
486                // If there was a wake_up sensor_event, reset the flag.
487                mEventCache[index_wake_up_event + numEventsSent].flags  &=
488                        ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
489                if (mWakeLockRefCount > 0) {
490                    --mWakeLockRefCount;
491                }
492#if DEBUG_CONNECTIONS
493                --mTotalAcksNeeded;
494#endif
495            }
496            memmove(mEventCache, &mEventCache[numEventsSent],
497                                 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
498            ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
499                    numEventsSent, mCacheSize);
500            mCacheSize -= numEventsSent;
501            return;
502        }
503        numEventsSent += numEventsToWrite;
504#if DEBUG_CONNECTIONS
505        mEventsSentFromCache += numEventsToWrite;
506#endif
507    }
508    ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
509    // All events from the cache have been sent. Reset cache size to zero.
510    mCacheSize = 0;
511    // There are no more events in the cache. We don't need to poll for write on the fd.
512    // Update Looper registration.
513    updateLooperRegistrationLocked(mService->getLooper());
514}
515
516void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
517                sensors_event_t const* scratch, const int numEventsDropped) {
518    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
519    // Count flushComplete events in the events that are about to the dropped. These will be sent
520    // separately before the next batch of events.
521    for (int j = 0; j < numEventsDropped; ++j) {
522        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
523            ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
524            if (index < 0) {
525                ALOGW("%s: sensor 0x%x is not found in connection",
526                      __func__, scratch[j].meta_data.sensor);
527                continue;
528            }
529
530            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
531            flushInfo.mPendingFlushEventsToSend++;
532            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
533                     flushInfo.mPendingFlushEventsToSend);
534        }
535    }
536    return;
537}
538
539int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
540                       sensors_event_t const* scratch, const int count) {
541    for (int i = 0; i < count; ++i) {
542        if (mService->isWakeUpSensorEvent(scratch[i])) {
543            return i;
544        }
545    }
546    return -1;
547}
548
549sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
550{
551    return mChannel;
552}
553
554status_t SensorService::SensorEventConnection::enableDisable(
555        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
556        int reservedFlags)
557{
558    status_t err;
559    if (enabled) {
560        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
561                               reservedFlags, mOpPackageName);
562
563    } else {
564        err = mService->disable(this, handle);
565    }
566    return err;
567}
568
569status_t SensorService::SensorEventConnection::setEventRate(
570        int handle, nsecs_t samplingPeriodNs)
571{
572    return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
573}
574
575status_t  SensorService::SensorEventConnection::flush() {
576    return  mService->flushSensor(this, mOpPackageName);
577}
578
579int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
580    // SensorEventConnection does not support configureChannel, parameters not used
581    UNUSED(handle);
582    UNUSED(rateLevel);
583    return INVALID_OPERATION;
584}
585
586int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
587    if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
588        {
589            // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
590            // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
591            // can release the wake-lock.
592            ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
593            Mutex::Autolock _l(mConnectionLock);
594            mDead = true;
595            mWakeLockRefCount = 0;
596            updateLooperRegistrationLocked(mService->getLooper());
597        }
598        mService->checkWakeLockState();
599        if (mDataInjectionMode) {
600            // If the Looper has encountered some error in data injection mode, reset SensorService
601            // back to normal mode.
602            mService->resetToNormalMode();
603            mDataInjectionMode = false;
604        }
605        return 1;
606    }
607
608    if (events & ALOOPER_EVENT_INPUT) {
609        unsigned char buf[sizeof(sensors_event_t)];
610        ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
611        {
612            Mutex::Autolock _l(mConnectionLock);
613            if (numBytesRead == sizeof(sensors_event_t)) {
614                if (!mDataInjectionMode) {
615                    ALOGE("Data injected in normal mode, dropping event"
616                          "package=%s uid=%d", mPackageName.string(), mUid);
617                    // Unregister call backs.
618                    return 0;
619                }
620                sensors_event_t sensor_event;
621                memcpy(&sensor_event, buf, sizeof(sensors_event_t));
622                sp<SensorInterface> si =
623                        mService->getSensorInterfaceFromHandle(sensor_event.sensor);
624                if (si == nullptr) {
625                    return 1;
626                }
627
628                SensorDevice& dev(SensorDevice::getInstance());
629                sensor_event.type = si->getSensor().getType();
630                dev.injectSensorData(&sensor_event);
631#if DEBUG_CONNECTIONS
632                ++mEventsReceived;
633#endif
634            } else if (numBytesRead == sizeof(uint32_t)) {
635                uint32_t numAcks = 0;
636                memcpy(&numAcks, buf, numBytesRead);
637                // Sanity check to ensure  there are no read errors in recv, numAcks is always
638                // within the range and not zero. If any of the above don't hold reset
639                // mWakeLockRefCount to zero.
640                if (numAcks > 0 && numAcks < mWakeLockRefCount) {
641                    mWakeLockRefCount -= numAcks;
642                } else {
643                    mWakeLockRefCount = 0;
644                }
645#if DEBUG_CONNECTIONS
646                mTotalAcksReceived += numAcks;
647#endif
648           } else {
649               // Read error, reset wakelock refcount.
650               mWakeLockRefCount = 0;
651           }
652        }
653        // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
654        // here as checkWakeLockState() will need it.
655        if (mWakeLockRefCount == 0) {
656            mService->checkWakeLockState();
657        }
658        // continue getting callbacks.
659        return 1;
660    }
661
662    if (events & ALOOPER_EVENT_OUTPUT) {
663        // send sensor data that is stored in mEventCache for this connection.
664        mService->sendEventsFromCache(this);
665    }
666    return 1;
667}
668
669int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
670    size_t fifoWakeUpSensors = 0;
671    size_t fifoNonWakeUpSensors = 0;
672    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
673        sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
674        if (si == nullptr) {
675            continue;
676        }
677        const Sensor& sensor = si->getSensor();
678        if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
679            // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
680            // non wake_up sensors.
681            if (sensor.isWakeUpSensor()) {
682                fifoWakeUpSensors += sensor.getFifoReservedEventCount();
683            } else {
684                fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
685            }
686        } else {
687            // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
688            if (sensor.isWakeUpSensor()) {
689                fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
690                                          fifoWakeUpSensors : sensor.getFifoMaxEventCount();
691
692            } else {
693                fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
694                                          fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
695
696            }
697        }
698   }
699   if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
700       // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
701       // size that is equal to that of the batch mode.
702       // ALOGW("Write failure in non-batch mode");
703       return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
704   }
705   return fifoWakeUpSensors + fifoNonWakeUpSensors;
706}
707
708} // namespace android
709
710