blob: 9a13c006647dab313d62168893ca7ba5b8e725a3 [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
Mike Ma24743862020-01-29 00:36:55 -080020#include <android/util/ProtoOutputStream.h>
21#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080022#include <sensor/SensorEventQueue.h>
Peng Xueb4d6282015-12-10 18:02:41 -080023
24#include "vec.h"
25#include "SensorEventConnection.h"
Peng Xu755c4512016-04-07 23:15:14 -070026#include "SensorDevice.h"
Peng Xueb4d6282015-12-10 18:02:41 -080027
Peng Xue36e3472016-11-03 11:57:10 -070028#define UNUSED(x) (void)(x)
29
Peng Xueb4d6282015-12-10 18:02:41 -080030namespace android {
31
32SensorService::SensorEventConnection::SensorEventConnection(
33 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
Svet Ganove752a5c2018-01-15 17:14:20 -080034 const String16& opPackageName, bool hasSensorAccess)
Peng Xueb4d6282015-12-10 18:02:41 -080035 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Yi Kong8f313e32018-07-17 14:13:29 -070036 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
Brian Stackae4053f2018-12-10 14:54:18 -080037 mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
38 mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false),
39 mHasSensorAccess(hasSensorAccess) {
Peng Xueb4d6282015-12-10 18:02:41 -080040 mChannel = new BitTube(mService->mSocketBufferSize);
41#if DEBUG_CONNECTIONS
42 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
43 mTotalAcksNeeded = mTotalAcksReceived = 0;
44#endif
45}
46
47SensorService::SensorEventConnection::~SensorEventConnection() {
48 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Peng Xu8cbefd72017-07-10 16:41:08 -070049 destroy();
50}
51
52void SensorService::SensorEventConnection::destroy() {
53 Mutex::Autolock _l(mDestroyLock);
54
55 // destroy once only
56 if (mDestroyed) {
57 return;
58 }
59
Peng Xueb4d6282015-12-10 18:02:41 -080060 mService->cleanupConnection(this);
Yi Kong8f313e32018-07-17 14:13:29 -070061 if (mEventCache != nullptr) {
George Burgess IV1866ed42018-01-21 12:14:09 -080062 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -080063 }
Peng Xu8cbefd72017-07-10 16:41:08 -070064 mDestroyed = true;
Peng Xueb4d6282015-12-10 18:02:41 -080065}
66
67void SensorService::SensorEventConnection::onFirstRef() {
68 LooperCallback::onFirstRef();
69}
70
71bool SensorService::SensorEventConnection::needsWakeLock() {
72 Mutex::Autolock _l(mConnectionLock);
73 return !mDead && mWakeLockRefCount > 0;
74}
75
76void SensorService::SensorEventConnection::resetWakeLockRefCount() {
77 Mutex::Autolock _l(mConnectionLock);
78 mWakeLockRefCount = 0;
79}
80
81void SensorService::SensorEventConnection::dump(String8& result) {
82 Mutex::Autolock _l(mConnectionLock);
Brian Stackbce04d72019-03-21 10:54:10 -070083 result.appendFormat("\tOperating Mode: ");
84 if (!mService->isWhiteListedPackage(getPackageName())) {
85 result.append("RESTRICTED\n");
86 } else if (mDataInjectionMode) {
87 result.append("DATA_INJECTION\n");
88 } else {
89 result.append("NORMAL\n");
90 }
Peng Xueb4d6282015-12-10 18:02:41 -080091 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
92 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
93 mMaxCacheSize);
94 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
95 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
96 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
97 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
98 mSensorInfo.keyAt(i),
99 flushInfo.mFirstFlushPending ? "First flush pending" :
100 "active",
101 flushInfo.mPendingFlushEventsToSend);
102 }
103#if DEBUG_CONNECTIONS
104 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
105 " total_acks_needed %d | total_acks_recvd %d\n",
106 mEventsReceived,
107 mEventsSent,
108 mEventsSentFromCache,
109 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
110 mTotalAcksNeeded,
111 mTotalAcksReceived);
112#endif
113}
114
Mike Ma24743862020-01-29 00:36:55 -0800115/**
116 * Dump debugging information as android.service.SensorEventConnectionProto protobuf message using
117 * ProtoOutputStream.
118 *
119 * See proto definition and some notes about ProtoOutputStream in
120 * frameworks/base/core/proto/android/service/sensor_service.proto
121 */
122void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
123 using namespace service::SensorEventConnectionProto;
124 Mutex::Autolock _l(mConnectionLock);
125
126 if (!mService->isWhiteListedPackage(getPackageName())) {
127 proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
128 } else if (mDataInjectionMode) {
129 proto->write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
130 } else {
131 proto->write(OPERATING_MODE, OP_MODE_NORMAL);
132 }
133 proto->write(PACKAGE_NAME, std::string(mPackageName.string()));
134 proto->write(WAKE_LOCK_REF_COUNT, int32_t(mWakeLockRefCount));
135 proto->write(UID, int32_t(mUid));
136 proto->write(CACHE_SIZE, int32_t(mCacheSize));
137 proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
138 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
139 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
140 const uint64_t token = proto->start(FLUSH_INFOS);
141 proto->write(FlushInfoProto::SENSOR_NAME,
142 std::string(mService->getSensorName(mSensorInfo.keyAt(i))));
143 proto->write(FlushInfoProto::SENSOR_HANDLE, mSensorInfo.keyAt(i));
144 proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
145 proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
146 flushInfo.mPendingFlushEventsToSend);
147 proto->end(token);
148 }
149#if DEBUG_CONNECTIONS
150 proto->write(EVENTS_RECEIVED, mEventsReceived);
151 proto->write(EVENTS_SENT, mEventsSent);
152 proto->write(EVENTS_CACHE, mEventsSentFromCache);
153 proto->write(EVENTS_DROPPED, mEventsReceived - (mEventsSentFromCache + mEventsSent +
154 mCacheSize));
155 proto->write(TOTAL_ACKS_NEEDED, mTotalAcksNeeded);
156 proto->write(TOTAL_ACKS_RECEIVED, mTotalAcksReceived);
157#endif
158}
159
Peng Xueb4d6282015-12-10 18:02:41 -0800160bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
161 Mutex::Autolock _l(mConnectionLock);
Peng Xu755c4512016-04-07 23:15:14 -0700162 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
163 if (si == nullptr ||
164 !canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
165 mSensorInfo.indexOfKey(handle) >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800166 return false;
167 }
Peng Xu755c4512016-04-07 23:15:14 -0700168 mSensorInfo.add(handle, FlushInfo());
169 return true;
Peng Xueb4d6282015-12-10 18:02:41 -0800170}
171
172bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
173 Mutex::Autolock _l(mConnectionLock);
174 if (mSensorInfo.removeItem(handle) >= 0) {
175 return true;
176 }
177 return false;
178}
179
180bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
181 Mutex::Autolock _l(mConnectionLock);
182 return mSensorInfo.indexOfKey(handle) >= 0;
183}
184
185bool SensorService::SensorEventConnection::hasAnySensor() const {
186 Mutex::Autolock _l(mConnectionLock);
187 return mSensorInfo.size() ? true : false;
188}
189
190bool SensorService::SensorEventConnection::hasOneShotSensors() const {
191 Mutex::Autolock _l(mConnectionLock);
192 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
193 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700194 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
195 if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
Peng Xueb4d6282015-12-10 18:02:41 -0800196 return true;
197 }
198 }
199 return false;
200}
201
202String8 SensorService::SensorEventConnection::getPackageName() const {
203 return mPackageName;
204}
205
206void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
207 bool value) {
208 Mutex::Autolock _l(mConnectionLock);
209 ssize_t index = mSensorInfo.indexOfKey(handle);
210 if (index >= 0) {
211 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
212 flushInfo.mFirstFlushPending = value;
213 }
214}
215
216void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
217 Mutex::Autolock _l(mConnectionLock);
218 updateLooperRegistrationLocked(looper);
219}
220
221void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
222 const sp<Looper>& looper) {
223 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
224 mDataInjectionMode;
225 // If all sensors are unregistered OR Looper has encountered an error, we can remove the Fd from
226 // the Looper if it has been previously added.
227 if (!isConnectionActive || mDead) { if (mHasLooperCallbacks) {
228 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this,
229 mChannel->getSendFd());
230 looper->removeFd(mChannel->getSendFd()); mHasLooperCallbacks = false; }
231 return; }
232
233 int looper_flags = 0;
234 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
235 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
236 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
237 const int handle = mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -0700238 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
239 if (si != nullptr && si->getSensor().isWakeUpSensor()) {
Peng Xueb4d6282015-12-10 18:02:41 -0800240 looper_flags |= ALOOPER_EVENT_INPUT;
Peng Xueb4d6282015-12-10 18:02:41 -0800241 }
242 }
243
244 // If flags is still set to zero, we don't need to add this fd to the Looper, if the fd has
245 // already been added, remove it. This is likely to happen when ALL the events stored in the
246 // cache have been sent to the corresponding app.
247 if (looper_flags == 0) {
248 if (mHasLooperCallbacks) {
249 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
250 looper->removeFd(mChannel->getSendFd());
251 mHasLooperCallbacks = false;
252 }
253 return;
254 }
255
256 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
257 // registered for wake-up sensors OR for sending events in the cache.
Yi Kong8f313e32018-07-17 14:13:29 -0700258 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -0800259 if (ret == 1) {
260 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
261 mHasLooperCallbacks = true;
262 } else {
263 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
264 }
265}
266
267void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
268 Mutex::Autolock _l(mConnectionLock);
269 ssize_t index = mSensorInfo.indexOfKey(handle);
270 if (index >= 0) {
271 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
272 flushInfo.mPendingFlushEventsToSend++;
273 }
274}
275
276status_t SensorService::SensorEventConnection::sendEvents(
277 sensors_event_t const* buffer, size_t numEvents,
278 sensors_event_t* scratch,
Peng Xuded526e2016-08-12 16:39:44 -0700279 wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
Peng Xueb4d6282015-12-10 18:02:41 -0800280 // filter out events not for this connection
Svet Ganove752a5c2018-01-15 17:14:20 -0800281
George Burgess IV1866ed42018-01-21 12:14:09 -0800282 std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
Svet Ganove752a5c2018-01-15 17:14:20 -0800283
Peng Xueb4d6282015-12-10 18:02:41 -0800284 int count = 0;
285 Mutex::Autolock _l(mConnectionLock);
286 if (scratch) {
287 size_t i=0;
288 while (i<numEvents) {
289 int32_t sensor_handle = buffer[i].sensor;
290 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
291 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
292 buffer[i].meta_data.sensor);
293 // Setting sensor_handle to the correct sensor to ensure the sensor events per
294 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
295 // events.
296 sensor_handle = buffer[i].meta_data.sensor;
297 }
298
299 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
300 // Check if this connection has registered for this sensor. If not continue to the
301 // next sensor_event.
302 if (index < 0) {
303 ++i;
304 continue;
305 }
306
307 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
308 // Check if there is a pending flush_complete event for this sensor on this connection.
309 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
Peng Xuded526e2016-08-12 16:39:44 -0700310 mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800311 flushInfo.mFirstFlushPending = false;
312 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
313 buffer[i].meta_data.sensor);
314 ++i;
315 continue;
316 }
317
318 // If there is a pending flush complete event for this sensor on this connection,
319 // ignore the event and proceed to the next.
320 if (flushInfo.mFirstFlushPending) {
321 ++i;
322 continue;
323 }
324
325 do {
326 // Keep copying events into the scratch buffer as long as they are regular
327 // sensor_events are from the same sensor_handle OR they are flush_complete_events
328 // from the same sensor_handle AND the current connection is mapped to the
329 // corresponding flush_complete_event.
330 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Peng Xuded526e2016-08-12 16:39:44 -0700331 if (mapFlushEventsToConnections[i] == this) {
Peng Xueb4d6282015-12-10 18:02:41 -0800332 scratch[count++] = buffer[i];
333 }
Peng Xueb4d6282015-12-10 18:02:41 -0800334 } else {
Brian Stackc225aa12019-04-19 09:30:25 -0700335 // Regular sensor event, just copy it to the scratch buffer after checking
336 // the AppOp.
337 if (hasSensorAccess() && noteOpIfRequired(buffer[i])) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800338 scratch[count++] = buffer[i];
339 }
Peng Xueb4d6282015-12-10 18:02:41 -0800340 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800341 i++;
Peng Xueb4d6282015-12-10 18:02:41 -0800342 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
343 buffer[i].type != SENSOR_TYPE_META_DATA) ||
344 (buffer[i].type == SENSOR_TYPE_META_DATA &&
345 buffer[i].meta_data.sensor == sensor_handle)));
346 }
347 } else {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800348 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800349 scratch = const_cast<sensors_event_t *>(buffer);
350 count = numEvents;
351 } else {
George Burgess IV1866ed42018-01-21 12:14:09 -0800352 sanitizedBuffer.reset(new sensors_event_t[numEvents]);
353 scratch = sanitizedBuffer.get();
Svet Ganove752a5c2018-01-15 17:14:20 -0800354 for (size_t i = 0; i < numEvents; i++) {
355 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
356 scratch[count++] = buffer[i++];
357 }
358 }
359 }
Peng Xueb4d6282015-12-10 18:02:41 -0800360 }
361
362 sendPendingFlushEventsLocked();
363 // Early return if there are no events for this connection.
364 if (count == 0) {
365 return status_t(NO_ERROR);
366 }
367
368#if DEBUG_CONNECTIONS
369 mEventsReceived += count;
370#endif
371 if (mCacheSize != 0) {
372 // There are some events in the cache which need to be sent first. Copy this buffer to
373 // the end of cache.
Brian Stack93432ad2018-11-27 18:28:48 -0800374 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800375 return status_t(NO_ERROR);
376 }
377
Svet Ganove752a5c2018-01-15 17:14:20 -0800378 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800379 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800380 index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
381 if (index_wake_up_event >= 0) {
382 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
383 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800384#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800385 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800386#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800387 }
Peng Xueb4d6282015-12-10 18:02:41 -0800388 }
389
390 // NOTE: ASensorEvent and sensors_event_t are the same type.
391 ssize_t size = SensorEventQueue::write(mChannel,
392 reinterpret_cast<ASensorEvent const*>(scratch), count);
393 if (size < 0) {
394 // Write error, copy events to local cache.
395 if (index_wake_up_event >= 0) {
396 // If there was a wake_up sensor_event, reset the flag.
397 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
398 if (mWakeLockRefCount > 0) {
399 --mWakeLockRefCount;
400 }
401#if DEBUG_CONNECTIONS
402 --mTotalAcksNeeded;
403#endif
404 }
Yi Kong8f313e32018-07-17 14:13:29 -0700405 if (mEventCache == nullptr) {
Peng Xueb4d6282015-12-10 18:02:41 -0800406 mMaxCacheSize = computeMaxCacheSizeLocked();
407 mEventCache = new sensors_event_t[mMaxCacheSize];
408 mCacheSize = 0;
409 }
Brian Stack93432ad2018-11-27 18:28:48 -0800410 // Save the events so that they can be written later
411 appendEventsToCacheLocked(scratch, count);
Peng Xueb4d6282015-12-10 18:02:41 -0800412
413 // Add this file descriptor to the looper to get a callback when this fd is available for
414 // writing.
415 updateLooperRegistrationLocked(mService->getLooper());
416 return size;
417 }
418
419#if DEBUG_CONNECTIONS
420 if (size > 0) {
421 mEventsSent += count;
422 }
423#endif
424
425 return size < 0 ? status_t(size) : status_t(NO_ERROR);
426}
427
Svet Ganove752a5c2018-01-15 17:14:20 -0800428void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
429 Mutex::Autolock _l(mConnectionLock);
430 mHasSensorAccess = hasAccess;
431}
432
Michael Groover5e1f60b2018-12-04 22:34:29 -0800433bool SensorService::SensorEventConnection::hasSensorAccess() {
434 return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
435}
436
Brian Stackc225aa12019-04-19 09:30:25 -0700437bool SensorService::SensorEventConnection::noteOpIfRequired(const sensors_event_t& event) {
438 bool success = true;
439 const auto iter = mHandleToAppOp.find(event.sensor);
440 if (iter != mHandleToAppOp.end()) {
441 int32_t appOpMode = mService->sAppOpsManager.noteOp((*iter).second, mUid, mOpPackageName);
442 success = (appOpMode == AppOpsManager::MODE_ALLOWED);
443 }
444 return success;
445}
446
Peng Xueb4d6282015-12-10 18:02:41 -0800447void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
448 int count) {
449 sensors_event_t *eventCache_new;
450 const int new_cache_size = computeMaxCacheSizeLocked();
451 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
452 eventCache_new = new sensors_event_t[new_cache_size];
453 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
454 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
455
456 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
457 new_cache_size);
458
George Burgess IV1866ed42018-01-21 12:14:09 -0800459 delete[] mEventCache;
Peng Xueb4d6282015-12-10 18:02:41 -0800460 mEventCache = eventCache_new;
461 mCacheSize += count;
462 mMaxCacheSize = new_cache_size;
463}
464
Brian Stack93432ad2018-11-27 18:28:48 -0800465void SensorService::SensorEventConnection::appendEventsToCacheLocked(sensors_event_t const* events,
466 int count) {
467 if (count <= 0) {
468 return;
469 } else if (mCacheSize + count <= mMaxCacheSize) {
470 // The events fit within the current cache: add them
471 memcpy(&mEventCache[mCacheSize], events, count * sizeof(sensors_event_t));
472 mCacheSize += count;
473 } else if (mCacheSize + count <= computeMaxCacheSizeLocked()) {
474 // The events fit within a resized cache: resize the cache and add the events
475 reAllocateCacheLocked(events, count);
476 } else {
477 // The events do not fit within the cache: drop the oldest events.
Brian Stack93432ad2018-11-27 18:28:48 -0800478 int freeSpace = mMaxCacheSize - mCacheSize;
479
480 // Drop up to the currently cached number of events to make room for new events
481 int cachedEventsToDrop = std::min(mCacheSize, count - freeSpace);
482
483 // New events need to be dropped if there are more new events than the size of the cache
484 int newEventsToDrop = std::max(0, count - mMaxCacheSize);
485
486 // Determine the number of new events to copy into the cache
487 int eventsToCopy = std::min(mMaxCacheSize, count);
488
Brian Stackae4053f2018-12-10 14:54:18 -0800489 constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
490 if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
491 ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
492 " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
493 count, mEventsDropped);
494 mEventsDropped = 0;
495 mTimeOfLastEventDrop = events[0].timestamp;
496 } else {
497 // Record the number dropped
498 mEventsDropped += cachedEventsToDrop + newEventsToDrop;
499 }
500
Brian Stack93432ad2018-11-27 18:28:48 -0800501 // Check for any flush complete events in the events that will be dropped
502 countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
503 countFlushCompleteEventsLocked(events, newEventsToDrop);
504
505 // Only shift the events if they will not all be overwritten
506 if (eventsToCopy != mMaxCacheSize) {
507 memmove(mEventCache, &mEventCache[cachedEventsToDrop],
508 (mCacheSize - cachedEventsToDrop) * sizeof(sensors_event_t));
509 }
510 mCacheSize -= cachedEventsToDrop;
511
512 // Copy the events into the cache
513 memcpy(&mEventCache[mCacheSize], &events[newEventsToDrop],
514 eventsToCopy * sizeof(sensors_event_t));
515 mCacheSize += eventsToCopy;
516 }
517}
518
Peng Xueb4d6282015-12-10 18:02:41 -0800519void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
520 ASensorEvent flushCompleteEvent;
521 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
522 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
523 // Loop through all the sensors for this connection and check if there are any pending
524 // flush complete events to be sent.
525 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700526 const int handle = mSensorInfo.keyAt(i);
527 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
528 if (si == nullptr) {
529 continue;
530 }
531
Peng Xueb4d6282015-12-10 18:02:41 -0800532 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
533 while (flushInfo.mPendingFlushEventsToSend > 0) {
Peng Xu755c4512016-04-07 23:15:14 -0700534 flushCompleteEvent.meta_data.sensor = handle;
535 bool wakeUpSensor = si->getSensor().isWakeUpSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800536 if (wakeUpSensor) {
537 ++mWakeLockRefCount;
538 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
539 }
540 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
541 if (size < 0) {
542 if (wakeUpSensor) --mWakeLockRefCount;
543 return;
544 }
545 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
546 flushCompleteEvent.meta_data.sensor);
547 flushInfo.mPendingFlushEventsToSend--;
548 }
549 }
550}
551
552void SensorService::SensorEventConnection::writeToSocketFromCache() {
553 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
554 // half the size of the socket buffer allocated in BitTube whichever is smaller.
555 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
556 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
557 Mutex::Autolock _l(mConnectionLock);
558 // Send pending flush complete events (if any)
559 sendPendingFlushEventsLocked();
560 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
561 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Svet Ganove752a5c2018-01-15 17:14:20 -0800562 int index_wake_up_event = -1;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800563 if (hasSensorAccess()) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800564 index_wake_up_event =
565 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
566 if (index_wake_up_event >= 0) {
567 mEventCache[index_wake_up_event + numEventsSent].flags |=
568 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
569 ++mWakeLockRefCount;
Peng Xueb4d6282015-12-10 18:02:41 -0800570#if DEBUG_CONNECTIONS
Svet Ganove752a5c2018-01-15 17:14:20 -0800571 ++mTotalAcksNeeded;
Peng Xueb4d6282015-12-10 18:02:41 -0800572#endif
Svet Ganove752a5c2018-01-15 17:14:20 -0800573 }
Peng Xueb4d6282015-12-10 18:02:41 -0800574 }
575
576 ssize_t size = SensorEventQueue::write(mChannel,
577 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
578 numEventsToWrite);
579 if (size < 0) {
580 if (index_wake_up_event >= 0) {
581 // If there was a wake_up sensor_event, reset the flag.
582 mEventCache[index_wake_up_event + numEventsSent].flags &=
583 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
584 if (mWakeLockRefCount > 0) {
585 --mWakeLockRefCount;
586 }
587#if DEBUG_CONNECTIONS
588 --mTotalAcksNeeded;
589#endif
590 }
591 memmove(mEventCache, &mEventCache[numEventsSent],
592 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
593 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
594 numEventsSent, mCacheSize);
595 mCacheSize -= numEventsSent;
596 return;
597 }
598 numEventsSent += numEventsToWrite;
599#if DEBUG_CONNECTIONS
600 mEventsSentFromCache += numEventsToWrite;
601#endif
602 }
603 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
604 // All events from the cache have been sent. Reset cache size to zero.
605 mCacheSize = 0;
606 // There are no more events in the cache. We don't need to poll for write on the fd.
607 // Update Looper registration.
608 updateLooperRegistrationLocked(mService->getLooper());
609}
610
611void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
612 sensors_event_t const* scratch, const int numEventsDropped) {
613 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
614 // Count flushComplete events in the events that are about to the dropped. These will be sent
615 // separately before the next batch of events.
616 for (int j = 0; j < numEventsDropped; ++j) {
617 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
Peng Xu63fbab82017-06-20 12:41:33 -0700618 ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
619 if (index < 0) {
620 ALOGW("%s: sensor 0x%x is not found in connection",
621 __func__, scratch[j].meta_data.sensor);
622 continue;
623 }
624
625 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Peng Xueb4d6282015-12-10 18:02:41 -0800626 flushInfo.mPendingFlushEventsToSend++;
627 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
628 flushInfo.mPendingFlushEventsToSend);
629 }
630 }
631 return;
632}
633
634int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
635 sensors_event_t const* scratch, const int count) {
636 for (int i = 0; i < count; ++i) {
637 if (mService->isWakeUpSensorEvent(scratch[i])) {
638 return i;
639 }
640 }
641 return -1;
642}
643
644sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
645{
646 return mChannel;
647}
648
649status_t SensorService::SensorEventConnection::enableDisable(
650 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
651 int reservedFlags)
652{
653 status_t err;
654 if (enabled) {
655 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
656 reservedFlags, mOpPackageName);
657
658 } else {
659 err = mService->disable(this, handle);
660 }
661 return err;
662}
663
664status_t SensorService::SensorEventConnection::setEventRate(
665 int handle, nsecs_t samplingPeriodNs)
666{
667 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
668}
669
670status_t SensorService::SensorEventConnection::flush() {
671 return mService->flushSensor(this, mOpPackageName);
672}
673
Peng Xue36e3472016-11-03 11:57:10 -0700674int32_t SensorService::SensorEventConnection::configureChannel(int handle, int rateLevel) {
675 // SensorEventConnection does not support configureChannel, parameters not used
676 UNUSED(handle);
677 UNUSED(rateLevel);
678 return INVALID_OPERATION;
679}
680
Peng Xueb4d6282015-12-10 18:02:41 -0800681int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
682 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
683 {
684 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
685 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
686 // can release the wake-lock.
687 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
688 Mutex::Autolock _l(mConnectionLock);
689 mDead = true;
690 mWakeLockRefCount = 0;
691 updateLooperRegistrationLocked(mService->getLooper());
692 }
693 mService->checkWakeLockState();
694 if (mDataInjectionMode) {
695 // If the Looper has encountered some error in data injection mode, reset SensorService
696 // back to normal mode.
697 mService->resetToNormalMode();
698 mDataInjectionMode = false;
699 }
700 return 1;
701 }
702
703 if (events & ALOOPER_EVENT_INPUT) {
704 unsigned char buf[sizeof(sensors_event_t)];
705 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
706 {
Peng Xu755c4512016-04-07 23:15:14 -0700707 Mutex::Autolock _l(mConnectionLock);
708 if (numBytesRead == sizeof(sensors_event_t)) {
709 if (!mDataInjectionMode) {
710 ALOGE("Data injected in normal mode, dropping event"
711 "package=%s uid=%d", mPackageName.string(), mUid);
712 // Unregister call backs.
713 return 0;
714 }
715 sensors_event_t sensor_event;
716 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
717 sp<SensorInterface> si =
718 mService->getSensorInterfaceFromHandle(sensor_event.sensor);
719 if (si == nullptr) {
720 return 1;
721 }
722
723 SensorDevice& dev(SensorDevice::getInstance());
724 sensor_event.type = si->getSensor().getType();
725 dev.injectSensorData(&sensor_event);
Peng Xueb4d6282015-12-10 18:02:41 -0800726#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700727 ++mEventsReceived;
Peng Xueb4d6282015-12-10 18:02:41 -0800728#endif
Peng Xu755c4512016-04-07 23:15:14 -0700729 } else if (numBytesRead == sizeof(uint32_t)) {
730 uint32_t numAcks = 0;
731 memcpy(&numAcks, buf, numBytesRead);
732 // Sanity check to ensure there are no read errors in recv, numAcks is always
733 // within the range and not zero. If any of the above don't hold reset
734 // mWakeLockRefCount to zero.
735 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
736 mWakeLockRefCount -= numAcks;
737 } else {
738 mWakeLockRefCount = 0;
739 }
Peng Xueb4d6282015-12-10 18:02:41 -0800740#if DEBUG_CONNECTIONS
Peng Xu755c4512016-04-07 23:15:14 -0700741 mTotalAcksReceived += numAcks;
Peng Xueb4d6282015-12-10 18:02:41 -0800742#endif
743 } else {
744 // Read error, reset wakelock refcount.
745 mWakeLockRefCount = 0;
746 }
747 }
748 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
749 // here as checkWakeLockState() will need it.
750 if (mWakeLockRefCount == 0) {
751 mService->checkWakeLockState();
752 }
753 // continue getting callbacks.
754 return 1;
755 }
756
757 if (events & ALOOPER_EVENT_OUTPUT) {
758 // send sensor data that is stored in mEventCache for this connection.
759 mService->sendEventsFromCache(this);
760 }
761 return 1;
762}
763
764int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
765 size_t fifoWakeUpSensors = 0;
766 size_t fifoNonWakeUpSensors = 0;
767 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
Peng Xu755c4512016-04-07 23:15:14 -0700768 sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
769 if (si == nullptr) {
770 continue;
771 }
772 const Sensor& sensor = si->getSensor();
Peng Xueb4d6282015-12-10 18:02:41 -0800773 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
774 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
775 // non wake_up sensors.
776 if (sensor.isWakeUpSensor()) {
777 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
778 } else {
779 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
780 }
781 } else {
782 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
783 if (sensor.isWakeUpSensor()) {
784 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
785 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
786
787 } else {
788 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
789 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
790
791 }
792 }
793 }
794 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
795 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
796 // size that is equal to that of the batch mode.
797 // ALOGW("Write failure in non-batch mode");
798 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
799 }
800 return fifoWakeUpSensors + fifoNonWakeUpSensors;
801}
802
803} // namespace android
804