blob: a9e8321dcfeaa06c05774cebbf10e1aab9667a64 [file] [log] [blame]
Peng Xueb4d6282015-12-10 18:02:41 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Arthur Ishiguro3b27b3b2020-09-22 13:05:15 -070017#include <log/log.h>
Peng Xueb4d6282015-12-10 18:02:41 -080018#include <sys/socket.h>
19#include <utils/threads.h>
20
Mathias Agopian801ea092017-03-06 15:05:04 -080021#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080022
23#include "vec.h"
24#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070025#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080026
Peng Xue36e3472016-11-03 11:57:10 -070027#define UNUSED(x) (void)(x)
28
Peng Xueb4d6282015-12-10 18:02:41 -080029namespace android {
30
31SensorService::SensorEventConnection::SensorEventConnection(
32 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Svet Ganove752a5c2018-01-15 17:14:20 -080033 const String16& opPackageName, bool hasSensorAccess)
Peng Xueb4d6282015-12-10 18:02:41 -080034 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
35 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
Peng Xu8cbefd72017-07-10 16:41:08 -070036 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName),
Svet Ganove752a5c2018-01-15 17:14:20 -080037 mDestroyed(false), 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();
Peng Xueb4d6282015-12-10 18:02:41 -080048 mService->cleanupConnection(this);
49 if (mEventCache != NULL) {
50 delete mEventCache;
51 }
Arthur Ishiguro3b27b3b2020-09-22 13:05:15 -070052}
53
54void SensorService::SensorEventConnection::destroy() {
Peng Xu8cbefd72017-07-10 16:41:08 -070055 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080056}
57
58void SensorService::SensorEventConnection::onFirstRef() {
59 LooperCallback::onFirstRef();
60}
61
62bool SensorService::SensorEventConnection::needsWakeLock() {
63 Mutex::Autolock _l(mConnectionLock);
64 return !mDead && mWakeLockRefCount > 0;
65}
66
67void SensorService::SensorEventConnection::resetWakeLockRefCount() {
68 Mutex::Autolock _l(mConnectionLock);
69 mWakeLockRefCount = 0;
70}
71
72void SensorService::SensorEventConnection::dump(String8& result) {
73 Mutex::Autolock _l(mConnectionLock);
74 result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
75 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
76 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
77 mMaxCacheSize);
78 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
79 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
80 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
81 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
82 mSensorInfo.keyAt(i),
83 flushInfo.mFirstFlushPending ? "First flush pending" :
84 "active",
85 flushInfo.mPendingFlushEventsToSend);
86 }
87#if DEBUG_CONNECTIONS
88 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
89 " total_acks_needed %d | total_acks_recvd %d\n",
90 mEventsReceived,
91 mEventsSent,
92 mEventsSentFromCache,
93 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
94 mTotalAcksNeeded,
95 mTotalAcksReceived);
96#endif
97}
98
99bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
100 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700101 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
102 if (si == nullptr ||
103 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
104 mSensorInfo.indexOfKey(handle) >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800105 return false;
106 }
Peng Xu755c4512016-04-07 23:15:14 -0700107 mSensorInfo.add(handle, FlushInfo());
108 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800109}
110
111bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
112 Mutex::Autolock _l(mConnectionLock);
113 if (mSensorInfo.removeItem(handle) >= 0) {
114 return true;
115 }
116 return false;
117}
118
119bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
120 Mutex::Autolock _l(mConnectionLock);
121 return mSensorInfo.indexOfKey(handle) >= 0;
122}
123
124bool SensorService::SensorEventConnection::hasAnySensor() const {
125 Mutex::Autolock _l(mConnectionLock);
126 return mSensorInfo.size() ? true : false;
127}
128
129bool SensorService::SensorEventConnection::hasOneShotSensors() const {
130 Mutex::Autolock _l(mConnectionLock);
131 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
132 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700133 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
134 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800135 return true;
136 }
137 }
138 return false;
139}
140
141String8 SensorService::SensorEventConnection::getPackageName() const {
142 return mPackageName;
143}
144
145void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
146 bool value) {
147 Mutex::Autolock _l(mConnectionLock);
148 ssize_t index = mSensorInfo.indexOfKey(handle);
149 if (index >= 0) {
150 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
151 flushInfo.mFirstFlushPending = value;
152 }
153}
154
155void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
156 Mutex::Autolock _l(mConnectionLock);
157 updateLooperRegistrationLocked(looper);
158}
159
160void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
161 const sp<Looper>& looper) {
162 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
163 mDataInjectionMode;
164 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
165 // the Looper if it has been previously added.
166 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
167 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
168 mChannel->getSendFd());
169 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
170 return; }
171
172 int looper_flags = 0;
173 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
174 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
175 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
176 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700177 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
178 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800179 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800180 }
181 }
182
183 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
184 // already been added, remove it. This is likely to happen when ALL the events stored in the
185 // cache have been sent to the corresponding app.
186 if (looper_flags == 0) {
187 if (mHasLooperCallbacks) {
188 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
189 looper->removeFd(mChannel->getSendFd());
190 mHasLooperCallbacks = false;
191 }
192 return;
193 }
194
195 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
196 // registered for wake-up sensors OR for sending events in the cache.
197 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
198 if (ret == 1) {
199 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
200 mHasLooperCallbacks = true;
201 } else {
202 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
203 }
204}
205
206void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
207 Mutex::Autolock _l(mConnectionLock);
208 ssize_t index = mSensorInfo.indexOfKey(handle);
209 if (index >= 0) {
210 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
211 flushInfo.mPendingFlushEventsToSend++;
212 }
213}
214
215status_t SensorService::SensorEventConnection::sendEvents(
216 sensors_event_t const* buffer, size_t numEvents,
217 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700218 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800219 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800220
221 sensors_event_t* sanitizedBuffer = nullptr;
222
Peng Xueb4d6282015-12-10 18:02:41 -0800223 int count = 0;
224 Mutex::Autolock _l(mConnectionLock);
225 if (scratch) {
226 size_t i=0;
227 while (i<numEvents) {
228 int32_t sensor_handle = buffer[i].sensor;
229 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
230 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
231 buffer[i].meta_data.sensor);
232 // Setting sensor_handle to the correct sensor to ensure the sensor events per
233 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
234 // events.
235 sensor_handle = buffer[i].meta_data.sensor;
236 }
237
238 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
239 // Check if this connection has registered for this sensor. If not continue to the
240 // next sensor_event.
241 if (index < 0) {
242 ++i;
243 continue;
244 }
245
246 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
247 // Check if there is a pending flush_complete event for this sensor on this connection.
248 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700249 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800250 flushInfo.mFirstFlushPending = false;
251 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
252 buffer[i].meta_data.sensor);
253 ++i;
254 continue;
255 }
256
257 // If there is a pending flush complete event for this sensor on this connection,
258 // ignore the event and proceed to the next.
259 if (flushInfo.mFirstFlushPending) {
260 ++i;
261 continue;
262 }
263
264 do {
265 // Keep copying events into the scratch buffer as long as they are regular
266 // sensor_events are from the same sensor_handle OR they are flush_complete_events
267 // from the same sensor_handle AND the current connection is mapped to the
268 // corresponding flush_complete_event.
269 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700270 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800271 scratch[count++] = buffer[i];
272 }
Peng Xueb4d6282015-12-10 18:02:41 -0800273 } else {
274 // Regular sensor event, just copy it to the scratch buffer.
Svet Ganove752a5c2018-01-15 17:14:20 -0800275 if (mHasSensorAccess) {
276 scratch[count++] = buffer[i];
277 }
Peng Xueb4d6282015-12-10 18:02:41 -0800278 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800279 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800280 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
281 buffer[i].type != SENSOR_TYPE_META_DATA) ||
282 (buffer[i].type == SENSOR_TYPE_META_DATA &&
283 buffer[i].meta_data.sensor == sensor_handle)));
284 }
285 } else {
Svet Ganove752a5c2018-01-15 17:14:20 -0800286 if (mHasSensorAccess) {
287 scratch = const_cast<sensors_event_t *>(buffer);
288 count = numEvents;
289 } else {
290 scratch = sanitizedBuffer = new sensors_event_t[numEvents];
291 for (size_t i = 0; i < numEvents; i++) {
292 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
293 scratch[count++] = buffer[i++];
294 }
295 }
296 }
Peng Xueb4d6282015-12-10 18:02:41 -0800297 }
298
299 sendPendingFlushEventsLocked();
300 // Early return if there are no events for this connection.
301 if (count == 0) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800302 delete sanitizedBuffer;
Peng Xueb4d6282015-12-10 18:02:41 -0800303 return status_t(NO_ERROR);
304 }
305
306#if DEBUG_CONNECTIONS
307 mEventsReceived += count;
308#endif
309 if (mCacheSize != 0) {
310 // There are some events in the cache which need to be sent first. Copy this buffer to
311 // the end of cache.
312 if (mCacheSize + count <= mMaxCacheSize) {
313 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
314 mCacheSize += count;
315 } else {
316 // Check if any new sensors have registered on this connection which may have increased
317 // the max cache size that is desired.
318 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
319 reAllocateCacheLocked(scratch, count);
Svet Ganove752a5c2018-01-15 17:14:20 -0800320 delete sanitizedBuffer;
Peng Xueb4d6282015-12-10 18:02:41 -0800321 return status_t(NO_ERROR);
322 }
323 // Some events need to be dropped.
324 int remaningCacheSize = mMaxCacheSize - mCacheSize;
325 if (remaningCacheSize != 0) {
326 memcpy(&mEventCache[mCacheSize], scratch,
327 remaningCacheSize * sizeof(sensors_event_t));
328 }
329 int numEventsDropped = count - remaningCacheSize;
330 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
331 // Drop the first "numEventsDropped" in the cache.
332 memmove(mEventCache, &mEventCache[numEventsDropped],
333 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
334
335 // Copy the remainingEvents in scratch buffer to the end of cache.
336 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
337 numEventsDropped * sizeof(sensors_event_t));
338 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800339 delete sanitizedBuffer;
Peng Xueb4d6282015-12-10 18:02:41 -0800340 return status_t(NO_ERROR);
341 }
342
Svet Ganove752a5c2018-01-15 17:14:20 -0800343 int index_wake_up_event = -1;
344 if (mHasSensorAccess) {
345 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
346 if (index_wake_up_event >= 0) {
347 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
348 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800349#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800350 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800351#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800352 }
Peng Xueb4d6282015-12-10 18:02:41 -0800353 }
354
355 // NOTE: ASensorEvent and sensors_event_t are the same type.
356 ssize_t size = SensorEventQueue::write(mChannel,
357 reinterpret_cast<ASensorEvent const*>(scratch), count);
358 if (size < 0) {
359 // Write error, copy events to local cache.
360 if (index_wake_up_event >= 0) {
361 // If there was a wake_up sensor_event, reset the flag.
362 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
363 if (mWakeLockRefCount > 0) {
364 --mWakeLockRefCount;
365 }
366#if DEBUG_CONNECTIONS
367 --mTotalAcksNeeded;
368#endif
369 }
370 if (mEventCache == NULL) {
371 mMaxCacheSize = computeMaxCacheSizeLocked();
372 mEventCache = new sensors_event_t[mMaxCacheSize];
373 mCacheSize = 0;
374 }
375 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
376 mCacheSize += count;
377
378 // Add this file descriptor to the looper to get a callback when this fd is available for
379 // writing.
380 updateLooperRegistrationLocked(mService->getLooper());
Svet Ganove752a5c2018-01-15 17:14:20 -0800381 delete sanitizedBuffer;
Peng Xueb4d6282015-12-10 18:02:41 -0800382 return size;
383 }
384
385#if DEBUG_CONNECTIONS
386 if (size > 0) {
387 mEventsSent += count;
388 }
389#endif
390
Svet Ganove752a5c2018-01-15 17:14:20 -0800391 delete sanitizedBuffer;
Peng Xueb4d6282015-12-10 18:02:41 -0800392 return size < 0 ? status_t(size) : status_t(NO_ERROR);
393}
394
Svet Ganove752a5c2018-01-15 17:14:20 -0800395void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
396 Mutex::Autolock _l(mConnectionLock);
397 mHasSensorAccess = hasAccess;
398}
399
Peng Xueb4d6282015-12-10 18:02:41 -0800400void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
401 int count) {
402 sensors_event_t *eventCache_new;
403 const int new_cache_size = computeMaxCacheSizeLocked();
404 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
405 eventCache_new = new sensors_event_t[new_cache_size];
406 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
407 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
408
409 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
410 new_cache_size);
411
412 delete mEventCache;
413 mEventCache = eventCache_new;
414 mCacheSize += count;
415 mMaxCacheSize = new_cache_size;
416}
417
418void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
419 ASensorEvent flushCompleteEvent;
420 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
421 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
422 // Loop through all the sensors for this connection and check if there are any pending
423 // flush complete events to be sent.
424 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700425 const int handle = mSensorInfo.keyAt(i);
426 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
427 if (si == nullptr) {
428 continue;
429 }
430
Peng Xueb4d6282015-12-10 18:02:41 -0800431 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
432 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700433 flushCompleteEvent.meta_data.sensor = handle;
434 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800435 if (wakeUpSensor) {
436 ++mWakeLockRefCount;
437 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
438 }
439 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
440 if (size < 0) {
441 if (wakeUpSensor) --mWakeLockRefCount;
442 return;
443 }
444 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
445 flushCompleteEvent.meta_data.sensor);
446 flushInfo.mPendingFlushEventsToSend--;
447 }
448 }
449}
450
451void SensorService::SensorEventConnection::writeToSocketFromCache() {
452 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
453 // half the size of the socket buffer allocated in BitTube whichever is smaller.
454 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
455 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
456 Mutex::Autolock _l(mConnectionLock);
457 // Send pending flush complete events (if any)
458 sendPendingFlushEventsLocked();
459 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
460 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800461 int index_wake_up_event = -1;
462 if (mHasSensorAccess) {
463 index_wake_up_event =
464 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
465 if (index_wake_up_event >= 0) {
466 mEventCache[index_wake_up_event + numEventsSent].flags |=
467 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
468 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800469#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800470 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800471#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800472 }
Peng Xueb4d6282015-12-10 18:02:41 -0800473 }
474
475 ssize_t size = SensorEventQueue::write(mChannel,
476 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
477 numEventsToWrite);
478 if (size < 0) {
479 if (index_wake_up_event >= 0) {
480 // If there was a wake_up sensor_event, reset the flag.
481 mEventCache[index_wake_up_event + numEventsSent].flags &=
482 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
483 if (mWakeLockRefCount > 0) {
484 --mWakeLockRefCount;
485 }
486#if DEBUG_CONNECTIONS
487 --mTotalAcksNeeded;
488#endif
489 }
490 memmove(mEventCache, &mEventCache[numEventsSent],
491 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
492 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
493 numEventsSent, mCacheSize);
494 mCacheSize -= numEventsSent;
495 return;
496 }
497 numEventsSent += numEventsToWrite;
498#if DEBUG_CONNECTIONS
499 mEventsSentFromCache += numEventsToWrite;
500#endif
501 }
502 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
503 // All events from the cache have been sent. Reset cache size to zero.
504 mCacheSize = 0;
505 // There are no more events in the cache. We don't need to poll for write on the fd.
506 // Update Looper registration.
507 updateLooperRegistrationLocked(mService->getLooper());
508}
509
510void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
511 sensors_event_t const* scratch, const int numEventsDropped) {
512 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
513 // Count flushComplete events in the events that are about to the dropped. These will be sent
514 // separately before the next batch of events.
515 for (int j = 0; j < numEventsDropped; ++j) {
516 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700517 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
518 if (index < 0) {
519 ALOGW("%s: sensor 0x%x is not found in connection",
520 __func__, scratch[j].meta_data.sensor);
521 continue;
522 }
523
524 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800525 flushInfo.mPendingFlushEventsToSend++;
526 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
527 flushInfo.mPendingFlushEventsToSend);
528 }
529 }
530 return;
531}
532
533int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
534 sensors_event_t const* scratch, const int count) {
535 for (int i = 0; i < count; ++i) {
536 if (mService->isWakeUpSensorEvent(scratch[i])) {
537 return i;
538 }
539 }
540 return -1;
541}
542
543sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
544{
545 return mChannel;
546}
547
548status_t SensorService::SensorEventConnection::enableDisable(
549 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
550 int reservedFlags)
551{
Arthur Ishiguro3b27b3b2020-09-22 13:05:15 -0700552 if (mDestroyed) {
553 android_errorWriteLog(0x534e4554, "168211968");
554 return DEAD_OBJECT;
555 }
556
Peng Xueb4d6282015-12-10 18:02:41 -0800557 status_t err;
558 if (enabled) {
559 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
560 reservedFlags, mOpPackageName);
561
562 } else {
563 err = mService->disable(this, handle);
564 }
565 return err;
566}
567
568status_t SensorService::SensorEventConnection::setEventRate(
569 int handle, nsecs_t samplingPeriodNs)
570{
Arthur Ishiguro3b27b3b2020-09-22 13:05:15 -0700571 if (mDestroyed) {
572 android_errorWriteLog(0x534e4554, "168211968");
573 return DEAD_OBJECT;
574 }
575
Peng Xueb4d6282015-12-10 18:02:41 -0800576 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
577}
578
579status_t SensorService::SensorEventConnection::flush() {
Arthur Ishiguro3b27b3b2020-09-22 13:05:15 -0700580 if (mDestroyed) {
581 return DEAD_OBJECT;
582 }
583
Peng Xueb4d6282015-12-10 18:02:41 -0800584 return mService->flushSensor(this, mOpPackageName);
585}
586
Peng Xue36e3472016-11-03 11:57:10 -0700587int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
588 // SensorEventConnection does not support configureChannel, parameters not used
589 UNUSED(handle);
590 UNUSED(rateLevel);
591 return INVALID_OPERATION;
592}
593
Peng Xueb4d6282015-12-10 18:02:41 -0800594int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
595 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
596 {
597 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
598 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
599 // can release the wake-lock.
600 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
601 Mutex::Autolock _l(mConnectionLock);
602 mDead = true;
603 mWakeLockRefCount = 0;
604 updateLooperRegistrationLocked(mService->getLooper());
605 }
606 mService->checkWakeLockState();
607 if (mDataInjectionMode) {
608 // If the Looper has encountered some error in data injection mode, reset SensorService
609 // back to normal mode.
610 mService->resetToNormalMode();
611 mDataInjectionMode = false;
612 }
613 return 1;
614 }
615
616 if (events & ALOOPER_EVENT_INPUT) {
617 unsigned char buf[sizeof(sensors_event_t)];
618 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
619 {
Peng Xu755c4512016-04-07 23:15:14 -0700620 Mutex::Autolock _l(mConnectionLock);
621 if (numBytesRead == sizeof(sensors_event_t)) {
622 if (!mDataInjectionMode) {
623 ALOGE("Data injected in normal mode, dropping event"
624 "package=%s uid=%d", mPackageName.string(), mUid);
625 // Unregister call backs.
626 return 0;
627 }
628 sensors_event_t sensor_event;
629 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
630 sp<SensorInterface> si =
631 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
632 if (si == nullptr) {
633 return 1;
634 }
635
636 SensorDevice& dev(SensorDevice::getInstance());
637 sensor_event.type = si->getSensor().getType();
638 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800639#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700640 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800641#endif
Peng Xu755c4512016-04-07 23:15:14 -0700642 } else if (numBytesRead == sizeof(uint32_t)) {
643 uint32_t numAcks = 0;
644 memcpy(&numAcks, buf, numBytesRead);
645 // Sanity check to ensure there are no read errors in recv, numAcks is always
646 // within the range and not zero. If any of the above don't hold reset
647 // mWakeLockRefCount to zero.
648 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
649 mWakeLockRefCount -= numAcks;
650 } else {
651 mWakeLockRefCount = 0;
652 }
Peng Xueb4d6282015-12-10 18:02:41 -0800653#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700654 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800655#endif
656 } else {
657 // Read error, reset wakelock refcount.
658 mWakeLockRefCount = 0;
659 }
660 }
661 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
662 // here as checkWakeLockState() will need it.
663 if (mWakeLockRefCount == 0) {
664 mService->checkWakeLockState();
665 }
666 // continue getting callbacks.
667 return 1;
668 }
669
670 if (events & ALOOPER_EVENT_OUTPUT) {
671 // send sensor data that is stored in mEventCache for this connection.
672 mService->sendEventsFromCache(this);
673 }
674 return 1;
675}
676
677int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
678 size_t fifoWakeUpSensors = 0;
679 size_t fifoNonWakeUpSensors = 0;
680 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700681 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
682 if (si == nullptr) {
683 continue;
684 }
685 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800686 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
687 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
688 // non wake_up sensors.
689 if (sensor.isWakeUpSensor()) {
690 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
691 } else {
692 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
693 }
694 } else {
695 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
696 if (sensor.isWakeUpSensor()) {
697 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
698 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
699
700 } else {
701 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
702 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
703
704 }
705 }
706 }
707 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
708 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
709 // size that is equal to that of the batch mode.
710 // ALOGW("Write failure in non-batch mode");
711 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
712 }
713 return fifoWakeUpSensors + fifoNonWakeUpSensors;
714}
715
716} // namespace android
717