blob: 1811716af95c231fe3ab76ee15d1893f29fe28cd [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 Ishigurobbf3b372020-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
Mathias Agopian801ea092017-03-06 15:05:04 -080021#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080022
23#include "vec.h"
24#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070025#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080026
Peng Xue36e3472016-11-03 11:57:10 -070027#define UNUSED(x) (void)(x)
28
Peng Xueb4d6282015-12-10 18:02:41 -080029namespace android {
30
31SensorService::SensorEventConnection::SensorEventConnection(
32 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Svet Ganove752a5c2018-01-15 17:14:20 -080033 const String16& opPackageName, bool hasSensorAccess)
Peng Xueb4d6282015-12-10 18:02:41 -080034 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070035 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080036 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
37 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false),
38 mHasSensorAccess(hasSensorAccess) {
Peng Xueb4d6282015-12-10 18:02:41 -080039 mChannel = new BitTube(mService->mSocketBufferSize);
40#if DEBUG_CONNECTIONS
41 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
42 mTotalAcksNeeded = mTotalAcksReceived = 0;
43#endif
44}
45
46SensorService::SensorEventConnection::~SensorEventConnection() {
47 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070048 destroy();
Peng Xueb4d6282015-12-10 18:02:41 -080049 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070050 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080051 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080052 }
Arthur Ishigurobbf3b372020-09-22 13:05:15 -070053}
54
55void SensorService::SensorEventConnection::destroy() {
Peng Xu8cbefd72017-07-10 16:41:08 -070056 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080057}
58
59void SensorService::SensorEventConnection::onFirstRef() {
60 LooperCallback::onFirstRef();
61}
62
63bool SensorService::SensorEventConnection::needsWakeLock() {
64 Mutex::Autolock _l(mConnectionLock);
65 return !mDead && mWakeLockRefCount > 0;
66}
67
68void SensorService::SensorEventConnection::resetWakeLockRefCount() {
69 Mutex::Autolock _l(mConnectionLock);
70 mWakeLockRefCount = 0;
71}
72
73void SensorService::SensorEventConnection::dump(String8& result) {
74 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070075 result.appendFormat("\tOperating Mode: ");
76 if (!mService->isWhiteListedPackage(getPackageName())) {
77 result.append("RESTRICTED\n");
78 } else if (mDataInjectionMode) {
79 result.append("DATA_INJECTION\n");
80 } else {
81 result.append("NORMAL\n");
82 }
Peng Xueb4d6282015-12-10 18:02:41 -080083 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
84 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
85 mMaxCacheSize);
86 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
87 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
88 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
89 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
90 mSensorInfo.keyAt(i),
91 flushInfo.mFirstFlushPending ? "First flush pending" :
92 "active",
93 flushInfo.mPendingFlushEventsToSend);
94 }
95#if DEBUG_CONNECTIONS
96 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
97 " total_acks_needed %d | total_acks_recvd %d\n",
98 mEventsReceived,
99 mEventsSent,
100 mEventsSentFromCache,
101 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
102 mTotalAcksNeeded,
103 mTotalAcksReceived);
104#endif
105}
106
107bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
108 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700109 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
110 if (si == nullptr ||
111 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
112 mSensorInfo.indexOfKey(handle) >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800113 return false;
114 }
Peng Xu755c4512016-04-07 23:15:14 -0700115 mSensorInfo.add(handle, FlushInfo());
116 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800117}
118
119bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
120 Mutex::Autolock _l(mConnectionLock);
121 if (mSensorInfo.removeItem(handle) >= 0) {
122 return true;
123 }
124 return false;
125}
126
127bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
128 Mutex::Autolock _l(mConnectionLock);
129 return mSensorInfo.indexOfKey(handle) >= 0;
130}
131
132bool SensorService::SensorEventConnection::hasAnySensor() const {
133 Mutex::Autolock _l(mConnectionLock);
134 return mSensorInfo.size() ? true : false;
135}
136
137bool SensorService::SensorEventConnection::hasOneShotSensors() const {
138 Mutex::Autolock _l(mConnectionLock);
139 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
140 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700141 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
142 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800143 return true;
144 }
145 }
146 return false;
147}
148
149String8 SensorService::SensorEventConnection::getPackageName() const {
150 return mPackageName;
151}
152
153void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
154 bool value) {
155 Mutex::Autolock _l(mConnectionLock);
156 ssize_t index = mSensorInfo.indexOfKey(handle);
157 if (index >= 0) {
158 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
159 flushInfo.mFirstFlushPending = value;
160 }
161}
162
163void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
164 Mutex::Autolock _l(mConnectionLock);
165 updateLooperRegistrationLocked(looper);
166}
167
168void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
169 const sp<Looper>& looper) {
170 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
171 mDataInjectionMode;
172 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
173 // the Looper if it has been previously added.
174 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
175 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
176 mChannel->getSendFd());
177 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
178 return; }
179
180 int looper_flags = 0;
181 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
182 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
183 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
184 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700185 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
186 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800187 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800188 }
189 }
190
191 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
192 // already been added, remove it. This is likely to happen when ALL the events stored in the
193 // cache have been sent to the corresponding app.
194 if (looper_flags == 0) {
195 if (mHasLooperCallbacks) {
196 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
197 looper->removeFd(mChannel->getSendFd());
198 mHasLooperCallbacks = false;
199 }
200 return;
201 }
202
203 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
204 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700205 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800206 if (ret == 1) {
207 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
208 mHasLooperCallbacks = true;
209 } else {
210 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
211 }
212}
213
214void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
215 Mutex::Autolock _l(mConnectionLock);
216 ssize_t index = mSensorInfo.indexOfKey(handle);
217 if (index >= 0) {
218 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
219 flushInfo.mPendingFlushEventsToSend++;
220 }
221}
222
223status_t SensorService::SensorEventConnection::sendEvents(
224 sensors_event_t const* buffer, size_t numEvents,
225 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700226 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800227 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800228
George Burgess IV1866ed42018-01-21 12:14:09 -0800229 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800230
Peng Xueb4d6282015-12-10 18:02:41 -0800231 int count = 0;
232 Mutex::Autolock _l(mConnectionLock);
233 if (scratch) {
234 size_t i=0;
235 while (i<numEvents) {
236 int32_t sensor_handle = buffer[i].sensor;
237 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
238 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
239 buffer[i].meta_data.sensor);
240 // Setting sensor_handle to the correct sensor to ensure the sensor events per
241 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
242 // events.
243 sensor_handle = buffer[i].meta_data.sensor;
244 }
245
246 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
247 // Check if this connection has registered for this sensor. If not continue to the
248 // next sensor_event.
249 if (index < 0) {
250 ++i;
251 continue;
252 }
253
254 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
255 // Check if there is a pending flush_complete event for this sensor on this connection.
256 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700257 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800258 flushInfo.mFirstFlushPending = false;
259 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
260 buffer[i].meta_data.sensor);
261 ++i;
262 continue;
263 }
264
265 // If there is a pending flush complete event for this sensor on this connection,
266 // ignore the event and proceed to the next.
267 if (flushInfo.mFirstFlushPending) {
268 ++i;
269 continue;
270 }
271
272 do {
273 // Keep copying events into the scratch buffer as long as they are regular
274 // sensor_events are from the same sensor_handle OR they are flush_complete_events
275 // from the same sensor_handle AND the current connection is mapped to the
276 // corresponding flush_complete_event.
277 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700278 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800279 scratch[count++] = buffer[i];
280 }
Peng Xueb4d6282015-12-10 18:02:41 -0800281 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700282 // Regular sensor event, just copy it to the scratch buffer after checking
283 // the AppOp.
284 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800285 scratch[count++] = buffer[i];
286 }
Peng Xueb4d6282015-12-10 18:02:41 -0800287 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800288 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800289 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
290 buffer[i].type != SENSOR_TYPE_META_DATA) ||
291 (buffer[i].type == SENSOR_TYPE_META_DATA &&
292 buffer[i].meta_data.sensor == sensor_handle)));
293 }
294 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800295 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800296 scratch = const_cast<sensors_event_t *>(buffer);
297 count = numEvents;
298 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800299 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
300 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800301 for (size_t i = 0; i < numEvents; i++) {
302 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
303 scratch[count++] = buffer[i++];
304 }
305 }
306 }
Peng Xueb4d6282015-12-10 18:02:41 -0800307 }
308
309 sendPendingFlushEventsLocked();
310 // Early return if there are no events for this connection.
311 if (count == 0) {
312 return status_t(NO_ERROR);
313 }
314
315#if DEBUG_CONNECTIONS
316 mEventsReceived += count;
317#endif
318 if (mCacheSize != 0) {
319 // There are some events in the cache which need to be sent first. Copy this buffer to
320 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800321 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800322 return status_t(NO_ERROR);
323 }
324
Svet Ganove752a5c2018-01-15 17:14:20 -0800325 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800326 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800327 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
328 if (index_wake_up_event >= 0) {
329 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
330 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800331#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800332 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800333#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800334 }
Peng Xueb4d6282015-12-10 18:02:41 -0800335 }
336
337 // NOTE: ASensorEvent and sensors_event_t are the same type.
338 ssize_t size = SensorEventQueue::write(mChannel,
339 reinterpret_cast<ASensorEvent const*>(scratch), count);
340 if (size < 0) {
341 // Write error, copy events to local cache.
342 if (index_wake_up_event >= 0) {
343 // If there was a wake_up sensor_event, reset the flag.
344 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
345 if (mWakeLockRefCount > 0) {
346 --mWakeLockRefCount;
347 }
348#if DEBUG_CONNECTIONS
349 --mTotalAcksNeeded;
350#endif
351 }
Yi Kong8f313e32018-07-17 14:13:29 -0700352 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800353 mMaxCacheSize = computeMaxCacheSizeLocked();
354 mEventCache = new sensors_event_t[mMaxCacheSize];
355 mCacheSize = 0;
356 }
Brian Stack93432ad2018-11-27 18:28:48 -0800357 // Save the events so that they can be written later
358 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800359
360 // Add this file descriptor to the looper to get a callback when this fd is available for
361 // writing.
362 updateLooperRegistrationLocked(mService->getLooper());
363 return size;
364 }
365
366#if DEBUG_CONNECTIONS
367 if (size > 0) {
368 mEventsSent += count;
369 }
370#endif
371
372 return size < 0 ? status_t(size) : status_t(NO_ERROR);
373}
374
Svet Ganove752a5c2018-01-15 17:14:20 -0800375void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
376 Mutex::Autolock _l(mConnectionLock);
377 mHasSensorAccess = hasAccess;
378}
379
Michael Groover5e1f60b2018-12-04 22:34:29 -0800380bool SensorService::SensorEventConnection::hasSensorAccess() {
381 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
382}
383
Brian Stackc225aa12019-04-19 09:30:25 -0700384bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
385 bool success = true;
386 const auto iter = mHandleToAppOp.find(event.sensor);
387 if (iter != mHandleToAppOp.end()) {
388 int32_t appOpMode = mService->sAppOpsManager.noteOp((*iter).second, mUid, mOpPackageName);
389 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
390 }
391 return success;
392}
393
Peng Xueb4d6282015-12-10 18:02:41 -0800394void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
395 int count) {
396 sensors_event_t *eventCache_new;
397 const int new_cache_size = computeMaxCacheSizeLocked();
398 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
399 eventCache_new = new sensors_event_t[new_cache_size];
400 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
401 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
402
403 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
404 new_cache_size);
405
George Burgess IV1866ed42018-01-21 12:14:09 -0800406 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800407 mEventCache = eventCache_new;
408 mCacheSize += count;
409 mMaxCacheSize = new_cache_size;
410}
411
Brian Stack93432ad2018-11-27 18:28:48 -0800412void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
413 int count) {
414 if (count <= 0) {
415 return;
416 } else if (mCacheSize + count <= mMaxCacheSize) {
417 // The events fit within the current cache: add them
418 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
419 mCacheSize += count;
420 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
421 // The events fit within a resized cache: resize the cache and add the events
422 reAllocateCacheLocked(events, count);
423 } else {
424 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800425 int freeSpace = mMaxCacheSize - mCacheSize;
426
427 // Drop up to the currently cached number of events to make room for new events
428 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
429
430 // New events need to be dropped if there are more new events than the size of the cache
431 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
432
433 // Determine the number of new events to copy into the cache
434 int eventsToCopy = std::min(mMaxCacheSize, count);
435
Brian Stackae4053f2018-12-10 14:54:18 -0800436 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
437 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
438 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
439 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
440 count, mEventsDropped);
441 mEventsDropped = 0;
442 mTimeOfLastEventDrop = events[0].timestamp;
443 } else {
444 // Record the number dropped
445 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
446 }
447
Brian Stack93432ad2018-11-27 18:28:48 -0800448 // Check for any flush complete events in the events that will be dropped
449 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
450 countFlushCompleteEventsLocked(events, newEventsToDrop);
451
452 // Only shift the events if they will not all be overwritten
453 if (eventsToCopy != mMaxCacheSize) {
454 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
455 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
456 }
457 mCacheSize -= cachedEventsToDrop;
458
459 // Copy the events into the cache
460 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
461 eventsToCopy * sizeof(sensors_event_t));
462 mCacheSize += eventsToCopy;
463 }
464}
465
Peng Xueb4d6282015-12-10 18:02:41 -0800466void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
467 ASensorEvent flushCompleteEvent;
468 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
469 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
470 // Loop through all the sensors for this connection and check if there are any pending
471 // flush complete events to be sent.
472 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700473 const int handle = mSensorInfo.keyAt(i);
474 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
475 if (si == nullptr) {
476 continue;
477 }
478
Peng Xueb4d6282015-12-10 18:02:41 -0800479 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
480 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700481 flushCompleteEvent.meta_data.sensor = handle;
482 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800483 if (wakeUpSensor) {
484 ++mWakeLockRefCount;
485 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
486 }
487 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
488 if (size < 0) {
489 if (wakeUpSensor) --mWakeLockRefCount;
490 return;
491 }
492 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
493 flushCompleteEvent.meta_data.sensor);
494 flushInfo.mPendingFlushEventsToSend--;
495 }
496 }
497}
498
499void SensorService::SensorEventConnection::writeToSocketFromCache() {
500 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
501 // half the size of the socket buffer allocated in BitTube whichever is smaller.
502 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
503 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
504 Mutex::Autolock _l(mConnectionLock);
505 // Send pending flush complete events (if any)
506 sendPendingFlushEventsLocked();
507 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
508 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800509 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800510 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800511 index_wake_up_event =
512 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
513 if (index_wake_up_event >= 0) {
514 mEventCache[index_wake_up_event + numEventsSent].flags |=
515 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
516 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800517#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800518 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800519#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800520 }
Peng Xueb4d6282015-12-10 18:02:41 -0800521 }
522
523 ssize_t size = SensorEventQueue::write(mChannel,
524 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
525 numEventsToWrite);
526 if (size < 0) {
527 if (index_wake_up_event >= 0) {
528 // If there was a wake_up sensor_event, reset the flag.
529 mEventCache[index_wake_up_event + numEventsSent].flags &=
530 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
531 if (mWakeLockRefCount > 0) {
532 --mWakeLockRefCount;
533 }
534#if DEBUG_CONNECTIONS
535 --mTotalAcksNeeded;
536#endif
537 }
538 memmove(mEventCache, &mEventCache[numEventsSent],
539 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
540 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
541 numEventsSent, mCacheSize);
542 mCacheSize -= numEventsSent;
543 return;
544 }
545 numEventsSent += numEventsToWrite;
546#if DEBUG_CONNECTIONS
547 mEventsSentFromCache += numEventsToWrite;
548#endif
549 }
550 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
551 // All events from the cache have been sent. Reset cache size to zero.
552 mCacheSize = 0;
553 // There are no more events in the cache. We don't need to poll for write on the fd.
554 // Update Looper registration.
555 updateLooperRegistrationLocked(mService->getLooper());
556}
557
558void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
559 sensors_event_t const* scratch, const int numEventsDropped) {
560 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
561 // Count flushComplete events in the events that are about to the dropped. These will be sent
562 // separately before the next batch of events.
563 for (int j = 0; j < numEventsDropped; ++j) {
564 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700565 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
566 if (index < 0) {
567 ALOGW("%s: sensor 0x%x is not found in connection",
568 __func__, scratch[j].meta_data.sensor);
569 continue;
570 }
571
572 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800573 flushInfo.mPendingFlushEventsToSend++;
574 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
575 flushInfo.mPendingFlushEventsToSend);
576 }
577 }
578 return;
579}
580
581int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
582 sensors_event_t const* scratch, const int count) {
583 for (int i = 0; i < count; ++i) {
584 if (mService->isWakeUpSensorEvent(scratch[i])) {
585 return i;
586 }
587 }
588 return -1;
589}
590
591sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
592{
593 return mChannel;
594}
595
596status_t SensorService::SensorEventConnection::enableDisable(
597 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
598 int reservedFlags)
599{
Arthur Ishigurobbf3b372020-09-22 13:05:15 -0700600 if (mDestroyed) {
601 android_errorWriteLog(0x534e4554, "168211968");
602 return DEAD_OBJECT;
603 }
604
Peng Xueb4d6282015-12-10 18:02:41 -0800605 status_t err;
606 if (enabled) {
607 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
608 reservedFlags, mOpPackageName);
609
610 } else {
611 err = mService->disable(this, handle);
612 }
613 return err;
614}
615
616status_t SensorService::SensorEventConnection::setEventRate(
617 int handle, nsecs_t samplingPeriodNs)
618{
Arthur Ishigurobbf3b372020-09-22 13:05:15 -0700619 if (mDestroyed) {
620 android_errorWriteLog(0x534e4554, "168211968");
621 return DEAD_OBJECT;
622 }
623
Peng Xueb4d6282015-12-10 18:02:41 -0800624 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
625}
626
627status_t SensorService::SensorEventConnection::flush() {
Arthur Ishigurobbf3b372020-09-22 13:05:15 -0700628 if (mDestroyed) {
629 return DEAD_OBJECT;
630 }
631
Peng Xueb4d6282015-12-10 18:02:41 -0800632 return mService->flushSensor(this, mOpPackageName);
633}
634
Peng Xue36e3472016-11-03 11:57:10 -0700635int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
636 // SensorEventConnection does not support configureChannel, parameters not used
637 UNUSED(handle);
638 UNUSED(rateLevel);
639 return INVALID_OPERATION;
640}
641
Peng Xueb4d6282015-12-10 18:02:41 -0800642int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
643 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
644 {
645 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
646 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
647 // can release the wake-lock.
648 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
649 Mutex::Autolock _l(mConnectionLock);
650 mDead = true;
651 mWakeLockRefCount = 0;
652 updateLooperRegistrationLocked(mService->getLooper());
653 }
654 mService->checkWakeLockState();
655 if (mDataInjectionMode) {
656 // If the Looper has encountered some error in data injection mode, reset SensorService
657 // back to normal mode.
658 mService->resetToNormalMode();
659 mDataInjectionMode = false;
660 }
661 return 1;
662 }
663
664 if (events & ALOOPER_EVENT_INPUT) {
665 unsigned char buf[sizeof(sensors_event_t)];
666 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
667 {
Peng Xu755c4512016-04-07 23:15:14 -0700668 Mutex::Autolock _l(mConnectionLock);
669 if (numBytesRead == sizeof(sensors_event_t)) {
670 if (!mDataInjectionMode) {
671 ALOGE("Data injected in normal mode, dropping event"
672 "package=%s uid=%d", mPackageName.string(), mUid);
673 // Unregister call backs.
674 return 0;
675 }
676 sensors_event_t sensor_event;
677 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
678 sp<SensorInterface> si =
679 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
680 if (si == nullptr) {
681 return 1;
682 }
683
684 SensorDevice& dev(SensorDevice::getInstance());
685 sensor_event.type = si->getSensor().getType();
686 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800687#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700688 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800689#endif
Peng Xu755c4512016-04-07 23:15:14 -0700690 } else if (numBytesRead == sizeof(uint32_t)) {
691 uint32_t numAcks = 0;
692 memcpy(&numAcks, buf, numBytesRead);
693 // Sanity check to ensure there are no read errors in recv, numAcks is always
694 // within the range and not zero. If any of the above don't hold reset
695 // mWakeLockRefCount to zero.
696 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
697 mWakeLockRefCount -= numAcks;
698 } else {
699 mWakeLockRefCount = 0;
700 }
Peng Xueb4d6282015-12-10 18:02:41 -0800701#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700702 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800703#endif
704 } else {
705 // Read error, reset wakelock refcount.
706 mWakeLockRefCount = 0;
707 }
708 }
709 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
710 // here as checkWakeLockState() will need it.
711 if (mWakeLockRefCount == 0) {
712 mService->checkWakeLockState();
713 }
714 // continue getting callbacks.
715 return 1;
716 }
717
718 if (events & ALOOPER_EVENT_OUTPUT) {
719 // send sensor data that is stored in mEventCache for this connection.
720 mService->sendEventsFromCache(this);
721 }
722 return 1;
723}
724
725int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
726 size_t fifoWakeUpSensors = 0;
727 size_t fifoNonWakeUpSensors = 0;
728 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700729 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
730 if (si == nullptr) {
731 continue;
732 }
733 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800734 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
735 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
736 // non wake_up sensors.
737 if (sensor.isWakeUpSensor()) {
738 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
739 } else {
740 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
741 }
742 } else {
743 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
744 if (sensor.isWakeUpSensor()) {
745 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
746 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
747
748 } else {
749 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
750 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
751
752 }
753 }
754 }
755 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
756 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
757 // size that is equal to that of the batch mode.
758 // ALOGW("Write failure in non-batch mode");
759 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
760 }
761 return fifoWakeUpSensors + fifoNonWakeUpSensors;
762}
763
764} // namespace android
765