blob: e79937295bb6716e5a150e35941d4bc1b5c9e962 [file] [log] [blame]
Peng Xueb4d6282015-12-10 18:02:41 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <sys/socket.h>
18#include <utils/threads.h>
19
Mike Ma24743862020-01-29 00:36:55 -080020#include <android/util/ProtoOutputStream.h>
21#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080022#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080023
24#include "vec.h"
25#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070026#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080027
Peng Xue36e3472016-11-03 11:57:10 -070028#define UNUSED(x) (void)(x)
29
Peng Xueb4d6282015-12-10 18:02:41 -080030namespace android {
31
32SensorService::SensorEventConnection::SensorEventConnection(
33 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Svet Ganove752a5c2018-01-15 17:14:20 -080034 const String16& opPackageName, bool hasSensorAccess)
Peng Xueb4d6282015-12-10 18:02:41 -080035 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070036 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080037 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
38 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false),
39 mHasSensorAccess(hasSensorAccess) {
Peng Xueb4d6282015-12-10 18:02:41 -080040 mChannel = new BitTube(mService->mSocketBufferSize);
41#if DEBUG_CONNECTIONS
42 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
43 mTotalAcksNeeded = mTotalAcksReceived = 0;
44#endif
45}
46
47SensorService::SensorEventConnection::~SensorEventConnection() {
48 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070049 destroy();
50}
51
52void SensorService::SensorEventConnection::destroy() {
53 Mutex::Autolock _l(mDestroyLock);
54
55 // destroy once only
56 if (mDestroyed) {
57 return;
58 }
59
Peng Xueb4d6282015-12-10 18:02:41 -080060 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070061 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080062 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080063 }
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() {
72 Mutex::Autolock _l(mConnectionLock);
73 return !mDead && mWakeLockRefCount > 0;
74}
75
76void SensorService::SensorEventConnection::resetWakeLockRefCount() {
77 Mutex::Autolock _l(mConnectionLock);
78 mWakeLockRefCount = 0;
79}
80
81void SensorService::SensorEventConnection::dump(String8& result) {
82 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) {
95 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;
124 Mutex::Autolock _l(mConnectionLock);
125
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) {
139 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
Peng Xueb4d6282015-12-10 18:02:41 -0800160bool 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 ||
164 !canAccessSensor(si->getSensor(), "Tried adding", 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 Ishiguroad46c782020-03-26 11:24:43 -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) {
173 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700174 if (mSensorInfo.erase(handle) >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800175 return true;
176 }
177 return false;
178}
179
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700180std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
181 Mutex::Autolock _l(mConnectionLock);
182 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 {
190 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700191 return mSensorInfo.count(handle) > 0;
Peng Xueb4d6282015-12-10 18:02:41 -0800192}
193
194bool SensorService::SensorEventConnection::hasAnySensor() const {
195 Mutex::Autolock _l(mConnectionLock);
196 return mSensorInfo.size() ? true : false;
197}
198
199bool SensorService::SensorEventConnection::hasOneShotSensors() const {
200 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) {
217 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700218 if (mSensorInfo.count(handle) > 0) {
219 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) {
225 Mutex::Autolock _l(mConnectionLock);
226 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
275void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
276 Mutex::Autolock _l(mConnectionLock);
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700277 if (mSensorInfo.count(handle) > 0) {
278 FlushInfo& flushInfo = mSensorInfo[handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800279 flushInfo.mPendingFlushEventsToSend++;
280 }
281}
282
283status_t SensorService::SensorEventConnection::sendEvents(
284 sensors_event_t const* buffer, size_t numEvents,
285 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700286 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800287 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800288
George Burgess IV1866ed42018-01-21 12:14:09 -0800289 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800290
Peng Xueb4d6282015-12-10 18:02:41 -0800291 int count = 0;
292 Mutex::Autolock _l(mConnectionLock);
293 if (scratch) {
294 size_t i=0;
295 while (i<numEvents) {
296 int32_t sensor_handle = buffer[i].sensor;
297 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
298 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
299 buffer[i].meta_data.sensor);
300 // Setting sensor_handle to the correct sensor to ensure the sensor events per
301 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
302 // events.
303 sensor_handle = buffer[i].meta_data.sensor;
304 }
305
Peng Xueb4d6282015-12-10 18:02:41 -0800306 // Check if this connection has registered for this sensor. If not continue to the
307 // next sensor_event.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700308 if (mSensorInfo.count(sensor_handle) == 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800309 ++i;
310 continue;
311 }
312
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700313 FlushInfo& flushInfo = mSensorInfo[sensor_handle];
Peng Xueb4d6282015-12-10 18:02:41 -0800314 // Check if there is a pending flush_complete event for this sensor on this connection.
315 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700316 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800317 flushInfo.mFirstFlushPending = false;
318 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
319 buffer[i].meta_data.sensor);
320 ++i;
321 continue;
322 }
323
324 // If there is a pending flush complete event for this sensor on this connection,
325 // ignore the event and proceed to the next.
326 if (flushInfo.mFirstFlushPending) {
327 ++i;
328 continue;
329 }
330
331 do {
332 // Keep copying events into the scratch buffer as long as they are regular
333 // sensor_events are from the same sensor_handle OR they are flush_complete_events
334 // from the same sensor_handle AND the current connection is mapped to the
335 // corresponding flush_complete_event.
336 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700337 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800338 scratch[count++] = buffer[i];
339 }
Peng Xueb4d6282015-12-10 18:02:41 -0800340 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700341 // Regular sensor event, just copy it to the scratch buffer after checking
342 // the AppOp.
343 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800344 scratch[count++] = buffer[i];
345 }
Peng Xueb4d6282015-12-10 18:02:41 -0800346 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800347 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800348 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
349 buffer[i].type != SENSOR_TYPE_META_DATA) ||
350 (buffer[i].type == SENSOR_TYPE_META_DATA &&
351 buffer[i].meta_data.sensor == sensor_handle)));
352 }
353 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800354 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800355 scratch = const_cast<sensors_event_t *>(buffer);
356 count = numEvents;
357 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800358 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
359 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800360 for (size_t i = 0; i < numEvents; i++) {
361 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
362 scratch[count++] = buffer[i++];
363 }
364 }
365 }
Peng Xueb4d6282015-12-10 18:02:41 -0800366 }
367
368 sendPendingFlushEventsLocked();
369 // Early return if there are no events for this connection.
370 if (count == 0) {
371 return status_t(NO_ERROR);
372 }
373
374#if DEBUG_CONNECTIONS
375 mEventsReceived += count;
376#endif
377 if (mCacheSize != 0) {
378 // There are some events in the cache which need to be sent first. Copy this buffer to
379 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800380 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800381 return status_t(NO_ERROR);
382 }
383
Svet Ganove752a5c2018-01-15 17:14:20 -0800384 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800385 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800386 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
387 if (index_wake_up_event >= 0) {
388 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
389 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800390#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800391 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800392#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800393 }
Peng Xueb4d6282015-12-10 18:02:41 -0800394 }
395
396 // NOTE: ASensorEvent and sensors_event_t are the same type.
397 ssize_t size = SensorEventQueue::write(mChannel,
398 reinterpret_cast<ASensorEvent const*>(scratch), count);
399 if (size < 0) {
400 // Write error, copy events to local cache.
401 if (index_wake_up_event >= 0) {
402 // If there was a wake_up sensor_event, reset the flag.
403 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
404 if (mWakeLockRefCount > 0) {
405 --mWakeLockRefCount;
406 }
407#if DEBUG_CONNECTIONS
408 --mTotalAcksNeeded;
409#endif
410 }
Yi Kong8f313e32018-07-17 14:13:29 -0700411 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800412 mMaxCacheSize = computeMaxCacheSizeLocked();
413 mEventCache = new sensors_event_t[mMaxCacheSize];
414 mCacheSize = 0;
415 }
Brian Stack93432ad2018-11-27 18:28:48 -0800416 // Save the events so that they can be written later
417 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800418
419 // Add this file descriptor to the looper to get a callback when this fd is available for
420 // writing.
421 updateLooperRegistrationLocked(mService->getLooper());
422 return size;
423 }
424
425#if DEBUG_CONNECTIONS
426 if (size > 0) {
427 mEventsSent += count;
428 }
429#endif
430
431 return size < 0 ? status_t(size) : status_t(NO_ERROR);
432}
433
Svet Ganove752a5c2018-01-15 17:14:20 -0800434void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
435 Mutex::Autolock _l(mConnectionLock);
436 mHasSensorAccess = hasAccess;
437}
438
Michael Groover5e1f60b2018-12-04 22:34:29 -0800439bool SensorService::SensorEventConnection::hasSensorAccess() {
440 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
441}
442
Brian Stackc225aa12019-04-19 09:30:25 -0700443bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
444 bool success = true;
445 const auto iter = mHandleToAppOp.find(event.sensor);
446 if (iter != mHandleToAppOp.end()) {
447 int32_t appOpMode = mService->sAppOpsManager.noteOp((*iter).second, mUid, mOpPackageName);
448 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
449 }
450 return success;
451}
452
Peng Xueb4d6282015-12-10 18:02:41 -0800453void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
454 int count) {
455 sensors_event_t *eventCache_new;
456 const int new_cache_size = computeMaxCacheSizeLocked();
457 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
458 eventCache_new = new sensors_event_t[new_cache_size];
459 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
460 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
461
462 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
463 new_cache_size);
464
George Burgess IV1866ed42018-01-21 12:14:09 -0800465 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800466 mEventCache = eventCache_new;
467 mCacheSize += count;
468 mMaxCacheSize = new_cache_size;
469}
470
Brian Stack93432ad2018-11-27 18:28:48 -0800471void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
472 int count) {
473 if (count <= 0) {
474 return;
475 } else if (mCacheSize + count <= mMaxCacheSize) {
476 // The events fit within the current cache: add them
477 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
478 mCacheSize += count;
479 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
480 // The events fit within a resized cache: resize the cache and add the events
481 reAllocateCacheLocked(events, count);
482 } else {
483 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800484 int freeSpace = mMaxCacheSize - mCacheSize;
485
486 // Drop up to the currently cached number of events to make room for new events
487 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
488
489 // New events need to be dropped if there are more new events than the size of the cache
490 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
491
492 // Determine the number of new events to copy into the cache
493 int eventsToCopy = std::min(mMaxCacheSize, count);
494
Brian Stackae4053f2018-12-10 14:54:18 -0800495 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
496 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
497 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
498 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
499 count, mEventsDropped);
500 mEventsDropped = 0;
501 mTimeOfLastEventDrop = events[0].timestamp;
502 } else {
503 // Record the number dropped
504 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
505 }
506
Brian Stack93432ad2018-11-27 18:28:48 -0800507 // Check for any flush complete events in the events that will be dropped
508 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
509 countFlushCompleteEventsLocked(events, newEventsToDrop);
510
511 // Only shift the events if they will not all be overwritten
512 if (eventsToCopy != mMaxCacheSize) {
513 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
514 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
515 }
516 mCacheSize -= cachedEventsToDrop;
517
518 // Copy the events into the cache
519 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
520 eventsToCopy * sizeof(sensors_event_t));
521 mCacheSize += eventsToCopy;
522 }
523}
524
Peng Xueb4d6282015-12-10 18:02:41 -0800525void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
526 ASensorEvent flushCompleteEvent;
527 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
528 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
529 // Loop through all the sensors for this connection and check if there are any pending
530 // flush complete events to be sent.
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700531 for (auto& it : mSensorInfo) {
532 const int handle = it.first;
Peng Xu755c4512016-04-07 23:15:14 -0700533 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
534 if (si == nullptr) {
535 continue;
536 }
537
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700538 FlushInfo& flushInfo = it.second;
Peng Xueb4d6282015-12-10 18:02:41 -0800539 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700540 flushCompleteEvent.meta_data.sensor = handle;
541 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800542 if (wakeUpSensor) {
543 ++mWakeLockRefCount;
544 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
545 }
546 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
547 if (size < 0) {
548 if (wakeUpSensor) --mWakeLockRefCount;
549 return;
550 }
551 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
552 flushCompleteEvent.meta_data.sensor);
553 flushInfo.mPendingFlushEventsToSend--;
554 }
555 }
556}
557
558void SensorService::SensorEventConnection::writeToSocketFromCache() {
559 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
560 // half the size of the socket buffer allocated in BitTube whichever is smaller.
561 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
562 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
563 Mutex::Autolock _l(mConnectionLock);
564 // Send pending flush complete events (if any)
565 sendPendingFlushEventsLocked();
566 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
567 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800568 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800569 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800570 index_wake_up_event =
571 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
572 if (index_wake_up_event >= 0) {
573 mEventCache[index_wake_up_event + numEventsSent].flags |=
574 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
575 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800576#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800577 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800578#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800579 }
Peng Xueb4d6282015-12-10 18:02:41 -0800580 }
581
582 ssize_t size = SensorEventQueue::write(mChannel,
583 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
584 numEventsToWrite);
585 if (size < 0) {
586 if (index_wake_up_event >= 0) {
587 // If there was a wake_up sensor_event, reset the flag.
588 mEventCache[index_wake_up_event + numEventsSent].flags &=
589 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
590 if (mWakeLockRefCount > 0) {
591 --mWakeLockRefCount;
592 }
593#if DEBUG_CONNECTIONS
594 --mTotalAcksNeeded;
595#endif
596 }
597 memmove(mEventCache, &mEventCache[numEventsSent],
598 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
599 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
600 numEventsSent, mCacheSize);
601 mCacheSize -= numEventsSent;
602 return;
603 }
604 numEventsSent += numEventsToWrite;
605#if DEBUG_CONNECTIONS
606 mEventsSentFromCache += numEventsToWrite;
607#endif
608 }
609 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
610 // All events from the cache have been sent. Reset cache size to zero.
611 mCacheSize = 0;
612 // There are no more events in the cache. We don't need to poll for write on the fd.
613 // Update Looper registration.
614 updateLooperRegistrationLocked(mService->getLooper());
615}
616
617void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
618 sensors_event_t const* scratch, const int numEventsDropped) {
619 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
620 // Count flushComplete events in the events that are about to the dropped. These will be sent
621 // separately before the next batch of events.
622 for (int j = 0; j < numEventsDropped; ++j) {
623 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700624 if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
Peng Xu63fbab82017-06-20 12:41:33 -0700625 ALOGW("%s: sensor 0x%x is not found in connection",
626 __func__, scratch[j].meta_data.sensor);
627 continue;
628 }
629
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700630 FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
Peng Xueb4d6282015-12-10 18:02:41 -0800631 flushInfo.mPendingFlushEventsToSend++;
632 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
633 flushInfo.mPendingFlushEventsToSend);
634 }
635 }
636 return;
637}
638
639int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
640 sensors_event_t const* scratch, const int count) {
641 for (int i = 0; i < count; ++i) {
642 if (mService->isWakeUpSensorEvent(scratch[i])) {
643 return i;
644 }
645 }
646 return -1;
647}
648
649sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
650{
651 return mChannel;
652}
653
654status_t SensorService::SensorEventConnection::enableDisable(
655 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
656 int reservedFlags)
657{
658 status_t err;
659 if (enabled) {
660 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
661 reservedFlags, mOpPackageName);
662
663 } else {
664 err = mService->disable(this, handle);
665 }
666 return err;
667}
668
669status_t SensorService::SensorEventConnection::setEventRate(
670 int handle, nsecs_t samplingPeriodNs)
671{
672 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
673}
674
675status_t SensorService::SensorEventConnection::flush() {
676 return mService->flushSensor(this, mOpPackageName);
677}
678
Peng Xue36e3472016-11-03 11:57:10 -0700679int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
680 // SensorEventConnection does not support configureChannel, parameters not used
681 UNUSED(handle);
682 UNUSED(rateLevel);
683 return INVALID_OPERATION;
684}
685
Peng Xueb4d6282015-12-10 18:02:41 -0800686int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
687 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
688 {
689 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
690 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
691 // can release the wake-lock.
692 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
693 Mutex::Autolock _l(mConnectionLock);
694 mDead = true;
695 mWakeLockRefCount = 0;
696 updateLooperRegistrationLocked(mService->getLooper());
697 }
698 mService->checkWakeLockState();
699 if (mDataInjectionMode) {
700 // If the Looper has encountered some error in data injection mode, reset SensorService
701 // back to normal mode.
702 mService->resetToNormalMode();
703 mDataInjectionMode = false;
704 }
705 return 1;
706 }
707
708 if (events & ALOOPER_EVENT_INPUT) {
709 unsigned char buf[sizeof(sensors_event_t)];
710 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
711 {
Peng Xu755c4512016-04-07 23:15:14 -0700712 Mutex::Autolock _l(mConnectionLock);
713 if (numBytesRead == sizeof(sensors_event_t)) {
714 if (!mDataInjectionMode) {
715 ALOGE("Data injected in normal mode, dropping event"
716 "package=%s uid=%d", mPackageName.string(), mUid);
717 // Unregister call backs.
718 return 0;
719 }
720 sensors_event_t sensor_event;
721 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
722 sp<SensorInterface> si =
723 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
724 if (si == nullptr) {
725 return 1;
726 }
727
728 SensorDevice& dev(SensorDevice::getInstance());
729 sensor_event.type = si->getSensor().getType();
730 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800731#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700732 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800733#endif
Peng Xu755c4512016-04-07 23:15:14 -0700734 } else if (numBytesRead == sizeof(uint32_t)) {
735 uint32_t numAcks = 0;
736 memcpy(&numAcks, buf, numBytesRead);
737 // Sanity check to ensure there are no read errors in recv, numAcks is always
738 // within the range and not zero. If any of the above don't hold reset
739 // mWakeLockRefCount to zero.
740 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
741 mWakeLockRefCount -= numAcks;
742 } else {
743 mWakeLockRefCount = 0;
744 }
Peng Xueb4d6282015-12-10 18:02:41 -0800745#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700746 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800747#endif
748 } else {
749 // Read error, reset wakelock refcount.
750 mWakeLockRefCount = 0;
751 }
752 }
753 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
754 // here as checkWakeLockState() will need it.
755 if (mWakeLockRefCount == 0) {
756 mService->checkWakeLockState();
757 }
758 // continue getting callbacks.
759 return 1;
760 }
761
762 if (events & ALOOPER_EVENT_OUTPUT) {
763 // send sensor data that is stored in mEventCache for this connection.
764 mService->sendEventsFromCache(this);
765 }
766 return 1;
767}
768
769int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
770 size_t fifoWakeUpSensors = 0;
771 size_t fifoNonWakeUpSensors = 0;
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700772 for (auto& it : mSensorInfo) {
773 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
Peng Xu755c4512016-04-07 23:15:14 -0700774 if (si == nullptr) {
775 continue;
776 }
777 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800778 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
779 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
780 // non wake_up sensors.
781 if (sensor.isWakeUpSensor()) {
782 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
783 } else {
784 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
785 }
786 } else {
787 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
788 if (sensor.isWakeUpSensor()) {
789 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
790 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
791
792 } else {
793 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
794 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
795
796 }
797 }
798 }
799 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
800 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
801 // size that is equal to that of the batch mode.
802 // ALOGW("Write failure in non-batch mode");
803 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
804 }
805 return fifoWakeUpSensors + fifoNonWakeUpSensors;
806}
807
808} // namespace android
809