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