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