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