2 * Copyright (C) 2013 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <hardware/sensors.h>
24 #include <cutils/atomic.h>
27 #include <cutils/log.h>
34 #include <SensorEventQueue.h>
37 static const char* CONFIG_FILENAME = "/system/etc/sensors/hals.conf";
38 static const char* LEGAL_SUBHAL_PATH_PREFIX = "/system/lib/hw/";
39 static const char* LEGAL_SUBHAL_ALTERNATE_PATH_PREFIX = "/system/vendor/lib/";
40 static const int MAX_CONF_LINE_LENGTH = 1024;
42 static pthread_mutex_t init_modules_mutex = PTHREAD_MUTEX_INITIALIZER;
43 static pthread_mutex_t init_sensors_mutex = PTHREAD_MUTEX_INITIALIZER;
45 // This mutex is shared by all queues
46 static pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
48 // Used to pause the multihal poll(). Broadcasted by sub-polling tasks if waiting_for_data.
49 static pthread_cond_t data_available_cond = PTHREAD_COND_INITIALIZER;
50 bool waiting_for_data = false;
53 * Vector of sub modules, whose indexes are referred to in this file as module_index.
55 static std::vector<hw_module_t *> *sub_hw_modules = NULL;
58 * Comparable class that globally identifies a sensor, by module index and local handle.
59 * A module index is the module's index in sub_hw_modules.
60 * A local handle is the handle the sub-module assigns to a sensor.
66 bool operator<(const FullHandle &that) const {
67 if (moduleIndex < that.moduleIndex) {
70 if (moduleIndex > that.moduleIndex) {
73 return localHandle < that.localHandle;
76 bool operator==(const FullHandle &that) const {
77 return moduleIndex == that.moduleIndex && localHandle == that.localHandle;
81 std::map<int, FullHandle> global_to_full;
82 std::map<FullHandle, int> full_to_global;
83 int next_global_handle = 1;
85 static int assign_global_handle(int module_index, int local_handle) {
86 int global_handle = next_global_handle++;
87 FullHandle full_handle;
88 full_handle.moduleIndex = module_index;
89 full_handle.localHandle = local_handle;
90 full_to_global[full_handle] = global_handle;
91 global_to_full[global_handle] = full_handle;
95 // Returns the local handle, or -1 if it does not exist.
96 static int get_local_handle(int global_handle) {
97 if (global_to_full.count(global_handle) == 0) {
98 ALOGW("Unknown global_handle %d", global_handle);
101 return global_to_full[global_handle].localHandle;
104 // Returns the sub_hw_modules index of the module that contains the sensor associates with this
105 // global_handle, or -1 if that global_handle does not exist.
106 static int get_module_index(int global_handle) {
107 if (global_to_full.count(global_handle) == 0) {
108 ALOGW("Unknown global_handle %d", global_handle);
111 FullHandle f = global_to_full[global_handle];
112 ALOGV("FullHandle for global_handle %d: moduleIndex %d, localHandle %d",
113 global_handle, f.moduleIndex, f.localHandle);
114 return f.moduleIndex;
117 // Returns the global handle for this full_handle, or -1 if the full_handle is unknown.
118 static int get_global_handle(FullHandle* full_handle) {
119 int global_handle = -1;
120 if (full_to_global.count(*full_handle)) {
121 global_handle = full_to_global[*full_handle];
123 ALOGW("Unknown FullHandle: moduleIndex %d, localHandle %d",
124 full_handle->moduleIndex, full_handle->localHandle);
126 return global_handle;
129 static const int SENSOR_EVENT_QUEUE_CAPACITY = 20;
132 sensors_poll_device_t* device;
133 SensorEventQueue* queue;
136 void *writerTask(void* ptr) {
137 ALOGV("writerTask STARTS");
138 TaskContext* ctx = (TaskContext*)ptr;
139 sensors_poll_device_t* device = ctx->device;
140 SensorEventQueue* queue = ctx->queue;
141 sensors_event_t* buffer;
144 pthread_mutex_lock(&queue_mutex);
145 if (queue->waitForSpace(&queue_mutex)) {
146 ALOGV("writerTask waited for space");
148 int bufferSize = queue->getWritableRegion(SENSOR_EVENT_QUEUE_CAPACITY, &buffer);
149 // Do blocking poll outside of lock
150 pthread_mutex_unlock(&queue_mutex);
152 ALOGV("writerTask before poll() - bufferSize = %d", bufferSize);
153 eventsPolled = device->poll(device, buffer, bufferSize);
154 ALOGV("writerTask poll() got %d events.", eventsPolled);
155 if (eventsPolled == 0) {
158 pthread_mutex_lock(&queue_mutex);
159 queue->markAsWritten(eventsPolled);
160 ALOGV("writerTask wrote %d events", eventsPolled);
161 if (waiting_for_data) {
162 ALOGV("writerTask - broadcast data_available_cond");
163 pthread_cond_broadcast(&data_available_cond);
165 pthread_mutex_unlock(&queue_mutex);
167 // never actually returns
172 * Cache of all sensors, with original handles replaced by global handles.
173 * This will be handled to get_sensors_list() callers.
175 static struct sensor_t const* global_sensors_list = NULL;
176 static int global_sensors_count = -1;
179 * Extends a sensors_poll_device_1 by including all the sub-module's devices.
181 struct sensors_poll_context_t {
183 * This is the device that SensorDevice.cpp uses to make API calls
184 * to the multihal, which fans them out to sub-HALs.
186 sensors_poll_device_1 proxy_device; // must be first
188 void addSubHwDevice(struct hw_device_t*);
190 int activate(int handle, int enabled);
191 int setDelay(int handle, int64_t ns);
192 int poll(sensors_event_t* data, int count);
193 int batch(int handle, int flags, int64_t period_ns, int64_t timeout);
194 int flush(int handle);
197 std::vector<hw_device_t*> sub_hw_devices;
198 std::vector<SensorEventQueue*> queues;
199 std::vector<pthread_t> threads;
202 sensors_poll_device_t* get_v0_device_by_handle(int global_handle);
203 sensors_poll_device_1_t* get_v1_device_by_handle(int global_handle);
204 int get_device_version_by_handle(int global_handle);
206 void copy_event_remap_handle(sensors_event_t* src, sensors_event_t* dest, int sub_index);
209 void sensors_poll_context_t::addSubHwDevice(struct hw_device_t* sub_hw_device) {
210 ALOGV("addSubHwDevice");
211 this->sub_hw_devices.push_back(sub_hw_device);
213 SensorEventQueue *queue = new SensorEventQueue(SENSOR_EVENT_QUEUE_CAPACITY);
214 this->queues.push_back(queue);
216 TaskContext* taskContext = new TaskContext();
217 taskContext->device = (sensors_poll_device_t*) sub_hw_device;
218 taskContext->queue = queue;
220 pthread_t writerThread;
221 pthread_create(&writerThread, NULL, writerTask, taskContext);
222 this->threads.push_back(writerThread);
225 // Returns the device pointer, or NULL if the global handle is invalid.
226 sensors_poll_device_t* sensors_poll_context_t::get_v0_device_by_handle(int global_handle) {
227 int sub_index = get_module_index(global_handle);
228 if (sub_index < 0 || sub_index >= this->sub_hw_devices.size()) {
231 return (sensors_poll_device_t*) this->sub_hw_devices[sub_index];
234 // Returns the device pointer, or NULL if the global handle is invalid.
235 sensors_poll_device_1_t* sensors_poll_context_t::get_v1_device_by_handle(int global_handle) {
236 int sub_index = get_module_index(global_handle);
237 if (sub_index < 0 || sub_index >= this->sub_hw_devices.size()) {
240 return (sensors_poll_device_1_t*) this->sub_hw_devices[sub_index];
243 // Returns the device version, or -1 if the handle is invalid.
244 int sensors_poll_context_t::get_device_version_by_handle(int handle) {
245 sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
247 return v0->common.version;
253 int sensors_poll_context_t::activate(int handle, int enabled) {
254 int retval = -EINVAL;
256 int local_handle = get_local_handle(handle);
257 sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
258 if (local_handle >= 0 && v0) {
259 retval = v0->activate(v0, local_handle, enabled);
261 ALOGV("retval %d", retval);
265 int sensors_poll_context_t::setDelay(int handle, int64_t ns) {
266 int retval = -EINVAL;
268 int local_handle = get_local_handle(handle);
269 sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
270 if (local_handle >= 0 && v0) {
271 retval = v0->setDelay(v0, local_handle, ns);
273 ALOGV("retval %d", retval);
277 void sensors_poll_context_t::copy_event_remap_handle(sensors_event_t* dest, sensors_event_t* src,
279 memcpy(dest, src, sizeof(struct sensors_event_t));
280 // A normal event's "sensor" field is a local handle. Convert it to a global handle.
281 // A meta-data event must have its sensor set to 0, but it has a nested event
282 // with a local handle that needs to be converted to a global handle.
283 FullHandle full_handle;
284 full_handle.moduleIndex = sub_index;
286 // If it's a metadata event, rewrite the inner payload, not the sensor field.
287 // If the event's sensor field is unregistered for any reason, rewrite the sensor field
288 // with a -1, instead of writing an incorrect but plausible sensor number, because
289 // get_global_handle() returns -1 for unknown FullHandles.
290 if (dest->type == SENSOR_TYPE_META_DATA) {
291 full_handle.localHandle = dest->meta_data.sensor;
292 dest->meta_data.sensor = get_global_handle(&full_handle);
294 full_handle.localHandle = dest->sensor;
295 dest->sensor = get_global_handle(&full_handle);
299 int sensors_poll_context_t::poll(sensors_event_t *data, int maxReads) {
305 pthread_mutex_lock(&queue_mutex);
306 queueCount = (int)this->queues.size();
307 while (eventsRead == 0) {
308 while (empties < queueCount && eventsRead < maxReads) {
309 SensorEventQueue* queue = this->queues.at(this->nextReadIndex);
310 sensors_event_t* event = queue->peek();
315 this->copy_event_remap_handle(&data[eventsRead], event, nextReadIndex);
316 if (data[eventsRead].sensor == -1) {
317 // Bad handle, do not pass corrupted event upstream !
318 ALOGW("Dropping bad local handle event packet on the floor");
324 this->nextReadIndex = (this->nextReadIndex + 1) % queueCount;
326 if (eventsRead == 0) {
327 // The queues have been scanned and none contain data, so wait.
328 ALOGV("poll stopping to wait for data");
329 waiting_for_data = true;
330 pthread_cond_wait(&data_available_cond, &queue_mutex);
331 waiting_for_data = false;
335 pthread_mutex_unlock(&queue_mutex);
336 ALOGV("poll returning %d events.", eventsRead);
341 int sensors_poll_context_t::batch(int handle, int flags, int64_t period_ns, int64_t timeout) {
343 int retval = -EINVAL;
344 int version = this->get_device_version_by_handle(handle);
345 int local_handle = get_local_handle(handle);
346 sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(handle);
347 if (version >= SENSORS_DEVICE_API_VERSION_1_0 && local_handle >= 0 && v1) {
348 retval = v1->batch(v1, local_handle, flags, period_ns, timeout);
350 ALOGV("retval %d", retval);
354 int sensors_poll_context_t::flush(int handle) {
356 int retval = -EINVAL;
357 int version = this->get_device_version_by_handle(handle);
358 int local_handle = get_local_handle(handle);
359 sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(handle);
360 if (version >= SENSORS_DEVICE_API_VERSION_1_0 && local_handle >= 0 && v1) {
361 retval = v1->flush(v1, local_handle);
363 ALOGV("retval %d", retval);
367 int sensors_poll_context_t::close() {
369 for (std::vector<hw_device_t*>::iterator it = this->sub_hw_devices.begin();
370 it != this->sub_hw_devices.end(); it++) {
371 hw_device_t* dev = *it;
372 int retval = dev->close(dev);
373 ALOGV("retval %d", retval);
379 static int device__close(struct hw_device_t *dev) {
380 sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
382 int retval = ctx->close();
388 static int device__activate(struct sensors_poll_device_t *dev, int handle,
390 sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
391 return ctx->activate(handle, enabled);
394 static int device__setDelay(struct sensors_poll_device_t *dev, int handle,
396 sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
397 return ctx->setDelay(handle, ns);
400 static int device__poll(struct sensors_poll_device_t *dev, sensors_event_t* data,
402 sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
403 return ctx->poll(data, count);
406 static int device__batch(struct sensors_poll_device_1 *dev, int handle,
407 int flags, int64_t period_ns, int64_t timeout) {
408 sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
409 return ctx->batch(handle, flags, period_ns, timeout);
412 static int device__flush(struct sensors_poll_device_1 *dev, int handle) {
413 sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
414 return ctx->flush(handle);
417 static int open_sensors(const struct hw_module_t* module, const char* name,
418 struct hw_device_t** device);
420 static bool starts_with(const char* s, const char* prefix) {
421 if (s == NULL || prefix == NULL) {
424 size_t s_size = strlen(s);
425 size_t prefix_size = strlen(prefix);
426 return s_size >= prefix_size && strncmp(s, prefix, prefix_size) == 0;
430 * Adds valid paths from the config file to the vector passed in.
431 * The vector must not be null.
433 static void get_so_paths(std::vector<char*> *so_paths) {
434 FILE *conf_file = fopen(CONFIG_FILENAME, "r");
435 if (conf_file == NULL) {
436 ALOGW("No multihal config file found at %s", CONFIG_FILENAME);
439 ALOGV("Multihal config file found at %s", CONFIG_FILENAME);
443 while (getline(&line, &len, conf_file) != -1) {
444 // overwrite trailing eoln with null char
445 char* pch = strchr(line, '\n');
449 ALOGV("config file line #%d: '%s'", ++line_count, line);
450 char *real_path = realpath(line, NULL);
451 if (starts_with(real_path, LEGAL_SUBHAL_PATH_PREFIX) ||
452 starts_with(real_path, LEGAL_SUBHAL_ALTERNATE_PATH_PREFIX)) {
453 ALOGV("accepting valid path '%s'", real_path);
454 char* compact_line = new char[strlen(real_path) + 1];
455 strcpy(compact_line, real_path);
456 so_paths->push_back(compact_line);
458 ALOGW("rejecting path '%s' because it does not start with '%s' or '%s'",
459 real_path, LEGAL_SUBHAL_PATH_PREFIX, LEGAL_SUBHAL_ALTERNATE_PATH_PREFIX);
465 ALOGV("hals.conf contained %d lines", line_count);
469 * Ensures that the sub-module array is initialized.
470 * This can be first called from get_sensors_list or from open_sensors.
472 static void lazy_init_modules() {
473 pthread_mutex_lock(&init_modules_mutex);
474 if (sub_hw_modules != NULL) {
475 pthread_mutex_unlock(&init_modules_mutex);
478 std::vector<char*> *so_paths = new std::vector<char*>();
479 get_so_paths(so_paths);
481 // dlopen the module files and cache their module symbols in sub_hw_modules
482 sub_hw_modules = new std::vector<hw_module_t *>();
483 dlerror(); // clear any old errors
484 const char* sym = HAL_MODULE_INFO_SYM_AS_STR;
485 for (std::vector<char*>::iterator it = so_paths->begin(); it != so_paths->end(); it++) {
487 void* lib_handle = dlopen(path, RTLD_LAZY);
488 if (lib_handle == NULL) {
489 ALOGW("dlerror(): %s", dlerror());
491 ALOGI("Loaded library from %s", path);
492 ALOGV("Opening symbol \"%s\"", sym);
495 struct hw_module_t* module = (hw_module_t*) dlsym(lib_handle, sym);
497 if ((error = dlerror()) != NULL) {
498 ALOGW("Error calling dlsym: %s", error);
499 } else if (module == NULL) {
500 ALOGW("module == NULL");
502 ALOGV("Loaded symbols from \"%s\"", sym);
503 sub_hw_modules->push_back(module);
507 pthread_mutex_unlock(&init_modules_mutex);
511 * Lazy-initializes global_sensors_count, global_sensors_list, and module_sensor_handles.
513 static void lazy_init_sensors_list() {
514 ALOGV("lazy_init_sensors_list");
515 pthread_mutex_lock(&init_sensors_mutex);
516 if (global_sensors_list != NULL) {
517 // already initialized
518 pthread_mutex_unlock(&init_sensors_mutex);
519 ALOGV("lazy_init_sensors_list - early return");
523 ALOGV("lazy_init_sensors_list needs to do work");
526 // Count all the sensors, then allocate an array of blanks.
527 global_sensors_count = 0;
528 const struct sensor_t *subhal_sensors_list;
529 for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
530 it != sub_hw_modules->end(); it++) {
531 struct sensors_module_t *module = (struct sensors_module_t*) *it;
532 global_sensors_count += module->get_sensors_list(module, &subhal_sensors_list);
533 ALOGV("increased global_sensors_count to %d", global_sensors_count);
536 // The global_sensors_list is full of consts.
537 // Manipulate this non-const list, and point the const one to it when we're done.
538 sensor_t* mutable_sensor_list = new sensor_t[global_sensors_count];
540 // index of the next sensor to set in mutable_sensor_list
541 int mutable_sensor_index = 0;
542 int module_index = 0;
544 for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
545 it != sub_hw_modules->end(); it++) {
546 hw_module_t *hw_module = *it;
547 ALOGV("examine one module");
548 // Read the sub-module's sensor list.
549 struct sensors_module_t *module = (struct sensors_module_t*) hw_module;
550 int module_sensor_count = module->get_sensors_list(module, &subhal_sensors_list);
551 ALOGV("the module has %d sensors", module_sensor_count);
553 // Copy the HAL's sensor list into global_sensors_list,
554 // with the handle changed to be a global handle.
555 for (int i = 0; i < module_sensor_count; i++) {
556 ALOGV("examining one sensor");
557 const struct sensor_t *local_sensor = &subhal_sensors_list[i];
558 int local_handle = local_sensor->handle;
559 memcpy(&mutable_sensor_list[mutable_sensor_index], local_sensor,
560 sizeof(struct sensor_t));
562 // Overwrite the global version's handle with a global handle.
563 int global_handle = assign_global_handle(module_index, local_handle);
565 mutable_sensor_list[mutable_sensor_index].handle = global_handle;
566 ALOGV("module_index %d, local_handle %d, global_handle %d",
567 module_index, local_handle, global_handle);
569 mutable_sensor_index++;
573 // Set the const static global_sensors_list to the mutable one allocated by this function.
574 global_sensors_list = mutable_sensor_list;
576 pthread_mutex_unlock(&init_sensors_mutex);
577 ALOGV("end lazy_init_sensors_list");
580 static int module__get_sensors_list(struct sensors_module_t* module,
581 struct sensor_t const** list) {
582 ALOGV("module__get_sensors_list start");
583 lazy_init_sensors_list();
584 *list = global_sensors_list;
585 ALOGV("global_sensors_count: %d", global_sensors_count);
586 for (int i = 0; i < global_sensors_count; i++) {
587 ALOGV("sensor type: %d", global_sensors_list[i].type);
589 return global_sensors_count;
592 static struct hw_module_methods_t sensors_module_methods = {
596 struct sensors_module_t HAL_MODULE_INFO_SYM = {
598 tag : HARDWARE_MODULE_TAG,
601 id : SENSORS_HARDWARE_MODULE_ID,
602 name : "MultiHal Sensor Module",
603 author : "Google, Inc",
604 methods : &sensors_module_methods,
608 get_sensors_list : module__get_sensors_list
611 static int open_sensors(const struct hw_module_t* hw_module, const char* name,
612 struct hw_device_t** hw_device_out) {
613 ALOGV("open_sensors begin...");
617 // Create proxy device, to return later.
618 sensors_poll_context_t *dev = new sensors_poll_context_t();
619 memset(dev, 0, sizeof(sensors_poll_device_1_t));
620 dev->proxy_device.common.tag = HARDWARE_DEVICE_TAG;
621 dev->proxy_device.common.version = SENSORS_DEVICE_API_VERSION_1_1;
622 dev->proxy_device.common.module = const_cast<hw_module_t*>(hw_module);
623 dev->proxy_device.common.close = device__close;
624 dev->proxy_device.activate = device__activate;
625 dev->proxy_device.setDelay = device__setDelay;
626 dev->proxy_device.poll = device__poll;
627 dev->proxy_device.batch = device__batch;
628 dev->proxy_device.flush = device__flush;
630 dev->nextReadIndex = 0;
632 // Open() the subhal modules. Remember their devices in a vector parallel to sub_hw_modules.
633 for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
634 it != sub_hw_modules->end(); it++) {
635 sensors_module_t *sensors_module = (sensors_module_t*) *it;
636 struct hw_device_t* sub_hw_device;
637 int sub_open_result = sensors_module->common.methods->open(*it, name, &sub_hw_device);
638 if (!sub_open_result)
639 dev->addSubHwDevice(sub_hw_device);
642 // Prepare the output param and return
643 *hw_device_out = &dev->proxy_device.common;
644 ALOGV("...open_sensors end");