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