blob: 6c8671289d8a9877dd9d4ae1fc75c89c53be5abb [file] [log] [blame]
Peng Xueb4d6282015-12-10 18:02:41 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Arthur Ishigurof1bf7dd2020-09-22 13:05:15 -070017#include <log/log.h>
Peng Xueb4d6282015-12-10 18:02:41 -080018#include <sys/socket.h>
19#include <utils/threads.h>
20
Mike Ma24743862020-01-29 00:36:55 -080021#include <android/util/ProtoOutputStream.h>
22#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080023#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080024
25#include "vec.h"
26#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070027#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080028
Peng Xue36e3472016-11-03 11:57:10 -070029#define UNUSED(x) (void)(x)
30
Peng Xueb4d6282015-12-10 18:02:41 -080031namespace android {
32
33SensorService::SensorEventConnection::SensorEventConnection(
34 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070035 const String16& opPackageName)
Peng Xueb4d6282015-12-10 18:02:41 -080036 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070037 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080038 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070039 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false) {
Peng Xueb4d6282015-12-10 18:02:41 -080040 mChannel = new BitTube(mService->mSocketBufferSize);
Brian Duddie457e6392020-06-19 11:38:29 -070041 mTargetSdk = SensorService::getTargetSdkVersion(opPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -080042#if DEBUG_CONNECTIONS
43 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
44 mTotalAcksNeeded = mTotalAcksReceived = 0;
45#endif
46}
47
48SensorService::SensorEventConnection::~SensorEventConnection() {
49 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070050 destroy();
Peng Xueb4d6282015-12-10 18:02:41 -080051 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070052 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080053 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080054 }
Arthur Ishigurof1bf7dd2020-09-22 13:05:15 -070055}
56
57void SensorService::SensorEventConnection::destroy() {
Peng Xu8cbefd72017-07-10 16:41:08 -070058 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080059}
60
61void SensorService::SensorEventConnection::onFirstRef() {
62 LooperCallback::onFirstRef();
63}
64
65bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070066 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080067 return !mDead && mWakeLockRefCount > 0;
68}
69
70void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070071 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080072 mWakeLockRefCount = 0;
73}
74
75void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070076 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070077 result.appendFormat("\tOperating Mode: ");
78 if (!mService->isWhiteListedPackage(getPackageName())) {
79 result.append("RESTRICTED\n");
80 } else if (mDataInjectionMode) {
81 result.append("DATA_INJECTION\n");
82 } else {
83 result.append("NORMAL\n");
84 }
Peng Xueb4d6282015-12-10 18:02:41 -080085 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
86 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
87 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070088 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070089 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -080090 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -070091 mService->getSensorName(it.first).string(),
92 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -080093 flushInfo.mFirstFlushPending ? "First flush pending" :
94 "active",
95 flushInfo.mPendingFlushEventsToSend);
96 }
97#if DEBUG_CONNECTIONS
98 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
99 " total_acks_needed %d | total_acks_recvd %d\n",
100 mEventsReceived,
101 mEventsSent,
102 mEventsSentFromCache,
103 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
104 mTotalAcksNeeded,
105 mTotalAcksReceived);
106#endif
107}
108
Mike Ma24743862020-01-29 00:36:55 -0800109/**
110 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
111 * ProtoOutputStream.
112 *
113 * See proto definition and some notes about ProtoOutputStream in
114 * frameworks/base/core/proto/android/service/sensor_service.proto
115 */
116void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
117 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700118 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800119
120 if (!mService->isWhiteListedPackage(getPackageName())) {
121 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
122 } else if (mDataInjectionMode) {
123 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
124 } else {
125 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
126 }
127 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
128 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
129 proto->write(UID, int32_t(mUid));
130 proto->write(CACHE_SIZE, int32_t(mCacheSize));
131 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700132 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700133 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800134 const uint64_t token = proto->start(FLUSH_INFOS);
135 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700136 std::string(mService->getSensorName(it.first)));
137 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800138 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
139 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
140 flushInfo.mPendingFlushEventsToSend);
141 proto->end(token);
142 }
143#if DEBUG_CONNECTIONS
144 proto->write(EVENTS_RECEIVED, mEventsReceived);
145 proto->write(EVENTS_SENT, mEventsSent);
146 proto->write(EVENTS_CACHE, mEventsSentFromCache);
147 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
148 mCacheSize));
149 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
150 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
151#endif
152}
153
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700154bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
155 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700156 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
157 if (si == nullptr ||
158 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700159 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800160 return false;
161 }
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700162 mSensorInfo[handle] = FlushInfo();
Peng Xu755c4512016-04-07 23:15:14 -0700163 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800164}
165
166bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700167 Mutex::Autolock _l(mConnectionLock);
168 if (mSensorInfo.erase(handle) >= 0) {
169 return true;
170 }
171 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800172}
173
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700174std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700175 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700176 std::vector<int32_t> list;
177 for (auto& it : mSensorInfo) {
178 list.push_back(it.first);
179 }
180 return list;
181}
182
Peng Xueb4d6282015-12-10 18:02:41 -0800183bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700184 Mutex::Autolock _l(mConnectionLock);
185 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800186}
187
188bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700189 Mutex::Autolock _l(mConnectionLock);
190 return mSensorInfo.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800191}
192
193bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700194 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700195 for (auto &it : mSensorInfo) {
196 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700197 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
198 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800199 return true;
200 }
201 }
202 return false;
203}
204
205String8 SensorService::SensorEventConnection::getPackageName() const {
206 return mPackageName;
207}
208
209void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
210 bool value) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700211 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700212 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700213 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800214 flushInfo.mFirstFlushPending = value;
215 }
216}
217
218void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700219 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800220 updateLooperRegistrationLocked(looper);
221}
222
223void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
224 const sp<Looper>& looper) {
225 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
226 mDataInjectionMode;
227 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
228 // the Looper if it has been previously added.
229 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
230 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
231 mChannel->getSendFd());
232 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
233 return; }
234
235 int looper_flags = 0;
236 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
237 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700238 for (auto& it : mSensorInfo) {
239 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700240 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
241 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800242 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800243 }
244 }
245
246 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
247 // already been added, remove it. This is likely to happen when ALL the events stored in the
248 // cache have been sent to the corresponding app.
249 if (looper_flags == 0) {
250 if (mHasLooperCallbacks) {
251 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
252 looper->removeFd(mChannel->getSendFd());
253 mHasLooperCallbacks = false;
254 }
255 return;
256 }
257
258 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
259 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700260 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800261 if (ret == 1) {
262 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
263 mHasLooperCallbacks = true;
264 } else {
265 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
266 }
267}
268
Stan Rokita29adc8c2020-07-06 17:38:03 -0700269bool SensorService::SensorEventConnection::incrementPendingFlushCountIfHasAccess(int32_t handle) {
270 if (hasSensorAccess()) {
271 Mutex::Autolock _l(mConnectionLock);
272 if (mSensorInfo.count(handle) > 0) {
273 FlushInfo& flushInfo = mSensorInfo[handle];
274 flushInfo.mPendingFlushEventsToSend++;
275 }
276 return true;
277 } else {
278 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800279 }
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()) {
Brian Duddie457e6392020-06-19 11:38:29 -0700442 // Special handling for step count/detect backwards compatibility: if the app's target SDK
443 // is pre-Q, still permit delivering events to the app even if permission isn't granted
444 // (since this permission was only introduced in Q)
445 if ((event.type == SENSOR_TYPE_STEP_COUNTER || event.type == SENSOR_TYPE_STEP_DETECTOR) &&
446 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
447 success = true;
448 } else {
449 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid,
450 mOpPackageName);
451 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
452 }
Brian Stackc225aa12019-04-19 09:30:25 -0700453 }
454 return success;
455}
456
Peng Xueb4d6282015-12-10 18:02:41 -0800457void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
458 int count) {
459 sensors_event_t *eventCache_new;
460 const int new_cache_size = computeMaxCacheSizeLocked();
461 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
462 eventCache_new = new sensors_event_t[new_cache_size];
463 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
464 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
465
466 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
467 new_cache_size);
468
George Burgess IV1866ed42018-01-21 12:14:09 -0800469 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800470 mEventCache = eventCache_new;
471 mCacheSize += count;
472 mMaxCacheSize = new_cache_size;
473}
474
Brian Stack93432ad2018-11-27 18:28:48 -0800475void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
476 int count) {
477 if (count <= 0) {
478 return;
479 } else if (mCacheSize + count <= mMaxCacheSize) {
480 // The events fit within the current cache: add them
481 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
482 mCacheSize += count;
483 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
484 // The events fit within a resized cache: resize the cache and add the events
485 reAllocateCacheLocked(events, count);
486 } else {
487 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800488 int freeSpace = mMaxCacheSize - mCacheSize;
489
490 // Drop up to the currently cached number of events to make room for new events
491 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
492
493 // New events need to be dropped if there are more new events than the size of the cache
494 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
495
496 // Determine the number of new events to copy into the cache
497 int eventsToCopy = std::min(mMaxCacheSize, count);
498
Brian Stackae4053f2018-12-10 14:54:18 -0800499 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
500 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
501 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
502 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
503 count, mEventsDropped);
504 mEventsDropped = 0;
505 mTimeOfLastEventDrop = events[0].timestamp;
506 } else {
507 // Record the number dropped
508 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
509 }
510
Brian Stack93432ad2018-11-27 18:28:48 -0800511 // Check for any flush complete events in the events that will be dropped
512 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
513 countFlushCompleteEventsLocked(events, newEventsToDrop);
514
515 // Only shift the events if they will not all be overwritten
516 if (eventsToCopy != mMaxCacheSize) {
517 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
518 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
519 }
520 mCacheSize -= cachedEventsToDrop;
521
522 // Copy the events into the cache
523 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
524 eventsToCopy * sizeof(sensors_event_t));
525 mCacheSize += eventsToCopy;
526 }
527}
528
Peng Xueb4d6282015-12-10 18:02:41 -0800529void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
530 ASensorEvent flushCompleteEvent;
531 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
532 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
533 // Loop through all the sensors for this connection and check if there are any pending
534 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700535 for (auto& it : mSensorInfo) {
536 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700537 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
538 if (si == nullptr) {
539 continue;
540 }
541
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700542 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800543 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700544 flushCompleteEvent.meta_data.sensor = handle;
545 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800546 if (wakeUpSensor) {
547 ++mWakeLockRefCount;
548 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
549 }
550 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
551 if (size < 0) {
552 if (wakeUpSensor) --mWakeLockRefCount;
553 return;
554 }
555 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
556 flushCompleteEvent.meta_data.sensor);
557 flushInfo.mPendingFlushEventsToSend--;
558 }
559 }
560}
561
562void SensorService::SensorEventConnection::writeToSocketFromCache() {
563 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
564 // half the size of the socket buffer allocated in BitTube whichever is smaller.
565 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
566 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700567 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800568 // Send pending flush complete events (if any)
569 sendPendingFlushEventsLocked();
570 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
571 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800572 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800573 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800574 index_wake_up_event =
575 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
576 if (index_wake_up_event >= 0) {
577 mEventCache[index_wake_up_event + numEventsSent].flags |=
578 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
579 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800580#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800581 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800582#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800583 }
Peng Xueb4d6282015-12-10 18:02:41 -0800584 }
585
586 ssize_t size = SensorEventQueue::write(mChannel,
587 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
588 numEventsToWrite);
589 if (size < 0) {
590 if (index_wake_up_event >= 0) {
591 // If there was a wake_up sensor_event, reset the flag.
592 mEventCache[index_wake_up_event + numEventsSent].flags &=
593 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
594 if (mWakeLockRefCount > 0) {
595 --mWakeLockRefCount;
596 }
597#if DEBUG_CONNECTIONS
598 --mTotalAcksNeeded;
599#endif
600 }
601 memmove(mEventCache, &mEventCache[numEventsSent],
602 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
603 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
604 numEventsSent, mCacheSize);
605 mCacheSize -= numEventsSent;
606 return;
607 }
608 numEventsSent += numEventsToWrite;
609#if DEBUG_CONNECTIONS
610 mEventsSentFromCache += numEventsToWrite;
611#endif
612 }
613 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
614 // All events from the cache have been sent. Reset cache size to zero.
615 mCacheSize = 0;
616 // There are no more events in the cache. We don't need to poll for write on the fd.
617 // Update Looper registration.
618 updateLooperRegistrationLocked(mService->getLooper());
619}
620
621void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
622 sensors_event_t const* scratch, const int numEventsDropped) {
623 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
624 // Count flushComplete events in the events that are about to the dropped. These will be sent
625 // separately before the next batch of events.
626 for (int j = 0; j < numEventsDropped; ++j) {
627 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700628 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700629 ALOGW("%s: sensor 0x%x is not found in connection",
630 __func__, scratch[j].meta_data.sensor);
631 continue;
632 }
633
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700634 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800635 flushInfo.mPendingFlushEventsToSend++;
636 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
637 flushInfo.mPendingFlushEventsToSend);
638 }
639 }
640 return;
641}
642
643int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
644 sensors_event_t const* scratch, const int count) {
645 for (int i = 0; i < count; ++i) {
646 if (mService->isWakeUpSensorEvent(scratch[i])) {
647 return i;
648 }
649 }
650 return -1;
651}
652
653sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
654{
655 return mChannel;
656}
657
658status_t SensorService::SensorEventConnection::enableDisable(
659 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
660 int reservedFlags)
661{
Arthur Ishigurof1bf7dd2020-09-22 13:05:15 -0700662 if (mDestroyed) {
663 android_errorWriteLog(0x534e4554, "168211968");
664 return DEAD_OBJECT;
665 }
666
Peng Xueb4d6282015-12-10 18:02:41 -0800667 status_t err;
668 if (enabled) {
669 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
670 reservedFlags, mOpPackageName);
671
672 } else {
673 err = mService->disable(this, handle);
674 }
675 return err;
676}
677
678status_t SensorService::SensorEventConnection::setEventRate(
679 int handle, nsecs_t samplingPeriodNs)
680{
Arthur Ishigurof1bf7dd2020-09-22 13:05:15 -0700681 if (mDestroyed) {
682 android_errorWriteLog(0x534e4554, "168211968");
683 return DEAD_OBJECT;
684 }
685
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700686 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800687}
688
689status_t SensorService::SensorEventConnection::flush() {
Arthur Ishigurof1bf7dd2020-09-22 13:05:15 -0700690 if (mDestroyed) {
691 return DEAD_OBJECT;
692 }
693
Peng Xueb4d6282015-12-10 18:02:41 -0800694 return mService->flushSensor(this, mOpPackageName);
695}
696
Peng Xue36e3472016-11-03 11:57:10 -0700697int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
698 // SensorEventConnection does not support configureChannel, parameters not used
699 UNUSED(handle);
700 UNUSED(rateLevel);
701 return INVALID_OPERATION;
702}
703
Peng Xueb4d6282015-12-10 18:02:41 -0800704int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
705 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
706 {
707 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
708 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
709 // can release the wake-lock.
710 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700711 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800712 mDead = true;
713 mWakeLockRefCount = 0;
714 updateLooperRegistrationLocked(mService->getLooper());
715 }
716 mService->checkWakeLockState();
717 if (mDataInjectionMode) {
718 // If the Looper has encountered some error in data injection mode, reset SensorService
719 // back to normal mode.
720 mService->resetToNormalMode();
721 mDataInjectionMode = false;
722 }
723 return 1;
724 }
725
726 if (events & ALOOPER_EVENT_INPUT) {
727 unsigned char buf[sizeof(sensors_event_t)];
728 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
729 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700730 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700731 if (numBytesRead == sizeof(sensors_event_t)) {
732 if (!mDataInjectionMode) {
733 ALOGE("Data injected in normal mode, dropping event"
734 "package=%s uid=%d", mPackageName.string(), mUid);
735 // Unregister call backs.
736 return 0;
737 }
738 sensors_event_t sensor_event;
739 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
740 sp<SensorInterface> si =
741 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
742 if (si == nullptr) {
743 return 1;
744 }
745
746 SensorDevice& dev(SensorDevice::getInstance());
747 sensor_event.type = si->getSensor().getType();
748 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800749#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700750 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800751#endif
Peng Xu755c4512016-04-07 23:15:14 -0700752 } else if (numBytesRead == sizeof(uint32_t)) {
753 uint32_t numAcks = 0;
754 memcpy(&numAcks, buf, numBytesRead);
755 // Sanity check to ensure there are no read errors in recv, numAcks is always
756 // within the range and not zero. If any of the above don't hold reset
757 // mWakeLockRefCount to zero.
758 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
759 mWakeLockRefCount -= numAcks;
760 } else {
761 mWakeLockRefCount = 0;
762 }
Peng Xueb4d6282015-12-10 18:02:41 -0800763#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700764 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800765#endif
766 } else {
767 // Read error, reset wakelock refcount.
768 mWakeLockRefCount = 0;
769 }
770 }
771 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
772 // here as checkWakeLockState() will need it.
773 if (mWakeLockRefCount == 0) {
774 mService->checkWakeLockState();
775 }
776 // continue getting callbacks.
777 return 1;
778 }
779
780 if (events & ALOOPER_EVENT_OUTPUT) {
781 // send sensor data that is stored in mEventCache for this connection.
782 mService->sendEventsFromCache(this);
783 }
784 return 1;
785}
786
787int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
788 size_t fifoWakeUpSensors = 0;
789 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700790 for (auto& it : mSensorInfo) {
791 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700792 if (si == nullptr) {
793 continue;
794 }
795 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800796 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
797 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
798 // non wake_up sensors.
799 if (sensor.isWakeUpSensor()) {
800 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
801 } else {
802 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
803 }
804 } else {
805 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
806 if (sensor.isWakeUpSensor()) {
807 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
808 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
809
810 } else {
811 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
812 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
813
814 }
815 }
816 }
817 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
818 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
819 // size that is equal to that of the batch mode.
820 // ALOGW("Write failure in non-batch mode");
821 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
822 }
823 return fifoWakeUpSensors + fifoNonWakeUpSensors;
824}
825
826} // namespace android
827