blob: ccf05d916ece92eaac33c39bdf0ac6c77ccdec84 [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);
40#if DEBUG_CONNECTIONS
41 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
42 mTotalAcksNeeded = mTotalAcksReceived = 0;
43#endif
44}
45
46SensorService::SensorEventConnection::~SensorEventConnection() {
47 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070048 destroy();
49}
50
51void SensorService::SensorEventConnection::destroy() {
52 Mutex::Autolock _l(mDestroyLock);
53
54 // destroy once only
55 if (mDestroyed) {
56 return;
57 }
58
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 }
Peng Xu8cbefd72017-07-10 16:41:08 -070063 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080064}
65
66void SensorService::SensorEventConnection::onFirstRef() {
67 LooperCallback::onFirstRef();
68}
69
70bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070071 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080072 return !mDead && mWakeLockRefCount > 0;
73}
74
75void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070076 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080077 mWakeLockRefCount = 0;
78}
79
80void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070081 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070082 result.appendFormat("\tOperating Mode: ");
83 if (!mService->isWhiteListedPackage(getPackageName())) {
84 result.append("RESTRICTED\n");
85 } else if (mDataInjectionMode) {
86 result.append("DATA_INJECTION\n");
87 } else {
88 result.append("NORMAL\n");
89 }
Peng Xueb4d6282015-12-10 18:02:41 -080090 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
91 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
92 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070093 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070094 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -080095 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -070096 mService->getSensorName(it.first).string(),
97 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -080098 flushInfo.mFirstFlushPending ? "First flush pending" :
99 "active",
100 flushInfo.mPendingFlushEventsToSend);
101 }
102#if DEBUG_CONNECTIONS
103 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
104 " total_acks_needed %d | total_acks_recvd %d\n",
105 mEventsReceived,
106 mEventsSent,
107 mEventsSentFromCache,
108 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
109 mTotalAcksNeeded,
110 mTotalAcksReceived);
111#endif
112}
113
Mike Ma24743862020-01-29 00:36:55 -0800114/**
115 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
116 * ProtoOutputStream.
117 *
118 * See proto definition and some notes about ProtoOutputStream in
119 * frameworks/base/core/proto/android/service/sensor_service.proto
120 */
121void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
122 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700123 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800124
125 if (!mService->isWhiteListedPackage(getPackageName())) {
126 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
127 } else if (mDataInjectionMode) {
128 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
129 } else {
130 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
131 }
132 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
133 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
134 proto->write(UID, int32_t(mUid));
135 proto->write(CACHE_SIZE, int32_t(mCacheSize));
136 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700137 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700138 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800139 const uint64_t token = proto->start(FLUSH_INFOS);
140 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700141 std::string(mService->getSensorName(it.first)));
142 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800143 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
144 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
145 flushInfo.mPendingFlushEventsToSend);
146 proto->end(token);
147 }
148#if DEBUG_CONNECTIONS
149 proto->write(EVENTS_RECEIVED, mEventsReceived);
150 proto->write(EVENTS_SENT, mEventsSent);
151 proto->write(EVENTS_CACHE, mEventsSentFromCache);
152 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
153 mCacheSize));
154 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
155 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
156#endif
157}
158
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700159bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
160 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700161 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
162 if (si == nullptr ||
163 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700164 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800165 return false;
166 }
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700167 mSensorInfo[handle] = FlushInfo();
Peng Xu755c4512016-04-07 23:15:14 -0700168 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800169}
170
171bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700172 Mutex::Autolock _l(mConnectionLock);
173 if (mSensorInfo.erase(handle) >= 0) {
174 return true;
175 }
176 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800177}
178
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700179std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700180 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700181 std::vector<int32_t> list;
182 for (auto& it : mSensorInfo) {
183 list.push_back(it.first);
184 }
185 return list;
186}
187
Peng Xueb4d6282015-12-10 18:02:41 -0800188bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700189 Mutex::Autolock _l(mConnectionLock);
190 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800191}
192
193bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700194 Mutex::Autolock _l(mConnectionLock);
195 return mSensorInfo.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800196}
197
198bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700199 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700200 for (auto &it : mSensorInfo) {
201 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700202 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
203 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800204 return true;
205 }
206 }
207 return false;
208}
209
210String8 SensorService::SensorEventConnection::getPackageName() const {
211 return mPackageName;
212}
213
214void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
215 bool value) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700216 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700217 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700218 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800219 flushInfo.mFirstFlushPending = value;
220 }
221}
222
223void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700224 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800225 updateLooperRegistrationLocked(looper);
226}
227
228void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
229 const sp<Looper>& looper) {
230 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
231 mDataInjectionMode;
232 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
233 // the Looper if it has been previously added.
234 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
235 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
236 mChannel->getSendFd());
237 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
238 return; }
239
240 int looper_flags = 0;
241 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
242 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700243 for (auto& it : mSensorInfo) {
244 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700245 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
246 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800247 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800248 }
249 }
250
251 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
252 // already been added, remove it. This is likely to happen when ALL the events stored in the
253 // cache have been sent to the corresponding app.
254 if (looper_flags == 0) {
255 if (mHasLooperCallbacks) {
256 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
257 looper->removeFd(mChannel->getSendFd());
258 mHasLooperCallbacks = false;
259 }
260 return;
261 }
262
263 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
264 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700265 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800266 if (ret == 1) {
267 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
268 mHasLooperCallbacks = true;
269 } else {
270 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
271 }
272}
273
274void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700275 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700276 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700277 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800278 flushInfo.mPendingFlushEventsToSend++;
279 }
280}
281
282status_t SensorService::SensorEventConnection::sendEvents(
283 sensors_event_t const* buffer, size_t numEvents,
284 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700285 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800286 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800287
George Burgess IV1866ed42018-01-21 12:14:09 -0800288 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800289
Peng Xueb4d6282015-12-10 18:02:41 -0800290 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700291 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800292 if (scratch) {
293 size_t i=0;
294 while (i<numEvents) {
295 int32_t sensor_handle = buffer[i].sensor;
296 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
297 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
298 buffer[i].meta_data.sensor);
299 // Setting sensor_handle to the correct sensor to ensure the sensor events per
300 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
301 // events.
302 sensor_handle = buffer[i].meta_data.sensor;
303 }
304
Peng Xueb4d6282015-12-10 18:02:41 -0800305 // Check if this connection has registered for this sensor. If not continue to the
306 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700307 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800308 ++i;
309 continue;
310 }
311
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700312 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800313 // Check if there is a pending flush_complete event for this sensor on this connection.
314 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700315 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800316 flushInfo.mFirstFlushPending = false;
317 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
318 buffer[i].meta_data.sensor);
319 ++i;
320 continue;
321 }
322
323 // If there is a pending flush complete event for this sensor on this connection,
324 // ignore the event and proceed to the next.
325 if (flushInfo.mFirstFlushPending) {
326 ++i;
327 continue;
328 }
329
330 do {
331 // Keep copying events into the scratch buffer as long as they are regular
332 // sensor_events are from the same sensor_handle OR they are flush_complete_events
333 // from the same sensor_handle AND the current connection is mapped to the
334 // corresponding flush_complete_event.
335 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700336 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800337 scratch[count++] = buffer[i];
338 }
Peng Xueb4d6282015-12-10 18:02:41 -0800339 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700340 // Regular sensor event, just copy it to the scratch buffer after checking
341 // the AppOp.
342 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800343 scratch[count++] = buffer[i];
344 }
Peng Xueb4d6282015-12-10 18:02:41 -0800345 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800346 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800347 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
348 buffer[i].type != SENSOR_TYPE_META_DATA) ||
349 (buffer[i].type == SENSOR_TYPE_META_DATA &&
350 buffer[i].meta_data.sensor == sensor_handle)));
351 }
352 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800353 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800354 scratch = const_cast<sensors_event_t *>(buffer);
355 count = numEvents;
356 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800357 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
358 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800359 for (size_t i = 0; i < numEvents; i++) {
360 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
361 scratch[count++] = buffer[i++];
362 }
363 }
364 }
Peng Xueb4d6282015-12-10 18:02:41 -0800365 }
366
367 sendPendingFlushEventsLocked();
368 // Early return if there are no events for this connection.
369 if (count == 0) {
370 return status_t(NO_ERROR);
371 }
372
373#if DEBUG_CONNECTIONS
374 mEventsReceived += count;
375#endif
376 if (mCacheSize != 0) {
377 // There are some events in the cache which need to be sent first. Copy this buffer to
378 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800379 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800380 return status_t(NO_ERROR);
381 }
382
Svet Ganove752a5c2018-01-15 17:14:20 -0800383 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800384 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800385 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
386 if (index_wake_up_event >= 0) {
387 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
388 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800389#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800390 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800391#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800392 }
Peng Xueb4d6282015-12-10 18:02:41 -0800393 }
394
395 // NOTE: ASensorEvent and sensors_event_t are the same type.
396 ssize_t size = SensorEventQueue::write(mChannel,
397 reinterpret_cast<ASensorEvent const*>(scratch), count);
398 if (size < 0) {
399 // Write error, copy events to local cache.
400 if (index_wake_up_event >= 0) {
401 // If there was a wake_up sensor_event, reset the flag.
402 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
403 if (mWakeLockRefCount > 0) {
404 --mWakeLockRefCount;
405 }
406#if DEBUG_CONNECTIONS
407 --mTotalAcksNeeded;
408#endif
409 }
Yi Kong8f313e32018-07-17 14:13:29 -0700410 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800411 mMaxCacheSize = computeMaxCacheSizeLocked();
412 mEventCache = new sensors_event_t[mMaxCacheSize];
413 mCacheSize = 0;
414 }
Brian Stack93432ad2018-11-27 18:28:48 -0800415 // Save the events so that they can be written later
416 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800417
418 // Add this file descriptor to the looper to get a callback when this fd is available for
419 // writing.
420 updateLooperRegistrationLocked(mService->getLooper());
421 return size;
422 }
423
424#if DEBUG_CONNECTIONS
425 if (size > 0) {
426 mEventsSent += count;
427 }
428#endif
429
430 return size < 0 ? status_t(size) : status_t(NO_ERROR);
431}
432
Michael Groover5e1f60b2018-12-04 22:34:29 -0800433bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700434 return mService->isUidActive(mUid)
435 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800436}
437
Brian Stackc225aa12019-04-19 09:30:25 -0700438bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
439 bool success = true;
440 const auto iter = mHandleToAppOp.find(event.sensor);
441 if (iter != mHandleToAppOp.end()) {
442 int32_t appOpMode = mService->sAppOpsManager.noteOp((*iter).second, mUid, mOpPackageName);
443 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
444 }
445 return success;
446}
447
Peng Xueb4d6282015-12-10 18:02:41 -0800448void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
449 int count) {
450 sensors_event_t *eventCache_new;
451 const int new_cache_size = computeMaxCacheSizeLocked();
452 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
453 eventCache_new = new sensors_event_t[new_cache_size];
454 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
455 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
456
457 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
458 new_cache_size);
459
George Burgess IV1866ed42018-01-21 12:14:09 -0800460 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800461 mEventCache = eventCache_new;
462 mCacheSize += count;
463 mMaxCacheSize = new_cache_size;
464}
465
Brian Stack93432ad2018-11-27 18:28:48 -0800466void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
467 int count) {
468 if (count <= 0) {
469 return;
470 } else if (mCacheSize + count <= mMaxCacheSize) {
471 // The events fit within the current cache: add them
472 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
473 mCacheSize += count;
474 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
475 // The events fit within a resized cache: resize the cache and add the events
476 reAllocateCacheLocked(events, count);
477 } else {
478 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800479 int freeSpace = mMaxCacheSize - mCacheSize;
480
481 // Drop up to the currently cached number of events to make room for new events
482 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
483
484 // New events need to be dropped if there are more new events than the size of the cache
485 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
486
487 // Determine the number of new events to copy into the cache
488 int eventsToCopy = std::min(mMaxCacheSize, count);
489
Brian Stackae4053f2018-12-10 14:54:18 -0800490 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
491 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
492 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
493 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
494 count, mEventsDropped);
495 mEventsDropped = 0;
496 mTimeOfLastEventDrop = events[0].timestamp;
497 } else {
498 // Record the number dropped
499 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
500 }
501
Brian Stack93432ad2018-11-27 18:28:48 -0800502 // Check for any flush complete events in the events that will be dropped
503 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
504 countFlushCompleteEventsLocked(events, newEventsToDrop);
505
506 // Only shift the events if they will not all be overwritten
507 if (eventsToCopy != mMaxCacheSize) {
508 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
509 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
510 }
511 mCacheSize -= cachedEventsToDrop;
512
513 // Copy the events into the cache
514 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
515 eventsToCopy * sizeof(sensors_event_t));
516 mCacheSize += eventsToCopy;
517 }
518}
519
Peng Xueb4d6282015-12-10 18:02:41 -0800520void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
521 ASensorEvent flushCompleteEvent;
522 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
523 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
524 // Loop through all the sensors for this connection and check if there are any pending
525 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700526 for (auto& it : mSensorInfo) {
527 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700528 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
529 if (si == nullptr) {
530 continue;
531 }
532
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700533 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800534 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700535 flushCompleteEvent.meta_data.sensor = handle;
536 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800537 if (wakeUpSensor) {
538 ++mWakeLockRefCount;
539 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
540 }
541 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
542 if (size < 0) {
543 if (wakeUpSensor) --mWakeLockRefCount;
544 return;
545 }
546 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
547 flushCompleteEvent.meta_data.sensor);
548 flushInfo.mPendingFlushEventsToSend--;
549 }
550 }
551}
552
553void SensorService::SensorEventConnection::writeToSocketFromCache() {
554 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
555 // half the size of the socket buffer allocated in BitTube whichever is smaller.
556 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
557 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700558 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800559 // Send pending flush complete events (if any)
560 sendPendingFlushEventsLocked();
561 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
562 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800563 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800564 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800565 index_wake_up_event =
566 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
567 if (index_wake_up_event >= 0) {
568 mEventCache[index_wake_up_event + numEventsSent].flags |=
569 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
570 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800571#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800572 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800573#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800574 }
Peng Xueb4d6282015-12-10 18:02:41 -0800575 }
576
577 ssize_t size = SensorEventQueue::write(mChannel,
578 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
579 numEventsToWrite);
580 if (size < 0) {
581 if (index_wake_up_event >= 0) {
582 // If there was a wake_up sensor_event, reset the flag.
583 mEventCache[index_wake_up_event + numEventsSent].flags &=
584 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
585 if (mWakeLockRefCount > 0) {
586 --mWakeLockRefCount;
587 }
588#if DEBUG_CONNECTIONS
589 --mTotalAcksNeeded;
590#endif
591 }
592 memmove(mEventCache, &mEventCache[numEventsSent],
593 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
594 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
595 numEventsSent, mCacheSize);
596 mCacheSize -= numEventsSent;
597 return;
598 }
599 numEventsSent += numEventsToWrite;
600#if DEBUG_CONNECTIONS
601 mEventsSentFromCache += numEventsToWrite;
602#endif
603 }
604 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
605 // All events from the cache have been sent. Reset cache size to zero.
606 mCacheSize = 0;
607 // There are no more events in the cache. We don't need to poll for write on the fd.
608 // Update Looper registration.
609 updateLooperRegistrationLocked(mService->getLooper());
610}
611
612void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
613 sensors_event_t const* scratch, const int numEventsDropped) {
614 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
615 // Count flushComplete events in the events that are about to the dropped. These will be sent
616 // separately before the next batch of events.
617 for (int j = 0; j < numEventsDropped; ++j) {
618 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700619 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700620 ALOGW("%s: sensor 0x%x is not found in connection",
621 __func__, scratch[j].meta_data.sensor);
622 continue;
623 }
624
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700625 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800626 flushInfo.mPendingFlushEventsToSend++;
627 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
628 flushInfo.mPendingFlushEventsToSend);
629 }
630 }
631 return;
632}
633
634int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
635 sensors_event_t const* scratch, const int count) {
636 for (int i = 0; i < count; ++i) {
637 if (mService->isWakeUpSensorEvent(scratch[i])) {
638 return i;
639 }
640 }
641 return -1;
642}
643
644sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
645{
646 return mChannel;
647}
648
649status_t SensorService::SensorEventConnection::enableDisable(
650 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
651 int reservedFlags)
652{
653 status_t err;
654 if (enabled) {
655 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
656 reservedFlags, mOpPackageName);
657
658 } else {
659 err = mService->disable(this, handle);
660 }
661 return err;
662}
663
664status_t SensorService::SensorEventConnection::setEventRate(
665 int handle, nsecs_t samplingPeriodNs)
666{
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700667 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800668}
669
670status_t SensorService::SensorEventConnection::flush() {
671 return mService->flushSensor(this, mOpPackageName);
672}
673
Peng Xue36e3472016-11-03 11:57:10 -0700674int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
675 // SensorEventConnection does not support configureChannel, parameters not used
676 UNUSED(handle);
677 UNUSED(rateLevel);
678 return INVALID_OPERATION;
679}
680
Peng Xueb4d6282015-12-10 18:02:41 -0800681int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
682 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
683 {
684 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
685 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
686 // can release the wake-lock.
687 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700688 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800689 mDead = true;
690 mWakeLockRefCount = 0;
691 updateLooperRegistrationLocked(mService->getLooper());
692 }
693 mService->checkWakeLockState();
694 if (mDataInjectionMode) {
695 // If the Looper has encountered some error in data injection mode, reset SensorService
696 // back to normal mode.
697 mService->resetToNormalMode();
698 mDataInjectionMode = false;
699 }
700 return 1;
701 }
702
703 if (events & ALOOPER_EVENT_INPUT) {
704 unsigned char buf[sizeof(sensors_event_t)];
705 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
706 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700707 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700708 if (numBytesRead == sizeof(sensors_event_t)) {
709 if (!mDataInjectionMode) {
710 ALOGE("Data injected in normal mode, dropping event"
711 "package=%s uid=%d", mPackageName.string(), mUid);
712 // Unregister call backs.
713 return 0;
714 }
715 sensors_event_t sensor_event;
716 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
717 sp<SensorInterface> si =
718 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
719 if (si == nullptr) {
720 return 1;
721 }
722
723 SensorDevice& dev(SensorDevice::getInstance());
724 sensor_event.type = si->getSensor().getType();
725 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800726#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700727 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800728#endif
Peng Xu755c4512016-04-07 23:15:14 -0700729 } else if (numBytesRead == sizeof(uint32_t)) {
730 uint32_t numAcks = 0;
731 memcpy(&numAcks, buf, numBytesRead);
732 // Sanity check to ensure there are no read errors in recv, numAcks is always
733 // within the range and not zero. If any of the above don't hold reset
734 // mWakeLockRefCount to zero.
735 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
736 mWakeLockRefCount -= numAcks;
737 } else {
738 mWakeLockRefCount = 0;
739 }
Peng Xueb4d6282015-12-10 18:02:41 -0800740#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700741 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800742#endif
743 } else {
744 // Read error, reset wakelock refcount.
745 mWakeLockRefCount = 0;
746 }
747 }
748 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
749 // here as checkWakeLockState() will need it.
750 if (mWakeLockRefCount == 0) {
751 mService->checkWakeLockState();
752 }
753 // continue getting callbacks.
754 return 1;
755 }
756
757 if (events & ALOOPER_EVENT_OUTPUT) {
758 // send sensor data that is stored in mEventCache for this connection.
759 mService->sendEventsFromCache(this);
760 }
761 return 1;
762}
763
764int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
765 size_t fifoWakeUpSensors = 0;
766 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700767 for (auto& it : mSensorInfo) {
768 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700769 if (si == nullptr) {
770 continue;
771 }
772 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800773 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
774 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
775 // non wake_up sensors.
776 if (sensor.isWakeUpSensor()) {
777 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
778 } else {
779 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
780 }
781 } else {
782 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
783 if (sensor.isWakeUpSensor()) {
784 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
785 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
786
787 } else {
788 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
789 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
790
791 }
792 }
793 }
794 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
795 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
796 // size that is equal to that of the batch mode.
797 // ALOGW("Write failure in non-batch mode");
798 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
799 }
800 return fifoWakeUpSensors + fifoNonWakeUpSensors;
801}
802
803} // namespace android
804