blob: c4cfdc63bf874130251d0abfbfec4b8e6eea1527 [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
Mathias Agopian801ea092017-03-06 15:05:04 -080020#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080021
22#include "vec.h"
23#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070024#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080025
Peng Xue36e3472016-11-03 11:57:10 -070026#define UNUSED(x) (void)(x)
27
Peng Xueb4d6282015-12-10 18:02:41 -080028namespace android {
29
30SensorService::SensorEventConnection::SensorEventConnection(
31 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Svet Ganove752a5c2018-01-15 17:14:20 -080032 const String16& opPackageName, bool hasSensorAccess)
Peng Xueb4d6282015-12-10 18:02:41 -080033 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070034 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080035 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
36 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false),
37 mHasSensorAccess(hasSensorAccess) {
Peng Xueb4d6282015-12-10 18:02:41 -080038 mChannel = new BitTube(mService->mSocketBufferSize);
39#if DEBUG_CONNECTIONS
40 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
41 mTotalAcksNeeded = mTotalAcksReceived = 0;
42#endif
43}
44
45SensorService::SensorEventConnection::~SensorEventConnection() {
46 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070047 destroy();
48}
49
50void SensorService::SensorEventConnection::destroy() {
51 Mutex::Autolock _l(mDestroyLock);
52
53 // destroy once only
54 if (mDestroyed) {
55 return;
56 }
57
Peng Xueb4d6282015-12-10 18:02:41 -080058 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070059 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080060 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080061 }
Peng Xu8cbefd72017-07-10 16:41:08 -070062 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080063}
64
65void SensorService::SensorEventConnection::onFirstRef() {
66 LooperCallback::onFirstRef();
67}
68
69bool SensorService::SensorEventConnection::needsWakeLock() {
70 Mutex::Autolock _l(mConnectionLock);
71 return !mDead && mWakeLockRefCount > 0;
72}
73
74void SensorService::SensorEventConnection::resetWakeLockRefCount() {
75 Mutex::Autolock _l(mConnectionLock);
76 mWakeLockRefCount = 0;
77}
78
79void SensorService::SensorEventConnection::dump(String8& result) {
80 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070081 result.appendFormat("\tOperating Mode: ");
82 if (!mService->isWhiteListedPackage(getPackageName())) {
83 result.append("RESTRICTED\n");
84 } else if (mDataInjectionMode) {
85 result.append("DATA_INJECTION\n");
86 } else {
87 result.append("NORMAL\n");
88 }
Peng Xueb4d6282015-12-10 18:02:41 -080089 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
90 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
91 mMaxCacheSize);
92 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
93 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
94 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
95 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
96 mSensorInfo.keyAt(i),
97 flushInfo.mFirstFlushPending ? "First flush pending" :
98 "active",
99 flushInfo.mPendingFlushEventsToSend);
100 }
101#if DEBUG_CONNECTIONS
102 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
103 " total_acks_needed %d | total_acks_recvd %d\n",
104 mEventsReceived,
105 mEventsSent,
106 mEventsSentFromCache,
107 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
108 mTotalAcksNeeded,
109 mTotalAcksReceived);
110#endif
111}
112
113bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
114 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700115 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
116 if (si == nullptr ||
117 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
118 mSensorInfo.indexOfKey(handle) >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800119 return false;
120 }
Peng Xu755c4512016-04-07 23:15:14 -0700121 mSensorInfo.add(handle, FlushInfo());
122 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800123}
124
125bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
126 Mutex::Autolock _l(mConnectionLock);
127 if (mSensorInfo.removeItem(handle) >= 0) {
128 return true;
129 }
130 return false;
131}
132
133bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
134 Mutex::Autolock _l(mConnectionLock);
135 return mSensorInfo.indexOfKey(handle) >= 0;
136}
137
138bool SensorService::SensorEventConnection::hasAnySensor() const {
139 Mutex::Autolock _l(mConnectionLock);
140 return mSensorInfo.size() ? true : false;
141}
142
143bool SensorService::SensorEventConnection::hasOneShotSensors() const {
144 Mutex::Autolock _l(mConnectionLock);
145 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
146 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700147 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
148 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800149 return true;
150 }
151 }
152 return false;
153}
154
155String8 SensorService::SensorEventConnection::getPackageName() const {
156 return mPackageName;
157}
158
159void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
160 bool value) {
161 Mutex::Autolock _l(mConnectionLock);
162 ssize_t index = mSensorInfo.indexOfKey(handle);
163 if (index >= 0) {
164 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
165 flushInfo.mFirstFlushPending = value;
166 }
167}
168
169void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
170 Mutex::Autolock _l(mConnectionLock);
171 updateLooperRegistrationLocked(looper);
172}
173
174void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
175 const sp<Looper>& looper) {
176 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
177 mDataInjectionMode;
178 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
179 // the Looper if it has been previously added.
180 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
181 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
182 mChannel->getSendFd());
183 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
184 return; }
185
186 int looper_flags = 0;
187 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
188 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
189 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
190 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700191 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
192 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800193 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800194 }
195 }
196
197 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
198 // already been added, remove it. This is likely to happen when ALL the events stored in the
199 // cache have been sent to the corresponding app.
200 if (looper_flags == 0) {
201 if (mHasLooperCallbacks) {
202 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
203 looper->removeFd(mChannel->getSendFd());
204 mHasLooperCallbacks = false;
205 }
206 return;
207 }
208
209 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
210 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700211 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800212 if (ret == 1) {
213 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
214 mHasLooperCallbacks = true;
215 } else {
216 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
217 }
218}
219
220void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
221 Mutex::Autolock _l(mConnectionLock);
222 ssize_t index = mSensorInfo.indexOfKey(handle);
223 if (index >= 0) {
224 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
225 flushInfo.mPendingFlushEventsToSend++;
226 }
227}
228
229status_t SensorService::SensorEventConnection::sendEvents(
230 sensors_event_t const* buffer, size_t numEvents,
231 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700232 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800233 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800234
George Burgess IV1866ed42018-01-21 12:14:09 -0800235 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800236
Peng Xueb4d6282015-12-10 18:02:41 -0800237 int count = 0;
238 Mutex::Autolock _l(mConnectionLock);
239 if (scratch) {
240 size_t i=0;
241 while (i<numEvents) {
242 int32_t sensor_handle = buffer[i].sensor;
243 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
244 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
245 buffer[i].meta_data.sensor);
246 // Setting sensor_handle to the correct sensor to ensure the sensor events per
247 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
248 // events.
249 sensor_handle = buffer[i].meta_data.sensor;
250 }
251
252 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
253 // Check if this connection has registered for this sensor. If not continue to the
254 // next sensor_event.
255 if (index < 0) {
256 ++i;
257 continue;
258 }
259
260 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
261 // Check if there is a pending flush_complete event for this sensor on this connection.
262 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700263 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800264 flushInfo.mFirstFlushPending = false;
265 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
266 buffer[i].meta_data.sensor);
267 ++i;
268 continue;
269 }
270
271 // If there is a pending flush complete event for this sensor on this connection,
272 // ignore the event and proceed to the next.
273 if (flushInfo.mFirstFlushPending) {
274 ++i;
275 continue;
276 }
277
278 do {
279 // Keep copying events into the scratch buffer as long as they are regular
280 // sensor_events are from the same sensor_handle OR they are flush_complete_events
281 // from the same sensor_handle AND the current connection is mapped to the
282 // corresponding flush_complete_event.
283 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700284 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800285 scratch[count++] = buffer[i];
286 }
Peng Xueb4d6282015-12-10 18:02:41 -0800287 } else {
288 // Regular sensor event, just copy it to the scratch buffer.
Michael Groover5e1f60b2018-12-04 22:34:29 -0800289 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800290 scratch[count++] = buffer[i];
291 }
Peng Xueb4d6282015-12-10 18:02:41 -0800292 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800293 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800294 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
295 buffer[i].type != SENSOR_TYPE_META_DATA) ||
296 (buffer[i].type == SENSOR_TYPE_META_DATA &&
297 buffer[i].meta_data.sensor == sensor_handle)));
298 }
299 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800300 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800301 scratch = const_cast<sensors_event_t *>(buffer);
302 count = numEvents;
303 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800304 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
305 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800306 for (size_t i = 0; i < numEvents; i++) {
307 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
308 scratch[count++] = buffer[i++];
309 }
310 }
311 }
Peng Xueb4d6282015-12-10 18:02:41 -0800312 }
313
314 sendPendingFlushEventsLocked();
315 // Early return if there are no events for this connection.
316 if (count == 0) {
317 return status_t(NO_ERROR);
318 }
319
320#if DEBUG_CONNECTIONS
321 mEventsReceived += count;
322#endif
323 if (mCacheSize != 0) {
324 // There are some events in the cache which need to be sent first. Copy this buffer to
325 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800326 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800327 return status_t(NO_ERROR);
328 }
329
Svet Ganove752a5c2018-01-15 17:14:20 -0800330 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800331 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800332 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
333 if (index_wake_up_event >= 0) {
334 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
335 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800336#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800337 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800338#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800339 }
Peng Xueb4d6282015-12-10 18:02:41 -0800340 }
341
342 // NOTE: ASensorEvent and sensors_event_t are the same type.
343 ssize_t size = SensorEventQueue::write(mChannel,
344 reinterpret_cast<ASensorEvent const*>(scratch), count);
345 if (size < 0) {
346 // Write error, copy events to local cache.
347 if (index_wake_up_event >= 0) {
348 // If there was a wake_up sensor_event, reset the flag.
349 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
350 if (mWakeLockRefCount > 0) {
351 --mWakeLockRefCount;
352 }
353#if DEBUG_CONNECTIONS
354 --mTotalAcksNeeded;
355#endif
356 }
Yi Kong8f313e32018-07-17 14:13:29 -0700357 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800358 mMaxCacheSize = computeMaxCacheSizeLocked();
359 mEventCache = new sensors_event_t[mMaxCacheSize];
360 mCacheSize = 0;
361 }
Brian Stack93432ad2018-11-27 18:28:48 -0800362 // Save the events so that they can be written later
363 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800364
365 // Add this file descriptor to the looper to get a callback when this fd is available for
366 // writing.
367 updateLooperRegistrationLocked(mService->getLooper());
368 return size;
369 }
370
371#if DEBUG_CONNECTIONS
372 if (size > 0) {
373 mEventsSent += count;
374 }
375#endif
376
377 return size < 0 ? status_t(size) : status_t(NO_ERROR);
378}
379
Svet Ganove752a5c2018-01-15 17:14:20 -0800380void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
381 Mutex::Autolock _l(mConnectionLock);
382 mHasSensorAccess = hasAccess;
383}
384
Michael Groover5e1f60b2018-12-04 22:34:29 -0800385bool SensorService::SensorEventConnection::hasSensorAccess() {
386 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
387}
388
Peng Xueb4d6282015-12-10 18:02:41 -0800389void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
390 int count) {
391 sensors_event_t *eventCache_new;
392 const int new_cache_size = computeMaxCacheSizeLocked();
393 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
394 eventCache_new = new sensors_event_t[new_cache_size];
395 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
396 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
397
398 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
399 new_cache_size);
400
George Burgess IV1866ed42018-01-21 12:14:09 -0800401 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800402 mEventCache = eventCache_new;
403 mCacheSize += count;
404 mMaxCacheSize = new_cache_size;
405}
406
Brian Stack93432ad2018-11-27 18:28:48 -0800407void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
408 int count) {
409 if (count <= 0) {
410 return;
411 } else if (mCacheSize + count <= mMaxCacheSize) {
412 // The events fit within the current cache: add them
413 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
414 mCacheSize += count;
415 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
416 // The events fit within a resized cache: resize the cache and add the events
417 reAllocateCacheLocked(events, count);
418 } else {
419 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800420 int freeSpace = mMaxCacheSize - mCacheSize;
421
422 // Drop up to the currently cached number of events to make room for new events
423 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
424
425 // New events need to be dropped if there are more new events than the size of the cache
426 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
427
428 // Determine the number of new events to copy into the cache
429 int eventsToCopy = std::min(mMaxCacheSize, count);
430
Brian Stackae4053f2018-12-10 14:54:18 -0800431 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
432 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
433 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
434 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
435 count, mEventsDropped);
436 mEventsDropped = 0;
437 mTimeOfLastEventDrop = events[0].timestamp;
438 } else {
439 // Record the number dropped
440 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
441 }
442
Brian Stack93432ad2018-11-27 18:28:48 -0800443 // Check for any flush complete events in the events that will be dropped
444 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
445 countFlushCompleteEventsLocked(events, newEventsToDrop);
446
447 // Only shift the events if they will not all be overwritten
448 if (eventsToCopy != mMaxCacheSize) {
449 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
450 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
451 }
452 mCacheSize -= cachedEventsToDrop;
453
454 // Copy the events into the cache
455 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
456 eventsToCopy * sizeof(sensors_event_t));
457 mCacheSize += eventsToCopy;
458 }
459}
460
Peng Xueb4d6282015-12-10 18:02:41 -0800461void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
462 ASensorEvent flushCompleteEvent;
463 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
464 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
465 // Loop through all the sensors for this connection and check if there are any pending
466 // flush complete events to be sent.
467 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700468 const int handle = mSensorInfo.keyAt(i);
469 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
470 if (si == nullptr) {
471 continue;
472 }
473
Peng Xueb4d6282015-12-10 18:02:41 -0800474 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
475 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700476 flushCompleteEvent.meta_data.sensor = handle;
477 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800478 if (wakeUpSensor) {
479 ++mWakeLockRefCount;
480 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
481 }
482 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
483 if (size < 0) {
484 if (wakeUpSensor) --mWakeLockRefCount;
485 return;
486 }
487 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
488 flushCompleteEvent.meta_data.sensor);
489 flushInfo.mPendingFlushEventsToSend--;
490 }
491 }
492}
493
494void SensorService::SensorEventConnection::writeToSocketFromCache() {
495 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
496 // half the size of the socket buffer allocated in BitTube whichever is smaller.
497 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
498 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
499 Mutex::Autolock _l(mConnectionLock);
500 // Send pending flush complete events (if any)
501 sendPendingFlushEventsLocked();
502 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
503 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800504 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800505 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800506 index_wake_up_event =
507 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
508 if (index_wake_up_event >= 0) {
509 mEventCache[index_wake_up_event + numEventsSent].flags |=
510 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
511 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800512#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800513 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800514#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800515 }
Peng Xueb4d6282015-12-10 18:02:41 -0800516 }
517
518 ssize_t size = SensorEventQueue::write(mChannel,
519 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
520 numEventsToWrite);
521 if (size < 0) {
522 if (index_wake_up_event >= 0) {
523 // If there was a wake_up sensor_event, reset the flag.
524 mEventCache[index_wake_up_event + numEventsSent].flags &=
525 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
526 if (mWakeLockRefCount > 0) {
527 --mWakeLockRefCount;
528 }
529#if DEBUG_CONNECTIONS
530 --mTotalAcksNeeded;
531#endif
532 }
533 memmove(mEventCache, &mEventCache[numEventsSent],
534 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
535 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
536 numEventsSent, mCacheSize);
537 mCacheSize -= numEventsSent;
538 return;
539 }
540 numEventsSent += numEventsToWrite;
541#if DEBUG_CONNECTIONS
542 mEventsSentFromCache += numEventsToWrite;
543#endif
544 }
545 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
546 // All events from the cache have been sent. Reset cache size to zero.
547 mCacheSize = 0;
548 // There are no more events in the cache. We don't need to poll for write on the fd.
549 // Update Looper registration.
550 updateLooperRegistrationLocked(mService->getLooper());
551}
552
553void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
554 sensors_event_t const* scratch, const int numEventsDropped) {
555 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
556 // Count flushComplete events in the events that are about to the dropped. These will be sent
557 // separately before the next batch of events.
558 for (int j = 0; j < numEventsDropped; ++j) {
559 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700560 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
561 if (index < 0) {
562 ALOGW("%s: sensor 0x%x is not found in connection",
563 __func__, scratch[j].meta_data.sensor);
564 continue;
565 }
566
567 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800568 flushInfo.mPendingFlushEventsToSend++;
569 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
570 flushInfo.mPendingFlushEventsToSend);
571 }
572 }
573 return;
574}
575
576int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
577 sensors_event_t const* scratch, const int count) {
578 for (int i = 0; i < count; ++i) {
579 if (mService->isWakeUpSensorEvent(scratch[i])) {
580 return i;
581 }
582 }
583 return -1;
584}
585
586sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
587{
588 return mChannel;
589}
590
591status_t SensorService::SensorEventConnection::enableDisable(
592 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
593 int reservedFlags)
594{
595 status_t err;
596 if (enabled) {
597 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
598 reservedFlags, mOpPackageName);
599
600 } else {
601 err = mService->disable(this, handle);
602 }
603 return err;
604}
605
606status_t SensorService::SensorEventConnection::setEventRate(
607 int handle, nsecs_t samplingPeriodNs)
608{
609 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
610}
611
612status_t SensorService::SensorEventConnection::flush() {
613 return mService->flushSensor(this, mOpPackageName);
614}
615
Peng Xue36e3472016-11-03 11:57:10 -0700616int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
617 // SensorEventConnection does not support configureChannel, parameters not used
618 UNUSED(handle);
619 UNUSED(rateLevel);
620 return INVALID_OPERATION;
621}
622
Peng Xueb4d6282015-12-10 18:02:41 -0800623int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
624 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
625 {
626 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
627 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
628 // can release the wake-lock.
629 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
630 Mutex::Autolock _l(mConnectionLock);
631 mDead = true;
632 mWakeLockRefCount = 0;
633 updateLooperRegistrationLocked(mService->getLooper());
634 }
635 mService->checkWakeLockState();
636 if (mDataInjectionMode) {
637 // If the Looper has encountered some error in data injection mode, reset SensorService
638 // back to normal mode.
639 mService->resetToNormalMode();
640 mDataInjectionMode = false;
641 }
642 return 1;
643 }
644
645 if (events & ALOOPER_EVENT_INPUT) {
646 unsigned char buf[sizeof(sensors_event_t)];
647 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
648 {
Peng Xu755c4512016-04-07 23:15:14 -0700649 Mutex::Autolock _l(mConnectionLock);
650 if (numBytesRead == sizeof(sensors_event_t)) {
651 if (!mDataInjectionMode) {
652 ALOGE("Data injected in normal mode, dropping event"
653 "package=%s uid=%d", mPackageName.string(), mUid);
654 // Unregister call backs.
655 return 0;
656 }
657 sensors_event_t sensor_event;
658 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
659 sp<SensorInterface> si =
660 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
661 if (si == nullptr) {
662 return 1;
663 }
664
665 SensorDevice& dev(SensorDevice::getInstance());
666 sensor_event.type = si->getSensor().getType();
667 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800668#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700669 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800670#endif
Peng Xu755c4512016-04-07 23:15:14 -0700671 } else if (numBytesRead == sizeof(uint32_t)) {
672 uint32_t numAcks = 0;
673 memcpy(&numAcks, buf, numBytesRead);
674 // Sanity check to ensure there are no read errors in recv, numAcks is always
675 // within the range and not zero. If any of the above don't hold reset
676 // mWakeLockRefCount to zero.
677 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
678 mWakeLockRefCount -= numAcks;
679 } else {
680 mWakeLockRefCount = 0;
681 }
Peng Xueb4d6282015-12-10 18:02:41 -0800682#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700683 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800684#endif
685 } else {
686 // Read error, reset wakelock refcount.
687 mWakeLockRefCount = 0;
688 }
689 }
690 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
691 // here as checkWakeLockState() will need it.
692 if (mWakeLockRefCount == 0) {
693 mService->checkWakeLockState();
694 }
695 // continue getting callbacks.
696 return 1;
697 }
698
699 if (events & ALOOPER_EVENT_OUTPUT) {
700 // send sensor data that is stored in mEventCache for this connection.
701 mService->sendEventsFromCache(this);
702 }
703 return 1;
704}
705
706int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
707 size_t fifoWakeUpSensors = 0;
708 size_t fifoNonWakeUpSensors = 0;
709 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700710 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
711 if (si == nullptr) {
712 continue;
713 }
714 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800715 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
716 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
717 // non wake_up sensors.
718 if (sensor.isWakeUpSensor()) {
719 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
720 } else {
721 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
722 }
723 } else {
724 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
725 if (sensor.isWakeUpSensor()) {
726 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
727 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
728
729 } else {
730 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
731 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
732
733 }
734 }
735 }
736 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
737 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
738 // size that is equal to that of the batch mode.
739 // ALOGW("Write failure in non-batch mode");
740 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
741 }
742 return fifoWakeUpSensors + fifoNonWakeUpSensors;
743}
744
745} // namespace android
746