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 "AidlSensorHalWrapper.h"
18 #include "ISensorsWrapper.h"
19 #include "SensorDeviceUtils.h"
20 #include "android/hardware/sensors/2.0/types.h"
21 
22 #include <aidl/android/hardware/sensors/BnSensorsCallback.h>
23 #include <aidlcommonsupport/NativeHandle.h>
24 #include <android-base/logging.h>
25 #include <android/binder_manager.h>
26 #include <aidl/sensors/convert.h>
27 
28 using ::aidl::android::hardware::sensors::AdditionalInfo;
29 using ::aidl::android::hardware::sensors::DynamicSensorInfo;
30 using ::aidl::android::hardware::sensors::Event;
31 using ::aidl::android::hardware::sensors::ISensors;
32 using ::aidl::android::hardware::sensors::SensorInfo;
33 using ::aidl::android::hardware::sensors::SensorStatus;
34 using ::aidl::android::hardware::sensors::SensorType;
35 using ::android::AidlMessageQueue;
36 using ::android::hardware::EventFlag;
37 using ::android::hardware::sensors::V2_1::implementation::MAX_RECEIVE_BUFFER_EVENT_COUNT;
38 using ::android::hardware::sensors::implementation::convertToStatus;
39 using ::android::hardware::sensors::implementation::convertToSensor;
40 using ::android::hardware::sensors::implementation::convertToSensorEvent;
41 using ::android::hardware::sensors::implementation::convertFromSensorEvent;
42 
43 
44 namespace android {
45 
46 namespace {
47 
serviceDied(void * cookie)48 void serviceDied(void *cookie) {
49     ALOGW("Sensors HAL died, attempting to reconnect.");
50     ((AidlSensorHalWrapper *)cookie)->prepareForReconnect();
51 }
52 
53 template <typename EnumType>
asBaseType(EnumType value)54 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
55     return static_cast<typename std::underlying_type<EnumType>::type>(value);
56 }
57 
58 enum EventQueueFlagBitsInternal : uint32_t {
59     INTERNAL_WAKE = 1 << 16,
60 };
61 
62 } // anonymous namespace
63 
64 class AidlSensorsCallback : public ::aidl::android::hardware::sensors::BnSensorsCallback {
65 public:
AidlSensorsCallback(AidlSensorHalWrapper::SensorDeviceCallback * sensorDeviceCallback)66     AidlSensorsCallback(AidlSensorHalWrapper::SensorDeviceCallback *sensorDeviceCallback)
67           : mSensorDeviceCallback(sensorDeviceCallback) {}
68 
onDynamicSensorsConnected(const std::vector<SensorInfo> & sensorInfos)69     ::ndk::ScopedAStatus onDynamicSensorsConnected(
70             const std::vector<SensorInfo> &sensorInfos) override {
71         std::vector<sensor_t> sensors;
72         for (const SensorInfo &sensorInfo : sensorInfos) {
73             sensor_t sensor;
74             convertToSensor(sensorInfo, &sensor);
75             sensors.push_back(sensor);
76         }
77 
78         mSensorDeviceCallback->onDynamicSensorsConnected(sensors);
79         return ::ndk::ScopedAStatus::ok();
80     }
81 
onDynamicSensorsDisconnected(const std::vector<int32_t> & sensorHandles)82     ::ndk::ScopedAStatus onDynamicSensorsDisconnected(
83             const std::vector<int32_t> &sensorHandles) override {
84         mSensorDeviceCallback->onDynamicSensorsDisconnected(sensorHandles);
85         return ::ndk::ScopedAStatus::ok();
86     }
87 
88 private:
89     ISensorHalWrapper::SensorDeviceCallback *mSensorDeviceCallback;
90 };
91 
AidlSensorHalWrapper()92 AidlSensorHalWrapper::AidlSensorHalWrapper()
93       : mEventQueueFlag(nullptr),
94         mWakeLockQueueFlag(nullptr),
95         mDeathRecipient(AIBinder_DeathRecipient_new(serviceDied)) {}
96 
supportsPolling()97 bool AidlSensorHalWrapper::supportsPolling() {
98     return false;
99 }
100 
supportsMessageQueues()101 bool AidlSensorHalWrapper::supportsMessageQueues() {
102     return true;
103 }
104 
connect(SensorDeviceCallback * callback)105 bool AidlSensorHalWrapper::connect(SensorDeviceCallback *callback) {
106     mSensorDeviceCallback = callback;
107     mSensors = nullptr;
108 
109     auto aidlServiceName = std::string() + ISensors::descriptor + "/default";
110     if (AServiceManager_isDeclared(aidlServiceName.c_str())) {
111         if (mSensors != nullptr) {
112             AIBinder_unlinkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
113         }
114 
115         ndk::SpAIBinder binder(AServiceManager_waitForService(aidlServiceName.c_str()));
116         if (binder.get() != nullptr) {
117             mSensors = ISensors::fromBinder(binder);
118             mEventQueue = std::make_unique<AidlMessageQueue<
119                     Event, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
120                                                    /*configureEventFlagWord=*/true);
121 
122             mWakeLockQueue = std::make_unique<AidlMessageQueue<
123                     int32_t, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
124                                                      /*configureEventFlagWord=*/true);
125             if (mEventQueueFlag != nullptr) {
126                 EventFlag::deleteEventFlag(&mEventQueueFlag);
127             }
128             EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
129             if (mWakeLockQueueFlag != nullptr) {
130                 EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
131             }
132             EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakeLockQueueFlag);
133 
134             CHECK(mEventQueue != nullptr && mEventQueueFlag != nullptr &&
135                   mWakeLockQueue != nullptr && mWakeLockQueueFlag != nullptr);
136 
137             mCallback = ndk::SharedRefBase::make<AidlSensorsCallback>(mSensorDeviceCallback);
138             mSensors->initialize(mEventQueue->dupeDesc(), mWakeLockQueue->dupeDesc(), mCallback);
139 
140             AIBinder_linkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
141         } else {
142             ALOGE("Could not connect to declared sensors AIDL HAL");
143         }
144     }
145 
146     return mSensors != nullptr;
147 }
148 
prepareForReconnect()149 void AidlSensorHalWrapper::prepareForReconnect() {
150     mReconnecting = true;
151     if (mEventQueueFlag != nullptr) {
152         mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
153     }
154 }
155 
poll(sensors_event_t *,size_t)156 ssize_t AidlSensorHalWrapper::poll(sensors_event_t * /* buffer */, size_t /* count */) {
157     return 0;
158 }
159 
pollFmq(sensors_event_t * buffer,size_t maxNumEventsToRead)160 ssize_t AidlSensorHalWrapper::pollFmq(sensors_event_t *buffer, size_t maxNumEventsToRead) {
161     ssize_t eventsRead = 0;
162     size_t availableEvents = mEventQueue->availableToRead();
163 
164     if (availableEvents == 0) {
165         uint32_t eventFlagState = 0;
166 
167         // Wait for events to become available. This is necessary so that the Event FMQ's read() is
168         // able to be called with the correct number of events to read. If the specified number of
169         // events is not available, then read() would return no events, possibly introducing
170         // additional latency in delivering events to applications.
171         if (mEventQueueFlag != nullptr) {
172             mEventQueueFlag->wait(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_READ_AND_PROCESS) |
173                                           asBaseType(INTERNAL_WAKE),
174                                   &eventFlagState);
175         }
176         availableEvents = mEventQueue->availableToRead();
177 
178         if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
179             ALOGD("Event FMQ internal wake, returning from poll with no events");
180             return DEAD_OBJECT;
181         } else if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mInHalBypassMode &&
182                    availableEvents == 0) {
183             ALOGD("Event FMQ internal wake due to HAL Bypass Mode, returning from poll with no "
184                   "events");
185             return OK;
186         }
187     }
188 
189     size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
190     if (eventsToRead > 0) {
191         if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
192             // Notify the Sensors HAL that sensor events have been read. This is required to support
193             // the use of writeBlocking by the Sensors HAL.
194             if (mEventQueueFlag != nullptr) {
195                 mEventQueueFlag->wake(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_EVENTS_READ));
196             }
197 
198             for (size_t i = 0; i < eventsToRead; i++) {
199                 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
200             }
201             eventsRead = eventsToRead;
202         } else {
203             ALOGW("Failed to read %zu events, currently %zu events available", eventsToRead,
204                   availableEvents);
205         }
206     }
207 
208     return eventsRead;
209 }
210 
getSensorsList()211 std::vector<sensor_t> AidlSensorHalWrapper::getSensorsList() {
212     std::vector<sensor_t> sensorsFound;
213 
214     if (mSensors != nullptr) {
215         std::vector<SensorInfo> list;
216         mSensors->getSensorsList(&list);
217         for (size_t i = 0; i < list.size(); i++) {
218             sensor_t sensor;
219             convertToSensor(list[i], &sensor);
220             sensorsFound.push_back(sensor);
221         }
222     }
223 
224     return sensorsFound;
225 }
226 
setOperationMode(SensorService::Mode mode)227 status_t AidlSensorHalWrapper::setOperationMode(SensorService::Mode mode) {
228     if (mSensors == nullptr) return NO_INIT;
229     if (mode == SensorService::Mode::HAL_BYPASS_REPLAY_DATA_INJECTION) {
230         if (!mInHalBypassMode) {
231             mInHalBypassMode = true;
232             mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
233         }
234         return OK;
235     } else {
236         if (mInHalBypassMode) {
237             mInHalBypassMode = false;
238         }
239     }
240     return convertToStatus(mSensors->setOperationMode(static_cast<ISensors::OperationMode>(mode)));
241 }
242 
activate(int32_t sensorHandle,bool enabled)243 status_t AidlSensorHalWrapper::activate(int32_t sensorHandle, bool enabled) {
244     if (mSensors == nullptr) return NO_INIT;
245     return convertToStatus(mSensors->activate(sensorHandle, enabled));
246 }
247 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)248 status_t AidlSensorHalWrapper::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
249                                      int64_t maxReportLatencyNs) {
250     if (mSensors == nullptr) return NO_INIT;
251     return convertToStatus(mSensors->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs));
252 }
253 
flush(int32_t sensorHandle)254 status_t AidlSensorHalWrapper::flush(int32_t sensorHandle) {
255     if (mSensors == nullptr) return NO_INIT;
256     return convertToStatus(mSensors->flush(sensorHandle));
257 }
258 
injectSensorData(const sensors_event_t * event)259 status_t AidlSensorHalWrapper::injectSensorData(const sensors_event_t *event) {
260     if (mSensors == nullptr) return NO_INIT;
261 
262     Event ev;
263     convertFromSensorEvent(*event, &ev);
264     return convertToStatus(mSensors->injectSensorData(ev));
265 }
266 
registerDirectChannel(const sensors_direct_mem_t * memory,int32_t * channelHandle)267 status_t AidlSensorHalWrapper::registerDirectChannel(const sensors_direct_mem_t *memory,
268                                                      int32_t *channelHandle) {
269     if (mSensors == nullptr) return NO_INIT;
270 
271     ISensors::SharedMemInfo::SharedMemType type;
272     switch (memory->type) {
273         case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
274             type = ISensors::SharedMemInfo::SharedMemType::ASHMEM;
275             break;
276         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
277             type = ISensors::SharedMemInfo::SharedMemType::GRALLOC;
278             break;
279         default:
280             return BAD_VALUE;
281     }
282 
283     if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
284         return BAD_VALUE;
285     }
286     ISensors::SharedMemInfo::SharedMemFormat format =
287             ISensors::SharedMemInfo::SharedMemFormat::SENSORS_EVENT;
288 
289     ISensors::SharedMemInfo mem = {
290             .type = type,
291             .format = format,
292             .size = static_cast<int32_t>(memory->size),
293             .memoryHandle = dupToAidl(memory->handle),
294     };
295 
296     return convertToStatus(mSensors->registerDirectChannel(mem, channelHandle));
297 }
298 
unregisterDirectChannel(int32_t channelHandle)299 status_t AidlSensorHalWrapper::unregisterDirectChannel(int32_t channelHandle) {
300     if (mSensors == nullptr) return NO_INIT;
301     return convertToStatus(mSensors->unregisterDirectChannel(channelHandle));
302 }
303 
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)304 status_t AidlSensorHalWrapper::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
305                                                       const struct sensors_direct_cfg_t *config) {
306     if (mSensors == nullptr) return NO_INIT;
307 
308     ISensors::RateLevel rate;
309     switch (config->rate_level) {
310         case SENSOR_DIRECT_RATE_STOP:
311             rate = ISensors::RateLevel::STOP;
312             break;
313         case SENSOR_DIRECT_RATE_NORMAL:
314             rate = ISensors::RateLevel::NORMAL;
315             break;
316         case SENSOR_DIRECT_RATE_FAST:
317             rate = ISensors::RateLevel::FAST;
318             break;
319         case SENSOR_DIRECT_RATE_VERY_FAST:
320             rate = ISensors::RateLevel::VERY_FAST;
321             break;
322         default:
323             return BAD_VALUE;
324     }
325 
326     int32_t token;
327     status_t status = convertToStatus(
328         mSensors->configDirectReport(sensorHandle, channelHandle, rate, &token));
329     if (status == OK && rate != ISensors::RateLevel::STOP) {
330         status = static_cast<status_t>(token);
331     }
332     return status;
333 }
334 
writeWakeLockHandled(uint32_t count)335 void AidlSensorHalWrapper::writeWakeLockHandled(uint32_t count) {
336     int signedCount = (int)count;
337     if (mWakeLockQueue->write(&signedCount)) {
338         mWakeLockQueueFlag->wake(asBaseType(ISensors::WAKE_LOCK_QUEUE_FLAG_BITS_DATA_WRITTEN));
339     } else {
340         ALOGW("Failed to write wake lock handled");
341     }
342 }
343 
344 } // namespace android
345