blob: 776efab19c83331a3e957c923bdad6bfd0c2f8bb [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.
Svet Ganove752a5c2018-01-15 17:14:20 -0800282 if (mHasSensorAccess) {
283 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 {
Svet Ganove752a5c2018-01-15 17:14:20 -0800293 if (mHasSensorAccess) {
294 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;
324 if (mHasSensorAccess) {
325 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
Peng Xueb4d6282015-12-10 18:02:41 -0800378void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
379 int count) {
380 sensors_event_t *eventCache_new;
381 const int new_cache_size = computeMaxCacheSizeLocked();
382 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
383 eventCache_new = new sensors_event_t[new_cache_size];
384 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
385 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
386
387 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
388 new_cache_size);
389
George Burgess IV1866ed42018-01-21 12:14:09 -0800390 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800391 mEventCache = eventCache_new;
392 mCacheSize += count;
393 mMaxCacheSize = new_cache_size;
394}
395
Brian Stack93432ad2018-11-27 18:28:48 -0800396void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
397 int count) {
398 if (count <= 0) {
399 return;
400 } else if (mCacheSize + count <= mMaxCacheSize) {
401 // The events fit within the current cache: add them
402 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
403 mCacheSize += count;
404 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
405 // The events fit within a resized cache: resize the cache and add the events
406 reAllocateCacheLocked(events, count);
407 } else {
408 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800409 int freeSpace = mMaxCacheSize - mCacheSize;
410
411 // Drop up to the currently cached number of events to make room for new events
412 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
413
414 // New events need to be dropped if there are more new events than the size of the cache
415 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
416
417 // Determine the number of new events to copy into the cache
418 int eventsToCopy = std::min(mMaxCacheSize, count);
419
Brian Stackae4053f2018-12-10 14:54:18 -0800420 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
421 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
422 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
423 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
424 count, mEventsDropped);
425 mEventsDropped = 0;
426 mTimeOfLastEventDrop = events[0].timestamp;
427 } else {
428 // Record the number dropped
429 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
430 }
431
Brian Stack93432ad2018-11-27 18:28:48 -0800432 // Check for any flush complete events in the events that will be dropped
433 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
434 countFlushCompleteEventsLocked(events, newEventsToDrop);
435
436 // Only shift the events if they will not all be overwritten
437 if (eventsToCopy != mMaxCacheSize) {
438 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
439 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
440 }
441 mCacheSize -= cachedEventsToDrop;
442
443 // Copy the events into the cache
444 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
445 eventsToCopy * sizeof(sensors_event_t));
446 mCacheSize += eventsToCopy;
447 }
448}
449
Peng Xueb4d6282015-12-10 18:02:41 -0800450void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
451 ASensorEvent flushCompleteEvent;
452 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
453 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
454 // Loop through all the sensors for this connection and check if there are any pending
455 // flush complete events to be sent.
456 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700457 const int handle = mSensorInfo.keyAt(i);
458 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
459 if (si == nullptr) {
460 continue;
461 }
462
Peng Xueb4d6282015-12-10 18:02:41 -0800463 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
464 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700465 flushCompleteEvent.meta_data.sensor = handle;
466 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800467 if (wakeUpSensor) {
468 ++mWakeLockRefCount;
469 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
470 }
471 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
472 if (size < 0) {
473 if (wakeUpSensor) --mWakeLockRefCount;
474 return;
475 }
476 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
477 flushCompleteEvent.meta_data.sensor);
478 flushInfo.mPendingFlushEventsToSend--;
479 }
480 }
481}
482
483void SensorService::SensorEventConnection::writeToSocketFromCache() {
484 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
485 // half the size of the socket buffer allocated in BitTube whichever is smaller.
486 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
487 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
488 Mutex::Autolock _l(mConnectionLock);
489 // Send pending flush complete events (if any)
490 sendPendingFlushEventsLocked();
491 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
492 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800493 int index_wake_up_event = -1;
494 if (mHasSensorAccess) {
495 index_wake_up_event =
496 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
497 if (index_wake_up_event >= 0) {
498 mEventCache[index_wake_up_event + numEventsSent].flags |=
499 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
500 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800501#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800502 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800503#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800504 }
Peng Xueb4d6282015-12-10 18:02:41 -0800505 }
506
507 ssize_t size = SensorEventQueue::write(mChannel,
508 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
509 numEventsToWrite);
510 if (size < 0) {
511 if (index_wake_up_event >= 0) {
512 // If there was a wake_up sensor_event, reset the flag.
513 mEventCache[index_wake_up_event + numEventsSent].flags &=
514 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
515 if (mWakeLockRefCount > 0) {
516 --mWakeLockRefCount;
517 }
518#if DEBUG_CONNECTIONS
519 --mTotalAcksNeeded;
520#endif
521 }
522 memmove(mEventCache, &mEventCache[numEventsSent],
523 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
524 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
525 numEventsSent, mCacheSize);
526 mCacheSize -= numEventsSent;
527 return;
528 }
529 numEventsSent += numEventsToWrite;
530#if DEBUG_CONNECTIONS
531 mEventsSentFromCache += numEventsToWrite;
532#endif
533 }
534 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
535 // All events from the cache have been sent. Reset cache size to zero.
536 mCacheSize = 0;
537 // There are no more events in the cache. We don't need to poll for write on the fd.
538 // Update Looper registration.
539 updateLooperRegistrationLocked(mService->getLooper());
540}
541
542void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
543 sensors_event_t const* scratch, const int numEventsDropped) {
544 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
545 // Count flushComplete events in the events that are about to the dropped. These will be sent
546 // separately before the next batch of events.
547 for (int j = 0; j < numEventsDropped; ++j) {
548 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700549 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
550 if (index < 0) {
551 ALOGW("%s: sensor 0x%x is not found in connection",
552 __func__, scratch[j].meta_data.sensor);
553 continue;
554 }
555
556 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800557 flushInfo.mPendingFlushEventsToSend++;
558 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
559 flushInfo.mPendingFlushEventsToSend);
560 }
561 }
562 return;
563}
564
565int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
566 sensors_event_t const* scratch, const int count) {
567 for (int i = 0; i < count; ++i) {
568 if (mService->isWakeUpSensorEvent(scratch[i])) {
569 return i;
570 }
571 }
572 return -1;
573}
574
575sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
576{
577 return mChannel;
578}
579
580status_t SensorService::SensorEventConnection::enableDisable(
581 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
582 int reservedFlags)
583{
584 status_t err;
585 if (enabled) {
586 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
587 reservedFlags, mOpPackageName);
588
589 } else {
590 err = mService->disable(this, handle);
591 }
592 return err;
593}
594
595status_t SensorService::SensorEventConnection::setEventRate(
596 int handle, nsecs_t samplingPeriodNs)
597{
598 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
599}
600
601status_t SensorService::SensorEventConnection::flush() {
602 return mService->flushSensor(this, mOpPackageName);
603}
604
Peng Xue36e3472016-11-03 11:57:10 -0700605int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
606 // SensorEventConnection does not support configureChannel, parameters not used
607 UNUSED(handle);
608 UNUSED(rateLevel);
609 return INVALID_OPERATION;
610}
611
Peng Xueb4d6282015-12-10 18:02:41 -0800612int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
613 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
614 {
615 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
616 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
617 // can release the wake-lock.
618 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
619 Mutex::Autolock _l(mConnectionLock);
620 mDead = true;
621 mWakeLockRefCount = 0;
622 updateLooperRegistrationLocked(mService->getLooper());
623 }
624 mService->checkWakeLockState();
625 if (mDataInjectionMode) {
626 // If the Looper has encountered some error in data injection mode, reset SensorService
627 // back to normal mode.
628 mService->resetToNormalMode();
629 mDataInjectionMode = false;
630 }
631 return 1;
632 }
633
634 if (events & ALOOPER_EVENT_INPUT) {
635 unsigned char buf[sizeof(sensors_event_t)];
636 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
637 {
Peng Xu755c4512016-04-07 23:15:14 -0700638 Mutex::Autolock _l(mConnectionLock);
639 if (numBytesRead == sizeof(sensors_event_t)) {
640 if (!mDataInjectionMode) {
641 ALOGE("Data injected in normal mode, dropping event"
642 "package=%s uid=%d", mPackageName.string(), mUid);
643 // Unregister call backs.
644 return 0;
645 }
646 sensors_event_t sensor_event;
647 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
648 sp<SensorInterface> si =
649 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
650 if (si == nullptr) {
651 return 1;
652 }
653
654 SensorDevice& dev(SensorDevice::getInstance());
655 sensor_event.type = si->getSensor().getType();
656 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800657#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700658 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800659#endif
Peng Xu755c4512016-04-07 23:15:14 -0700660 } else if (numBytesRead == sizeof(uint32_t)) {
661 uint32_t numAcks = 0;
662 memcpy(&numAcks, buf, numBytesRead);
663 // Sanity check to ensure there are no read errors in recv, numAcks is always
664 // within the range and not zero. If any of the above don't hold reset
665 // mWakeLockRefCount to zero.
666 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
667 mWakeLockRefCount -= numAcks;
668 } else {
669 mWakeLockRefCount = 0;
670 }
Peng Xueb4d6282015-12-10 18:02:41 -0800671#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700672 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800673#endif
674 } else {
675 // Read error, reset wakelock refcount.
676 mWakeLockRefCount = 0;
677 }
678 }
679 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
680 // here as checkWakeLockState() will need it.
681 if (mWakeLockRefCount == 0) {
682 mService->checkWakeLockState();
683 }
684 // continue getting callbacks.
685 return 1;
686 }
687
688 if (events & ALOOPER_EVENT_OUTPUT) {
689 // send sensor data that is stored in mEventCache for this connection.
690 mService->sendEventsFromCache(this);
691 }
692 return 1;
693}
694
695int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
696 size_t fifoWakeUpSensors = 0;
697 size_t fifoNonWakeUpSensors = 0;
698 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700699 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
700 if (si == nullptr) {
701 continue;
702 }
703 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800704 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
705 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
706 // non wake_up sensors.
707 if (sensor.isWakeUpSensor()) {
708 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
709 } else {
710 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
711 }
712 } else {
713 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
714 if (sensor.isWakeUpSensor()) {
715 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
716 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
717
718 } else {
719 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
720 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
721
722 }
723 }
724 }
725 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
726 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
727 // size that is equal to that of the batch mode.
728 // ALOGW("Write failure in non-batch mode");
729 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
730 }
731 return fifoWakeUpSensors + fifoNonWakeUpSensors;
732}
733
734} // namespace android
735