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 #include "HalProxy.h"
18 
19 #include <android/hardware/sensors/2.0/types.h>
20 
21 #include <android-base/file.h>
22 #include "hardware_legacy/power.h"
23 
24 #include <dlfcn.h>
25 
26 #include <cinttypes>
27 #include <cmath>
28 #include <fstream>
29 #include <functional>
30 #include <thread>
31 
32 namespace android {
33 namespace hardware {
34 namespace sensors {
35 namespace V2_1 {
36 namespace implementation {
37 
38 using ::android::hardware::sensors::V1_0::Result;
39 using ::android::hardware::sensors::V2_0::EventQueueFlagBits;
40 using ::android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
41 using ::android::hardware::sensors::V2_0::implementation::getTimeNow;
42 using ::android::hardware::sensors::V2_0::implementation::kWakelockTimeoutNs;
43 
44 typedef V2_0::implementation::ISensorsSubHal*(SensorsHalGetSubHalFunc)(uint32_t*);
45 typedef V2_1::implementation::ISensorsSubHal*(SensorsHalGetSubHalV2_1Func)(uint32_t*);
46 
47 static constexpr int32_t kBitsAfterSubHalIndex = 24;
48 
49 /**
50  * Set the subhal index as first byte of sensor handle and return this modified version.
51  *
52  * @param sensorHandle The sensor handle to modify.
53  * @param subHalIndex The index in the hal proxy of the sub hal this sensor belongs to.
54  *
55  * @return The modified sensor handle.
56  */
setSubHalIndex(int32_t sensorHandle,size_t subHalIndex)57 int32_t setSubHalIndex(int32_t sensorHandle, size_t subHalIndex) {
58     return sensorHandle | (static_cast<int32_t>(subHalIndex) << kBitsAfterSubHalIndex);
59 }
60 
61 /**
62  * Extract the subHalIndex from sensorHandle.
63  *
64  * @param sensorHandle The sensorHandle to extract from.
65  *
66  * @return The subhal index.
67  */
extractSubHalIndex(int32_t sensorHandle)68 size_t extractSubHalIndex(int32_t sensorHandle) {
69     return static_cast<size_t>(sensorHandle >> kBitsAfterSubHalIndex);
70 }
71 
72 /**
73  * Convert nanoseconds to milliseconds.
74  *
75  * @param nanos The nanoseconds input.
76  *
77  * @return The milliseconds count.
78  */
msFromNs(int64_t nanos)79 int64_t msFromNs(int64_t nanos) {
80     constexpr int64_t nanosecondsInAMillsecond = 1000000;
81     return nanos / nanosecondsInAMillsecond;
82 }
83 
HalProxy()84 HalProxy::HalProxy() {
85     const char* kMultiHalConfigFile = "/vendor/etc/sensors/hals.conf";
86     initializeSubHalListFromConfigFile(kMultiHalConfigFile);
87     init();
88 }
89 
HalProxy(std::vector<ISensorsSubHalV2_0 * > & subHalList)90 HalProxy::HalProxy(std::vector<ISensorsSubHalV2_0*>& subHalList) {
91     for (ISensorsSubHalV2_0* subHal : subHalList) {
92         mSubHalList.push_back(std::make_unique<SubHalWrapperV2_0>(subHal));
93     }
94 
95     init();
96 }
97 
HalProxy(std::vector<ISensorsSubHalV2_0 * > & subHalList,std::vector<ISensorsSubHalV2_1 * > & subHalListV2_1)98 HalProxy::HalProxy(std::vector<ISensorsSubHalV2_0*>& subHalList,
99                    std::vector<ISensorsSubHalV2_1*>& subHalListV2_1) {
100     for (ISensorsSubHalV2_0* subHal : subHalList) {
101         mSubHalList.push_back(std::make_unique<SubHalWrapperV2_0>(subHal));
102     }
103 
104     for (ISensorsSubHalV2_1* subHal : subHalListV2_1) {
105         mSubHalList.push_back(std::make_unique<SubHalWrapperV2_1>(subHal));
106     }
107 
108     init();
109 }
110 
~HalProxy()111 HalProxy::~HalProxy() {
112     stopThreads();
113 }
114 
getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb)115 Return<void> HalProxy::getSensorsList_2_1(ISensorsV2_1::getSensorsList_2_1_cb _hidl_cb) {
116     std::vector<V2_1::SensorInfo> sensors;
117     for (const auto& iter : mSensors) {
118         sensors.push_back(iter.second);
119     }
120     _hidl_cb(sensors);
121     return Void();
122 }
123 
getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb)124 Return<void> HalProxy::getSensorsList(ISensorsV2_0::getSensorsList_cb _hidl_cb) {
125     std::vector<V1_0::SensorInfo> sensors;
126     for (const auto& iter : mSensors) {
127         sensors.push_back(convertToOldSensorInfo(iter.second));
128     }
129     _hidl_cb(sensors);
130     return Void();
131 }
132 
setOperationMode(OperationMode mode)133 Return<Result> HalProxy::setOperationMode(OperationMode mode) {
134     Result result = Result::OK;
135     size_t subHalIndex;
136     for (subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
137         result = mSubHalList[subHalIndex]->setOperationMode(mode);
138         if (result != Result::OK) {
139             ALOGE("setOperationMode failed for SubHal: %s",
140                   mSubHalList[subHalIndex]->getName().c_str());
141             break;
142         }
143     }
144 
145     if (result != Result::OK) {
146         // Reset the subhal operation modes that have been flipped
147         for (size_t i = 0; i < subHalIndex; i++) {
148             mSubHalList[i]->setOperationMode(mCurrentOperationMode);
149         }
150     } else {
151         mCurrentOperationMode = mode;
152     }
153     return result;
154 }
155 
activate(int32_t sensorHandle,bool enabled)156 Return<Result> HalProxy::activate(int32_t sensorHandle, bool enabled) {
157     if (!isSubHalIndexValid(sensorHandle)) {
158         return Result::BAD_VALUE;
159     }
160     return getSubHalForSensorHandle(sensorHandle)
161             ->activate(clearSubHalIndex(sensorHandle), enabled);
162 }
163 
initialize_2_1(const::android::hardware::MQDescriptorSync<V2_1::Event> & eventQueueDescriptor,const::android::hardware::MQDescriptorSync<uint32_t> & wakeLockDescriptor,const sp<V2_1::ISensorsCallback> & sensorsCallback)164 Return<Result> HalProxy::initialize_2_1(
165         const ::android::hardware::MQDescriptorSync<V2_1::Event>& eventQueueDescriptor,
166         const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
167         const sp<V2_1::ISensorsCallback>& sensorsCallback) {
168     sp<ISensorsCallbackWrapperBase> dynamicCallback =
169             new ISensorsCallbackWrapperV2_1(sensorsCallback);
170 
171     // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
172     auto eventQueue =
173             std::make_unique<EventMessageQueueV2_1>(eventQueueDescriptor, true /* resetPointers */);
174     std::unique_ptr<EventMessageQueueWrapperBase> queue =
175             std::make_unique<EventMessageQueueWrapperV2_1>(eventQueue);
176 
177     return initializeCommon(queue, wakeLockDescriptor, dynamicCallback);
178 }
179 
initialize(const::android::hardware::MQDescriptorSync<V1_0::Event> & eventQueueDescriptor,const::android::hardware::MQDescriptorSync<uint32_t> & wakeLockDescriptor,const sp<V2_0::ISensorsCallback> & sensorsCallback)180 Return<Result> HalProxy::initialize(
181         const ::android::hardware::MQDescriptorSync<V1_0::Event>& eventQueueDescriptor,
182         const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
183         const sp<V2_0::ISensorsCallback>& sensorsCallback) {
184     sp<ISensorsCallbackWrapperBase> dynamicCallback =
185             new ISensorsCallbackWrapperV2_0(sensorsCallback);
186 
187     // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
188     auto eventQueue =
189             std::make_unique<EventMessageQueueV2_0>(eventQueueDescriptor, true /* resetPointers */);
190     std::unique_ptr<EventMessageQueueWrapperBase> queue =
191             std::make_unique<EventMessageQueueWrapperV1_0>(eventQueue);
192 
193     return initializeCommon(queue, wakeLockDescriptor, dynamicCallback);
194 }
195 
initializeCommon(std::unique_ptr<EventMessageQueueWrapperBase> & eventQueue,const::android::hardware::MQDescriptorSync<uint32_t> & wakeLockDescriptor,const sp<ISensorsCallbackWrapperBase> & sensorsCallback)196 Return<Result> HalProxy::initializeCommon(
197         std::unique_ptr<EventMessageQueueWrapperBase>& eventQueue,
198         const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
199         const sp<ISensorsCallbackWrapperBase>& sensorsCallback) {
200     Result result = Result::OK;
201 
202     stopThreads();
203     resetSharedWakelock();
204 
205     // So that the pending write events queue can be cleared safely and when we start threads
206     // again we do not get new events until after initialize resets the subhals.
207     disableAllSensors();
208 
209     // Clears the queue if any events were pending write before.
210     mPendingWriteEventsQueue = std::queue<std::pair<std::vector<V2_1::Event>, size_t>>();
211     mSizePendingWriteEventsQueue = 0;
212 
213     // Clears previously connected dynamic sensors
214     mDynamicSensors.clear();
215 
216     mDynamicSensorsCallback = sensorsCallback;
217 
218     // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
219     mEventQueue = std::move(eventQueue);
220 
221     // Create the Wake Lock FMQ that is used by the framework to communicate whenever WAKE_UP
222     // events have been successfully read and handled by the framework.
223     mWakeLockQueue =
224             std::make_unique<WakeLockMessageQueue>(wakeLockDescriptor, true /* resetPointers */);
225 
226     if (mEventQueueFlag != nullptr) {
227         EventFlag::deleteEventFlag(&mEventQueueFlag);
228     }
229     if (mWakelockQueueFlag != nullptr) {
230         EventFlag::deleteEventFlag(&mWakelockQueueFlag);
231     }
232     if (EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag) != OK) {
233         result = Result::BAD_VALUE;
234     }
235     if (EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakelockQueueFlag) != OK) {
236         result = Result::BAD_VALUE;
237     }
238     if (!mDynamicSensorsCallback || !mEventQueue || !mWakeLockQueue || mEventQueueFlag == nullptr) {
239         result = Result::BAD_VALUE;
240     }
241 
242     mThreadsRun.store(true);
243 
244     mPendingWritesThread = std::thread(startPendingWritesThread, this);
245     mWakelockThread = std::thread(startWakelockThread, this);
246 
247     for (size_t i = 0; i < mSubHalList.size(); i++) {
248         Result currRes = mSubHalList[i]->initialize(this, this, i);
249         if (currRes != Result::OK) {
250             result = currRes;
251             ALOGE("Subhal '%s' failed to initialize.", mSubHalList[i]->getName().c_str());
252             break;
253         }
254     }
255 
256     mCurrentOperationMode = OperationMode::NORMAL;
257 
258     return result;
259 }
260 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)261 Return<Result> HalProxy::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
262                                int64_t maxReportLatencyNs) {
263     if (!isSubHalIndexValid(sensorHandle)) {
264         return Result::BAD_VALUE;
265     }
266     return getSubHalForSensorHandle(sensorHandle)
267             ->batch(clearSubHalIndex(sensorHandle), samplingPeriodNs, maxReportLatencyNs);
268 }
269 
flush(int32_t sensorHandle)270 Return<Result> HalProxy::flush(int32_t sensorHandle) {
271     if (!isSubHalIndexValid(sensorHandle)) {
272         return Result::BAD_VALUE;
273     }
274     return getSubHalForSensorHandle(sensorHandle)->flush(clearSubHalIndex(sensorHandle));
275 }
276 
injectSensorData_2_1(const V2_1::Event & event)277 Return<Result> HalProxy::injectSensorData_2_1(const V2_1::Event& event) {
278     return injectSensorData(convertToOldEvent(event));
279 }
280 
injectSensorData(const V1_0::Event & event)281 Return<Result> HalProxy::injectSensorData(const V1_0::Event& event) {
282     Result result = Result::OK;
283     if (mCurrentOperationMode == OperationMode::NORMAL &&
284         event.sensorType != V1_0::SensorType::ADDITIONAL_INFO) {
285         ALOGE("An event with type != ADDITIONAL_INFO passed to injectSensorData while operation"
286               " mode was NORMAL.");
287         result = Result::BAD_VALUE;
288     }
289     if (result == Result::OK) {
290         V1_0::Event subHalEvent = event;
291         if (!isSubHalIndexValid(event.sensorHandle)) {
292             return Result::BAD_VALUE;
293         }
294         subHalEvent.sensorHandle = clearSubHalIndex(event.sensorHandle);
295         result = getSubHalForSensorHandle(event.sensorHandle)
296                          ->injectSensorData(convertToNewEvent(subHalEvent));
297     }
298     return result;
299 }
300 
registerDirectChannel(const SharedMemInfo & mem,ISensorsV2_0::registerDirectChannel_cb _hidl_cb)301 Return<void> HalProxy::registerDirectChannel(const SharedMemInfo& mem,
302                                              ISensorsV2_0::registerDirectChannel_cb _hidl_cb) {
303     if (mDirectChannelSubHal == nullptr) {
304         _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
305     } else {
306         mDirectChannelSubHal->registerDirectChannel(mem, _hidl_cb);
307     }
308     return Return<void>();
309 }
310 
unregisterDirectChannel(int32_t channelHandle)311 Return<Result> HalProxy::unregisterDirectChannel(int32_t channelHandle) {
312     Result result;
313     if (mDirectChannelSubHal == nullptr) {
314         result = Result::INVALID_OPERATION;
315     } else {
316         result = mDirectChannelSubHal->unregisterDirectChannel(channelHandle);
317     }
318     return result;
319 }
320 
configDirectReport(int32_t sensorHandle,int32_t channelHandle,RateLevel rate,ISensorsV2_0::configDirectReport_cb _hidl_cb)321 Return<void> HalProxy::configDirectReport(int32_t sensorHandle, int32_t channelHandle,
322                                           RateLevel rate,
323                                           ISensorsV2_0::configDirectReport_cb _hidl_cb) {
324     if (mDirectChannelSubHal == nullptr) {
325         _hidl_cb(Result::INVALID_OPERATION, -1 /* reportToken */);
326     } else if (sensorHandle == -1 && rate != RateLevel::STOP) {
327         _hidl_cb(Result::BAD_VALUE, -1 /* reportToken */);
328     } else {
329         // -1 denotes all sensors should be disabled
330         if (sensorHandle != -1) {
331             sensorHandle = clearSubHalIndex(sensorHandle);
332         }
333         mDirectChannelSubHal->configDirectReport(sensorHandle, channelHandle, rate, _hidl_cb);
334     }
335     return Return<void>();
336 }
337 
debug(const hidl_handle & fd,const hidl_vec<hidl_string> &)338 Return<void> HalProxy::debug(const hidl_handle& fd, const hidl_vec<hidl_string>& /*args*/) {
339     if (fd.getNativeHandle() == nullptr || fd->numFds < 1) {
340         ALOGE("%s: missing fd for writing", __FUNCTION__);
341         return Void();
342     }
343 
344     android::base::borrowed_fd writeFd = dup(fd->data[0]);
345 
346     std::ostringstream stream;
347     stream << "===HalProxy===" << std::endl;
348     stream << "Internal values:" << std::endl;
349     stream << "  Threads are running: " << (mThreadsRun.load() ? "true" : "false") << std::endl;
350     int64_t now = getTimeNow();
351     stream << "  Wakelock timeout start time: " << msFromNs(now - mWakelockTimeoutStartTime)
352            << " ms ago" << std::endl;
353     stream << "  Wakelock timeout reset time: " << msFromNs(now - mWakelockTimeoutResetTime)
354            << " ms ago" << std::endl;
355     // TODO(b/142969448): Add logging for history of wakelock acquisition per subhal.
356     stream << "  Wakelock ref count: " << mWakelockRefCount << std::endl;
357     stream << "  # of events on pending write writes queue: " << mSizePendingWriteEventsQueue
358            << std::endl;
359     stream << " Most events seen on pending write events queue: "
360            << mMostEventsObservedPendingWriteEventsQueue << std::endl;
361     if (!mPendingWriteEventsQueue.empty()) {
362         stream << "  Size of events list on front of pending writes queue: "
363                << mPendingWriteEventsQueue.front().first.size() << std::endl;
364     }
365     stream << "  # of non-dynamic sensors across all subhals: " << mSensors.size() << std::endl;
366     stream << "  # of dynamic sensors across all subhals: " << mDynamicSensors.size() << std::endl;
367     stream << "SubHals (" << mSubHalList.size() << "):" << std::endl;
368     for (auto& subHal : mSubHalList) {
369         stream << "  Name: " << subHal->getName() << std::endl;
370         stream << "  Debug dump: " << std::endl;
371         android::base::WriteStringToFd(stream.str(), writeFd);
372         subHal->debug(fd, {});
373         stream.str("");
374         stream << std::endl;
375     }
376     android::base::WriteStringToFd(stream.str(), writeFd);
377     return Return<void>();
378 }
379 
onDynamicSensorsConnected(const hidl_vec<SensorInfo> & dynamicSensorsAdded,int32_t subHalIndex)380 Return<void> HalProxy::onDynamicSensorsConnected(const hidl_vec<SensorInfo>& dynamicSensorsAdded,
381                                                  int32_t subHalIndex) {
382     std::vector<SensorInfo> sensors;
383     {
384         std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
385         for (SensorInfo sensor : dynamicSensorsAdded) {
386             if (!subHalIndexIsClear(sensor.sensorHandle)) {
387                 ALOGE("Dynamic sensor added %s had sensorHandle with first byte not 0.",
388                       sensor.name.c_str());
389             } else {
390                 sensor.sensorHandle = setSubHalIndex(sensor.sensorHandle, subHalIndex);
391                 mDynamicSensors[sensor.sensorHandle] = sensor;
392                 sensors.push_back(sensor);
393             }
394         }
395     }
396     mDynamicSensorsCallback->onDynamicSensorsConnected(sensors);
397     return Return<void>();
398 }
399 
onDynamicSensorsDisconnected(const hidl_vec<int32_t> & dynamicSensorHandlesRemoved,int32_t subHalIndex)400 Return<void> HalProxy::onDynamicSensorsDisconnected(
401         const hidl_vec<int32_t>& dynamicSensorHandlesRemoved, int32_t subHalIndex) {
402     // TODO(b/143302327): Block this call until all pending events are flushed from queue
403     std::vector<int32_t> sensorHandles;
404     {
405         std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
406         for (int32_t sensorHandle : dynamicSensorHandlesRemoved) {
407             if (!subHalIndexIsClear(sensorHandle)) {
408                 ALOGE("Dynamic sensorHandle removed had first byte not 0.");
409             } else {
410                 sensorHandle = setSubHalIndex(sensorHandle, subHalIndex);
411                 if (mDynamicSensors.find(sensorHandle) != mDynamicSensors.end()) {
412                     mDynamicSensors.erase(sensorHandle);
413                     sensorHandles.push_back(sensorHandle);
414                 }
415             }
416         }
417     }
418     mDynamicSensorsCallback->onDynamicSensorsDisconnected(sensorHandles);
419     return Return<void>();
420 }
421 
initializeSubHalListFromConfigFile(const char * configFileName)422 void HalProxy::initializeSubHalListFromConfigFile(const char* configFileName) {
423     std::ifstream subHalConfigStream(configFileName);
424     if (!subHalConfigStream) {
425         ALOGE("Failed to load subHal config file: %s", configFileName);
426     } else {
427         std::string subHalLibraryFile;
428         while (subHalConfigStream >> subHalLibraryFile) {
429             void* handle = getHandleForSubHalSharedObject(subHalLibraryFile);
430             if (handle == nullptr) {
431                 ALOGE("dlopen failed for library: %s", subHalLibraryFile.c_str());
432             } else {
433                 SensorsHalGetSubHalFunc* sensorsHalGetSubHalPtr =
434                         (SensorsHalGetSubHalFunc*)dlsym(handle, "sensorsHalGetSubHal");
435                 if (sensorsHalGetSubHalPtr != nullptr) {
436                     std::function<SensorsHalGetSubHalFunc> sensorsHalGetSubHal =
437                             *sensorsHalGetSubHalPtr;
438                     uint32_t version;
439                     ISensorsSubHalV2_0* subHal = sensorsHalGetSubHal(&version);
440                     if (version != SUB_HAL_2_0_VERSION) {
441                         ALOGE("SubHal version was not 2.0 for library: %s",
442                               subHalLibraryFile.c_str());
443                     } else {
444                         ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
445                         mSubHalList.push_back(std::make_unique<SubHalWrapperV2_0>(subHal));
446                     }
447                 } else {
448                     SensorsHalGetSubHalV2_1Func* getSubHalV2_1Ptr =
449                             (SensorsHalGetSubHalV2_1Func*)dlsym(handle, "sensorsHalGetSubHal_2_1");
450 
451                     if (getSubHalV2_1Ptr == nullptr) {
452                         ALOGE("Failed to locate sensorsHalGetSubHal function for library: %s",
453                               subHalLibraryFile.c_str());
454                     } else {
455                         std::function<SensorsHalGetSubHalV2_1Func> sensorsHalGetSubHal_2_1 =
456                                 *getSubHalV2_1Ptr;
457                         uint32_t version;
458                         ISensorsSubHalV2_1* subHal = sensorsHalGetSubHal_2_1(&version);
459                         if (version != SUB_HAL_2_1_VERSION) {
460                             ALOGE("SubHal version was not 2.1 for library: %s",
461                                   subHalLibraryFile.c_str());
462                         } else {
463                             ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
464                             mSubHalList.push_back(std::make_unique<SubHalWrapperV2_1>(subHal));
465                         }
466                     }
467                 }
468             }
469         }
470     }
471 }
472 
initializeSensorList()473 void HalProxy::initializeSensorList() {
474     for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
475         auto result = mSubHalList[subHalIndex]->getSensorsList([&](const auto& list) {
476             for (SensorInfo sensor : list) {
477                 if (!subHalIndexIsClear(sensor.sensorHandle)) {
478                     ALOGE("SubHal sensorHandle's first byte was not 0");
479                 } else {
480                     ALOGV("Loaded sensor: %s", sensor.name.c_str());
481                     sensor.sensorHandle = setSubHalIndex(sensor.sensorHandle, subHalIndex);
482                     setDirectChannelFlags(&sensor, mSubHalList[subHalIndex]);
483                     mSensors[sensor.sensorHandle] = sensor;
484                 }
485             }
486         });
487         if (!result.isOk()) {
488             ALOGE("getSensorsList call failed for SubHal: %s",
489                   mSubHalList[subHalIndex]->getName().c_str());
490         }
491     }
492 }
493 
getHandleForSubHalSharedObject(const std::string & filename)494 void* HalProxy::getHandleForSubHalSharedObject(const std::string& filename) {
495     static const std::string kSubHalShareObjectLocations[] = {
496             "",  // Default locations will be searched
497 #ifdef __LP64__
498             "/vendor/lib64/hw/", "/odm/lib64/hw/"
499 #else
500             "/vendor/lib/hw/", "/odm/lib/hw/"
501 #endif
502     };
503 
504     for (const std::string& dir : kSubHalShareObjectLocations) {
505         void* handle = dlopen((dir + filename).c_str(), RTLD_NOW);
506         if (handle != nullptr) {
507             return handle;
508         }
509     }
510     return nullptr;
511 }
512 
init()513 void HalProxy::init() {
514     initializeSensorList();
515 }
516 
stopThreads()517 void HalProxy::stopThreads() {
518     mThreadsRun.store(false);
519     if (mEventQueueFlag != nullptr && mEventQueue != nullptr) {
520         size_t numToRead = mEventQueue->availableToRead();
521         std::vector<Event> events(numToRead);
522         mEventQueue->read(events.data(), numToRead);
523         mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::EVENTS_READ));
524     }
525     if (mWakelockQueueFlag != nullptr && mWakeLockQueue != nullptr) {
526         uint32_t kZero = 0;
527         mWakeLockQueue->write(&kZero);
528         mWakelockQueueFlag->wake(static_cast<uint32_t>(WakeLockQueueFlagBits::DATA_WRITTEN));
529     }
530     mWakelockCV.notify_one();
531     mEventQueueWriteCV.notify_one();
532     if (mPendingWritesThread.joinable()) {
533         mPendingWritesThread.join();
534     }
535     if (mWakelockThread.joinable()) {
536         mWakelockThread.join();
537     }
538 }
539 
disableAllSensors()540 void HalProxy::disableAllSensors() {
541     for (const auto& sensorEntry : mSensors) {
542         int32_t sensorHandle = sensorEntry.first;
543         activate(sensorHandle, false /* enabled */);
544     }
545     std::lock_guard<std::mutex> dynamicSensorsLock(mDynamicSensorsMutex);
546     for (const auto& sensorEntry : mDynamicSensors) {
547         int32_t sensorHandle = sensorEntry.first;
548         activate(sensorHandle, false /* enabled */);
549     }
550 }
551 
startPendingWritesThread(HalProxy * halProxy)552 void HalProxy::startPendingWritesThread(HalProxy* halProxy) {
553     halProxy->handlePendingWrites();
554 }
555 
handlePendingWrites()556 void HalProxy::handlePendingWrites() {
557     // TODO(b/143302327): Find a way to optimize locking strategy maybe using two mutexes instead of
558     // one.
559     std::unique_lock<std::mutex> lock(mEventQueueWriteMutex);
560     while (mThreadsRun.load()) {
561         mEventQueueWriteCV.wait(
562                 lock, [&] { return !mPendingWriteEventsQueue.empty() || !mThreadsRun.load(); });
563         if (mThreadsRun.load()) {
564             std::vector<Event>& pendingWriteEvents = mPendingWriteEventsQueue.front().first;
565             size_t numWakeupEvents = mPendingWriteEventsQueue.front().second;
566             size_t eventQueueSize = mEventQueue->getQuantumCount();
567             size_t numToWrite = std::min(pendingWriteEvents.size(), eventQueueSize);
568             lock.unlock();
569             if (!mEventQueue->writeBlocking(
570                         pendingWriteEvents.data(), numToWrite,
571                         static_cast<uint32_t>(EventQueueFlagBits::EVENTS_READ),
572                         static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS),
573                         kPendingWriteTimeoutNs, mEventQueueFlag)) {
574                 ALOGE("Dropping %zu events after blockingWrite failed.", numToWrite);
575                 if (numWakeupEvents > 0) {
576                     if (pendingWriteEvents.size() > eventQueueSize) {
577                         decrementRefCountAndMaybeReleaseWakelock(
578                                 countNumWakeupEvents(pendingWriteEvents, eventQueueSize));
579                     } else {
580                         decrementRefCountAndMaybeReleaseWakelock(numWakeupEvents);
581                     }
582                 }
583             }
584             lock.lock();
585             mSizePendingWriteEventsQueue -= numToWrite;
586             if (pendingWriteEvents.size() > eventQueueSize) {
587                 // TODO(b/143302327): Check if this erase operation is too inefficient. It will copy
588                 // all the events ahead of it down to fill gap off array at front after the erase.
589                 pendingWriteEvents.erase(pendingWriteEvents.begin(),
590                                          pendingWriteEvents.begin() + eventQueueSize);
591             } else {
592                 mPendingWriteEventsQueue.pop();
593             }
594         }
595     }
596 }
597 
startWakelockThread(HalProxy * halProxy)598 void HalProxy::startWakelockThread(HalProxy* halProxy) {
599     halProxy->handleWakelocks();
600 }
601 
handleWakelocks()602 void HalProxy::handleWakelocks() {
603     std::unique_lock<std::recursive_mutex> lock(mWakelockMutex);
604     while (mThreadsRun.load()) {
605         mWakelockCV.wait(lock, [&] { return mWakelockRefCount > 0 || !mThreadsRun.load(); });
606         if (mThreadsRun.load()) {
607             int64_t timeLeft;
608             if (sharedWakelockDidTimeout(&timeLeft)) {
609                 resetSharedWakelock();
610             } else {
611                 uint32_t numWakeLocksProcessed;
612                 lock.unlock();
613                 bool success = mWakeLockQueue->readBlocking(
614                         &numWakeLocksProcessed, 1, 0,
615                         static_cast<uint32_t>(WakeLockQueueFlagBits::DATA_WRITTEN), timeLeft);
616                 lock.lock();
617                 if (success) {
618                     decrementRefCountAndMaybeReleaseWakelock(
619                             static_cast<size_t>(numWakeLocksProcessed));
620                 }
621             }
622         }
623     }
624     resetSharedWakelock();
625 }
626 
sharedWakelockDidTimeout(int64_t * timeLeft)627 bool HalProxy::sharedWakelockDidTimeout(int64_t* timeLeft) {
628     bool didTimeout;
629     int64_t duration = getTimeNow() - mWakelockTimeoutStartTime;
630     if (duration > kWakelockTimeoutNs) {
631         didTimeout = true;
632     } else {
633         didTimeout = false;
634         *timeLeft = kWakelockTimeoutNs - duration;
635     }
636     return didTimeout;
637 }
638 
resetSharedWakelock()639 void HalProxy::resetSharedWakelock() {
640     std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
641     decrementRefCountAndMaybeReleaseWakelock(mWakelockRefCount);
642     mWakelockTimeoutResetTime = getTimeNow();
643 }
644 
postEventsToMessageQueue(const std::vector<Event> & events,size_t numWakeupEvents,V2_0::implementation::ScopedWakelock wakelock)645 void HalProxy::postEventsToMessageQueue(const std::vector<Event>& events, size_t numWakeupEvents,
646                                         V2_0::implementation::ScopedWakelock wakelock) {
647     size_t numToWrite = 0;
648     std::lock_guard<std::mutex> lock(mEventQueueWriteMutex);
649     if (wakelock.isLocked()) {
650         incrementRefCountAndMaybeAcquireWakelock(numWakeupEvents);
651     }
652     if (mPendingWriteEventsQueue.empty()) {
653         numToWrite = std::min(events.size(), mEventQueue->availableToWrite());
654         if (numToWrite > 0) {
655             if (mEventQueue->write(events.data(), numToWrite)) {
656                 // TODO(b/143302327): While loop if mEventQueue->avaiableToWrite > 0 to possibly fit
657                 // in more writes immediately
658                 mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
659             } else {
660                 numToWrite = 0;
661             }
662         }
663     }
664     size_t numLeft = events.size() - numToWrite;
665     if (numToWrite < events.size() &&
666         mSizePendingWriteEventsQueue + numLeft <= kMaxSizePendingWriteEventsQueue) {
667         std::vector<Event> eventsLeft(events.begin() + numToWrite, events.end());
668         mPendingWriteEventsQueue.push({eventsLeft, numWakeupEvents});
669         mSizePendingWriteEventsQueue += numLeft;
670         mMostEventsObservedPendingWriteEventsQueue =
671                 std::max(mMostEventsObservedPendingWriteEventsQueue, mSizePendingWriteEventsQueue);
672         mEventQueueWriteCV.notify_one();
673     }
674 }
675 
incrementRefCountAndMaybeAcquireWakelock(size_t delta,int64_t * timeoutStart)676 bool HalProxy::incrementRefCountAndMaybeAcquireWakelock(size_t delta,
677                                                         int64_t* timeoutStart /* = nullptr */) {
678     if (!mThreadsRun.load()) return false;
679     std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
680     if (mWakelockRefCount == 0) {
681         acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakelockName);
682         mWakelockCV.notify_one();
683     }
684     mWakelockTimeoutStartTime = getTimeNow();
685     mWakelockRefCount += delta;
686     if (timeoutStart != nullptr) {
687         *timeoutStart = mWakelockTimeoutStartTime;
688     }
689     return true;
690 }
691 
decrementRefCountAndMaybeReleaseWakelock(size_t delta,int64_t timeoutStart)692 void HalProxy::decrementRefCountAndMaybeReleaseWakelock(size_t delta,
693                                                         int64_t timeoutStart /* = -1 */) {
694     if (!mThreadsRun.load()) return;
695     std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
696     if (timeoutStart == -1) timeoutStart = mWakelockTimeoutResetTime;
697     if (mWakelockRefCount == 0 || timeoutStart < mWakelockTimeoutResetTime) return;
698     mWakelockRefCount -= std::min(mWakelockRefCount, delta);
699     if (mWakelockRefCount == 0) {
700         release_wake_lock(kWakelockName);
701     }
702 }
703 
setDirectChannelFlags(SensorInfo * sensorInfo,std::shared_ptr<ISubHalWrapperBase> subHal)704 void HalProxy::setDirectChannelFlags(SensorInfo* sensorInfo,
705                                      std::shared_ptr<ISubHalWrapperBase> subHal) {
706     bool sensorSupportsDirectChannel =
707             (sensorInfo->flags & (V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
708                                   V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL)) != 0;
709     if (mDirectChannelSubHal == nullptr && sensorSupportsDirectChannel) {
710         mDirectChannelSubHal = subHal;
711     } else if (mDirectChannelSubHal != nullptr && subHal != mDirectChannelSubHal) {
712         // disable direct channel capability for sensors in subHals that are not
713         // the only one we will enable
714         sensorInfo->flags &= ~(V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
715                                V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL);
716     }
717 }
718 
getSubHalForSensorHandle(int32_t sensorHandle)719 std::shared_ptr<ISubHalWrapperBase> HalProxy::getSubHalForSensorHandle(int32_t sensorHandle) {
720     return mSubHalList[extractSubHalIndex(sensorHandle)];
721 }
722 
isSubHalIndexValid(int32_t sensorHandle)723 bool HalProxy::isSubHalIndexValid(int32_t sensorHandle) {
724     return extractSubHalIndex(sensorHandle) < mSubHalList.size();
725 }
726 
countNumWakeupEvents(const std::vector<Event> & events,size_t n)727 size_t HalProxy::countNumWakeupEvents(const std::vector<Event>& events, size_t n) {
728     size_t numWakeupEvents = 0;
729     for (size_t i = 0; i < n; i++) {
730         int32_t sensorHandle = events[i].sensorHandle;
731         if (mSensors[sensorHandle].flags & static_cast<uint32_t>(V1_0::SensorFlagBits::WAKE_UP)) {
732             numWakeupEvents++;
733         }
734     }
735     return numWakeupEvents;
736 }
737 
clearSubHalIndex(int32_t sensorHandle)738 int32_t HalProxy::clearSubHalIndex(int32_t sensorHandle) {
739     return sensorHandle & (~kSensorHandleSubHalIndexMask);
740 }
741 
subHalIndexIsClear(int32_t sensorHandle)742 bool HalProxy::subHalIndexIsClear(int32_t sensorHandle) {
743     return (sensorHandle & kSensorHandleSubHalIndexMask) == 0;
744 }
745 
746 }  // namespace implementation
747 }  // namespace V2_1
748 }  // namespace sensors
749 }  // namespace hardware
750 }  // namespace android
751