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