blob: 3446f58b965b1a18efab57709924ac2935134b90 [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"
Suprabh Shukla0f239092023-04-04 03:33:09 -070026#include "BatteryService.h"
Peng Xueb4d6282015-12-10 18:02:41 -080027#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070028#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080029
Peng Xue36e3472016-11-03 11:57:10 -070030#define UNUSED(x) (void)(x)
31
Peng Xueb4d6282015-12-10 18:02:41 -080032namespace android {
Anthony Stange07eb4212020-08-28 14:50:28 -040033namespace {
34
35// Used as the default value for the target SDK until it's obtained via getTargetSdkVersion.
36constexpr int kTargetSdkUnknown = 0;
37
38} // namespace
Peng Xueb4d6282015-12-10 18:02:41 -080039
40SensorService::SensorEventConnection::SensorEventConnection(
41 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Arthur Ishiguro340882c2021-02-18 15:17:44 -080042 const String16& opPackageName, const String16& attributionTag)
Peng Xueb4d6282015-12-10 18:02:41 -080043 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070044 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080045 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
Arthur Ishiguro340882c2021-02-18 15:17:44 -080046 mPackageName(packageName), mOpPackageName(opPackageName), mAttributionTag(attributionTag),
47 mTargetSdk(kTargetSdkUnknown), mDestroyed(false) {
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();
Arthur Ishiguro9f0f6472023-04-03 17:01:40 +000059 delete[] mEventCache;
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -070060}
61
62void SensorService::SensorEventConnection::destroy() {
Arthur Ishiguro9f0f6472023-04-03 17:01:40 +000063 if (!mDestroyed.exchange(true)) {
64 mService->cleanupConnection(this);
65 }
Peng Xueb4d6282015-12-10 18:02:41 -080066}
67
68void SensorService::SensorEventConnection::onFirstRef() {
69 LooperCallback::onFirstRef();
70}
71
72bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070073 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080074 return !mDead && mWakeLockRefCount > 0;
75}
76
77void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070078 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080079 mWakeLockRefCount = 0;
80}
81
82void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070083 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070084 result.appendFormat("\tOperating Mode: ");
Anthony Stangecd01ec12023-01-06 18:35:13 +000085 if (!mService->isAllowListedPackage(getPackageName())) {
Brian Stackbce04d72019-03-21 10:54:10 -070086 result.append("RESTRICTED\n");
87 } else if (mDataInjectionMode) {
88 result.append("DATA_INJECTION\n");
89 } else {
90 result.append("NORMAL\n");
91 }
Peng Xueb4d6282015-12-10 18:02:41 -080092 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
Tomasz Wasilczykfde494d2023-08-11 00:06:51 +000093 "max cache size %d\n", mPackageName.c_str(), mWakeLockRefCount, mUid, mCacheSize,
Peng Xueb4d6282015-12-10 18:02:41 -080094 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070095 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070096 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -080097 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Tomasz Wasilczykfde494d2023-08-11 00:06:51 +000098 mService->getSensorName(it.first).c_str(),
Arthur Ishiguroad46c782020-03-26 11:24:43 -070099 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -0800100 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
Mike Ma24743862020-01-29 00:36:55 -0800116/**
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 */
123void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
124 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700125 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800126
Anthony Stangecd01ec12023-01-06 18:35:13 +0000127 if (!mService->isAllowListedPackage(getPackageName())) {
Mike Ma24743862020-01-29 00:36:55 -0800128 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 }
Tomasz Wasilczykfde494d2023-08-11 00:06:51 +0000134 proto->write(PACKAGE_NAME, std::string(mPackageName.c_str()));
Mike Ma24743862020-01-29 00:36:55 -0800135 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));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700139 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700140 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800141 const uint64_t token = proto->start(FLUSH_INFOS);
142 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700143 std::string(mService->getSensorName(it.first)));
144 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800145 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
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700161bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
162 Mutex::Autolock _l(mConnectionLock);
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100163 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -0700164 if (si == nullptr ||
Brian Duddie4a4d0462022-05-09 16:49:49 -0700165 !mService->canAccessSensor(si->getSensor(), "Add to SensorEventConnection: ",
166 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;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100205 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -0700206 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;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100248 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -0700249 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
290status_t SensorService::SensorEventConnection::sendEvents(
291 sensors_event_t const* buffer, size_t numEvents,
292 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700293 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800294 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800295
George Burgess IV1866ed42018-01-21 12:14:09 -0800296 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800297
Peng Xueb4d6282015-12-10 18:02:41 -0800298 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700299 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800300 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
Peng Xueb4d6282015-12-10 18:02:41 -0800313 // Check if this connection has registered for this sensor. If not continue to the
314 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700315 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800316 ++i;
317 continue;
318 }
319
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700320 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800321 // 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 &&
Peng Xuded526e2016-08-12 16:39:44 -0700323 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800324 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) {
Peng Xuded526e2016-08-12 16:39:44 -0700344 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800345 scratch[count++] = buffer[i];
346 }
Peng Xueb4d6282015-12-10 18:02:41 -0800347 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700348 // Regular sensor event, just copy it to the scratch buffer after checking
349 // the AppOp.
350 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Anh Phamdf549ea2021-03-22 11:50:48 +0100351 scratch[count++] = buffer[i];
Svet Ganove752a5c2018-01-15 17:14:20 -0800352 }
Peng Xueb4d6282015-12-10 18:02:41 -0800353 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800354 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800355 } 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 {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800361 if (hasSensorAccess()) {
Anh Phamdf549ea2021-03-22 11:50:48 +0100362 scratch = const_cast<sensors_event_t *>(buffer);
363 count = numEvents;
Svet Ganove752a5c2018-01-15 17:14:20 -0800364 } else {
Anh Phamdf549ea2021-03-22 11:50:48 +0100365 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
366 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800367 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 }
Peng Xueb4d6282015-12-10 18:02:41 -0800373 }
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.
Brian Stack93432ad2018-11-27 18:28:48 -0800387 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800388 return status_t(NO_ERROR);
389 }
390
Svet Ganove752a5c2018-01-15 17:14:20 -0800391 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800392 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800393 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
394 if (index_wake_up_event >= 0) {
Suprabh Shukla0f239092023-04-04 03:33:09 -0700395 BatteryService::noteWakeupSensorEvent(scratch[index_wake_up_event].timestamp,
396 mUid, scratch[index_wake_up_event].sensor);
Svet Ganove752a5c2018-01-15 17:14:20 -0800397 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
398 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800399#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800400 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800401#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800402 }
Peng Xueb4d6282015-12-10 18:02:41 -0800403 }
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 }
Yi Kong8f313e32018-07-17 14:13:29 -0700420 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800421 mMaxCacheSize = computeMaxCacheSizeLocked();
422 mEventCache = new sensors_event_t[mMaxCacheSize];
423 mCacheSize = 0;
424 }
Brian Stack93432ad2018-11-27 18:28:48 -0800425 // Save the events so that they can be written later
426 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800427
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
Michael Groover5e1f60b2018-12-04 22:34:29 -0800443bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700444 return mService->isUidActive(mUid)
445 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800446}
447
Brian Stackc225aa12019-04-19 09:30:25 -0700448bool 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()) {
Anthony Stange07eb4212020-08-28 14:50:28 -0400452 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
Brian Duddie457e6392020-06-19 11:38:29 -0700460 // 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) &&
Rocky Fangcb142de2024-04-12 19:25:27 +0000464 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
465 success = true;
466 } else if (mUid == AID_SYSTEM) {
467 // Allow access if it is requested from system.
Brian Duddie457e6392020-06-19 11:38:29 -0700468 success = true;
469 } else {
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700470 int32_t sensorHandle = event.sensor;
471 String16 noteMsg("Sensor event (");
472 noteMsg.append(String16(mService->getSensorStringType(sensorHandle)));
473 noteMsg.append(String16(")"));
Rocky Fangcb142de2024-04-12 19:25:27 +0000474 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid, mOpPackageName,
475 mAttributionTag, noteMsg);
Brian Duddie457e6392020-06-19 11:38:29 -0700476 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
477 }
Brian Stackc225aa12019-04-19 09:30:25 -0700478 }
479 return success;
480}
481
Peng Xueb4d6282015-12-10 18:02:41 -0800482void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
483 int count) {
484 sensors_event_t *eventCache_new;
485 const int new_cache_size = computeMaxCacheSizeLocked();
486 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
487 eventCache_new = new sensors_event_t[new_cache_size];
488 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
489 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
490
491 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
492 new_cache_size);
493
George Burgess IV1866ed42018-01-21 12:14:09 -0800494 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800495 mEventCache = eventCache_new;
496 mCacheSize += count;
497 mMaxCacheSize = new_cache_size;
498}
499
Brian Stack93432ad2018-11-27 18:28:48 -0800500void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
501 int count) {
502 if (count <= 0) {
503 return;
504 } else if (mCacheSize + count <= mMaxCacheSize) {
505 // The events fit within the current cache: add them
506 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
507 mCacheSize += count;
508 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
509 // The events fit within a resized cache: resize the cache and add the events
510 reAllocateCacheLocked(events, count);
511 } else {
512 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800513 int freeSpace = mMaxCacheSize - mCacheSize;
514
515 // Drop up to the currently cached number of events to make room for new events
516 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
517
518 // New events need to be dropped if there are more new events than the size of the cache
519 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
520
521 // Determine the number of new events to copy into the cache
522 int eventsToCopy = std::min(mMaxCacheSize, count);
523
Brian Stackae4053f2018-12-10 14:54:18 -0800524 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
525 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
526 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
527 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
528 count, mEventsDropped);
529 mEventsDropped = 0;
530 mTimeOfLastEventDrop = events[0].timestamp;
531 } else {
532 // Record the number dropped
533 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
534 }
535
Brian Stack93432ad2018-11-27 18:28:48 -0800536 // Check for any flush complete events in the events that will be dropped
537 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
538 countFlushCompleteEventsLocked(events, newEventsToDrop);
539
540 // Only shift the events if they will not all be overwritten
541 if (eventsToCopy != mMaxCacheSize) {
542 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
543 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
544 }
545 mCacheSize -= cachedEventsToDrop;
546
547 // Copy the events into the cache
548 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
549 eventsToCopy * sizeof(sensors_event_t));
550 mCacheSize += eventsToCopy;
551 }
552}
553
Peng Xueb4d6282015-12-10 18:02:41 -0800554void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
555 ASensorEvent flushCompleteEvent;
556 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
557 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
558 // Loop through all the sensors for this connection and check if there are any pending
559 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700560 for (auto& it : mSensorInfo) {
561 const int handle = it.first;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100562 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
Peng Xu755c4512016-04-07 23:15:14 -0700563 if (si == nullptr) {
564 continue;
565 }
566
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700567 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800568 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700569 flushCompleteEvent.meta_data.sensor = handle;
570 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800571 if (wakeUpSensor) {
572 ++mWakeLockRefCount;
573 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
574 }
575 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
576 if (size < 0) {
577 if (wakeUpSensor) --mWakeLockRefCount;
578 return;
579 }
580 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
581 flushCompleteEvent.meta_data.sensor);
582 flushInfo.mPendingFlushEventsToSend--;
583 }
584 }
585}
586
587void SensorService::SensorEventConnection::writeToSocketFromCache() {
588 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
589 // half the size of the socket buffer allocated in BitTube whichever is smaller.
590 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
591 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700592 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800593 // Send pending flush complete events (if any)
594 sendPendingFlushEventsLocked();
595 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
596 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800597 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800598 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800599 index_wake_up_event =
600 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
601 if (index_wake_up_event >= 0) {
602 mEventCache[index_wake_up_event + numEventsSent].flags |=
603 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
604 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800605#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800606 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800607#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800608 }
Peng Xueb4d6282015-12-10 18:02:41 -0800609 }
610
611 ssize_t size = SensorEventQueue::write(mChannel,
612 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
613 numEventsToWrite);
614 if (size < 0) {
615 if (index_wake_up_event >= 0) {
616 // If there was a wake_up sensor_event, reset the flag.
617 mEventCache[index_wake_up_event + numEventsSent].flags &=
618 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
619 if (mWakeLockRefCount > 0) {
620 --mWakeLockRefCount;
621 }
622#if DEBUG_CONNECTIONS
623 --mTotalAcksNeeded;
624#endif
625 }
626 memmove(mEventCache, &mEventCache[numEventsSent],
627 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
628 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
629 numEventsSent, mCacheSize);
630 mCacheSize -= numEventsSent;
631 return;
632 }
633 numEventsSent += numEventsToWrite;
634#if DEBUG_CONNECTIONS
635 mEventsSentFromCache += numEventsToWrite;
636#endif
637 }
638 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
639 // All events from the cache have been sent. Reset cache size to zero.
640 mCacheSize = 0;
641 // There are no more events in the cache. We don't need to poll for write on the fd.
642 // Update Looper registration.
643 updateLooperRegistrationLocked(mService->getLooper());
644}
645
646void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
647 sensors_event_t const* scratch, const int numEventsDropped) {
648 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
649 // Count flushComplete events in the events that are about to the dropped. These will be sent
650 // separately before the next batch of events.
651 for (int j = 0; j < numEventsDropped; ++j) {
652 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700653 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700654 ALOGW("%s: sensor 0x%x is not found in connection",
655 __func__, scratch[j].meta_data.sensor);
656 continue;
657 }
658
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700659 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800660 flushInfo.mPendingFlushEventsToSend++;
661 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
662 flushInfo.mPendingFlushEventsToSend);
663 }
664 }
665 return;
666}
667
668int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
669 sensors_event_t const* scratch, const int count) {
670 for (int i = 0; i < count; ++i) {
671 if (mService->isWakeUpSensorEvent(scratch[i])) {
672 return i;
673 }
674 }
675 return -1;
676}
677
678sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
679{
680 return mChannel;
681}
682
683status_t SensorService::SensorEventConnection::enableDisable(
684 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
685 int reservedFlags)
686{
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700687 if (mDestroyed) {
688 android_errorWriteLog(0x534e4554, "168211968");
689 return DEAD_OBJECT;
690 }
691
Peng Xueb4d6282015-12-10 18:02:41 -0800692 status_t err;
693 if (enabled) {
Anh Pham5198c992021-02-10 14:15:30 +0100694 nsecs_t requestedSamplingPeriodNs = samplingPeriodNs;
Anh Phamaf91a912021-02-10 14:10:53 +0100695 bool isSensorCapped = false;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100696 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
Anh Phamaf91a912021-02-10 14:10:53 +0100697 if (si != nullptr) {
698 const Sensor& s = si->getSensor();
699 if (mService->isSensorInCappedSet(s.getType())) {
700 isSensorCapped = true;
701 }
702 }
703 if (isSensorCapped) {
704 err = mService->adjustSamplingPeriodBasedOnMicAndPermission(&samplingPeriodNs,
705 String16(mOpPackageName));
706 if (err != OK) {
707 return err;
708 }
709 }
Peng Xueb4d6282015-12-10 18:02:41 -0800710 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
711 reservedFlags, mOpPackageName);
Anh Pham5198c992021-02-10 14:15:30 +0100712 if (err == OK && isSensorCapped) {
Arthur Ishiguro8a628522021-09-22 14:10:16 -0700713 if ((requestedSamplingPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) ||
714 !isRateCappedBasedOnPermission()) {
Anh Pham5198c992021-02-10 14:15:30 +0100715 mMicSamplingPeriodBackup[handle] = requestedSamplingPeriodNs;
716 } else {
717 mMicSamplingPeriodBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
718 }
719 }
Peng Xueb4d6282015-12-10 18:02:41 -0800720
721 } else {
722 err = mService->disable(this, handle);
Anh Pham5198c992021-02-10 14:15:30 +0100723 mMicSamplingPeriodBackup.erase(handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800724 }
725 return err;
726}
727
Anh Phamaf91a912021-02-10 14:10:53 +0100728status_t SensorService::SensorEventConnection::setEventRate(int handle, nsecs_t samplingPeriodNs) {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700729 if (mDestroyed) {
730 android_errorWriteLog(0x534e4554, "168211968");
731 return DEAD_OBJECT;
732 }
733
Anh Pham5198c992021-02-10 14:15:30 +0100734 nsecs_t requestedSamplingPeriodNs = samplingPeriodNs;
Anh Phamaf91a912021-02-10 14:10:53 +0100735 bool isSensorCapped = false;
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100736 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
Anh Phamaf91a912021-02-10 14:10:53 +0100737 if (si != nullptr) {
738 const Sensor& s = si->getSensor();
739 if (mService->isSensorInCappedSet(s.getType())) {
740 isSensorCapped = true;
741 }
742 }
743 if (isSensorCapped) {
744 status_t err = mService->adjustSamplingPeriodBasedOnMicAndPermission(&samplingPeriodNs,
745 String16(mOpPackageName));
746 if (err != OK) {
747 return err;
748 }
749 }
Anh Pham5198c992021-02-10 14:15:30 +0100750 status_t ret = mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
751 if (ret == OK && isSensorCapped) {
Arthur Ishiguro8a628522021-09-22 14:10:16 -0700752 if ((requestedSamplingPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) ||
753 !isRateCappedBasedOnPermission()) {
Anh Pham5198c992021-02-10 14:15:30 +0100754 mMicSamplingPeriodBackup[handle] = requestedSamplingPeriodNs;
755 } else {
756 mMicSamplingPeriodBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
757 }
758 }
759 return ret;
760}
761
762void SensorService::SensorEventConnection::onMicSensorAccessChanged(bool isMicToggleOn) {
763 if (isMicToggleOn) {
764 capRates();
765 } else {
766 uncapRates();
767 }
768}
769
770void SensorService::SensorEventConnection::capRates() {
771 Mutex::Autolock _l(mConnectionLock);
772 SensorDevice& dev(SensorDevice::getInstance());
773 for (auto &i : mMicSamplingPeriodBackup) {
774 int handle = i.first;
775 nsecs_t samplingPeriodNs = i.second;
776 if (samplingPeriodNs < SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
777 if (hasSensorAccess()) {
778 mService->setEventRate(this, handle, SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS,
779 mOpPackageName);
780 } else {
781 // Update SensorDevice with the capped rate so that when sensor access is restored,
782 // the correct event rate is used.
783 dev.onMicSensorAccessChanged(this, handle,
784 SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS);
785 }
786 }
787 }
788}
789
790void SensorService::SensorEventConnection::uncapRates() {
791 Mutex::Autolock _l(mConnectionLock);
792 SensorDevice& dev(SensorDevice::getInstance());
793 for (auto &i : mMicSamplingPeriodBackup) {
794 int handle = i.first;
795 nsecs_t samplingPeriodNs = i.second;
796 if (samplingPeriodNs < SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
797 if (hasSensorAccess()) {
798 mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
799 } else {
800 // Update SensorDevice with the uncapped rate so that when sensor access is
801 // restored, the correct event rate is used.
802 dev.onMicSensorAccessChanged(this, handle, samplingPeriodNs);
803 }
804 }
805 }
Peng Xueb4d6282015-12-10 18:02:41 -0800806}
807
808status_t SensorService::SensorEventConnection::flush() {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700809 if (mDestroyed) {
810 return DEAD_OBJECT;
811 }
812
Peng Xueb4d6282015-12-10 18:02:41 -0800813 return mService->flushSensor(this, mOpPackageName);
814}
815
Peng Xue36e3472016-11-03 11:57:10 -0700816int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
817 // SensorEventConnection does not support configureChannel, parameters not used
818 UNUSED(handle);
819 UNUSED(rateLevel);
820 return INVALID_OPERATION;
821}
822
Peng Xueb4d6282015-12-10 18:02:41 -0800823int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
824 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
825 {
826 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
827 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
828 // can release the wake-lock.
829 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700830 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800831 mDead = true;
832 mWakeLockRefCount = 0;
833 updateLooperRegistrationLocked(mService->getLooper());
834 }
835 mService->checkWakeLockState();
836 if (mDataInjectionMode) {
837 // If the Looper has encountered some error in data injection mode, reset SensorService
838 // back to normal mode.
839 mService->resetToNormalMode();
840 mDataInjectionMode = false;
841 }
842 return 1;
843 }
844
845 if (events & ALOOPER_EVENT_INPUT) {
846 unsigned char buf[sizeof(sensors_event_t)];
847 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
848 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700849 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700850 if (numBytesRead == sizeof(sensors_event_t)) {
851 if (!mDataInjectionMode) {
852 ALOGE("Data injected in normal mode, dropping event"
Tomasz Wasilczykfde494d2023-08-11 00:06:51 +0000853 "package=%s uid=%d", mPackageName.c_str(), mUid);
Peng Xu755c4512016-04-07 23:15:14 -0700854 // Unregister call backs.
855 return 0;
856 }
Anthony Stangecd01ec12023-01-06 18:35:13 +0000857 if (!mService->isAllowListedPackage(mPackageName)) {
Anthony Stange9bb16702023-01-03 22:42:31 +0000858 ALOGE("App not allowed to inject data, dropping event"
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000859 "package=%s uid=%d", mPackageName.c_str(), mUid);
Anthony Stange9bb16702023-01-03 22:42:31 +0000860 return 0;
861 }
Peng Xu755c4512016-04-07 23:15:14 -0700862 sensors_event_t sensor_event;
863 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100864 std::shared_ptr<SensorInterface> si =
Peng Xu755c4512016-04-07 23:15:14 -0700865 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
866 if (si == nullptr) {
867 return 1;
868 }
869
870 SensorDevice& dev(SensorDevice::getInstance());
871 sensor_event.type = si->getSensor().getType();
872 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800873#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700874 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800875#endif
Peng Xu755c4512016-04-07 23:15:14 -0700876 } else if (numBytesRead == sizeof(uint32_t)) {
877 uint32_t numAcks = 0;
878 memcpy(&numAcks, buf, numBytesRead);
lifr3ab0a1b2021-08-06 00:14:26 +0800879 // Check to ensure there are no read errors in recv, numAcks is always
Peng Xu755c4512016-04-07 23:15:14 -0700880 // within the range and not zero. If any of the above don't hold reset
881 // mWakeLockRefCount to zero.
882 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
883 mWakeLockRefCount -= numAcks;
884 } else {
885 mWakeLockRefCount = 0;
886 }
Peng Xueb4d6282015-12-10 18:02:41 -0800887#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700888 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800889#endif
890 } else {
891 // Read error, reset wakelock refcount.
892 mWakeLockRefCount = 0;
893 }
894 }
895 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
896 // here as checkWakeLockState() will need it.
897 if (mWakeLockRefCount == 0) {
898 mService->checkWakeLockState();
899 }
900 // continue getting callbacks.
901 return 1;
902 }
903
904 if (events & ALOOPER_EVENT_OUTPUT) {
905 // send sensor data that is stored in mEventCache for this connection.
906 mService->sendEventsFromCache(this);
907 }
908 return 1;
909}
910
911int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
912 size_t fifoWakeUpSensors = 0;
913 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700914 for (auto& it : mSensorInfo) {
Vladimir Komsiyski705e5ab2022-12-08 17:29:14 +0100915 std::shared_ptr<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700916 if (si == nullptr) {
917 continue;
918 }
919 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800920 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
921 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
922 // non wake_up sensors.
923 if (sensor.isWakeUpSensor()) {
924 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
925 } else {
926 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
927 }
928 } else {
929 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
930 if (sensor.isWakeUpSensor()) {
931 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
932 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
933
934 } else {
935 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
936 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
937
938 }
939 }
940 }
941 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
942 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
943 // size that is equal to that of the batch mode.
944 // ALOGW("Write failure in non-batch mode");
945 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
946 }
947 return fifoWakeUpSensors + fifoNonWakeUpSensors;
948}
949
950} // namespace android
951