blob: b4b5f98609945a90499bbf46e0f35607bcd3773c [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
Stan Rokita29adc8c2020-07-06 17:38:03 -0700275bool SensorService::SensorEventConnection::incrementPendingFlushCountIfHasAccess(int32_t handle) {
276 if (hasSensorAccess()) {
277 Mutex::Autolock _l(mConnectionLock);
278 if (mSensorInfo.count(handle) > 0) {
279 FlushInfo& flushInfo = mSensorInfo[handle];
280 flushInfo.mPendingFlushEventsToSend++;
281 }
282 return true;
283 } else {
284 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800285 }
286}
287
288status_t SensorService::SensorEventConnection::sendEvents(
289 sensors_event_t const* buffer, size_t numEvents,
290 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700291 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800292 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800293
George Burgess IV1866ed42018-01-21 12:14:09 -0800294 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800295
Peng Xueb4d6282015-12-10 18:02:41 -0800296 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700297 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800298 if (scratch) {
299 size_t i=0;
300 while (i<numEvents) {
301 int32_t sensor_handle = buffer[i].sensor;
302 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
303 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
304 buffer[i].meta_data.sensor);
305 // Setting sensor_handle to the correct sensor to ensure the sensor events per
306 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
307 // events.
308 sensor_handle = buffer[i].meta_data.sensor;
309 }
310
Peng Xueb4d6282015-12-10 18:02:41 -0800311 // Check if this connection has registered for this sensor. If not continue to the
312 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700313 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800314 ++i;
315 continue;
316 }
317
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700318 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800319 // Check if there is a pending flush_complete event for this sensor on this connection.
320 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700321 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800322 flushInfo.mFirstFlushPending = false;
323 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
324 buffer[i].meta_data.sensor);
325 ++i;
326 continue;
327 }
328
329 // If there is a pending flush complete event for this sensor on this connection,
330 // ignore the event and proceed to the next.
331 if (flushInfo.mFirstFlushPending) {
332 ++i;
333 continue;
334 }
335
336 do {
337 // Keep copying events into the scratch buffer as long as they are regular
338 // sensor_events are from the same sensor_handle OR they are flush_complete_events
339 // from the same sensor_handle AND the current connection is mapped to the
340 // corresponding flush_complete_event.
341 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700342 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800343 scratch[count++] = buffer[i];
344 }
Peng Xueb4d6282015-12-10 18:02:41 -0800345 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700346 // Regular sensor event, just copy it to the scratch buffer after checking
347 // the AppOp.
348 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800349 scratch[count++] = buffer[i];
350 }
Peng Xueb4d6282015-12-10 18:02:41 -0800351 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800352 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800353 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
354 buffer[i].type != SENSOR_TYPE_META_DATA) ||
355 (buffer[i].type == SENSOR_TYPE_META_DATA &&
356 buffer[i].meta_data.sensor == sensor_handle)));
357 }
358 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800359 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800360 scratch = const_cast<sensors_event_t *>(buffer);
361 count = numEvents;
362 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800363 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
364 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800365 for (size_t i = 0; i < numEvents; i++) {
366 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
367 scratch[count++] = buffer[i++];
368 }
369 }
370 }
Peng Xueb4d6282015-12-10 18:02:41 -0800371 }
372
373 sendPendingFlushEventsLocked();
374 // Early return if there are no events for this connection.
375 if (count == 0) {
376 return status_t(NO_ERROR);
377 }
378
379#if DEBUG_CONNECTIONS
380 mEventsReceived += count;
381#endif
382 if (mCacheSize != 0) {
383 // There are some events in the cache which need to be sent first. Copy this buffer to
384 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800385 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800386 return status_t(NO_ERROR);
387 }
388
Svet Ganove752a5c2018-01-15 17:14:20 -0800389 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800390 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800391 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
392 if (index_wake_up_event >= 0) {
393 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
394 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800395#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800396 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800397#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800398 }
Peng Xueb4d6282015-12-10 18:02:41 -0800399 }
400
401 // NOTE: ASensorEvent and sensors_event_t are the same type.
402 ssize_t size = SensorEventQueue::write(mChannel,
403 reinterpret_cast<ASensorEvent const*>(scratch), count);
404 if (size < 0) {
405 // Write error, copy events to local cache.
406 if (index_wake_up_event >= 0) {
407 // If there was a wake_up sensor_event, reset the flag.
408 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
409 if (mWakeLockRefCount > 0) {
410 --mWakeLockRefCount;
411 }
412#if DEBUG_CONNECTIONS
413 --mTotalAcksNeeded;
414#endif
415 }
Yi Kong8f313e32018-07-17 14:13:29 -0700416 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800417 mMaxCacheSize = computeMaxCacheSizeLocked();
418 mEventCache = new sensors_event_t[mMaxCacheSize];
419 mCacheSize = 0;
420 }
Brian Stack93432ad2018-11-27 18:28:48 -0800421 // Save the events so that they can be written later
422 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800423
424 // Add this file descriptor to the looper to get a callback when this fd is available for
425 // writing.
426 updateLooperRegistrationLocked(mService->getLooper());
427 return size;
428 }
429
430#if DEBUG_CONNECTIONS
431 if (size > 0) {
432 mEventsSent += count;
433 }
434#endif
435
436 return size < 0 ? status_t(size) : status_t(NO_ERROR);
437}
438
Michael Groover5e1f60b2018-12-04 22:34:29 -0800439bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700440 return mService->isUidActive(mUid)
441 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800442}
443
Brian Stackc225aa12019-04-19 09:30:25 -0700444bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
445 bool success = true;
446 const auto iter = mHandleToAppOp.find(event.sensor);
447 if (iter != mHandleToAppOp.end()) {
Brian Duddie457e6392020-06-19 11:38:29 -0700448 // Special handling for step count/detect backwards compatibility: if the app's target SDK
449 // is pre-Q, still permit delivering events to the app even if permission isn't granted
450 // (since this permission was only introduced in Q)
451 if ((event.type == SENSOR_TYPE_STEP_COUNTER || event.type == SENSOR_TYPE_STEP_DETECTOR) &&
452 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
453 success = true;
454 } else {
455 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid,
456 mOpPackageName);
457 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
458 }
Brian Stackc225aa12019-04-19 09:30:25 -0700459 }
460 return success;
461}
462
Peng Xueb4d6282015-12-10 18:02:41 -0800463void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
464 int count) {
465 sensors_event_t *eventCache_new;
466 const int new_cache_size = computeMaxCacheSizeLocked();
467 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
468 eventCache_new = new sensors_event_t[new_cache_size];
469 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
470 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
471
472 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
473 new_cache_size);
474
George Burgess IV1866ed42018-01-21 12:14:09 -0800475 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800476 mEventCache = eventCache_new;
477 mCacheSize += count;
478 mMaxCacheSize = new_cache_size;
479}
480
Brian Stack93432ad2018-11-27 18:28:48 -0800481void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
482 int count) {
483 if (count <= 0) {
484 return;
485 } else if (mCacheSize + count <= mMaxCacheSize) {
486 // The events fit within the current cache: add them
487 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
488 mCacheSize += count;
489 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
490 // The events fit within a resized cache: resize the cache and add the events
491 reAllocateCacheLocked(events, count);
492 } else {
493 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800494 int freeSpace = mMaxCacheSize - mCacheSize;
495
496 // Drop up to the currently cached number of events to make room for new events
497 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
498
499 // New events need to be dropped if there are more new events than the size of the cache
500 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
501
502 // Determine the number of new events to copy into the cache
503 int eventsToCopy = std::min(mMaxCacheSize, count);
504
Brian Stackae4053f2018-12-10 14:54:18 -0800505 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
506 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
507 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
508 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
509 count, mEventsDropped);
510 mEventsDropped = 0;
511 mTimeOfLastEventDrop = events[0].timestamp;
512 } else {
513 // Record the number dropped
514 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
515 }
516
Brian Stack93432ad2018-11-27 18:28:48 -0800517 // Check for any flush complete events in the events that will be dropped
518 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
519 countFlushCompleteEventsLocked(events, newEventsToDrop);
520
521 // Only shift the events if they will not all be overwritten
522 if (eventsToCopy != mMaxCacheSize) {
523 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
524 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
525 }
526 mCacheSize -= cachedEventsToDrop;
527
528 // Copy the events into the cache
529 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
530 eventsToCopy * sizeof(sensors_event_t));
531 mCacheSize += eventsToCopy;
532 }
533}
534
Peng Xueb4d6282015-12-10 18:02:41 -0800535void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
536 ASensorEvent flushCompleteEvent;
537 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
538 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
539 // Loop through all the sensors for this connection and check if there are any pending
540 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700541 for (auto& it : mSensorInfo) {
542 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700543 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
544 if (si == nullptr) {
545 continue;
546 }
547
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700548 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800549 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700550 flushCompleteEvent.meta_data.sensor = handle;
551 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800552 if (wakeUpSensor) {
553 ++mWakeLockRefCount;
554 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
555 }
556 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
557 if (size < 0) {
558 if (wakeUpSensor) --mWakeLockRefCount;
559 return;
560 }
561 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
562 flushCompleteEvent.meta_data.sensor);
563 flushInfo.mPendingFlushEventsToSend--;
564 }
565 }
566}
567
568void SensorService::SensorEventConnection::writeToSocketFromCache() {
569 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
570 // half the size of the socket buffer allocated in BitTube whichever is smaller.
571 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
572 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700573 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800574 // Send pending flush complete events (if any)
575 sendPendingFlushEventsLocked();
576 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
577 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800578 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800579 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800580 index_wake_up_event =
581 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
582 if (index_wake_up_event >= 0) {
583 mEventCache[index_wake_up_event + numEventsSent].flags |=
584 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
585 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800586#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800587 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800588#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800589 }
Peng Xueb4d6282015-12-10 18:02:41 -0800590 }
591
592 ssize_t size = SensorEventQueue::write(mChannel,
593 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
594 numEventsToWrite);
595 if (size < 0) {
596 if (index_wake_up_event >= 0) {
597 // If there was a wake_up sensor_event, reset the flag.
598 mEventCache[index_wake_up_event + numEventsSent].flags &=
599 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
600 if (mWakeLockRefCount > 0) {
601 --mWakeLockRefCount;
602 }
603#if DEBUG_CONNECTIONS
604 --mTotalAcksNeeded;
605#endif
606 }
607 memmove(mEventCache, &mEventCache[numEventsSent],
608 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
609 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
610 numEventsSent, mCacheSize);
611 mCacheSize -= numEventsSent;
612 return;
613 }
614 numEventsSent += numEventsToWrite;
615#if DEBUG_CONNECTIONS
616 mEventsSentFromCache += numEventsToWrite;
617#endif
618 }
619 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
620 // All events from the cache have been sent. Reset cache size to zero.
621 mCacheSize = 0;
622 // There are no more events in the cache. We don't need to poll for write on the fd.
623 // Update Looper registration.
624 updateLooperRegistrationLocked(mService->getLooper());
625}
626
627void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
628 sensors_event_t const* scratch, const int numEventsDropped) {
629 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
630 // Count flushComplete events in the events that are about to the dropped. These will be sent
631 // separately before the next batch of events.
632 for (int j = 0; j < numEventsDropped; ++j) {
633 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700634 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700635 ALOGW("%s: sensor 0x%x is not found in connection",
636 __func__, scratch[j].meta_data.sensor);
637 continue;
638 }
639
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700640 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800641 flushInfo.mPendingFlushEventsToSend++;
642 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
643 flushInfo.mPendingFlushEventsToSend);
644 }
645 }
646 return;
647}
648
649int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
650 sensors_event_t const* scratch, const int count) {
651 for (int i = 0; i < count; ++i) {
652 if (mService->isWakeUpSensorEvent(scratch[i])) {
653 return i;
654 }
655 }
656 return -1;
657}
658
659sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
660{
661 return mChannel;
662}
663
664status_t SensorService::SensorEventConnection::enableDisable(
665 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
666 int reservedFlags)
667{
668 status_t err;
669 if (enabled) {
670 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
671 reservedFlags, mOpPackageName);
672
673 } else {
674 err = mService->disable(this, handle);
675 }
676 return err;
677}
678
679status_t SensorService::SensorEventConnection::setEventRate(
680 int handle, nsecs_t samplingPeriodNs)
681{
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700682 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800683}
684
685status_t SensorService::SensorEventConnection::flush() {
686 return mService->flushSensor(this, mOpPackageName);
687}
688
Peng Xue36e3472016-11-03 11:57:10 -0700689int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
690 // SensorEventConnection does not support configureChannel, parameters not used
691 UNUSED(handle);
692 UNUSED(rateLevel);
693 return INVALID_OPERATION;
694}
695
Peng Xueb4d6282015-12-10 18:02:41 -0800696int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
697 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
698 {
699 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
700 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
701 // can release the wake-lock.
702 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700703 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800704 mDead = true;
705 mWakeLockRefCount = 0;
706 updateLooperRegistrationLocked(mService->getLooper());
707 }
708 mService->checkWakeLockState();
709 if (mDataInjectionMode) {
710 // If the Looper has encountered some error in data injection mode, reset SensorService
711 // back to normal mode.
712 mService->resetToNormalMode();
713 mDataInjectionMode = false;
714 }
715 return 1;
716 }
717
718 if (events & ALOOPER_EVENT_INPUT) {
719 unsigned char buf[sizeof(sensors_event_t)];
720 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
721 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700722 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700723 if (numBytesRead == sizeof(sensors_event_t)) {
724 if (!mDataInjectionMode) {
725 ALOGE("Data injected in normal mode, dropping event"
726 "package=%s uid=%d", mPackageName.string(), mUid);
727 // Unregister call backs.
728 return 0;
729 }
730 sensors_event_t sensor_event;
731 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
732 sp<SensorInterface> si =
733 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
734 if (si == nullptr) {
735 return 1;
736 }
737
738 SensorDevice& dev(SensorDevice::getInstance());
739 sensor_event.type = si->getSensor().getType();
740 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800741#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700742 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800743#endif
Peng Xu755c4512016-04-07 23:15:14 -0700744 } else if (numBytesRead == sizeof(uint32_t)) {
745 uint32_t numAcks = 0;
746 memcpy(&numAcks, buf, numBytesRead);
747 // Sanity check to ensure there are no read errors in recv, numAcks is always
748 // within the range and not zero. If any of the above don't hold reset
749 // mWakeLockRefCount to zero.
750 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
751 mWakeLockRefCount -= numAcks;
752 } else {
753 mWakeLockRefCount = 0;
754 }
Peng Xueb4d6282015-12-10 18:02:41 -0800755#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700756 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800757#endif
758 } else {
759 // Read error, reset wakelock refcount.
760 mWakeLockRefCount = 0;
761 }
762 }
763 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
764 // here as checkWakeLockState() will need it.
765 if (mWakeLockRefCount == 0) {
766 mService->checkWakeLockState();
767 }
768 // continue getting callbacks.
769 return 1;
770 }
771
772 if (events & ALOOPER_EVENT_OUTPUT) {
773 // send sensor data that is stored in mEventCache for this connection.
774 mService->sendEventsFromCache(this);
775 }
776 return 1;
777}
778
779int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
780 size_t fifoWakeUpSensors = 0;
781 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700782 for (auto& it : mSensorInfo) {
783 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700784 if (si == nullptr) {
785 continue;
786 }
787 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800788 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
789 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
790 // non wake_up sensors.
791 if (sensor.isWakeUpSensor()) {
792 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
793 } else {
794 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
795 }
796 } else {
797 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
798 if (sensor.isWakeUpSensor()) {
799 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
800 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
801
802 } else {
803 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
804 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
805
806 }
807 }
808 }
809 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
810 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
811 // size that is equal to that of the batch mode.
812 // ALOGW("Write failure in non-batch mode");
813 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
814 }
815 return fifoWakeUpSensors + fifoNonWakeUpSensors;
816}
817
818} // namespace android
819