1 /*
2 * Copyright (C) 2021 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 "HidlSensorHalWrapper.h"
18 #include "android/hardware/sensors/2.0/types.h"
19 #include "android/hardware/sensors/2.1/ISensorsCallback.h"
20 #include "android/hardware/sensors/2.1/types.h"
21 #include "convertV2_1.h"
22
23 #include <android-base/logging.h>
24
25 using android::hardware::hidl_vec;
26 using android::hardware::sensors::V1_0::RateLevel;
27 using android::hardware::sensors::V1_0::Result;
28 using android::hardware::sensors::V1_0::SharedMemFormat;
29 using android::hardware::sensors::V1_0::SharedMemInfo;
30 using android::hardware::sensors::V1_0::SharedMemType;
31 using android::hardware::sensors::V2_0::EventQueueFlagBits;
32 using android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
33 using android::hardware::sensors::V2_1::Event;
34 using android::hardware::sensors::V2_1::ISensorsCallback;
35 using android::hardware::sensors::V2_1::implementation::convertFromSensorEvent;
36 using android::hardware::sensors::V2_1::implementation::convertToNewEvents;
37 using android::hardware::sensors::V2_1::implementation::convertToNewSensorInfos;
38 using android::hardware::sensors::V2_1::implementation::convertToSensor;
39 using android::hardware::sensors::V2_1::implementation::ISensorsWrapperV1_0;
40 using android::hardware::sensors::V2_1::implementation::ISensorsWrapperV2_0;
41 using android::hardware::sensors::V2_1::implementation::ISensorsWrapperV2_1;
42
43 namespace android {
44
45 namespace {
46
statusFromResult(Result result)47 status_t statusFromResult(Result result) {
48 switch (result) {
49 case Result::OK:
50 return OK;
51 case Result::BAD_VALUE:
52 return BAD_VALUE;
53 case Result::PERMISSION_DENIED:
54 return PERMISSION_DENIED;
55 case Result::INVALID_OPERATION:
56 return INVALID_OPERATION;
57 case Result::NO_MEMORY:
58 return NO_MEMORY;
59 }
60 }
61
62 template <typename EnumType>
asBaseType(EnumType value)63 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
64 return static_cast<typename std::underlying_type<EnumType>::type>(value);
65 }
66
67 enum EventQueueFlagBitsInternal : uint32_t {
68 INTERNAL_WAKE = 1 << 16,
69 };
70
71 } // anonymous namespace
72
serviceDied(uint64_t,const wp<::android::hidl::base::V1_0::IBase> &)73 void SensorsHalDeathReceiver::serviceDied(
74 uint64_t /* cookie */, const wp<::android::hidl::base::V1_0::IBase>& /* service */) {
75 ALOGW("Sensors HAL died, attempting to reconnect.");
76 mHidlSensorHalWrapper->prepareForReconnect();
77 }
78
79 struct HidlSensorsCallback : public ISensorsCallback {
80 using Result = ::android::hardware::sensors::V1_0::Result;
81 using SensorInfo = ::android::hardware::sensors::V2_1::SensorInfo;
82
HidlSensorsCallbackandroid::HidlSensorsCallback83 HidlSensorsCallback(ISensorHalWrapper::SensorDeviceCallback* sensorDeviceCallback) {
84 mSensorDeviceCallback = sensorDeviceCallback;
85 }
86
onDynamicSensorsConnected_2_1android::HidlSensorsCallback87 Return<void> onDynamicSensorsConnected_2_1(
88 const hidl_vec<SensorInfo>& dynamicSensorsAdded) override {
89 std::vector<sensor_t> sensors;
90 for (const android::hardware::sensors::V2_1::SensorInfo& info : dynamicSensorsAdded) {
91 sensor_t sensor;
92 convertToSensor(info, &sensor);
93 sensors.push_back(sensor);
94 }
95
96 mSensorDeviceCallback->onDynamicSensorsConnected(sensors);
97 return Return<void>();
98 }
99
onDynamicSensorsConnectedandroid::HidlSensorsCallback100 Return<void> onDynamicSensorsConnected(
101 const hidl_vec<android::hardware::sensors::V1_0::SensorInfo>& dynamicSensorsAdded)
102 override {
103 return onDynamicSensorsConnected_2_1(convertToNewSensorInfos(dynamicSensorsAdded));
104 }
105
onDynamicSensorsDisconnectedandroid::HidlSensorsCallback106 Return<void> onDynamicSensorsDisconnected(
107 const hidl_vec<int32_t>& dynamicSensorHandlesRemoved) override {
108 mSensorDeviceCallback->onDynamicSensorsDisconnected(dynamicSensorHandlesRemoved);
109 return Return<void>();
110 }
111
112 private:
113 ISensorHalWrapper::SensorDeviceCallback* mSensorDeviceCallback;
114 };
115
supportsPolling()116 bool HidlSensorHalWrapper::supportsPolling() {
117 return mSensors->supportsPolling();
118 }
119
supportsMessageQueues()120 bool HidlSensorHalWrapper::supportsMessageQueues() {
121 return mSensors->supportsMessageQueues();
122 }
123
connect(SensorDeviceCallback * callback)124 bool HidlSensorHalWrapper::connect(SensorDeviceCallback* callback) {
125 mSensorDeviceCallback = callback;
126 bool ret = connectHidlService();
127 if (mEventQueueFlag != nullptr) {
128 mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
129 }
130 return ret;
131 }
132
prepareForReconnect()133 void HidlSensorHalWrapper::prepareForReconnect() {
134 mReconnecting = true;
135 if (mEventQueueFlag != nullptr) {
136 mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
137 }
138 }
139
poll(sensors_event_t * buffer,size_t count)140 ssize_t HidlSensorHalWrapper::poll(sensors_event_t* buffer, size_t count) {
141 ssize_t err;
142 int numHidlTransportErrors = 0;
143 bool hidlTransportError = false;
144
145 do {
146 auto ret = mSensors->poll(count,
147 [&](auto result, const auto& events,
148 const auto& dynamicSensorsAdded) {
149 if (result == Result::OK) {
150 convertToSensorEvents(convertToNewEvents(events),
151 convertToNewSensorInfos(
152 dynamicSensorsAdded),
153 buffer);
154 err = (ssize_t)events.size();
155 } else {
156 err = statusFromResult(result);
157 }
158 });
159
160 if (ret.isOk()) {
161 hidlTransportError = false;
162 } else {
163 hidlTransportError = true;
164 numHidlTransportErrors++;
165 if (numHidlTransportErrors > 50) {
166 // Log error and bail
167 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
168 handleHidlDeath(ret.description());
169 } else {
170 std::this_thread::sleep_for(std::chrono::milliseconds(10));
171 }
172 }
173 } while (hidlTransportError);
174
175 if (numHidlTransportErrors > 0) {
176 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
177 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
178 mHidlTransportErrors.add(errLog);
179 mTotalHidlTransportErrors++;
180 }
181
182 return err;
183 }
184
pollFmq(sensors_event_t * buffer,size_t maxNumEventsToRead)185 ssize_t HidlSensorHalWrapper::pollFmq(sensors_event_t* buffer, size_t maxNumEventsToRead) {
186 ssize_t eventsRead = 0;
187 size_t availableEvents = mSensors->getEventQueue()->availableToRead();
188
189 if (availableEvents == 0) {
190 uint32_t eventFlagState = 0;
191
192 // Wait for events to become available. This is necessary so that the Event FMQ's read() is
193 // able to be called with the correct number of events to read. If the specified number of
194 // events is not available, then read() would return no events, possibly introducing
195 // additional latency in delivering events to applications.
196 if (mEventQueueFlag != nullptr) {
197 mEventQueueFlag->wait(asBaseType(EventQueueFlagBits::READ_AND_PROCESS) |
198 asBaseType(INTERNAL_WAKE),
199 &eventFlagState);
200 }
201 availableEvents = mSensors->getEventQueue()->availableToRead();
202
203 if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
204 ALOGD("Event FMQ internal wake, returning from poll with no events");
205 return DEAD_OBJECT;
206 }
207 }
208
209 size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
210 if (eventsToRead > 0) {
211 if (mSensors->getEventQueue()->read(mEventBuffer.data(), eventsToRead)) {
212 // Notify the Sensors HAL that sensor events have been read. This is required to support
213 // the use of writeBlocking by the Sensors HAL.
214 if (mEventQueueFlag != nullptr) {
215 mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
216 }
217
218 for (size_t i = 0; i < eventsToRead; i++) {
219 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
220 }
221 eventsRead = eventsToRead;
222 } else {
223 ALOGW("Failed to read %zu events, currently %zu events available", eventsToRead,
224 availableEvents);
225 }
226 }
227
228 return eventsRead;
229 }
230
getSensorsList()231 std::vector<sensor_t> HidlSensorHalWrapper::getSensorsList() {
232 std::vector<sensor_t> sensorsFound;
233 if (mSensors != nullptr) {
234 checkReturn(mSensors->getSensorsList([&](const auto& list) {
235 for (size_t i = 0; i < list.size(); i++) {
236 sensor_t sensor;
237 convertToSensor(list[i], &sensor);
238 sensorsFound.push_back(sensor);
239
240 // Only disable all sensors on HAL 1.0 since HAL 2.0
241 // handles this in its initialize method
242 if (!mSensors->supportsMessageQueues()) {
243 checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
244 }
245 }
246 }));
247 }
248
249 return sensorsFound;
250 }
251
setOperationMode(SensorService::Mode mode)252 status_t HidlSensorHalWrapper::setOperationMode(SensorService::Mode mode) {
253 if (mSensors == nullptr) return NO_INIT;
254 return checkReturnAndGetStatus(
255 mSensors->setOperationMode(static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
256 }
257
activate(int32_t sensorHandle,bool enabled)258 status_t HidlSensorHalWrapper::activate(int32_t sensorHandle, bool enabled) {
259 if (mSensors == nullptr) return NO_INIT;
260 return checkReturnAndGetStatus(mSensors->activate(sensorHandle, enabled));
261 }
262
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)263 status_t HidlSensorHalWrapper::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
264 int64_t maxReportLatencyNs) {
265 if (mSensors == nullptr) return NO_INIT;
266 return checkReturnAndGetStatus(
267 mSensors->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs));
268 }
269
flush(int32_t sensorHandle)270 status_t HidlSensorHalWrapper::flush(int32_t sensorHandle) {
271 if (mSensors == nullptr) return NO_INIT;
272 return checkReturnAndGetStatus(mSensors->flush(sensorHandle));
273 }
274
injectSensorData(const sensors_event_t * event)275 status_t HidlSensorHalWrapper::injectSensorData(const sensors_event_t* event) {
276 if (mSensors == nullptr) return NO_INIT;
277
278 Event ev;
279 convertFromSensorEvent(*event, &ev);
280 return checkReturnAndGetStatus(mSensors->injectSensorData(ev));
281 }
282
registerDirectChannel(const sensors_direct_mem_t * memory,int32_t * outChannelHandle)283 status_t HidlSensorHalWrapper::registerDirectChannel(const sensors_direct_mem_t* memory,
284 int32_t* outChannelHandle) {
285 if (mSensors == nullptr) return NO_INIT;
286
287 SharedMemType type;
288 switch (memory->type) {
289 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
290 type = SharedMemType::ASHMEM;
291 break;
292 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
293 type = SharedMemType::GRALLOC;
294 break;
295 default:
296 return BAD_VALUE;
297 }
298
299 SharedMemFormat format;
300 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
301 return BAD_VALUE;
302 }
303 format = SharedMemFormat::SENSORS_EVENT;
304
305 SharedMemInfo mem = {
306 .type = type,
307 .format = format,
308 .size = static_cast<uint32_t>(memory->size),
309 .memoryHandle = memory->handle,
310 };
311
312 status_t ret = OK;
313 checkReturn(mSensors->registerDirectChannel(mem,
314 [&ret, &outChannelHandle](auto result,
315 auto channelHandle) {
316 if (result == Result::OK) {
317 *outChannelHandle = channelHandle;
318 } else {
319 ret = statusFromResult(result);
320 }
321 }));
322 return ret;
323 }
324
unregisterDirectChannel(int32_t channelHandle)325 status_t HidlSensorHalWrapper::unregisterDirectChannel(int32_t channelHandle) {
326 if (mSensors == nullptr) return NO_INIT;
327 return checkReturnAndGetStatus(mSensors->unregisterDirectChannel(channelHandle));
328 }
329
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)330 status_t HidlSensorHalWrapper::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
331 const struct sensors_direct_cfg_t* config) {
332 if (mSensors == nullptr) return NO_INIT;
333
334 RateLevel rate;
335 switch (config->rate_level) {
336 case SENSOR_DIRECT_RATE_STOP:
337 rate = RateLevel::STOP;
338 break;
339 case SENSOR_DIRECT_RATE_NORMAL:
340 rate = RateLevel::NORMAL;
341 break;
342 case SENSOR_DIRECT_RATE_FAST:
343 rate = RateLevel::FAST;
344 break;
345 case SENSOR_DIRECT_RATE_VERY_FAST:
346 rate = RateLevel::VERY_FAST;
347 break;
348 default:
349 return BAD_VALUE;
350 }
351
352 status_t ret;
353 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
354 [&ret, rate](auto result, auto token) {
355 if (rate == RateLevel::STOP) {
356 ret = statusFromResult(result);
357 } else {
358 if (result == Result::OK) {
359 ret = token;
360 } else {
361 ret = statusFromResult(result);
362 }
363 }
364 }));
365
366 return ret;
367 }
368
writeWakeLockHandled(uint32_t count)369 void HidlSensorHalWrapper::writeWakeLockHandled(uint32_t count) {
370 if (mWakeLockQueue->write(&count)) {
371 mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
372 } else {
373 ALOGW("Failed to write wake lock handled");
374 }
375 }
376
checkReturnAndGetStatus(const hardware::Return<Result> & ret)377 status_t HidlSensorHalWrapper::checkReturnAndGetStatus(const hardware::Return<Result>& ret) {
378 checkReturn(ret);
379 return (!ret.isOk()) ? DEAD_OBJECT : statusFromResult(ret);
380 }
381
handleHidlDeath(const std::string & detail)382 void HidlSensorHalWrapper::handleHidlDeath(const std::string& detail) {
383 if (!mSensors->supportsMessageQueues()) {
384 // restart is the only option at present.
385 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
386 } else {
387 ALOGD("ISensors HAL died, death recipient will attempt reconnect");
388 }
389 }
390
connectHidlService()391 bool HidlSensorHalWrapper::connectHidlService() {
392 HalConnectionStatus status = connectHidlServiceV2_1();
393 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
394 status = connectHidlServiceV2_0();
395 }
396
397 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
398 status = connectHidlServiceV1_0();
399 }
400 return (status == HalConnectionStatus::CONNECTED);
401 }
402
connectHidlServiceV1_0()403 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::connectHidlServiceV1_0() {
404 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
405 size_t retry = 10;
406 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
407
408 while (retry-- > 0) {
409 sp<android::hardware::sensors::V1_0::ISensors> sensors =
410 android::hardware::sensors::V1_0::ISensors::getService();
411 if (sensors == nullptr) {
412 // no sensor hidl service found
413 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
414 break;
415 }
416
417 mSensors = new ISensorsWrapperV1_0(sensors);
418 mRestartWaiter->reset();
419 // Poke ISensor service. If it has lingering connection from previous generation of
420 // system server, it will kill itself. There is no intention to handle the poll result,
421 // which will be done since the size is 0.
422 if (mSensors->poll(0, [](auto, const auto&, const auto&) {}).isOk()) {
423 // ok to continue
424 connectionStatus = HalConnectionStatus::CONNECTED;
425 break;
426 }
427
428 // hidl service is restarting, pointer is invalid.
429 mSensors = nullptr;
430 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
431 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
432 mRestartWaiter->wait();
433 }
434
435 return connectionStatus;
436 }
437
connectHidlServiceV2_0()438 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::connectHidlServiceV2_0() {
439 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
440 sp<android::hardware::sensors::V2_0::ISensors> sensors =
441 android::hardware::sensors::V2_0::ISensors::getService();
442
443 if (sensors == nullptr) {
444 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
445 } else {
446 mSensors = new ISensorsWrapperV2_0(sensors);
447 connectionStatus = initializeHidlServiceV2_X();
448 }
449
450 return connectionStatus;
451 }
452
connectHidlServiceV2_1()453 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::connectHidlServiceV2_1() {
454 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
455 sp<android::hardware::sensors::V2_1::ISensors> sensors =
456 android::hardware::sensors::V2_1::ISensors::getService();
457
458 if (sensors == nullptr) {
459 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
460 } else {
461 mSensors = new ISensorsWrapperV2_1(sensors);
462 connectionStatus = initializeHidlServiceV2_X();
463 }
464
465 return connectionStatus;
466 }
467
initializeHidlServiceV2_X()468 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::initializeHidlServiceV2_X() {
469 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
470
471 mWakeLockQueue =
472 std::make_unique<WakeLockQueue>(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
473 true /* configureEventFlagWord */);
474
475 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
476 hardware::EventFlag::createEventFlag(mSensors->getEventQueue()->getEventFlagWord(),
477 &mEventQueueFlag);
478
479 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
480 hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakeLockQueueFlag);
481
482 CHECK(mSensors != nullptr && mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
483 mWakeLockQueueFlag != nullptr);
484
485 mCallback = sp<HidlSensorsCallback>::make(mSensorDeviceCallback);
486 status_t status =
487 checkReturnAndGetStatus(mSensors->initialize(*mWakeLockQueue->getDesc(), mCallback));
488
489 if (status != NO_ERROR) {
490 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
491 ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
492 } else {
493 connectionStatus = HalConnectionStatus::CONNECTED;
494 mSensorsHalDeathReceiver = new SensorsHalDeathReceiver(this);
495 mSensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
496 }
497
498 return connectionStatus;
499 }
500
convertToSensorEvent(const Event & src,sensors_event_t * dst)501 void HidlSensorHalWrapper::convertToSensorEvent(const Event& src, sensors_event_t* dst) {
502 android::hardware::sensors::V2_1::implementation::convertToSensorEvent(src, dst);
503 }
504
convertToSensorEvents(const hidl_vec<Event> & src,const hidl_vec<SensorInfo> & dynamicSensorsAdded,sensors_event_t * dst)505 void HidlSensorHalWrapper::convertToSensorEvents(const hidl_vec<Event>& src,
506 const hidl_vec<SensorInfo>& dynamicSensorsAdded,
507 sensors_event_t* dst) {
508 if (dynamicSensorsAdded.size() > 0 && mCallback != nullptr) {
509 mCallback->onDynamicSensorsConnected_2_1(dynamicSensorsAdded);
510 }
511
512 for (size_t i = 0; i < src.size(); ++i) {
513 convertToSensorEvent(src[i], &dst[i]);
514 }
515 }
516
517 } // namespace android
518