blob: 5225dd7a6484661c924b01341451c8a63dfa3740 [file] [log] [blame]
Peng Xueb4d6282015-12-10 18:02:41 -08001/*
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
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -070017#include <log/log.h>
Peng Xueb4d6282015-12-10 18:02:41 -080018#include <sys/socket.h>
19#include <utils/threads.h>
20
Mike Ma24743862020-01-29 00:36:55 -080021#include <android/util/ProtoOutputStream.h>
22#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080023#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080024
25#include "vec.h"
26#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070027#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080028
Peng Xue36e3472016-11-03 11:57:10 -070029#define UNUSED(x) (void)(x)
30
Peng Xueb4d6282015-12-10 18:02:41 -080031namespace android {
Anthony Stange07eb4212020-08-28 14:50:28 -040032namespace {
33
34// Used as the default value for the target SDK until it's obtained via getTargetSdkVersion.
35constexpr int kTargetSdkUnknown = 0;
36
37} // namespace
Peng Xueb4d6282015-12-10 18:02:41 -080038
39SensorService::SensorEventConnection::SensorEventConnection(
40 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Arthur Ishiguro340882c2021-02-18 15:17:44 -080041 const String16& opPackageName, const String16& attributionTag)
Peng Xueb4d6282015-12-10 18:02:41 -080042 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070043 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080044 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
Arthur Ishiguro340882c2021-02-18 15:17:44 -080045 mPackageName(packageName), mOpPackageName(opPackageName), mAttributionTag(attributionTag),
46 mTargetSdk(kTargetSdkUnknown), mDestroyed(false) {
Anh Phamaf91a912021-02-10 14:10:53 +010047 mIsRateCappedBasedOnPermission = mService->isRateCappedBasedOnPermission(mOpPackageName);
Anh Pham5198c992021-02-10 14:15:30 +010048 mUserId = multiuser_get_user_id(mUid);
Peng Xueb4d6282015-12-10 18:02:41 -080049 mChannel = new BitTube(mService->mSocketBufferSize);
50#if DEBUG_CONNECTIONS
51 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
52 mTotalAcksNeeded = mTotalAcksReceived = 0;
53#endif
54}
55
56SensorService::SensorEventConnection::~SensorEventConnection() {
57 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070058 destroy();
Peng Xueb4d6282015-12-10 18:02:41 -080059 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070060 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080061 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080062 }
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -070063}
64
65void SensorService::SensorEventConnection::destroy() {
Peng Xu8cbefd72017-07-10 16:41:08 -070066 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080067}
68
69void SensorService::SensorEventConnection::onFirstRef() {
70 LooperCallback::onFirstRef();
71}
72
73bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070074 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080075 return !mDead && mWakeLockRefCount > 0;
76}
77
78void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070079 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080080 mWakeLockRefCount = 0;
81}
82
83void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070084 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070085 result.appendFormat("\tOperating Mode: ");
86 if (!mService->isWhiteListedPackage(getPackageName())) {
87 result.append("RESTRICTED\n");
88 } else if (mDataInjectionMode) {
89 result.append("DATA_INJECTION\n");
90 } else {
91 result.append("NORMAL\n");
92 }
Peng Xueb4d6282015-12-10 18:02:41 -080093 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
94 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
95 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070096 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070097 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -080098 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -070099 mService->getSensorName(it.first).string(),
100 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -0800101 flushInfo.mFirstFlushPending ? "First flush pending" :
102 "active",
103 flushInfo.mPendingFlushEventsToSend);
104 }
105#if DEBUG_CONNECTIONS
106 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
107 " total_acks_needed %d | total_acks_recvd %d\n",
108 mEventsReceived,
109 mEventsSent,
110 mEventsSentFromCache,
111 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
112 mTotalAcksNeeded,
113 mTotalAcksReceived);
114#endif
115}
116
Mike Ma24743862020-01-29 00:36:55 -0800117/**
118 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
119 * ProtoOutputStream.
120 *
121 * See proto definition and some notes about ProtoOutputStream in
122 * frameworks/base/core/proto/android/service/sensor_service.proto
123 */
124void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
125 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700126 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800127
128 if (!mService->isWhiteListedPackage(getPackageName())) {
129 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
130 } else if (mDataInjectionMode) {
131 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
132 } else {
133 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
134 }
135 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
136 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
137 proto->write(UID, int32_t(mUid));
138 proto->write(CACHE_SIZE, int32_t(mCacheSize));
139 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700140 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700141 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800142 const uint64_t token = proto->start(FLUSH_INFOS);
143 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700144 std::string(mService->getSensorName(it.first)));
145 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800146 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
147 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
148 flushInfo.mPendingFlushEventsToSend);
149 proto->end(token);
150 }
151#if DEBUG_CONNECTIONS
152 proto->write(EVENTS_RECEIVED, mEventsReceived);
153 proto->write(EVENTS_SENT, mEventsSent);
154 proto->write(EVENTS_CACHE, mEventsSentFromCache);
155 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
156 mCacheSize));
157 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
158 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
159#endif
160}
161
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700162bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
163 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700164 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
165 if (si == nullptr ||
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700166 !canAccessSensor(si->getSensor(), "Add to SensorEventConnection: ", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700167 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800168 return false;
169 }
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700170 mSensorInfo[handle] = FlushInfo();
Peng Xu755c4512016-04-07 23:15:14 -0700171 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800172}
173
174bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700175 Mutex::Autolock _l(mConnectionLock);
176 if (mSensorInfo.erase(handle) >= 0) {
177 return true;
178 }
179 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800180}
181
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700182std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700183 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700184 std::vector<int32_t> list;
185 for (auto& it : mSensorInfo) {
186 list.push_back(it.first);
187 }
188 return list;
189}
190
Peng Xueb4d6282015-12-10 18:02:41 -0800191bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700192 Mutex::Autolock _l(mConnectionLock);
193 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800194}
195
196bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700197 Mutex::Autolock _l(mConnectionLock);
198 return mSensorInfo.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800199}
200
201bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700202 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700203 for (auto &it : mSensorInfo) {
204 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700205 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
206 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800207 return true;
208 }
209 }
210 return false;
211}
212
213String8 SensorService::SensorEventConnection::getPackageName() const {
214 return mPackageName;
215}
216
217void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
218 bool value) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700219 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700220 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700221 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800222 flushInfo.mFirstFlushPending = value;
223 }
224}
225
226void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700227 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800228 updateLooperRegistrationLocked(looper);
229}
230
231void 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;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700246 for (auto& it : mSensorInfo) {
247 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700248 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
249 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800250 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800251 }
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.
Yi Kong8f313e32018-07-17 14:13:29 -0700268 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800269 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
Stan Rokita29adc8c2020-07-06 17:38:03 -0700277bool 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;
Peng Xueb4d6282015-12-10 18:02:41 -0800287 }
288}
289
Anh Pham532e6552021-02-10 14:16:56 +0100290// TODO(b/179649922): A better algorithm to guarantee that capped connections will get a sampling
291// rate close to 200 Hz. With the current algorithm, apps might be punished unfairly: E.g.,two apps
292// make requests to the sensor service at the same time, one is not capped and uses 250 Hz, and one
293//is capped, the capped connection will only get 125 Hz.
294void SensorService::SensorEventConnection::addSensorEventsToBuffer(bool shouldResample,
295 const sensors_event_t& sensorEvent, sensors_event_t* buffer, int* index) {
296 if (!shouldResample || !mService->isSensorInCappedSet(sensorEvent.type)) {
297 buffer[(*index)++] = sensorEvent;
298 } else {
299 int64_t lastTimestamp = -1;
300 auto entry = mSensorLastTimestamp.find(sensorEvent.sensor);
301 if (entry != mSensorLastTimestamp.end()) {
302 lastTimestamp = entry->second;
303 }
304 // Allow 10% headroom here because the clocks are not perfect.
305 if (lastTimestamp == -1 || sensorEvent.timestamp - lastTimestamp
306 >= 0.9 * SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
307 mSensorLastTimestamp[sensorEvent.sensor] = sensorEvent.timestamp;
308 buffer[(*index)++] = sensorEvent;
309 }
310 }
311}
312
Peng Xueb4d6282015-12-10 18:02:41 -0800313status_t SensorService::SensorEventConnection::sendEvents(
314 sensors_event_t const* buffer, size_t numEvents,
315 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700316 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800317 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800318
George Burgess IV1866ed42018-01-21 12:14:09 -0800319 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800320
Anh Pham532e6552021-02-10 14:16:56 +0100321 bool shouldResample = mService->isMicSensorPrivacyEnabledForUid(mUid) ||
322 mIsRateCappedBasedOnPermission;
Peng Xueb4d6282015-12-10 18:02:41 -0800323 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700324 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800325 if (scratch) {
326 size_t i=0;
327 while (i<numEvents) {
328 int32_t sensor_handle = buffer[i].sensor;
329 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
330 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
331 buffer[i].meta_data.sensor);
332 // Setting sensor_handle to the correct sensor to ensure the sensor events per
333 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
334 // events.
335 sensor_handle = buffer[i].meta_data.sensor;
336 }
337
Peng Xueb4d6282015-12-10 18:02:41 -0800338 // Check if this connection has registered for this sensor. If not continue to the
339 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700340 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800341 ++i;
342 continue;
343 }
344
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700345 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800346 // Check if there is a pending flush_complete event for this sensor on this connection.
347 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700348 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800349 flushInfo.mFirstFlushPending = false;
350 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
351 buffer[i].meta_data.sensor);
352 ++i;
353 continue;
354 }
355
356 // If there is a pending flush complete event for this sensor on this connection,
357 // ignore the event and proceed to the next.
358 if (flushInfo.mFirstFlushPending) {
359 ++i;
360 continue;
361 }
362
363 do {
364 // Keep copying events into the scratch buffer as long as they are regular
365 // sensor_events are from the same sensor_handle OR they are flush_complete_events
366 // from the same sensor_handle AND the current connection is mapped to the
367 // corresponding flush_complete_event.
368 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700369 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800370 scratch[count++] = buffer[i];
371 }
Peng Xueb4d6282015-12-10 18:02:41 -0800372 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700373 // Regular sensor event, just copy it to the scratch buffer after checking
374 // the AppOp.
375 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Anh Pham532e6552021-02-10 14:16:56 +0100376 addSensorEventsToBuffer(shouldResample, buffer[i], scratch, &count);
Svet Ganove752a5c2018-01-15 17:14:20 -0800377 }
Peng Xueb4d6282015-12-10 18:02:41 -0800378 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800379 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800380 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
381 buffer[i].type != SENSOR_TYPE_META_DATA) ||
382 (buffer[i].type == SENSOR_TYPE_META_DATA &&
383 buffer[i].meta_data.sensor == sensor_handle)));
384 }
385 } else {
Anh Pham532e6552021-02-10 14:16:56 +0100386 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
387 scratch = sanitizedBuffer.get();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800388 if (hasSensorAccess()) {
Anh Pham532e6552021-02-10 14:16:56 +0100389 for (size_t i = 0; i < numEvents; i++) {
390 addSensorEventsToBuffer(shouldResample, buffer[i], scratch, &count);
391 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800392 } else {
Svet Ganove752a5c2018-01-15 17:14:20 -0800393 for (size_t i = 0; i < numEvents; i++) {
394 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
395 scratch[count++] = buffer[i++];
396 }
397 }
398 }
Peng Xueb4d6282015-12-10 18:02:41 -0800399 }
400
401 sendPendingFlushEventsLocked();
402 // Early return if there are no events for this connection.
403 if (count == 0) {
404 return status_t(NO_ERROR);
405 }
406
407#if DEBUG_CONNECTIONS
408 mEventsReceived += count;
409#endif
410 if (mCacheSize != 0) {
411 // There are some events in the cache which need to be sent first. Copy this buffer to
412 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800413 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800414 return status_t(NO_ERROR);
415 }
416
Svet Ganove752a5c2018-01-15 17:14:20 -0800417 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800418 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800419 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
420 if (index_wake_up_event >= 0) {
421 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
422 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800423#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800424 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800425#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800426 }
Peng Xueb4d6282015-12-10 18:02:41 -0800427 }
428
429 // NOTE: ASensorEvent and sensors_event_t are the same type.
430 ssize_t size = SensorEventQueue::write(mChannel,
431 reinterpret_cast<ASensorEvent const*>(scratch), count);
432 if (size < 0) {
433 // Write error, copy events to local cache.
434 if (index_wake_up_event >= 0) {
435 // If there was a wake_up sensor_event, reset the flag.
436 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
437 if (mWakeLockRefCount > 0) {
438 --mWakeLockRefCount;
439 }
440#if DEBUG_CONNECTIONS
441 --mTotalAcksNeeded;
442#endif
443 }
Yi Kong8f313e32018-07-17 14:13:29 -0700444 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800445 mMaxCacheSize = computeMaxCacheSizeLocked();
446 mEventCache = new sensors_event_t[mMaxCacheSize];
447 mCacheSize = 0;
448 }
Brian Stack93432ad2018-11-27 18:28:48 -0800449 // Save the events so that they can be written later
450 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800451
452 // Add this file descriptor to the looper to get a callback when this fd is available for
453 // writing.
454 updateLooperRegistrationLocked(mService->getLooper());
455 return size;
456 }
457
458#if DEBUG_CONNECTIONS
459 if (size > 0) {
460 mEventsSent += count;
461 }
462#endif
463
464 return size < 0 ? status_t(size) : status_t(NO_ERROR);
465}
466
Michael Groover5e1f60b2018-12-04 22:34:29 -0800467bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700468 return mService->isUidActive(mUid)
469 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800470}
471
Brian Stackc225aa12019-04-19 09:30:25 -0700472bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
473 bool success = true;
474 const auto iter = mHandleToAppOp.find(event.sensor);
475 if (iter != mHandleToAppOp.end()) {
Anthony Stange07eb4212020-08-28 14:50:28 -0400476 if (mTargetSdk == kTargetSdkUnknown) {
477 // getTargetSdkVersion returns -1 if it fails so this operation should only be run once
478 // per connection and then cached. Perform this here as opposed to in the constructor to
479 // avoid log spam for NDK/VNDK clients that don't use sensors guarded with permissions
480 // and pass in invalid op package names.
481 mTargetSdk = SensorService::getTargetSdkVersion(mOpPackageName);
482 }
483
Brian Duddie457e6392020-06-19 11:38:29 -0700484 // Special handling for step count/detect backwards compatibility: if the app's target SDK
485 // is pre-Q, still permit delivering events to the app even if permission isn't granted
486 // (since this permission was only introduced in Q)
487 if ((event.type == SENSOR_TYPE_STEP_COUNTER || event.type == SENSOR_TYPE_STEP_DETECTOR) &&
488 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
489 success = true;
490 } else {
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700491 int32_t sensorHandle = event.sensor;
492 String16 noteMsg("Sensor event (");
493 noteMsg.append(String16(mService->getSensorStringType(sensorHandle)));
494 noteMsg.append(String16(")"));
Brian Duddie457e6392020-06-19 11:38:29 -0700495 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid,
Arthur Ishiguro340882c2021-02-18 15:17:44 -0800496 mOpPackageName, mAttributionTag,
497 noteMsg);
Brian Duddie457e6392020-06-19 11:38:29 -0700498 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
499 }
Brian Stackc225aa12019-04-19 09:30:25 -0700500 }
501 return success;
502}
503
Peng Xueb4d6282015-12-10 18:02:41 -0800504void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
505 int count) {
506 sensors_event_t *eventCache_new;
507 const int new_cache_size = computeMaxCacheSizeLocked();
508 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
509 eventCache_new = new sensors_event_t[new_cache_size];
510 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
511 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
512
513 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
514 new_cache_size);
515
George Burgess IV1866ed42018-01-21 12:14:09 -0800516 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800517 mEventCache = eventCache_new;
518 mCacheSize += count;
519 mMaxCacheSize = new_cache_size;
520}
521
Brian Stack93432ad2018-11-27 18:28:48 -0800522void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
523 int count) {
524 if (count <= 0) {
525 return;
526 } else if (mCacheSize + count <= mMaxCacheSize) {
527 // The events fit within the current cache: add them
528 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
529 mCacheSize += count;
530 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
531 // The events fit within a resized cache: resize the cache and add the events
532 reAllocateCacheLocked(events, count);
533 } else {
534 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800535 int freeSpace = mMaxCacheSize - mCacheSize;
536
537 // Drop up to the currently cached number of events to make room for new events
538 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
539
540 // New events need to be dropped if there are more new events than the size of the cache
541 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
542
543 // Determine the number of new events to copy into the cache
544 int eventsToCopy = std::min(mMaxCacheSize, count);
545
Brian Stackae4053f2018-12-10 14:54:18 -0800546 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
547 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
548 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
549 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
550 count, mEventsDropped);
551 mEventsDropped = 0;
552 mTimeOfLastEventDrop = events[0].timestamp;
553 } else {
554 // Record the number dropped
555 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
556 }
557
Brian Stack93432ad2018-11-27 18:28:48 -0800558 // Check for any flush complete events in the events that will be dropped
559 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
560 countFlushCompleteEventsLocked(events, newEventsToDrop);
561
562 // Only shift the events if they will not all be overwritten
563 if (eventsToCopy != mMaxCacheSize) {
564 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
565 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
566 }
567 mCacheSize -= cachedEventsToDrop;
568
569 // Copy the events into the cache
570 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
571 eventsToCopy * sizeof(sensors_event_t));
572 mCacheSize += eventsToCopy;
573 }
574}
575
Peng Xueb4d6282015-12-10 18:02:41 -0800576void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
577 ASensorEvent flushCompleteEvent;
578 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
579 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
580 // Loop through all the sensors for this connection and check if there are any pending
581 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700582 for (auto& it : mSensorInfo) {
583 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700584 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
585 if (si == nullptr) {
586 continue;
587 }
588
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700589 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800590 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700591 flushCompleteEvent.meta_data.sensor = handle;
592 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800593 if (wakeUpSensor) {
594 ++mWakeLockRefCount;
595 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
596 }
597 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
598 if (size < 0) {
599 if (wakeUpSensor) --mWakeLockRefCount;
600 return;
601 }
602 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
603 flushCompleteEvent.meta_data.sensor);
604 flushInfo.mPendingFlushEventsToSend--;
605 }
606 }
607}
608
609void SensorService::SensorEventConnection::writeToSocketFromCache() {
610 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
611 // half the size of the socket buffer allocated in BitTube whichever is smaller.
612 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
613 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700614 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800615 // Send pending flush complete events (if any)
616 sendPendingFlushEventsLocked();
617 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
618 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800619 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800620 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800621 index_wake_up_event =
622 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
623 if (index_wake_up_event >= 0) {
624 mEventCache[index_wake_up_event + numEventsSent].flags |=
625 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
626 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800627#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800628 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800629#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800630 }
Peng Xueb4d6282015-12-10 18:02:41 -0800631 }
632
633 ssize_t size = SensorEventQueue::write(mChannel,
634 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
635 numEventsToWrite);
636 if (size < 0) {
637 if (index_wake_up_event >= 0) {
638 // If there was a wake_up sensor_event, reset the flag.
639 mEventCache[index_wake_up_event + numEventsSent].flags &=
640 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
641 if (mWakeLockRefCount > 0) {
642 --mWakeLockRefCount;
643 }
644#if DEBUG_CONNECTIONS
645 --mTotalAcksNeeded;
646#endif
647 }
648 memmove(mEventCache, &mEventCache[numEventsSent],
649 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
650 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
651 numEventsSent, mCacheSize);
652 mCacheSize -= numEventsSent;
653 return;
654 }
655 numEventsSent += numEventsToWrite;
656#if DEBUG_CONNECTIONS
657 mEventsSentFromCache += numEventsToWrite;
658#endif
659 }
660 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
661 // All events from the cache have been sent. Reset cache size to zero.
662 mCacheSize = 0;
663 // There are no more events in the cache. We don't need to poll for write on the fd.
664 // Update Looper registration.
665 updateLooperRegistrationLocked(mService->getLooper());
666}
667
668void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
669 sensors_event_t const* scratch, const int numEventsDropped) {
670 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
671 // Count flushComplete events in the events that are about to the dropped. These will be sent
672 // separately before the next batch of events.
673 for (int j = 0; j < numEventsDropped; ++j) {
674 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700675 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700676 ALOGW("%s: sensor 0x%x is not found in connection",
677 __func__, scratch[j].meta_data.sensor);
678 continue;
679 }
680
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700681 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800682 flushInfo.mPendingFlushEventsToSend++;
683 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
684 flushInfo.mPendingFlushEventsToSend);
685 }
686 }
687 return;
688}
689
690int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
691 sensors_event_t const* scratch, const int count) {
692 for (int i = 0; i < count; ++i) {
693 if (mService->isWakeUpSensorEvent(scratch[i])) {
694 return i;
695 }
696 }
697 return -1;
698}
699
700sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
701{
702 return mChannel;
703}
704
705status_t SensorService::SensorEventConnection::enableDisable(
706 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
707 int reservedFlags)
708{
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700709 if (mDestroyed) {
710 android_errorWriteLog(0x534e4554, "168211968");
711 return DEAD_OBJECT;
712 }
713
Peng Xueb4d6282015-12-10 18:02:41 -0800714 status_t err;
715 if (enabled) {
Anh Pham5198c992021-02-10 14:15:30 +0100716 nsecs_t requestedSamplingPeriodNs = samplingPeriodNs;
Anh Phamaf91a912021-02-10 14:10:53 +0100717 bool isSensorCapped = false;
718 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
719 if (si != nullptr) {
720 const Sensor& s = si->getSensor();
721 if (mService->isSensorInCappedSet(s.getType())) {
722 isSensorCapped = true;
723 }
724 }
725 if (isSensorCapped) {
726 err = mService->adjustSamplingPeriodBasedOnMicAndPermission(&samplingPeriodNs,
727 String16(mOpPackageName));
728 if (err != OK) {
729 return err;
730 }
731 }
Peng Xueb4d6282015-12-10 18:02:41 -0800732 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
733 reservedFlags, mOpPackageName);
Anh Pham5198c992021-02-10 14:15:30 +0100734 if (err == OK && isSensorCapped) {
735 if (!mIsRateCappedBasedOnPermission ||
736 requestedSamplingPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
737 mMicSamplingPeriodBackup[handle] = requestedSamplingPeriodNs;
738 } else {
739 mMicSamplingPeriodBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
740 }
741 }
Peng Xueb4d6282015-12-10 18:02:41 -0800742
743 } else {
744 err = mService->disable(this, handle);
Anh Pham5198c992021-02-10 14:15:30 +0100745 mMicSamplingPeriodBackup.erase(handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800746 }
747 return err;
748}
749
Anh Phamaf91a912021-02-10 14:10:53 +0100750status_t SensorService::SensorEventConnection::setEventRate(int handle, nsecs_t samplingPeriodNs) {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700751 if (mDestroyed) {
752 android_errorWriteLog(0x534e4554, "168211968");
753 return DEAD_OBJECT;
754 }
755
Anh Pham5198c992021-02-10 14:15:30 +0100756 nsecs_t requestedSamplingPeriodNs = samplingPeriodNs;
Anh Phamaf91a912021-02-10 14:10:53 +0100757 bool isSensorCapped = false;
758 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
759 if (si != nullptr) {
760 const Sensor& s = si->getSensor();
761 if (mService->isSensorInCappedSet(s.getType())) {
762 isSensorCapped = true;
763 }
764 }
765 if (isSensorCapped) {
766 status_t err = mService->adjustSamplingPeriodBasedOnMicAndPermission(&samplingPeriodNs,
767 String16(mOpPackageName));
768 if (err != OK) {
769 return err;
770 }
771 }
Anh Pham5198c992021-02-10 14:15:30 +0100772 status_t ret = mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
773 if (ret == OK && isSensorCapped) {
774 if (!mIsRateCappedBasedOnPermission ||
775 requestedSamplingPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
776 mMicSamplingPeriodBackup[handle] = requestedSamplingPeriodNs;
777 } else {
778 mMicSamplingPeriodBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
779 }
780 }
781 return ret;
782}
783
784void SensorService::SensorEventConnection::onMicSensorAccessChanged(bool isMicToggleOn) {
785 if (isMicToggleOn) {
786 capRates();
787 } else {
788 uncapRates();
789 }
790}
791
792void SensorService::SensorEventConnection::capRates() {
793 Mutex::Autolock _l(mConnectionLock);
794 SensorDevice& dev(SensorDevice::getInstance());
795 for (auto &i : mMicSamplingPeriodBackup) {
796 int handle = i.first;
797 nsecs_t samplingPeriodNs = i.second;
798 if (samplingPeriodNs < SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
799 if (hasSensorAccess()) {
800 mService->setEventRate(this, handle, SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS,
801 mOpPackageName);
802 } else {
803 // Update SensorDevice with the capped rate so that when sensor access is restored,
804 // the correct event rate is used.
805 dev.onMicSensorAccessChanged(this, handle,
806 SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS);
807 }
808 }
809 }
810}
811
812void SensorService::SensorEventConnection::uncapRates() {
813 Mutex::Autolock _l(mConnectionLock);
814 SensorDevice& dev(SensorDevice::getInstance());
815 for (auto &i : mMicSamplingPeriodBackup) {
816 int handle = i.first;
817 nsecs_t samplingPeriodNs = i.second;
818 if (samplingPeriodNs < SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
819 if (hasSensorAccess()) {
820 mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
821 } else {
822 // Update SensorDevice with the uncapped rate so that when sensor access is
823 // restored, the correct event rate is used.
824 dev.onMicSensorAccessChanged(this, handle, samplingPeriodNs);
825 }
826 }
827 }
Peng Xueb4d6282015-12-10 18:02:41 -0800828}
829
830status_t SensorService::SensorEventConnection::flush() {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700831 if (mDestroyed) {
832 return DEAD_OBJECT;
833 }
834
Peng Xueb4d6282015-12-10 18:02:41 -0800835 return mService->flushSensor(this, mOpPackageName);
836}
837
Peng Xue36e3472016-11-03 11:57:10 -0700838int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
839 // SensorEventConnection does not support configureChannel, parameters not used
840 UNUSED(handle);
841 UNUSED(rateLevel);
842 return INVALID_OPERATION;
843}
844
Peng Xueb4d6282015-12-10 18:02:41 -0800845int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
846 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
847 {
848 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
849 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
850 // can release the wake-lock.
851 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700852 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800853 mDead = true;
854 mWakeLockRefCount = 0;
855 updateLooperRegistrationLocked(mService->getLooper());
856 }
857 mService->checkWakeLockState();
858 if (mDataInjectionMode) {
859 // If the Looper has encountered some error in data injection mode, reset SensorService
860 // back to normal mode.
861 mService->resetToNormalMode();
862 mDataInjectionMode = false;
863 }
864 return 1;
865 }
866
867 if (events & ALOOPER_EVENT_INPUT) {
868 unsigned char buf[sizeof(sensors_event_t)];
869 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
870 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700871 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700872 if (numBytesRead == sizeof(sensors_event_t)) {
873 if (!mDataInjectionMode) {
874 ALOGE("Data injected in normal mode, dropping event"
875 "package=%s uid=%d", mPackageName.string(), mUid);
876 // Unregister call backs.
877 return 0;
878 }
879 sensors_event_t sensor_event;
880 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
881 sp<SensorInterface> si =
882 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
883 if (si == nullptr) {
884 return 1;
885 }
886
887 SensorDevice& dev(SensorDevice::getInstance());
888 sensor_event.type = si->getSensor().getType();
889 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800890#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700891 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800892#endif
Peng Xu755c4512016-04-07 23:15:14 -0700893 } else if (numBytesRead == sizeof(uint32_t)) {
894 uint32_t numAcks = 0;
895 memcpy(&numAcks, buf, numBytesRead);
896 // Sanity check to ensure there are no read errors in recv, numAcks is always
897 // within the range and not zero. If any of the above don't hold reset
898 // mWakeLockRefCount to zero.
899 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
900 mWakeLockRefCount -= numAcks;
901 } else {
902 mWakeLockRefCount = 0;
903 }
Peng Xueb4d6282015-12-10 18:02:41 -0800904#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700905 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800906#endif
907 } else {
908 // Read error, reset wakelock refcount.
909 mWakeLockRefCount = 0;
910 }
911 }
912 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
913 // here as checkWakeLockState() will need it.
914 if (mWakeLockRefCount == 0) {
915 mService->checkWakeLockState();
916 }
917 // continue getting callbacks.
918 return 1;
919 }
920
921 if (events & ALOOPER_EVENT_OUTPUT) {
922 // send sensor data that is stored in mEventCache for this connection.
923 mService->sendEventsFromCache(this);
924 }
925 return 1;
926}
927
928int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
929 size_t fifoWakeUpSensors = 0;
930 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700931 for (auto& it : mSensorInfo) {
932 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700933 if (si == nullptr) {
934 continue;
935 }
936 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800937 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
938 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
939 // non wake_up sensors.
940 if (sensor.isWakeUpSensor()) {
941 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
942 } else {
943 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
944 }
945 } else {
946 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
947 if (sensor.isWakeUpSensor()) {
948 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
949 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
950
951 } else {
952 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
953 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
954
955 }
956 }
957 }
958 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
959 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
960 // size that is equal to that of the batch mode.
961 // ALOGW("Write failure in non-batch mode");
962 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
963 }
964 return fifoWakeUpSensors + fifoNonWakeUpSensors;
965}
966
967} // namespace android
968