blob: 9b30dceeb9c92bdd58a0b77b95d9f8154e7e524b [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
17#include <sys/socket.h>
18#include <utils/threads.h>
19
Mike Ma24743862020-01-29 00:36:55 -080020#include <android/util/ProtoOutputStream.h>
21#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080022#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080023
24#include "vec.h"
25#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070026#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080027
Peng Xue36e3472016-11-03 11:57:10 -070028#define UNUSED(x) (void)(x)
29
Peng Xueb4d6282015-12-10 18:02:41 -080030namespace android {
31
32SensorService::SensorEventConnection::SensorEventConnection(
33 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070034 const String16& opPackageName)
Peng Xueb4d6282015-12-10 18:02:41 -080035 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070036 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080037 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070038 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false) {
Peng Xueb4d6282015-12-10 18:02:41 -080039 mChannel = new BitTube(mService->mSocketBufferSize);
Brian Duddie457e6392020-06-19 11:38:29 -070040 mTargetSdk = SensorService::getTargetSdkVersion(opPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -080041#if DEBUG_CONNECTIONS
42 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
43 mTotalAcksNeeded = mTotalAcksReceived = 0;
44#endif
45}
46
47SensorService::SensorEventConnection::~SensorEventConnection() {
48 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070049 destroy();
50}
51
52void SensorService::SensorEventConnection::destroy() {
53 Mutex::Autolock _l(mDestroyLock);
54
55 // destroy once only
56 if (mDestroyed) {
57 return;
58 }
59
Peng Xueb4d6282015-12-10 18:02:41 -080060 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070061 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080062 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080063 }
Peng Xu8cbefd72017-07-10 16:41:08 -070064 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080065}
66
67void SensorService::SensorEventConnection::onFirstRef() {
68 LooperCallback::onFirstRef();
69}
70
71bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070072 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080073 return !mDead && mWakeLockRefCount > 0;
74}
75
76void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070077 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080078 mWakeLockRefCount = 0;
79}
80
81void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070082 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070083 result.appendFormat("\tOperating Mode: ");
84 if (!mService->isWhiteListedPackage(getPackageName())) {
85 result.append("RESTRICTED\n");
86 } else if (mDataInjectionMode) {
87 result.append("DATA_INJECTION\n");
88 } else {
89 result.append("NORMAL\n");
90 }
Peng Xueb4d6282015-12-10 18:02:41 -080091 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
92 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
93 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070094 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070095 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -080096 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -070097 mService->getSensorName(it.first).string(),
98 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -080099 flushInfo.mFirstFlushPending ? "First flush pending" :
100 "active",
101 flushInfo.mPendingFlushEventsToSend);
102 }
103#if DEBUG_CONNECTIONS
104 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
105 " total_acks_needed %d | total_acks_recvd %d\n",
106 mEventsReceived,
107 mEventsSent,
108 mEventsSentFromCache,
109 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
110 mTotalAcksNeeded,
111 mTotalAcksReceived);
112#endif
113}
114
Mike Ma24743862020-01-29 00:36:55 -0800115/**
116 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
117 * ProtoOutputStream.
118 *
119 * See proto definition and some notes about ProtoOutputStream in
120 * frameworks/base/core/proto/android/service/sensor_service.proto
121 */
122void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
123 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700124 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800125
126 if (!mService->isWhiteListedPackage(getPackageName())) {
127 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
128 } else if (mDataInjectionMode) {
129 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
130 } else {
131 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
132 }
133 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
134 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
135 proto->write(UID, int32_t(mUid));
136 proto->write(CACHE_SIZE, int32_t(mCacheSize));
137 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700138 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700139 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800140 const uint64_t token = proto->start(FLUSH_INFOS);
141 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700142 std::string(mService->getSensorName(it.first)));
143 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800144 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
145 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
146 flushInfo.mPendingFlushEventsToSend);
147 proto->end(token);
148 }
149#if DEBUG_CONNECTIONS
150 proto->write(EVENTS_RECEIVED, mEventsReceived);
151 proto->write(EVENTS_SENT, mEventsSent);
152 proto->write(EVENTS_CACHE, mEventsSentFromCache);
153 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
154 mCacheSize));
155 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
156 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
157#endif
158}
159
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700160bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
161 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700162 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
163 if (si == nullptr ||
164 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700165 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800166 return false;
167 }
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700168 mSensorInfo[handle] = FlushInfo();
Peng Xu755c4512016-04-07 23:15:14 -0700169 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800170}
171
172bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700173 Mutex::Autolock _l(mConnectionLock);
174 if (mSensorInfo.erase(handle) >= 0) {
175 return true;
176 }
177 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800178}
179
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700180std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700181 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700182 std::vector<int32_t> list;
183 for (auto& it : mSensorInfo) {
184 list.push_back(it.first);
185 }
186 return list;
187}
188
Peng Xueb4d6282015-12-10 18:02:41 -0800189bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700190 Mutex::Autolock _l(mConnectionLock);
191 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800192}
193
194bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700195 Mutex::Autolock _l(mConnectionLock);
196 return mSensorInfo.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800197}
198
199bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700200 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700201 for (auto &it : mSensorInfo) {
202 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700203 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
204 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800205 return true;
206 }
207 }
208 return false;
209}
210
211String8 SensorService::SensorEventConnection::getPackageName() const {
212 return mPackageName;
213}
214
215void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
216 bool value) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700217 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700218 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700219 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800220 flushInfo.mFirstFlushPending = value;
221 }
222}
223
224void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700225 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800226 updateLooperRegistrationLocked(looper);
227}
228
229void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
230 const sp<Looper>& looper) {
231 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
232 mDataInjectionMode;
233 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
234 // the Looper if it has been previously added.
235 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
236 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
237 mChannel->getSendFd());
238 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
239 return; }
240
241 int looper_flags = 0;
242 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
243 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700244 for (auto& it : mSensorInfo) {
245 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700246 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
247 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800248 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800249 }
250 }
251
252 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
253 // already been added, remove it. This is likely to happen when ALL the events stored in the
254 // cache have been sent to the corresponding app.
255 if (looper_flags == 0) {
256 if (mHasLooperCallbacks) {
257 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
258 looper->removeFd(mChannel->getSendFd());
259 mHasLooperCallbacks = false;
260 }
261 return;
262 }
263
264 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
265 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700266 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800267 if (ret == 1) {
268 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
269 mHasLooperCallbacks = true;
270 } else {
271 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
272 }
273}
274
275void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700276 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700277 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700278 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800279 flushInfo.mPendingFlushEventsToSend++;
280 }
281}
282
283status_t SensorService::SensorEventConnection::sendEvents(
284 sensors_event_t const* buffer, size_t numEvents,
285 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700286 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800287 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800288
George Burgess IV1866ed42018-01-21 12:14:09 -0800289 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800290
Peng Xueb4d6282015-12-10 18:02:41 -0800291 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700292 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800293 if (scratch) {
294 size_t i=0;
295 while (i<numEvents) {
296 int32_t sensor_handle = buffer[i].sensor;
297 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
298 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
299 buffer[i].meta_data.sensor);
300 // Setting sensor_handle to the correct sensor to ensure the sensor events per
301 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
302 // events.
303 sensor_handle = buffer[i].meta_data.sensor;
304 }
305
Peng Xueb4d6282015-12-10 18:02:41 -0800306 // Check if this connection has registered for this sensor. If not continue to the
307 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700308 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800309 ++i;
310 continue;
311 }
312
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700313 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800314 // Check if there is a pending flush_complete event for this sensor on this connection.
315 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700316 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800317 flushInfo.mFirstFlushPending = false;
318 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
319 buffer[i].meta_data.sensor);
320 ++i;
321 continue;
322 }
323
324 // If there is a pending flush complete event for this sensor on this connection,
325 // ignore the event and proceed to the next.
326 if (flushInfo.mFirstFlushPending) {
327 ++i;
328 continue;
329 }
330
331 do {
332 // Keep copying events into the scratch buffer as long as they are regular
333 // sensor_events are from the same sensor_handle OR they are flush_complete_events
334 // from the same sensor_handle AND the current connection is mapped to the
335 // corresponding flush_complete_event.
336 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700337 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800338 scratch[count++] = buffer[i];
339 }
Peng Xueb4d6282015-12-10 18:02:41 -0800340 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700341 // Regular sensor event, just copy it to the scratch buffer after checking
342 // the AppOp.
343 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800344 scratch[count++] = buffer[i];
345 }
Peng Xueb4d6282015-12-10 18:02:41 -0800346 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800347 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800348 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
349 buffer[i].type != SENSOR_TYPE_META_DATA) ||
350 (buffer[i].type == SENSOR_TYPE_META_DATA &&
351 buffer[i].meta_data.sensor == sensor_handle)));
352 }
353 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800354 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800355 scratch = const_cast<sensors_event_t *>(buffer);
356 count = numEvents;
357 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800358 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
359 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800360 for (size_t i = 0; i < numEvents; i++) {
361 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
362 scratch[count++] = buffer[i++];
363 }
364 }
365 }
Peng Xueb4d6282015-12-10 18:02:41 -0800366 }
367
368 sendPendingFlushEventsLocked();
369 // Early return if there are no events for this connection.
370 if (count == 0) {
371 return status_t(NO_ERROR);
372 }
373
374#if DEBUG_CONNECTIONS
375 mEventsReceived += count;
376#endif
377 if (mCacheSize != 0) {
378 // There are some events in the cache which need to be sent first. Copy this buffer to
379 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800380 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800381 return status_t(NO_ERROR);
382 }
383
Svet Ganove752a5c2018-01-15 17:14:20 -0800384 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800385 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800386 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
387 if (index_wake_up_event >= 0) {
388 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
389 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800390#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800391 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800392#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800393 }
Peng Xueb4d6282015-12-10 18:02:41 -0800394 }
395
396 // NOTE: ASensorEvent and sensors_event_t are the same type.
397 ssize_t size = SensorEventQueue::write(mChannel,
398 reinterpret_cast<ASensorEvent const*>(scratch), count);
399 if (size < 0) {
400 // Write error, copy events to local cache.
401 if (index_wake_up_event >= 0) {
402 // If there was a wake_up sensor_event, reset the flag.
403 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
404 if (mWakeLockRefCount > 0) {
405 --mWakeLockRefCount;
406 }
407#if DEBUG_CONNECTIONS
408 --mTotalAcksNeeded;
409#endif
410 }
Yi Kong8f313e32018-07-17 14:13:29 -0700411 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800412 mMaxCacheSize = computeMaxCacheSizeLocked();
413 mEventCache = new sensors_event_t[mMaxCacheSize];
414 mCacheSize = 0;
415 }
Brian Stack93432ad2018-11-27 18:28:48 -0800416 // Save the events so that they can be written later
417 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800418
419 // Add this file descriptor to the looper to get a callback when this fd is available for
420 // writing.
421 updateLooperRegistrationLocked(mService->getLooper());
422 return size;
423 }
424
425#if DEBUG_CONNECTIONS
426 if (size > 0) {
427 mEventsSent += count;
428 }
429#endif
430
431 return size < 0 ? status_t(size) : status_t(NO_ERROR);
432}
433
Michael Groover5e1f60b2018-12-04 22:34:29 -0800434bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700435 return mService->isUidActive(mUid)
436 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800437}
438
Brian Stackc225aa12019-04-19 09:30:25 -0700439bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
440 bool success = true;
441 const auto iter = mHandleToAppOp.find(event.sensor);
442 if (iter != mHandleToAppOp.end()) {
Brian Duddie457e6392020-06-19 11:38:29 -0700443 // Special handling for step count/detect backwards compatibility: if the app's target SDK
444 // is pre-Q, still permit delivering events to the app even if permission isn't granted
445 // (since this permission was only introduced in Q)
446 if ((event.type == SENSOR_TYPE_STEP_COUNTER || event.type == SENSOR_TYPE_STEP_DETECTOR) &&
447 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
448 success = true;
449 } else {
450 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid,
451 mOpPackageName);
452 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
453 }
Brian Stackc225aa12019-04-19 09:30:25 -0700454 }
455 return success;
456}
457
Peng Xueb4d6282015-12-10 18:02:41 -0800458void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
459 int count) {
460 sensors_event_t *eventCache_new;
461 const int new_cache_size = computeMaxCacheSizeLocked();
462 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
463 eventCache_new = new sensors_event_t[new_cache_size];
464 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
465 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
466
467 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
468 new_cache_size);
469
George Burgess IV1866ed42018-01-21 12:14:09 -0800470 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800471 mEventCache = eventCache_new;
472 mCacheSize += count;
473 mMaxCacheSize = new_cache_size;
474}
475
Brian Stack93432ad2018-11-27 18:28:48 -0800476void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
477 int count) {
478 if (count <= 0) {
479 return;
480 } else if (mCacheSize + count <= mMaxCacheSize) {
481 // The events fit within the current cache: add them
482 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
483 mCacheSize += count;
484 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
485 // The events fit within a resized cache: resize the cache and add the events
486 reAllocateCacheLocked(events, count);
487 } else {
488 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800489 int freeSpace = mMaxCacheSize - mCacheSize;
490
491 // Drop up to the currently cached number of events to make room for new events
492 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
493
494 // New events need to be dropped if there are more new events than the size of the cache
495 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
496
497 // Determine the number of new events to copy into the cache
498 int eventsToCopy = std::min(mMaxCacheSize, count);
499
Brian Stackae4053f2018-12-10 14:54:18 -0800500 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
501 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
502 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
503 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
504 count, mEventsDropped);
505 mEventsDropped = 0;
506 mTimeOfLastEventDrop = events[0].timestamp;
507 } else {
508 // Record the number dropped
509 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
510 }
511
Brian Stack93432ad2018-11-27 18:28:48 -0800512 // Check for any flush complete events in the events that will be dropped
513 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
514 countFlushCompleteEventsLocked(events, newEventsToDrop);
515
516 // Only shift the events if they will not all be overwritten
517 if (eventsToCopy != mMaxCacheSize) {
518 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
519 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
520 }
521 mCacheSize -= cachedEventsToDrop;
522
523 // Copy the events into the cache
524 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
525 eventsToCopy * sizeof(sensors_event_t));
526 mCacheSize += eventsToCopy;
527 }
528}
529
Peng Xueb4d6282015-12-10 18:02:41 -0800530void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
531 ASensorEvent flushCompleteEvent;
532 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
533 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
534 // Loop through all the sensors for this connection and check if there are any pending
535 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700536 for (auto& it : mSensorInfo) {
537 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700538 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
539 if (si == nullptr) {
540 continue;
541 }
542
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700543 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800544 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700545 flushCompleteEvent.meta_data.sensor = handle;
546 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800547 if (wakeUpSensor) {
548 ++mWakeLockRefCount;
549 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
550 }
551 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
552 if (size < 0) {
553 if (wakeUpSensor) --mWakeLockRefCount;
554 return;
555 }
556 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
557 flushCompleteEvent.meta_data.sensor);
558 flushInfo.mPendingFlushEventsToSend--;
559 }
560 }
561}
562
563void SensorService::SensorEventConnection::writeToSocketFromCache() {
564 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
565 // half the size of the socket buffer allocated in BitTube whichever is smaller.
566 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
567 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700568 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800569 // Send pending flush complete events (if any)
570 sendPendingFlushEventsLocked();
571 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
572 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800573 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800574 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800575 index_wake_up_event =
576 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
577 if (index_wake_up_event >= 0) {
578 mEventCache[index_wake_up_event + numEventsSent].flags |=
579 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
580 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800581#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800582 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800583#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800584 }
Peng Xueb4d6282015-12-10 18:02:41 -0800585 }
586
587 ssize_t size = SensorEventQueue::write(mChannel,
588 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
589 numEventsToWrite);
590 if (size < 0) {
591 if (index_wake_up_event >= 0) {
592 // If there was a wake_up sensor_event, reset the flag.
593 mEventCache[index_wake_up_event + numEventsSent].flags &=
594 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
595 if (mWakeLockRefCount > 0) {
596 --mWakeLockRefCount;
597 }
598#if DEBUG_CONNECTIONS
599 --mTotalAcksNeeded;
600#endif
601 }
602 memmove(mEventCache, &mEventCache[numEventsSent],
603 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
604 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
605 numEventsSent, mCacheSize);
606 mCacheSize -= numEventsSent;
607 return;
608 }
609 numEventsSent += numEventsToWrite;
610#if DEBUG_CONNECTIONS
611 mEventsSentFromCache += numEventsToWrite;
612#endif
613 }
614 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
615 // All events from the cache have been sent. Reset cache size to zero.
616 mCacheSize = 0;
617 // There are no more events in the cache. We don't need to poll for write on the fd.
618 // Update Looper registration.
619 updateLooperRegistrationLocked(mService->getLooper());
620}
621
622void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
623 sensors_event_t const* scratch, const int numEventsDropped) {
624 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
625 // Count flushComplete events in the events that are about to the dropped. These will be sent
626 // separately before the next batch of events.
627 for (int j = 0; j < numEventsDropped; ++j) {
628 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700629 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700630 ALOGW("%s: sensor 0x%x is not found in connection",
631 __func__, scratch[j].meta_data.sensor);
632 continue;
633 }
634
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700635 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800636 flushInfo.mPendingFlushEventsToSend++;
637 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
638 flushInfo.mPendingFlushEventsToSend);
639 }
640 }
641 return;
642}
643
644int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
645 sensors_event_t const* scratch, const int count) {
646 for (int i = 0; i < count; ++i) {
647 if (mService->isWakeUpSensorEvent(scratch[i])) {
648 return i;
649 }
650 }
651 return -1;
652}
653
654sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
655{
656 return mChannel;
657}
658
659status_t SensorService::SensorEventConnection::enableDisable(
660 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
661 int reservedFlags)
662{
663 status_t err;
664 if (enabled) {
665 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
666 reservedFlags, mOpPackageName);
667
668 } else {
669 err = mService->disable(this, handle);
670 }
671 return err;
672}
673
674status_t SensorService::SensorEventConnection::setEventRate(
675 int handle, nsecs_t samplingPeriodNs)
676{
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700677 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800678}
679
680status_t SensorService::SensorEventConnection::flush() {
681 return mService->flushSensor(this, mOpPackageName);
682}
683
Peng Xue36e3472016-11-03 11:57:10 -0700684int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
685 // SensorEventConnection does not support configureChannel, parameters not used
686 UNUSED(handle);
687 UNUSED(rateLevel);
688 return INVALID_OPERATION;
689}
690
Peng Xueb4d6282015-12-10 18:02:41 -0800691int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
692 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
693 {
694 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
695 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
696 // can release the wake-lock.
697 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700698 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800699 mDead = true;
700 mWakeLockRefCount = 0;
701 updateLooperRegistrationLocked(mService->getLooper());
702 }
703 mService->checkWakeLockState();
704 if (mDataInjectionMode) {
705 // If the Looper has encountered some error in data injection mode, reset SensorService
706 // back to normal mode.
707 mService->resetToNormalMode();
708 mDataInjectionMode = false;
709 }
710 return 1;
711 }
712
713 if (events & ALOOPER_EVENT_INPUT) {
714 unsigned char buf[sizeof(sensors_event_t)];
715 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
716 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700717 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700718 if (numBytesRead == sizeof(sensors_event_t)) {
719 if (!mDataInjectionMode) {
720 ALOGE("Data injected in normal mode, dropping event"
721 "package=%s uid=%d", mPackageName.string(), mUid);
722 // Unregister call backs.
723 return 0;
724 }
725 sensors_event_t sensor_event;
726 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
727 sp<SensorInterface> si =
728 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
729 if (si == nullptr) {
730 return 1;
731 }
732
733 SensorDevice& dev(SensorDevice::getInstance());
734 sensor_event.type = si->getSensor().getType();
735 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800736#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700737 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800738#endif
Peng Xu755c4512016-04-07 23:15:14 -0700739 } else if (numBytesRead == sizeof(uint32_t)) {
740 uint32_t numAcks = 0;
741 memcpy(&numAcks, buf, numBytesRead);
742 // Sanity check to ensure there are no read errors in recv, numAcks is always
743 // within the range and not zero. If any of the above don't hold reset
744 // mWakeLockRefCount to zero.
745 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
746 mWakeLockRefCount -= numAcks;
747 } else {
748 mWakeLockRefCount = 0;
749 }
Peng Xueb4d6282015-12-10 18:02:41 -0800750#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700751 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800752#endif
753 } else {
754 // Read error, reset wakelock refcount.
755 mWakeLockRefCount = 0;
756 }
757 }
758 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
759 // here as checkWakeLockState() will need it.
760 if (mWakeLockRefCount == 0) {
761 mService->checkWakeLockState();
762 }
763 // continue getting callbacks.
764 return 1;
765 }
766
767 if (events & ALOOPER_EVENT_OUTPUT) {
768 // send sensor data that is stored in mEventCache for this connection.
769 mService->sendEventsFromCache(this);
770 }
771 return 1;
772}
773
774int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
775 size_t fifoWakeUpSensors = 0;
776 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700777 for (auto& it : mSensorInfo) {
778 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700779 if (si == nullptr) {
780 continue;
781 }
782 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800783 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
784 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
785 // non wake_up sensors.
786 if (sensor.isWakeUpSensor()) {
787 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
788 } else {
789 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
790 }
791 } else {
792 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
793 if (sensor.isWakeUpSensor()) {
794 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
795 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
796
797 } else {
798 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
799 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
800
801 }
802 }
803 }
804 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
805 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
806 // size that is equal to that of the batch mode.
807 // ALOGW("Write failure in non-batch mode");
808 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
809 }
810 return fifoWakeUpSensors + fifoNonWakeUpSensors;
811}
812
813} // namespace android
814