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