blob: 2f24e5fd0d48a07f85bcb0573688ae8347ac1ca4 [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
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000020#include "ISensorsWrapper.h"
Peng Xu1a00e2d2017-09-27 23:08:30 -070021#include "SensorDeviceUtils.h"
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070022#include "SensorService.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080023#include "SensorServiceUtils.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080024
Brian Stack979887b2018-09-19 15:27:48 -070025#include <fmq/MessageQueue.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080026#include <sensor/Sensor.h>
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000027#include <sensor/SensorEventQueue.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 <string>
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000037#include <unordered_map>
Arthur Ishiguro4f1dd8a2021-11-12 17:21:24 +000038#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
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000052class SensorDevice : public Singleton<SensorDevice>, public SensorServiceUtil::Dumpable {
Peng Xu6a2d3a02015-12-21 12:00:23 -080053public:
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070054 class HidlTransportErrorLog {
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000055 public:
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070056 HidlTransportErrorLog() {
57 mTs = 0;
58 mCount = 0;
59 }
60
61 HidlTransportErrorLog(time_t ts, int count) {
62 mTs = ts;
63 mCount = count;
64 }
65
66 String8 toString() const {
67 String8 result;
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000068 struct tm* timeInfo = localtime(&mTs);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070069 result.appendFormat("%02d:%02d:%02d :: %d", timeInfo->tm_hour, timeInfo->tm_min,
70 timeInfo->tm_sec, mCount);
71 return result;
72 }
73
74 private:
75 time_t mTs; // timestamp of the error
Arthur Ishigurod6b9e212021-11-14 01:20:55 +000076 int mCount; // number of transport errors observed
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070077 };
78
Brian Stacka28e9212018-09-19 15:20:30 -070079 ~SensorDevice();
Brian Stack156da082018-10-01 15:58:53 -070080 void prepareForReconnect();
81 void reconnect();
Brian Stacka28e9212018-09-19 15:20:30 -070082
Peng Xu6a2d3a02015-12-21 12:00:23 -080083 ssize_t getSensorList(sensor_t const** list);
Andreas Huber99fdbb52016-10-10 13:22:58 -070084
Peng Xu6a2d3a02015-12-21 12:00:23 -080085 void handleDynamicSensorConnection(int handle, bool connected);
86 status_t initCheck() const;
87 int getHalDeviceVersion() const;
Andreas Huber99fdbb52016-10-10 13:22:58 -070088
Peng Xu6a2d3a02015-12-21 12:00:23 -080089 ssize_t poll(sensors_event_t* buffer, size_t count);
Brian Stackb7bfc0f2018-09-25 09:41:16 -070090 void writeWakeLockHandled(uint32_t count);
Andreas Huber99fdbb52016-10-10 13:22:58 -070091
Peng Xu6a2d3a02015-12-21 12:00:23 -080092 status_t activate(void* ident, int handle, int enabled);
93 status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
94 int64_t maxBatchReportLatencyNs);
95 // Call batch with timeout zero instead of calling setDelay() for newer devices.
96 status_t setDelay(void* ident, int handle, int64_t ns);
97 status_t flush(void* ident, int handle);
98 status_t setMode(uint32_t mode);
Peng Xue36e3472016-11-03 11:57:10 -070099
Peng Xu53632542017-01-23 20:06:27 -0800100 bool isDirectReportSupported() const;
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000101 int32_t registerDirectChannel(const sensors_direct_mem_t* memory);
Peng Xue36e3472016-11-03 11:57:10 -0700102 void unregisterDirectChannel(int32_t channelHandle);
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000103 int32_t configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
104 const struct sensors_direct_cfg_t* config);
Peng Xue36e3472016-11-03 11:57:10 -0700105
Peng Xu6a2d3a02015-12-21 12:00:23 -0800106 void disableAllSensors();
107 void enableAllSensors();
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000108 void autoDisable(void* ident, int handle);
Andreas Huber99fdbb52016-10-10 13:22:58 -0700109
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000110 status_t injectSensorData(const sensors_event_t* event);
111 void notifyConnectionDestroyed(void* ident);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800112
Brian Stack6c49e6f2018-09-24 15:44:32 -0700113 using Result = ::android::hardware::sensors::V1_0::Result;
114 hardware::Return<void> onDynamicSensorsConnected(
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000115 const hardware::hidl_vec<hardware::sensors::V2_1::SensorInfo>& dynamicSensorsAdded);
Brian Stack6c49e6f2018-09-24 15:44:32 -0700116 hardware::Return<void> onDynamicSensorsDisconnected(
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000117 const hardware::hidl_vec<int32_t>& dynamicSensorHandlesRemoved);
Brian Stack6c49e6f2018-09-24 15:44:32 -0700118
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700119 void setUidStateForConnection(void* ident, SensorService::UidState state);
120
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000121 bool isReconnecting() const { return mReconnecting; }
Brian Stack156da082018-10-01 15:58:53 -0700122
Brian Stackbce04d72019-03-21 10:54:10 -0700123 bool isSensorActive(int handle) const;
124
Anh Pham5198c992021-02-10 14:15:30 +0100125 // To update the BatchParams of a SensorEventConnection when the mic toggle changes its state
126 // while the Sensors Off toggle is on.
127 void onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs);
128
Peng Xu6a2d3a02015-12-21 12:00:23 -0800129 // Dumpable
Mike Ma24743862020-01-29 00:36:55 -0800130 virtual std::string dump() const override;
131 virtual void dump(util::ProtoOutputStream* proto) const override;
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000132
Peng Xu6a2d3a02015-12-21 12:00:23 -0800133private:
Mathias Agopianf001c922010-11-11 17:58:51 -0800134 friend class Singleton<SensorDevice>;
Steven Morelandd15c0302016-12-20 11:14:50 -0800135
Anthony Stangee38a1412020-02-13 21:28:37 -0500136 sp<::android::hardware::sensors::V2_1::implementation::ISensorsWrapperBase> mSensors;
Arthur Ishiguro4f1dd8a2021-11-12 17:21:24 +0000137 std::vector<sensor_t> mSensorList;
Peng Xu2bec6232016-07-01 17:13:10 -0700138 std::unordered_map<int32_t, sensor_t*> mConnectedDynamicSensors;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700139
Anthony Stangefb4e33a2021-09-29 15:47:53 +0000140 // A bug in the Sensors HIDL spec which marks onDynamicSensorsConnected as oneway causes dynamic
141 // meta events and onDynamicSensorsConnected to be received out of order. This mutex + CV are
142 // used to block meta event processing until onDynamicSensorsConnected is received to simplify
143 // HAL implementations.
144 std::mutex mDynamicSensorsMutex;
145 std::condition_variable mDynamicSensorsCv;
146 static constexpr std::chrono::seconds MAX_DYN_SENSOR_WAIT{5};
147
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000148 static const nsecs_t MINIMUM_EVENTS_PERIOD = 1000000; // 1000 Hz
149 mutable Mutex mLock; // protect mActivationCount[].batchParams
Mathias Agopianf001c922010-11-11 17:58:51 -0800150 // fixed-size array after construction
Aravind Akella724d91d2013-06-27 12:04:23 -0700151
152 // Struct to store all the parameters(samplingPeriod, maxBatchReportLatency and flags) from
153 // batch call. For continous mode clients, maxBatchReportLatency is set to zero.
154 struct BatchParams {
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000155 nsecs_t mTSample, mTBatch;
156 BatchParams() : mTSample(INT64_MAX), mTBatch(INT64_MAX) {}
157 BatchParams(nsecs_t tSample, nsecs_t tBatch) : mTSample(tSample), mTBatch(tBatch) {}
158 bool operator!=(const BatchParams& other) {
159 return !(mTSample == other.mTSample && mTBatch == other.mTBatch);
160 }
161 // Merge another parameter with this one. The updated mTSample will be the min of the two.
162 // The update mTBatch will be the min of original mTBatch and the apparent batch period
163 // of the other. the apparent batch is the maximum of mTBatch and mTSample,
164 void merge(const BatchParams& other) {
165 mTSample = std::min(mTSample, other.mTSample);
166 mTBatch = std::min(mTBatch, std::max(other.mTBatch, other.mTSample));
167 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700168 };
169
170 // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
171 // bestBatchParams. For every batch() call corresponding params are stored in batchParams
172 // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
173 // mode request is batch(... timeout > 0 ...) followed by activate().
174 // Info is a per-sensor data structure which contains the batch parameters for each client that
175 // has registered for this sensor.
Mathias Agopianf001c922010-11-11 17:58:51 -0800176 struct Info {
Aravind Akella724d91d2013-06-27 12:04:23 -0700177 BatchParams bestBatchParams;
178 // Key is the unique identifier(ident) for each client, value is the batch parameters
179 // requested by the client.
180 KeyedVector<void*, BatchParams> batchParams;
181
Brian Stack0c305fe2019-04-09 12:49:24 -0700182 // Flag to track if the sensor is active
183 bool isActive = false;
184
Aravind Akella724d91d2013-06-27 12:04:23 -0700185 // Sets batch parameters for this ident. Returns error if this ident is not already present
186 // in the KeyedVector above.
187 status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
188 int64_t maxBatchReportLatencyNs);
189 // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
190 void selectBatchParams();
191 // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
192 // the removed ident. If index >=0, ident is present and successfully removed.
193 ssize_t removeBatchParamsForIdent(void* ident);
Aravind Akella4949c502015-02-11 15:54:35 -0800194
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700195 bool hasBatchParamsForIdent(void* ident) const {
196 return batchParams.indexOfKey(ident) >= 0;
197 }
198
199 /**
200 * @return The number of active clients of this sensor.
201 */
Brian Stack156da082018-10-01 15:58:53 -0700202 int numActiveClients() const;
Mathias Agopianf001c922010-11-11 17:58:51 -0800203 };
204 DefaultKeyedVector<int, Info> mActivationCount;
205
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700206 // Keep track of any hidl transport failures
207 SensorServiceUtil::RingBuffer<HidlTransportErrorLog> mHidlTransportErrors;
208 int mTotalHidlTransportErrors;
209
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700210 /**
211 * Enums describing the reason why a client was disabled.
212 */
213 enum DisabledReason : uint8_t {
214 // UID becomes idle (e.g. app goes to background).
215 DISABLED_REASON_UID_IDLE = 0,
216
217 // Sensors are restricted for all clients.
218 DISABLED_REASON_SERVICE_RESTRICTED,
219 DISABLED_REASON_MAX,
220 };
221
222 static_assert(DisabledReason::DISABLED_REASON_MAX < sizeof(uint8_t) * CHAR_BIT);
223
224 // Use this map to determine which client is activated or deactivated.
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000225 std::unordered_map<void*, uint8_t> mDisabledClients;
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700226
227 void addDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
228 void removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
229
Mathias Agopianf001c922010-11-11 17:58:51 -0800230 SensorDevice();
Peng Xua8fad9b2017-03-17 12:20:27 -0700231 bool connectHidlService();
Brian Stack156da082018-10-01 15:58:53 -0700232 void initializeSensorList();
233 void reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations);
Arthur Ishiguro4f1dd8a2021-11-12 17:21:24 +0000234 static bool sensorHandlesChanged(const std::vector<sensor_t>& oldSensorList,
235 const std::vector<sensor_t>& newSensorList);
Brian Stack156da082018-10-01 15:58:53 -0700236 static bool sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor);
Brian Stack979887b2018-09-19 15:27:48 -0700237
238 enum HalConnectionStatus {
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000239 CONNECTED, // Successfully connected to the HAL
240 DOES_NOT_EXIST, // Could not find the HAL
Brian Stack979887b2018-09-19 15:27:48 -0700241 FAILED_TO_CONNECT, // Found the HAL but failed to connect/initialize
242 UNKNOWN,
243 };
244 HalConnectionStatus connectHidlServiceV1_0();
245 HalConnectionStatus connectHidlServiceV2_0();
Anthony Stangee38a1412020-02-13 21:28:37 -0500246 HalConnectionStatus connectHidlServiceV2_1();
247 HalConnectionStatus initializeHidlServiceV2_X();
Aravind Akella4949c502015-02-11 15:54:35 -0800248
Brian Stacka28e9212018-09-19 15:20:30 -0700249 ssize_t pollHal(sensors_event_t* buffer, size_t count);
250 ssize_t pollFmq(sensors_event_t* buffer, size_t count);
Brian Stack156da082018-10-01 15:58:53 -0700251 status_t activateLocked(void* ident, int handle, int enabled);
252 status_t batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
253 int64_t maxBatchReportLatencyNs);
Brian Stacka28e9212018-09-19 15:20:30 -0700254
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700255 status_t updateBatchParamsLocked(int handle, Info& info);
256 status_t doActivateHardwareLocked(int handle, bool enable);
257
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000258 void handleHidlDeath(const std::string& detail);
259 template <typename T>
Brian Duddie6d2e3752019-05-30 09:52:28 -0700260 void checkReturn(const Return<T>& ret) {
Peng Xu3889e6e2017-03-02 19:10:38 -0800261 if (!ret.isOk()) {
262 handleHidlDeath(ret.description());
263 }
Peng Xu3889e6e2017-03-02 19:10:38 -0800264 }
Brian Duddie6d2e3752019-05-30 09:52:28 -0700265 status_t checkReturnAndGetStatus(const Return<Result>& ret);
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000266 // TODO(b/67425500): remove waiter after bug is resolved.
Peng Xu1a00e2d2017-09-27 23:08:30 -0700267 sp<SensorDeviceUtils::HidlServiceRegistrationWaiter> mRestartWaiter;
Peng Xu3889e6e2017-03-02 19:10:38 -0800268
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700269 bool isClientDisabled(void* ident) const;
270 bool isClientDisabledLocked(void* ident) const;
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000271 std::vector<void*> getDisabledClientsLocked() const;
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700272
273 bool clientHasNoAccessLocked(void* ident) const;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700274
Anthony Stangee38a1412020-02-13 21:28:37 -0500275 using Event = hardware::sensors::V2_1::Event;
276 using SensorInfo = hardware::sensors::V2_1::SensorInfo;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700277
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000278 void convertToSensorEvent(const Event& src, sensors_event_t* dst);
Andreas Huber99fdbb52016-10-10 13:22:58 -0700279
Arthur Ishigurod6b9e212021-11-14 01:20:55 +0000280 void convertToSensorEventsAndQuantize(const hardware::hidl_vec<Event>& src,
281 const hardware::hidl_vec<SensorInfo>& dynamicSensorsAdded,
282 sensors_event_t* dst);
Peng Xu53632542017-01-23 20:06:27 -0800283
Anthony Stange12924862020-03-20 10:46:15 -0400284 float getResolutionForSensor(int sensorHandle);
285
Peng Xu53632542017-01-23 20:06:27 -0800286 bool mIsDirectReportSupported;
Brian Stack979887b2018-09-19 15:27:48 -0700287
Brian Stack979887b2018-09-19 15:27:48 -0700288 typedef hardware::MessageQueue<uint32_t, hardware::kSynchronizedReadWrite> WakeLockQueue;
Brian Stack979887b2018-09-19 15:27:48 -0700289 std::unique_ptr<WakeLockQueue> mWakeLockQueue;
Brian Stacka28e9212018-09-19 15:20:30 -0700290
291 hardware::EventFlag* mEventQueueFlag;
Brian Stacka24e7d42019-01-08 12:56:09 -0800292 hardware::EventFlag* mWakeLockQueueFlag;
Brian Stacka28e9212018-09-19 15:20:30 -0700293
294 std::array<Event, SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT> mEventBuffer;
Brian Stack574cda32018-10-01 11:18:51 -0700295
296 sp<SensorsHalDeathReceivier> mSensorsHalDeathReceiver;
Brian Stack156da082018-10-01 15:58:53 -0700297 std::atomic_bool mReconnecting;
Mathias Agopianf001c922010-11-11 17:58:51 -0800298};
299
300// ---------------------------------------------------------------------------
301}; // namespace android
302
303#endif // ANDROID_SENSOR_DEVICE_H