blob: d14a3014c8bf8345ceed03162efc285d729e2b1d [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 {
Anthony Stange07eb4212020-08-28 14:50:28 -040031namespace {
32
33// Used as the default value for the target SDK until it's obtained via getTargetSdkVersion.
34constexpr int kTargetSdkUnknown = 0;
35
36} // namespace
Peng Xueb4d6282015-12-10 18:02:41 -080037
38SensorService::SensorEventConnection::SensorEventConnection(
39 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070040 const String16& opPackageName)
Peng Xueb4d6282015-12-10 18:02:41 -080041 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070042 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080043 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
Anthony Stange07eb4212020-08-28 14:50:28 -040044 mPackageName(packageName), mOpPackageName(opPackageName), mTargetSdk(kTargetSdkUnknown),
45 mDestroyed(false) {
Peng Xueb4d6282015-12-10 18:02:41 -080046 mChannel = new BitTube(mService->mSocketBufferSize);
47#if DEBUG_CONNECTIONS
48 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
49 mTotalAcksNeeded = mTotalAcksReceived = 0;
50#endif
51}
52
53SensorService::SensorEventConnection::~SensorEventConnection() {
54 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070055 destroy();
56}
57
58void SensorService::SensorEventConnection::destroy() {
59 Mutex::Autolock _l(mDestroyLock);
60
61 // destroy once only
62 if (mDestroyed) {
63 return;
64 }
65
Peng Xueb4d6282015-12-10 18:02:41 -080066 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070067 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080068 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080069 }
Peng Xu8cbefd72017-07-10 16:41:08 -070070 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080071}
72
73void SensorService::SensorEventConnection::onFirstRef() {
74 LooperCallback::onFirstRef();
75}
76
77bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070078 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080079 return !mDead && mWakeLockRefCount > 0;
80}
81
82void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070083 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080084 mWakeLockRefCount = 0;
85}
86
87void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070088 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070089 result.appendFormat("\tOperating Mode: ");
90 if (!mService->isWhiteListedPackage(getPackageName())) {
91 result.append("RESTRICTED\n");
92 } else if (mDataInjectionMode) {
93 result.append("DATA_INJECTION\n");
94 } else {
95 result.append("NORMAL\n");
96 }
Peng Xueb4d6282015-12-10 18:02:41 -080097 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
98 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
99 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700100 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700101 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800102 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700103 mService->getSensorName(it.first).string(),
104 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -0800105 flushInfo.mFirstFlushPending ? "First flush pending" :
106 "active",
107 flushInfo.mPendingFlushEventsToSend);
108 }
109#if DEBUG_CONNECTIONS
110 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
111 " total_acks_needed %d | total_acks_recvd %d\n",
112 mEventsReceived,
113 mEventsSent,
114 mEventsSentFromCache,
115 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
116 mTotalAcksNeeded,
117 mTotalAcksReceived);
118#endif
119}
120
Mike Ma24743862020-01-29 00:36:55 -0800121/**
122 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
123 * ProtoOutputStream.
124 *
125 * See proto definition and some notes about ProtoOutputStream in
126 * frameworks/base/core/proto/android/service/sensor_service.proto
127 */
128void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
129 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700130 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800131
132 if (!mService->isWhiteListedPackage(getPackageName())) {
133 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
134 } else if (mDataInjectionMode) {
135 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
136 } else {
137 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
138 }
139 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
140 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
141 proto->write(UID, int32_t(mUid));
142 proto->write(CACHE_SIZE, int32_t(mCacheSize));
143 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700144 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700145 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800146 const uint64_t token = proto->start(FLUSH_INFOS);
147 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700148 std::string(mService->getSensorName(it.first)));
149 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800150 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
151 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
152 flushInfo.mPendingFlushEventsToSend);
153 proto->end(token);
154 }
155#if DEBUG_CONNECTIONS
156 proto->write(EVENTS_RECEIVED, mEventsReceived);
157 proto->write(EVENTS_SENT, mEventsSent);
158 proto->write(EVENTS_CACHE, mEventsSentFromCache);
159 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
160 mCacheSize));
161 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
162 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
163#endif
164}
165
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700166bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
167 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700168 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
169 if (si == nullptr ||
170 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700171 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800172 return false;
173 }
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700174 mSensorInfo[handle] = FlushInfo();
Peng Xu755c4512016-04-07 23:15:14 -0700175 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800176}
177
178bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700179 Mutex::Autolock _l(mConnectionLock);
180 if (mSensorInfo.erase(handle) >= 0) {
181 return true;
182 }
183 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800184}
185
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700186std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700187 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700188 std::vector<int32_t> list;
189 for (auto& it : mSensorInfo) {
190 list.push_back(it.first);
191 }
192 return list;
193}
194
Peng Xueb4d6282015-12-10 18:02:41 -0800195bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700196 Mutex::Autolock _l(mConnectionLock);
197 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800198}
199
200bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700201 Mutex::Autolock _l(mConnectionLock);
202 return mSensorInfo.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800203}
204
205bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700206 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700207 for (auto &it : mSensorInfo) {
208 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700209 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
210 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800211 return true;
212 }
213 }
214 return false;
215}
216
217String8 SensorService::SensorEventConnection::getPackageName() const {
218 return mPackageName;
219}
220
221void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
222 bool value) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700223 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700224 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700225 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800226 flushInfo.mFirstFlushPending = value;
227 }
228}
229
230void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700231 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800232 updateLooperRegistrationLocked(looper);
233}
234
235void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
236 const sp<Looper>& looper) {
237 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
238 mDataInjectionMode;
239 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
240 // the Looper if it has been previously added.
241 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
242 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
243 mChannel->getSendFd());
244 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
245 return; }
246
247 int looper_flags = 0;
248 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
249 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700250 for (auto& it : mSensorInfo) {
251 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700252 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
253 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800254 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800255 }
256 }
257
258 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
259 // already been added, remove it. This is likely to happen when ALL the events stored in the
260 // cache have been sent to the corresponding app.
261 if (looper_flags == 0) {
262 if (mHasLooperCallbacks) {
263 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
264 looper->removeFd(mChannel->getSendFd());
265 mHasLooperCallbacks = false;
266 }
267 return;
268 }
269
270 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
271 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700272 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800273 if (ret == 1) {
274 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
275 mHasLooperCallbacks = true;
276 } else {
277 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
278 }
279}
280
Stan Rokita29adc8c2020-07-06 17:38:03 -0700281bool SensorService::SensorEventConnection::incrementPendingFlushCountIfHasAccess(int32_t handle) {
282 if (hasSensorAccess()) {
283 Mutex::Autolock _l(mConnectionLock);
284 if (mSensorInfo.count(handle) > 0) {
285 FlushInfo& flushInfo = mSensorInfo[handle];
286 flushInfo.mPendingFlushEventsToSend++;
287 }
288 return true;
289 } else {
290 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800291 }
292}
293
294status_t SensorService::SensorEventConnection::sendEvents(
295 sensors_event_t const* buffer, size_t numEvents,
296 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700297 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800298 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800299
George Burgess IV1866ed42018-01-21 12:14:09 -0800300 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800301
Peng Xueb4d6282015-12-10 18:02:41 -0800302 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700303 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800304 if (scratch) {
305 size_t i=0;
306 while (i<numEvents) {
307 int32_t sensor_handle = buffer[i].sensor;
308 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
309 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
310 buffer[i].meta_data.sensor);
311 // Setting sensor_handle to the correct sensor to ensure the sensor events per
312 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
313 // events.
314 sensor_handle = buffer[i].meta_data.sensor;
315 }
316
Peng Xueb4d6282015-12-10 18:02:41 -0800317 // Check if this connection has registered for this sensor. If not continue to the
318 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700319 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800320 ++i;
321 continue;
322 }
323
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700324 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800325 // Check if there is a pending flush_complete event for this sensor on this connection.
326 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700327 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800328 flushInfo.mFirstFlushPending = false;
329 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
330 buffer[i].meta_data.sensor);
331 ++i;
332 continue;
333 }
334
335 // If there is a pending flush complete event for this sensor on this connection,
336 // ignore the event and proceed to the next.
337 if (flushInfo.mFirstFlushPending) {
338 ++i;
339 continue;
340 }
341
342 do {
343 // Keep copying events into the scratch buffer as long as they are regular
344 // sensor_events are from the same sensor_handle OR they are flush_complete_events
345 // from the same sensor_handle AND the current connection is mapped to the
346 // corresponding flush_complete_event.
347 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700348 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800349 scratch[count++] = buffer[i];
350 }
Peng Xueb4d6282015-12-10 18:02:41 -0800351 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700352 // Regular sensor event, just copy it to the scratch buffer after checking
353 // the AppOp.
354 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800355 scratch[count++] = buffer[i];
356 }
Peng Xueb4d6282015-12-10 18:02:41 -0800357 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800358 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800359 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
360 buffer[i].type != SENSOR_TYPE_META_DATA) ||
361 (buffer[i].type == SENSOR_TYPE_META_DATA &&
362 buffer[i].meta_data.sensor == sensor_handle)));
363 }
364 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800365 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800366 scratch = const_cast<sensors_event_t *>(buffer);
367 count = numEvents;
368 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800369 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
370 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800371 for (size_t i = 0; i < numEvents; i++) {
372 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
373 scratch[count++] = buffer[i++];
374 }
375 }
376 }
Peng Xueb4d6282015-12-10 18:02:41 -0800377 }
378
379 sendPendingFlushEventsLocked();
380 // Early return if there are no events for this connection.
381 if (count == 0) {
382 return status_t(NO_ERROR);
383 }
384
385#if DEBUG_CONNECTIONS
386 mEventsReceived += count;
387#endif
388 if (mCacheSize != 0) {
389 // There are some events in the cache which need to be sent first. Copy this buffer to
390 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800391 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800392 return status_t(NO_ERROR);
393 }
394
Svet Ganove752a5c2018-01-15 17:14:20 -0800395 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800396 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800397 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
398 if (index_wake_up_event >= 0) {
399 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
400 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800401#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800402 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800403#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800404 }
Peng Xueb4d6282015-12-10 18:02:41 -0800405 }
406
407 // NOTE: ASensorEvent and sensors_event_t are the same type.
408 ssize_t size = SensorEventQueue::write(mChannel,
409 reinterpret_cast<ASensorEvent const*>(scratch), count);
410 if (size < 0) {
411 // Write error, copy events to local cache.
412 if (index_wake_up_event >= 0) {
413 // If there was a wake_up sensor_event, reset the flag.
414 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
415 if (mWakeLockRefCount > 0) {
416 --mWakeLockRefCount;
417 }
418#if DEBUG_CONNECTIONS
419 --mTotalAcksNeeded;
420#endif
421 }
Yi Kong8f313e32018-07-17 14:13:29 -0700422 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800423 mMaxCacheSize = computeMaxCacheSizeLocked();
424 mEventCache = new sensors_event_t[mMaxCacheSize];
425 mCacheSize = 0;
426 }
Brian Stack93432ad2018-11-27 18:28:48 -0800427 // Save the events so that they can be written later
428 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800429
430 // Add this file descriptor to the looper to get a callback when this fd is available for
431 // writing.
432 updateLooperRegistrationLocked(mService->getLooper());
433 return size;
434 }
435
436#if DEBUG_CONNECTIONS
437 if (size > 0) {
438 mEventsSent += count;
439 }
440#endif
441
442 return size < 0 ? status_t(size) : status_t(NO_ERROR);
443}
444
Michael Groover5e1f60b2018-12-04 22:34:29 -0800445bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700446 return mService->isUidActive(mUid)
447 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800448}
449
Brian Stackc225aa12019-04-19 09:30:25 -0700450bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
451 bool success = true;
452 const auto iter = mHandleToAppOp.find(event.sensor);
453 if (iter != mHandleToAppOp.end()) {
Anthony Stange07eb4212020-08-28 14:50:28 -0400454 if (mTargetSdk == kTargetSdkUnknown) {
455 // getTargetSdkVersion returns -1 if it fails so this operation should only be run once
456 // per connection and then cached. Perform this here as opposed to in the constructor to
457 // avoid log spam for NDK/VNDK clients that don't use sensors guarded with permissions
458 // and pass in invalid op package names.
459 mTargetSdk = SensorService::getTargetSdkVersion(mOpPackageName);
460 }
461
Brian Duddie457e6392020-06-19 11:38:29 -0700462 // Special handling for step count/detect backwards compatibility: if the app's target SDK
463 // is pre-Q, still permit delivering events to the app even if permission isn't granted
464 // (since this permission was only introduced in Q)
465 if ((event.type == SENSOR_TYPE_STEP_COUNTER || event.type == SENSOR_TYPE_STEP_DETECTOR) &&
466 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
467 success = true;
468 } else {
469 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid,
470 mOpPackageName);
471 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
472 }
Brian Stackc225aa12019-04-19 09:30:25 -0700473 }
474 return success;
475}
476
Peng Xueb4d6282015-12-10 18:02:41 -0800477void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
478 int count) {
479 sensors_event_t *eventCache_new;
480 const int new_cache_size = computeMaxCacheSizeLocked();
481 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
482 eventCache_new = new sensors_event_t[new_cache_size];
483 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
484 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
485
486 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
487 new_cache_size);
488
George Burgess IV1866ed42018-01-21 12:14:09 -0800489 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800490 mEventCache = eventCache_new;
491 mCacheSize += count;
492 mMaxCacheSize = new_cache_size;
493}
494
Brian Stack93432ad2018-11-27 18:28:48 -0800495void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
496 int count) {
497 if (count <= 0) {
498 return;
499 } else if (mCacheSize + count <= mMaxCacheSize) {
500 // The events fit within the current cache: add them
501 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
502 mCacheSize += count;
503 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
504 // The events fit within a resized cache: resize the cache and add the events
505 reAllocateCacheLocked(events, count);
506 } else {
507 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800508 int freeSpace = mMaxCacheSize - mCacheSize;
509
510 // Drop up to the currently cached number of events to make room for new events
511 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
512
513 // New events need to be dropped if there are more new events than the size of the cache
514 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
515
516 // Determine the number of new events to copy into the cache
517 int eventsToCopy = std::min(mMaxCacheSize, count);
518
Brian Stackae4053f2018-12-10 14:54:18 -0800519 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
520 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
521 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
522 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
523 count, mEventsDropped);
524 mEventsDropped = 0;
525 mTimeOfLastEventDrop = events[0].timestamp;
526 } else {
527 // Record the number dropped
528 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
529 }
530
Brian Stack93432ad2018-11-27 18:28:48 -0800531 // Check for any flush complete events in the events that will be dropped
532 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
533 countFlushCompleteEventsLocked(events, newEventsToDrop);
534
535 // Only shift the events if they will not all be overwritten
536 if (eventsToCopy != mMaxCacheSize) {
537 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
538 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
539 }
540 mCacheSize -= cachedEventsToDrop;
541
542 // Copy the events into the cache
543 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
544 eventsToCopy * sizeof(sensors_event_t));
545 mCacheSize += eventsToCopy;
546 }
547}
548
Peng Xueb4d6282015-12-10 18:02:41 -0800549void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
550 ASensorEvent flushCompleteEvent;
551 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
552 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
553 // Loop through all the sensors for this connection and check if there are any pending
554 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700555 for (auto& it : mSensorInfo) {
556 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700557 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
558 if (si == nullptr) {
559 continue;
560 }
561
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700562 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800563 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700564 flushCompleteEvent.meta_data.sensor = handle;
565 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800566 if (wakeUpSensor) {
567 ++mWakeLockRefCount;
568 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
569 }
570 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
571 if (size < 0) {
572 if (wakeUpSensor) --mWakeLockRefCount;
573 return;
574 }
575 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
576 flushCompleteEvent.meta_data.sensor);
577 flushInfo.mPendingFlushEventsToSend--;
578 }
579 }
580}
581
582void SensorService::SensorEventConnection::writeToSocketFromCache() {
583 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
584 // half the size of the socket buffer allocated in BitTube whichever is smaller.
585 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
586 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700587 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800588 // Send pending flush complete events (if any)
589 sendPendingFlushEventsLocked();
590 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
591 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800592 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800593 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800594 index_wake_up_event =
595 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
596 if (index_wake_up_event >= 0) {
597 mEventCache[index_wake_up_event + numEventsSent].flags |=
598 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
599 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800600#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800601 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800602#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800603 }
Peng Xueb4d6282015-12-10 18:02:41 -0800604 }
605
606 ssize_t size = SensorEventQueue::write(mChannel,
607 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
608 numEventsToWrite);
609 if (size < 0) {
610 if (index_wake_up_event >= 0) {
611 // If there was a wake_up sensor_event, reset the flag.
612 mEventCache[index_wake_up_event + numEventsSent].flags &=
613 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
614 if (mWakeLockRefCount > 0) {
615 --mWakeLockRefCount;
616 }
617#if DEBUG_CONNECTIONS
618 --mTotalAcksNeeded;
619#endif
620 }
621 memmove(mEventCache, &mEventCache[numEventsSent],
622 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
623 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
624 numEventsSent, mCacheSize);
625 mCacheSize -= numEventsSent;
626 return;
627 }
628 numEventsSent += numEventsToWrite;
629#if DEBUG_CONNECTIONS
630 mEventsSentFromCache += numEventsToWrite;
631#endif
632 }
633 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
634 // All events from the cache have been sent. Reset cache size to zero.
635 mCacheSize = 0;
636 // There are no more events in the cache. We don't need to poll for write on the fd.
637 // Update Looper registration.
638 updateLooperRegistrationLocked(mService->getLooper());
639}
640
641void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
642 sensors_event_t const* scratch, const int numEventsDropped) {
643 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
644 // Count flushComplete events in the events that are about to the dropped. These will be sent
645 // separately before the next batch of events.
646 for (int j = 0; j < numEventsDropped; ++j) {
647 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700648 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700649 ALOGW("%s: sensor 0x%x is not found in connection",
650 __func__, scratch[j].meta_data.sensor);
651 continue;
652 }
653
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700654 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800655 flushInfo.mPendingFlushEventsToSend++;
656 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
657 flushInfo.mPendingFlushEventsToSend);
658 }
659 }
660 return;
661}
662
663int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
664 sensors_event_t const* scratch, const int count) {
665 for (int i = 0; i < count; ++i) {
666 if (mService->isWakeUpSensorEvent(scratch[i])) {
667 return i;
668 }
669 }
670 return -1;
671}
672
673sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
674{
675 return mChannel;
676}
677
678status_t SensorService::SensorEventConnection::enableDisable(
679 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
680 int reservedFlags)
681{
682 status_t err;
683 if (enabled) {
684 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
685 reservedFlags, mOpPackageName);
686
687 } else {
688 err = mService->disable(this, handle);
689 }
690 return err;
691}
692
693status_t SensorService::SensorEventConnection::setEventRate(
694 int handle, nsecs_t samplingPeriodNs)
695{
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700696 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800697}
698
699status_t SensorService::SensorEventConnection::flush() {
700 return mService->flushSensor(this, mOpPackageName);
701}
702
Peng Xue36e3472016-11-03 11:57:10 -0700703int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
704 // SensorEventConnection does not support configureChannel, parameters not used
705 UNUSED(handle);
706 UNUSED(rateLevel);
707 return INVALID_OPERATION;
708}
709
Peng Xueb4d6282015-12-10 18:02:41 -0800710int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
711 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
712 {
713 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
714 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
715 // can release the wake-lock.
716 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700717 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800718 mDead = true;
719 mWakeLockRefCount = 0;
720 updateLooperRegistrationLocked(mService->getLooper());
721 }
722 mService->checkWakeLockState();
723 if (mDataInjectionMode) {
724 // If the Looper has encountered some error in data injection mode, reset SensorService
725 // back to normal mode.
726 mService->resetToNormalMode();
727 mDataInjectionMode = false;
728 }
729 return 1;
730 }
731
732 if (events & ALOOPER_EVENT_INPUT) {
733 unsigned char buf[sizeof(sensors_event_t)];
734 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
735 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700736 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700737 if (numBytesRead == sizeof(sensors_event_t)) {
738 if (!mDataInjectionMode) {
739 ALOGE("Data injected in normal mode, dropping event"
740 "package=%s uid=%d", mPackageName.string(), mUid);
741 // Unregister call backs.
742 return 0;
743 }
744 sensors_event_t sensor_event;
745 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
746 sp<SensorInterface> si =
747 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
748 if (si == nullptr) {
749 return 1;
750 }
751
752 SensorDevice& dev(SensorDevice::getInstance());
753 sensor_event.type = si->getSensor().getType();
754 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800755#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700756 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800757#endif
Peng Xu755c4512016-04-07 23:15:14 -0700758 } else if (numBytesRead == sizeof(uint32_t)) {
759 uint32_t numAcks = 0;
760 memcpy(&numAcks, buf, numBytesRead);
761 // Sanity check to ensure there are no read errors in recv, numAcks is always
762 // within the range and not zero. If any of the above don't hold reset
763 // mWakeLockRefCount to zero.
764 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
765 mWakeLockRefCount -= numAcks;
766 } else {
767 mWakeLockRefCount = 0;
768 }
Peng Xueb4d6282015-12-10 18:02:41 -0800769#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700770 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800771#endif
772 } else {
773 // Read error, reset wakelock refcount.
774 mWakeLockRefCount = 0;
775 }
776 }
777 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
778 // here as checkWakeLockState() will need it.
779 if (mWakeLockRefCount == 0) {
780 mService->checkWakeLockState();
781 }
782 // continue getting callbacks.
783 return 1;
784 }
785
786 if (events & ALOOPER_EVENT_OUTPUT) {
787 // send sensor data that is stored in mEventCache for this connection.
788 mService->sendEventsFromCache(this);
789 }
790 return 1;
791}
792
793int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
794 size_t fifoWakeUpSensors = 0;
795 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700796 for (auto& it : mSensorInfo) {
797 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700798 if (si == nullptr) {
799 continue;
800 }
801 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800802 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
803 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
804 // non wake_up sensors.
805 if (sensor.isWakeUpSensor()) {
806 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
807 } else {
808 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
809 }
810 } else {
811 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
812 if (sensor.isWakeUpSensor()) {
813 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
814 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
815
816 } else {
817 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
818 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
819
820 }
821 }
822 }
823 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
824 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
825 // size that is equal to that of the batch mode.
826 // ALOGW("Write failure in non-batch mode");
827 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
828 }
829 return fifoWakeUpSensors + fifoNonWakeUpSensors;
830}
831
832} // namespace android
833