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