blob: b66cbcfbe5790b8748f048c46b5f15b0f1738225 [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);
81 result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
82 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
83 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
84 mMaxCacheSize);
85 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
86 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
87 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
88 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
89 mSensorInfo.keyAt(i),
90 flushInfo.mFirstFlushPending ? "First flush pending" :
91 "active",
92 flushInfo.mPendingFlushEventsToSend);
93 }
94#if DEBUG_CONNECTIONS
95 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
96 " total_acks_needed %d | total_acks_recvd %d\n",
97 mEventsReceived,
98 mEventsSent,
99 mEventsSentFromCache,
100 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
101 mTotalAcksNeeded,
102 mTotalAcksReceived);
103#endif
104}
105
106bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
107 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700108 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
109 if (si == nullptr ||
110 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
111 mSensorInfo.indexOfKey(handle) >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800112 return false;
113 }
Peng Xu755c4512016-04-07 23:15:14 -0700114 mSensorInfo.add(handle, FlushInfo());
115 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800116}
117
118bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
119 Mutex::Autolock _l(mConnectionLock);
120 if (mSensorInfo.removeItem(handle) >= 0) {
121 return true;
122 }
123 return false;
124}
125
126bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
127 Mutex::Autolock _l(mConnectionLock);
128 return mSensorInfo.indexOfKey(handle) >= 0;
129}
130
131bool SensorService::SensorEventConnection::hasAnySensor() const {
132 Mutex::Autolock _l(mConnectionLock);
133 return mSensorInfo.size() ? true : false;
134}
135
136bool SensorService::SensorEventConnection::hasOneShotSensors() const {
137 Mutex::Autolock _l(mConnectionLock);
138 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
139 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700140 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
141 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800142 return true;
143 }
144 }
145 return false;
146}
147
148String8 SensorService::SensorEventConnection::getPackageName() const {
149 return mPackageName;
150}
151
152void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
153 bool value) {
154 Mutex::Autolock _l(mConnectionLock);
155 ssize_t index = mSensorInfo.indexOfKey(handle);
156 if (index >= 0) {
157 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
158 flushInfo.mFirstFlushPending = value;
159 }
160}
161
162void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
163 Mutex::Autolock _l(mConnectionLock);
164 updateLooperRegistrationLocked(looper);
165}
166
167void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
168 const sp<Looper>& looper) {
169 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
170 mDataInjectionMode;
171 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
172 // the Looper if it has been previously added.
173 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
174 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
175 mChannel->getSendFd());
176 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
177 return; }
178
179 int looper_flags = 0;
180 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
181 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
182 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
183 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700184 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
185 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800186 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800187 }
188 }
189
190 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
191 // already been added, remove it. This is likely to happen when ALL the events stored in the
192 // cache have been sent to the corresponding app.
193 if (looper_flags == 0) {
194 if (mHasLooperCallbacks) {
195 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
196 looper->removeFd(mChannel->getSendFd());
197 mHasLooperCallbacks = false;
198 }
199 return;
200 }
201
202 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
203 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700204 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800205 if (ret == 1) {
206 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
207 mHasLooperCallbacks = true;
208 } else {
209 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
210 }
211}
212
213void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
214 Mutex::Autolock _l(mConnectionLock);
215 ssize_t index = mSensorInfo.indexOfKey(handle);
216 if (index >= 0) {
217 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
218 flushInfo.mPendingFlushEventsToSend++;
219 }
220}
221
222status_t SensorService::SensorEventConnection::sendEvents(
223 sensors_event_t const* buffer, size_t numEvents,
224 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700225 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800226 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800227
George Burgess IV1866ed42018-01-21 12:14:09 -0800228 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800229
Peng Xueb4d6282015-12-10 18:02:41 -0800230 int count = 0;
231 Mutex::Autolock _l(mConnectionLock);
232 if (scratch) {
233 size_t i=0;
234 while (i<numEvents) {
235 int32_t sensor_handle = buffer[i].sensor;
236 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
237 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
238 buffer[i].meta_data.sensor);
239 // Setting sensor_handle to the correct sensor to ensure the sensor events per
240 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
241 // events.
242 sensor_handle = buffer[i].meta_data.sensor;
243 }
244
245 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
246 // Check if this connection has registered for this sensor. If not continue to the
247 // next sensor_event.
248 if (index < 0) {
249 ++i;
250 continue;
251 }
252
253 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
254 // Check if there is a pending flush_complete event for this sensor on this connection.
255 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700256 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800257 flushInfo.mFirstFlushPending = false;
258 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
259 buffer[i].meta_data.sensor);
260 ++i;
261 continue;
262 }
263
264 // If there is a pending flush complete event for this sensor on this connection,
265 // ignore the event and proceed to the next.
266 if (flushInfo.mFirstFlushPending) {
267 ++i;
268 continue;
269 }
270
271 do {
272 // Keep copying events into the scratch buffer as long as they are regular
273 // sensor_events are from the same sensor_handle OR they are flush_complete_events
274 // from the same sensor_handle AND the current connection is mapped to the
275 // corresponding flush_complete_event.
276 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700277 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800278 scratch[count++] = buffer[i];
279 }
Peng Xueb4d6282015-12-10 18:02:41 -0800280 } else {
281 // Regular sensor event, just copy it to the scratch buffer.
Michael Groover5e1f60b2018-12-04 22:34:29 -0800282 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800283 scratch[count++] = buffer[i];
284 }
Peng Xueb4d6282015-12-10 18:02:41 -0800285 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800286 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800287 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
288 buffer[i].type != SENSOR_TYPE_META_DATA) ||
289 (buffer[i].type == SENSOR_TYPE_META_DATA &&
290 buffer[i].meta_data.sensor == sensor_handle)));
291 }
292 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800293 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800294 scratch = const_cast<sensors_event_t *>(buffer);
295 count = numEvents;
296 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800297 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
298 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800299 for (size_t i = 0; i < numEvents; i++) {
300 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
301 scratch[count++] = buffer[i++];
302 }
303 }
304 }
Peng Xueb4d6282015-12-10 18:02:41 -0800305 }
306
307 sendPendingFlushEventsLocked();
308 // Early return if there are no events for this connection.
309 if (count == 0) {
310 return status_t(NO_ERROR);
311 }
312
313#if DEBUG_CONNECTIONS
314 mEventsReceived += count;
315#endif
316 if (mCacheSize != 0) {
317 // There are some events in the cache which need to be sent first. Copy this buffer to
318 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800319 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800320 return status_t(NO_ERROR);
321 }
322
Svet Ganove752a5c2018-01-15 17:14:20 -0800323 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800324 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800325 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
326 if (index_wake_up_event >= 0) {
327 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
328 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800329#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800330 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800331#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800332 }
Peng Xueb4d6282015-12-10 18:02:41 -0800333 }
334
335 // NOTE: ASensorEvent and sensors_event_t are the same type.
336 ssize_t size = SensorEventQueue::write(mChannel,
337 reinterpret_cast<ASensorEvent const*>(scratch), count);
338 if (size < 0) {
339 // Write error, copy events to local cache.
340 if (index_wake_up_event >= 0) {
341 // If there was a wake_up sensor_event, reset the flag.
342 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
343 if (mWakeLockRefCount > 0) {
344 --mWakeLockRefCount;
345 }
346#if DEBUG_CONNECTIONS
347 --mTotalAcksNeeded;
348#endif
349 }
Yi Kong8f313e32018-07-17 14:13:29 -0700350 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800351 mMaxCacheSize = computeMaxCacheSizeLocked();
352 mEventCache = new sensors_event_t[mMaxCacheSize];
353 mCacheSize = 0;
354 }
Brian Stack93432ad2018-11-27 18:28:48 -0800355 // Save the events so that they can be written later
356 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800357
358 // Add this file descriptor to the looper to get a callback when this fd is available for
359 // writing.
360 updateLooperRegistrationLocked(mService->getLooper());
361 return size;
362 }
363
364#if DEBUG_CONNECTIONS
365 if (size > 0) {
366 mEventsSent += count;
367 }
368#endif
369
370 return size < 0 ? status_t(size) : status_t(NO_ERROR);
371}
372
Svet Ganove752a5c2018-01-15 17:14:20 -0800373void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
374 Mutex::Autolock _l(mConnectionLock);
375 mHasSensorAccess = hasAccess;
376}
377
Michael Groover5e1f60b2018-12-04 22:34:29 -0800378bool SensorService::SensorEventConnection::hasSensorAccess() {
379 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
380}
381
Peng Xueb4d6282015-12-10 18:02:41 -0800382void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
383 int count) {
384 sensors_event_t *eventCache_new;
385 const int new_cache_size = computeMaxCacheSizeLocked();
386 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
387 eventCache_new = new sensors_event_t[new_cache_size];
388 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
389 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
390
391 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
392 new_cache_size);
393
George Burgess IV1866ed42018-01-21 12:14:09 -0800394 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800395 mEventCache = eventCache_new;
396 mCacheSize += count;
397 mMaxCacheSize = new_cache_size;
398}
399
Brian Stack93432ad2018-11-27 18:28:48 -0800400void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
401 int count) {
402 if (count <= 0) {
403 return;
404 } else if (mCacheSize + count <= mMaxCacheSize) {
405 // The events fit within the current cache: add them
406 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
407 mCacheSize += count;
408 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
409 // The events fit within a resized cache: resize the cache and add the events
410 reAllocateCacheLocked(events, count);
411 } else {
412 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800413 int freeSpace = mMaxCacheSize - mCacheSize;
414
415 // Drop up to the currently cached number of events to make room for new events
416 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
417
418 // New events need to be dropped if there are more new events than the size of the cache
419 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
420
421 // Determine the number of new events to copy into the cache
422 int eventsToCopy = std::min(mMaxCacheSize, count);
423
Brian Stackae4053f2018-12-10 14:54:18 -0800424 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
425 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
426 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
427 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
428 count, mEventsDropped);
429 mEventsDropped = 0;
430 mTimeOfLastEventDrop = events[0].timestamp;
431 } else {
432 // Record the number dropped
433 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
434 }
435
Brian Stack93432ad2018-11-27 18:28:48 -0800436 // Check for any flush complete events in the events that will be dropped
437 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
438 countFlushCompleteEventsLocked(events, newEventsToDrop);
439
440 // Only shift the events if they will not all be overwritten
441 if (eventsToCopy != mMaxCacheSize) {
442 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
443 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
444 }
445 mCacheSize -= cachedEventsToDrop;
446
447 // Copy the events into the cache
448 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
449 eventsToCopy * sizeof(sensors_event_t));
450 mCacheSize += eventsToCopy;
451 }
452}
453
Peng Xueb4d6282015-12-10 18:02:41 -0800454void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
455 ASensorEvent flushCompleteEvent;
456 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
457 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
458 // Loop through all the sensors for this connection and check if there are any pending
459 // flush complete events to be sent.
460 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700461 const int handle = mSensorInfo.keyAt(i);
462 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
463 if (si == nullptr) {
464 continue;
465 }
466
Peng Xueb4d6282015-12-10 18:02:41 -0800467 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
468 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700469 flushCompleteEvent.meta_data.sensor = handle;
470 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800471 if (wakeUpSensor) {
472 ++mWakeLockRefCount;
473 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
474 }
475 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
476 if (size < 0) {
477 if (wakeUpSensor) --mWakeLockRefCount;
478 return;
479 }
480 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
481 flushCompleteEvent.meta_data.sensor);
482 flushInfo.mPendingFlushEventsToSend--;
483 }
484 }
485}
486
487void SensorService::SensorEventConnection::writeToSocketFromCache() {
488 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
489 // half the size of the socket buffer allocated in BitTube whichever is smaller.
490 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
491 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
492 Mutex::Autolock _l(mConnectionLock);
493 // Send pending flush complete events (if any)
494 sendPendingFlushEventsLocked();
495 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
496 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800497 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800498 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800499 index_wake_up_event =
500 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
501 if (index_wake_up_event >= 0) {
502 mEventCache[index_wake_up_event + numEventsSent].flags |=
503 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
504 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800505#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800506 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800507#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800508 }
Peng Xueb4d6282015-12-10 18:02:41 -0800509 }
510
511 ssize_t size = SensorEventQueue::write(mChannel,
512 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
513 numEventsToWrite);
514 if (size < 0) {
515 if (index_wake_up_event >= 0) {
516 // If there was a wake_up sensor_event, reset the flag.
517 mEventCache[index_wake_up_event + numEventsSent].flags &=
518 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
519 if (mWakeLockRefCount > 0) {
520 --mWakeLockRefCount;
521 }
522#if DEBUG_CONNECTIONS
523 --mTotalAcksNeeded;
524#endif
525 }
526 memmove(mEventCache, &mEventCache[numEventsSent],
527 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
528 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
529 numEventsSent, mCacheSize);
530 mCacheSize -= numEventsSent;
531 return;
532 }
533 numEventsSent += numEventsToWrite;
534#if DEBUG_CONNECTIONS
535 mEventsSentFromCache += numEventsToWrite;
536#endif
537 }
538 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
539 // All events from the cache have been sent. Reset cache size to zero.
540 mCacheSize = 0;
541 // There are no more events in the cache. We don't need to poll for write on the fd.
542 // Update Looper registration.
543 updateLooperRegistrationLocked(mService->getLooper());
544}
545
546void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
547 sensors_event_t const* scratch, const int numEventsDropped) {
548 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
549 // Count flushComplete events in the events that are about to the dropped. These will be sent
550 // separately before the next batch of events.
551 for (int j = 0; j < numEventsDropped; ++j) {
552 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700553 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
554 if (index < 0) {
555 ALOGW("%s: sensor 0x%x is not found in connection",
556 __func__, scratch[j].meta_data.sensor);
557 continue;
558 }
559
560 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800561 flushInfo.mPendingFlushEventsToSend++;
562 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
563 flushInfo.mPendingFlushEventsToSend);
564 }
565 }
566 return;
567}
568
569int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
570 sensors_event_t const* scratch, const int count) {
571 for (int i = 0; i < count; ++i) {
572 if (mService->isWakeUpSensorEvent(scratch[i])) {
573 return i;
574 }
575 }
576 return -1;
577}
578
579sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
580{
581 return mChannel;
582}
583
584status_t SensorService::SensorEventConnection::enableDisable(
585 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
586 int reservedFlags)
587{
588 status_t err;
589 if (enabled) {
590 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
591 reservedFlags, mOpPackageName);
592
593 } else {
594 err = mService->disable(this, handle);
595 }
596 return err;
597}
598
599status_t SensorService::SensorEventConnection::setEventRate(
600 int handle, nsecs_t samplingPeriodNs)
601{
602 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
603}
604
605status_t SensorService::SensorEventConnection::flush() {
606 return mService->flushSensor(this, mOpPackageName);
607}
608
Peng Xue36e3472016-11-03 11:57:10 -0700609int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
610 // SensorEventConnection does not support configureChannel, parameters not used
611 UNUSED(handle);
612 UNUSED(rateLevel);
613 return INVALID_OPERATION;
614}
615
Peng Xueb4d6282015-12-10 18:02:41 -0800616int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
617 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
618 {
619 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
620 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
621 // can release the wake-lock.
622 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
623 Mutex::Autolock _l(mConnectionLock);
624 mDead = true;
625 mWakeLockRefCount = 0;
626 updateLooperRegistrationLocked(mService->getLooper());
627 }
628 mService->checkWakeLockState();
629 if (mDataInjectionMode) {
630 // If the Looper has encountered some error in data injection mode, reset SensorService
631 // back to normal mode.
632 mService->resetToNormalMode();
633 mDataInjectionMode = false;
634 }
635 return 1;
636 }
637
638 if (events & ALOOPER_EVENT_INPUT) {
639 unsigned char buf[sizeof(sensors_event_t)];
640 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
641 {
Peng Xu755c4512016-04-07 23:15:14 -0700642 Mutex::Autolock _l(mConnectionLock);
643 if (numBytesRead == sizeof(sensors_event_t)) {
644 if (!mDataInjectionMode) {
645 ALOGE("Data injected in normal mode, dropping event"
646 "package=%s uid=%d", mPackageName.string(), mUid);
647 // Unregister call backs.
648 return 0;
649 }
650 sensors_event_t sensor_event;
651 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
652 sp<SensorInterface> si =
653 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
654 if (si == nullptr) {
655 return 1;
656 }
657
658 SensorDevice& dev(SensorDevice::getInstance());
659 sensor_event.type = si->getSensor().getType();
660 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800661#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700662 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800663#endif
Peng Xu755c4512016-04-07 23:15:14 -0700664 } else if (numBytesRead == sizeof(uint32_t)) {
665 uint32_t numAcks = 0;
666 memcpy(&numAcks, buf, numBytesRead);
667 // Sanity check to ensure there are no read errors in recv, numAcks is always
668 // within the range and not zero. If any of the above don't hold reset
669 // mWakeLockRefCount to zero.
670 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
671 mWakeLockRefCount -= numAcks;
672 } else {
673 mWakeLockRefCount = 0;
674 }
Peng Xueb4d6282015-12-10 18:02:41 -0800675#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700676 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800677#endif
678 } else {
679 // Read error, reset wakelock refcount.
680 mWakeLockRefCount = 0;
681 }
682 }
683 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
684 // here as checkWakeLockState() will need it.
685 if (mWakeLockRefCount == 0) {
686 mService->checkWakeLockState();
687 }
688 // continue getting callbacks.
689 return 1;
690 }
691
692 if (events & ALOOPER_EVENT_OUTPUT) {
693 // send sensor data that is stored in mEventCache for this connection.
694 mService->sendEventsFromCache(this);
695 }
696 return 1;
697}
698
699int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
700 size_t fifoWakeUpSensors = 0;
701 size_t fifoNonWakeUpSensors = 0;
702 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700703 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
704 if (si == nullptr) {
705 continue;
706 }
707 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800708 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
709 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
710 // non wake_up sensors.
711 if (sensor.isWakeUpSensor()) {
712 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
713 } else {
714 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
715 }
716 } else {
717 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
718 if (sensor.isWakeUpSensor()) {
719 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
720 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
721
722 } else {
723 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
724 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
725
726 }
727 }
728 }
729 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
730 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
731 // size that is equal to that of the batch mode.
732 // ALOGW("Write failure in non-batch mode");
733 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
734 }
735 return fifoWakeUpSensors + fifoNonWakeUpSensors;
736}
737
738} // namespace android
739