blob: 0e409409f2ed79ca714d7873b7eb56448b59f520 [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 {
Brian Stackc225aa12019-04-19 09:30:25 -0700288 // Regular sensor event, just copy it to the scratch buffer after checking
289 // the AppOp.
290 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800291 scratch[count++] = buffer[i];
292 }
Peng Xueb4d6282015-12-10 18:02:41 -0800293 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800294 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800295 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
296 buffer[i].type != SENSOR_TYPE_META_DATA) ||
297 (buffer[i].type == SENSOR_TYPE_META_DATA &&
298 buffer[i].meta_data.sensor == sensor_handle)));
299 }
300 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800301 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800302 scratch = const_cast<sensors_event_t *>(buffer);
303 count = numEvents;
304 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800305 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
306 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800307 for (size_t i = 0; i < numEvents; i++) {
308 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
309 scratch[count++] = buffer[i++];
310 }
311 }
312 }
Peng Xueb4d6282015-12-10 18:02:41 -0800313 }
314
315 sendPendingFlushEventsLocked();
316 // Early return if there are no events for this connection.
317 if (count == 0) {
318 return status_t(NO_ERROR);
319 }
320
321#if DEBUG_CONNECTIONS
322 mEventsReceived += count;
323#endif
324 if (mCacheSize != 0) {
325 // There are some events in the cache which need to be sent first. Copy this buffer to
326 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800327 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800328 return status_t(NO_ERROR);
329 }
330
Svet Ganove752a5c2018-01-15 17:14:20 -0800331 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800332 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800333 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
334 if (index_wake_up_event >= 0) {
335 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
336 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800337#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800338 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800339#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800340 }
Peng Xueb4d6282015-12-10 18:02:41 -0800341 }
342
343 // NOTE: ASensorEvent and sensors_event_t are the same type.
344 ssize_t size = SensorEventQueue::write(mChannel,
345 reinterpret_cast<ASensorEvent const*>(scratch), count);
346 if (size < 0) {
347 // Write error, copy events to local cache.
348 if (index_wake_up_event >= 0) {
349 // If there was a wake_up sensor_event, reset the flag.
350 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
351 if (mWakeLockRefCount > 0) {
352 --mWakeLockRefCount;
353 }
354#if DEBUG_CONNECTIONS
355 --mTotalAcksNeeded;
356#endif
357 }
Yi Kong8f313e32018-07-17 14:13:29 -0700358 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800359 mMaxCacheSize = computeMaxCacheSizeLocked();
360 mEventCache = new sensors_event_t[mMaxCacheSize];
361 mCacheSize = 0;
362 }
Brian Stack93432ad2018-11-27 18:28:48 -0800363 // Save the events so that they can be written later
364 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800365
366 // Add this file descriptor to the looper to get a callback when this fd is available for
367 // writing.
368 updateLooperRegistrationLocked(mService->getLooper());
369 return size;
370 }
371
372#if DEBUG_CONNECTIONS
373 if (size > 0) {
374 mEventsSent += count;
375 }
376#endif
377
378 return size < 0 ? status_t(size) : status_t(NO_ERROR);
379}
380
Svet Ganove752a5c2018-01-15 17:14:20 -0800381void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
382 Mutex::Autolock _l(mConnectionLock);
383 mHasSensorAccess = hasAccess;
384}
385
Michael Groover5e1f60b2018-12-04 22:34:29 -0800386bool SensorService::SensorEventConnection::hasSensorAccess() {
387 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
388}
389
Brian Stackc225aa12019-04-19 09:30:25 -0700390bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
391 bool success = true;
392 const auto iter = mHandleToAppOp.find(event.sensor);
393 if (iter != mHandleToAppOp.end()) {
394 int32_t appOpMode = mService->sAppOpsManager.noteOp((*iter).second, mUid, mOpPackageName);
395 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
396 }
397 return success;
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
George Burgess IV1866ed42018-01-21 12:14:09 -0800412 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800413 mEventCache = eventCache_new;
414 mCacheSize += count;
415 mMaxCacheSize = new_cache_size;
416}
417
Brian Stack93432ad2018-11-27 18:28:48 -0800418void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
419 int count) {
420 if (count <= 0) {
421 return;
422 } else if (mCacheSize + count <= mMaxCacheSize) {
423 // The events fit within the current cache: add them
424 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
425 mCacheSize += count;
426 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
427 // The events fit within a resized cache: resize the cache and add the events
428 reAllocateCacheLocked(events, count);
429 } else {
430 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800431 int freeSpace = mMaxCacheSize - mCacheSize;
432
433 // Drop up to the currently cached number of events to make room for new events
434 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
435
436 // New events need to be dropped if there are more new events than the size of the cache
437 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
438
439 // Determine the number of new events to copy into the cache
440 int eventsToCopy = std::min(mMaxCacheSize, count);
441
Brian Stackae4053f2018-12-10 14:54:18 -0800442 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
443 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
444 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
445 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
446 count, mEventsDropped);
447 mEventsDropped = 0;
448 mTimeOfLastEventDrop = events[0].timestamp;
449 } else {
450 // Record the number dropped
451 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
452 }
453
Brian Stack93432ad2018-11-27 18:28:48 -0800454 // Check for any flush complete events in the events that will be dropped
455 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
456 countFlushCompleteEventsLocked(events, newEventsToDrop);
457
458 // Only shift the events if they will not all be overwritten
459 if (eventsToCopy != mMaxCacheSize) {
460 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
461 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
462 }
463 mCacheSize -= cachedEventsToDrop;
464
465 // Copy the events into the cache
466 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
467 eventsToCopy * sizeof(sensors_event_t));
468 mCacheSize += eventsToCopy;
469 }
470}
471
Peng Xueb4d6282015-12-10 18:02:41 -0800472void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
473 ASensorEvent flushCompleteEvent;
474 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
475 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
476 // Loop through all the sensors for this connection and check if there are any pending
477 // flush complete events to be sent.
478 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700479 const int handle = mSensorInfo.keyAt(i);
480 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
481 if (si == nullptr) {
482 continue;
483 }
484
Peng Xueb4d6282015-12-10 18:02:41 -0800485 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
486 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700487 flushCompleteEvent.meta_data.sensor = handle;
488 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800489 if (wakeUpSensor) {
490 ++mWakeLockRefCount;
491 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
492 }
493 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
494 if (size < 0) {
495 if (wakeUpSensor) --mWakeLockRefCount;
496 return;
497 }
498 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
499 flushCompleteEvent.meta_data.sensor);
500 flushInfo.mPendingFlushEventsToSend--;
501 }
502 }
503}
504
505void SensorService::SensorEventConnection::writeToSocketFromCache() {
506 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
507 // half the size of the socket buffer allocated in BitTube whichever is smaller.
508 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
509 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
510 Mutex::Autolock _l(mConnectionLock);
511 // Send pending flush complete events (if any)
512 sendPendingFlushEventsLocked();
513 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
514 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800515 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800516 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800517 index_wake_up_event =
518 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
519 if (index_wake_up_event >= 0) {
520 mEventCache[index_wake_up_event + numEventsSent].flags |=
521 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
522 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800523#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800524 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800525#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800526 }
Peng Xueb4d6282015-12-10 18:02:41 -0800527 }
528
529 ssize_t size = SensorEventQueue::write(mChannel,
530 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
531 numEventsToWrite);
532 if (size < 0) {
533 if (index_wake_up_event >= 0) {
534 // If there was a wake_up sensor_event, reset the flag.
535 mEventCache[index_wake_up_event + numEventsSent].flags &=
536 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
537 if (mWakeLockRefCount > 0) {
538 --mWakeLockRefCount;
539 }
540#if DEBUG_CONNECTIONS
541 --mTotalAcksNeeded;
542#endif
543 }
544 memmove(mEventCache, &mEventCache[numEventsSent],
545 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
546 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
547 numEventsSent, mCacheSize);
548 mCacheSize -= numEventsSent;
549 return;
550 }
551 numEventsSent += numEventsToWrite;
552#if DEBUG_CONNECTIONS
553 mEventsSentFromCache += numEventsToWrite;
554#endif
555 }
556 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
557 // All events from the cache have been sent. Reset cache size to zero.
558 mCacheSize = 0;
559 // There are no more events in the cache. We don't need to poll for write on the fd.
560 // Update Looper registration.
561 updateLooperRegistrationLocked(mService->getLooper());
562}
563
564void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
565 sensors_event_t const* scratch, const int numEventsDropped) {
566 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
567 // Count flushComplete events in the events that are about to the dropped. These will be sent
568 // separately before the next batch of events.
569 for (int j = 0; j < numEventsDropped; ++j) {
570 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700571 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
572 if (index < 0) {
573 ALOGW("%s: sensor 0x%x is not found in connection",
574 __func__, scratch[j].meta_data.sensor);
575 continue;
576 }
577
578 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800579 flushInfo.mPendingFlushEventsToSend++;
580 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
581 flushInfo.mPendingFlushEventsToSend);
582 }
583 }
584 return;
585}
586
587int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
588 sensors_event_t const* scratch, const int count) {
589 for (int i = 0; i < count; ++i) {
590 if (mService->isWakeUpSensorEvent(scratch[i])) {
591 return i;
592 }
593 }
594 return -1;
595}
596
597sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
598{
599 return mChannel;
600}
601
602status_t SensorService::SensorEventConnection::enableDisable(
603 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
604 int reservedFlags)
605{
606 status_t err;
607 if (enabled) {
608 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
609 reservedFlags, mOpPackageName);
610
611 } else {
612 err = mService->disable(this, handle);
613 }
614 return err;
615}
616
617status_t SensorService::SensorEventConnection::setEventRate(
618 int handle, nsecs_t samplingPeriodNs)
619{
620 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
621}
622
623status_t SensorService::SensorEventConnection::flush() {
624 return mService->flushSensor(this, mOpPackageName);
625}
626
Peng Xue36e3472016-11-03 11:57:10 -0700627int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
628 // SensorEventConnection does not support configureChannel, parameters not used
629 UNUSED(handle);
630 UNUSED(rateLevel);
631 return INVALID_OPERATION;
632}
633
Peng Xueb4d6282015-12-10 18:02:41 -0800634int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
635 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
636 {
637 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
638 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
639 // can release the wake-lock.
640 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
641 Mutex::Autolock _l(mConnectionLock);
642 mDead = true;
643 mWakeLockRefCount = 0;
644 updateLooperRegistrationLocked(mService->getLooper());
645 }
646 mService->checkWakeLockState();
647 if (mDataInjectionMode) {
648 // If the Looper has encountered some error in data injection mode, reset SensorService
649 // back to normal mode.
650 mService->resetToNormalMode();
651 mDataInjectionMode = false;
652 }
653 return 1;
654 }
655
656 if (events & ALOOPER_EVENT_INPUT) {
657 unsigned char buf[sizeof(sensors_event_t)];
658 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
659 {
Peng Xu755c4512016-04-07 23:15:14 -0700660 Mutex::Autolock _l(mConnectionLock);
661 if (numBytesRead == sizeof(sensors_event_t)) {
662 if (!mDataInjectionMode) {
663 ALOGE("Data injected in normal mode, dropping event"
664 "package=%s uid=%d", mPackageName.string(), mUid);
665 // Unregister call backs.
666 return 0;
667 }
668 sensors_event_t sensor_event;
669 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
670 sp<SensorInterface> si =
671 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
672 if (si == nullptr) {
673 return 1;
674 }
675
676 SensorDevice& dev(SensorDevice::getInstance());
677 sensor_event.type = si->getSensor().getType();
678 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800679#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700680 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800681#endif
Peng Xu755c4512016-04-07 23:15:14 -0700682 } else if (numBytesRead == sizeof(uint32_t)) {
683 uint32_t numAcks = 0;
684 memcpy(&numAcks, buf, numBytesRead);
685 // Sanity check to ensure there are no read errors in recv, numAcks is always
686 // within the range and not zero. If any of the above don't hold reset
687 // mWakeLockRefCount to zero.
688 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
689 mWakeLockRefCount -= numAcks;
690 } else {
691 mWakeLockRefCount = 0;
692 }
Peng Xueb4d6282015-12-10 18:02:41 -0800693#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700694 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800695#endif
696 } else {
697 // Read error, reset wakelock refcount.
698 mWakeLockRefCount = 0;
699 }
700 }
701 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
702 // here as checkWakeLockState() will need it.
703 if (mWakeLockRefCount == 0) {
704 mService->checkWakeLockState();
705 }
706 // continue getting callbacks.
707 return 1;
708 }
709
710 if (events & ALOOPER_EVENT_OUTPUT) {
711 // send sensor data that is stored in mEventCache for this connection.
712 mService->sendEventsFromCache(this);
713 }
714 return 1;
715}
716
717int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
718 size_t fifoWakeUpSensors = 0;
719 size_t fifoNonWakeUpSensors = 0;
720 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700721 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
722 if (si == nullptr) {
723 continue;
724 }
725 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800726 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
727 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
728 // non wake_up sensors.
729 if (sensor.isWakeUpSensor()) {
730 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
731 } else {
732 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
733 }
734 } else {
735 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
736 if (sensor.isWakeUpSensor()) {
737 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
738 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
739
740 } else {
741 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
742 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
743
744 }
745 }
746 }
747 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
748 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
749 // size that is equal to that of the batch mode.
750 // ALOGW("Write failure in non-batch mode");
751 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
752 }
753 return fifoWakeUpSensors + fifoNonWakeUpSensors;
754}
755
756} // namespace android
757