/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "EventMessageQueueWrapper.h" #include "HalProxyCallback.h" #include "ISensorsCallbackWrapper.h" #include "SubHalWrapper.h" #include "V2_0/ScopedWakelock.h" #include "V2_0/SubHal.h" #include "V2_1/SubHal.h" #include "convertV2_1.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace android { namespace hardware { namespace sensors { namespace V2_1 { namespace implementation { /** * HalProxy is the main interface for Multi-HAL. It is responsible for managing subHALs and * proxying function calls to/from the subHAL APIs from the sensors framework. It also manages any * wakelocks allocated through the IHalProxyCallback and manages posting events to the sensors * framework. */ class HalProxy : public V2_0::implementation::IScopedWakelockRefCounter, public V2_0::implementation::ISubHalCallback { public: using Event = ::android::hardware::sensors::V2_1::Event; using OperationMode = ::android::hardware::sensors::V1_0::OperationMode; using RateLevel = ::android::hardware::sensors::V1_0::RateLevel; using Result = ::android::hardware::sensors::V1_0::Result; using SensorInfo = ::android::hardware::sensors::V2_1::SensorInfo; using SharedMemInfo = ::android::hardware::sensors::V1_0::SharedMemInfo; using IHalProxyCallbackV2_0 = V2_0::implementation::IHalProxyCallback; using IHalProxyCallbackV2_1 = V2_1::implementation::IHalProxyCallback; using ISensorsSubHalV2_0 = V2_0::implementation::ISensorsSubHal; using ISensorsSubHalV2_1 = V2_1::implementation::ISensorsSubHal; using ISensorsV2_0 = V2_0::ISensors; using ISensorsV2_1 = V2_1::ISensors; using HalProxyCallbackBase = V2_0::implementation::HalProxyCallbackBase; explicit HalProxy(); // Test only constructor. explicit HalProxy(std::vector& subHalList); explicit HalProxy(std::vector& subHalList, std::vector& subHalListV2_1); ~HalProxy(); // Methods from ::android::hardware::sensors::V2_1::ISensors follow. Return getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb); Return initialize_2_1( const ::android::hardware::MQDescriptorSync& eventQueueDescriptor, const ::android::hardware::MQDescriptorSync& wakeLockDescriptor, const sp& sensorsCallback); Return injectSensorData_2_1(const Event& event); // Methods from ::android::hardware::sensors::V2_0::ISensors follow. Return getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb); Return setOperationMode(OperationMode mode); Return activate(int32_t sensorHandle, bool enabled); Return initialize( const ::android::hardware::MQDescriptorSync& eventQueueDescriptor, const ::android::hardware::MQDescriptorSync& wakeLockDescriptor, const sp& sensorsCallback); Return initializeCommon( std::unique_ptr& eventQueue, const ::android::hardware::MQDescriptorSync& wakeLockDescriptor, const sp& sensorsCallback); Return batch(int32_t sensorHandle, int64_t samplingPeriodNs, int64_t maxReportLatencyNs); Return flush(int32_t sensorHandle); Return injectSensorData(const V1_0::Event& event); Return registerDirectChannel(const SharedMemInfo& mem, ISensorsV2_0::registerDirectChannel_cb _hidl_cb); Return unregisterDirectChannel(int32_t channelHandle); Return configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate, ISensorsV2_0::configDirectReport_cb _hidl_cb); Return debug(const hidl_handle& fd, const hidl_vec& args); Return onDynamicSensorsConnected(const hidl_vec& dynamicSensorsAdded, int32_t subHalIndex) override; Return onDynamicSensorsDisconnected(const hidl_vec& dynamicSensorHandlesRemoved, int32_t subHalIndex) override; void postEventsToMessageQueue(const std::vector& events, size_t numWakeupEvents, V2_0::implementation::ScopedWakelock wakelock) override; const SensorInfo& getSensorInfo(int32_t sensorHandle) override { return mSensors[sensorHandle]; } bool areThreadsRunning() override { return mThreadsRun.load(); } // Below methods are from IScopedWakelockRefCounter interface bool incrementRefCountAndMaybeAcquireWakelock(size_t delta, int64_t* timeoutStart = nullptr) override; void decrementRefCountAndMaybeReleaseWakelock(size_t delta, int64_t timeoutStart = -1) override; private: using EventMessageQueueV2_1 = MessageQueue; using EventMessageQueueV2_0 = MessageQueue; using WakeLockMessageQueue = MessageQueue; /** * The Event FMQ where sensor events are written */ std::unique_ptr mEventQueue; /** * The Wake Lock FMQ that is read to determine when the framework has handled WAKE_UP events */ std::unique_ptr mWakeLockQueue; /** * Event Flag to signal to the framework when sensor events are available to be read and to * interrupt event queue blocking write. */ EventFlag* mEventQueueFlag = nullptr; //! Event Flag to signal internally that the wakelock queue should stop its blocking read. EventFlag* mWakelockQueueFlag = nullptr; /** * Callback to the sensors framework to inform it that new sensors have been added or removed. */ sp mDynamicSensorsCallback; /** * SubHal objects that have been saved from vendor dynamic libraries. */ std::vector> mSubHalList; /** * Map of sensor handles to SensorInfo objects that contains the sensor info from subhals as * well as the modified sensor handle for the framework. * * The subhal index is encoded in the first byte of the sensor handle and the remaining * bytes are generated by the subhal to identify the sensor. */ std::map mSensors; //! Map of the dynamic sensors that have been added to halproxy. std::map mDynamicSensors; //! The current operation mode for all subhals. OperationMode mCurrentOperationMode = OperationMode::NORMAL; //! The single subHal that supports directChannel reporting. std::shared_ptr mDirectChannelSubHal; //! The timeout for each pending write on background thread for events. static const int64_t kPendingWriteTimeoutNs = 5 * INT64_C(1000000000) /* 5 seconds */; //! The bit mask used to get the subhal index from a sensor handle. static constexpr int32_t kSensorHandleSubHalIndexMask = 0xFF000000; /** * A FIFO queue of pairs of vector of events and the number of wakeup events in that vector * which are waiting to be written to the events fmq in the background thread. */ std::queue, size_t>> mPendingWriteEventsQueue; //! The most events observed on the pending write events queue for debug purposes. size_t mMostEventsObservedPendingWriteEventsQueue = 0; //! The max number of events allowed in the pending write events queue static constexpr size_t kMaxSizePendingWriteEventsQueue = 100000; //! The number of events in the pending write events queue size_t mSizePendingWriteEventsQueue = 0; //! The mutex protecting writing to the fmq and the pending events queue std::mutex mEventQueueWriteMutex; //! The condition variable waiting on pending write events to stack up std::condition_variable mEventQueueWriteCV; //! The thread object ptr that handles pending writes std::thread mPendingWritesThread; //! The thread object that handles wakelocks std::thread mWakelockThread; //! The bool indicating whether to end the threads started in initialize std::atomic_bool mThreadsRun = true; //! The mutex protecting access to the dynamic sensors added and removed methods. std::mutex mDynamicSensorsMutex; // WakelockRefCount membar vars below //! The mutex protecting the wakelock refcount and subsequent wakelock releases and //! acquisitions std::recursive_mutex mWakelockMutex; std::condition_variable_any mWakelockCV; //! The refcount of how many ScopedWakelocks and pending wakeup events are active size_t mWakelockRefCount = 0; int64_t mWakelockTimeoutStartTime = V2_0::implementation::getTimeNow(); int64_t mWakelockTimeoutResetTime = V2_0::implementation::getTimeNow(); const char* kWakelockName = "SensorsHAL_WAKEUP"; /** * Initialize the list of SubHal objects in mSubHalList by reading from dynamic libraries * listed in a config file. */ void initializeSubHalListFromConfigFile(const char* configFileName); /** * Initialize the HalProxyCallback vector using the list of subhals. */ void initializeSubHalCallbacks(); /** * Initialize the list of SensorInfo objects in mSensorList by getting sensors from each * subhal. */ void initializeSensorList(); /** * Try using the default include directories as well as the directories defined in * kSubHalShareObjectLocations to get a handle for dlsym for a subhal. * * @param filename The file name to search for. * * @return The handle or nullptr if search failed. */ void* getHandleForSubHalSharedObject(const std::string& filename); /** * Calls the helper methods that all ctors use. */ void init(); /** * Stops all threads by setting the threads running flag to false and joining to them. */ void stopThreads(); /** * Disable all the sensors observed by the HalProxy. */ void disableAllSensors(); /** * Starts the thread that handles pending writes to event fmq. * * @param halProxy The HalProxy object pointer. */ static void startPendingWritesThread(HalProxy* halProxy); //! Handles the pending writes on events to eventqueue. void handlePendingWrites(); /** * Starts the thread that handles decrementing the ref count on wakeup events processed by the * framework and timing out wakelocks. * * @param halProxy The HalProxy object pointer. */ static void startWakelockThread(HalProxy* halProxy); //! Handles the wakelocks. void handleWakelocks(); /** * @param timeLeft The variable that should be set to the timeleft before timeout will occur or * unmodified if timeout occurred. * * @return true if the shared wakelock has been held passed the timeout and should be released */ bool sharedWakelockDidTimeout(int64_t* timeLeft); /** * Reset all the member variables associated with the wakelock ref count and maybe release * the shared wakelock. */ void resetSharedWakelock(); /** * Clear direct channel flags if the HalProxy has already chosen a subhal as its direct channel * subhal. Set the directChannelSubHal pointer to the subHal passed in if this is the first * direct channel enabled sensor seen. * * @param sensorInfo The SensorInfo object that may be altered to have direct channel support * disabled. * @param subHal The subhal pointer that the current sensorInfo object came from. */ void setDirectChannelFlags(SensorInfo* sensorInfo, std::shared_ptr subHal); /* * Get the subhal pointer which can be found by indexing into the mSubHalList vector * using the index from the first byte of sensorHandle. * * @param sensorHandle The handle used to identify a sensor in one of the subhals. */ std::shared_ptr getSubHalForSensorHandle(int32_t sensorHandle); /** * Checks that sensorHandle's subhal index byte is within bounds of mSubHalList. * * @param sensorHandle The sensor handle to check. * * @return true if sensorHandles's subhal index byte is valid. */ bool isSubHalIndexValid(int32_t sensorHandle); /** * Count the number of wakeup events in the first n events of the vector. * * @param events The vector of Event objects. * @param n The end index not inclusive of events to consider. * * @return The number of wakeup events of the considered events. */ size_t countNumWakeupEvents(const std::vector& events, size_t n); /* * Clear out the subhal index bytes from a sensorHandle. * * @param sensorHandle The sensor handle to modify. * * @return The modified version of the sensor handle. */ static int32_t clearSubHalIndex(int32_t sensorHandle); /** * @param sensorHandle The sensor handle to modify. * * @return true if subHalIndex byte of sensorHandle is zeroed. */ static bool subHalIndexIsClear(int32_t sensorHandle); }; /** * Since a newer HAL can't masquerade as a older HAL, IHalProxy enables the HalProxy to be compiled * either for HAL 2.0 or HAL 2.1 depending on the build configuration. */ template class IHalProxy : public HalProxy, public ISensorsVersion { Return getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb) override { return HalProxy::getSensorsList(_hidl_cb); } Return setOperationMode(OperationMode mode) override { return HalProxy::setOperationMode(mode); } Return activate(int32_t sensorHandle, bool enabled) override { return HalProxy::activate(sensorHandle, enabled); } Return initialize( const ::android::hardware::MQDescriptorSync& eventQueueDescriptor, const ::android::hardware::MQDescriptorSync& wakeLockDescriptor, const sp& sensorsCallback) override { return HalProxy::initialize(eventQueueDescriptor, wakeLockDescriptor, sensorsCallback); } Return batch(int32_t sensorHandle, int64_t samplingPeriodNs, int64_t maxReportLatencyNs) override { return HalProxy::batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs); } Return flush(int32_t sensorHandle) override { return HalProxy::flush(sensorHandle); } Return injectSensorData(const V1_0::Event& event) override { return HalProxy::injectSensorData(event); } Return registerDirectChannel(const SharedMemInfo& mem, ISensorsV2_0::registerDirectChannel_cb _hidl_cb) override { return HalProxy::registerDirectChannel(mem, _hidl_cb); } Return unregisterDirectChannel(int32_t channelHandle) override { return HalProxy::unregisterDirectChannel(channelHandle); } Return configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate, ISensorsV2_0::configDirectReport_cb _hidl_cb) override { return HalProxy::configDirectReport(sensorHandle, channelHandle, rate, _hidl_cb); } Return debug(const hidl_handle& fd, const hidl_vec& args) override { return HalProxy::debug(fd, args); } }; class HalProxyV2_0 : public IHalProxy {}; class HalProxyV2_1 : public IHalProxy { Return getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb) override { return HalProxy::getSensorsList_2_1(_hidl_cb); } Return initialize_2_1( const ::android::hardware::MQDescriptorSync& eventQueueDescriptor, const ::android::hardware::MQDescriptorSync& wakeLockDescriptor, const sp& sensorsCallback) override { return HalProxy::initialize_2_1(eventQueueDescriptor, wakeLockDescriptor, sensorsCallback); } Return injectSensorData_2_1(const Event& event) override { return HalProxy::injectSensorData_2_1(event); } }; } // namespace implementation } // namespace V2_1 } // namespace sensors } // namespace hardware } // namespace android