1/*
2 * Copyright (C) 2016 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 "Sensors.h"
18#include "convert.h"
19#include "multihal.h"
20
21#include <android-base/logging.h>
22
23#include <sys/stat.h>
24
25namespace android {
26namespace hardware {
27namespace sensors {
28namespace V1_0 {
29namespace implementation {
30
31/*
32 * If a multi-hal configuration file exists in the proper location,
33 * return true indicating we need to use multi-hal functionality.
34 */
35static bool UseMultiHal() {
36    const std::string& name = MULTI_HAL_CONFIG_FILE_PATH;
37    struct stat buffer;
38    return (stat (name.c_str(), &buffer) == 0);
39}
40
41static Result ResultFromStatus(status_t err) {
42    switch (err) {
43        case OK:
44            return Result::OK;
45        case PERMISSION_DENIED:
46            return Result::PERMISSION_DENIED;
47        case NO_MEMORY:
48            return Result::NO_MEMORY;
49        case BAD_VALUE:
50            return Result::BAD_VALUE;
51        default:
52            return Result::INVALID_OPERATION;
53    }
54}
55
56Sensors::Sensors()
57    : mInitCheck(NO_INIT),
58      mSensorModule(nullptr),
59      mSensorDevice(nullptr) {
60    status_t err = OK;
61    if (UseMultiHal()) {
62        mSensorModule = ::get_multi_hal_module_info();
63    } else {
64        err = hw_get_module(
65            SENSORS_HARDWARE_MODULE_ID,
66            (hw_module_t const **)&mSensorModule);
67    }
68    if (mSensorModule == NULL) {
69        err = UNKNOWN_ERROR;
70    }
71
72    if (err != OK) {
73        LOG(ERROR) << "Couldn't load "
74                   << SENSORS_HARDWARE_MODULE_ID
75                   << " module ("
76                   << strerror(-err)
77                   << ")";
78
79        mInitCheck = err;
80        return;
81    }
82
83    err = sensors_open_1(&mSensorModule->common, &mSensorDevice);
84
85    if (err != OK) {
86        LOG(ERROR) << "Couldn't open device for module "
87                   << SENSORS_HARDWARE_MODULE_ID
88                   << " ("
89                   << strerror(-err)
90                   << ")";
91
92        mInitCheck = err;
93        return;
94    }
95
96    // Require all the old HAL APIs to be present except for injection, which
97    // is considered optional.
98    CHECK_GE(getHalDeviceVersion(), SENSORS_DEVICE_API_VERSION_1_3);
99
100    if (getHalDeviceVersion() == SENSORS_DEVICE_API_VERSION_1_4) {
101        if (mSensorDevice->inject_sensor_data == nullptr) {
102            LOG(ERROR) << "HAL specifies version 1.4, but does not implement inject_sensor_data()";
103        }
104        if (mSensorModule->set_operation_mode == nullptr) {
105            LOG(ERROR) << "HAL specifies version 1.4, but does not implement set_operation_mode()";
106        }
107    }
108
109    mInitCheck = OK;
110}
111
112status_t Sensors::initCheck() const {
113    return mInitCheck;
114}
115
116Return<void> Sensors::getSensorsList(getSensorsList_cb _hidl_cb) {
117    sensor_t const *list;
118    size_t count = mSensorModule->get_sensors_list(mSensorModule, &list);
119
120    hidl_vec<SensorInfo> out;
121    out.resize(count);
122
123    for (size_t i = 0; i < count; ++i) {
124        const sensor_t *src = &list[i];
125        SensorInfo *dst = &out[i];
126
127        convertFromSensor(*src, dst);
128    }
129
130    _hidl_cb(out);
131
132    return Void();
133}
134
135int Sensors::getHalDeviceVersion() const {
136    if (!mSensorDevice) {
137        return -1;
138    }
139
140    return mSensorDevice->common.version;
141}
142
143Return<Result> Sensors::setOperationMode(OperationMode mode) {
144    if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_4
145            || mSensorModule->set_operation_mode == nullptr) {
146        return Result::INVALID_OPERATION;
147    }
148    return ResultFromStatus(mSensorModule->set_operation_mode((uint32_t)mode));
149}
150
151Return<Result> Sensors::activate(
152        int32_t sensor_handle, bool enabled) {
153    return ResultFromStatus(
154            mSensorDevice->activate(
155                reinterpret_cast<sensors_poll_device_t *>(mSensorDevice),
156                sensor_handle,
157                enabled));
158}
159
160Return<void> Sensors::poll(int32_t maxCount, poll_cb _hidl_cb) {
161
162    hidl_vec<Event> out;
163    hidl_vec<SensorInfo> dynamicSensorsAdded;
164
165    std::unique_ptr<sensors_event_t[]> data;
166    int err = android::NO_ERROR;
167
168    { // scope of reentry lock
169
170        // This enforces a single client, meaning that a maximum of one client can call poll().
171        // If this function is re-entred, it means that we are stuck in a state that may prevent
172        // the system from proceeding normally.
173        //
174        // Exit and let the system restart the sensor-hal-implementation hidl service.
175        //
176        // This function must not call _hidl_cb(...) or return until there is no risk of blocking.
177        std::unique_lock<std::mutex> lock(mPollLock, std::try_to_lock);
178        if(!lock.owns_lock()){
179            // cannot get the lock, hidl service will go into deadlock if it is not restarted.
180            // This is guaranteed to not trigger in passthrough mode.
181            LOG(ERROR) <<
182                    "ISensors::poll() re-entry. I do not know what to do except killing myself.";
183            ::exit(-1);
184        }
185
186        if (maxCount <= 0) {
187            err = android::BAD_VALUE;
188        } else {
189            int bufferSize = maxCount <= kPollMaxBufferSize ? maxCount : kPollMaxBufferSize;
190            data.reset(new sensors_event_t[bufferSize]);
191            err = mSensorDevice->poll(
192                    reinterpret_cast<sensors_poll_device_t *>(mSensorDevice),
193                    data.get(), bufferSize);
194        }
195    }
196
197    if (err < 0) {
198        _hidl_cb(ResultFromStatus(err), out, dynamicSensorsAdded);
199        return Void();
200    }
201
202    const size_t count = (size_t)err;
203
204    for (size_t i = 0; i < count; ++i) {
205        if (data[i].type != SENSOR_TYPE_DYNAMIC_SENSOR_META) {
206            continue;
207        }
208
209        const dynamic_sensor_meta_event_t *dyn = &data[i].dynamic_sensor_meta;
210
211        if (!dyn->connected) {
212            continue;
213        }
214
215        CHECK(dyn->sensor != nullptr);
216        CHECK_EQ(dyn->sensor->handle, dyn->handle);
217
218        SensorInfo info;
219        convertFromSensor(*dyn->sensor, &info);
220
221        size_t numDynamicSensors = dynamicSensorsAdded.size();
222        dynamicSensorsAdded.resize(numDynamicSensors + 1);
223        dynamicSensorsAdded[numDynamicSensors] = info;
224    }
225
226    out.resize(count);
227    convertFromSensorEvents(err, data.get(), &out);
228
229    _hidl_cb(Result::OK, out, dynamicSensorsAdded);
230
231    return Void();
232}
233
234Return<Result> Sensors::batch(
235        int32_t sensor_handle,
236        int64_t sampling_period_ns,
237        int64_t max_report_latency_ns) {
238    return ResultFromStatus(
239            mSensorDevice->batch(
240                mSensorDevice,
241                sensor_handle,
242                0, /*flags*/
243                sampling_period_ns,
244                max_report_latency_ns));
245}
246
247Return<Result> Sensors::flush(int32_t sensor_handle) {
248    return ResultFromStatus(mSensorDevice->flush(mSensorDevice, sensor_handle));
249}
250
251Return<Result> Sensors::injectSensorData(const Event& event) {
252    if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_4
253            || mSensorDevice->inject_sensor_data == nullptr) {
254        return Result::INVALID_OPERATION;
255    }
256
257    sensors_event_t out;
258    convertToSensorEvent(event, &out);
259
260    return ResultFromStatus(
261            mSensorDevice->inject_sensor_data(mSensorDevice, &out));
262}
263
264Return<void> Sensors::registerDirectChannel(
265        const SharedMemInfo& mem, registerDirectChannel_cb _hidl_cb) {
266    if (mSensorDevice->register_direct_channel == nullptr
267            || mSensorDevice->config_direct_report == nullptr) {
268        // HAL does not support
269        _hidl_cb(Result::INVALID_OPERATION, -1);
270        return Void();
271    }
272
273    sensors_direct_mem_t m;
274    if (!convertFromSharedMemInfo(mem, &m)) {
275      _hidl_cb(Result::BAD_VALUE, -1);
276      return Void();
277    }
278
279    int err = mSensorDevice->register_direct_channel(mSensorDevice, &m, -1);
280
281    if (err < 0) {
282        _hidl_cb(ResultFromStatus(err), -1);
283    } else {
284        int32_t channelHandle = static_cast<int32_t>(err);
285        _hidl_cb(Result::OK, channelHandle);
286    }
287    return Void();
288}
289
290Return<Result> Sensors::unregisterDirectChannel(int32_t channelHandle) {
291    if (mSensorDevice->register_direct_channel == nullptr
292            || mSensorDevice->config_direct_report == nullptr) {
293        // HAL does not support
294        return Result::INVALID_OPERATION;
295    }
296
297    mSensorDevice->register_direct_channel(mSensorDevice, nullptr, channelHandle);
298
299    return Result::OK;
300}
301
302Return<void> Sensors::configDirectReport(
303        int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
304        configDirectReport_cb _hidl_cb) {
305    if (mSensorDevice->register_direct_channel == nullptr
306            || mSensorDevice->config_direct_report == nullptr) {
307        // HAL does not support
308        _hidl_cb(Result::INVALID_OPERATION, -1);
309        return Void();
310    }
311
312    sensors_direct_cfg_t cfg = {
313        .rate_level = convertFromRateLevel(rate)
314    };
315    if (cfg.rate_level < 0) {
316        _hidl_cb(Result::BAD_VALUE, -1);
317        return Void();
318    }
319
320    int err = mSensorDevice->config_direct_report(mSensorDevice,
321            sensorHandle, channelHandle, &cfg);
322
323    if (rate == RateLevel::STOP) {
324        _hidl_cb(ResultFromStatus(err), -1);
325    } else {
326        _hidl_cb(err > 0 ? Result::OK : ResultFromStatus(err), err);
327    }
328    return Void();
329}
330
331// static
332void Sensors::convertFromSensorEvents(
333        size_t count,
334        const sensors_event_t *srcArray,
335        hidl_vec<Event> *dstVec) {
336    for (size_t i = 0; i < count; ++i) {
337        const sensors_event_t &src = srcArray[i];
338        Event *dst = &(*dstVec)[i];
339
340        convertFromSensorEvent(src, dst);
341    }
342}
343
344ISensors *HIDL_FETCH_ISensors(const char * /* hal */) {
345    Sensors *sensors = new Sensors;
346    if (sensors->initCheck() != OK) {
347        delete sensors;
348        sensors = nullptr;
349
350        return nullptr;
351    }
352
353    return sensors;
354}
355
356}  // namespace implementation
357}  // namespace V1_0
358}  // namespace sensors
359}  // namespace hardware
360}  // namespace android
361