blob: 6810c1b7814892edf977ea97fbb838794a978279 [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 Ishiguro3e9afc12020-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 {
Anthony Stange07eb4212020-08-28 14:50:28 -040032namespace {
33
34// Used as the default value for the target SDK until it's obtained via getTargetSdkVersion.
35constexpr int kTargetSdkUnknown = 0;
36
37} // namespace
Peng Xueb4d6282015-12-10 18:02:41 -080038
39SensorService::SensorEventConnection::SensorEventConnection(
40 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070041 const String16& opPackageName)
Peng Xueb4d6282015-12-10 18:02:41 -080042 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070043 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080044 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
Anthony Stange07eb4212020-08-28 14:50:28 -040045 mPackageName(packageName), mOpPackageName(opPackageName), mTargetSdk(kTargetSdkUnknown),
46 mDestroyed(false) {
Peng Xueb4d6282015-12-10 18:02:41 -080047 mChannel = new BitTube(mService->mSocketBufferSize);
48#if DEBUG_CONNECTIONS
49 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
50 mTotalAcksNeeded = mTotalAcksReceived = 0;
51#endif
52}
53
54SensorService::SensorEventConnection::~SensorEventConnection() {
55 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070056 destroy();
Peng Xueb4d6282015-12-10 18:02:41 -080057 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070058 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080059 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080060 }
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -070061}
62
63void SensorService::SensorEventConnection::destroy() {
Peng Xu8cbefd72017-07-10 16:41:08 -070064 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080065}
66
67void SensorService::SensorEventConnection::onFirstRef() {
68 LooperCallback::onFirstRef();
69}
70
71bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070072 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080073 return !mDead && mWakeLockRefCount > 0;
74}
75
76void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070077 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080078 mWakeLockRefCount = 0;
79}
80
81void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070082 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070083 result.appendFormat("\tOperating Mode: ");
84 if (!mService->isWhiteListedPackage(getPackageName())) {
85 result.append("RESTRICTED\n");
86 } else if (mDataInjectionMode) {
87 result.append("DATA_INJECTION\n");
88 } else {
89 result.append("NORMAL\n");
90 }
Peng Xueb4d6282015-12-10 18:02:41 -080091 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
92 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
93 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070094 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070095 const FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -080096 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -070097 mService->getSensorName(it.first).string(),
98 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -080099 flushInfo.mFirstFlushPending ? "First flush pending" :
100 "active",
101 flushInfo.mPendingFlushEventsToSend);
102 }
103#if DEBUG_CONNECTIONS
104 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
105 " total_acks_needed %d | total_acks_recvd %d\n",
106 mEventsReceived,
107 mEventsSent,
108 mEventsSentFromCache,
109 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
110 mTotalAcksNeeded,
111 mTotalAcksReceived);
112#endif
113}
114
Mike Ma24743862020-01-29 00:36:55 -0800115/**
116 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
117 * ProtoOutputStream.
118 *
119 * See proto definition and some notes about ProtoOutputStream in
120 * frameworks/base/core/proto/android/service/sensor_service.proto
121 */
122void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
123 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700124 Mutex::Autolock _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800125
126 if (!mService->isWhiteListedPackage(getPackageName())) {
127 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
128 } else if (mDataInjectionMode) {
129 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
130 } else {
131 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
132 }
133 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
134 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
135 proto->write(UID, int32_t(mUid));
136 proto->write(CACHE_SIZE, int32_t(mCacheSize));
137 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700138 for (auto& it : mSensorInfo) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700139 const FlushInfo& flushInfo = it.second;
Mike Ma24743862020-01-29 00:36:55 -0800140 const uint64_t token = proto->start(FLUSH_INFOS);
141 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700142 std::string(mService->getSensorName(it.first)));
143 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800144 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
145 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
146 flushInfo.mPendingFlushEventsToSend);
147 proto->end(token);
148 }
149#if DEBUG_CONNECTIONS
150 proto->write(EVENTS_RECEIVED, mEventsReceived);
151 proto->write(EVENTS_SENT, mEventsSent);
152 proto->write(EVENTS_CACHE, mEventsSentFromCache);
153 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
154 mCacheSize));
155 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
156 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
157#endif
158}
159
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700160bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
161 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700162 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
163 if (si == nullptr ||
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700164 !canAccessSensor(si->getSensor(), "Add to SensorEventConnection: ", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700165 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800166 return false;
167 }
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700168 mSensorInfo[handle] = FlushInfo();
Peng Xu755c4512016-04-07 23:15:14 -0700169 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800170}
171
172bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700173 Mutex::Autolock _l(mConnectionLock);
174 if (mSensorInfo.erase(handle) >= 0) {
175 return true;
176 }
177 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800178}
179
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700180std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700181 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700182 std::vector<int32_t> list;
183 for (auto& it : mSensorInfo) {
184 list.push_back(it.first);
185 }
186 return list;
187}
188
Peng Xueb4d6282015-12-10 18:02:41 -0800189bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700190 Mutex::Autolock _l(mConnectionLock);
191 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800192}
193
194bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700195 Mutex::Autolock _l(mConnectionLock);
196 return mSensorInfo.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800197}
198
199bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700200 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700201 for (auto &it : mSensorInfo) {
202 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700203 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
204 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800205 return true;
206 }
207 }
208 return false;
209}
210
211String8 SensorService::SensorEventConnection::getPackageName() const {
212 return mPackageName;
213}
214
215void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
216 bool value) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700217 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700218 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700219 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800220 flushInfo.mFirstFlushPending = value;
221 }
222}
223
224void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700225 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800226 updateLooperRegistrationLocked(looper);
227}
228
229void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
230 const sp<Looper>& looper) {
231 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
232 mDataInjectionMode;
233 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
234 // the Looper if it has been previously added.
235 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
236 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
237 mChannel->getSendFd());
238 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
239 return; }
240
241 int looper_flags = 0;
242 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
243 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700244 for (auto& it : mSensorInfo) {
245 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700246 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
247 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800248 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800249 }
250 }
251
252 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
253 // already been added, remove it. This is likely to happen when ALL the events stored in the
254 // cache have been sent to the corresponding app.
255 if (looper_flags == 0) {
256 if (mHasLooperCallbacks) {
257 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
258 looper->removeFd(mChannel->getSendFd());
259 mHasLooperCallbacks = false;
260 }
261 return;
262 }
263
264 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
265 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700266 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800267 if (ret == 1) {
268 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
269 mHasLooperCallbacks = true;
270 } else {
271 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
272 }
273}
274
Stan Rokita29adc8c2020-07-06 17:38:03 -0700275bool SensorService::SensorEventConnection::incrementPendingFlushCountIfHasAccess(int32_t handle) {
276 if (hasSensorAccess()) {
277 Mutex::Autolock _l(mConnectionLock);
278 if (mSensorInfo.count(handle) > 0) {
279 FlushInfo& flushInfo = mSensorInfo[handle];
280 flushInfo.mPendingFlushEventsToSend++;
281 }
282 return true;
283 } else {
284 return false;
Peng Xueb4d6282015-12-10 18:02:41 -0800285 }
286}
287
288status_t SensorService::SensorEventConnection::sendEvents(
289 sensors_event_t const* buffer, size_t numEvents,
290 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700291 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800292 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800293
George Burgess IV1866ed42018-01-21 12:14:09 -0800294 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800295
Peng Xueb4d6282015-12-10 18:02:41 -0800296 int count = 0;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700297 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800298 if (scratch) {
299 size_t i=0;
300 while (i<numEvents) {
301 int32_t sensor_handle = buffer[i].sensor;
302 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
303 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
304 buffer[i].meta_data.sensor);
305 // Setting sensor_handle to the correct sensor to ensure the sensor events per
306 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
307 // events.
308 sensor_handle = buffer[i].meta_data.sensor;
309 }
310
Peng Xueb4d6282015-12-10 18:02:41 -0800311 // Check if this connection has registered for this sensor. If not continue to the
312 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700313 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800314 ++i;
315 continue;
316 }
317
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700318 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800319 // Check if there is a pending flush_complete event for this sensor on this connection.
320 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700321 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800322 flushInfo.mFirstFlushPending = false;
323 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
324 buffer[i].meta_data.sensor);
325 ++i;
326 continue;
327 }
328
329 // If there is a pending flush complete event for this sensor on this connection,
330 // ignore the event and proceed to the next.
331 if (flushInfo.mFirstFlushPending) {
332 ++i;
333 continue;
334 }
335
336 do {
337 // Keep copying events into the scratch buffer as long as they are regular
338 // sensor_events are from the same sensor_handle OR they are flush_complete_events
339 // from the same sensor_handle AND the current connection is mapped to the
340 // corresponding flush_complete_event.
341 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700342 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800343 scratch[count++] = buffer[i];
344 }
Peng Xueb4d6282015-12-10 18:02:41 -0800345 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700346 // Regular sensor event, just copy it to the scratch buffer after checking
347 // the AppOp.
348 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800349 scratch[count++] = buffer[i];
350 }
Peng Xueb4d6282015-12-10 18:02:41 -0800351 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800352 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800353 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
354 buffer[i].type != SENSOR_TYPE_META_DATA) ||
355 (buffer[i].type == SENSOR_TYPE_META_DATA &&
356 buffer[i].meta_data.sensor == sensor_handle)));
357 }
358 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800359 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800360 scratch = const_cast<sensors_event_t *>(buffer);
361 count = numEvents;
362 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800363 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
364 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800365 for (size_t i = 0; i < numEvents; i++) {
366 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
367 scratch[count++] = buffer[i++];
368 }
369 }
370 }
Peng Xueb4d6282015-12-10 18:02:41 -0800371 }
372
373 sendPendingFlushEventsLocked();
374 // Early return if there are no events for this connection.
375 if (count == 0) {
376 return status_t(NO_ERROR);
377 }
378
379#if DEBUG_CONNECTIONS
380 mEventsReceived += count;
381#endif
382 if (mCacheSize != 0) {
383 // There are some events in the cache which need to be sent first. Copy this buffer to
384 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800385 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800386 return status_t(NO_ERROR);
387 }
388
Svet Ganove752a5c2018-01-15 17:14:20 -0800389 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800390 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800391 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
392 if (index_wake_up_event >= 0) {
393 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
394 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800395#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800396 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800397#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800398 }
Peng Xueb4d6282015-12-10 18:02:41 -0800399 }
400
401 // NOTE: ASensorEvent and sensors_event_t are the same type.
402 ssize_t size = SensorEventQueue::write(mChannel,
403 reinterpret_cast<ASensorEvent const*>(scratch), count);
404 if (size < 0) {
405 // Write error, copy events to local cache.
406 if (index_wake_up_event >= 0) {
407 // If there was a wake_up sensor_event, reset the flag.
408 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
409 if (mWakeLockRefCount > 0) {
410 --mWakeLockRefCount;
411 }
412#if DEBUG_CONNECTIONS
413 --mTotalAcksNeeded;
414#endif
415 }
Yi Kong8f313e32018-07-17 14:13:29 -0700416 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800417 mMaxCacheSize = computeMaxCacheSizeLocked();
418 mEventCache = new sensors_event_t[mMaxCacheSize];
419 mCacheSize = 0;
420 }
Brian Stack93432ad2018-11-27 18:28:48 -0800421 // Save the events so that they can be written later
422 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800423
424 // Add this file descriptor to the looper to get a callback when this fd is available for
425 // writing.
426 updateLooperRegistrationLocked(mService->getLooper());
427 return size;
428 }
429
430#if DEBUG_CONNECTIONS
431 if (size > 0) {
432 mEventsSent += count;
433 }
434#endif
435
436 return size < 0 ? status_t(size) : status_t(NO_ERROR);
437}
438
Michael Groover5e1f60b2018-12-04 22:34:29 -0800439bool SensorService::SensorEventConnection::hasSensorAccess() {
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700440 return mService->isUidActive(mUid)
441 && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800442}
443
Brian Stackc225aa12019-04-19 09:30:25 -0700444bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
445 bool success = true;
446 const auto iter = mHandleToAppOp.find(event.sensor);
447 if (iter != mHandleToAppOp.end()) {
Anthony Stange07eb4212020-08-28 14:50:28 -0400448 if (mTargetSdk == kTargetSdkUnknown) {
449 // getTargetSdkVersion returns -1 if it fails so this operation should only be run once
450 // per connection and then cached. Perform this here as opposed to in the constructor to
451 // avoid log spam for NDK/VNDK clients that don't use sensors guarded with permissions
452 // and pass in invalid op package names.
453 mTargetSdk = SensorService::getTargetSdkVersion(mOpPackageName);
454 }
455
Brian Duddie457e6392020-06-19 11:38:29 -0700456 // Special handling for step count/detect backwards compatibility: if the app's target SDK
457 // is pre-Q, still permit delivering events to the app even if permission isn't granted
458 // (since this permission was only introduced in Q)
459 if ((event.type == SENSOR_TYPE_STEP_COUNTER || event.type == SENSOR_TYPE_STEP_DETECTOR) &&
460 mTargetSdk > 0 && mTargetSdk <= __ANDROID_API_P__) {
461 success = true;
462 } else {
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700463 int32_t sensorHandle = event.sensor;
464 String16 noteMsg("Sensor event (");
465 noteMsg.append(String16(mService->getSensorStringType(sensorHandle)));
466 noteMsg.append(String16(")"));
Brian Duddie457e6392020-06-19 11:38:29 -0700467 int32_t appOpMode = mService->sAppOpsManager.noteOp(iter->second, mUid,
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700468 mOpPackageName, {}, noteMsg);
Brian Duddie457e6392020-06-19 11:38:29 -0700469 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
470 }
Brian Stackc225aa12019-04-19 09:30:25 -0700471 }
472 return success;
473}
474
Peng Xueb4d6282015-12-10 18:02:41 -0800475void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
476 int count) {
477 sensors_event_t *eventCache_new;
478 const int new_cache_size = computeMaxCacheSizeLocked();
479 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
480 eventCache_new = new sensors_event_t[new_cache_size];
481 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
482 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
483
484 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
485 new_cache_size);
486
George Burgess IV1866ed42018-01-21 12:14:09 -0800487 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800488 mEventCache = eventCache_new;
489 mCacheSize += count;
490 mMaxCacheSize = new_cache_size;
491}
492
Brian Stack93432ad2018-11-27 18:28:48 -0800493void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
494 int count) {
495 if (count <= 0) {
496 return;
497 } else if (mCacheSize + count <= mMaxCacheSize) {
498 // The events fit within the current cache: add them
499 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
500 mCacheSize += count;
501 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
502 // The events fit within a resized cache: resize the cache and add the events
503 reAllocateCacheLocked(events, count);
504 } else {
505 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800506 int freeSpace = mMaxCacheSize - mCacheSize;
507
508 // Drop up to the currently cached number of events to make room for new events
509 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
510
511 // New events need to be dropped if there are more new events than the size of the cache
512 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
513
514 // Determine the number of new events to copy into the cache
515 int eventsToCopy = std::min(mMaxCacheSize, count);
516
Brian Stackae4053f2018-12-10 14:54:18 -0800517 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
518 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
519 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
520 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
521 count, mEventsDropped);
522 mEventsDropped = 0;
523 mTimeOfLastEventDrop = events[0].timestamp;
524 } else {
525 // Record the number dropped
526 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
527 }
528
Brian Stack93432ad2018-11-27 18:28:48 -0800529 // Check for any flush complete events in the events that will be dropped
530 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
531 countFlushCompleteEventsLocked(events, newEventsToDrop);
532
533 // Only shift the events if they will not all be overwritten
534 if (eventsToCopy != mMaxCacheSize) {
535 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
536 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
537 }
538 mCacheSize -= cachedEventsToDrop;
539
540 // Copy the events into the cache
541 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
542 eventsToCopy * sizeof(sensors_event_t));
543 mCacheSize += eventsToCopy;
544 }
545}
546
Peng Xueb4d6282015-12-10 18:02:41 -0800547void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
548 ASensorEvent flushCompleteEvent;
549 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
550 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
551 // Loop through all the sensors for this connection and check if there are any pending
552 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700553 for (auto& it : mSensorInfo) {
554 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700555 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
556 if (si == nullptr) {
557 continue;
558 }
559
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700560 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800561 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700562 flushCompleteEvent.meta_data.sensor = handle;
563 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800564 if (wakeUpSensor) {
565 ++mWakeLockRefCount;
566 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
567 }
568 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
569 if (size < 0) {
570 if (wakeUpSensor) --mWakeLockRefCount;
571 return;
572 }
573 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
574 flushCompleteEvent.meta_data.sensor);
575 flushInfo.mPendingFlushEventsToSend--;
576 }
577 }
578}
579
580void SensorService::SensorEventConnection::writeToSocketFromCache() {
581 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
582 // half the size of the socket buffer allocated in BitTube whichever is smaller.
583 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
584 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700585 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800586 // Send pending flush complete events (if any)
587 sendPendingFlushEventsLocked();
588 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
589 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800590 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800591 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800592 index_wake_up_event =
593 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
594 if (index_wake_up_event >= 0) {
595 mEventCache[index_wake_up_event + numEventsSent].flags |=
596 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
597 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800598#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800599 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800600#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800601 }
Peng Xueb4d6282015-12-10 18:02:41 -0800602 }
603
604 ssize_t size = SensorEventQueue::write(mChannel,
605 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
606 numEventsToWrite);
607 if (size < 0) {
608 if (index_wake_up_event >= 0) {
609 // If there was a wake_up sensor_event, reset the flag.
610 mEventCache[index_wake_up_event + numEventsSent].flags &=
611 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
612 if (mWakeLockRefCount > 0) {
613 --mWakeLockRefCount;
614 }
615#if DEBUG_CONNECTIONS
616 --mTotalAcksNeeded;
617#endif
618 }
619 memmove(mEventCache, &mEventCache[numEventsSent],
620 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
621 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
622 numEventsSent, mCacheSize);
623 mCacheSize -= numEventsSent;
624 return;
625 }
626 numEventsSent += numEventsToWrite;
627#if DEBUG_CONNECTIONS
628 mEventsSentFromCache += numEventsToWrite;
629#endif
630 }
631 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
632 // All events from the cache have been sent. Reset cache size to zero.
633 mCacheSize = 0;
634 // There are no more events in the cache. We don't need to poll for write on the fd.
635 // Update Looper registration.
636 updateLooperRegistrationLocked(mService->getLooper());
637}
638
639void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
640 sensors_event_t const* scratch, const int numEventsDropped) {
641 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
642 // Count flushComplete events in the events that are about to the dropped. These will be sent
643 // separately before the next batch of events.
644 for (int j = 0; j < numEventsDropped; ++j) {
645 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700646 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700647 ALOGW("%s: sensor 0x%x is not found in connection",
648 __func__, scratch[j].meta_data.sensor);
649 continue;
650 }
651
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700652 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800653 flushInfo.mPendingFlushEventsToSend++;
654 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
655 flushInfo.mPendingFlushEventsToSend);
656 }
657 }
658 return;
659}
660
661int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
662 sensors_event_t const* scratch, const int count) {
663 for (int i = 0; i < count; ++i) {
664 if (mService->isWakeUpSensorEvent(scratch[i])) {
665 return i;
666 }
667 }
668 return -1;
669}
670
671sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
672{
673 return mChannel;
674}
675
676status_t SensorService::SensorEventConnection::enableDisable(
677 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
678 int reservedFlags)
679{
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700680 if (mDestroyed) {
681 android_errorWriteLog(0x534e4554, "168211968");
682 return DEAD_OBJECT;
683 }
684
Peng Xueb4d6282015-12-10 18:02:41 -0800685 status_t err;
686 if (enabled) {
687 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
688 reservedFlags, mOpPackageName);
689
690 } else {
691 err = mService->disable(this, handle);
692 }
693 return err;
694}
695
696status_t SensorService::SensorEventConnection::setEventRate(
697 int handle, nsecs_t samplingPeriodNs)
698{
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700699 if (mDestroyed) {
700 android_errorWriteLog(0x534e4554, "168211968");
701 return DEAD_OBJECT;
702 }
703
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700704 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800705}
706
707status_t SensorService::SensorEventConnection::flush() {
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700708 if (mDestroyed) {
709 return DEAD_OBJECT;
710 }
711
Peng Xueb4d6282015-12-10 18:02:41 -0800712 return mService->flushSensor(this, mOpPackageName);
713}
714
Peng Xue36e3472016-11-03 11:57:10 -0700715int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
716 // SensorEventConnection does not support configureChannel, parameters not used
717 UNUSED(handle);
718 UNUSED(rateLevel);
719 return INVALID_OPERATION;
720}
721
Peng Xueb4d6282015-12-10 18:02:41 -0800722int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
723 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
724 {
725 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
726 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
727 // can release the wake-lock.
728 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700729 Mutex::Autolock _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800730 mDead = true;
731 mWakeLockRefCount = 0;
732 updateLooperRegistrationLocked(mService->getLooper());
733 }
734 mService->checkWakeLockState();
735 if (mDataInjectionMode) {
736 // If the Looper has encountered some error in data injection mode, reset SensorService
737 // back to normal mode.
738 mService->resetToNormalMode();
739 mDataInjectionMode = false;
740 }
741 return 1;
742 }
743
744 if (events & ALOOPER_EVENT_INPUT) {
745 unsigned char buf[sizeof(sensors_event_t)];
746 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
747 {
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700748 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700749 if (numBytesRead == sizeof(sensors_event_t)) {
750 if (!mDataInjectionMode) {
751 ALOGE("Data injected in normal mode, dropping event"
752 "package=%s uid=%d", mPackageName.string(), mUid);
753 // Unregister call backs.
754 return 0;
755 }
756 sensors_event_t sensor_event;
757 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
758 sp<SensorInterface> si =
759 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
760 if (si == nullptr) {
761 return 1;
762 }
763
764 SensorDevice& dev(SensorDevice::getInstance());
765 sensor_event.type = si->getSensor().getType();
766 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800767#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700768 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800769#endif
Peng Xu755c4512016-04-07 23:15:14 -0700770 } else if (numBytesRead == sizeof(uint32_t)) {
771 uint32_t numAcks = 0;
772 memcpy(&numAcks, buf, numBytesRead);
773 // Sanity check to ensure there are no read errors in recv, numAcks is always
774 // within the range and not zero. If any of the above don't hold reset
775 // mWakeLockRefCount to zero.
776 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
777 mWakeLockRefCount -= numAcks;
778 } else {
779 mWakeLockRefCount = 0;
780 }
Peng Xueb4d6282015-12-10 18:02:41 -0800781#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700782 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800783#endif
784 } else {
785 // Read error, reset wakelock refcount.
786 mWakeLockRefCount = 0;
787 }
788 }
789 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
790 // here as checkWakeLockState() will need it.
791 if (mWakeLockRefCount == 0) {
792 mService->checkWakeLockState();
793 }
794 // continue getting callbacks.
795 return 1;
796 }
797
798 if (events & ALOOPER_EVENT_OUTPUT) {
799 // send sensor data that is stored in mEventCache for this connection.
800 mService->sendEventsFromCache(this);
801 }
802 return 1;
803}
804
805int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
806 size_t fifoWakeUpSensors = 0;
807 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700808 for (auto& it : mSensorInfo) {
809 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700810 if (si == nullptr) {
811 continue;
812 }
813 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800814 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
815 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
816 // non wake_up sensors.
817 if (sensor.isWakeUpSensor()) {
818 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
819 } else {
820 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
821 }
822 } else {
823 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
824 if (sensor.isWakeUpSensor()) {
825 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
826 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
827
828 } else {
829 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
830 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
831
832 }
833 }
834 }
835 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
836 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
837 // size that is equal to that of the batch mode.
838 // ALOGW("Write failure in non-batch mode");
839 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
840 }
841 return fifoWakeUpSensors + fifoNonWakeUpSensors;
842}
843
844} // namespace android
845