blob: 4e3f120cccfffcef8f2bfa315bc6a200c307c3f7 [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#ifndef ANDROID_SENSOR_EVENT_CONNECTION_H
18#define ANDROID_SENSOR_EVENT_CONNECTION_H
19
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -070020#include <atomic>
Peng Xueb4d6282015-12-10 18:02:41 -080021#include <stdint.h>
22#include <sys/types.h>
Brian Stackc225aa12019-04-19 09:30:25 -070023#include <unordered_map>
Peng Xueb4d6282015-12-10 18:02:41 -080024
25#include <utils/Vector.h>
26#include <utils/SortedVector.h>
Peng Xueb4d6282015-12-10 18:02:41 -080027#include <utils/threads.h>
28#include <utils/AndroidThreads.h>
29#include <utils/RefBase.h>
30#include <utils/Looper.h>
31#include <utils/String8.h>
32
33#include <binder/BinderService.h>
34
Mathias Agopian801ea092017-03-06 15:05:04 -080035#include <sensor/Sensor.h>
36#include <sensor/BitTube.h>
37#include <sensor/ISensorServer.h>
38#include <sensor/ISensorEventConnection.h>
Peng Xueb4d6282015-12-10 18:02:41 -080039
40#include "SensorService.h"
41
42namespace android {
43
44class SensorService;
45
46class SensorService::SensorEventConnection:
47 public BnSensorEventConnection, public LooperCallback {
48
49 friend class SensorService;
50
51public:
52 SensorEventConnection(const sp<SensorService>& service, uid_t uid, String8 packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -080053 bool isDataInjectionMode, const String16& opPackageName,
54 const String16& attributionTag);
Peng Xueb4d6282015-12-10 18:02:41 -080055
56 status_t sendEvents(sensors_event_t const* buffer, size_t count, sensors_event_t* scratch,
Yi Kong8f313e32018-07-17 14:13:29 -070057 wp<const SensorEventConnection> const * mapFlushEventsToConnections = nullptr);
Peng Xueb4d6282015-12-10 18:02:41 -080058 bool hasSensor(int32_t handle) const;
59 bool hasAnySensor() const;
60 bool hasOneShotSensors() const;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -070061 bool addSensor(int32_t handle);
Peng Xueb4d6282015-12-10 18:02:41 -080062 bool removeSensor(int32_t handle);
Arthur Ishiguroad46c782020-03-26 11:24:43 -070063 std::vector<int32_t> getActiveSensorHandles() const;
Peng Xueb4d6282015-12-10 18:02:41 -080064 void setFirstFlushPending(int32_t handle, bool value);
65 void dump(String8& result);
Mike Ma24743862020-01-29 00:36:55 -080066 void dump(util::ProtoOutputStream* proto) const;
Peng Xueb4d6282015-12-10 18:02:41 -080067 bool needsWakeLock();
68 void resetWakeLockRefCount();
69 String8 getPackageName() const;
70
71 uid_t getUid() const { return mUid; }
Anh Pham5198c992021-02-10 14:15:30 +010072 // cap/uncap existing connection depending on the state of the mic toggle.
73 void onMicSensorAccessChanged(bool isMicToggleOn);
74 userid_t getUserId() const { return mUserId; }
Peng Xueb4d6282015-12-10 18:02:41 -080075
76private:
77 virtual ~SensorEventConnection();
78 virtual void onFirstRef();
79 virtual sp<BitTube> getSensorChannel() const;
80 virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs,
81 nsecs_t maxBatchReportLatencyNs, int reservedFlags);
82 virtual status_t setEventRate(int handle, nsecs_t samplingPeriodNs);
83 virtual status_t flush();
Peng Xue36e3472016-11-03 11:57:10 -070084 virtual int32_t configureChannel(int handle, int rateLevel);
Peng Xu8cbefd72017-07-10 16:41:08 -070085 virtual void destroy();
Peng Xue36e3472016-11-03 11:57:10 -070086
Peng Xueb4d6282015-12-10 18:02:41 -080087 // Count the number of flush complete events which are about to be dropped in the buffer.
88 // Increment mPendingFlushEventsToSend in mSensorInfo. These flush complete events will be sent
89 // separately before the next batch of events.
90 void countFlushCompleteEventsLocked(sensors_event_t const* scratch, int numEventsDropped);
91
92 // Check if there are any wake up events in the buffer. If yes, return the index of the first
93 // wake_up sensor event in the buffer else return -1. This wake_up sensor event will have the
94 // flag WAKE_UP_SENSOR_EVENT_NEEDS_ACK set. Exactly one event per packet will have the wake_up
95 // flag set. SOCK_SEQPACKET ensures that either the entire packet is read or dropped.
96 int findWakeUpSensorEventLocked(sensors_event_t const* scratch, int count);
97
98 // Send pending flush_complete events. There may have been flush_complete_events that are
99 // dropped which need to be sent separately before other events. On older HALs (1_0) this method
100 // emulates the behavior of flush().
101 void sendPendingFlushEventsLocked();
102
103 // Writes events from mEventCache to the socket.
104 void writeToSocketFromCache();
105
106 // Compute the approximate cache size from the FIFO sizes of various sensors registered for this
107 // connection. Wake up and non-wake up sensors have separate FIFOs but FIFO may be shared
108 // amongst wake-up sensors and non-wake up sensors.
109 int computeMaxCacheSizeLocked() const;
110
111 // When more sensors register, the maximum cache size desired may change. Compute max cache
112 // size, reallocate memory and copy over events from the older cache.
113 void reAllocateCacheLocked(sensors_event_t const* scratch, int count);
114
Brian Stack93432ad2018-11-27 18:28:48 -0800115 // Add the events to the cache. If the cache would be exceeded, drop events at the beginning of
116 // the cache.
117 void appendEventsToCacheLocked(sensors_event_t const* events, int count);
118
Peng Xueb4d6282015-12-10 18:02:41 -0800119 // LooperCallback method. If there is data to read on this fd, it is an ack from the app that it
120 // has read events from a wake up sensor, decrement mWakeLockRefCount. If this fd is available
121 // for writing send the data from the cache.
122 virtual int handleEvent(int fd, int events, void* data);
123
Stan Rokita29adc8c2020-07-06 17:38:03 -0700124 // Increment mPendingFlushEventsToSend for the given handle if the connection has sensor access.
125 // Returns true if this connection does have sensor access.
126 bool incrementPendingFlushCountIfHasAccess(int32_t handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800127
128 // Add or remove the file descriptor associated with the BitTube to the looper. If mDead is set
129 // to true or there are no more sensors for this connection, the file descriptor is removed if
130 // it has been previously added to the Looper. Depending on the state of the connection FD may
131 // be added to the Looper. The flags to set are determined by the internal state of the
132 // connection. FDs are added to the looper when wake-up sensors are registered (to poll for
133 // acknowledgements) and when write fails on the socket when there are too many error and the
134 // other end hangs up or when this client unregisters for this connection.
135 void updateLooperRegistration(const sp<Looper>& looper); void
136 updateLooperRegistrationLocked(const sp<Looper>& looper);
137
Michael Groover5e1f60b2018-12-04 22:34:29 -0800138 // Returns whether sensor access is available based on both the uid being active and sensor
139 // privacy not being enabled.
140 bool hasSensorAccess();
141
Brian Stackc225aa12019-04-19 09:30:25 -0700142 // Call noteOp for the sensor if the sensor requires a permission
143 bool noteOpIfRequired(const sensors_event_t& event);
Anh Pham5198c992021-02-10 14:15:30 +0100144 // Limits all active connections when the mic toggle is flipped to on.
145 void capRates();
146 // Recover sensor connection previously capped by capRates().
147 void uncapRates();
Anh Pham532e6552021-02-10 14:16:56 +0100148
149 // Add sensorEvent to buffer at position index if the sensorEvent satisfies throttling rules.
150 void addSensorEventsToBuffer(bool shouldResample, const sensors_event_t& sensorEvent,
151 sensors_event_t* buffer, int* index);
Peng Xueb4d6282015-12-10 18:02:41 -0800152 sp<SensorService> const mService;
153 sp<BitTube> mChannel;
154 uid_t mUid;
Anh Phamaf91a912021-02-10 14:10:53 +0100155 std::atomic_bool mIsRateCappedBasedOnPermission;
Anh Pham532e6552021-02-10 14:16:56 +0100156 // Store a mapping of sensor to the timestamp of their last sensor event.
157 std::unordered_map<int, int64_t> mSensorLastTimestamp;
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700158 mutable Mutex mConnectionLock;
Peng Xueb4d6282015-12-10 18:02:41 -0800159 // Number of events from wake up sensors which are still pending and haven't been delivered to
160 // the corresponding application. It is incremented by one unit for each write to the socket.
161 uint32_t mWakeLockRefCount;
162
163 // If this flag is set to true, it means that the file descriptor associated with the BitTube
164 // has been added to the Looper in SensorService. This flag is typically set when this
165 // connection has wake-up sensors associated with it or when write has failed on this connection
166 // and we're storing some events in the cache.
167 bool mHasLooperCallbacks;
168 // If there are any errors associated with the Looper this flag is set to true and
169 // mWakeLockRefCount is reset to zero. needsWakeLock method will always return false, if this
170 // flag is set.
171 bool mDead;
172
173 bool mDataInjectionMode;
174 struct FlushInfo {
175 // The number of flush complete events dropped for this sensor is stored here. They are
176 // sent separately before the next batch of events.
177 int mPendingFlushEventsToSend;
178
179 // Every activate is preceded by a flush. Only after the first flush complete is received,
180 // the events for the sensor are sent on that *connection*.
181 bool mFirstFlushPending;
182
183 FlushInfo() : mPendingFlushEventsToSend(0), mFirstFlushPending(false) {}
184 };
Arthur Ishiguroad46c782020-03-26 11:24:43 -0700185 // protected by SensorService::mLock. Key for this map is the sensor handle.
Arthur Ishiguro062b27b2020-04-13 08:04:49 -0700186 std::unordered_map<int32_t, FlushInfo> mSensorInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800187
188 sensors_event_t *mEventCache;
189 int mCacheSize, mMaxCacheSize;
Brian Stackae4053f2018-12-10 14:54:18 -0800190 int64_t mTimeOfLastEventDrop;
191 int mEventsDropped;
Peng Xueb4d6282015-12-10 18:02:41 -0800192 String8 mPackageName;
193 const String16 mOpPackageName;
Arthur Ishiguro340882c2021-02-18 15:17:44 -0800194 const String16 mAttributionTag;
Brian Duddie457e6392020-06-19 11:38:29 -0700195 int mTargetSdk;
Peng Xueb4d6282015-12-10 18:02:41 -0800196#if DEBUG_CONNECTIONS
197 int mEventsReceived, mEventsSent, mEventsSentFromCache;
198 int mTotalAcksNeeded, mTotalAcksReceived;
199#endif
200
Arthur Ishiguro3e9afc12020-09-22 13:05:15 -0700201 // Used to track if this object was inappropriately used after destroy().
202 std::atomic_bool mDestroyed;
Brian Stackc225aa12019-04-19 09:30:25 -0700203
204 // Store a mapping of sensor handles to required AppOp for a sensor. This map only contains a
205 // valid mapping for sensors that require a permission in order to reduce the lookup time.
206 std::unordered_map<int32_t, int32_t> mHandleToAppOp;
Anh Pham5198c992021-02-10 14:15:30 +0100207 // Mapping of sensor handles to its rate before being capped by the mic toggle.
208 std::unordered_map<int, nsecs_t> mMicSamplingPeriodBackup;
209 userid_t mUserId;
Peng Xueb4d6282015-12-10 18:02:41 -0800210};
211
212} // namepsace android
213
214#endif // ANDROID_SENSOR_EVENT_CONNECTION_H
215