blob: ce28e6785f71790f7c937606f3717341b7051a70 [file] [log] [blame]
Stan Rokita2e37ec442019-07-30 11:35:48 -04001/*
2 * Copyright (C) 2019 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#pragma once
18
19#include "ScopedWakelock.h"
20#include "SubHal.h"
21
22#include <android/hardware/sensors/2.0/ISensors.h>
23#include <android/hardware/sensors/2.0/types.h>
24#include <fmq/MessageQueue.h>
25#include <hardware_legacy/power.h>
26#include <hidl/MQDescriptor.h>
27#include <hidl/Status.h>
28
29#include <atomic>
30#include <condition_variable>
31#include <map>
32#include <mutex>
33#include <queue>
34#include <thread>
35#include <utility>
36
37namespace android {
38namespace hardware {
39namespace sensors {
40namespace V2_0 {
41namespace implementation {
42
43using ::android::sp;
44using ::android::hardware::EventFlag;
45using ::android::hardware::hidl_string;
46using ::android::hardware::hidl_vec;
47using ::android::hardware::MessageQueue;
48using ::android::hardware::MQDescriptor;
49using ::android::hardware::Return;
50using ::android::hardware::Void;
51
52class HalProxy : public ISensors, public IScopedWakelockRefCounter {
53 public:
54 using Event = ::android::hardware::sensors::V1_0::Event;
55 using OperationMode = ::android::hardware::sensors::V1_0::OperationMode;
56 using RateLevel = ::android::hardware::sensors::V1_0::RateLevel;
57 using Result = ::android::hardware::sensors::V1_0::Result;
58 using SensorInfo = ::android::hardware::sensors::V1_0::SensorInfo;
59 using SharedMemInfo = ::android::hardware::sensors::V1_0::SharedMemInfo;
60 using ISensorsSubHal = ::android::hardware::sensors::V2_0::implementation::ISensorsSubHal;
61
62 explicit HalProxy();
63 // Test only constructor.
64 explicit HalProxy(std::vector<ISensorsSubHal*>& subHalList);
65 ~HalProxy();
66
67 // Methods from ::android::hardware::sensors::V2_0::ISensors follow.
68 Return<void> getSensorsList(getSensorsList_cb _hidl_cb) override;
69
70 Return<Result> setOperationMode(OperationMode mode) override;
71
72 Return<Result> activate(int32_t sensorHandle, bool enabled) override;
73
74 Return<Result> initialize(
75 const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
76 const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
77 const sp<ISensorsCallback>& sensorsCallback) override;
78
79 Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
80 int64_t maxReportLatencyNs) override;
81
82 Return<Result> flush(int32_t sensorHandle) override;
83
84 Return<Result> injectSensorData(const Event& event) override;
85
86 Return<void> registerDirectChannel(const SharedMemInfo& mem,
87 registerDirectChannel_cb _hidl_cb) override;
88
89 Return<Result> unregisterDirectChannel(int32_t channelHandle) override;
90
91 Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
92 configDirectReport_cb _hidl_cb) override;
93
94 Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
95
96 // Below methods from ::android::hardware::sensors::V2_0::ISensorsCallback with a minor change
97 // to pass in the sub-HAL index. While the above methods are invoked from the sensors framework
98 // via the binder, these methods are invoked from a callback provided to sub-HALs inside the
99 // same process as the HalProxy, but potentially running on different threads.
100 Return<void> onDynamicSensorsConnected(const hidl_vec<SensorInfo>& dynamicSensorsAdded,
101 int32_t subHalIndex);
102
103 Return<void> onDynamicSensorsDisconnected(const hidl_vec<int32_t>& dynamicSensorHandlesRemoved,
104 int32_t subHalIndex);
105
106 // Below methods are for HalProxyCallback
107
108 /**
109 * Post events to the event message queue if there is room to write them. Otherwise post the
110 * remaining events to a background thread for a blocking write with a kPendingWriteTimeoutNs
111 * timeout.
112 *
113 * @param events The list of events to post to the message queue.
114 * @param numWakeupEvents The number of wakeup events in events.
115 * @param wakelock The wakelock associated with this post of events.
116 */
117 void postEventsToMessageQueue(const std::vector<Event>& events, size_t numWakeupEvents,
118 ScopedWakelock wakelock);
119
120 /**
121 * Get the sensor info associated with that sensorHandle.
122 *
123 * @param sensorHandle The sensor handle.
124 *
125 * @return The sensor info object in the mapping.
126 */
127 const SensorInfo& getSensorInfo(int32_t sensorHandle) { return mSensors[sensorHandle]; }
128
129 bool areThreadsRunning() { return mThreadsRun.load(); }
130
131 // Below methods are from IScopedWakelockRefCounter interface
132 bool incrementRefCountAndMaybeAcquireWakelock(size_t delta,
133 int64_t* timeoutStart = nullptr) override;
134
135 void decrementRefCountAndMaybeReleaseWakelock(size_t delta, int64_t timeoutStart = -1) override;
136
137 private:
138 using EventMessageQueue = MessageQueue<Event, kSynchronizedReadWrite>;
139 using WakeLockMessageQueue = MessageQueue<uint32_t, kSynchronizedReadWrite>;
140
141 /**
142 * The Event FMQ where sensor events are written
143 */
144 std::unique_ptr<EventMessageQueue> mEventQueue;
145
146 /**
147 * The Wake Lock FMQ that is read to determine when the framework has handled WAKE_UP events
148 */
149 std::unique_ptr<WakeLockMessageQueue> mWakeLockQueue;
150
151 /**
152 * Event Flag to signal to the framework when sensor events are available to be read and to
153 * interrupt event queue blocking write.
154 */
155 EventFlag* mEventQueueFlag = nullptr;
156
157 //! Event Flag to signal internally that the wakelock queue should stop its blocking read.
158 EventFlag* mWakelockQueueFlag = nullptr;
159
160 /**
161 * Callback to the sensors framework to inform it that new sensors have been added or removed.
162 */
163 sp<ISensorsCallback> mDynamicSensorsCallback;
164
165 /**
166 * SubHal object pointers that have been saved from vendor dynamic libraries.
167 */
168 std::vector<ISensorsSubHal*> mSubHalList;
169
170 //! The list of subhal callbacks for each subhal where the indices correlate with mSubHalList
171 std::vector<const sp<IHalProxyCallback>> mSubHalCallbacks;
172
173 /**
174 * Map of sensor handles to SensorInfo objects that contains the sensor info from subhals as
175 * well as the modified sensor handle for the framework.
176 *
177 * The subhal index is encoded in the first byte of the sensor handle and the remaining
178 * bytes are generated by the subhal to identify the sensor.
179 */
180 std::map<int32_t, SensorInfo> mSensors;
181
182 //! Map of the dynamic sensors that have been added to halproxy.
183 std::map<int32_t, SensorInfo> mDynamicSensors;
184
185 //! The current operation mode for all subhals.
186 OperationMode mCurrentOperationMode = OperationMode::NORMAL;
187
188 //! The single subHal that supports directChannel reporting.
189 ISensorsSubHal* mDirectChannelSubHal = nullptr;
190
191 //! The timeout for each pending write on background thread for events.
192 static const int64_t kPendingWriteTimeoutNs = 5 * INT64_C(1000000000) /* 5 seconds */;
193
194 //! The bit mask used to get the subhal index from a sensor handle.
195 static constexpr int32_t kSensorHandleSubHalIndexMask = 0xFF000000;
196
197 /**
198 * A FIFO queue of pairs of vector of events and the number of wakeup events in that vector
199 * which are waiting to be written to the events fmq in the background thread.
200 */
201 std::queue<std::pair<std::vector<Event>, size_t>> mPendingWriteEventsQueue;
202
Stan Rokita5098f0a2019-11-04 13:36:54 -0800203 //! The max number of events allowed in the pending write events queue
204 static constexpr size_t kMaxSizePendingWriteEventsQueue = 100000;
205
206 //! The number of events in the pending write events queue
207 size_t mSizePendingWriteEventsQueue = 0;
208
Stan Rokita2e37ec442019-07-30 11:35:48 -0400209 //! The mutex protecting writing to the fmq and the pending events queue
210 std::mutex mEventQueueWriteMutex;
211
212 //! The condition variable waiting on pending write events to stack up
213 std::condition_variable mEventQueueWriteCV;
214
215 //! The thread object ptr that handles pending writes
216 std::thread mPendingWritesThread;
217
218 //! The thread object that handles wakelocks
219 std::thread mWakelockThread;
220
221 //! The bool indicating whether to end the threads started in initialize
222 std::atomic_bool mThreadsRun = true;
223
224 //! The mutex protecting access to the dynamic sensors added and removed methods.
225 std::mutex mDynamicSensorsMutex;
226
227 // WakelockRefCount membar vars below
228
229 //! The mutex protecting the wakelock refcount and subsequent wakelock releases and
230 //! acquisitions
231 std::recursive_mutex mWakelockMutex;
232
233 std::condition_variable_any mWakelockCV;
234
235 //! The refcount of how many ScopedWakelocks and pending wakeup events are active
236 size_t mWakelockRefCount = 0;
237
238 int64_t mWakelockTimeoutStartTime = getTimeNow();
239
240 int64_t mWakelockTimeoutResetTime = getTimeNow();
241
242 const char* kWakelockName = "SensorsHAL_WAKEUP";
243
244 /**
245 * Initialize the list of SubHal objects in mSubHalList by reading from dynamic libraries
246 * listed in a config file.
247 */
248 void initializeSubHalListFromConfigFile(const char* configFileName);
249
250 /**
251 * Initialize the HalProxyCallback vector using the list of subhals.
252 */
253 void initializeSubHalCallbacks();
254
255 /**
256 * Initialize the list of SensorInfo objects in mSensorList by getting sensors from each
257 * subhal.
258 */
259 void initializeSensorList();
260
261 /**
262 * Calls the helper methods that all ctors use.
263 */
264 void init();
265
266 /**
267 * Stops all threads by setting the threads running flag to false and joining to them.
268 */
269 void stopThreads();
270
271 /**
272 * Disable all the sensors observed by the HalProxy.
273 */
274 void disableAllSensors();
275
276 /**
277 * Starts the thread that handles pending writes to event fmq.
278 *
279 * @param halProxy The HalProxy object pointer.
280 */
281 static void startPendingWritesThread(HalProxy* halProxy);
282
283 //! Handles the pending writes on events to eventqueue.
284 void handlePendingWrites();
285
286 /**
287 * Starts the thread that handles decrementing the ref count on wakeup events processed by the
288 * framework and timing out wakelocks.
289 *
290 * @param halProxy The HalProxy object pointer.
291 */
292 static void startWakelockThread(HalProxy* halProxy);
293
294 //! Handles the wakelocks.
295 void handleWakelocks();
296
297 /**
298 * @param timeLeft The variable that should be set to the timeleft before timeout will occur or
299 * unmodified if timeout occurred.
300 *
301 * @return true if the shared wakelock has been held passed the timeout and should be released
302 */
303 bool sharedWakelockDidTimeout(int64_t* timeLeft);
304
305 /**
306 * Reset all the member variables associated with the wakelock ref count and maybe release
307 * the shared wakelock.
308 */
309 void resetSharedWakelock();
310
311 /**
312 * Clear direct channel flags if the HalProxy has already chosen a subhal as its direct channel
313 * subhal. Set the directChannelSubHal pointer to the subHal passed in if this is the first
314 * direct channel enabled sensor seen.
315 *
316 * @param sensorInfo The SensorInfo object that may be altered to have direct channel support
317 * disabled.
318 * @param subHal The subhal pointer that the current sensorInfo object came from.
319 */
320 void setDirectChannelFlags(SensorInfo* sensorInfo, ISensorsSubHal* subHal);
321
322 /*
323 * Get the subhal pointer which can be found by indexing into the mSubHalList vector
324 * using the index from the first byte of sensorHandle.
325 *
326 * @param sensorHandle The handle used to identify a sensor in one of the subhals.
327 */
328 ISensorsSubHal* getSubHalForSensorHandle(int32_t sensorHandle);
329
330 /**
331 * Checks that sensorHandle's subhal index byte is within bounds of mSubHalList.
332 *
333 * @param sensorHandle The sensor handle to check.
334 *
335 * @return true if sensorHandles's subhal index byte is valid.
336 */
337 bool isSubHalIndexValid(int32_t sensorHandle);
338
339 /**
340 * Count the number of wakeup events in the first n events of the vector.
341 *
342 * @param events The vector of Event objects.
343 * @param n The end index not inclusive of events to consider.
344 *
345 * @return The number of wakeup events of the considered events.
346 */
347 size_t countNumWakeupEvents(const std::vector<Event>& events, size_t n);
348
349 /*
350 * Clear out the subhal index bytes from a sensorHandle.
351 *
352 * @param sensorHandle The sensor handle to modify.
353 *
354 * @return The modified version of the sensor handle.
355 */
356 static int32_t clearSubHalIndex(int32_t sensorHandle);
357
358 /**
359 * @param sensorHandle The sensor handle to modify.
360 *
361 * @return true if subHalIndex byte of sensorHandle is zeroed.
362 */
363 static bool subHalIndexIsClear(int32_t sensorHandle);
364};
365
366/**
367 * Callback class used to provide the HalProxy with the index of which subHal is invoking
368 */
369class HalProxyCallback : public IHalProxyCallback {
370 using SensorInfo = ::android::hardware::sensors::V1_0::SensorInfo;
371
372 public:
373 HalProxyCallback(HalProxy* halProxy, int32_t subHalIndex)
374 : mHalProxy(halProxy), mSubHalIndex(subHalIndex) {}
375
376 Return<void> onDynamicSensorsConnected(
377 const hidl_vec<SensorInfo>& dynamicSensorsAdded) override {
378 return mHalProxy->onDynamicSensorsConnected(dynamicSensorsAdded, mSubHalIndex);
379 }
380
381 Return<void> onDynamicSensorsDisconnected(
382 const hidl_vec<int32_t>& dynamicSensorHandlesRemoved) override {
383 return mHalProxy->onDynamicSensorsDisconnected(dynamicSensorHandlesRemoved, mSubHalIndex);
384 }
385
386 void postEvents(const std::vector<Event>& events, ScopedWakelock wakelock);
387
388 ScopedWakelock createScopedWakelock(bool lock);
389
390 private:
391 HalProxy* mHalProxy;
392 int32_t mSubHalIndex;
393
394 std::vector<Event> processEvents(const std::vector<Event>& events,
395 size_t* numWakeupEvents) const;
396};
397
398} // namespace implementation
399} // namespace V2_0
400} // namespace sensors
401} // namespace hardware
402} // namespace android