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-base/logging.h>
20 #include <android/util/ProtoOutputStream.h>
21 #include <com_android_frameworks_sensorservice_flags.h>
22 #include <cutils/atomic.h>
23 #include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
24 #include <hardware/sensors-base.h>
25 #include <hardware/sensors.h>
26 #include <sensors/convert.h>
27 #include <utils/Errors.h>
28 #include <utils/Singleton.h>
29 
30 #include <chrono>
31 #include <cinttypes>
32 #include <condition_variable>
33 #include <cstddef>
34 #include <mutex>
35 #include <thread>
36 
37 #include "AidlSensorHalWrapper.h"
38 #include "HidlSensorHalWrapper.h"
39 #include "android/hardware/sensors/2.0/types.h"
40 #include "android/hardware/sensors/2.1/types.h"
41 #include "convertV2_1.h"
42 
43 using namespace android::hardware::sensors;
44 using android::util::ProtoOutputStream;
45 namespace sensorservice_flags = com::android::frameworks::sensorservice::flags;
46 
47 namespace android {
48 // ---------------------------------------------------------------------------
49 
50 ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
51 
52 namespace {
53 
54 template <typename EnumType>
asBaseType(EnumType value)55 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
56     return static_cast<typename std::underlying_type<EnumType>::type>(value);
57 }
58 
59 // Used internally by the framework to wake the Event FMQ. These values must start after
60 // the last value of EventQueueFlagBits
61 enum EventQueueFlagBitsInternal : uint32_t {
62     INTERNAL_WAKE = 1 << 16,
63 };
64 
65 enum DevicePrivateBase : int32_t {
66     DEVICE_PRIVATE_BASE = 65536,
67 };
68 
69 } // anonymous namespace
70 
SensorDevice()71 SensorDevice::SensorDevice() : mInHalBypassMode(false) {
72     if (!connectHalService()) {
73         return;
74     }
75 
76     initializeSensorList();
77 
78     mIsDirectReportSupported = (mHalWrapper->unregisterDirectChannel(-1) != INVALID_OPERATION);
79 }
80 
initializeSensorList()81 void SensorDevice::initializeSensorList() {
82     if (mHalWrapper == nullptr) {
83         return;
84     }
85 
86     auto list = mHalWrapper->getSensorsList();
87     const size_t count = list.size();
88 
89     mActivationCount.setCapacity(count);
90     Info model;
91     for (size_t i = 0; i < count; i++) {
92         sensor_t sensor = list[i];
93 
94         if (sensor.type < DEVICE_PRIVATE_BASE) {
95             sensor.resolution = SensorDeviceUtils::resolutionForSensor(sensor);
96 
97             // Some sensors don't have a default resolution and will be left at 0.
98             // Don't crash in this case since CTS will verify that devices don't go to
99             // production with a resolution of 0.
100             if (sensor.resolution != 0) {
101                 float quantizedRange = sensor.maxRange;
102                 SensorDeviceUtils::quantizeValue(&quantizedRange, sensor.resolution,
103                                                  /*factor=*/1);
104                 // Only rewrite maxRange if the requantization produced a "significant"
105                 // change, which is fairly arbitrarily defined as resolution / 8.
106                 // Smaller deltas are permitted, as they may simply be due to floating
107                 // point representation error, etc.
108                 if (fabsf(sensor.maxRange - quantizedRange) > sensor.resolution / 8) {
109                     ALOGW("%s's max range %.12f is not a multiple of the resolution "
110                           "%.12f - updated to %.12f",
111                           sensor.name, sensor.maxRange, sensor.resolution, quantizedRange);
112                     sensor.maxRange = quantizedRange;
113                 }
114             } else {
115                 // Don't crash here or the device will go into a crashloop.
116                 ALOGW("%s should have a non-zero resolution", sensor.name);
117             }
118         }
119 
120         // Check and clamp power if it is 0 (or close)
121         constexpr float MIN_POWER_MA = 0.001; // 1 microAmp
122         if (sensor.power < MIN_POWER_MA) {
123             ALOGI("%s's reported power %f invalid, clamped to %f", sensor.name, sensor.power,
124                   MIN_POWER_MA);
125             sensor.power = MIN_POWER_MA;
126         }
127         mSensorList.push_back(sensor);
128 
129         mActivationCount.add(list[i].handle, model);
130 
131         // Only disable all sensors on HAL 1.0 since HAL 2.0
132         // handles this in its initialize method
133         if (!mHalWrapper->supportsMessageQueues()) {
134             mHalWrapper->activate(list[i].handle, 0 /* enabled */);
135         }
136     }
137 }
138 
~SensorDevice()139 SensorDevice::~SensorDevice() {}
140 
connectHalService()141 bool SensorDevice::connectHalService() {
142     std::unique_ptr<ISensorHalWrapper> aidl_wrapper = std::make_unique<AidlSensorHalWrapper>();
143     if (aidl_wrapper->connect(this)) {
144         mHalWrapper = std::move(aidl_wrapper);
145         return true;
146     }
147 
148     std::unique_ptr<ISensorHalWrapper> hidl_wrapper = std::make_unique<HidlSensorHalWrapper>();
149     if (hidl_wrapper->connect(this)) {
150         mHalWrapper = std::move(hidl_wrapper);
151         return true;
152     }
153 
154     // TODO: check aidl connection;
155     return false;
156 }
157 
prepareForReconnect()158 void SensorDevice::prepareForReconnect() {
159     mHalWrapper->prepareForReconnect();
160 }
161 
reconnect()162 void SensorDevice::reconnect() {
163     Mutex::Autolock _l(mLock);
164 
165     auto previousActivations = mActivationCount;
166     auto previousSensorList = mSensorList;
167 
168     mActivationCount.clear();
169     mSensorList.clear();
170     if (sensorservice_flags::dynamic_sensor_hal_reconnect_handling()) {
171         mConnectedDynamicSensors.clear();
172     }
173 
174     if (mHalWrapper->connect(this)) {
175         initializeSensorList();
176 
177         if (sensorHandlesChanged(previousSensorList, mSensorList)) {
178             LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
179         } else {
180             reactivateSensors(previousActivations);
181         }
182     }
183     mHalWrapper->mReconnecting = false;
184 }
185 
sensorHandlesChanged(const std::vector<sensor_t> & oldSensorList,const std::vector<sensor_t> & newSensorList)186 bool SensorDevice::sensorHandlesChanged(const std::vector<sensor_t>& oldSensorList,
187                                         const std::vector<sensor_t>& newSensorList) {
188     bool didChange = false;
189 
190     if (oldSensorList.size() != newSensorList.size()) {
191         ALOGI("Sensor list size changed from %zu to %zu", oldSensorList.size(),
192               newSensorList.size());
193         didChange = true;
194     }
195 
196     for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
197         bool found = false;
198         const sensor_t& newSensor = newSensorList[i];
199         for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
200             const sensor_t& prevSensor = oldSensorList[j];
201             if (prevSensor.handle == newSensor.handle) {
202                 found = true;
203                 if (!sensorIsEquivalent(prevSensor, newSensor)) {
204                     ALOGI("Sensor %s not equivalent to previous version", newSensor.name);
205                     didChange = true;
206                 }
207             }
208         }
209 
210         if (!found) {
211             // Could not find the new sensor in the old list of sensors, the lists must
212             // have changed.
213             ALOGI("Sensor %s (handle %d) did not exist before", newSensor.name, newSensor.handle);
214             didChange = true;
215         }
216     }
217     return didChange;
218 }
219 
sensorIsEquivalent(const sensor_t & prevSensor,const sensor_t & newSensor)220 bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
221     bool equivalent = true;
222     if (prevSensor.handle != newSensor.handle ||
223         (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
224         (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
225         (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
226         (prevSensor.version != newSensor.version) || (prevSensor.type != newSensor.type) ||
227         (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
228         (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
229         (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
230         (prevSensor.minDelay != newSensor.minDelay) ||
231         (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
232         (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
233         (prevSensor.maxDelay != newSensor.maxDelay) || (prevSensor.flags != newSensor.flags)) {
234         equivalent = false;
235     }
236     return equivalent;
237 }
238 
reactivateSensors(const DefaultKeyedVector<int,Info> & previousActivations)239 void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
240     for (size_t i = 0; i < mSensorList.size(); i++) {
241         int handle = mSensorList[i].handle;
242         ssize_t activationIndex = previousActivations.indexOfKey(handle);
243         if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
244             continue;
245         }
246 
247         const Info& info = previousActivations[activationIndex];
248         for (size_t j = 0; j < info.batchParams.size(); j++) {
249             const BatchParams& batchParams = info.batchParams[j];
250             status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
251                                        batchParams.mTSample, batchParams.mTBatch);
252 
253             if (res == NO_ERROR) {
254                 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
255             }
256         }
257     }
258 }
259 
handleDynamicSensorConnection(int handle,bool connected)260 void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
261     // not need to check mSensors because this is is only called after successful poll()
262     if (connected) {
263         Info model;
264         mActivationCount.add(handle, model);
265         mHalWrapper->activate(handle, 0 /* enabled */);
266     } else {
267         mActivationCount.removeItem(handle);
268     }
269 }
270 
dump() const271 std::string SensorDevice::dump() const {
272     if (mHalWrapper == nullptr) return "HAL not initialized\n";
273 
274     String8 result;
275     result.appendFormat("Total %zu h/w sensors, %zu running %zu disabled clients:\n",
276                         mSensorList.size(), mActivationCount.size(), mDisabledClients.size());
277 
278     Mutex::Autolock _l(mLock);
279     for (const auto& s : mSensorList) {
280         int32_t handle = s.handle;
281         const Info& info = mActivationCount.valueFor(handle);
282         if (info.numActiveClients() == 0) continue;
283 
284         result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
285 
286         result.append("sampling_period(ms) = {");
287         for (size_t j = 0; j < info.batchParams.size(); j++) {
288             const BatchParams& params = info.batchParams[j];
289             result.appendFormat("%.1f%s%s", params.mTSample / 1e6f,
290                                 isClientDisabledLocked(info.batchParams.keyAt(j)) ? "(disabled)"
291                                                                                   : "",
292                                 (j < info.batchParams.size() - 1) ? ", " : "");
293         }
294         result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
295 
296         result.append("batching_period(ms) = {");
297         for (size_t j = 0; j < info.batchParams.size(); j++) {
298             const BatchParams& params = info.batchParams[j];
299             result.appendFormat("%.1f%s%s", params.mTBatch / 1e6f,
300                                 isClientDisabledLocked(info.batchParams.keyAt(j)) ? "(disabled)"
301                                                                                   : "",
302                                 (j < info.batchParams.size() - 1) ? ", " : "");
303         }
304         result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
305     }
306 
307     return result.c_str();
308 }
309 
310 /**
311  * Dump debugging information as android.service.SensorDeviceProto protobuf message using
312  * ProtoOutputStream.
313  *
314  * See proto definition and some notes about ProtoOutputStream in
315  * frameworks/base/core/proto/android/service/sensor_service.proto
316  */
dump(ProtoOutputStream * proto) const317 void SensorDevice::dump(ProtoOutputStream* proto) const {
318     using namespace service::SensorDeviceProto;
319     if (mHalWrapper == nullptr) {
320         proto->write(INITIALIZED, false);
321         return;
322     }
323     proto->write(INITIALIZED, true);
324     proto->write(TOTAL_SENSORS, int(mSensorList.size()));
325     proto->write(ACTIVE_SENSORS, int(mActivationCount.size()));
326 
327     Mutex::Autolock _l(mLock);
328     for (const auto& s : mSensorList) {
329         int32_t handle = s.handle;
330         const Info& info = mActivationCount.valueFor(handle);
331         if (info.numActiveClients() == 0) continue;
332 
333         uint64_t token = proto->start(SENSORS);
334         proto->write(SensorProto::HANDLE, handle);
335         proto->write(SensorProto::ACTIVE_COUNT, int(info.batchParams.size()));
336         for (size_t j = 0; j < info.batchParams.size(); j++) {
337             const BatchParams& params = info.batchParams[j];
338             proto->write(SensorProto::SAMPLING_PERIOD_MS, params.mTSample / 1e6f);
339             proto->write(SensorProto::BATCHING_PERIOD_MS, params.mTBatch / 1e6f);
340         }
341         proto->write(SensorProto::SAMPLING_PERIOD_SELECTED, info.bestBatchParams.mTSample / 1e6f);
342         proto->write(SensorProto::BATCHING_PERIOD_SELECTED, info.bestBatchParams.mTBatch / 1e6f);
343         proto->end(token);
344     }
345 }
346 
getDynamicSensorHandles()347 std::vector<int32_t> SensorDevice::getDynamicSensorHandles() {
348     std::vector<int32_t> sensorHandles;
349     std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
350     for (auto& sensors : mConnectedDynamicSensors) {
351         sensorHandles.push_back(sensors.first);
352     }
353     return sensorHandles;
354 }
355 
getSensorList(sensor_t const ** list)356 ssize_t SensorDevice::getSensorList(sensor_t const** list) {
357     *list = &mSensorList[0];
358 
359     return mSensorList.size();
360 }
361 
initCheck() const362 status_t SensorDevice::initCheck() const {
363     return mHalWrapper != nullptr ? NO_ERROR : NO_INIT;
364 }
365 
poll(sensors_event_t * buffer,size_t count)366 ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
367     if (mHalWrapper == nullptr) return NO_INIT;
368 
369     ssize_t eventsRead = 0;
370     if (mInHalBypassMode) [[unlikely]] {
371         eventsRead = getHalBypassInjectedEvents(buffer, count);
372     } else {
373         if (mHalWrapper->supportsMessageQueues()) {
374             eventsRead = mHalWrapper->pollFmq(buffer, count);
375         } else if (mHalWrapper->supportsPolling()) {
376             eventsRead = mHalWrapper->poll(buffer, count);
377         } else {
378             ALOGE("Must support polling or FMQ");
379             eventsRead = -1;
380         }
381     }
382 
383     if (eventsRead > 0) {
384         for (ssize_t i = 0; i < eventsRead; i++) {
385             float resolution = getResolutionForSensor(buffer[i].sensor);
386             android::SensorDeviceUtils::quantizeSensorEventValues(&buffer[i], resolution);
387 
388             if (buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
389                 struct dynamic_sensor_meta_event& dyn = buffer[i].dynamic_sensor_meta;
390                 if (dyn.connected) {
391                     std::unique_lock<std::mutex> lock(mDynamicSensorsMutex);
392                     // Give MAX_DYN_SENSOR_WAIT_SEC for onDynamicSensorsConnected to be invoked
393                     // since it can be received out of order from this event due to a bug in the
394                     // HIDL spec that marks it as oneway.
395                     auto it = mConnectedDynamicSensors.find(dyn.handle);
396                     if (it == mConnectedDynamicSensors.end()) {
397                         mDynamicSensorsCv.wait_for(lock, MAX_DYN_SENSOR_WAIT, [&, dyn] {
398                             return mConnectedDynamicSensors.find(dyn.handle) !=
399                                     mConnectedDynamicSensors.end();
400                         });
401                         it = mConnectedDynamicSensors.find(dyn.handle);
402                         CHECK(it != mConnectedDynamicSensors.end());
403                     }
404 
405                     dyn.sensor = &it->second;
406                 }
407             }
408         }
409     }
410 
411     return eventsRead;
412 }
413 
onDynamicSensorsConnected(const std::vector<sensor_t> & dynamicSensorsAdded)414 void SensorDevice::onDynamicSensorsConnected(const std::vector<sensor_t>& dynamicSensorsAdded) {
415     std::unique_lock<std::mutex> lock(mDynamicSensorsMutex);
416 
417     // Allocate a sensor_t structure for each dynamic sensor added and insert
418     // it into the dictionary of connected dynamic sensors keyed by handle.
419     for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
420         const sensor_t& sensor = dynamicSensorsAdded[i];
421 
422         auto it = mConnectedDynamicSensors.find(sensor.handle);
423         CHECK(it == mConnectedDynamicSensors.end());
424 
425         mConnectedDynamicSensors.insert(std::make_pair(sensor.handle, sensor));
426     }
427 
428     mDynamicSensorsCv.notify_all();
429 }
430 
onDynamicSensorsDisconnected(const std::vector<int32_t> &)431 void SensorDevice::onDynamicSensorsDisconnected(
432         const std::vector<int32_t>& /*dynamicSensorHandlesRemoved*/) {
433     // This function is currently a no-op has removing data in mConnectedDynamicSensors here will
434     // cause a race condition between when this callback is invoked and when the dynamic sensor meta
435     // event is processed by polling. The clean up should only happen after processing the meta
436     // event. See the call stack of cleanupDisconnectedDynamicSensor.
437 }
438 
cleanupDisconnectedDynamicSensor(int handle)439 void SensorDevice::cleanupDisconnectedDynamicSensor(int handle) {
440     std::lock_guard<std::mutex> lock(mDynamicSensorsMutex);
441     auto it = mConnectedDynamicSensors.find(handle);
442     if (it != mConnectedDynamicSensors.end()) {
443         mConnectedDynamicSensors.erase(it);
444     }
445 }
446 
writeWakeLockHandled(uint32_t count)447 void SensorDevice::writeWakeLockHandled(uint32_t count) {
448     if (mHalWrapper != nullptr && mHalWrapper->supportsMessageQueues()) {
449         mHalWrapper->writeWakeLockHandled(count);
450     }
451 }
452 
autoDisable(void * ident,int handle)453 void SensorDevice::autoDisable(void* ident, int handle) {
454     Mutex::Autolock _l(mLock);
455     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
456     if (activationIndex < 0) {
457         ALOGW("Handle %d cannot be found in activation record", handle);
458         return;
459     }
460     Info& info(mActivationCount.editValueAt(activationIndex));
461     info.removeBatchParamsForIdent(ident);
462     if (info.numActiveClients() == 0) {
463         info.isActive = false;
464     }
465 }
466 
activate(void * ident,int handle,int enabled)467 status_t SensorDevice::activate(void* ident, int handle, int enabled) {
468     if (mHalWrapper == nullptr) return NO_INIT;
469 
470     Mutex::Autolock _l(mLock);
471     return activateLocked(ident, handle, enabled);
472 }
473 
activateLocked(void * ident,int handle,int enabled)474 status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
475     bool activateHardware = false;
476 
477     status_t err(NO_ERROR);
478 
479     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
480     if (activationIndex < 0) {
481         ALOGW("Handle %d cannot be found in activation record", handle);
482         return BAD_VALUE;
483     }
484     Info& info(mActivationCount.editValueAt(activationIndex));
485 
486     ALOGD_IF(DEBUG_CONNECTIONS,
487              "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu", ident,
488              handle, enabled, info.batchParams.size());
489 
490     if (enabled) {
491         ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
492 
493         if (isClientDisabledLocked(ident)) {
494             ALOGW("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d", ident,
495                   handle);
496             return NO_ERROR;
497         }
498 
499         if (info.batchParams.indexOfKey(ident) >= 0) {
500             if (info.numActiveClients() > 0 && !info.isActive) {
501                 activateHardware = true;
502             }
503         } else {
504             // Log error. Every activate call should be preceded by a batch() call.
505             ALOGE("\t >>>ERROR: activate called without batch");
506         }
507     } else {
508         ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
509 
510         // TODO(b/316958439): Remove these line after
511         // sensor_device_on_dynamic_sensor_disconnected is ramped up. Bounded
512         // here since this function is coupled with
513         // dynamic_sensors_hal_disconnect_dynamic_sensor flag. If a connected
514         // dynamic sensor is deactivated, remove it from the dictionary.
515         auto it = mConnectedDynamicSensors.find(handle);
516         if (it != mConnectedDynamicSensors.end()) {
517           mConnectedDynamicSensors.erase(it);
518         }
519         // End of TODO(b/316958439)
520 
521         if (info.removeBatchParamsForIdent(ident) >= 0) {
522             if (info.numActiveClients() == 0) {
523                 // This is the last connection, we need to de-activate the underlying h/w sensor.
524                 activateHardware = true;
525             } else {
526                 // Call batch for this sensor with the previously calculated best effort
527                 // batch_rate and timeout. One of the apps has unregistered for sensor
528                 // events, and the best effort batch parameters might have changed.
529                 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64,
530                          handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
531                 mHalWrapper->batch(handle, info.bestBatchParams.mTSample,
532                                    info.bestBatchParams.mTBatch);
533             }
534         } else {
535             // sensor wasn't enabled for this ident
536         }
537 
538         if (isClientDisabledLocked(ident)) {
539             return NO_ERROR;
540         }
541     }
542 
543     if (activateHardware) {
544         err = doActivateHardwareLocked(handle, enabled);
545 
546         if (err != NO_ERROR && enabled) {
547             // Failure when enabling the sensor. Clean up on failure.
548             info.removeBatchParamsForIdent(ident);
549         } else {
550             // Update the isActive flag if there is no error. If there is an error when disabling a
551             // sensor, still set the flag to false since the batch parameters have already been
552             // removed. This ensures that everything remains in-sync.
553             info.isActive = enabled;
554         }
555     }
556 
557     return err;
558 }
559 
doActivateHardwareLocked(int handle,bool enabled)560 status_t SensorDevice::doActivateHardwareLocked(int handle, bool enabled) {
561     ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
562              enabled);
563     status_t err = mHalWrapper->activate(handle, enabled);
564     ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
565              strerror(-err));
566     return err;
567 }
568 
batch(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)569 status_t SensorDevice::batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
570                              int64_t maxBatchReportLatencyNs) {
571     if (mHalWrapper == nullptr) return NO_INIT;
572 
573     if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
574         samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
575     }
576     if (maxBatchReportLatencyNs < 0) {
577         maxBatchReportLatencyNs = 0;
578     }
579 
580     ALOGD_IF(DEBUG_CONNECTIONS,
581              "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64
582              " timeout=%" PRId64,
583              ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
584 
585     Mutex::Autolock _l(mLock);
586     return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
587 }
588 
batchLocked(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)589 status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
590                                    int64_t maxBatchReportLatencyNs) {
591     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
592     if (activationIndex < 0) {
593         ALOGW("Handle %d cannot be found in activation record", handle);
594         return BAD_VALUE;
595     }
596     Info& info(mActivationCount.editValueAt(activationIndex));
597 
598     if (info.batchParams.indexOfKey(ident) < 0) {
599         BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
600         info.batchParams.add(ident, params);
601     } else {
602         // A batch has already been called with this ident. Update the batch parameters.
603         info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
604     }
605 
606     status_t err = updateBatchParamsLocked(handle, info);
607     if (err != NO_ERROR) {
608         ALOGE("sensor batch failed 0x%08x %" PRId64 " %" PRId64 " err=%s", handle,
609               info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch, strerror(-err));
610         info.removeBatchParamsForIdent(ident);
611     }
612 
613     return err;
614 }
615 
updateBatchParamsLocked(int handle,Info & info)616 status_t SensorDevice::updateBatchParamsLocked(int handle, Info& info) {
617     BatchParams prevBestBatchParams = info.bestBatchParams;
618     // Find the minimum of all timeouts and batch_rates for this sensor.
619     info.selectBatchParams();
620 
621     ALOGD_IF(DEBUG_CONNECTIONS,
622              "\t>>> curr_period=%" PRId64 " min_period=%" PRId64 " curr_timeout=%" PRId64
623              " min_timeout=%" PRId64,
624              prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
625              prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
626 
627     status_t err(NO_ERROR);
628     // If the min period or min timeout has changed since the last batch call, call batch.
629     if (prevBestBatchParams != info.bestBatchParams && info.numActiveClients() > 0) {
630         ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
631                  info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
632         err = mHalWrapper->batch(handle, info.bestBatchParams.mTSample,
633                                  info.bestBatchParams.mTBatch);
634     }
635 
636     return err;
637 }
638 
setDelay(void * ident,int handle,int64_t samplingPeriodNs)639 status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
640     return batch(ident, handle, 0, samplingPeriodNs, 0);
641 }
642 
getHalDeviceVersion() const643 int SensorDevice::getHalDeviceVersion() const {
644     if (mHalWrapper == nullptr) return -1;
645     return SENSORS_DEVICE_API_VERSION_1_4;
646 }
647 
flush(void * ident,int handle)648 status_t SensorDevice::flush(void* ident, int handle) {
649     if (mHalWrapper == nullptr) return NO_INIT;
650     if (isClientDisabled(ident)) return INVALID_OPERATION;
651     ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
652     return mHalWrapper->flush(handle);
653 }
654 
isClientDisabled(void * ident) const655 bool SensorDevice::isClientDisabled(void* ident) const {
656     Mutex::Autolock _l(mLock);
657     return isClientDisabledLocked(ident);
658 }
659 
isClientDisabledLocked(void * ident) const660 bool SensorDevice::isClientDisabledLocked(void* ident) const {
661     return mDisabledClients.count(ident) > 0;
662 }
663 
getDisabledClientsLocked() const664 std::vector<void*> SensorDevice::getDisabledClientsLocked() const {
665     std::vector<void*> vec;
666     for (const auto& it : mDisabledClients) {
667         vec.push_back(it.first);
668     }
669 
670     return vec;
671 }
672 
addDisabledReasonForIdentLocked(void * ident,DisabledReason reason)673 void SensorDevice::addDisabledReasonForIdentLocked(void* ident, DisabledReason reason) {
674     mDisabledClients[ident] |= 1 << reason;
675 }
676 
removeDisabledReasonForIdentLocked(void * ident,DisabledReason reason)677 void SensorDevice::removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason) {
678     if (isClientDisabledLocked(ident)) {
679         mDisabledClients[ident] &= ~(1 << reason);
680         if (mDisabledClients[ident] == 0) {
681             mDisabledClients.erase(ident);
682         }
683     }
684 }
685 
setUidStateForConnection(void * ident,SensorService::UidState state)686 void SensorDevice::setUidStateForConnection(void* ident, SensorService::UidState state) {
687     Mutex::Autolock _l(mLock);
688     if (state == SensorService::UID_STATE_ACTIVE) {
689         removeDisabledReasonForIdentLocked(ident, DisabledReason::DISABLED_REASON_UID_IDLE);
690     } else {
691         addDisabledReasonForIdentLocked(ident, DisabledReason::DISABLED_REASON_UID_IDLE);
692     }
693 
694     for (size_t i = 0; i < mActivationCount.size(); ++i) {
695         int handle = mActivationCount.keyAt(i);
696         Info& info = mActivationCount.editValueAt(i);
697 
698         if (info.hasBatchParamsForIdent(ident)) {
699             updateBatchParamsLocked(handle, info);
700             bool disable = info.numActiveClients() == 0 && info.isActive;
701             bool enable = info.numActiveClients() > 0 && !info.isActive;
702 
703             if ((enable || disable) && doActivateHardwareLocked(handle, enable) == NO_ERROR) {
704                 info.isActive = enable;
705             }
706         }
707     }
708 }
709 
isSensorActive(int handle) const710 bool SensorDevice::isSensorActive(int handle) const {
711     Mutex::Autolock _l(mLock);
712     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
713     if (activationIndex < 0) {
714         return false;
715     }
716     return mActivationCount.valueAt(activationIndex).isActive;
717 }
718 
onMicSensorAccessChanged(void * ident,int handle,nsecs_t samplingPeriodNs)719 void SensorDevice::onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs) {
720     Mutex::Autolock _l(mLock);
721     ssize_t activationIndex = mActivationCount.indexOfKey(handle);
722     if (activationIndex < 0) {
723         ALOGW("Handle %d cannot be found in activation record", handle);
724         return;
725     }
726     Info& info(mActivationCount.editValueAt(activationIndex));
727     if (info.hasBatchParamsForIdent(ident)) {
728         ssize_t index = info.batchParams.indexOfKey(ident);
729         BatchParams& params = info.batchParams.editValueAt(index);
730         params.mTSample = samplingPeriodNs;
731     }
732 }
733 
enableAllSensors()734 void SensorDevice::enableAllSensors() {
735     if (mHalWrapper == nullptr) return;
736     Mutex::Autolock _l(mLock);
737 
738     for (void* client : getDisabledClientsLocked()) {
739         removeDisabledReasonForIdentLocked(client,
740                                            DisabledReason::DISABLED_REASON_SERVICE_RESTRICTED);
741     }
742 
743     for (size_t i = 0; i < mActivationCount.size(); ++i) {
744         Info& info = mActivationCount.editValueAt(i);
745         if (info.batchParams.isEmpty()) continue;
746         info.selectBatchParams();
747         const int sensor_handle = mActivationCount.keyAt(i);
748         ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
749                  sensor_handle);
750         status_t err = mHalWrapper->batch(sensor_handle, info.bestBatchParams.mTSample,
751                                           info.bestBatchParams.mTBatch);
752         ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
753 
754         if (err == NO_ERROR) {
755             err = mHalWrapper->activate(sensor_handle, 1 /* enabled */);
756             ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
757         }
758 
759         if (err == NO_ERROR) {
760             info.isActive = true;
761         }
762     }
763 }
764 
disableAllSensors()765 void SensorDevice::disableAllSensors() {
766     if (mHalWrapper == nullptr) return;
767     Mutex::Autolock _l(mLock);
768     for (size_t i = 0; i < mActivationCount.size(); ++i) {
769         Info& info = mActivationCount.editValueAt(i);
770         // Check if this sensor has been activated previously and disable it.
771         if (info.batchParams.size() > 0) {
772             const int sensor_handle = mActivationCount.keyAt(i);
773             ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
774                      sensor_handle);
775             mHalWrapper->activate(sensor_handle, 0 /* enabled */);
776 
777             // Add all the connections that were registered for this sensor to the disabled
778             // clients list.
779             for (size_t j = 0; j < info.batchParams.size(); ++j) {
780                 addDisabledReasonForIdentLocked(info.batchParams.keyAt(j),
781                                                 DisabledReason::DISABLED_REASON_SERVICE_RESTRICTED);
782                 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
783             }
784 
785             info.isActive = false;
786         }
787     }
788 }
789 
injectSensorData(const sensors_event_t * injected_sensor_event)790 status_t SensorDevice::injectSensorData(const sensors_event_t* injected_sensor_event) {
791     if (mHalWrapper == nullptr) return NO_INIT;
792     ALOGD_IF(DEBUG_CONNECTIONS,
793              "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
794              injected_sensor_event->sensor, injected_sensor_event->timestamp,
795              injected_sensor_event->data[0], injected_sensor_event->data[1],
796              injected_sensor_event->data[2], injected_sensor_event->data[3],
797              injected_sensor_event->data[4], injected_sensor_event->data[5]);
798 
799     if (mInHalBypassMode) {
800         std::lock_guard _l(mHalBypassLock);
801         mHalBypassInjectedEventQueue.push(*injected_sensor_event);
802         mHalBypassCV.notify_one();
803         return OK;
804     }
805     return mHalWrapper->injectSensorData(injected_sensor_event);
806 }
807 
setMode(uint32_t mode)808 status_t SensorDevice::setMode(uint32_t mode) {
809     if (mHalWrapper == nullptr) return NO_INIT;
810     if (mode == SensorService::Mode::HAL_BYPASS_REPLAY_DATA_INJECTION) {
811         if (!mInHalBypassMode) {
812             std::lock_guard _l(mHalBypassLock);
813             while (!mHalBypassInjectedEventQueue.empty()) {
814                 // flush any stale events from the injected event queue
815                 mHalBypassInjectedEventQueue.pop();
816             }
817             mInHalBypassMode = true;
818         }
819     } else {
820         if (mInHalBypassMode) {
821             // We are transitioning out of HAL Bypass mode. We need to notify the reader thread
822             // (specifically getHalBypassInjectedEvents()) of this change in state so that it is not
823             // stuck waiting on more injected events to come and therefore preventing events coming
824             // from the HAL from being read.
825             std::lock_guard _l(mHalBypassLock);
826             mInHalBypassMode = false;
827             mHalBypassCV.notify_one();
828         }
829     }
830     return mHalWrapper->setOperationMode(static_cast<SensorService::Mode>(mode));
831 }
832 
registerDirectChannel(const sensors_direct_mem_t * memory)833 int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
834     if (mHalWrapper == nullptr) return NO_INIT;
835     Mutex::Autolock _l(mLock);
836 
837     int32_t channelHandle;
838     status_t status = mHalWrapper->registerDirectChannel(memory, &channelHandle);
839     if (status != OK) {
840         channelHandle = -1;
841     }
842 
843     return channelHandle;
844 }
845 
unregisterDirectChannel(int32_t channelHandle)846 void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
847     mHalWrapper->unregisterDirectChannel(channelHandle);
848 }
849 
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)850 int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
851                                              const struct sensors_direct_cfg_t* config) {
852     if (mHalWrapper == nullptr) return NO_INIT;
853     Mutex::Autolock _l(mLock);
854 
855     return mHalWrapper->configureDirectChannel(sensorHandle, channelHandle, config);
856 }
857 
858 // ---------------------------------------------------------------------------
859 
numActiveClients() const860 int SensorDevice::Info::numActiveClients() const {
861     SensorDevice& device(SensorDevice::getInstance());
862     int num = 0;
863     for (size_t i = 0; i < batchParams.size(); ++i) {
864         if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
865             ++num;
866         }
867     }
868     return num;
869 }
870 
setBatchParamsForIdent(void * ident,int,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)871 status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int, int64_t samplingPeriodNs,
872                                                     int64_t maxBatchReportLatencyNs) {
873     ssize_t index = batchParams.indexOfKey(ident);
874     if (index < 0) {
875         ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64 " timeout=%" PRId64
876               ") failed (%s)",
877               ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
878         return BAD_INDEX;
879     }
880     BatchParams& params = batchParams.editValueAt(index);
881     params.mTSample = samplingPeriodNs;
882     params.mTBatch = maxBatchReportLatencyNs;
883     return NO_ERROR;
884 }
885 
selectBatchParams()886 void SensorDevice::Info::selectBatchParams() {
887     BatchParams bestParams; // default to max Tsample and max Tbatch
888     SensorDevice& device(SensorDevice::getInstance());
889 
890     for (size_t i = 0; i < batchParams.size(); ++i) {
891         if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
892             continue;
893         }
894         bestParams.merge(batchParams[i]);
895     }
896     // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
897     if (bestParams.mTBatch <= bestParams.mTSample) {
898         bestParams.mTBatch = 0;
899     }
900     bestBatchParams = bestParams;
901 }
902 
removeBatchParamsForIdent(void * ident)903 ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
904     ssize_t idx = batchParams.removeItem(ident);
905     if (idx >= 0) {
906         selectBatchParams();
907     }
908     return idx;
909 }
910 
notifyConnectionDestroyed(void * ident)911 void SensorDevice::notifyConnectionDestroyed(void* ident) {
912     Mutex::Autolock _l(mLock);
913     mDisabledClients.erase(ident);
914 }
915 
isDirectReportSupported() const916 bool SensorDevice::isDirectReportSupported() const {
917     return mIsDirectReportSupported;
918 }
919 
getResolutionForSensor(int sensorHandle)920 float SensorDevice::getResolutionForSensor(int sensorHandle) {
921     for (size_t i = 0; i < mSensorList.size(); i++) {
922         if (sensorHandle == mSensorList[i].handle) {
923             return mSensorList[i].resolution;
924         }
925     }
926 
927     auto it = mConnectedDynamicSensors.find(sensorHandle);
928     if (it != mConnectedDynamicSensors.end()) {
929         return it->second.resolution;
930     }
931 
932     return 0;
933 }
934 
getHalBypassInjectedEvents(sensors_event_t * buffer,size_t maxNumEventsToRead)935 ssize_t SensorDevice::getHalBypassInjectedEvents(sensors_event_t* buffer,
936                                                  size_t maxNumEventsToRead) {
937     std::unique_lock _l(mHalBypassLock);
938     if (mHalBypassInjectedEventQueue.empty()) {
939         // if the injected event queue is empty, block and wait till there are events to process
940         // or if we are no longer in HAL Bypass mode so that this method is not called in a tight
941         // loop. Otherwise, continue copying the injected events into the supplied buffer.
942         mHalBypassCV.wait(_l, [this] {
943             return (!mHalBypassInjectedEventQueue.empty() || !mInHalBypassMode);
944         });
945     }
946     size_t eventsToRead = std::min(mHalBypassInjectedEventQueue.size(), maxNumEventsToRead);
947     for (size_t i = 0; i < eventsToRead; i++) {
948         buffer[i] = mHalBypassInjectedEventQueue.front();
949         mHalBypassInjectedEventQueue.pop();
950     }
951     return eventsToRead;
952 }
953 
954 // ---------------------------------------------------------------------------
955 }; // namespace android
956