blob: e90a02ff2e9cb2b3989a1d28c641b78038025555 [file] [log] [blame]
Mathias Agopianf001c922010-11-11 17:58:51 -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_DEVICE_H
18#define ANDROID_SENSOR_DEVICE_H
19
Peng Xu1a00e2d2017-09-27 23:08:30 -070020#include "SensorDeviceUtils.h"
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070021#include "SensorService.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080022#include "SensorServiceUtils.h"
Anthony Stangee38a1412020-02-13 21:28:37 -050023#include "ISensorsWrapper.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080024
Brian Stack979887b2018-09-19 15:27:48 -070025#include <fmq/MessageQueue.h>
Brian Stacka28e9212018-09-19 15:20:30 -070026#include <sensor/SensorEventQueue.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080027#include <sensor/Sensor.h>
Steven Morelandd15c0302016-12-20 11:14:50 -080028#include <stdint.h>
29#include <sys/types.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080030#include <utils/KeyedVector.h>
31#include <utils/Singleton.h>
32#include <utils/String8.h>
Brian Stacka28e9212018-09-19 15:20:30 -070033#include <utils/Timers.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080034
Peng Xu2bec6232016-07-01 17:13:10 -070035#include <algorithm> //std::max std::min
Arthur Ishiguro4f1dd8a2021-11-12 17:21:24 +000036#include <unordered_map>
37#include <string>
38#include <vector>
Andreas Huber99fdbb52016-10-10 13:22:58 -070039
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070040#include "RingBuffer.h"
41
Mathias Agopianf001c922010-11-11 17:58:51 -080042// ---------------------------------------------------------------------------
43
44namespace android {
Andreas Huber99fdbb52016-10-10 13:22:58 -070045
Mathias Agopianf001c922010-11-11 17:58:51 -080046// ---------------------------------------------------------------------------
Brian Stack574cda32018-10-01 11:18:51 -070047class SensorsHalDeathReceivier : public android::hardware::hidl_death_recipient {
48 virtual void serviceDied(uint64_t cookie,
49 const wp<::android::hidl::base::V1_0::IBase>& service) override;
50};
Mathias Agopianf001c922010-11-11 17:58:51 -080051
Brian Stack6c49e6f2018-09-24 15:44:32 -070052class SensorDevice : public Singleton<SensorDevice>,
Brian Stack6c49e6f2018-09-24 15:44:32 -070053 public SensorServiceUtil::Dumpable {
Peng Xu6a2d3a02015-12-21 12:00:23 -080054public:
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070055 class HidlTransportErrorLog {
56 public:
57
58 HidlTransportErrorLog() {
59 mTs = 0;
60 mCount = 0;
61 }
62
63 HidlTransportErrorLog(time_t ts, int count) {
64 mTs = ts;
65 mCount = count;
66 }
67
68 String8 toString() const {
69 String8 result;
70 struct tm *timeInfo = localtime(&mTs);
71 result.appendFormat("%02d:%02d:%02d :: %d", timeInfo->tm_hour, timeInfo->tm_min,
72 timeInfo->tm_sec, mCount);
73 return result;
74 }
75
76 private:
77 time_t mTs; // timestamp of the error
78 int mCount; // number of transport errors observed
79 };
80
Brian Stacka28e9212018-09-19 15:20:30 -070081 ~SensorDevice();
Brian Stack156da082018-10-01 15:58:53 -070082 void prepareForReconnect();
83 void reconnect();
Brian Stacka28e9212018-09-19 15:20:30 -070084
Peng Xu6a2d3a02015-12-21 12:00:23 -080085 ssize_t getSensorList(sensor_t const** list);
Andreas Huber99fdbb52016-10-10 13:22:58 -070086
Peng Xu6a2d3a02015-12-21 12:00:23 -080087 void handleDynamicSensorConnection(int handle, bool connected);
88 status_t initCheck() const;
89 int getHalDeviceVersion() const;
Andreas Huber99fdbb52016-10-10 13:22:58 -070090
Peng Xu6a2d3a02015-12-21 12:00:23 -080091 ssize_t poll(sensors_event_t* buffer, size_t count);
Brian Stackb7bfc0f2018-09-25 09:41:16 -070092 void writeWakeLockHandled(uint32_t count);
Andreas Huber99fdbb52016-10-10 13:22:58 -070093
Peng Xu6a2d3a02015-12-21 12:00:23 -080094 status_t activate(void* ident, int handle, int enabled);
95 status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
96 int64_t maxBatchReportLatencyNs);
97 // Call batch with timeout zero instead of calling setDelay() for newer devices.
98 status_t setDelay(void* ident, int handle, int64_t ns);
99 status_t flush(void* ident, int handle);
100 status_t setMode(uint32_t mode);
Peng Xue36e3472016-11-03 11:57:10 -0700101
Peng Xu53632542017-01-23 20:06:27 -0800102 bool isDirectReportSupported() const;
Peng Xue36e3472016-11-03 11:57:10 -0700103 int32_t registerDirectChannel(const sensors_direct_mem_t *memory);
104 void unregisterDirectChannel(int32_t channelHandle);
105 int32_t configureDirectChannel(int32_t sensorHandle,
106 int32_t channelHandle, const struct sensors_direct_cfg_t *config);
107
Peng Xu6a2d3a02015-12-21 12:00:23 -0800108 void disableAllSensors();
109 void enableAllSensors();
110 void autoDisable(void *ident, int handle);
Andreas Huber99fdbb52016-10-10 13:22:58 -0700111
Peng Xu6a2d3a02015-12-21 12:00:23 -0800112 status_t injectSensorData(const sensors_event_t *event);
Peng Xu4f707f82016-09-26 11:28:32 -0700113 void notifyConnectionDestroyed(void *ident);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800114
Brian Stack6c49e6f2018-09-24 15:44:32 -0700115 using Result = ::android::hardware::sensors::V1_0::Result;
116 hardware::Return<void> onDynamicSensorsConnected(
Anthony Stangee38a1412020-02-13 21:28:37 -0500117 const hardware::hidl_vec<hardware::sensors::V2_1::SensorInfo> &dynamicSensorsAdded);
Brian Stack6c49e6f2018-09-24 15:44:32 -0700118 hardware::Return<void> onDynamicSensorsDisconnected(
Brian Stackbbab1ea2018-10-01 10:49:07 -0700119 const hardware::hidl_vec<int32_t> &dynamicSensorHandlesRemoved);
Brian Stack6c49e6f2018-09-24 15:44:32 -0700120
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700121 void setUidStateForConnection(void* ident, SensorService::UidState state);
122
Brian Stack156da082018-10-01 15:58:53 -0700123 bool isReconnecting() const {
124 return mReconnecting;
125 }
126
Brian Stackbce04d72019-03-21 10:54:10 -0700127 bool isSensorActive(int handle) const;
128
Anh Pham5198c992021-02-10 14:15:30 +0100129 // To update the BatchParams of a SensorEventConnection when the mic toggle changes its state
130 // while the Sensors Off toggle is on.
131 void onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs);
132
Peng Xu6a2d3a02015-12-21 12:00:23 -0800133 // Dumpable
Mike Ma24743862020-01-29 00:36:55 -0800134 virtual std::string dump() const override;
135 virtual void dump(util::ProtoOutputStream* proto) const override;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800136private:
Mathias Agopianf001c922010-11-11 17:58:51 -0800137 friend class Singleton<SensorDevice>;
Steven Morelandd15c0302016-12-20 11:14:50 -0800138
Anthony Stangee38a1412020-02-13 21:28:37 -0500139 sp<::android::hardware::sensors::V2_1::implementation::ISensorsWrapperBase> mSensors;
Arthur Ishiguro4f1dd8a2021-11-12 17:21:24 +0000140 std::vector<sensor_t> mSensorList;
Peng Xu2bec6232016-07-01 17:13:10 -0700141 std::unordered_map<int32_t, sensor_t*> mConnectedDynamicSensors;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700142
Anthony Stangefb4e33a2021-09-29 15:47:53 +0000143 // A bug in the Sensors HIDL spec which marks onDynamicSensorsConnected as oneway causes dynamic
144 // meta events and onDynamicSensorsConnected to be received out of order. This mutex + CV are
145 // used to block meta event processing until onDynamicSensorsConnected is received to simplify
146 // HAL implementations.
147 std::mutex mDynamicSensorsMutex;
148 std::condition_variable mDynamicSensorsCv;
149 static constexpr std::chrono::seconds MAX_DYN_SENSOR_WAIT{5};
150
Aravind Akella724d91d2013-06-27 12:04:23 -0700151 static const nsecs_t MINIMUM_EVENTS_PERIOD = 1000000; // 1000 Hz
152 mutable Mutex mLock; // protect mActivationCount[].batchParams
Mathias Agopianf001c922010-11-11 17:58:51 -0800153 // fixed-size array after construction
Aravind Akella724d91d2013-06-27 12:04:23 -0700154
155 // Struct to store all the parameters(samplingPeriod, maxBatchReportLatency and flags) from
156 // batch call. For continous mode clients, maxBatchReportLatency is set to zero.
157 struct BatchParams {
Peng Xu2bec6232016-07-01 17:13:10 -0700158 nsecs_t mTSample, mTBatch;
159 BatchParams() : mTSample(INT64_MAX), mTBatch(INT64_MAX) {}
160 BatchParams(nsecs_t tSample, nsecs_t tBatch): mTSample(tSample), mTBatch(tBatch) {}
Aravind Akella724d91d2013-06-27 12:04:23 -0700161 bool operator != (const BatchParams& other) {
Peng Xu2bec6232016-07-01 17:13:10 -0700162 return !(mTSample == other.mTSample && mTBatch == other.mTBatch);
163 }
164 // Merge another parameter with this one. The updated mTSample will be the min of the two.
165 // The update mTBatch will be the min of original mTBatch and the apparent batch period
166 // of the other. the apparent batch is the maximum of mTBatch and mTSample,
167 void merge(const BatchParams &other) {
168 mTSample = std::min(mTSample, other.mTSample);
169 mTBatch = std::min(mTBatch, std::max(other.mTBatch, other.mTSample));
Aravind Akella724d91d2013-06-27 12:04:23 -0700170 }
171 };
172
173 // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
174 // bestBatchParams. For every batch() call corresponding params are stored in batchParams
175 // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
176 // mode request is batch(... timeout > 0 ...) followed by activate().
177 // Info is a per-sensor data structure which contains the batch parameters for each client that
178 // has registered for this sensor.
Mathias Agopianf001c922010-11-11 17:58:51 -0800179 struct Info {
Aravind Akella724d91d2013-06-27 12:04:23 -0700180 BatchParams bestBatchParams;
181 // Key is the unique identifier(ident) for each client, value is the batch parameters
182 // requested by the client.
183 KeyedVector<void*, BatchParams> batchParams;
184
Brian Stack0c305fe2019-04-09 12:49:24 -0700185 // Flag to track if the sensor is active
186 bool isActive = false;
187
Aravind Akella724d91d2013-06-27 12:04:23 -0700188 // Sets batch parameters for this ident. Returns error if this ident is not already present
189 // in the KeyedVector above.
190 status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
191 int64_t maxBatchReportLatencyNs);
192 // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
193 void selectBatchParams();
194 // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
195 // the removed ident. If index >=0, ident is present and successfully removed.
196 ssize_t removeBatchParamsForIdent(void* ident);
Aravind Akella4949c502015-02-11 15:54:35 -0800197
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700198 bool hasBatchParamsForIdent(void* ident) const {
199 return batchParams.indexOfKey(ident) >= 0;
200 }
201
202 /**
203 * @return The number of active clients of this sensor.
204 */
Brian Stack156da082018-10-01 15:58:53 -0700205 int numActiveClients() const;
Mathias Agopianf001c922010-11-11 17:58:51 -0800206 };
207 DefaultKeyedVector<int, Info> mActivationCount;
208
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700209 // Keep track of any hidl transport failures
210 SensorServiceUtil::RingBuffer<HidlTransportErrorLog> mHidlTransportErrors;
211 int mTotalHidlTransportErrors;
212
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700213 /**
214 * Enums describing the reason why a client was disabled.
215 */
216 enum DisabledReason : uint8_t {
217 // UID becomes idle (e.g. app goes to background).
218 DISABLED_REASON_UID_IDLE = 0,
219
220 // Sensors are restricted for all clients.
221 DISABLED_REASON_SERVICE_RESTRICTED,
222 DISABLED_REASON_MAX,
223 };
224
225 static_assert(DisabledReason::DISABLED_REASON_MAX < sizeof(uint8_t) * CHAR_BIT);
226
227 // Use this map to determine which client is activated or deactivated.
228 std::unordered_map<void *, uint8_t> mDisabledClients;
229
230 void addDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
231 void removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
232
Mathias Agopianf001c922010-11-11 17:58:51 -0800233 SensorDevice();
Peng Xua8fad9b2017-03-17 12:20:27 -0700234 bool connectHidlService();
Brian Stack156da082018-10-01 15:58:53 -0700235 void initializeSensorList();
236 void reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations);
Arthur Ishiguro4f1dd8a2021-11-12 17:21:24 +0000237 static bool sensorHandlesChanged(const std::vector<sensor_t>& oldSensorList,
238 const std::vector<sensor_t>& newSensorList);
Brian Stack156da082018-10-01 15:58:53 -0700239 static bool sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor);
Brian Stack979887b2018-09-19 15:27:48 -0700240
241 enum HalConnectionStatus {
242 CONNECTED, // Successfully connected to the HAL
243 DOES_NOT_EXIST, // Could not find the HAL
244 FAILED_TO_CONNECT, // Found the HAL but failed to connect/initialize
245 UNKNOWN,
246 };
247 HalConnectionStatus connectHidlServiceV1_0();
248 HalConnectionStatus connectHidlServiceV2_0();
Anthony Stangee38a1412020-02-13 21:28:37 -0500249 HalConnectionStatus connectHidlServiceV2_1();
250 HalConnectionStatus initializeHidlServiceV2_X();
Aravind Akella4949c502015-02-11 15:54:35 -0800251
Brian Stacka28e9212018-09-19 15:20:30 -0700252 ssize_t pollHal(sensors_event_t* buffer, size_t count);
253 ssize_t pollFmq(sensors_event_t* buffer, size_t count);
Brian Stack156da082018-10-01 15:58:53 -0700254 status_t activateLocked(void* ident, int handle, int enabled);
255 status_t batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
256 int64_t maxBatchReportLatencyNs);
Brian Stacka28e9212018-09-19 15:20:30 -0700257
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700258 status_t updateBatchParamsLocked(int handle, Info& info);
259 status_t doActivateHardwareLocked(int handle, bool enable);
260
Brian Duddie6d2e3752019-05-30 09:52:28 -0700261 void handleHidlDeath(const std::string &detail);
Peng Xu3889e6e2017-03-02 19:10:38 -0800262 template<typename T>
Brian Duddie6d2e3752019-05-30 09:52:28 -0700263 void checkReturn(const Return<T>& ret) {
Peng Xu3889e6e2017-03-02 19:10:38 -0800264 if (!ret.isOk()) {
265 handleHidlDeath(ret.description());
266 }
Peng Xu3889e6e2017-03-02 19:10:38 -0800267 }
Brian Duddie6d2e3752019-05-30 09:52:28 -0700268 status_t checkReturnAndGetStatus(const Return<Result>& ret);
Peng Xu1a00e2d2017-09-27 23:08:30 -0700269 //TODO(b/67425500): remove waiter after bug is resolved.
270 sp<SensorDeviceUtils::HidlServiceRegistrationWaiter> mRestartWaiter;
Peng Xu3889e6e2017-03-02 19:10:38 -0800271
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700272 bool isClientDisabled(void* ident) const;
273 bool isClientDisabledLocked(void* ident) const;
274 std::vector<void *> getDisabledClientsLocked() const;
275
276 bool clientHasNoAccessLocked(void* ident) const;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700277
Anthony Stangee38a1412020-02-13 21:28:37 -0500278 using Event = hardware::sensors::V2_1::Event;
279 using SensorInfo = hardware::sensors::V2_1::SensorInfo;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700280
281 void convertToSensorEvent(const Event &src, sensors_event_t *dst);
282
Anthony Stange12924862020-03-20 10:46:15 -0400283 void convertToSensorEventsAndQuantize(
Andreas Huber99fdbb52016-10-10 13:22:58 -0700284 const hardware::hidl_vec<Event> &src,
285 const hardware::hidl_vec<SensorInfo> &dynamicSensorsAdded,
286 sensors_event_t *dst);
Peng Xu53632542017-01-23 20:06:27 -0800287
Anthony Stange12924862020-03-20 10:46:15 -0400288 float getResolutionForSensor(int sensorHandle);
289
Peng Xu53632542017-01-23 20:06:27 -0800290 bool mIsDirectReportSupported;
Brian Stack979887b2018-09-19 15:27:48 -0700291
Brian Stack979887b2018-09-19 15:27:48 -0700292 typedef hardware::MessageQueue<uint32_t, hardware::kSynchronizedReadWrite> WakeLockQueue;
Brian Stack979887b2018-09-19 15:27:48 -0700293 std::unique_ptr<WakeLockQueue> mWakeLockQueue;
Brian Stacka28e9212018-09-19 15:20:30 -0700294
295 hardware::EventFlag* mEventQueueFlag;
Brian Stacka24e7d42019-01-08 12:56:09 -0800296 hardware::EventFlag* mWakeLockQueueFlag;
Brian Stacka28e9212018-09-19 15:20:30 -0700297
298 std::array<Event, SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT> mEventBuffer;
Brian Stack574cda32018-10-01 11:18:51 -0700299
300 sp<SensorsHalDeathReceivier> mSensorsHalDeathReceiver;
Brian Stack156da082018-10-01 15:58:53 -0700301 std::atomic_bool mReconnecting;
Mathias Agopianf001c922010-11-11 17:58:51 -0800302};
303
304// ---------------------------------------------------------------------------
305}; // namespace android
306
307#endif // ANDROID_SENSOR_DEVICE_H