blob: 77d8c11962388fc47fec3c2fcb550a677a7df151 [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 Ishiguro8a7ec572020-03-18 11:02:35 -070017#include <cinttypes>
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,
Svet Ganove752a5c2018-01-15 17:14:20 -080035 const String16& opPackageName, bool hasSensorAccess)
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),
39 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false),
40 mHasSensorAccess(hasSensorAccess) {
Peng Xueb4d6282015-12-10 18:02:41 -080041 mChannel = new BitTube(mService->mSocketBufferSize);
42#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();
51}
52
53void SensorService::SensorEventConnection::destroy() {
54 Mutex::Autolock _l(mDestroyLock);
55
56 // destroy once only
57 if (mDestroyed) {
58 return;
59 }
60
Peng Xueb4d6282015-12-10 18:02:41 -080061 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070062 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080063 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080064 }
Peng Xu8cbefd72017-07-10 16:41:08 -070065 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080066}
67
68void SensorService::SensorEventConnection::onFirstRef() {
69 LooperCallback::onFirstRef();
70}
71
72bool SensorService::SensorEventConnection::needsWakeLock() {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -070073 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080074 return !mDead && mWakeLockRefCount > 0;
75}
76
77void SensorService::SensorEventConnection::resetWakeLockRefCount() {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -070078 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -080079 mWakeLockRefCount = 0;
80}
81
82void SensorService::SensorEventConnection::dump(String8& result) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -070083 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070084 result.appendFormat("\tOperating Mode: ");
85 if (!mService->isWhiteListedPackage(getPackageName())) {
86 result.append("RESTRICTED\n");
87 } else if (mDataInjectionMode) {
88 result.append("DATA_INJECTION\n");
89 } else {
90 result.append("NORMAL\n");
91 }
Peng Xueb4d6282015-12-10 18:02:41 -080092 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
93 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
94 mMaxCacheSize);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070095 for (auto& it : mSensorInfo) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -070096 const FlushInfo& flushInfo = it.second.flushInfo;
Peng Xueb4d6282015-12-10 18:02:41 -080097 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Arthur Ishiguroad46c782020-03-26 11:24:43 -070098 mService->getSensorName(it.first).string(),
99 it.first,
Peng Xueb4d6282015-12-10 18:02:41 -0800100 flushInfo.mFirstFlushPending ? "First flush pending" :
101 "active",
102 flushInfo.mPendingFlushEventsToSend);
103 }
104#if DEBUG_CONNECTIONS
105 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
106 " total_acks_needed %d | total_acks_recvd %d\n",
107 mEventsReceived,
108 mEventsSent,
109 mEventsSentFromCache,
110 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
111 mTotalAcksNeeded,
112 mTotalAcksReceived);
113#endif
114}
115
Mike Ma24743862020-01-29 00:36:55 -0800116/**
117 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
118 * ProtoOutputStream.
119 *
120 * See proto definition and some notes about ProtoOutputStream in
121 * frameworks/base/core/proto/android/service/sensor_service.proto
122 */
123void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
124 using namespace service::SensorEventConnectionProto;
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700125 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Mike Ma24743862020-01-29 00:36:55 -0800126
127 if (!mService->isWhiteListedPackage(getPackageName())) {
128 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
129 } else if (mDataInjectionMode) {
130 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
131 } else {
132 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
133 }
134 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
135 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
136 proto->write(UID, int32_t(mUid));
137 proto->write(CACHE_SIZE, int32_t(mCacheSize));
138 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700139 for (auto& it : mSensorInfo) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700140 const FlushInfo& flushInfo = it.second.flushInfo;
Mike Ma24743862020-01-29 00:36:55 -0800141 const uint64_t token = proto->start(FLUSH_INFOS);
142 proto->write(FlushInfoProto::SENSOR_NAME,
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700143 std::string(mService->getSensorName(it.first)));
144 proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
Mike Ma24743862020-01-29 00:36:55 -0800145 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
146 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
147 flushInfo.mPendingFlushEventsToSend);
148 proto->end(token);
149 }
150#if DEBUG_CONNECTIONS
151 proto->write(EVENTS_RECEIVED, mEventsReceived);
152 proto->write(EVENTS_SENT, mEventsSent);
153 proto->write(EVENTS_CACHE, mEventsSentFromCache);
154 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
155 mCacheSize));
156 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
157 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
158#endif
159}
160
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700161bool SensorService::SensorEventConnection::addSensor(
162 int32_t handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags) {
163 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700164 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
165 if (si == nullptr ||
166 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700167 mSensorInfo.count(handle) > 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800168 return false;
169 }
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700170
171 SensorRequest request = {
172 .samplingPeriodNs = samplingPeriodNs,
173 .maxBatchReportLatencyNs = maxBatchReportLatencyNs,
174 .reservedFlags = reservedFlags
175 };
176
177 mSensorInfo[handle] = request;
Peng Xu755c4512016-04-07 23:15:14 -0700178 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800179}
180
181bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700182 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
183 return mSensorInfo.erase(handle) > 0;
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 Ishiguro8a7ec572020-03-18 11:02:35 -0700187 std::lock_guard<std::recursive_mutex> _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 Ishiguro8a7ec572020-03-18 11:02:35 -0700196 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
197 return mSensorInfo.count(handle) + mSensorInfoBackup.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800198}
199
200bool SensorService::SensorEventConnection::hasAnySensor() const {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700201 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
202 return mSensorInfo.size() + mSensorInfoBackup.size() ? true : false;
Peng Xueb4d6282015-12-10 18:02:41 -0800203}
204
205bool SensorService::SensorEventConnection::hasOneShotSensors() const {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700206 std::lock_guard<std::recursive_mutex> _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 Ishiguro8a7ec572020-03-18 11:02:35 -0700223 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700224 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700225 FlushInfo& flushInfo = mSensorInfo[handle].flushInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800226 flushInfo.mFirstFlushPending = value;
227 }
228}
229
230void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700231 std::lock_guard<std::recursive_mutex> _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
281void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700282 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700283 if (mSensorInfo.count(handle) > 0) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700284 FlushInfo& flushInfo = mSensorInfo[handle].flushInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800285 flushInfo.mPendingFlushEventsToSend++;
286 }
287}
288
289status_t SensorService::SensorEventConnection::sendEvents(
290 sensors_event_t const* buffer, size_t numEvents,
291 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700292 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800293 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800294
George Burgess IV1866ed42018-01-21 12:14:09 -0800295 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800296
Peng Xueb4d6282015-12-10 18:02:41 -0800297 int count = 0;
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700298 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800299 if (scratch) {
300 size_t i=0;
301 while (i<numEvents) {
302 int32_t sensor_handle = buffer[i].sensor;
303 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
304 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
305 buffer[i].meta_data.sensor);
306 // Setting sensor_handle to the correct sensor to ensure the sensor events per
307 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
308 // events.
309 sensor_handle = buffer[i].meta_data.sensor;
310 }
311
Peng Xueb4d6282015-12-10 18:02:41 -0800312 // Check if this connection has registered for this sensor. If not continue to the
313 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700314 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800315 ++i;
316 continue;
317 }
318
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700319 FlushInfo& flushInfo = mSensorInfo[sensor_handle].flushInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800320 // Check if there is a pending flush_complete event for this sensor on this connection.
321 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700322 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800323 flushInfo.mFirstFlushPending = false;
324 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
325 buffer[i].meta_data.sensor);
326 ++i;
327 continue;
328 }
329
330 // If there is a pending flush complete event for this sensor on this connection,
331 // ignore the event and proceed to the next.
332 if (flushInfo.mFirstFlushPending) {
333 ++i;
334 continue;
335 }
336
337 do {
338 // Keep copying events into the scratch buffer as long as they are regular
339 // sensor_events are from the same sensor_handle OR they are flush_complete_events
340 // from the same sensor_handle AND the current connection is mapped to the
341 // corresponding flush_complete_event.
342 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700343 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800344 scratch[count++] = buffer[i];
345 }
Peng Xueb4d6282015-12-10 18:02:41 -0800346 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700347 // Regular sensor event, just copy it to the scratch buffer after checking
348 // the AppOp.
349 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800350 scratch[count++] = buffer[i];
351 }
Peng Xueb4d6282015-12-10 18:02:41 -0800352 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800353 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800354 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
355 buffer[i].type != SENSOR_TYPE_META_DATA) ||
356 (buffer[i].type == SENSOR_TYPE_META_DATA &&
357 buffer[i].meta_data.sensor == sensor_handle)));
358 }
359 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800360 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800361 scratch = const_cast<sensors_event_t *>(buffer);
362 count = numEvents;
363 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800364 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
365 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800366 for (size_t i = 0; i < numEvents; i++) {
367 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
368 scratch[count++] = buffer[i++];
369 }
370 }
371 }
Peng Xueb4d6282015-12-10 18:02:41 -0800372 }
373
374 sendPendingFlushEventsLocked();
375 // Early return if there are no events for this connection.
376 if (count == 0) {
377 return status_t(NO_ERROR);
378 }
379
380#if DEBUG_CONNECTIONS
381 mEventsReceived += count;
382#endif
383 if (mCacheSize != 0) {
384 // There are some events in the cache which need to be sent first. Copy this buffer to
385 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800386 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800387 return status_t(NO_ERROR);
388 }
389
Svet Ganove752a5c2018-01-15 17:14:20 -0800390 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800391 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800392 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
393 if (index_wake_up_event >= 0) {
394 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
395 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800396#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800397 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800398#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800399 }
Peng Xueb4d6282015-12-10 18:02:41 -0800400 }
401
402 // NOTE: ASensorEvent and sensors_event_t are the same type.
403 ssize_t size = SensorEventQueue::write(mChannel,
404 reinterpret_cast<ASensorEvent const*>(scratch), count);
405 if (size < 0) {
406 // Write error, copy events to local cache.
407 if (index_wake_up_event >= 0) {
408 // If there was a wake_up sensor_event, reset the flag.
409 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
410 if (mWakeLockRefCount > 0) {
411 --mWakeLockRefCount;
412 }
413#if DEBUG_CONNECTIONS
414 --mTotalAcksNeeded;
415#endif
416 }
Yi Kong8f313e32018-07-17 14:13:29 -0700417 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800418 mMaxCacheSize = computeMaxCacheSizeLocked();
419 mEventCache = new sensors_event_t[mMaxCacheSize];
420 mCacheSize = 0;
421 }
Brian Stack93432ad2018-11-27 18:28:48 -0800422 // Save the events so that they can be written later
423 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800424
425 // Add this file descriptor to the looper to get a callback when this fd is available for
426 // writing.
427 updateLooperRegistrationLocked(mService->getLooper());
428 return size;
429 }
430
431#if DEBUG_CONNECTIONS
432 if (size > 0) {
433 mEventsSent += count;
434 }
435#endif
436
437 return size < 0 ? status_t(size) : status_t(NO_ERROR);
438}
439
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700440void SensorService::SensorEventConnection::updateSensorSubscriptions() {
441 if (!hasSensorAccess()) {
442 stopAll();
443 } else {
444 recoverAll();
445 }
446}
447
Svet Ganove752a5c2018-01-15 17:14:20 -0800448void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700449 if (mHasSensorAccess != hasAccess) {
450 mHasSensorAccess = hasAccess;
451 updateSensorSubscriptions();
452 }
453}
454
455void SensorService::SensorEventConnection::stopAll() {
456 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
457 if (!mSensorInfo.empty()) {
458 mSensorInfoBackup = mSensorInfo;
459 mSensorInfo.clear();
460
461 for (auto& it : mSensorInfoBackup) {
462 int32_t handle = it.first;
463
464 status_t err = mService->disable(this, handle);
465
466 if (err != NO_ERROR) {
467 ALOGE("Error disabling sensor %d", handle);
468 }
469 }
470 }
471}
472
473void SensorService::SensorEventConnection::recoverAll() {
474 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
475 for (auto& it : mSensorInfoBackup) {
476 int32_t handle = it.first;
477 SensorRequest &request = it.second;
478
479 status_t err = mService->enable(
480 this, handle, request.samplingPeriodNs, request.maxBatchReportLatencyNs,
481 request.reservedFlags, mOpPackageName);
482
483 if (err != NO_ERROR) {
484 ALOGE("Error recovering sensor %d", handle);
485 }
486 }
487
488 mSensorInfoBackup.clear();
Svet Ganove752a5c2018-01-15 17:14:20 -0800489}
490
Michael Groover5e1f60b2018-12-04 22:34:29 -0800491bool SensorService::SensorEventConnection::hasSensorAccess() {
492 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
493}
494
Brian Stackc225aa12019-04-19 09:30:25 -0700495bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
496 bool success = true;
497 const auto iter = mHandleToAppOp.find(event.sensor);
498 if (iter != mHandleToAppOp.end()) {
499 int32_t appOpMode = mService->sAppOpsManager.noteOp((*iter).second, mUid, mOpPackageName);
500 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
501 }
502 return success;
503}
504
Peng Xueb4d6282015-12-10 18:02:41 -0800505void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
506 int count) {
507 sensors_event_t *eventCache_new;
508 const int new_cache_size = computeMaxCacheSizeLocked();
509 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
510 eventCache_new = new sensors_event_t[new_cache_size];
511 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
512 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
513
514 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
515 new_cache_size);
516
George Burgess IV1866ed42018-01-21 12:14:09 -0800517 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800518 mEventCache = eventCache_new;
519 mCacheSize += count;
520 mMaxCacheSize = new_cache_size;
521}
522
Brian Stack93432ad2018-11-27 18:28:48 -0800523void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
524 int count) {
525 if (count <= 0) {
526 return;
527 } else if (mCacheSize + count <= mMaxCacheSize) {
528 // The events fit within the current cache: add them
529 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
530 mCacheSize += count;
531 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
532 // The events fit within a resized cache: resize the cache and add the events
533 reAllocateCacheLocked(events, count);
534 } else {
535 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800536 int freeSpace = mMaxCacheSize - mCacheSize;
537
538 // Drop up to the currently cached number of events to make room for new events
539 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
540
541 // New events need to be dropped if there are more new events than the size of the cache
542 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
543
544 // Determine the number of new events to copy into the cache
545 int eventsToCopy = std::min(mMaxCacheSize, count);
546
Brian Stackae4053f2018-12-10 14:54:18 -0800547 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
548 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
549 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
550 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
551 count, mEventsDropped);
552 mEventsDropped = 0;
553 mTimeOfLastEventDrop = events[0].timestamp;
554 } else {
555 // Record the number dropped
556 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
557 }
558
Brian Stack93432ad2018-11-27 18:28:48 -0800559 // Check for any flush complete events in the events that will be dropped
560 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
561 countFlushCompleteEventsLocked(events, newEventsToDrop);
562
563 // Only shift the events if they will not all be overwritten
564 if (eventsToCopy != mMaxCacheSize) {
565 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
566 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
567 }
568 mCacheSize -= cachedEventsToDrop;
569
570 // Copy the events into the cache
571 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
572 eventsToCopy * sizeof(sensors_event_t));
573 mCacheSize += eventsToCopy;
574 }
575}
576
Peng Xueb4d6282015-12-10 18:02:41 -0800577void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
578 ASensorEvent flushCompleteEvent;
579 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
580 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
581 // Loop through all the sensors for this connection and check if there are any pending
582 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700583 for (auto& it : mSensorInfo) {
584 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700585 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
586 if (si == nullptr) {
587 continue;
588 }
589
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700590 FlushInfo& flushInfo = it.second.flushInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800591 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700592 flushCompleteEvent.meta_data.sensor = handle;
593 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800594 if (wakeUpSensor) {
595 ++mWakeLockRefCount;
596 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
597 }
598 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
599 if (size < 0) {
600 if (wakeUpSensor) --mWakeLockRefCount;
601 return;
602 }
603 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
604 flushCompleteEvent.meta_data.sensor);
605 flushInfo.mPendingFlushEventsToSend--;
606 }
607 }
608}
609
610void SensorService::SensorEventConnection::writeToSocketFromCache() {
611 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
612 // half the size of the socket buffer allocated in BitTube whichever is smaller.
613 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
614 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700615 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800616 // Send pending flush complete events (if any)
617 sendPendingFlushEventsLocked();
618 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
619 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800620 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800621 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800622 index_wake_up_event =
623 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
624 if (index_wake_up_event >= 0) {
625 mEventCache[index_wake_up_event + numEventsSent].flags |=
626 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
627 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800628#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800629 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800630#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800631 }
Peng Xueb4d6282015-12-10 18:02:41 -0800632 }
633
634 ssize_t size = SensorEventQueue::write(mChannel,
635 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
636 numEventsToWrite);
637 if (size < 0) {
638 if (index_wake_up_event >= 0) {
639 // If there was a wake_up sensor_event, reset the flag.
640 mEventCache[index_wake_up_event + numEventsSent].flags &=
641 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
642 if (mWakeLockRefCount > 0) {
643 --mWakeLockRefCount;
644 }
645#if DEBUG_CONNECTIONS
646 --mTotalAcksNeeded;
647#endif
648 }
649 memmove(mEventCache, &mEventCache[numEventsSent],
650 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
651 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
652 numEventsSent, mCacheSize);
653 mCacheSize -= numEventsSent;
654 return;
655 }
656 numEventsSent += numEventsToWrite;
657#if DEBUG_CONNECTIONS
658 mEventsSentFromCache += numEventsToWrite;
659#endif
660 }
661 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
662 // All events from the cache have been sent. Reset cache size to zero.
663 mCacheSize = 0;
664 // There are no more events in the cache. We don't need to poll for write on the fd.
665 // Update Looper registration.
666 updateLooperRegistrationLocked(mService->getLooper());
667}
668
669void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
670 sensors_event_t const* scratch, const int numEventsDropped) {
671 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
672 // Count flushComplete events in the events that are about to the dropped. These will be sent
673 // separately before the next batch of events.
674 for (int j = 0; j < numEventsDropped; ++j) {
675 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700676 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700677 ALOGW("%s: sensor 0x%x is not found in connection",
678 __func__, scratch[j].meta_data.sensor);
679 continue;
680 }
681
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700682 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor].flushInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800683 flushInfo.mPendingFlushEventsToSend++;
684 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
685 flushInfo.mPendingFlushEventsToSend);
686 }
687 }
688 return;
689}
690
691int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
692 sensors_event_t const* scratch, const int count) {
693 for (int i = 0; i < count; ++i) {
694 if (mService->isWakeUpSensorEvent(scratch[i])) {
695 return i;
696 }
697 }
698 return -1;
699}
700
701sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
702{
703 return mChannel;
704}
705
706status_t SensorService::SensorEventConnection::enableDisable(
707 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
708 int reservedFlags)
709{
710 status_t err;
711 if (enabled) {
712 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
713 reservedFlags, mOpPackageName);
714
715 } else {
716 err = mService->disable(this, handle);
717 }
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700718
Peng Xueb4d6282015-12-10 18:02:41 -0800719 return err;
720}
721
722status_t SensorService::SensorEventConnection::setEventRate(
723 int handle, nsecs_t samplingPeriodNs)
724{
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700725 status_t err = mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
726
727 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
728 if (err == NO_ERROR && mSensorInfo.count(handle) > 0) {
729 mSensorInfo[handle].samplingPeriodNs = samplingPeriodNs;
730 }
731
732 return err;
Peng Xueb4d6282015-12-10 18:02:41 -0800733}
734
735status_t SensorService::SensorEventConnection::flush() {
736 return mService->flushSensor(this, mOpPackageName);
737}
738
Peng Xue36e3472016-11-03 11:57:10 -0700739int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
740 // SensorEventConnection does not support configureChannel, parameters not used
741 UNUSED(handle);
742 UNUSED(rateLevel);
743 return INVALID_OPERATION;
744}
745
Peng Xueb4d6282015-12-10 18:02:41 -0800746int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
747 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
748 {
749 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
750 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
751 // can release the wake-lock.
752 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700753 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xueb4d6282015-12-10 18:02:41 -0800754 mDead = true;
755 mWakeLockRefCount = 0;
756 updateLooperRegistrationLocked(mService->getLooper());
757 }
758 mService->checkWakeLockState();
759 if (mDataInjectionMode) {
760 // If the Looper has encountered some error in data injection mode, reset SensorService
761 // back to normal mode.
762 mService->resetToNormalMode();
763 mDataInjectionMode = false;
764 }
765 return 1;
766 }
767
768 if (events & ALOOPER_EVENT_INPUT) {
769 unsigned char buf[sizeof(sensors_event_t)];
770 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
771 {
Arthur Ishiguro8a7ec572020-03-18 11:02:35 -0700772 std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700773 if (numBytesRead == sizeof(sensors_event_t)) {
774 if (!mDataInjectionMode) {
775 ALOGE("Data injected in normal mode, dropping event"
776 "package=%s uid=%d", mPackageName.string(), mUid);
777 // Unregister call backs.
778 return 0;
779 }
780 sensors_event_t sensor_event;
781 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
782 sp<SensorInterface> si =
783 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
784 if (si == nullptr) {
785 return 1;
786 }
787
788 SensorDevice& dev(SensorDevice::getInstance());
789 sensor_event.type = si->getSensor().getType();
790 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800791#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700792 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800793#endif
Peng Xu755c4512016-04-07 23:15:14 -0700794 } else if (numBytesRead == sizeof(uint32_t)) {
795 uint32_t numAcks = 0;
796 memcpy(&numAcks, buf, numBytesRead);
797 // Sanity check to ensure there are no read errors in recv, numAcks is always
798 // within the range and not zero. If any of the above don't hold reset
799 // mWakeLockRefCount to zero.
800 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
801 mWakeLockRefCount -= numAcks;
802 } else {
803 mWakeLockRefCount = 0;
804 }
Peng Xueb4d6282015-12-10 18:02:41 -0800805#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700806 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800807#endif
808 } else {
809 // Read error, reset wakelock refcount.
810 mWakeLockRefCount = 0;
811 }
812 }
813 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
814 // here as checkWakeLockState() will need it.
815 if (mWakeLockRefCount == 0) {
816 mService->checkWakeLockState();
817 }
818 // continue getting callbacks.
819 return 1;
820 }
821
822 if (events & ALOOPER_EVENT_OUTPUT) {
823 // send sensor data that is stored in mEventCache for this connection.
824 mService->sendEventsFromCache(this);
825 }
826 return 1;
827}
828
829int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
830 size_t fifoWakeUpSensors = 0;
831 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700832 for (auto& it : mSensorInfo) {
833 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700834 if (si == nullptr) {
835 continue;
836 }
837 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800838 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
839 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
840 // non wake_up sensors.
841 if (sensor.isWakeUpSensor()) {
842 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
843 } else {
844 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
845 }
846 } else {
847 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
848 if (sensor.isWakeUpSensor()) {
849 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
850 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
851
852 } else {
853 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
854 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
855
856 }
857 }
858 }
859 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
860 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
861 // size that is equal to that of the batch mode.
862 // ALOGW("Write failure in non-batch mode");
863 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
864 }
865 return fifoWakeUpSensors + fifoNonWakeUpSensors;
866}
867
868} // namespace android
869