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