blob: fe2b98b21a8370eda90d578ed24f689837842b83 [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 Rokita336c1c72019-10-14 15:30:57 -070068 stopThreads();
Anthony Stangea689f8a2019-07-30 11:35:48 -040069}
70
Stan Rokitadc7a8e72019-08-23 12:35:40 -070071Return<void> HalProxy::getSensorsList(getSensorsList_cb _hidl_cb) {
Stan Rokita537c0272019-09-13 10:36:07 -070072 std::vector<SensorInfo> sensors;
73 for (const auto& iter : mSensors) {
74 sensors.push_back(iter.second);
75 }
76 _hidl_cb(sensors);
Anthony Stangea689f8a2019-07-30 11:35:48 -040077 return Void();
78}
79
Stan Rokita7a723542019-08-29 15:47:50 -070080Return<Result> HalProxy::setOperationMode(OperationMode mode) {
81 Result result = Result::OK;
82 size_t subHalIndex;
83 for (subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
84 ISensorsSubHal* subHal = mSubHalList[subHalIndex];
85 result = subHal->setOperationMode(mode);
86 if (result != Result::OK) {
87 ALOGE("setOperationMode failed for SubHal: %s", subHal->getName().c_str());
88 break;
89 }
90 }
91 if (result != Result::OK) {
92 // Reset the subhal operation modes that have been flipped
93 for (size_t i = 0; i < subHalIndex; i++) {
94 ISensorsSubHal* subHal = mSubHalList[i];
95 subHal->setOperationMode(mCurrentOperationMode);
96 }
97 } else {
98 mCurrentOperationMode = mode;
99 }
100 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -0400101}
102
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700103Return<Result> HalProxy::activate(int32_t sensorHandle, bool enabled) {
104 return getSubHalForSensorHandle(sensorHandle)
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700105 ->activate(clearSubHalIndex(sensorHandle), enabled);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400106}
107
108Return<Result> HalProxy::initialize(
109 const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
110 const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
111 const sp<ISensorsCallback>& sensorsCallback) {
112 Result result = Result::OK;
113
Stan Rokita336c1c72019-10-14 15:30:57 -0700114 stopThreads();
115 resetSharedWakelock();
116
117 // So that the pending write events queue can be cleared safely and when we start threads
118 // again we do not get new events until after initialize resets the subhals.
119 disableAllSensors();
120
121 // Clears the queue if any events were pending write before.
122 mPendingWriteEventsQueue = std::queue<std::pair<std::vector<Event>, size_t>>();
123
124 // Clears previously connected dynamic sensors
125 mDynamicSensors.clear();
Anthony Stangea689f8a2019-07-30 11:35:48 -0400126
127 mDynamicSensorsCallback = sensorsCallback;
128
129 // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
130 mEventQueue =
131 std::make_unique<EventMessageQueue>(eventQueueDescriptor, true /* resetPointers */);
132
Anthony Stangea689f8a2019-07-30 11:35:48 -0400133 // Create the Wake Lock FMQ that is used by the framework to communicate whenever WAKE_UP
134 // events have been successfully read and handled by the framework.
135 mWakeLockQueue =
136 std::make_unique<WakeLockMessageQueue>(wakeLockDescriptor, true /* resetPointers */);
137
Stan Rokita336c1c72019-10-14 15:30:57 -0700138 if (mEventQueueFlag != nullptr) {
139 EventFlag::deleteEventFlag(&mEventQueueFlag);
140 }
141 if (mWakelockQueueFlag != nullptr) {
142 EventFlag::deleteEventFlag(&mWakelockQueueFlag);
143 }
144 if (EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag) != OK) {
145 result = Result::BAD_VALUE;
146 }
147 if (EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakelockQueueFlag) != OK) {
148 result = Result::BAD_VALUE;
149 }
Anthony Stangea689f8a2019-07-30 11:35:48 -0400150 if (!mDynamicSensorsCallback || !mEventQueue || !mWakeLockQueue || mEventQueueFlag == nullptr) {
151 result = Result::BAD_VALUE;
152 }
153
Stan Rokita336c1c72019-10-14 15:30:57 -0700154 mThreadsRun.store(true);
155
Stan Rokita59714262019-09-20 10:55:30 -0700156 mPendingWritesThread = std::thread(startPendingWritesThread, this);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700157 mWakelockThread = std::thread(startWakelockThread, this);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400158
Stan Rokita537c0272019-09-13 10:36:07 -0700159 for (size_t i = 0; i < mSubHalList.size(); i++) {
160 auto subHal = mSubHalList[i];
161 const auto& subHalCallback = mSubHalCallbacks[i];
162 Result currRes = subHal->initialize(subHalCallback);
163 if (currRes != Result::OK) {
164 result = currRes;
165 ALOGE("Subhal '%s' failed to initialize.", subHal->getName().c_str());
166 break;
167 }
168 }
169
Stan Rokita336c1c72019-10-14 15:30:57 -0700170 mCurrentOperationMode = OperationMode::NORMAL;
171
Anthony Stangea689f8a2019-07-30 11:35:48 -0400172 return result;
173}
174
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700175Return<Result> HalProxy::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
176 int64_t maxReportLatencyNs) {
177 return getSubHalForSensorHandle(sensorHandle)
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700178 ->batch(clearSubHalIndex(sensorHandle), samplingPeriodNs, maxReportLatencyNs);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400179}
180
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700181Return<Result> HalProxy::flush(int32_t sensorHandle) {
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700182 return getSubHalForSensorHandle(sensorHandle)->flush(clearSubHalIndex(sensorHandle));
Anthony Stangea689f8a2019-07-30 11:35:48 -0400183}
184
Stan Rokita83e43702019-09-24 10:16:08 -0700185Return<Result> HalProxy::injectSensorData(const Event& event) {
186 Result result = Result::OK;
187 if (mCurrentOperationMode == OperationMode::NORMAL &&
188 event.sensorType != V1_0::SensorType::ADDITIONAL_INFO) {
189 ALOGE("An event with type != ADDITIONAL_INFO passed to injectSensorData while operation"
190 " mode was NORMAL.");
191 result = Result::BAD_VALUE;
192 }
193 if (result == Result::OK) {
194 Event subHalEvent = event;
195 subHalEvent.sensorHandle = clearSubHalIndex(event.sensorHandle);
196 result = getSubHalForSensorHandle(event.sensorHandle)->injectSensorData(subHalEvent);
197 }
198 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -0400199}
200
Stan Rokitadb23aa82019-09-24 11:08:27 -0700201Return<void> HalProxy::registerDirectChannel(const SharedMemInfo& mem,
Anthony Stangea689f8a2019-07-30 11:35:48 -0400202 registerDirectChannel_cb _hidl_cb) {
Stan Rokitadb23aa82019-09-24 11:08:27 -0700203 if (mDirectChannelSubHal == nullptr) {
204 _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
205 } else {
206 mDirectChannelSubHal->registerDirectChannel(mem, _hidl_cb);
207 }
Anthony Stangea689f8a2019-07-30 11:35:48 -0400208 return Return<void>();
209}
210
Stan Rokitadb23aa82019-09-24 11:08:27 -0700211Return<Result> HalProxy::unregisterDirectChannel(int32_t channelHandle) {
212 Result result;
213 if (mDirectChannelSubHal == nullptr) {
214 result = Result::INVALID_OPERATION;
215 } else {
216 result = mDirectChannelSubHal->unregisterDirectChannel(channelHandle);
217 }
218 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -0400219}
220
Stan Rokitadb23aa82019-09-24 11:08:27 -0700221Return<void> HalProxy::configDirectReport(int32_t sensorHandle, int32_t channelHandle,
222 RateLevel rate, configDirectReport_cb _hidl_cb) {
223 if (mDirectChannelSubHal == nullptr) {
224 _hidl_cb(Result::INVALID_OPERATION, -1 /* reportToken */);
225 } else {
226 mDirectChannelSubHal->configDirectReport(clearSubHalIndex(sensorHandle), channelHandle,
227 rate, _hidl_cb);
228 }
Anthony Stangea689f8a2019-07-30 11:35:48 -0400229 return Return<void>();
230}
231
232Return<void> HalProxy::debug(const hidl_handle& /* fd */, const hidl_vec<hidl_string>& /* args */) {
233 // TODO: output debug information
234 return Return<void>();
235}
236
Stan Rokitae93fdf92019-09-24 11:58:51 -0700237Return<void> HalProxy::onDynamicSensorsConnected(const hidl_vec<SensorInfo>& dynamicSensorsAdded,
238 int32_t subHalIndex) {
239 std::vector<SensorInfo> sensors;
240 {
241 std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
242 for (SensorInfo sensor : dynamicSensorsAdded) {
243 if (!subHalIndexIsClear(sensor.sensorHandle)) {
244 ALOGE("Dynamic sensor added %s had sensorHandle with first byte not 0.",
245 sensor.name.c_str());
246 } else {
247 sensor.sensorHandle = setSubHalIndex(sensor.sensorHandle, subHalIndex);
248 mDynamicSensors[sensor.sensorHandle] = sensor;
249 sensors.push_back(sensor);
250 }
251 }
252 }
253 mDynamicSensorsCallback->onDynamicSensorsConnected(sensors);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400254 return Return<void>();
255}
256
257Return<void> HalProxy::onDynamicSensorsDisconnected(
Stan Rokitae93fdf92019-09-24 11:58:51 -0700258 const hidl_vec<int32_t>& dynamicSensorHandlesRemoved, int32_t subHalIndex) {
259 // TODO: Block this call until all pending events are flushed from queue
260 std::vector<int32_t> sensorHandles;
261 {
262 std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
263 for (int32_t sensorHandle : dynamicSensorHandlesRemoved) {
264 if (!subHalIndexIsClear(sensorHandle)) {
265 ALOGE("Dynamic sensorHandle removed had first byte not 0.");
266 } else {
267 sensorHandle = setSubHalIndex(sensorHandle, subHalIndex);
268 if (mDynamicSensors.find(sensorHandle) != mDynamicSensors.end()) {
269 mDynamicSensors.erase(sensorHandle);
270 sensorHandles.push_back(sensorHandle);
271 }
272 }
273 }
274 }
275 mDynamicSensorsCallback->onDynamicSensorsDisconnected(sensorHandles);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400276 return Return<void>();
277}
278
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700279void HalProxy::initializeSubHalListFromConfigFile(const char* configFileName) {
280 std::ifstream subHalConfigStream(configFileName);
281 if (!subHalConfigStream) {
Stan Rokita7a723542019-08-29 15:47:50 -0700282 ALOGE("Failed to load subHal config file: %s", configFileName);
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700283 } else {
284 std::string subHalLibraryFile;
285 while (subHalConfigStream >> subHalLibraryFile) {
286 void* handle = dlopen(subHalLibraryFile.c_str(), RTLD_NOW);
287 if (handle == nullptr) {
Stan Rokita7a723542019-08-29 15:47:50 -0700288 ALOGE("dlopen failed for library: %s", subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700289 } else {
290 SensorsHalGetSubHalFunc* sensorsHalGetSubHalPtr =
291 (SensorsHalGetSubHalFunc*)dlsym(handle, "sensorsHalGetSubHal");
292 if (sensorsHalGetSubHalPtr == nullptr) {
Stan Rokita7a723542019-08-29 15:47:50 -0700293 ALOGE("Failed to locate sensorsHalGetSubHal function for library: %s",
294 subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700295 } else {
296 std::function<SensorsHalGetSubHalFunc> sensorsHalGetSubHal =
297 *sensorsHalGetSubHalPtr;
298 uint32_t version;
299 ISensorsSubHal* subHal = sensorsHalGetSubHal(&version);
300 if (version != SUB_HAL_2_0_VERSION) {
Stan Rokita7a723542019-08-29 15:47:50 -0700301 ALOGE("SubHal version was not 2.0 for library: %s",
302 subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700303 } else {
304 ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
305 mSubHalList.push_back(subHal);
306 }
307 }
308 }
309 }
310 }
311}
312
Stan Rokita537c0272019-09-13 10:36:07 -0700313void HalProxy::initializeSubHalCallbacks() {
314 for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
315 sp<IHalProxyCallback> callback = new HalProxyCallback(this, subHalIndex);
316 mSubHalCallbacks.push_back(callback);
317 }
318}
319
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700320void HalProxy::initializeSensorList() {
321 for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
322 ISensorsSubHal* subHal = mSubHalList[subHalIndex];
323 auto result = subHal->getSensorsList([&](const auto& list) {
324 for (SensorInfo sensor : list) {
Stan Rokitae93fdf92019-09-24 11:58:51 -0700325 if (!subHalIndexIsClear(sensor.sensorHandle)) {
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700326 ALOGE("SubHal sensorHandle's first byte was not 0");
327 } else {
328 ALOGV("Loaded sensor: %s", sensor.name.c_str());
329 sensor.sensorHandle |= (subHalIndex << 24);
Stan Rokita7a723542019-08-29 15:47:50 -0700330 setDirectChannelFlags(&sensor, subHal);
Stan Rokita537c0272019-09-13 10:36:07 -0700331 mSensors[sensor.sensorHandle] = sensor;
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700332 }
333 }
334 });
335 if (!result.isOk()) {
336 ALOGE("getSensorsList call failed for SubHal: %s", subHal->getName().c_str());
337 }
338 }
339}
340
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700341void HalProxy::init() {
Stan Rokita537c0272019-09-13 10:36:07 -0700342 initializeSubHalCallbacks();
343 initializeSensorList();
344}
345
Stan Rokita336c1c72019-10-14 15:30:57 -0700346void HalProxy::stopThreads() {
347 mThreadsRun.store(false);
348 if (mEventQueueFlag != nullptr && mEventQueue != nullptr) {
349 size_t numToRead = mEventQueue->availableToRead();
350 std::vector<Event> events(numToRead);
351 mEventQueue->read(events.data(), numToRead);
352 mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::EVENTS_READ));
353 }
354 if (mWakelockQueueFlag != nullptr && mWakeLockQueue != nullptr) {
355 uint32_t kZero = 0;
356 mWakeLockQueue->write(&kZero);
357 mWakelockQueueFlag->wake(static_cast<uint32_t>(WakeLockQueueFlagBits::DATA_WRITTEN));
358 }
359 mWakelockCV.notify_one();
360 mEventQueueWriteCV.notify_one();
361 if (mPendingWritesThread.joinable()) {
362 mPendingWritesThread.join();
363 }
364 if (mWakelockThread.joinable()) {
365 mWakelockThread.join();
366 }
367}
368
369void HalProxy::disableAllSensors() {
370 for (const auto& sensorEntry : mSensors) {
371 int32_t sensorHandle = sensorEntry.first;
372 activate(sensorHandle, false /* enabled */);
373 }
374 std::lock_guard<std::mutex> dynamicSensorsLock(mDynamicSensorsMutex);
375 for (const auto& sensorEntry : mDynamicSensors) {
376 int32_t sensorHandle = sensorEntry.first;
377 activate(sensorHandle, false /* enabled */);
378 }
379}
380
Stan Rokita59714262019-09-20 10:55:30 -0700381void HalProxy::startPendingWritesThread(HalProxy* halProxy) {
382 halProxy->handlePendingWrites();
383}
384
385void HalProxy::handlePendingWrites() {
386 // TODO: Find a way to optimize locking strategy maybe using two mutexes instead of one.
387 std::unique_lock<std::mutex> lock(mEventQueueWriteMutex);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700388 while (mThreadsRun.load()) {
Stan Rokita59714262019-09-20 10:55:30 -0700389 mEventQueueWriteCV.wait(
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700390 lock, [&] { return !mPendingWriteEventsQueue.empty() || !mThreadsRun.load(); });
391 if (mThreadsRun.load()) {
392 std::vector<Event>& pendingWriteEvents = mPendingWriteEventsQueue.front().first;
393 size_t numWakeupEvents = mPendingWriteEventsQueue.front().second;
Stan Rokita59714262019-09-20 10:55:30 -0700394 size_t eventQueueSize = mEventQueue->getQuantumCount();
395 size_t numToWrite = std::min(pendingWriteEvents.size(), eventQueueSize);
396 lock.unlock();
Stan Rokita59714262019-09-20 10:55:30 -0700397 if (!mEventQueue->writeBlocking(
398 pendingWriteEvents.data(), numToWrite,
399 static_cast<uint32_t>(EventQueueFlagBits::EVENTS_READ),
400 static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS),
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700401 kPendingWriteTimeoutNs, mEventQueueFlag)) {
Stan Rokita59714262019-09-20 10:55:30 -0700402 ALOGE("Dropping %zu events after blockingWrite failed.", numToWrite);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700403 if (numWakeupEvents > 0) {
404 if (pendingWriteEvents.size() > eventQueueSize) {
405 decrementRefCountAndMaybeReleaseWakelock(
406 countNumWakeupEvents(pendingWriteEvents, eventQueueSize));
407 } else {
408 decrementRefCountAndMaybeReleaseWakelock(numWakeupEvents);
409 }
410 }
Stan Rokita59714262019-09-20 10:55:30 -0700411 }
412 lock.lock();
413 if (pendingWriteEvents.size() > eventQueueSize) {
414 // TODO: Check if this erase operation is too inefficient. It will copy all the
415 // events ahead of it down to fill gap off array at front after the erase.
416 pendingWriteEvents.erase(pendingWriteEvents.begin(),
417 pendingWriteEvents.begin() + eventQueueSize);
418 } else {
419 mPendingWriteEventsQueue.pop();
420 }
421 }
422 }
423}
424
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700425void HalProxy::startWakelockThread(HalProxy* halProxy) {
426 halProxy->handleWakelocks();
427}
428
429void HalProxy::handleWakelocks() {
430 std::unique_lock<std::recursive_mutex> lock(mWakelockMutex);
431 while (mThreadsRun.load()) {
432 mWakelockCV.wait(lock, [&] { return mWakelockRefCount > 0 || !mThreadsRun.load(); });
433 if (mThreadsRun.load()) {
434 int64_t timeLeft;
435 if (sharedWakelockDidTimeout(&timeLeft)) {
436 resetSharedWakelock();
437 } else {
438 uint32_t numWakeLocksProcessed;
439 lock.unlock();
440 bool success = mWakeLockQueue->readBlocking(
441 &numWakeLocksProcessed, 1, 0,
442 static_cast<uint32_t>(WakeLockQueueFlagBits::DATA_WRITTEN), timeLeft);
443 lock.lock();
444 if (success) {
445 decrementRefCountAndMaybeReleaseWakelock(
446 static_cast<size_t>(numWakeLocksProcessed));
447 }
448 }
449 }
450 }
451 resetSharedWakelock();
452}
453
454bool HalProxy::sharedWakelockDidTimeout(int64_t* timeLeft) {
455 bool didTimeout;
456 int64_t duration = getTimeNow() - mWakelockTimeoutStartTime;
457 if (duration > kWakelockTimeoutNs) {
458 didTimeout = true;
459 } else {
460 didTimeout = false;
461 *timeLeft = kWakelockTimeoutNs - duration;
462 }
463 return didTimeout;
464}
465
466void HalProxy::resetSharedWakelock() {
467 std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
468 decrementRefCountAndMaybeReleaseWakelock(mWakelockRefCount);
469 mWakelockTimeoutResetTime = getTimeNow();
470}
471
472void HalProxy::postEventsToMessageQueue(const std::vector<Event>& events, size_t numWakeupEvents,
473 ScopedWakelock wakelock) {
Stan Rokita59714262019-09-20 10:55:30 -0700474 size_t numToWrite = 0;
475 std::lock_guard<std::mutex> lock(mEventQueueWriteMutex);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700476 if (wakelock.isLocked()) {
477 incrementRefCountAndMaybeAcquireWakelock(numWakeupEvents);
478 }
Stan Rokita59714262019-09-20 10:55:30 -0700479 if (mPendingWriteEventsQueue.empty()) {
480 numToWrite = std::min(events.size(), mEventQueue->availableToWrite());
481 if (numToWrite > 0) {
482 if (mEventQueue->write(events.data(), numToWrite)) {
483 // TODO: While loop if mEventQueue->avaiableToWrite > 0 to possibly fit in more
484 // writes immediately
485 mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
486 } else {
487 numToWrite = 0;
488 }
Stan Rokita537c0272019-09-13 10:36:07 -0700489 }
490 }
491 if (numToWrite < events.size()) {
Stan Rokita59714262019-09-20 10:55:30 -0700492 // TODO: Bound the mPendingWriteEventsQueue so that we do not trigger OOMs if framework
493 // stalls
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700494 std::vector<Event> eventsLeft(events.begin() + numToWrite, events.end());
495 mPendingWriteEventsQueue.push({eventsLeft, numWakeupEvents});
Stan Rokita59714262019-09-20 10:55:30 -0700496 mEventQueueWriteCV.notify_one();
Stan Rokita537c0272019-09-13 10:36:07 -0700497 }
498}
499
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700500bool HalProxy::incrementRefCountAndMaybeAcquireWakelock(size_t delta,
501 int64_t* timeoutStart /* = nullptr */) {
502 if (!mThreadsRun.load()) return false;
503 std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700504 if (mWakelockRefCount == 0) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700505 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakelockName);
506 mWakelockCV.notify_one();
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700507 }
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700508 mWakelockTimeoutStartTime = getTimeNow();
509 mWakelockRefCount += delta;
510 if (timeoutStart != nullptr) {
511 *timeoutStart = mWakelockTimeoutStartTime;
512 }
513 return true;
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700514}
515
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700516void HalProxy::decrementRefCountAndMaybeReleaseWakelock(size_t delta,
517 int64_t timeoutStart /* = -1 */) {
518 if (!mThreadsRun.load()) return;
519 std::lock_guard<std::recursive_mutex> lockGuard(mWakelockMutex);
520 if (timeoutStart == -1) timeoutStart = mWakelockTimeoutResetTime;
521 if (mWakelockRefCount == 0 || timeoutStart < mWakelockTimeoutResetTime) return;
522 mWakelockRefCount -= std::min(mWakelockRefCount, delta);
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700523 if (mWakelockRefCount == 0) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700524 release_wake_lock(kWakelockName);
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700525 }
526}
527
Stan Rokita7a723542019-08-29 15:47:50 -0700528void HalProxy::setDirectChannelFlags(SensorInfo* sensorInfo, ISensorsSubHal* subHal) {
529 bool sensorSupportsDirectChannel =
530 (sensorInfo->flags & (V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
531 V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL)) != 0;
532 if (mDirectChannelSubHal == nullptr && sensorSupportsDirectChannel) {
533 mDirectChannelSubHal = subHal;
534 } else if (mDirectChannelSubHal != nullptr && subHal != mDirectChannelSubHal) {
535 // disable direct channel capability for sensors in subHals that are not
536 // the only one we will enable
537 sensorInfo->flags &= ~(V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
538 V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL);
539 }
540}
541
Stan Rokita16385312019-09-10 14:54:36 -0700542ISensorsSubHal* HalProxy::getSubHalForSensorHandle(uint32_t sensorHandle) {
543 return mSubHalList[static_cast<size_t>(sensorHandle >> 24)];
544}
545
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700546size_t HalProxy::countNumWakeupEvents(const std::vector<Event>& events, size_t n) {
547 size_t numWakeupEvents = 0;
548 for (size_t i = 0; i < n; i++) {
549 int32_t sensorHandle = events[i].sensorHandle;
550 if (mSensors[sensorHandle].flags & static_cast<uint32_t>(V1_0::SensorFlagBits::WAKE_UP)) {
551 numWakeupEvents++;
552 }
553 }
554 return numWakeupEvents;
555}
556
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700557uint32_t HalProxy::clearSubHalIndex(uint32_t sensorHandle) {
558 return sensorHandle & (~kSensorHandleSubHalIndexMask);
Stan Rokita16385312019-09-10 14:54:36 -0700559}
560
Stan Rokitae93fdf92019-09-24 11:58:51 -0700561bool HalProxy::subHalIndexIsClear(uint32_t sensorHandle) {
562 return (sensorHandle & kSensorHandleSubHalIndexMask) == 0;
563}
564
Stan Rokita537c0272019-09-13 10:36:07 -0700565void HalProxyCallback::postEvents(const std::vector<Event>& events, ScopedWakelock wakelock) {
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700566 if (events.empty() || !mHalProxy->areThreadsRunning()) return;
Stan Rokita537c0272019-09-13 10:36:07 -0700567 size_t numWakeupEvents;
568 std::vector<Event> processedEvents = processEvents(events, &numWakeupEvents);
569 if (numWakeupEvents > 0) {
570 ALOG_ASSERT(wakelock.isLocked(),
571 "Wakeup events posted while wakelock unlocked for subhal"
572 " w/ index %zu.",
573 mSubHalIndex);
574 } else {
575 ALOG_ASSERT(!wakelock.isLocked(),
576 "No Wakeup events posted but wakelock locked for subhal"
577 " w/ index %zu.",
578 mSubHalIndex);
579 }
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700580 mHalProxy->postEventsToMessageQueue(events, numWakeupEvents, std::move(wakelock));
Stan Rokita537c0272019-09-13 10:36:07 -0700581}
582
583ScopedWakelock HalProxyCallback::createScopedWakelock(bool lock) {
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700584 ScopedWakelock wakelock(mHalProxy, lock);
Stan Rokita537c0272019-09-13 10:36:07 -0700585 return wakelock;
586}
587
588std::vector<Event> HalProxyCallback::processEvents(const std::vector<Event>& events,
589 size_t* numWakeupEvents) const {
Stan Rokita537c0272019-09-13 10:36:07 -0700590 *numWakeupEvents = 0;
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700591 std::vector<Event> eventsOut;
Stan Rokita537c0272019-09-13 10:36:07 -0700592 for (Event event : events) {
Stan Rokitae93fdf92019-09-24 11:58:51 -0700593 event.sensorHandle = setSubHalIndex(event.sensorHandle, mSubHalIndex);
Stan Rokita537c0272019-09-13 10:36:07 -0700594 eventsOut.push_back(event);
Stan Rokita75cc7bf2019-09-26 13:17:01 -0700595 const SensorInfo& sensor = mHalProxy->getSensorInfo(event.sensorHandle);
596 if ((sensor.flags & V1_0::SensorFlagBits::WAKE_UP) != 0) {
Stan Rokita537c0272019-09-13 10:36:07 -0700597 (*numWakeupEvents)++;
598 }
599 }
600 return eventsOut;
601}
602
Anthony Stangea689f8a2019-07-30 11:35:48 -0400603} // namespace implementation
604} // namespace V2_0
605} // namespace sensors
606} // namespace hardware
607} // namespace android