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         } else if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mInHalBypassMode &&
207                    availableEvents == 0) {
208             ALOGD("Event FMQ internal wake due to HAL Bypass Mode, returning from poll with no "
209                   "events");
210             return OK;
211         }
212     }
213 
214     size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
215     if (eventsToRead > 0) {
216         if (mSensors->getEventQueue()->read(mEventBuffer.data(), eventsToRead)) {
217             // Notify the Sensors HAL that sensor events have been read. This is required to support
218             // the use of writeBlocking by the Sensors HAL.
219             if (mEventQueueFlag != nullptr) {
220                 mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
221             }
222 
223             for (size_t i = 0; i < eventsToRead; i++) {
224                 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
225             }
226             eventsRead = eventsToRead;
227         } else {
228             ALOGW("Failed to read %zu events, currently %zu events available", eventsToRead,
229                   availableEvents);
230         }
231     }
232 
233     return eventsRead;
234 }
235 
getSensorsList()236 std::vector<sensor_t> HidlSensorHalWrapper::getSensorsList() {
237     std::vector<sensor_t> sensorsFound;
238     if (mSensors != nullptr) {
239         checkReturn(mSensors->getSensorsList([&](const auto& list) {
240             for (size_t i = 0; i < list.size(); i++) {
241                 sensor_t sensor;
242                 convertToSensor(list[i], &sensor);
243                 sensorsFound.push_back(sensor);
244 
245                 // Only disable all sensors on HAL 1.0 since HAL 2.0
246                 // handles this in its initialize method
247                 if (!mSensors->supportsMessageQueues()) {
248                     checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
249                 }
250             }
251         }));
252     }
253 
254     return sensorsFound;
255 }
256 
setOperationMode(SensorService::Mode mode)257 status_t HidlSensorHalWrapper::setOperationMode(SensorService::Mode mode) {
258     if (mSensors == nullptr) return NO_INIT;
259     if (mode == SensorService::Mode::HAL_BYPASS_REPLAY_DATA_INJECTION) {
260         if (!mInHalBypassMode) {
261             mInHalBypassMode = true;
262             mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
263         }
264         return OK;
265     } else {
266         if (mInHalBypassMode) {
267             mInHalBypassMode = false;
268         }
269     }
270     return checkReturnAndGetStatus(
271             mSensors->setOperationMode(static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
272 }
273 
activate(int32_t sensorHandle,bool enabled)274 status_t HidlSensorHalWrapper::activate(int32_t sensorHandle, bool enabled) {
275     if (mSensors == nullptr) return NO_INIT;
276     return checkReturnAndGetStatus(mSensors->activate(sensorHandle, enabled));
277 }
278 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)279 status_t HidlSensorHalWrapper::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
280                                      int64_t maxReportLatencyNs) {
281     if (mSensors == nullptr) return NO_INIT;
282     return checkReturnAndGetStatus(
283             mSensors->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs));
284 }
285 
flush(int32_t sensorHandle)286 status_t HidlSensorHalWrapper::flush(int32_t sensorHandle) {
287     if (mSensors == nullptr) return NO_INIT;
288     return checkReturnAndGetStatus(mSensors->flush(sensorHandle));
289 }
290 
injectSensorData(const sensors_event_t * event)291 status_t HidlSensorHalWrapper::injectSensorData(const sensors_event_t* event) {
292     if (mSensors == nullptr) return NO_INIT;
293 
294     Event ev;
295     convertFromSensorEvent(*event, &ev);
296     return checkReturnAndGetStatus(mSensors->injectSensorData(ev));
297 }
298 
registerDirectChannel(const sensors_direct_mem_t * memory,int32_t * outChannelHandle)299 status_t HidlSensorHalWrapper::registerDirectChannel(const sensors_direct_mem_t* memory,
300                                                      int32_t* outChannelHandle) {
301     if (mSensors == nullptr) return NO_INIT;
302 
303     SharedMemType type;
304     switch (memory->type) {
305         case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
306             type = SharedMemType::ASHMEM;
307             break;
308         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
309             type = SharedMemType::GRALLOC;
310             break;
311         default:
312             return BAD_VALUE;
313     }
314 
315     SharedMemFormat format;
316     if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
317         return BAD_VALUE;
318     }
319     format = SharedMemFormat::SENSORS_EVENT;
320 
321     SharedMemInfo mem = {
322             .type = type,
323             .format = format,
324             .size = static_cast<uint32_t>(memory->size),
325             .memoryHandle = memory->handle,
326     };
327 
328     status_t ret = OK;
329     checkReturn(mSensors->registerDirectChannel(mem,
330                                                 [&ret, &outChannelHandle](auto result,
331                                                                           auto channelHandle) {
332                                                     if (result == Result::OK) {
333                                                         *outChannelHandle = channelHandle;
334                                                     } else {
335                                                         ret = statusFromResult(result);
336                                                     }
337                                                 }));
338     return ret;
339 }
340 
unregisterDirectChannel(int32_t channelHandle)341 status_t HidlSensorHalWrapper::unregisterDirectChannel(int32_t channelHandle) {
342     if (mSensors == nullptr) return NO_INIT;
343     return checkReturnAndGetStatus(mSensors->unregisterDirectChannel(channelHandle));
344 }
345 
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)346 status_t HidlSensorHalWrapper::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
347                                                       const struct sensors_direct_cfg_t* config) {
348     if (mSensors == nullptr) return NO_INIT;
349 
350     RateLevel rate;
351     switch (config->rate_level) {
352         case SENSOR_DIRECT_RATE_STOP:
353             rate = RateLevel::STOP;
354             break;
355         case SENSOR_DIRECT_RATE_NORMAL:
356             rate = RateLevel::NORMAL;
357             break;
358         case SENSOR_DIRECT_RATE_FAST:
359             rate = RateLevel::FAST;
360             break;
361         case SENSOR_DIRECT_RATE_VERY_FAST:
362             rate = RateLevel::VERY_FAST;
363             break;
364         default:
365             return BAD_VALUE;
366     }
367 
368     status_t ret;
369     checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
370                                              [&ret, rate](auto result, auto token) {
371                                                  if (rate == RateLevel::STOP) {
372                                                      ret = statusFromResult(result);
373                                                  } else {
374                                                      if (result == Result::OK) {
375                                                          ret = token;
376                                                      } else {
377                                                          ret = statusFromResult(result);
378                                                      }
379                                                  }
380                                              }));
381 
382     return ret;
383 }
384 
writeWakeLockHandled(uint32_t count)385 void HidlSensorHalWrapper::writeWakeLockHandled(uint32_t count) {
386     if (mWakeLockQueue->write(&count)) {
387         mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
388     } else {
389         ALOGW("Failed to write wake lock handled");
390     }
391 }
392 
checkReturnAndGetStatus(const hardware::Return<Result> & ret)393 status_t HidlSensorHalWrapper::checkReturnAndGetStatus(const hardware::Return<Result>& ret) {
394     checkReturn(ret);
395     return (!ret.isOk()) ? DEAD_OBJECT : statusFromResult(ret);
396 }
397 
handleHidlDeath(const std::string & detail)398 void HidlSensorHalWrapper::handleHidlDeath(const std::string& detail) {
399     if (!mSensors->supportsMessageQueues()) {
400         // restart is the only option at present.
401         LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
402     } else {
403         ALOGD("ISensors HAL died, death recipient will attempt reconnect");
404     }
405 }
406 
connectHidlService()407 bool HidlSensorHalWrapper::connectHidlService() {
408     HalConnectionStatus status = connectHidlServiceV2_1();
409     if (status == HalConnectionStatus::DOES_NOT_EXIST) {
410         status = connectHidlServiceV2_0();
411     }
412 
413     if (status == HalConnectionStatus::DOES_NOT_EXIST) {
414         status = connectHidlServiceV1_0();
415     }
416     return (status == HalConnectionStatus::CONNECTED);
417 }
418 
connectHidlServiceV1_0()419 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::connectHidlServiceV1_0() {
420     // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
421     size_t retry = 10;
422     HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
423 
424     while (retry-- > 0) {
425         sp<android::hardware::sensors::V1_0::ISensors> sensors =
426                 android::hardware::sensors::V1_0::ISensors::getService();
427         if (sensors == nullptr) {
428             // no sensor hidl service found
429             connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
430             break;
431         }
432 
433         mSensors = new ISensorsWrapperV1_0(sensors);
434         mRestartWaiter->reset();
435         // Poke ISensor service. If it has lingering connection from previous generation of
436         // system server, it will kill itself. There is no intention to handle the poll result,
437         // which will be done since the size is 0.
438         if (mSensors->poll(0, [](auto, const auto&, const auto&) {}).isOk()) {
439             // ok to continue
440             connectionStatus = HalConnectionStatus::CONNECTED;
441             break;
442         }
443 
444         // hidl service is restarting, pointer is invalid.
445         mSensors = nullptr;
446         connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
447         ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
448         mRestartWaiter->wait();
449     }
450 
451     return connectionStatus;
452 }
453 
connectHidlServiceV2_0()454 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::connectHidlServiceV2_0() {
455     HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
456     sp<android::hardware::sensors::V2_0::ISensors> sensors =
457             android::hardware::sensors::V2_0::ISensors::getService();
458 
459     if (sensors == nullptr) {
460         connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
461     } else {
462         mSensors = new ISensorsWrapperV2_0(sensors);
463         connectionStatus = initializeHidlServiceV2_X();
464     }
465 
466     return connectionStatus;
467 }
468 
connectHidlServiceV2_1()469 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::connectHidlServiceV2_1() {
470     HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
471     sp<android::hardware::sensors::V2_1::ISensors> sensors =
472             android::hardware::sensors::V2_1::ISensors::getService();
473 
474     if (sensors == nullptr) {
475         connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
476     } else {
477         mSensors = new ISensorsWrapperV2_1(sensors);
478         connectionStatus = initializeHidlServiceV2_X();
479     }
480 
481     return connectionStatus;
482 }
483 
initializeHidlServiceV2_X()484 ISensorHalWrapper::HalConnectionStatus HidlSensorHalWrapper::initializeHidlServiceV2_X() {
485     HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
486 
487     mWakeLockQueue =
488             std::make_unique<WakeLockQueue>(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
489                                             true /* configureEventFlagWord */);
490 
491     hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
492     hardware::EventFlag::createEventFlag(mSensors->getEventQueue()->getEventFlagWord(),
493                                          &mEventQueueFlag);
494 
495     hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
496     hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakeLockQueueFlag);
497 
498     CHECK(mSensors != nullptr && mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
499           mWakeLockQueueFlag != nullptr);
500 
501     mCallback = sp<HidlSensorsCallback>::make(mSensorDeviceCallback);
502     status_t status =
503             checkReturnAndGetStatus(mSensors->initialize(*mWakeLockQueue->getDesc(), mCallback));
504 
505     if (status != NO_ERROR) {
506         connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
507         ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
508     } else {
509         connectionStatus = HalConnectionStatus::CONNECTED;
510         mSensorsHalDeathReceiver = new SensorsHalDeathReceiver(this);
511         mSensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
512     }
513 
514     return connectionStatus;
515 }
516 
convertToSensorEvent(const Event & src,sensors_event_t * dst)517 void HidlSensorHalWrapper::convertToSensorEvent(const Event& src, sensors_event_t* dst) {
518     android::hardware::sensors::V2_1::implementation::convertToSensorEvent(src, dst);
519 }
520 
convertToSensorEvents(const hidl_vec<Event> & src,const hidl_vec<SensorInfo> & dynamicSensorsAdded,sensors_event_t * dst)521 void HidlSensorHalWrapper::convertToSensorEvents(const hidl_vec<Event>& src,
522                                                  const hidl_vec<SensorInfo>& dynamicSensorsAdded,
523                                                  sensors_event_t* dst) {
524     if (dynamicSensorsAdded.size() > 0 && mCallback != nullptr) {
525         mCallback->onDynamicSensorsConnected_2_1(dynamicSensorsAdded);
526     }
527 
528     for (size_t i = 0; i < src.size(); ++i) {
529         convertToSensorEvent(src[i], &dst[i]);
530     }
531 }
532 
533 } // namespace android
534