blob: d66721866c5939b1651889fb94fa19bc03d8dafa [file] [log] [blame]
Anthony Stangea689f8a2019-07-30 11:35:48 -04001/*
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
Stan Rokita537c0272019-09-13 10:36:07 -070019#include "SubHal.h"
20
Anthony Stangea689f8a2019-07-30 11:35:48 -040021#include <android/hardware/sensors/2.0/types.h>
22
Stan Rokitad0cd57d2019-09-17 15:52:51 -070023#include "hardware_legacy/power.h"
24
Stan Rokita28790672019-08-20 14:32:15 -070025#include <dlfcn.h>
26
Stan Rokita75cc7bf2019-09-26 13:17:01 -070027#include <cinttypes>
Stan Rokita28790672019-08-20 14:32:15 -070028#include <fstream>
29#include <functional>
Stan Rokita537c0272019-09-13 10:36:07 -070030#include <thread>
Stan Rokita28790672019-08-20 14:32:15 -070031
Anthony Stangea689f8a2019-07-30 11:35:48 -040032namespace android {
33namespace hardware {
34namespace sensors {
35namespace V2_0 {
36namespace implementation {
37
Stan Rokita537c0272019-09-13 10:36:07 -070038using ::android::hardware::sensors::V2_0::EventQueueFlagBits;
Stan Rokita75cc7bf2019-09-26 13:17:01 -070039using ::android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
40using ::android::hardware::sensors::V2_0::implementation::getTimeNow;
41using ::android::hardware::sensors::V2_0::implementation::kWakelockTimeoutNs;
Stan Rokita537c0272019-09-13 10:36:07 -070042
Stan Rokita28790672019-08-20 14:32:15 -070043typedef ISensorsSubHal*(SensorsHalGetSubHalFunc)(uint32_t*);
44
Stan Rokitae93fdf92019-09-24 11:58:51 -070045/**
46 * Set the subhal index as first byte of sensor handle and return this modified version.
47 *
48 * @param sensorHandle The sensor handle to modify.
49 * @param subHalIndex The index in the hal proxy of the sub hal this sensor belongs to.
50 *
51 * @return The modified sensor handle.
52 */
53uint32_t setSubHalIndex(uint32_t sensorHandle, size_t subHalIndex) {
54 return sensorHandle | (subHalIndex << 24);
55}
56
Anthony Stangea689f8a2019-07-30 11:35:48 -040057HalProxy::HalProxy() {
Stan Rokita7a723542019-08-29 15:47:50 -070058 const char* kMultiHalConfigFile = "/vendor/etc/sensors/hals.conf";
59 initializeSubHalListFromConfigFile(kMultiHalConfigFile);
Stan Rokita75cc7bf2019-09-26 13:17:01 -070060 init();
Anthony Stangea689f8a2019-07-30 11:35:48 -040061}
62
Anthony Stangeaacbf942019-08-30 15:21:34 -040063HalProxy::HalProxy(std::vector<ISensorsSubHal*>& subHalList) : mSubHalList(subHalList) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -070064 init();
Anthony Stangeaacbf942019-08-30 15:21:34 -040065}
66
Anthony Stangea689f8a2019-07-30 11:35:48 -040067HalProxy::~HalProxy() {
Stan Rokita75cc7bf2019-09-26 13:17:01 -070068 mThreadsRun.store(false);
69 mWakelockCV.notify_one();
70 mEventQueueWriteCV.notify_one();
Stan Rokita59714262019-09-20 10:55:30 -070071 if (mPendingWritesThread.joinable()) {
72 mPendingWritesThread.join();
73 }
Stan Rokita75cc7bf2019-09-26 13:17:01 -070074 if (mWakelockThread.joinable()) {
75 mWakelockThread.join();
76 }
Anthony Stangea689f8a2019-07-30 11:35:48 -040077}
78
Stan Rokitadc7a8e72019-08-23 12:35:40 -070079Return<void> HalProxy::getSensorsList(getSensorsList_cb _hidl_cb) {
Stan Rokita537c0272019-09-13 10:36:07 -070080 std::vector<SensorInfo> sensors;
81 for (const auto& iter : mSensors) {
82 sensors.push_back(iter.second);
83 }
84 _hidl_cb(sensors);
Anthony Stangea689f8a2019-07-30 11:35:48 -040085 return Void();
86}
87
Stan Rokita7a723542019-08-29 15:47:50 -070088Return<Result> HalProxy::setOperationMode(OperationMode mode) {
89 Result result = Result::OK;
90 size_t subHalIndex;
91 for (subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
92 ISensorsSubHal* subHal = mSubHalList[subHalIndex];
93 result = subHal->setOperationMode(mode);
94 if (result != Result::OK) {
95 ALOGE("setOperationMode failed for SubHal: %s", subHal->getName().c_str());
96 break;
97 }
98 }
99 if (result != Result::OK) {
100 // Reset the subhal operation modes that have been flipped
101 for (size_t i = 0; i < subHalIndex; i++) {
102 ISensorsSubHal* subHal = mSubHalList[i];
103 subHal->setOperationMode(mCurrentOperationMode);
104 }
105 } else {
106 mCurrentOperationMode = mode;
107 }
108 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -0400109}
110
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700111Return<Result> HalProxy::activate(int32_t sensorHandle, bool enabled) {
112 return getSubHalForSensorHandle(sensorHandle)
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700113 ->activate(clearSubHalIndex(sensorHandle), enabled);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400114}
115
116Return<Result> HalProxy::initialize(
117 const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
118 const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
119 const sp<ISensorsCallback>& sensorsCallback) {
120 Result result = Result::OK;
121
122 // TODO: clean up sensor requests, if not already done elsewhere through a death recipient, and
123 // clean up any other resources that exist (FMQs, flags, threads, etc.)
124
125 mDynamicSensorsCallback = sensorsCallback;
126
127 // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
128 mEventQueue =
129 std::make_unique<EventMessageQueue>(eventQueueDescriptor, true /* resetPointers */);
130
131 // Create the EventFlag that is used to signal to the framework that sensor events have been
132 // written to the Event FMQ
133 if (EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag) != OK) {
134 result = Result::BAD_VALUE;
135 }
136
137 // Create the Wake Lock FMQ that is used by the framework to communicate whenever WAKE_UP
138 // events have been successfully read and handled by the framework.
139 mWakeLockQueue =
140 std::make_unique<WakeLockMessageQueue>(wakeLockDescriptor, true /* resetPointers */);
141
142 if (!mDynamicSensorsCallback || !mEventQueue || !mWakeLockQueue || mEventQueueFlag == nullptr) {
143 result = Result::BAD_VALUE;
144 }
145
Stan Rokita59714262019-09-20 10:55:30 -0700146 mPendingWritesThread = std::thread(startPendingWritesThread, this);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700147 mWakelockThread = std::thread(startWakelockThread, this);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400148
Stan Rokita537c0272019-09-13 10:36:07 -0700149 for (size_t i = 0; i < mSubHalList.size(); i++) {
150 auto subHal = mSubHalList[i];
151 const auto& subHalCallback = mSubHalCallbacks[i];
152 Result currRes = subHal->initialize(subHalCallback);
153 if (currRes != Result::OK) {
154 result = currRes;
155 ALOGE("Subhal '%s' failed to initialize.", subHal->getName().c_str());
156 break;
157 }
158 }
159
Anthony Stangea689f8a2019-07-30 11:35:48 -0400160 return result;
161}
162
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700163Return<Result> HalProxy::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
164 int64_t maxReportLatencyNs) {
165 return getSubHalForSensorHandle(sensorHandle)
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700166 ->batch(clearSubHalIndex(sensorHandle), samplingPeriodNs, maxReportLatencyNs);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400167}
168
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700169Return<Result> HalProxy::flush(int32_t sensorHandle) {
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700170 return getSubHalForSensorHandle(sensorHandle)->flush(clearSubHalIndex(sensorHandle));
Anthony Stangea689f8a2019-07-30 11:35:48 -0400171}
172
Stan Rokita83e43702019-09-24 10:16:08 -0700173Return<Result> HalProxy::injectSensorData(const Event& event) {
174 Result result = Result::OK;
175 if (mCurrentOperationMode == OperationMode::NORMAL &&
176 event.sensorType != V1_0::SensorType::ADDITIONAL_INFO) {
177 ALOGE("An event with type != ADDITIONAL_INFO passed to injectSensorData while operation"
178 " mode was NORMAL.");
179 result = Result::BAD_VALUE;
180 }
181 if (result == Result::OK) {
182 Event subHalEvent = event;
183 subHalEvent.sensorHandle = clearSubHalIndex(event.sensorHandle);
184 result = getSubHalForSensorHandle(event.sensorHandle)->injectSensorData(subHalEvent);
185 }
186 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -0400187}
188
Stan Rokitadb23aa82019-09-24 11:08:27 -0700189Return<void> HalProxy::registerDirectChannel(const SharedMemInfo& mem,
Anthony Stangea689f8a2019-07-30 11:35:48 -0400190 registerDirectChannel_cb _hidl_cb) {
Stan Rokitadb23aa82019-09-24 11:08:27 -0700191 if (mDirectChannelSubHal == nullptr) {
192 _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
193 } else {
194 mDirectChannelSubHal->registerDirectChannel(mem, _hidl_cb);
195 }
Anthony Stangea689f8a2019-07-30 11:35:48 -0400196 return Return<void>();
197}
198
Stan Rokitadb23aa82019-09-24 11:08:27 -0700199Return<Result> HalProxy::unregisterDirectChannel(int32_t channelHandle) {
200 Result result;
201 if (mDirectChannelSubHal == nullptr) {
202 result = Result::INVALID_OPERATION;
203 } else {
204 result = mDirectChannelSubHal->unregisterDirectChannel(channelHandle);
205 }
206 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -0400207}
208
Stan Rokitadb23aa82019-09-24 11:08:27 -0700209Return<void> HalProxy::configDirectReport(int32_t sensorHandle, int32_t channelHandle,
210 RateLevel rate, configDirectReport_cb _hidl_cb) {
211 if (mDirectChannelSubHal == nullptr) {
212 _hidl_cb(Result::INVALID_OPERATION, -1 /* reportToken */);
213 } else {
214 mDirectChannelSubHal->configDirectReport(clearSubHalIndex(sensorHandle), channelHandle,
215 rate, _hidl_cb);
216 }
Anthony Stangea689f8a2019-07-30 11:35:48 -0400217 return Return<void>();
218}
219
220Return<void> HalProxy::debug(const hidl_handle& /* fd */, const hidl_vec<hidl_string>& /* args */) {
221 // TODO: output debug information
222 return Return<void>();
223}
224
Stan Rokitae93fdf92019-09-24 11:58:51 -0700225Return<void> HalProxy::onDynamicSensorsConnected(const hidl_vec<SensorInfo>& dynamicSensorsAdded,
226 int32_t subHalIndex) {
227 std::vector<SensorInfo> sensors;
228 {
229 std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
230 for (SensorInfo sensor : dynamicSensorsAdded) {
231 if (!subHalIndexIsClear(sensor.sensorHandle)) {
232 ALOGE("Dynamic sensor added %s had sensorHandle with first byte not 0.",
233 sensor.name.c_str());
234 } else {
235 sensor.sensorHandle = setSubHalIndex(sensor.sensorHandle, subHalIndex);
236 mDynamicSensors[sensor.sensorHandle] = sensor;
237 sensors.push_back(sensor);
238 }
239 }
240 }
241 mDynamicSensorsCallback->onDynamicSensorsConnected(sensors);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400242 return Return<void>();
243}
244
245Return<void> HalProxy::onDynamicSensorsDisconnected(
Stan Rokitae93fdf92019-09-24 11:58:51 -0700246 const hidl_vec<int32_t>& dynamicSensorHandlesRemoved, int32_t subHalIndex) {
247 // TODO: Block this call until all pending events are flushed from queue
248 std::vector<int32_t> sensorHandles;
249 {
250 std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
251 for (int32_t sensorHandle : dynamicSensorHandlesRemoved) {
252 if (!subHalIndexIsClear(sensorHandle)) {
253 ALOGE("Dynamic sensorHandle removed had first byte not 0.");
254 } else {
255 sensorHandle = setSubHalIndex(sensorHandle, subHalIndex);
256 if (mDynamicSensors.find(sensorHandle) != mDynamicSensors.end()) {
257 mDynamicSensors.erase(sensorHandle);
258 sensorHandles.push_back(sensorHandle);
259 }
260 }
261 }
262 }
263 mDynamicSensorsCallback->onDynamicSensorsDisconnected(sensorHandles);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400264 return Return<void>();
265}
266
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700267void HalProxy::initializeSubHalListFromConfigFile(const char* configFileName) {
268 std::ifstream subHalConfigStream(configFileName);
269 if (!subHalConfigStream) {
Stan Rokita7a723542019-08-29 15:47:50 -0700270 ALOGE("Failed to load subHal config file: %s", configFileName);
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700271 } else {
272 std::string subHalLibraryFile;
273 while (subHalConfigStream >> subHalLibraryFile) {
274 void* handle = dlopen(subHalLibraryFile.c_str(), RTLD_NOW);
275 if (handle == nullptr) {
Stan Rokita7a723542019-08-29 15:47:50 -0700276 ALOGE("dlopen failed for library: %s", subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700277 } else {
278 SensorsHalGetSubHalFunc* sensorsHalGetSubHalPtr =
279 (SensorsHalGetSubHalFunc*)dlsym(handle, "sensorsHalGetSubHal");
280 if (sensorsHalGetSubHalPtr == nullptr) {
Stan Rokita7a723542019-08-29 15:47:50 -0700281 ALOGE("Failed to locate sensorsHalGetSubHal function for library: %s",
282 subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700283 } else {
284 std::function<SensorsHalGetSubHalFunc> sensorsHalGetSubHal =
285 *sensorsHalGetSubHalPtr;
286 uint32_t version;
287 ISensorsSubHal* subHal = sensorsHalGetSubHal(&version);
288 if (version != SUB_HAL_2_0_VERSION) {
Stan Rokita7a723542019-08-29 15:47:50 -0700289 ALOGE("SubHal version was not 2.0 for library: %s",
290 subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700291 } else {
292 ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
293 mSubHalList.push_back(subHal);
294 }
295 }
296 }
297 }
298 }
299}
300
Stan Rokita537c0272019-09-13 10:36:07 -0700301void HalProxy::initializeSubHalCallbacks() {
302 for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
303 sp<IHalProxyCallback> callback = new HalProxyCallback(this, subHalIndex);
304 mSubHalCallbacks.push_back(callback);
305 }
306}
307
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700308void HalProxy::initializeSensorList() {
309 for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
310 ISensorsSubHal* subHal = mSubHalList[subHalIndex];
311 auto result = subHal->getSensorsList([&](const auto& list) {
312 for (SensorInfo sensor : list) {
Stan Rokitae93fdf92019-09-24 11:58:51 -0700313 if (!subHalIndexIsClear(sensor.sensorHandle)) {
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700314 ALOGE("SubHal sensorHandle's first byte was not 0");
315 } else {
316 ALOGV("Loaded sensor: %s", sensor.name.c_str());
317 sensor.sensorHandle |= (subHalIndex << 24);
Stan Rokita7a723542019-08-29 15:47:50 -0700318 setDirectChannelFlags(&sensor, subHal);
Stan Rokita537c0272019-09-13 10:36:07 -0700319 mSensors[sensor.sensorHandle] = sensor;
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700320 }
321 }
322 });
323 if (!result.isOk()) {
324 ALOGE("getSensorsList call failed for SubHal: %s", subHal->getName().c_str());
325 }
326 }
327}
328
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700329void HalProxy::init() {
Stan Rokita537c0272019-09-13 10:36:07 -0700330 initializeSubHalCallbacks();
331 initializeSensorList();
332}
333
Stan Rokita59714262019-09-20 10:55:30 -0700334void HalProxy::startPendingWritesThread(HalProxy* halProxy) {
335 halProxy->handlePendingWrites();
336}
337
338void HalProxy::handlePendingWrites() {
339 // TODO: Find a way to optimize locking strategy maybe using two mutexes instead of one.
340 std::unique_lock<std::mutex> lock(mEventQueueWriteMutex);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700341 while (mThreadsRun.load()) {
Stan Rokita59714262019-09-20 10:55:30 -0700342 mEventQueueWriteCV.wait(
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700343 lock, [&] { return !mPendingWriteEventsQueue.empty() || !mThreadsRun.load(); });
344 if (mThreadsRun.load()) {
345 std::vector<Event>& pendingWriteEvents = mPendingWriteEventsQueue.front().first;
346 size_t numWakeupEvents = mPendingWriteEventsQueue.front().second;
Stan Rokita59714262019-09-20 10:55:30 -0700347 size_t eventQueueSize = mEventQueue->getQuantumCount();
348 size_t numToWrite = std::min(pendingWriteEvents.size(), eventQueueSize);
349 lock.unlock();
350 // TODO: Find a way to interrup writeBlocking if the thread should exit
351 // so we don't have to wait for timeout on framework restarts.
352 if (!mEventQueue->writeBlocking(
353 pendingWriteEvents.data(), numToWrite,
354 static_cast<uint32_t>(EventQueueFlagBits::EVENTS_READ),
355 static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS),
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700356 kPendingWriteTimeoutNs, mEventQueueFlag)) {
Stan Rokita59714262019-09-20 10:55:30 -0700357 ALOGE("Dropping %zu events after blockingWrite failed.", numToWrite);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700358 if (numWakeupEvents > 0) {
359 if (pendingWriteEvents.size() > eventQueueSize) {
360 decrementRefCountAndMaybeReleaseWakelock(
361 countNumWakeupEvents(pendingWriteEvents, eventQueueSize));
362 } else {
363 decrementRefCountAndMaybeReleaseWakelock(numWakeupEvents);
364 }
365 }
Stan Rokita59714262019-09-20 10:55:30 -0700366 }
367 lock.lock();
368 if (pendingWriteEvents.size() > eventQueueSize) {
369 // TODO: Check if this erase operation is too inefficient. It will copy all the
370 // events ahead of it down to fill gap off array at front after the erase.
371 pendingWriteEvents.erase(pendingWriteEvents.begin(),
372 pendingWriteEvents.begin() + eventQueueSize);
373 } else {
374 mPendingWriteEventsQueue.pop();
375 }
376 }
377 }
378}
379
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700380void HalProxy::startWakelockThread(HalProxy* halProxy) {
381 halProxy->handleWakelocks();
382}
383
384void HalProxy::handleWakelocks() {
385 std::unique_lock<std::recursive_mutex> lock(mWakelockMutex);
386 while (mThreadsRun.load()) {
387 mWakelockCV.wait(lock, [&] { return mWakelockRefCount > 0 || !mThreadsRun.load(); });
388 if (mThreadsRun.load()) {
389 int64_t timeLeft;
390 if (sharedWakelockDidTimeout(&timeLeft)) {
391 resetSharedWakelock();
392 } else {
393 uint32_t numWakeLocksProcessed;
394 lock.unlock();
395 bool success = mWakeLockQueue->readBlocking(
396 &numWakeLocksProcessed, 1, 0,
397 static_cast<uint32_t>(WakeLockQueueFlagBits::DATA_WRITTEN), timeLeft);
398 lock.lock();
399 if (success) {
400 decrementRefCountAndMaybeReleaseWakelock(
401 static_cast<size_t>(numWakeLocksProcessed));
402 }
403 }
404 }
405 }
406 resetSharedWakelock();
407}
408
409bool HalProxy::sharedWakelockDidTimeout(int64_t* timeLeft) {
410 bool didTimeout;
411 int64_t duration = getTimeNow() - mWakelockTimeoutStartTime;
412 if (duration > kWakelockTimeoutNs) {
413 didTimeout = true;
414 } else {
415 didTimeout = false;
416 *timeLeft = kWakelockTimeoutNs - duration;
417 }
418 return didTimeout;
419}
420
421void HalProxy::resetSharedWakelock() {
422 std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
423 decrementRefCountAndMaybeReleaseWakelock(mWakelockRefCount);
424 mWakelockTimeoutResetTime = getTimeNow();
425}
426
427void HalProxy::postEventsToMessageQueue(const std::vector<Event>& events, size_t numWakeupEvents,
428 ScopedWakelock wakelock) {
Stan Rokita59714262019-09-20 10:55:30 -0700429 size_t numToWrite = 0;
430 std::lock_guard<std::mutex> lock(mEventQueueWriteMutex);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700431 if (wakelock.isLocked()) {
432 incrementRefCountAndMaybeAcquireWakelock(numWakeupEvents);
433 }
Stan Rokita59714262019-09-20 10:55:30 -0700434 if (mPendingWriteEventsQueue.empty()) {
435 numToWrite = std::min(events.size(), mEventQueue->availableToWrite());
436 if (numToWrite > 0) {
437 if (mEventQueue->write(events.data(), numToWrite)) {
438 // TODO: While loop if mEventQueue->avaiableToWrite > 0 to possibly fit in more
439 // writes immediately
440 mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
441 } else {
442 numToWrite = 0;
443 }
Stan Rokita537c0272019-09-13 10:36:07 -0700444 }
445 }
446 if (numToWrite < events.size()) {
Stan Rokita59714262019-09-20 10:55:30 -0700447 // TODO: Bound the mPendingWriteEventsQueue so that we do not trigger OOMs if framework
448 // stalls
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700449 std::vector<Event> eventsLeft(events.begin() + numToWrite, events.end());
450 mPendingWriteEventsQueue.push({eventsLeft, numWakeupEvents});
Stan Rokita59714262019-09-20 10:55:30 -0700451 mEventQueueWriteCV.notify_one();
Stan Rokita537c0272019-09-13 10:36:07 -0700452 }
453}
454
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700455bool HalProxy::incrementRefCountAndMaybeAcquireWakelock(size_t delta,
456 int64_t* timeoutStart /* = nullptr */) {
457 if (!mThreadsRun.load()) return false;
458 std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700459 if (mWakelockRefCount == 0) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700460 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakelockName);
461 mWakelockCV.notify_one();
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700462 }
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700463 mWakelockTimeoutStartTime = getTimeNow();
464 mWakelockRefCount += delta;
465 if (timeoutStart != nullptr) {
466 *timeoutStart = mWakelockTimeoutStartTime;
467 }
468 return true;
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700469}
470
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700471void HalProxy::decrementRefCountAndMaybeReleaseWakelock(size_t delta,
472 int64_t timeoutStart /* = -1 */) {
473 if (!mThreadsRun.load()) return;
474 std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
475 if (timeoutStart == -1) timeoutStart = mWakelockTimeoutResetTime;
476 if (mWakelockRefCount == 0 || timeoutStart < mWakelockTimeoutResetTime) return;
477 mWakelockRefCount -= std::min(mWakelockRefCount, delta);
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700478 if (mWakelockRefCount == 0) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700479 release_wake_lock(kWakelockName);
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700480 }
481}
482
Stan Rokita7a723542019-08-29 15:47:50 -0700483void HalProxy::setDirectChannelFlags(SensorInfo* sensorInfo, ISensorsSubHal* subHal) {
484 bool sensorSupportsDirectChannel =
485 (sensorInfo->flags & (V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
486 V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL)) != 0;
487 if (mDirectChannelSubHal == nullptr && sensorSupportsDirectChannel) {
488 mDirectChannelSubHal = subHal;
489 } else if (mDirectChannelSubHal != nullptr && subHal != mDirectChannelSubHal) {
490 // disable direct channel capability for sensors in subHals that are not
491 // the only one we will enable
492 sensorInfo->flags &= ~(V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
493 V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL);
494 }
495}
496
Stan Rokita16385312019-09-10 14:54:36 -0700497ISensorsSubHal* HalProxy::getSubHalForSensorHandle(uint32_t sensorHandle) {
498 return mSubHalList[static_cast<size_t>(sensorHandle >> 24)];
499}
500
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700501size_t HalProxy::countNumWakeupEvents(const std::vector<Event>& events, size_t n) {
502 size_t numWakeupEvents = 0;
503 for (size_t i = 0; i < n; i++) {
504 int32_t sensorHandle = events[i].sensorHandle;
505 if (mSensors[sensorHandle].flags & static_cast<uint32_t>(V1_0::SensorFlagBits::WAKE_UP)) {
506 numWakeupEvents++;
507 }
508 }
509 return numWakeupEvents;
510}
511
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700512uint32_t HalProxy::clearSubHalIndex(uint32_t sensorHandle) {
513 return sensorHandle & (~kSensorHandleSubHalIndexMask);
Stan Rokita16385312019-09-10 14:54:36 -0700514}
515
Stan Rokitae93fdf92019-09-24 11:58:51 -0700516bool HalProxy::subHalIndexIsClear(uint32_t sensorHandle) {
517 return (sensorHandle & kSensorHandleSubHalIndexMask) == 0;
518}
519
Stan Rokita537c0272019-09-13 10:36:07 -0700520void HalProxyCallback::postEvents(const std::vector<Event>& events, ScopedWakelock wakelock) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700521 if (events.empty() || !mHalProxy->areThreadsRunning()) return;
Stan Rokita537c0272019-09-13 10:36:07 -0700522 size_t numWakeupEvents;
523 std::vector<Event> processedEvents = processEvents(events, &numWakeupEvents);
524 if (numWakeupEvents > 0) {
525 ALOG_ASSERT(wakelock.isLocked(),
526 "Wakeup events posted while wakelock unlocked for subhal"
527 " w/ index %zu.",
528 mSubHalIndex);
529 } else {
530 ALOG_ASSERT(!wakelock.isLocked(),
531 "No Wakeup events posted but wakelock locked for subhal"
532 " w/ index %zu.",
533 mSubHalIndex);
534 }
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700535 mHalProxy->postEventsToMessageQueue(events, numWakeupEvents, std::move(wakelock));
Stan Rokita537c0272019-09-13 10:36:07 -0700536}
537
538ScopedWakelock HalProxyCallback::createScopedWakelock(bool lock) {
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700539 ScopedWakelock wakelock(mHalProxy, lock);
Stan Rokita537c0272019-09-13 10:36:07 -0700540 return wakelock;
541}
542
543std::vector<Event> HalProxyCallback::processEvents(const std::vector<Event>& events,
544 size_t* numWakeupEvents) const {
Stan Rokita537c0272019-09-13 10:36:07 -0700545 *numWakeupEvents = 0;
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700546 std::vector<Event> eventsOut;
Stan Rokita537c0272019-09-13 10:36:07 -0700547 for (Event event : events) {
Stan Rokitae93fdf92019-09-24 11:58:51 -0700548 event.sensorHandle = setSubHalIndex(event.sensorHandle, mSubHalIndex);
Stan Rokita537c0272019-09-13 10:36:07 -0700549 eventsOut.push_back(event);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700550 const SensorInfo& sensor = mHalProxy->getSensorInfo(event.sensorHandle);
551 if ((sensor.flags & V1_0::SensorFlagBits::WAKE_UP) != 0) {
Stan Rokita537c0272019-09-13 10:36:07 -0700552 (*numWakeupEvents)++;
553 }
554 }
555 return eventsOut;
556}
557
Anthony Stangea689f8a2019-07-30 11:35:48 -0400558} // namespace implementation
559} // namespace V2_0
560} // namespace sensors
561} // namespace hardware
562} // namespace android