blob: ccd6e6647ef61e5d01ccb0a0cd90c526c39bdf18 [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
27#include <fstream>
28#include <functional>
Stan Rokita537c0272019-09-13 10:36:07 -070029#include <thread>
Stan Rokita28790672019-08-20 14:32:15 -070030
Anthony Stangea689f8a2019-07-30 11:35:48 -040031namespace android {
32namespace hardware {
33namespace sensors {
34namespace V2_0 {
35namespace implementation {
36
Stan Rokita537c0272019-09-13 10:36:07 -070037using ::android::hardware::sensors::V2_0::EventQueueFlagBits;
38
Stan Rokita28790672019-08-20 14:32:15 -070039typedef ISensorsSubHal*(SensorsHalGetSubHalFunc)(uint32_t*);
40
Anthony Stangea689f8a2019-07-30 11:35:48 -040041HalProxy::HalProxy() {
Stan Rokita7a723542019-08-29 15:47:50 -070042 const char* kMultiHalConfigFile = "/vendor/etc/sensors/hals.conf";
43 initializeSubHalListFromConfigFile(kMultiHalConfigFile);
Stan Rokita537c0272019-09-13 10:36:07 -070044 initializeSubHalCallbacksAndSensorList();
Anthony Stangea689f8a2019-07-30 11:35:48 -040045}
46
Anthony Stangeaacbf942019-08-30 15:21:34 -040047HalProxy::HalProxy(std::vector<ISensorsSubHal*>& subHalList) : mSubHalList(subHalList) {
Stan Rokita537c0272019-09-13 10:36:07 -070048 initializeSubHalCallbacksAndSensorList();
Anthony Stangeaacbf942019-08-30 15:21:34 -040049}
50
Anthony Stangea689f8a2019-07-30 11:35:48 -040051HalProxy::~HalProxy() {
Stan Rokita59714262019-09-20 10:55:30 -070052 {
53 std::lock_guard<std::mutex> lockGuard(mEventQueueWriteMutex);
54 mPendingWritesRun = false;
55 mEventQueueWriteCV.notify_one();
56 }
57 if (mPendingWritesThread.joinable()) {
58 mPendingWritesThread.join();
59 }
60 // TODO: Cleanup wakeup thread once it is implemented
Anthony Stangea689f8a2019-07-30 11:35:48 -040061}
62
Stan Rokitadc7a8e72019-08-23 12:35:40 -070063Return<void> HalProxy::getSensorsList(getSensorsList_cb _hidl_cb) {
Stan Rokita537c0272019-09-13 10:36:07 -070064 std::vector<SensorInfo> sensors;
65 for (const auto& iter : mSensors) {
66 sensors.push_back(iter.second);
67 }
68 _hidl_cb(sensors);
Anthony Stangea689f8a2019-07-30 11:35:48 -040069 return Void();
70}
71
Stan Rokita7a723542019-08-29 15:47:50 -070072Return<Result> HalProxy::setOperationMode(OperationMode mode) {
73 Result result = Result::OK;
74 size_t subHalIndex;
75 for (subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
76 ISensorsSubHal* subHal = mSubHalList[subHalIndex];
77 result = subHal->setOperationMode(mode);
78 if (result != Result::OK) {
79 ALOGE("setOperationMode failed for SubHal: %s", subHal->getName().c_str());
80 break;
81 }
82 }
83 if (result != Result::OK) {
84 // Reset the subhal operation modes that have been flipped
85 for (size_t i = 0; i < subHalIndex; i++) {
86 ISensorsSubHal* subHal = mSubHalList[i];
87 subHal->setOperationMode(mCurrentOperationMode);
88 }
89 } else {
90 mCurrentOperationMode = mode;
91 }
92 return result;
Anthony Stangea689f8a2019-07-30 11:35:48 -040093}
94
Stan Rokita4b4c7b72019-09-10 15:07:59 -070095Return<Result> HalProxy::activate(int32_t sensorHandle, bool enabled) {
96 return getSubHalForSensorHandle(sensorHandle)
Stan Rokitaf97a3f32019-09-13 09:58:47 -070097 ->activate(clearSubHalIndex(sensorHandle), enabled);
Anthony Stangea689f8a2019-07-30 11:35:48 -040098}
99
100Return<Result> HalProxy::initialize(
101 const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
102 const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
103 const sp<ISensorsCallback>& sensorsCallback) {
104 Result result = Result::OK;
105
106 // TODO: clean up sensor requests, if not already done elsewhere through a death recipient, and
107 // clean up any other resources that exist (FMQs, flags, threads, etc.)
108
109 mDynamicSensorsCallback = sensorsCallback;
110
111 // Create the Event FMQ from the eventQueueDescriptor. Reset the read/write positions.
112 mEventQueue =
113 std::make_unique<EventMessageQueue>(eventQueueDescriptor, true /* resetPointers */);
114
115 // Create the EventFlag that is used to signal to the framework that sensor events have been
116 // written to the Event FMQ
117 if (EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag) != OK) {
118 result = Result::BAD_VALUE;
119 }
120
121 // Create the Wake Lock FMQ that is used by the framework to communicate whenever WAKE_UP
122 // events have been successfully read and handled by the framework.
123 mWakeLockQueue =
124 std::make_unique<WakeLockMessageQueue>(wakeLockDescriptor, true /* resetPointers */);
125
126 if (!mDynamicSensorsCallback || !mEventQueue || !mWakeLockQueue || mEventQueueFlag == nullptr) {
127 result = Result::BAD_VALUE;
128 }
129
Stan Rokita59714262019-09-20 10:55:30 -0700130 mPendingWritesThread = std::thread(startPendingWritesThread, this);
131 // TODO: start threads to read wake locks.
Anthony Stangea689f8a2019-07-30 11:35:48 -0400132
Stan Rokita537c0272019-09-13 10:36:07 -0700133 for (size_t i = 0; i < mSubHalList.size(); i++) {
134 auto subHal = mSubHalList[i];
135 const auto& subHalCallback = mSubHalCallbacks[i];
136 Result currRes = subHal->initialize(subHalCallback);
137 if (currRes != Result::OK) {
138 result = currRes;
139 ALOGE("Subhal '%s' failed to initialize.", subHal->getName().c_str());
140 break;
141 }
142 }
143
Anthony Stangea689f8a2019-07-30 11:35:48 -0400144 return result;
145}
146
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700147Return<Result> HalProxy::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
148 int64_t maxReportLatencyNs) {
149 return getSubHalForSensorHandle(sensorHandle)
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700150 ->batch(clearSubHalIndex(sensorHandle), samplingPeriodNs, maxReportLatencyNs);
Anthony Stangea689f8a2019-07-30 11:35:48 -0400151}
152
Stan Rokita4b4c7b72019-09-10 15:07:59 -0700153Return<Result> HalProxy::flush(int32_t sensorHandle) {
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700154 return getSubHalForSensorHandle(sensorHandle)->flush(clearSubHalIndex(sensorHandle));
Anthony Stangea689f8a2019-07-30 11:35:48 -0400155}
156
157Return<Result> HalProxy::injectSensorData(const Event& /* event */) {
158 // TODO: Proxy API call to appropriate sub-HAL.
159 return Result::INVALID_OPERATION;
160}
161
162Return<void> HalProxy::registerDirectChannel(const SharedMemInfo& /* mem */,
163 registerDirectChannel_cb _hidl_cb) {
164 // TODO: During init, discover the first sub-HAL in the config that has sensors with direct
165 // channel support, if any, and proxy the API call there.
166 _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
167 return Return<void>();
168}
169
170Return<Result> HalProxy::unregisterDirectChannel(int32_t /* channelHandle */) {
171 // TODO: During init, discover the first sub-HAL in the config that has sensors with direct
172 // channel support, if any, and proxy the API call there.
173 return Result::INVALID_OPERATION;
174}
175
176Return<void> HalProxy::configDirectReport(int32_t /* sensorHandle */, int32_t /* channelHandle */,
177 RateLevel /* rate */, configDirectReport_cb _hidl_cb) {
178 // TODO: During init, discover the first sub-HAL in the config that has sensors with direct
179 // channel support, if any, and proxy the API call there.
180 _hidl_cb(Result::INVALID_OPERATION, 0 /* reportToken */);
181 return Return<void>();
182}
183
184Return<void> HalProxy::debug(const hidl_handle& /* fd */, const hidl_vec<hidl_string>& /* args */) {
185 // TODO: output debug information
186 return Return<void>();
187}
188
189Return<void> HalProxy::onDynamicSensorsConnected(
190 const hidl_vec<SensorInfo>& /* dynamicSensorsAdded */, int32_t /* subHalIndex */) {
191 // TODO: Map the SensorInfo to the global list and then invoke the framework's callback.
192 return Return<void>();
193}
194
195Return<void> HalProxy::onDynamicSensorsDisconnected(
196 const hidl_vec<int32_t>& /* dynamicSensorHandlesRemoved */, int32_t /* subHalIndex */) {
197 // TODO: Unmap the SensorInfo from the global list and then invoke the framework's callback.
198 return Return<void>();
199}
200
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700201void HalProxy::initializeSubHalListFromConfigFile(const char* configFileName) {
202 std::ifstream subHalConfigStream(configFileName);
203 if (!subHalConfigStream) {
Stan Rokita7a723542019-08-29 15:47:50 -0700204 ALOGE("Failed to load subHal config file: %s", configFileName);
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700205 } else {
206 std::string subHalLibraryFile;
207 while (subHalConfigStream >> subHalLibraryFile) {
208 void* handle = dlopen(subHalLibraryFile.c_str(), RTLD_NOW);
209 if (handle == nullptr) {
Stan Rokita7a723542019-08-29 15:47:50 -0700210 ALOGE("dlopen failed for library: %s", subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700211 } else {
212 SensorsHalGetSubHalFunc* sensorsHalGetSubHalPtr =
213 (SensorsHalGetSubHalFunc*)dlsym(handle, "sensorsHalGetSubHal");
214 if (sensorsHalGetSubHalPtr == nullptr) {
Stan Rokita7a723542019-08-29 15:47:50 -0700215 ALOGE("Failed to locate sensorsHalGetSubHal function for library: %s",
216 subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700217 } else {
218 std::function<SensorsHalGetSubHalFunc> sensorsHalGetSubHal =
219 *sensorsHalGetSubHalPtr;
220 uint32_t version;
221 ISensorsSubHal* subHal = sensorsHalGetSubHal(&version);
222 if (version != SUB_HAL_2_0_VERSION) {
Stan Rokita7a723542019-08-29 15:47:50 -0700223 ALOGE("SubHal version was not 2.0 for library: %s",
224 subHalLibraryFile.c_str());
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700225 } else {
226 ALOGV("Loaded SubHal from library: %s", subHalLibraryFile.c_str());
227 mSubHalList.push_back(subHal);
228 }
229 }
230 }
231 }
232 }
233}
234
Stan Rokita537c0272019-09-13 10:36:07 -0700235void HalProxy::initializeSubHalCallbacks() {
236 for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
237 sp<IHalProxyCallback> callback = new HalProxyCallback(this, subHalIndex);
238 mSubHalCallbacks.push_back(callback);
239 }
240}
241
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700242void HalProxy::initializeSensorList() {
243 for (size_t subHalIndex = 0; subHalIndex < mSubHalList.size(); subHalIndex++) {
244 ISensorsSubHal* subHal = mSubHalList[subHalIndex];
245 auto result = subHal->getSensorsList([&](const auto& list) {
246 for (SensorInfo sensor : list) {
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700247 if ((sensor.sensorHandle & kSensorHandleSubHalIndexMask) != 0) {
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700248 ALOGE("SubHal sensorHandle's first byte was not 0");
249 } else {
250 ALOGV("Loaded sensor: %s", sensor.name.c_str());
251 sensor.sensorHandle |= (subHalIndex << 24);
Stan Rokita7a723542019-08-29 15:47:50 -0700252 setDirectChannelFlags(&sensor, subHal);
Stan Rokita537c0272019-09-13 10:36:07 -0700253 mSensors[sensor.sensorHandle] = sensor;
Stan Rokitadc7a8e72019-08-23 12:35:40 -0700254 }
255 }
256 });
257 if (!result.isOk()) {
258 ALOGE("getSensorsList call failed for SubHal: %s", subHal->getName().c_str());
259 }
260 }
261}
262
Stan Rokita537c0272019-09-13 10:36:07 -0700263void HalProxy::initializeSubHalCallbacksAndSensorList() {
264 initializeSubHalCallbacks();
265 initializeSensorList();
266}
267
Stan Rokita59714262019-09-20 10:55:30 -0700268void HalProxy::startPendingWritesThread(HalProxy* halProxy) {
269 halProxy->handlePendingWrites();
270}
271
272void HalProxy::handlePendingWrites() {
273 // TODO: Find a way to optimize locking strategy maybe using two mutexes instead of one.
274 std::unique_lock<std::mutex> lock(mEventQueueWriteMutex);
275 while (mPendingWritesRun) {
276 mEventQueueWriteCV.wait(
277 lock, [&] { return !mPendingWriteEventsQueue.empty() || !mPendingWritesRun; });
278 if (!mPendingWriteEventsQueue.empty() && mPendingWritesRun) {
279 std::vector<Event>& pendingWriteEvents = mPendingWriteEventsQueue.front();
280 size_t eventQueueSize = mEventQueue->getQuantumCount();
281 size_t numToWrite = std::min(pendingWriteEvents.size(), eventQueueSize);
282 lock.unlock();
283 // TODO: Find a way to interrup writeBlocking if the thread should exit
284 // so we don't have to wait for timeout on framework restarts.
285 if (!mEventQueue->writeBlocking(
286 pendingWriteEvents.data(), numToWrite,
287 static_cast<uint32_t>(EventQueueFlagBits::EVENTS_READ),
288 static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS),
289 kWakelockTimeoutNs, mEventQueueFlag)) {
290 ALOGE("Dropping %zu events after blockingWrite failed.", numToWrite);
291 } else {
292 mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
293 }
294 lock.lock();
295 if (pendingWriteEvents.size() > eventQueueSize) {
296 // TODO: Check if this erase operation is too inefficient. It will copy all the
297 // events ahead of it down to fill gap off array at front after the erase.
298 pendingWriteEvents.erase(pendingWriteEvents.begin(),
299 pendingWriteEvents.begin() + eventQueueSize);
300 } else {
301 mPendingWriteEventsQueue.pop();
302 }
303 }
304 }
305}
306
Stan Rokita537c0272019-09-13 10:36:07 -0700307void HalProxy::postEventsToMessageQueue(const std::vector<Event>& events) {
Stan Rokita59714262019-09-20 10:55:30 -0700308 size_t numToWrite = 0;
309 std::lock_guard<std::mutex> lock(mEventQueueWriteMutex);
310 if (mPendingWriteEventsQueue.empty()) {
311 numToWrite = std::min(events.size(), mEventQueue->availableToWrite());
312 if (numToWrite > 0) {
313 if (mEventQueue->write(events.data(), numToWrite)) {
314 // TODO: While loop if mEventQueue->avaiableToWrite > 0 to possibly fit in more
315 // writes immediately
316 mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
317 } else {
318 numToWrite = 0;
319 }
Stan Rokita537c0272019-09-13 10:36:07 -0700320 }
321 }
322 if (numToWrite < events.size()) {
Stan Rokita59714262019-09-20 10:55:30 -0700323 // TODO: Bound the mPendingWriteEventsQueue so that we do not trigger OOMs if framework
324 // stalls
325 mPendingWriteEventsQueue.push(
326 std::vector<Event>(events.begin() + numToWrite, events.end()));
327 mEventQueueWriteCV.notify_one();
Stan Rokita537c0272019-09-13 10:36:07 -0700328 }
329}
330
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700331// TODO: Implement the wakelock timeout in these next two methods. Also pass in the subhal
332// index for better tracking.
333
334void HalProxy::incrementRefCountAndMaybeAcquireWakelock() {
335 std::lock_guard<std::mutex> lockGuard(mWakelockRefCountMutex);
336 if (mWakelockRefCount == 0) {
337 acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLockName);
338 }
339 mWakelockRefCount++;
340}
341
342void HalProxy::decrementRefCountAndMaybeReleaseWakelock() {
343 std::lock_guard<std::mutex> lockGuard(mWakelockRefCountMutex);
344 mWakelockRefCount--;
345 if (mWakelockRefCount == 0) {
346 release_wake_lock(kWakeLockName);
347 }
348}
349
Stan Rokita7a723542019-08-29 15:47:50 -0700350void HalProxy::setDirectChannelFlags(SensorInfo* sensorInfo, ISensorsSubHal* subHal) {
351 bool sensorSupportsDirectChannel =
352 (sensorInfo->flags & (V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
353 V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL)) != 0;
354 if (mDirectChannelSubHal == nullptr && sensorSupportsDirectChannel) {
355 mDirectChannelSubHal = subHal;
356 } else if (mDirectChannelSubHal != nullptr && subHal != mDirectChannelSubHal) {
357 // disable direct channel capability for sensors in subHals that are not
358 // the only one we will enable
359 sensorInfo->flags &= ~(V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
360 V1_0::SensorFlagBits::MASK_DIRECT_CHANNEL);
361 }
362}
363
Stan Rokita16385312019-09-10 14:54:36 -0700364ISensorsSubHal* HalProxy::getSubHalForSensorHandle(uint32_t sensorHandle) {
365 return mSubHalList[static_cast<size_t>(sensorHandle >> 24)];
366}
367
Stan Rokitaf97a3f32019-09-13 09:58:47 -0700368uint32_t HalProxy::clearSubHalIndex(uint32_t sensorHandle) {
369 return sensorHandle & (~kSensorHandleSubHalIndexMask);
Stan Rokita16385312019-09-10 14:54:36 -0700370}
371
Stan Rokita537c0272019-09-13 10:36:07 -0700372void HalProxyCallback::postEvents(const std::vector<Event>& events, ScopedWakelock wakelock) {
373 (void)wakelock;
374 size_t numWakeupEvents;
375 std::vector<Event> processedEvents = processEvents(events, &numWakeupEvents);
376 if (numWakeupEvents > 0) {
377 ALOG_ASSERT(wakelock.isLocked(),
378 "Wakeup events posted while wakelock unlocked for subhal"
379 " w/ index %zu.",
380 mSubHalIndex);
381 } else {
382 ALOG_ASSERT(!wakelock.isLocked(),
383 "No Wakeup events posted but wakelock locked for subhal"
384 " w/ index %zu.",
385 mSubHalIndex);
386 }
387
388 mHalProxy->postEventsToMessageQueue(processedEvents);
389}
390
391ScopedWakelock HalProxyCallback::createScopedWakelock(bool lock) {
Stan Rokitad0cd57d2019-09-17 15:52:51 -0700392 ScopedWakelock wakelock(mHalProxy, lock);
Stan Rokita537c0272019-09-13 10:36:07 -0700393 return wakelock;
394}
395
396std::vector<Event> HalProxyCallback::processEvents(const std::vector<Event>& events,
397 size_t* numWakeupEvents) const {
398 std::vector<Event> eventsOut;
399 *numWakeupEvents = 0;
400 for (Event event : events) {
401 event.sensorHandle = setSubHalIndex(event.sensorHandle);
402 eventsOut.push_back(event);
403 if ((mHalProxy->getSensorInfo(event.sensorHandle).flags & V1_0::SensorFlagBits::WAKE_UP) !=
404 0) {
405 (*numWakeupEvents)++;
406 }
407 }
408 return eventsOut;
409}
410
411uint32_t HalProxyCallback::setSubHalIndex(uint32_t sensorHandle) const {
412 return sensorHandle | mSubHalIndex << 24;
413}
414
Anthony Stangea689f8a2019-07-30 11:35:48 -0400415} // namespace implementation
416} // namespace V2_0
417} // namespace sensors
418} // namespace hardware
419} // namespace android