1 /*
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 "EventMessageQueueWrapper.h"
20 #include "HalProxyCallback.h"
21 #include "ISensorsCallbackWrapper.h"
22 #include "SubHalWrapper.h"
23 #include "V2_0/ScopedWakelock.h"
24 #include "V2_0/SubHal.h"
25 #include "V2_1/SubHal.h"
26 #include "WakeLockMessageQueueWrapper.h"
27 #include "convertV2_1.h"
28 
29 #include <android/hardware/sensors/2.1/ISensors.h>
30 #include <android/hardware/sensors/2.1/types.h>
31 #include <fmq/MessageQueue.h>
32 #include <hardware_legacy/power.h>
33 #include <hidl/MQDescriptor.h>
34 #include <hidl/Status.h>
35 
36 #include <atomic>
37 #include <condition_variable>
38 #include <map>
39 #include <mutex>
40 #include <queue>
41 #include <thread>
42 #include <utility>
43 
44 namespace android {
45 namespace hardware {
46 namespace sensors {
47 namespace V2_1 {
48 namespace implementation {
49 
50 /**
51  * HalProxy is the main interface for Multi-HAL. It is responsible for managing  subHALs and
52  * proxying function calls to/from the subHAL APIs from the sensors framework. It also manages any
53  * wakelocks allocated through the IHalProxyCallback and manages posting events to the sensors
54  * framework.
55  */
56 class HalProxy : public V2_0::implementation::IScopedWakelockRefCounter,
57                  public V2_0::implementation::ISubHalCallback {
58   public:
59     using Event = ::android::hardware::sensors::V2_1::Event;
60     using OperationMode = ::android::hardware::sensors::V1_0::OperationMode;
61     using RateLevel = ::android::hardware::sensors::V1_0::RateLevel;
62     using Result = ::android::hardware::sensors::V1_0::Result;
63     using SensorInfo = ::android::hardware::sensors::V2_1::SensorInfo;
64     using SharedMemInfo = ::android::hardware::sensors::V1_0::SharedMemInfo;
65     using IHalProxyCallbackV2_0 = V2_0::implementation::IHalProxyCallback;
66     using IHalProxyCallbackV2_1 = V2_1::implementation::IHalProxyCallback;
67     using ISensorsSubHalV2_0 = V2_0::implementation::ISensorsSubHal;
68     using ISensorsSubHalV2_1 = V2_1::implementation::ISensorsSubHal;
69     using ISensorsV2_0 = V2_0::ISensors;
70     using ISensorsV2_1 = V2_1::ISensors;
71     using HalProxyCallbackBase = V2_0::implementation::HalProxyCallbackBase;
72 
73     explicit HalProxy();
74     // Test only constructor.
75     explicit HalProxy(std::vector<ISensorsSubHalV2_0*>& subHalList);
76     explicit HalProxy(std::vector<ISensorsSubHalV2_0*>& subHalList,
77                       std::vector<ISensorsSubHalV2_1*>& subHalListV2_1);
78     ~HalProxy();
79 
80     // Methods from ::android::hardware::sensors::V2_1::ISensors follow.
81     Return<void> getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb);
82 
83     Return<Result> initialize_2_1(
84             const ::android::hardware::MQDescriptorSync<V2_1::Event>& eventQueueDescriptor,
85             const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
86             const sp<V2_1::ISensorsCallback>& sensorsCallback);
87 
88     Return<Result> injectSensorData_2_1(const Event& event);
89 
90     // Methods from ::android::hardware::sensors::V2_0::ISensors follow.
91     Return<void> getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb);
92 
93     Return<Result> setOperationMode(OperationMode mode);
94 
95     Return<Result> activate(int32_t sensorHandle, bool enabled);
96 
97     Return<Result> initialize(
98             const ::android::hardware::MQDescriptorSync<V1_0::Event>& eventQueueDescriptor,
99             const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
100             const sp<V2_0::ISensorsCallback>& sensorsCallback);
101 
102     Return<Result> initializeCommon(std::unique_ptr<EventMessageQueueWrapperBase>& eventQueue,
103                                     std::unique_ptr<WakeLockMessageQueueWrapperBase>& wakeLockQueue,
104                                     const sp<ISensorsCallbackWrapperBase>& sensorsCallback);
105 
106     Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
107                          int64_t maxReportLatencyNs);
108 
109     Return<Result> flush(int32_t sensorHandle);
110 
111     Return<Result> injectSensorData(const V1_0::Event& event);
112 
113     Return<void> registerDirectChannel(const SharedMemInfo& mem,
114                                        ISensorsV2_0::registerDirectChannel_cb _hidl_cb);
115 
116     Return<Result> unregisterDirectChannel(int32_t channelHandle);
117 
118     Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
119                                     ISensorsV2_0::configDirectReport_cb _hidl_cb);
120 
121     Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args);
122 
123     Return<void> onDynamicSensorsConnected(const hidl_vec<SensorInfo>& dynamicSensorsAdded,
124                                            int32_t subHalIndex) override;
125 
126     Return<void> onDynamicSensorsDisconnected(const hidl_vec<int32_t>& dynamicSensorHandlesRemoved,
127                                               int32_t subHalIndex) override;
128 
129     void postEventsToMessageQueue(const std::vector<Event>& events, size_t numWakeupEvents,
130                                   V2_0::implementation::ScopedWakelock wakelock) override;
131 
getSensorInfo(int32_t sensorHandle)132     const SensorInfo& getSensorInfo(int32_t sensorHandle) override {
133         return mSensors[sensorHandle];
134     }
135 
areThreadsRunning()136     bool areThreadsRunning() override { return mThreadsRun.load(); }
137 
138     // Below methods are from IScopedWakelockRefCounter interface
139     bool incrementRefCountAndMaybeAcquireWakelock(size_t delta,
140                                                   int64_t* timeoutStart = nullptr) override;
141 
142     void decrementRefCountAndMaybeReleaseWakelock(size_t delta, int64_t timeoutStart = -1) override;
143 
getSensors()144     const std::map<int32_t, SensorInfo>& getSensors() { return mSensors; }
145 
146   private:
147     using EventMessageQueueV2_1 = MessageQueue<V2_1::Event, kSynchronizedReadWrite>;
148     using EventMessageQueueV2_0 = MessageQueue<V1_0::Event, kSynchronizedReadWrite>;
149     using WakeLockMessageQueue = MessageQueue<uint32_t, kSynchronizedReadWrite>;
150 
151     /**
152      * The Event FMQ where sensor events are written
153      */
154     std::unique_ptr<EventMessageQueueWrapperBase> mEventQueue;
155 
156     /**
157      * The Wake Lock FMQ that is read to determine when the framework has handled WAKE_UP events
158      */
159     std::unique_ptr<WakeLockMessageQueueWrapperBase> mWakeLockQueue;
160 
161     /**
162      * Event Flag to signal to the framework when sensor events are available to be read and to
163      * interrupt event queue blocking write.
164      */
165     EventFlag* mEventQueueFlag = nullptr;
166 
167     //! Event Flag to signal internally that the wakelock queue should stop its blocking read.
168     EventFlag* mWakelockQueueFlag = nullptr;
169 
170     /**
171      * Callback to the sensors framework to inform it that new sensors have been added or removed.
172      */
173     sp<ISensorsCallbackWrapperBase> mDynamicSensorsCallback;
174 
175     /**
176      * SubHal objects that have been saved from vendor dynamic libraries.
177      */
178     std::vector<std::shared_ptr<ISubHalWrapperBase>> mSubHalList;
179 
180     /**
181      * Map of sensor handles to SensorInfo objects that contains the sensor info from subhals as
182      * well as the modified sensor handle for the framework.
183      *
184      * The subhal index is encoded in the first byte of the sensor handle and the remaining
185      * bytes are generated by the subhal to identify the sensor.
186      */
187     std::map<int32_t, SensorInfo> mSensors;
188 
189     //! Map of the dynamic sensors that have been added to halproxy.
190     std::map<int32_t, SensorInfo> mDynamicSensors;
191 
192     //! The current operation mode for all subhals.
193     OperationMode mCurrentOperationMode = OperationMode::NORMAL;
194 
195     //! The single subHal that supports directChannel reporting.
196     std::shared_ptr<ISubHalWrapperBase> mDirectChannelSubHal;
197 
198     //! The timeout for each pending write on background thread for events.
199     static const int64_t kPendingWriteTimeoutNs = 5 * INT64_C(1000000000) /* 5 seconds */;
200 
201     //! The bit mask used to get the subhal index from a sensor handle.
202     static constexpr int32_t kSensorHandleSubHalIndexMask = 0xFF000000;
203 
204     /**
205      * A FIFO queue of pairs of vector of events and the number of wakeup events in that vector
206      * which are waiting to be written to the events fmq in the background thread.
207      */
208     std::queue<std::pair<std::vector<Event>, size_t>> mPendingWriteEventsQueue;
209 
210     //! The most events observed on the pending write events queue for debug purposes.
211     size_t mMostEventsObservedPendingWriteEventsQueue = 0;
212 
213     //! The max number of events allowed in the pending write events queue
214     static constexpr size_t kMaxSizePendingWriteEventsQueue = 100000;
215 
216     //! The number of events in the pending write events queue
217     size_t mSizePendingWriteEventsQueue = 0;
218 
219     //! The mutex protecting writing to the fmq and the pending events queue
220     std::mutex mEventQueueWriteMutex;
221 
222     //! The condition variable waiting on pending write events to stack up
223     std::condition_variable mEventQueueWriteCV;
224 
225     //! The thread object ptr that handles pending writes
226     std::thread mPendingWritesThread;
227 
228     //! The thread object that handles wakelocks
229     std::thread mWakelockThread;
230 
231     //! The bool indicating whether to end the threads started in initialize
232     std::atomic_bool mThreadsRun = true;
233 
234     //! The mutex protecting access to the dynamic sensors added and removed methods.
235     std::mutex mDynamicSensorsMutex;
236 
237     // WakelockRefCount membar vars below
238 
239     //! The mutex protecting the wakelock refcount and subsequent wakelock releases and
240     //! acquisitions
241     std::recursive_mutex mWakelockMutex;
242 
243     std::condition_variable_any mWakelockCV;
244 
245     //! The refcount of how many ScopedWakelocks and pending wakeup events are active
246     size_t mWakelockRefCount = 0;
247 
248     int64_t mWakelockTimeoutStartTime = V2_0::implementation::getTimeNow();
249 
250     int64_t mWakelockTimeoutResetTime = V2_0::implementation::getTimeNow();
251 
252     const char* kWakelockName = "SensorsHAL_WAKEUP";
253 
254     /**
255      * Initialize the list of SubHal objects in mSubHalList by reading from dynamic libraries
256      * listed in a config file.
257      */
258     void initializeSubHalListFromConfigFile(const char* configFileName);
259 
260     /**
261      * Initialize the HalProxyCallback vector using the list of subhals.
262      */
263     void initializeSubHalCallbacks();
264 
265     /**
266      * Initialize the list of SensorInfo objects in mSensorList by getting sensors from each
267      * subhal.
268      */
269     void initializeSensorList();
270 
271     /**
272      * Try using the default include directories as well as the directories defined in
273      * kSubHalShareObjectLocations to get a handle for dlsym for a subhal.
274      *
275      * @param filename The file name to search for.
276      *
277      * @return The handle or nullptr if search failed.
278      */
279     void* getHandleForSubHalSharedObject(const std::string& filename);
280 
281     /**
282      * Calls the helper methods that all ctors use.
283      */
284     void init();
285 
286     /**
287      * Stops all threads by setting the threads running flag to false and joining to them.
288      */
289     void stopThreads();
290 
291     /**
292      * Disable all the sensors observed by the HalProxy.
293      */
294     void disableAllSensors();
295 
296     /**
297      * Starts the thread that handles pending writes to event fmq.
298      *
299      * @param halProxy The HalProxy object pointer.
300      */
301     static void startPendingWritesThread(HalProxy* halProxy);
302 
303     //! Handles the pending writes on events to eventqueue.
304     void handlePendingWrites();
305 
306     /**
307      * Starts the thread that handles decrementing the ref count on wakeup events processed by the
308      * framework and timing out wakelocks.
309      *
310      * @param halProxy The HalProxy object pointer.
311      */
312     static void startWakelockThread(HalProxy* halProxy);
313 
314     //! Handles the wakelocks.
315     void handleWakelocks();
316 
317     /**
318      * @param timeLeft The variable that should be set to the timeleft before timeout will occur or
319      * unmodified if timeout occurred.
320      *
321      * @return true if the shared wakelock has been held passed the timeout and should be released
322      */
323     bool sharedWakelockDidTimeout(int64_t* timeLeft);
324 
325     /**
326      * Reset all the member variables associated with the wakelock ref count and maybe release
327      * the shared wakelock.
328      */
329     void resetSharedWakelock();
330 
331     /**
332      * Clear direct channel flags if the HalProxy has already chosen a subhal as its direct channel
333      * subhal. Set the directChannelSubHal pointer to the subHal passed in if this is the first
334      * direct channel enabled sensor seen.
335      *
336      * @param sensorInfo The SensorInfo object that may be altered to have direct channel support
337      *    disabled.
338      * @param subHal The subhal pointer that the current sensorInfo object came from.
339      */
340     void setDirectChannelFlags(SensorInfo* sensorInfo, std::shared_ptr<ISubHalWrapperBase> subHal);
341 
342     /*
343      * Get the subhal pointer which can be found by indexing into the mSubHalList vector
344      * using the index from the first byte of sensorHandle.
345      *
346      * @param sensorHandle The handle used to identify a sensor in one of the subhals.
347      */
348     std::shared_ptr<ISubHalWrapperBase> getSubHalForSensorHandle(int32_t sensorHandle);
349 
350     /**
351      * Checks that sensorHandle's subhal index byte is within bounds of mSubHalList.
352      *
353      * @param sensorHandle The sensor handle to check.
354      *
355      * @return true if sensorHandles's subhal index byte is valid.
356      */
357     bool isSubHalIndexValid(int32_t sensorHandle);
358 
359     /**
360      * Count the number of wakeup events in the first n events of the vector.
361      *
362      * @param events The vector of Event objects.
363      * @param n The end index not inclusive of events to consider.
364      *
365      * @return The number of wakeup events of the considered events.
366      */
367     size_t countNumWakeupEvents(const std::vector<Event>& events, size_t n);
368 
369     /*
370      * Clear out the subhal index bytes from a sensorHandle.
371      *
372      * @param sensorHandle The sensor handle to modify.
373      *
374      * @return The modified version of the sensor handle.
375      */
376     static int32_t clearSubHalIndex(int32_t sensorHandle);
377 
378     /**
379      * @param sensorHandle The sensor handle to modify.
380      *
381      * @return true if subHalIndex byte of sensorHandle is zeroed.
382      */
383     static bool subHalIndexIsClear(int32_t sensorHandle);
384 };
385 
386 /**
387  * Since a newer HAL can't masquerade as a older HAL, IHalProxy enables the HalProxy to be compiled
388  * either for HAL 2.0 or HAL 2.1 depending on the build configuration.
389  */
390 template <class ISensorsVersion>
391 class IHalProxy : public HalProxy, public ISensorsVersion {
getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb)392     Return<void> getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb) override {
393         return HalProxy::getSensorsList(_hidl_cb);
394     }
395 
setOperationMode(OperationMode mode)396     Return<Result> setOperationMode(OperationMode mode) override {
397         return HalProxy::setOperationMode(mode);
398     }
399 
activate(int32_t sensorHandle,bool enabled)400     Return<Result> activate(int32_t sensorHandle, bool enabled) override {
401         return HalProxy::activate(sensorHandle, enabled);
402     }
403 
initialize(const::android::hardware::MQDescriptorSync<V1_0::Event> & eventQueueDescriptor,const::android::hardware::MQDescriptorSync<uint32_t> & wakeLockDescriptor,const sp<V2_0::ISensorsCallback> & sensorsCallback)404     Return<Result> initialize(
405             const ::android::hardware::MQDescriptorSync<V1_0::Event>& eventQueueDescriptor,
406             const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
407             const sp<V2_0::ISensorsCallback>& sensorsCallback) override {
408         return HalProxy::initialize(eventQueueDescriptor, wakeLockDescriptor, sensorsCallback);
409     }
410 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)411     Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
412                          int64_t maxReportLatencyNs) override {
413         return HalProxy::batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs);
414     }
415 
flush(int32_t sensorHandle)416     Return<Result> flush(int32_t sensorHandle) override { return HalProxy::flush(sensorHandle); }
417 
injectSensorData(const V1_0::Event & event)418     Return<Result> injectSensorData(const V1_0::Event& event) override {
419         return HalProxy::injectSensorData(event);
420     }
421 
registerDirectChannel(const SharedMemInfo & mem,ISensorsV2_0::registerDirectChannel_cb _hidl_cb)422     Return<void> registerDirectChannel(const SharedMemInfo& mem,
423                                        ISensorsV2_0::registerDirectChannel_cb _hidl_cb) override {
424         return HalProxy::registerDirectChannel(mem, _hidl_cb);
425     }
426 
unregisterDirectChannel(int32_t channelHandle)427     Return<Result> unregisterDirectChannel(int32_t channelHandle) override {
428         return HalProxy::unregisterDirectChannel(channelHandle);
429     }
430 
configDirectReport(int32_t sensorHandle,int32_t channelHandle,RateLevel rate,ISensorsV2_0::configDirectReport_cb _hidl_cb)431     Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
432                                     ISensorsV2_0::configDirectReport_cb _hidl_cb) override {
433         return HalProxy::configDirectReport(sensorHandle, channelHandle, rate, _hidl_cb);
434     }
435 
debug(const hidl_handle & fd,const hidl_vec<hidl_string> & args)436     Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override {
437         return HalProxy::debug(fd, args);
438     }
439 };
440 
441 class HalProxyV2_0 : public IHalProxy<V2_0::ISensors> {};
442 
443 class HalProxyV2_1 : public IHalProxy<V2_1::ISensors> {
getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb)444     Return<void> getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb) override {
445         return HalProxy::getSensorsList_2_1(_hidl_cb);
446     }
447 
initialize_2_1(const::android::hardware::MQDescriptorSync<V2_1::Event> & eventQueueDescriptor,const::android::hardware::MQDescriptorSync<uint32_t> & wakeLockDescriptor,const sp<V2_1::ISensorsCallback> & sensorsCallback)448     Return<Result> initialize_2_1(
449             const ::android::hardware::MQDescriptorSync<V2_1::Event>& eventQueueDescriptor,
450             const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
451             const sp<V2_1::ISensorsCallback>& sensorsCallback) override {
452         return HalProxy::initialize_2_1(eventQueueDescriptor, wakeLockDescriptor, sensorsCallback);
453     }
454 
injectSensorData_2_1(const Event & event)455     Return<Result> injectSensorData_2_1(const Event& event) override {
456         return HalProxy::injectSensorData_2_1(event);
457     }
458 };
459 
460 }  // namespace implementation
461 }  // namespace V2_1
462 }  // namespace sensors
463 }  // namespace hardware
464 }  // namespace android
465