blob: a2e7f238b453f6328731e06ba977356fe98fd73a [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 Ishiguro539c27c2020-04-13 09:47:59 -070041 const String16& opPackageName)
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),
Anthony Stange07eb4212020-08-28 14:50:28 -040045 mPackageName(packageName), mOpPackageName(opPackageName), mTargetSdk(kTargetSdkUnknown),
46 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 Ishiguro883748c2020-10-28 13:18:02 -0700496 mOpPackageName, {}, noteMsg);
Brian Duddie457e6392020-06-19 11:38:29 -0700497 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
498 }
Brian Stackc225aa12019-04-19 09:30:25 -0700499 }
500 return success;
501}
502
Peng Xueb4d6282015-12-10 18:02:41 -0800503void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
504 int count) {
505 sensors_event_t *eventCache_new;
506 const int new_cache_size = computeMaxCacheSizeLocked();
507 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
508 eventCache_new = new sensors_event_t[new_cache_size];
509 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
510 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
511
512 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
513 new_cache_size);
514
George Burgess IV1866ed42018-01-21 12:14:09 -0800515 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800516 mEventCache = eventCache_new;
517 mCacheSize += count;
518 mMaxCacheSize = new_cache_size;
519}
520
Brian Stack93432ad2018-11-27 18:28:48 -0800521void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
522 int count) {
523 if (count <= 0) {
524 return;
525 } else if (mCacheSize + count <= mMaxCacheSize) {
526 // The events fit within the current cache: add them
527 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
528 mCacheSize += count;
529 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
530 // The events fit within a resized cache: resize the cache and add the events
531 reAllocateCacheLocked(events, count);
532 } else {
533 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800534 int freeSpace = mMaxCacheSize - mCacheSize;
535
536 // Drop up to the currently cached number of events to make room for new events
537 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
538
539 // New events need to be dropped if there are more new events than the size of the cache
540 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
541
542 // Determine the number of new events to copy into the cache
543 int eventsToCopy = std::min(mMaxCacheSize, count);
544
Brian Stackae4053f2018-12-10 14:54:18 -0800545 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
546 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
547 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
548 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
549 count, mEventsDropped);
550 mEventsDropped = 0;
551 mTimeOfLastEventDrop = events[0].timestamp;
552 } else {
553 // Record the number dropped
554 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
555 }
556
Brian Stack93432ad2018-11-27 18:28:48 -0800557 // Check for any flush complete events in the events that will be dropped
558 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
559 countFlushCompleteEventsLocked(events, newEventsToDrop);
560
561 // Only shift the events if they will not all be overwritten
562 if (eventsToCopy != mMaxCacheSize) {
563 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
564 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
565 }
566 mCacheSize -= cachedEventsToDrop;
567
568 // Copy the events into the cache
569 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
570 eventsToCopy * sizeof(sensors_event_t));
571 mCacheSize += eventsToCopy;
572 }
573}
574
Peng Xueb4d6282015-12-10 18:02:41 -0800575void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
576 ASensorEvent flushCompleteEvent;
577 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
578 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
579 // Loop through all the sensors for this connection and check if there are any pending
580 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700581 for (auto& it : mSensorInfo) {
582 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700583 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
584 if (si == nullptr) {
585 continue;
586 }
587
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700588 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800589 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700590 flushCompleteEvent.meta_data.sensor = handle;
591 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800592 if (wakeUpSensor) {
593 ++mWakeLockRefCount;
594 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
595 }
596 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
597 if (size < 0) {
598 if (wakeUpSensor) --mWakeLockRefCount;
599 return;
600 }
601 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
602 flushCompleteEvent.meta_data.sensor);
603 flushInfo.mPendingFlushEventsToSend--;
604 }
605 }
606}
607
608void SensorService::SensorEventConnection::writeToSocketFromCache() {
609 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
610 // half the size of the socket buffer allocated in BitTube whichever is smaller.
611 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
612 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700613 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800614 // Send pending flush complete events (if any)
615 sendPendingFlushEventsLocked();
616 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
617 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800618 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800619 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800620 index_wake_up_event =
621 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
622 if (index_wake_up_event >= 0) {
623 mEventCache[index_wake_up_event + numEventsSent].flags |=
624 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
625 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800626#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800627 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800628#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800629 }
Peng Xueb4d6282015-12-10 18:02:41 -0800630 }
631
632 ssize_t size = SensorEventQueue::write(mChannel,
633 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
634 numEventsToWrite);
635 if (size < 0) {
636 if (index_wake_up_event >= 0) {
637 // If there was a wake_up sensor_event, reset the flag.
638 mEventCache[index_wake_up_event + numEventsSent].flags &=
639 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
640 if (mWakeLockRefCount > 0) {
641 --mWakeLockRefCount;
642 }
643#if DEBUG_CONNECTIONS
644 --mTotalAcksNeeded;
645#endif
646 }
647 memmove(mEventCache, &mEventCache[numEventsSent],
648 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
649 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
650 numEventsSent, mCacheSize);
651 mCacheSize -= numEventsSent;
652 return;
653 }
654 numEventsSent += numEventsToWrite;
655#if DEBUG_CONNECTIONS
656 mEventsSentFromCache += numEventsToWrite;
657#endif
658 }
659 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
660 // All events from the cache have been sent. Reset cache size to zero.
661 mCacheSize = 0;
662 // There are no more events in the cache. We don't need to poll for write on the fd.
663 // Update Looper registration.
664 updateLooperRegistrationLocked(mService->getLooper());
665}
666
667void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
668 sensors_event_t const* scratch, const int numEventsDropped) {
669 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
670 // Count flushComplete events in the events that are about to the dropped. These will be sent
671 // separately before the next batch of events.
672 for (int j = 0; j < numEventsDropped; ++j) {
673 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700674 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700675 ALOGW("%s: sensor 0x%x is not found in connection",
676 __func__, scratch[j].meta_data.sensor);
677 continue;
678 }
679
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700680 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800681 flushInfo.mPendingFlushEventsToSend++;
682 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
683 flushInfo.mPendingFlushEventsToSend);
684 }
685 }
686 return;
687}
688
689int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
690 sensors_event_t const* scratch, const int count) {
691 for (int i = 0; i < count; ++i) {
692 if (mService->isWakeUpSensorEvent(scratch[i])) {
693 return i;
694 }
695 }
696 return -1;
697}
698
699sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
700{
701 return mChannel;
702}
703
704status_t SensorService::SensorEventConnection::enableDisable(
705 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
706 int reservedFlags)
707{
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700708 if (mDestroyed) {
709 android_errorWriteLog(0x534e4554, "168211968");
710 return DEAD_OBJECT;
711 }
712
Peng Xueb4d6282015-12-10 18:02:41 -0800713 status_t err;
714 if (enabled) {
Anh Pham5198c992021-02-10 14:15:30 +0100715 nsecs_t requestedSamplingPeriodNs = samplingPeriodNs;
Anh Phamaf91a912021-02-10 14:10:53 +0100716 bool isSensorCapped = false;
717 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
718 if (si != nullptr) {
719 const Sensor& s = si->getSensor();
720 if (mService->isSensorInCappedSet(s.getType())) {
721 isSensorCapped = true;
722 }
723 }
724 if (isSensorCapped) {
725 err = mService->adjustSamplingPeriodBasedOnMicAndPermission(&samplingPeriodNs,
726 String16(mOpPackageName));
727 if (err != OK) {
728 return err;
729 }
730 }
Peng Xueb4d6282015-12-10 18:02:41 -0800731 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
732 reservedFlags, mOpPackageName);
Anh Pham5198c992021-02-10 14:15:30 +0100733 if (err == OK && isSensorCapped) {
734 if (!mIsRateCappedBasedOnPermission ||
735 requestedSamplingPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
736 mMicSamplingPeriodBackup[handle] = requestedSamplingPeriodNs;
737 } else {
738 mMicSamplingPeriodBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
739 }
740 }
Peng Xueb4d6282015-12-10 18:02:41 -0800741
742 } else {
743 err = mService->disable(this, handle);
Anh Pham5198c992021-02-10 14:15:30 +0100744 mMicSamplingPeriodBackup.erase(handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800745 }
746 return err;
747}
748
Anh Phamaf91a912021-02-10 14:10:53 +0100749status_t SensorService::SensorEventConnection::setEventRate(int handle, nsecs_t samplingPeriodNs) {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700750 if (mDestroyed) {
751 android_errorWriteLog(0x534e4554, "168211968");
752 return DEAD_OBJECT;
753 }
754
Anh Pham5198c992021-02-10 14:15:30 +0100755 nsecs_t requestedSamplingPeriodNs = samplingPeriodNs;
Anh Phamaf91a912021-02-10 14:10:53 +0100756 bool isSensorCapped = false;
757 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
758 if (si != nullptr) {
759 const Sensor& s = si->getSensor();
760 if (mService->isSensorInCappedSet(s.getType())) {
761 isSensorCapped = true;
762 }
763 }
764 if (isSensorCapped) {
765 status_t err = mService->adjustSamplingPeriodBasedOnMicAndPermission(&samplingPeriodNs,
766 String16(mOpPackageName));
767 if (err != OK) {
768 return err;
769 }
770 }
Anh Pham5198c992021-02-10 14:15:30 +0100771 status_t ret = mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
772 if (ret == OK && isSensorCapped) {
773 if (!mIsRateCappedBasedOnPermission ||
774 requestedSamplingPeriodNs >= SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
775 mMicSamplingPeriodBackup[handle] = requestedSamplingPeriodNs;
776 } else {
777 mMicSamplingPeriodBackup[handle] = SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS;
778 }
779 }
780 return ret;
781}
782
783void SensorService::SensorEventConnection::onMicSensorAccessChanged(bool isMicToggleOn) {
784 if (isMicToggleOn) {
785 capRates();
786 } else {
787 uncapRates();
788 }
789}
790
791void SensorService::SensorEventConnection::capRates() {
792 Mutex::Autolock _l(mConnectionLock);
793 SensorDevice& dev(SensorDevice::getInstance());
794 for (auto &i : mMicSamplingPeriodBackup) {
795 int handle = i.first;
796 nsecs_t samplingPeriodNs = i.second;
797 if (samplingPeriodNs < SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
798 if (hasSensorAccess()) {
799 mService->setEventRate(this, handle, SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS,
800 mOpPackageName);
801 } else {
802 // Update SensorDevice with the capped rate so that when sensor access is restored,
803 // the correct event rate is used.
804 dev.onMicSensorAccessChanged(this, handle,
805 SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS);
806 }
807 }
808 }
809}
810
811void SensorService::SensorEventConnection::uncapRates() {
812 Mutex::Autolock _l(mConnectionLock);
813 SensorDevice& dev(SensorDevice::getInstance());
814 for (auto &i : mMicSamplingPeriodBackup) {
815 int handle = i.first;
816 nsecs_t samplingPeriodNs = i.second;
817 if (samplingPeriodNs < SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS) {
818 if (hasSensorAccess()) {
819 mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
820 } else {
821 // Update SensorDevice with the uncapped rate so that when sensor access is
822 // restored, the correct event rate is used.
823 dev.onMicSensorAccessChanged(this, handle, samplingPeriodNs);
824 }
825 }
826 }
Peng Xueb4d6282015-12-10 18:02:41 -0800827}
828
829status_t SensorService::SensorEventConnection::flush() {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700830 if (mDestroyed) {
831 return DEAD_OBJECT;
832 }
833
Peng Xueb4d6282015-12-10 18:02:41 -0800834 return mService->flushSensor(this, mOpPackageName);
835}
836
Peng Xue36e3472016-11-03 11:57:10 -0700837int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
838 // SensorEventConnection does not support configureChannel, parameters not used
839 UNUSED(handle);
840 UNUSED(rateLevel);
841 return INVALID_OPERATION;
842}
843
Peng Xueb4d6282015-12-10 18:02:41 -0800844int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
845 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
846 {
847 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
848 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
849 // can release the wake-lock.
850 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700851 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800852 mDead = true;
853 mWakeLockRefCount = 0;
854 updateLooperRegistrationLocked(mService->getLooper());
855 }
856 mService->checkWakeLockState();
857 if (mDataInjectionMode) {
858 // If the Looper has encountered some error in data injection mode, reset SensorService
859 // back to normal mode.
860 mService->resetToNormalMode();
861 mDataInjectionMode = false;
862 }
863 return 1;
864 }
865
866 if (events & ALOOPER_EVENT_INPUT) {
867 unsigned char buf[sizeof(sensors_event_t)];
868 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
869 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700870 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700871 if (numBytesRead == sizeof(sensors_event_t)) {
872 if (!mDataInjectionMode) {
873 ALOGE("Data injected in normal mode, dropping event"
874 "package=%s uid=%d", mPackageName.string(), mUid);
875 // Unregister call backs.
876 return 0;
877 }
878 sensors_event_t sensor_event;
879 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
880 sp<SensorInterface> si =
881 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
882 if (si == nullptr) {
883 return 1;
884 }
885
886 SensorDevice& dev(SensorDevice::getInstance());
887 sensor_event.type = si->getSensor().getType();
888 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800889#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700890 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800891#endif
Peng Xu755c4512016-04-07 23:15:14 -0700892 } else if (numBytesRead == sizeof(uint32_t)) {
893 uint32_t numAcks = 0;
894 memcpy(&numAcks, buf, numBytesRead);
895 // Sanity check to ensure there are no read errors in recv, numAcks is always
896 // within the range and not zero. If any of the above don't hold reset
897 // mWakeLockRefCount to zero.
898 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
899 mWakeLockRefCount -= numAcks;
900 } else {
901 mWakeLockRefCount = 0;
902 }
Peng Xueb4d6282015-12-10 18:02:41 -0800903#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700904 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800905#endif
906 } else {
907 // Read error, reset wakelock refcount.
908 mWakeLockRefCount = 0;
909 }
910 }
911 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
912 // here as checkWakeLockState() will need it.
913 if (mWakeLockRefCount == 0) {
914 mService->checkWakeLockState();
915 }
916 // continue getting callbacks.
917 return 1;
918 }
919
920 if (events & ALOOPER_EVENT_OUTPUT) {
921 // send sensor data that is stored in mEventCache for this connection.
922 mService->sendEventsFromCache(this);
923 }
924 return 1;
925}
926
927int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
928 size_t fifoWakeUpSensors = 0;
929 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700930 for (auto& it : mSensorInfo) {
931 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700932 if (si == nullptr) {
933 continue;
934 }
935 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800936 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
937 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
938 // non wake_up sensors.
939 if (sensor.isWakeUpSensor()) {
940 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
941 } else {
942 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
943 }
944 } else {
945 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
946 if (sensor.isWakeUpSensor()) {
947 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
948 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
949
950 } else {
951 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
952 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
953
954 }
955 }
956 }
957 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
958 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
959 // size that is equal to that of the batch mode.
960 // ALOGW("Write failure in non-batch mode");
961 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
962 }
963 return fifoWakeUpSensors + fifoNonWakeUpSensors;
964}
965
966} // namespace android
967