1 /*
2  * Copyright (C) 2010 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 "SensorDevice.h"
18 
19 #include "android/hardware/sensors/2.0/ISensorsCallback.h"
20 #include "android/hardware/sensors/2.0/types.h"
21 #include "SensorService.h"
22 
23 #include <android-base/logging.h>
24 #include <sensors/convert.h>
25 #include <cutils/atomic.h>
26 #include <utils/Errors.h>
27 #include <utils/Singleton.h>
28 
29 #include <chrono>
30 #include <cinttypes>
31 #include <thread>
32 
33 using namespace android::hardware::sensors;
34 using namespace android::hardware::sensors::V1_0;
35 using namespace android::hardware::sensors::V1_0::implementation;
36 using android::hardware::sensors::V2_0::ISensorsCallback;
37 using android::hardware::sensors::V2_0::EventQueueFlagBits;
38 using android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
39 using android::hardware::hidl_vec;
40 using android::hardware::Return;
41 using android::SensorDeviceUtils::HidlServiceRegistrationWaiter;
42 
43 namespace android {
44 // ---------------------------------------------------------------------------
45 
46 ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
47 
48 namespace {
49 
statusFromResult(Result result)50 status_t statusFromResult(Result result) {
51     switch (result) {
52         case Result::OK:
53             return OK;
54         case Result::BAD_VALUE:
55             return BAD_VALUE;
56         case Result::PERMISSION_DENIED:
57             return PERMISSION_DENIED;
58         case Result::INVALID_OPERATION:
59             return INVALID_OPERATION;
60         case Result::NO_MEMORY:
61             return NO_MEMORY;
62     }
63 }
64 
65 template<typename EnumType>
asBaseType(EnumType value)66 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
67     return static_cast<typename std::underlying_type<EnumType>::type>(value);
68 }
69 
70 // Used internally by the framework to wake the Event FMQ. These values must start after
71 // the last value of EventQueueFlagBits
72 enum EventQueueFlagBitsInternal : uint32_t {
73     INTERNAL_WAKE =  1 << 16,
74 };
75 
76 }  // anonymous namespace
77 
serviceDied(uint64_t,const wp<::android::hidl::base::V1_0::IBase> &)78 void SensorsHalDeathReceivier::serviceDied(
79         uint64_t /* cookie */,
80         const wp<::android::hidl::base::V1_0::IBase>& /* service */) {
81     ALOGW("Sensors HAL died, attempting to reconnect.");
82     SensorDevice::getInstance().prepareForReconnect();
83 }
84 
85 struct SensorsCallback : public ISensorsCallback {
86     using Result = ::android::hardware::sensors::V1_0::Result;
onDynamicSensorsConnectedandroid::SensorsCallback87     Return<void> onDynamicSensorsConnected(
88             const hidl_vec<SensorInfo> &dynamicSensorsAdded) override {
89         return SensorDevice::getInstance().onDynamicSensorsConnected(dynamicSensorsAdded);
90     }
91 
onDynamicSensorsDisconnectedandroid::SensorsCallback92     Return<void> onDynamicSensorsDisconnected(
93             const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) override {
94         return SensorDevice::getInstance().onDynamicSensorsDisconnected(
95                 dynamicSensorHandlesRemoved);
96     }
97 };
98 
SensorDevice()99 SensorDevice::SensorDevice()
100         : mHidlTransportErrors(20),
101           mRestartWaiter(new HidlServiceRegistrationWaiter()),
102           mEventQueueFlag(nullptr),
103           mWakeLockQueueFlag(nullptr),
104           mReconnecting(false) {
105     if (!connectHidlService()) {
106         return;
107     }
108 
109     initializeSensorList();
110 
111     mIsDirectReportSupported =
112             (checkReturnAndGetStatus(mSensors->unregisterDirectChannel(-1)) != INVALID_OPERATION);
113 }
114 
initializeSensorList()115 void SensorDevice::initializeSensorList() {
116     float minPowerMa = 0.001; // 1 microAmp
117 
118     checkReturn(mSensors->getSensorsList(
119             [&](const auto &list) {
120                 const size_t count = list.size();
121 
122                 mActivationCount.setCapacity(count);
123                 Info model;
124                 for (size_t i=0 ; i < count; i++) {
125                     sensor_t sensor;
126                     convertToSensor(list[i], &sensor);
127                     // Sanity check and clamp power if it is 0 (or close)
128                     if (sensor.power < minPowerMa) {
129                         ALOGI("Reported power %f not deemed sane, clamping to %f",
130                               sensor.power, minPowerMa);
131                         sensor.power = minPowerMa;
132                     }
133                     mSensorList.push_back(sensor);
134 
135                     mActivationCount.add(list[i].sensorHandle, model);
136 
137                     checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
138                 }
139             }));
140 }
141 
~SensorDevice()142 SensorDevice::~SensorDevice() {
143     if (mEventQueueFlag != nullptr) {
144         hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
145         mEventQueueFlag = nullptr;
146     }
147 
148     if (mWakeLockQueueFlag != nullptr) {
149         hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
150         mWakeLockQueueFlag = nullptr;
151     }
152 }
153 
connectHidlService()154 bool SensorDevice::connectHidlService() {
155     HalConnectionStatus status = connectHidlServiceV2_0();
156     if (status == HalConnectionStatus::DOES_NOT_EXIST) {
157         status = connectHidlServiceV1_0();
158     }
159     return (status == HalConnectionStatus::CONNECTED);
160 }
161 
connectHidlServiceV1_0()162 SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
163     // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
164     size_t retry = 10;
165     HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
166 
167     while (retry-- > 0) {
168         sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
169         if (sensors == nullptr) {
170             // no sensor hidl service found
171             connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
172             break;
173         }
174 
175         mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors);
176         mRestartWaiter->reset();
177         // Poke ISensor service. If it has lingering connection from previous generation of
178         // system server, it will kill itself. There is no intention to handle the poll result,
179         // which will be done since the size is 0.
180         if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
181             // ok to continue
182             connectionStatus = HalConnectionStatus::CONNECTED;
183             break;
184         }
185 
186         // hidl service is restarting, pointer is invalid.
187         mSensors = nullptr;
188         connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
189         ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
190         mRestartWaiter->wait();
191     }
192 
193     return connectionStatus;
194 }
195 
connectHidlServiceV2_0()196 SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
197     HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
198     sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
199 
200     if (sensors == nullptr) {
201         connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
202     } else {
203         mSensors = new SensorServiceUtil::SensorsWrapperV2_0(sensors);
204 
205         mEventQueue = std::make_unique<EventMessageQueue>(
206                 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
207                 true /* configureEventFlagWord */);
208 
209         mWakeLockQueue = std::make_unique<WakeLockQueue>(
210                 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
211                 true /* configureEventFlagWord */);
212 
213         hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
214         hardware::EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
215 
216         hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
217         hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(),
218                                              &mWakeLockQueueFlag);
219 
220         CHECK(mSensors != nullptr && mEventQueue != nullptr &&
221                 mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
222                 mWakeLockQueueFlag != nullptr);
223 
224         status_t status = checkReturnAndGetStatus(mSensors->initialize(
225                 *mEventQueue->getDesc(),
226                 *mWakeLockQueue->getDesc(),
227                 new SensorsCallback()));
228 
229         if (status != NO_ERROR) {
230             connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
231             ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
232         } else {
233             connectionStatus = HalConnectionStatus::CONNECTED;
234             mSensorsHalDeathReceiver = new SensorsHalDeathReceivier();
235             sensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
236         }
237     }
238 
239     return connectionStatus;
240 }
241 
prepareForReconnect()242 void SensorDevice::prepareForReconnect() {
243     mReconnecting = true;
244 
245     // Wake up the polling thread so it returns and allows the SensorService to initiate
246     // a reconnect.
247     mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
248 }
249 
reconnect()250 void SensorDevice::reconnect() {
251     Mutex::Autolock _l(mLock);
252     mSensors = nullptr;
253 
254     auto previousActivations = mActivationCount;
255     auto previousSensorList = mSensorList;
256 
257     mActivationCount.clear();
258     mSensorList.clear();
259 
260     if (connectHidlServiceV2_0() == HalConnectionStatus::CONNECTED) {
261         initializeSensorList();
262 
263         if (sensorHandlesChanged(previousSensorList, mSensorList)) {
264             LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
265         } else {
266             reactivateSensors(previousActivations);
267         }
268     }
269     mReconnecting = false;
270 }
271 
sensorHandlesChanged(const Vector<sensor_t> & oldSensorList,const Vector<sensor_t> & newSensorList)272 bool SensorDevice::sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
273                                         const Vector<sensor_t>& newSensorList) {
274     bool didChange = false;
275 
276     if (oldSensorList.size() != newSensorList.size()) {
277         ALOGI("Sensor list size changed from %zu to %zu", oldSensorList.size(),
278               newSensorList.size());
279         didChange = true;
280     }
281 
282     for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
283         bool found = false;
284         const sensor_t& newSensor = newSensorList[i];
285         for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
286             const sensor_t& prevSensor = oldSensorList[j];
287             if (prevSensor.handle == newSensor.handle) {
288                 found = true;
289                 if (!sensorIsEquivalent(prevSensor, newSensor)) {
290                     ALOGI("Sensor %s not equivalent to previous version", newSensor.name);
291                     didChange = true;
292                 }
293             }
294         }
295 
296         if (!found) {
297             // Could not find the new sensor in the old list of sensors, the lists must
298             // have changed.
299             ALOGI("Sensor %s (handle %d) did not exist before", newSensor.name, newSensor.handle);
300             didChange = true;
301         }
302     }
303     return didChange;
304 }
305 
sensorIsEquivalent(const sensor_t & prevSensor,const sensor_t & newSensor)306 bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
307     bool equivalent = true;
308     if (prevSensor.handle != newSensor.handle ||
309             (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
310             (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
311             (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
312             (prevSensor.version != newSensor.version) ||
313             (prevSensor.type != newSensor.type) ||
314             (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
315             (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
316             (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
317             (prevSensor.minDelay != newSensor.minDelay) ||
318             (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
319             (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
320             (prevSensor.maxDelay != newSensor.maxDelay) ||
321             (prevSensor.flags != newSensor.flags)) {
322         equivalent = false;
323     }
324     return equivalent;
325 }
326 
reactivateSensors(const DefaultKeyedVector<int,Info> & previousActivations)327 void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
328     for (size_t i = 0; i < mSensorList.size(); i++) {
329         int handle = mSensorList[i].handle;
330         ssize_t activationIndex = previousActivations.indexOfKey(handle);
331         if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
332             continue;
333         }
334 
335         const Info& info = previousActivations[activationIndex];
336         for (size_t j = 0; j < info.batchParams.size(); j++) {
337             const BatchParams& batchParams = info.batchParams[j];
338             status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
339                     batchParams.mTSample, batchParams.mTBatch);
340 
341             if (res == NO_ERROR) {
342                 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
343             }
344         }
345     }
346 }
347 
handleDynamicSensorConnection(int handle,bool connected)348 void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
349     // not need to check mSensors because this is is only called after successful poll()
350     if (connected) {
351         Info model;
352         mActivationCount.add(handle, model);
353         checkReturn(mSensors->activate(handle, 0 /* enabled */));
354     } else {
355         mActivationCount.removeItem(handle);
356     }
357 }
358 
dump() const359 std::string SensorDevice::dump() const {
360     if (mSensors == nullptr) return "HAL not initialized\n";
361 
362     String8 result;
363     result.appendFormat("Total %zu h/w sensors, %zu running:\n",
364                         mSensorList.size(), mActivationCount.size());
365 
366     Mutex::Autolock _l(mLock);
367     for (const auto & s : mSensorList) {
368         int32_t handle = s.handle;
369         const Info& info = mActivationCount.valueFor(handle);
370         if (info.numActiveClients() == 0) continue;
371 
372         result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
373 
374         result.append("sampling_period(ms) = {");
375         for (size_t j = 0; j < info.batchParams.size(); j++) {
376             const BatchParams& params = info.batchParams[j];
377             result.appendFormat("%.1f%s", params.mTSample / 1e6f,
378                 j < info.batchParams.size() - 1 ? ", " : "");
379         }
380         result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
381 
382         result.append("batching_period(ms) = {");
383         for (size_t j = 0; j < info.batchParams.size(); j++) {
384             const BatchParams& params = info.batchParams[j];
385             result.appendFormat("%.1f%s", params.mTBatch / 1e6f,
386                     j < info.batchParams.size() - 1 ? ", " : "");
387         }
388         result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
389     }
390 
391     return result.string();
392 }
393 
getSensorList(sensor_t const ** list)394 ssize_t SensorDevice::getSensorList(sensor_t const** list) {
395     *list = &mSensorList[0];
396 
397     return mSensorList.size();
398 }
399 
initCheck() const400 status_t SensorDevice::initCheck() const {
401     return mSensors != nullptr ? NO_ERROR : NO_INIT;
402 }
403 
poll(sensors_event_t * buffer,size_t count)404 ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
405     if (mSensors == nullptr) return NO_INIT;
406 
407     ssize_t eventsRead = 0;
408     if (mSensors->supportsMessageQueues()) {
409         eventsRead = pollFmq(buffer, count);
410     } else if (mSensors->supportsPolling()) {
411         eventsRead = pollHal(buffer, count);
412     } else {
413         ALOGE("Must support polling or FMQ");
414         eventsRead = -1;
415     }
416     return eventsRead;
417 }
418 
pollHal(sensors_event_t * buffer,size_t count)419 ssize_t SensorDevice::pollHal(sensors_event_t* buffer, size_t count) {
420     ssize_t err;
421     int numHidlTransportErrors = 0;
422     bool hidlTransportError = false;
423 
424     do {
425         auto ret = mSensors->poll(
426                 count,
427                 [&](auto result,
428                     const auto &events,
429                     const auto &dynamicSensorsAdded) {
430                     if (result == Result::OK) {
431                         convertToSensorEvents(events, dynamicSensorsAdded, buffer);
432                         err = (ssize_t)events.size();
433                     } else {
434                         err = statusFromResult(result);
435                     }
436                 });
437 
438         if (ret.isOk())  {
439             hidlTransportError = false;
440         } else {
441             hidlTransportError = true;
442             numHidlTransportErrors++;
443             if (numHidlTransportErrors > 50) {
444                 // Log error and bail
445                 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
446                 handleHidlDeath(ret.description());
447             } else {
448                 std::this_thread::sleep_for(std::chrono::milliseconds(10));
449             }
450         }
451     } while (hidlTransportError);
452 
453     if(numHidlTransportErrors > 0) {
454         ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
455         HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
456         mHidlTransportErrors.add(errLog);
457         mTotalHidlTransportErrors++;
458     }
459 
460     return err;
461 }
462 
pollFmq(sensors_event_t * buffer,size_t maxNumEventsToRead)463 ssize_t SensorDevice::pollFmq(sensors_event_t* buffer, size_t maxNumEventsToRead) {
464     ssize_t eventsRead = 0;
465     size_t availableEvents = mEventQueue->availableToRead();
466 
467     if (availableEvents == 0) {
468         uint32_t eventFlagState = 0;
469 
470         // Wait for events to become available. This is necessary so that the Event FMQ's read() is
471         // able to be called with the correct number of events to read. If the specified number of
472         // events is not available, then read() would return no events, possibly introducing
473         // additional latency in delivering events to applications.
474         mEventQueueFlag->wait(asBaseType(EventQueueFlagBits::READ_AND_PROCESS) |
475                               asBaseType(INTERNAL_WAKE), &eventFlagState);
476         availableEvents = mEventQueue->availableToRead();
477 
478         if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
479             ALOGD("Event FMQ internal wake, returning from poll with no events");
480             return DEAD_OBJECT;
481         }
482     }
483 
484     size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
485     if (eventsToRead > 0) {
486         if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
487             // Notify the Sensors HAL that sensor events have been read. This is required to support
488             // the use of writeBlocking by the Sensors HAL.
489             mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
490 
491             for (size_t i = 0; i < eventsToRead; i++) {
492                 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
493             }
494             eventsRead = eventsToRead;
495         } else {
496             ALOGW("Failed to read %zu events, currently %zu events available",
497                     eventsToRead, availableEvents);
498         }
499     }
500 
501     return eventsRead;
502 }
503 
onDynamicSensorsConnected(const hidl_vec<SensorInfo> & dynamicSensorsAdded)504 Return<void> SensorDevice::onDynamicSensorsConnected(
505         const hidl_vec<SensorInfo> &dynamicSensorsAdded) {
506     // Allocate a sensor_t structure for each dynamic sensor added and insert
507     // it into the dictionary of connected dynamic sensors keyed by handle.
508     for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
509         const SensorInfo &info = dynamicSensorsAdded[i];
510 
511         auto it = mConnectedDynamicSensors.find(info.sensorHandle);
512         CHECK(it == mConnectedDynamicSensors.end());
513 
514         sensor_t *sensor = new sensor_t();
515         convertToSensor(info, sensor);
516 
517         mConnectedDynamicSensors.insert(
518                 std::make_pair(sensor->handle, sensor));
519     }
520 
521     return Return<void>();
522 }
523 
onDynamicSensorsDisconnected(const hidl_vec<int32_t> & dynamicSensorHandlesRemoved)524 Return<void> SensorDevice::onDynamicSensorsDisconnected(
525         const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) {
526     (void) dynamicSensorHandlesRemoved;
527     // TODO: Currently dynamic sensors do not seem to be removed
528     return Return<void>();
529 }
530 
writeWakeLockHandled(uint32_t count)531 void SensorDevice::writeWakeLockHandled(uint32_t count) {
532     if (mSensors != nullptr && mSensors->supportsMessageQueues()) {
533         if (mWakeLockQueue->write(&count)) {
534             mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
535         } else {
536             ALOGW("Failed to write wake lock handled");
537         }
538     }
539 }
540 
autoDisable(void * ident,int handle)541 void SensorDevice::autoDisable(void *ident, int handle) {
542     Mutex::Autolock _l(mLock);
543     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
544     if (activationIndex < 0) {
545         ALOGW("Handle %d cannot be found in activation record", handle);
546         return;
547     }
548     Info& info(mActivationCount.editValueAt(activationIndex));
549     info.removeBatchParamsForIdent(ident);
550     if (info.numActiveClients() == 0) {
551         info.isActive = false;
552     }
553 }
554 
activate(void * ident,int handle,int enabled)555 status_t SensorDevice::activate(void* ident, int handle, int enabled) {
556     if (mSensors == nullptr) return NO_INIT;
557 
558     Mutex::Autolock _l(mLock);
559     return activateLocked(ident, handle, enabled);
560 }
561 
activateLocked(void * ident,int handle,int enabled)562 status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
563     bool actuateHardware = false;
564 
565     status_t err(NO_ERROR);
566 
567     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
568     if (activationIndex < 0) {
569         ALOGW("Handle %d cannot be found in activation record", handle);
570         return BAD_VALUE;
571     }
572     Info& info(mActivationCount.editValueAt(activationIndex));
573 
574     ALOGD_IF(DEBUG_CONNECTIONS,
575              "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
576              ident, handle, enabled, info.batchParams.size());
577 
578     if (enabled) {
579         ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
580 
581         if (isClientDisabledLocked(ident)) {
582             ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
583                     ident, handle);
584             return INVALID_OPERATION;
585         }
586 
587         if (info.batchParams.indexOfKey(ident) >= 0) {
588             if (info.numActiveClients() > 0 && !info.isActive) {
589                 actuateHardware = true;
590             }
591         } else {
592             // Log error. Every activate call should be preceded by a batch() call.
593             ALOGE("\t >>>ERROR: activate called without batch");
594         }
595     } else {
596         ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
597 
598         // If a connected dynamic sensor is deactivated, remove it from the
599         // dictionary.
600         auto it = mConnectedDynamicSensors.find(handle);
601         if (it != mConnectedDynamicSensors.end()) {
602             delete it->second;
603             mConnectedDynamicSensors.erase(it);
604         }
605 
606         if (info.removeBatchParamsForIdent(ident) >= 0) {
607             if (info.numActiveClients() == 0) {
608                 // This is the last connection, we need to de-activate the underlying h/w sensor.
609                 actuateHardware = true;
610             } else {
611                 // Call batch for this sensor with the previously calculated best effort
612                 // batch_rate and timeout. One of the apps has unregistered for sensor
613                 // events, and the best effort batch parameters might have changed.
614                 ALOGD_IF(DEBUG_CONNECTIONS,
615                          "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
616                          info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
617                 checkReturn(mSensors->batch(
618                         handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
619             }
620         } else {
621             // sensor wasn't enabled for this ident
622         }
623 
624         if (isClientDisabledLocked(ident)) {
625             return NO_ERROR;
626         }
627     }
628 
629     if (actuateHardware) {
630         ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
631                  enabled);
632         err = checkReturnAndGetStatus(mSensors->activate(handle, enabled));
633         ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
634                  strerror(-err));
635 
636         if (err != NO_ERROR && enabled) {
637             // Failure when enabling the sensor. Clean up on failure.
638             info.removeBatchParamsForIdent(ident);
639         } else {
640             // Update the isActive flag if there is no error. If there is an error when disabling a
641             // sensor, still set the flag to false since the batch parameters have already been
642             // removed. This ensures that everything remains in-sync.
643             info.isActive = enabled;
644         }
645     }
646 
647     return err;
648 }
649 
batch(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)650 status_t SensorDevice::batch(
651         void* ident,
652         int handle,
653         int flags,
654         int64_t samplingPeriodNs,
655         int64_t maxBatchReportLatencyNs) {
656     if (mSensors == nullptr) return NO_INIT;
657 
658     if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
659         samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
660     }
661     if (maxBatchReportLatencyNs < 0) {
662         maxBatchReportLatencyNs = 0;
663     }
664 
665     ALOGD_IF(DEBUG_CONNECTIONS,
666              "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
667              ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
668 
669     Mutex::Autolock _l(mLock);
670     return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
671 }
672 
batchLocked(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)673 status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
674                                    int64_t maxBatchReportLatencyNs) {
675     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
676     if (activationIndex < 0) {
677         ALOGW("Handle %d cannot be found in activation record", handle);
678         return BAD_VALUE;
679     }
680     Info& info(mActivationCount.editValueAt(activationIndex));
681 
682     if (info.batchParams.indexOfKey(ident) < 0) {
683         BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
684         info.batchParams.add(ident, params);
685     } else {
686         // A batch has already been called with this ident. Update the batch parameters.
687         info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
688     }
689 
690     BatchParams prevBestBatchParams = info.bestBatchParams;
691     // Find the minimum of all timeouts and batch_rates for this sensor.
692     info.selectBatchParams();
693 
694     ALOGD_IF(DEBUG_CONNECTIONS,
695              "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
696              " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
697              prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
698              prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
699 
700     status_t err(NO_ERROR);
701     // If the min period or min timeout has changed since the last batch call, call batch.
702     if (prevBestBatchParams != info.bestBatchParams) {
703         ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
704                  info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
705         err = checkReturnAndGetStatus(mSensors->batch(
706                 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
707         if (err != NO_ERROR) {
708             ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
709                   mSensors.get(), handle, info.bestBatchParams.mTSample,
710                   info.bestBatchParams.mTBatch, strerror(-err));
711             info.removeBatchParamsForIdent(ident);
712         }
713     }
714     return err;
715 }
716 
setDelay(void * ident,int handle,int64_t samplingPeriodNs)717 status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
718     return batch(ident, handle, 0, samplingPeriodNs, 0);
719 }
720 
getHalDeviceVersion() const721 int SensorDevice::getHalDeviceVersion() const {
722     if (mSensors == nullptr) return -1;
723     return SENSORS_DEVICE_API_VERSION_1_4;
724 }
725 
flush(void * ident,int handle)726 status_t SensorDevice::flush(void* ident, int handle) {
727     if (mSensors == nullptr) return NO_INIT;
728     if (isClientDisabled(ident)) return INVALID_OPERATION;
729     ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
730     return checkReturnAndGetStatus(mSensors->flush(handle));
731 }
732 
isClientDisabled(void * ident)733 bool SensorDevice::isClientDisabled(void* ident) {
734     Mutex::Autolock _l(mLock);
735     return isClientDisabledLocked(ident);
736 }
737 
isClientDisabledLocked(void * ident)738 bool SensorDevice::isClientDisabledLocked(void* ident) {
739     return mDisabledClients.indexOf(ident) >= 0;
740 }
741 
isSensorActive(int handle) const742 bool SensorDevice::isSensorActive(int handle) const {
743     Mutex::Autolock _l(mLock);
744     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
745     if (activationIndex < 0) {
746         return false;
747     }
748     return mActivationCount.valueAt(activationIndex).numActiveClients() > 0;
749 }
750 
enableAllSensors()751 void SensorDevice::enableAllSensors() {
752     if (mSensors == nullptr) return;
753     Mutex::Autolock _l(mLock);
754     mDisabledClients.clear();
755     ALOGI("cleared mDisabledClients");
756     for (size_t i = 0; i< mActivationCount.size(); ++i) {
757         Info& info = mActivationCount.editValueAt(i);
758         if (info.batchParams.isEmpty()) continue;
759         info.selectBatchParams();
760         const int sensor_handle = mActivationCount.keyAt(i);
761         ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
762                    sensor_handle);
763         status_t err = checkReturnAndGetStatus(mSensors->batch(
764                 sensor_handle,
765                 info.bestBatchParams.mTSample,
766                 info.bestBatchParams.mTBatch));
767         ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
768 
769         if (err == NO_ERROR) {
770             err = checkReturnAndGetStatus(mSensors->activate(sensor_handle, 1 /* enabled */));
771             ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
772         }
773 
774         if (err == NO_ERROR) {
775             info.isActive = true;
776         }
777     }
778 }
779 
disableAllSensors()780 void SensorDevice::disableAllSensors() {
781     if (mSensors == nullptr) return;
782     Mutex::Autolock _l(mLock);
783     for (size_t i = 0; i< mActivationCount.size(); ++i) {
784         Info& info = mActivationCount.editValueAt(i);
785         // Check if this sensor has been activated previously and disable it.
786         if (info.batchParams.size() > 0) {
787            const int sensor_handle = mActivationCount.keyAt(i);
788            ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
789                    sensor_handle);
790            checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
791 
792            // Add all the connections that were registered for this sensor to the disabled
793            // clients list.
794            for (size_t j = 0; j < info.batchParams.size(); ++j) {
795                mDisabledClients.add(info.batchParams.keyAt(j));
796                ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
797            }
798 
799            info.isActive = false;
800         }
801     }
802 }
803 
injectSensorData(const sensors_event_t * injected_sensor_event)804 status_t SensorDevice::injectSensorData(
805         const sensors_event_t *injected_sensor_event) {
806     if (mSensors == nullptr) return NO_INIT;
807     ALOGD_IF(DEBUG_CONNECTIONS,
808             "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
809             injected_sensor_event->sensor,
810             injected_sensor_event->timestamp, injected_sensor_event->data[0],
811             injected_sensor_event->data[1], injected_sensor_event->data[2],
812             injected_sensor_event->data[3], injected_sensor_event->data[4],
813             injected_sensor_event->data[5]);
814 
815     Event ev;
816     convertFromSensorEvent(*injected_sensor_event, &ev);
817 
818     return checkReturnAndGetStatus(mSensors->injectSensorData(ev));
819 }
820 
setMode(uint32_t mode)821 status_t SensorDevice::setMode(uint32_t mode) {
822     if (mSensors == nullptr) return NO_INIT;
823     return checkReturnAndGetStatus(mSensors->setOperationMode(
824             static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
825 }
826 
registerDirectChannel(const sensors_direct_mem_t * memory)827 int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
828     if (mSensors == nullptr) return NO_INIT;
829     Mutex::Autolock _l(mLock);
830 
831     SharedMemType type;
832     switch (memory->type) {
833         case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
834             type = SharedMemType::ASHMEM;
835             break;
836         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
837             type = SharedMemType::GRALLOC;
838             break;
839         default:
840             return BAD_VALUE;
841     }
842 
843     SharedMemFormat format;
844     if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
845         return BAD_VALUE;
846     }
847     format = SharedMemFormat::SENSORS_EVENT;
848 
849     SharedMemInfo mem = {
850         .type = type,
851         .format = format,
852         .size = static_cast<uint32_t>(memory->size),
853         .memoryHandle = memory->handle,
854     };
855 
856     int32_t ret;
857     checkReturn(mSensors->registerDirectChannel(mem,
858             [&ret](auto result, auto channelHandle) {
859                 if (result == Result::OK) {
860                     ret = channelHandle;
861                 } else {
862                     ret = statusFromResult(result);
863                 }
864             }));
865     return ret;
866 }
867 
unregisterDirectChannel(int32_t channelHandle)868 void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
869     if (mSensors == nullptr) return;
870     Mutex::Autolock _l(mLock);
871     checkReturn(mSensors->unregisterDirectChannel(channelHandle));
872 }
873 
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)874 int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
875         int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
876     if (mSensors == nullptr) return NO_INIT;
877     Mutex::Autolock _l(mLock);
878 
879     RateLevel rate;
880     switch(config->rate_level) {
881         case SENSOR_DIRECT_RATE_STOP:
882             rate = RateLevel::STOP;
883             break;
884         case SENSOR_DIRECT_RATE_NORMAL:
885             rate = RateLevel::NORMAL;
886             break;
887         case SENSOR_DIRECT_RATE_FAST:
888             rate = RateLevel::FAST;
889             break;
890         case SENSOR_DIRECT_RATE_VERY_FAST:
891             rate = RateLevel::VERY_FAST;
892             break;
893         default:
894             return BAD_VALUE;
895     }
896 
897     int32_t ret;
898     checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
899             [&ret, rate] (auto result, auto token) {
900                 if (rate == RateLevel::STOP) {
901                     ret = statusFromResult(result);
902                 } else {
903                     if (result == Result::OK) {
904                         ret = token;
905                     } else {
906                         ret = statusFromResult(result);
907                     }
908                 }
909             }));
910 
911     return ret;
912 }
913 
914 // ---------------------------------------------------------------------------
915 
numActiveClients() const916 int SensorDevice::Info::numActiveClients() const {
917     SensorDevice& device(SensorDevice::getInstance());
918     int num = 0;
919     for (size_t i = 0; i < batchParams.size(); ++i) {
920         if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
921             ++num;
922         }
923     }
924     return num;
925 }
926 
setBatchParamsForIdent(void * ident,int,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)927 status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
928                                                     int64_t samplingPeriodNs,
929                                                     int64_t maxBatchReportLatencyNs) {
930     ssize_t index = batchParams.indexOfKey(ident);
931     if (index < 0) {
932         ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
933               " timeout=%" PRId64 ") failed (%s)",
934               ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
935         return BAD_INDEX;
936     }
937     BatchParams& params = batchParams.editValueAt(index);
938     params.mTSample = samplingPeriodNs;
939     params.mTBatch = maxBatchReportLatencyNs;
940     return NO_ERROR;
941 }
942 
selectBatchParams()943 void SensorDevice::Info::selectBatchParams() {
944     BatchParams bestParams; // default to max Tsample and max Tbatch
945     SensorDevice& device(SensorDevice::getInstance());
946 
947     for (size_t i = 0; i < batchParams.size(); ++i) {
948         if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
949             continue;
950         }
951         bestParams.merge(batchParams[i]);
952     }
953     // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
954     if (bestParams.mTBatch <= bestParams.mTSample) {
955         bestParams.mTBatch = 0;
956     }
957     bestBatchParams = bestParams;
958 }
959 
removeBatchParamsForIdent(void * ident)960 ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
961     ssize_t idx = batchParams.removeItem(ident);
962     if (idx >= 0) {
963         selectBatchParams();
964     }
965     return idx;
966 }
967 
notifyConnectionDestroyed(void * ident)968 void SensorDevice::notifyConnectionDestroyed(void* ident) {
969     Mutex::Autolock _l(mLock);
970     mDisabledClients.remove(ident);
971 }
972 
isDirectReportSupported() const973 bool SensorDevice::isDirectReportSupported() const {
974     return mIsDirectReportSupported;
975 }
976 
convertToSensorEvent(const Event & src,sensors_event_t * dst)977 void SensorDevice::convertToSensorEvent(
978         const Event &src, sensors_event_t *dst) {
979     ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
980             src, dst);
981 
982     if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
983         const DynamicSensorInfo &dyn = src.u.dynamic;
984 
985         dst->dynamic_sensor_meta.connected = dyn.connected;
986         dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
987         if (dyn.connected) {
988             auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
989             CHECK(it != mConnectedDynamicSensors.end());
990 
991             dst->dynamic_sensor_meta.sensor = it->second;
992 
993             memcpy(dst->dynamic_sensor_meta.uuid,
994                    dyn.uuid.data(),
995                    sizeof(dst->dynamic_sensor_meta.uuid));
996         }
997     }
998 }
999 
convertToSensorEvents(const hidl_vec<Event> & src,const hidl_vec<SensorInfo> & dynamicSensorsAdded,sensors_event_t * dst)1000 void SensorDevice::convertToSensorEvents(
1001         const hidl_vec<Event> &src,
1002         const hidl_vec<SensorInfo> &dynamicSensorsAdded,
1003         sensors_event_t *dst) {
1004 
1005     if (dynamicSensorsAdded.size() > 0) {
1006         onDynamicSensorsConnected(dynamicSensorsAdded);
1007     }
1008 
1009     for (size_t i = 0; i < src.size(); ++i) {
1010         convertToSensorEvent(src[i], &dst[i]);
1011     }
1012 }
1013 
handleHidlDeath(const std::string & detail)1014 void SensorDevice::handleHidlDeath(const std::string & detail) {
1015     if (!mSensors->supportsMessageQueues()) {
1016         // restart is the only option at present.
1017         LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
1018     } else {
1019         ALOGD("ISensors HAL died, death recipient will attempt reconnect");
1020     }
1021 }
1022 
checkReturnAndGetStatus(const Return<Result> & ret)1023 status_t SensorDevice::checkReturnAndGetStatus(const Return<Result>& ret) {
1024     checkReturn(ret);
1025     return (!ret.isOk()) ? DEAD_OBJECT : statusFromResult(ret);
1026 }
1027 
1028 // ---------------------------------------------------------------------------
1029 }; // namespace android
1030