• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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 "SensorEventQueue.h"
18 #include "multihal.h"
19 
20 #define LOG_NDEBUG 1
21 #include <log/log.h>
22 #include <cutils/atomic.h>
23 #include <hardware/sensors.h>
24 
25 #include <vector>
26 #include <string>
27 #include <fstream>
28 #include <map>
29 
30 #include <dirent.h>
31 #include <dlfcn.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <limits.h>
35 #include <math.h>
36 #include <poll.h>
37 #include <pthread.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 
41 
42 static pthread_mutex_t init_modules_mutex = PTHREAD_MUTEX_INITIALIZER;
43 static pthread_mutex_t init_sensors_mutex = PTHREAD_MUTEX_INITIALIZER;
44 
45 // This mutex is shared by all queues
46 static pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
47 
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;
51 
52 // Vector of sub modules, whose indexes are referred to in this file as module_index.
53 static std::vector<hw_module_t *> *sub_hw_modules = nullptr;
54 
55 // Vector of sub modules shared object handles
56 static std::vector<void *> *so_handles = nullptr;
57 
58 /*
59  * Comparable class that globally identifies a sensor, by module index and local handle.
60  * A module index is the module's index in sub_hw_modules.
61  * A local handle is the handle the sub-module assigns to a sensor.
62  */
63 struct FullHandle {
64     int moduleIndex;
65     int localHandle;
66 
operator <FullHandle67     bool operator<(const FullHandle &that) const {
68         if (moduleIndex < that.moduleIndex) {
69             return true;
70         }
71         if (moduleIndex > that.moduleIndex) {
72             return false;
73         }
74         return localHandle < that.localHandle;
75     }
76 
operator ==FullHandle77     bool operator==(const FullHandle &that) const {
78         return moduleIndex == that.moduleIndex && localHandle == that.localHandle;
79     }
80 };
81 
82 std::map<int, FullHandle> global_to_full;
83 std::map<FullHandle, int> full_to_global;
84 int next_global_handle = 1;
85 
assign_global_handle(int module_index,int local_handle)86 static int assign_global_handle(int module_index, int local_handle) {
87     int global_handle = next_global_handle++;
88     FullHandle full_handle;
89     full_handle.moduleIndex = module_index;
90     full_handle.localHandle = local_handle;
91     full_to_global[full_handle] = global_handle;
92     global_to_full[global_handle] = full_handle;
93     return global_handle;
94 }
95 
96 // Returns the local handle, or -1 if it does not exist.
get_local_handle(int global_handle)97 static int get_local_handle(int global_handle) {
98     if (global_to_full.count(global_handle) == 0) {
99         ALOGW("Unknown global_handle %d", global_handle);
100         return -1;
101     }
102     return global_to_full[global_handle].localHandle;
103 }
104 
105 // Returns the sub_hw_modules index of the module that contains the sensor associates with this
106 // global_handle, or -1 if that global_handle does not exist.
get_module_index(int global_handle)107 static int get_module_index(int global_handle) {
108     if (global_to_full.count(global_handle) == 0) {
109         ALOGW("Unknown global_handle %d", global_handle);
110         return -1;
111     }
112     FullHandle f = global_to_full[global_handle];
113     ALOGV("FullHandle for global_handle %d: moduleIndex %d, localHandle %d",
114             global_handle, f.moduleIndex, f.localHandle);
115     return f.moduleIndex;
116 }
117 
118 // Returns the global handle for this full_handle, or -1 if the full_handle is unknown.
get_global_handle(FullHandle * full_handle)119 static int get_global_handle(FullHandle* full_handle) {
120     int global_handle = -1;
121     if (full_to_global.count(*full_handle)) {
122         global_handle = full_to_global[*full_handle];
123     } else {
124         ALOGW("Unknown FullHandle: moduleIndex %d, localHandle %d",
125             full_handle->moduleIndex, full_handle->localHandle);
126     }
127     return global_handle;
128 }
129 
130 static const int SENSOR_EVENT_QUEUE_CAPACITY = 36;
131 
132 struct TaskContext {
133   sensors_poll_device_t* device;
134   SensorEventQueue* queue;
135 };
136 
writerTask(void * ptr)137 void *writerTask(void* ptr) {
138     ALOGV("writerTask STARTS");
139     TaskContext* ctx = (TaskContext*)ptr;
140     sensors_poll_device_t* device = ctx->device;
141     SensorEventQueue* queue = ctx->queue;
142     sensors_event_t* buffer;
143     int eventsPolled;
144     while (1) {
145         pthread_mutex_lock(&queue_mutex);
146         if (queue->waitForSpace(&queue_mutex)) {
147             ALOGV("writerTask waited for space");
148         }
149         int bufferSize = queue->getWritableRegion(SENSOR_EVENT_QUEUE_CAPACITY, &buffer);
150         // Do blocking poll outside of lock
151         pthread_mutex_unlock(&queue_mutex);
152 
153         ALOGV("writerTask before poll() - bufferSize = %d", bufferSize);
154         eventsPolled = device->poll(device, buffer, bufferSize);
155         ALOGV("writerTask poll() got %d events.", eventsPolled);
156         if (eventsPolled <= 0) {
157             if (eventsPolled < 0) {
158                 ALOGV("writerTask ignored error %d from %s", eventsPolled, device->common.module->name);
159                 ALOGE("ERROR: Fix %s so it does not return error from poll()", device->common.module->name);
160             }
161             continue;
162         }
163         pthread_mutex_lock(&queue_mutex);
164         queue->markAsWritten(eventsPolled);
165         ALOGV("writerTask wrote %d events", eventsPolled);
166         if (waiting_for_data) {
167             ALOGV("writerTask - broadcast data_available_cond");
168             pthread_cond_broadcast(&data_available_cond);
169         }
170         pthread_mutex_unlock(&queue_mutex);
171     }
172     // never actually returns
173     return NULL;
174 }
175 
176 /*
177  * Cache of all sensors, with original handles replaced by global handles.
178  * This will be handled to get_sensors_list() callers.
179  */
180 static struct sensor_t const* global_sensors_list = NULL;
181 static int global_sensors_count = -1;
182 
183 /*
184  * Extends a sensors_poll_device_1 by including all the sub-module's devices.
185  */
186 struct sensors_poll_context_t {
187     /*
188      * This is the device that SensorDevice.cpp uses to make API calls
189      * to the multihal, which fans them out to sub-HALs.
190      */
191     sensors_poll_device_1 proxy_device; // must be first
192 
193     void addSubHwDevice(struct hw_device_t*);
194 
195     int activate(int handle, int enabled);
196     int setDelay(int handle, int64_t ns);
197     int poll(sensors_event_t* data, int count);
198     int batch(int handle, int flags, int64_t period_ns, int64_t timeout);
199     int flush(int handle);
200     int inject_sensor_data(const sensors_event_t *data);
201     int register_direct_channel(const struct sensors_direct_mem_t* mem,
202                                 int channel_handle);
203     int config_direct_report(int sensor_handle,
204                              int channel_handle,
205                              const struct sensors_direct_cfg_t *config);
206     int close();
207 
208     std::vector<hw_device_t*> sub_hw_devices;
209     std::vector<SensorEventQueue*> queues;
210     std::vector<pthread_t> threads;
211     int nextReadIndex;
212 
213     sensors_poll_device_t* get_v0_device_by_handle(int global_handle);
214     sensors_poll_device_1_t* get_v1_device_by_handle(int global_handle);
215     sensors_poll_device_1_t* get_primary_v1_device();
216     int get_device_version_by_handle(int global_handle);
217 
218     void copy_event_remap_handle(sensors_event_t* src, sensors_event_t* dest, int sub_index);
219 };
220 
addSubHwDevice(struct hw_device_t * sub_hw_device)221 void sensors_poll_context_t::addSubHwDevice(struct hw_device_t* sub_hw_device) {
222     ALOGV("addSubHwDevice");
223     this->sub_hw_devices.push_back(sub_hw_device);
224 
225     SensorEventQueue *queue = new SensorEventQueue(SENSOR_EVENT_QUEUE_CAPACITY);
226     this->queues.push_back(queue);
227 
228     TaskContext* taskContext = new TaskContext();
229     taskContext->device = (sensors_poll_device_t*) sub_hw_device;
230     taskContext->queue = queue;
231 
232     pthread_t writerThread;
233     pthread_create(&writerThread, NULL, writerTask, taskContext);
234     this->threads.push_back(writerThread);
235 }
236 
237 // Returns the device pointer, or NULL if the global handle is invalid.
get_v0_device_by_handle(int global_handle)238 sensors_poll_device_t* sensors_poll_context_t::get_v0_device_by_handle(int global_handle) {
239     int sub_index = get_module_index(global_handle);
240     if (sub_index < 0 || sub_index >= (int) this->sub_hw_devices.size()) {
241         return NULL;
242     }
243     return (sensors_poll_device_t*) this->sub_hw_devices[sub_index];
244 }
245 
246 // Returns the device pointer, or NULL if the global handle is invalid.
get_v1_device_by_handle(int global_handle)247 sensors_poll_device_1_t* sensors_poll_context_t::get_v1_device_by_handle(int global_handle) {
248     int sub_index = get_module_index(global_handle);
249     if (sub_index < 0 || sub_index >= (int) this->sub_hw_devices.size()) {
250         return NULL;
251     }
252     return (sensors_poll_device_1_t*) this->sub_hw_devices[sub_index];
253 }
254 
255 // Returns the device pointer, or NULL if primary hal does not exist
get_primary_v1_device()256 sensors_poll_device_1_t* sensors_poll_context_t::get_primary_v1_device() {
257     if (sub_hw_devices.size() < 1) {
258         return nullptr;
259     }
260     return (sensors_poll_device_1_t*) this->sub_hw_devices[0];
261 }
262 
263 // Returns the device version, or -1 if the handle is invalid.
get_device_version_by_handle(int handle)264 int sensors_poll_context_t::get_device_version_by_handle(int handle) {
265     sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
266     if (v0) {
267         return v0->common.version;
268     } else {
269         return -1;
270     }
271 }
272 
273 // Android N and hire require sensor HALs to be at least 1_3 compliant
274 #define HAL_VERSION_IS_COMPLIANT(version)  \
275     (version >= SENSORS_DEVICE_API_VERSION_1_3)
276 
277 // Returns true if HAL is compliant, false if HAL is not compliant or if handle is invalid
halIsCompliant(sensors_poll_context_t * ctx,int handle)278 static bool halIsCompliant(sensors_poll_context_t *ctx, int handle) {
279     int version = ctx->get_device_version_by_handle(handle);
280     return version != -1 && HAL_VERSION_IS_COMPLIANT(version);
281 }
282 
halIsAPILevelCompliant(sensors_poll_context_t * ctx,int handle,int level)283 static bool halIsAPILevelCompliant(sensors_poll_context_t *ctx, int handle, int level) {
284     int version = ctx->get_device_version_by_handle(handle);
285     return version != -1 && (version >= level);
286 }
287 
halSupportDirectSensorReport(sensors_poll_device_1_t * v1)288 static bool halSupportDirectSensorReport(sensors_poll_device_1_t* v1) {
289     return v1 != nullptr && HAL_VERSION_IS_COMPLIANT(v1->common.version) &&
290             v1->register_direct_channel != nullptr && v1->config_direct_report != nullptr;
291 }
292 
apiNumToStr(int version)293 const char *apiNumToStr(int version) {
294     switch(version) {
295     case SENSORS_DEVICE_API_VERSION_1_0:
296         return "SENSORS_DEVICE_API_VERSION_1_0";
297     case SENSORS_DEVICE_API_VERSION_1_1:
298         return "SENSORS_DEVICE_API_VERSION_1_1";
299     case SENSORS_DEVICE_API_VERSION_1_2:
300         return "SENSORS_DEVICE_API_VERSION_1_2";
301     case SENSORS_DEVICE_API_VERSION_1_3:
302         return "SENSORS_DEVICE_API_VERSION_1_3";
303     case SENSORS_DEVICE_API_VERSION_1_4:
304         return "SENSORS_DEVICE_API_VERSION_1_4";
305     default:
306         return "UNKNOWN";
307     }
308 }
309 
activate(int handle,int enabled)310 int sensors_poll_context_t::activate(int handle, int enabled) {
311     int retval = -EINVAL;
312     ALOGV("activate");
313     int local_handle = get_local_handle(handle);
314     sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
315     if (halIsCompliant(this, handle) && local_handle >= 0 && v0) {
316         retval = v0->activate(v0, local_handle, enabled);
317     } else {
318         ALOGE("IGNORING activate(enable %d) call to non-API-compliant sensor handle=%d !",
319                 enabled, handle);
320     }
321     ALOGV("retval %d", retval);
322     return retval;
323 }
324 
setDelay(int handle,int64_t ns)325 int sensors_poll_context_t::setDelay(int handle, int64_t ns) {
326     int retval = -EINVAL;
327     ALOGV("setDelay");
328     int local_handle = get_local_handle(handle);
329     sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
330     if (halIsCompliant(this, handle) && local_handle >= 0 && v0) {
331         retval = v0->setDelay(v0, local_handle, ns);
332     } else {
333         ALOGE("IGNORING setDelay() call for non-API-compliant sensor handle=%d !", handle);
334     }
335     ALOGV("retval %d", retval);
336     return retval;
337 }
338 
copy_event_remap_handle(sensors_event_t * dest,sensors_event_t * src,int sub_index)339 void sensors_poll_context_t::copy_event_remap_handle(sensors_event_t* dest, sensors_event_t* src,
340         int sub_index) {
341     memcpy(dest, src, sizeof(struct sensors_event_t));
342     // A normal event's "sensor" field is a local handle. Convert it to a global handle.
343     // A meta-data event must have its sensor set to 0, but it has a nested event
344     // with a local handle that needs to be converted to a global handle.
345     FullHandle full_handle;
346     full_handle.moduleIndex = sub_index;
347 
348     // If it's a metadata event, rewrite the inner payload, not the sensor field.
349     // If the event's sensor field is unregistered for any reason, rewrite the sensor field
350     // with a -1, instead of writing an incorrect but plausible sensor number, because
351     // get_global_handle() returns -1 for unknown FullHandles.
352     if (dest->type == SENSOR_TYPE_META_DATA) {
353         full_handle.localHandle = dest->meta_data.sensor;
354         dest->meta_data.sensor = get_global_handle(&full_handle);
355     } else {
356         full_handle.localHandle = dest->sensor;
357         dest->sensor = get_global_handle(&full_handle);
358     }
359 }
360 
poll(sensors_event_t * data,int maxReads)361 int sensors_poll_context_t::poll(sensors_event_t *data, int maxReads) {
362     ALOGV("poll");
363     int empties = 0;
364     int queueCount = 0;
365     int eventsRead = 0;
366 
367     pthread_mutex_lock(&queue_mutex);
368     queueCount = (int)this->queues.size();
369     while (eventsRead == 0) {
370         while (empties < queueCount && eventsRead < maxReads) {
371             SensorEventQueue* queue = this->queues.at(this->nextReadIndex);
372             sensors_event_t* event = queue->peek();
373             if (event == NULL) {
374                 empties++;
375             } else {
376                 empties = 0;
377                 this->copy_event_remap_handle(&data[eventsRead], event, nextReadIndex);
378                 if (data[eventsRead].sensor == SENSORS_HANDLE_BASE - 1) {
379                     // Bad handle, do not pass corrupted event upstream !
380                     ALOGW("Dropping bad local handle event packet on the floor");
381                 } else {
382                     eventsRead++;
383                 }
384                 queue->dequeue();
385             }
386             this->nextReadIndex = (this->nextReadIndex + 1) % queueCount;
387         }
388         if (eventsRead == 0) {
389             // The queues have been scanned and none contain data, so wait.
390             ALOGV("poll stopping to wait for data");
391             waiting_for_data = true;
392             pthread_cond_wait(&data_available_cond, &queue_mutex);
393             waiting_for_data = false;
394             empties = 0;
395         }
396     }
397     pthread_mutex_unlock(&queue_mutex);
398     ALOGV("poll returning %d events.", eventsRead);
399 
400     return eventsRead;
401 }
402 
batch(int handle,int flags,int64_t period_ns,int64_t timeout)403 int sensors_poll_context_t::batch(int handle, int flags, int64_t period_ns, int64_t timeout) {
404     ALOGV("batch");
405     int retval = -EINVAL;
406     int local_handle = get_local_handle(handle);
407     sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(handle);
408     if (halIsCompliant(this, handle) && local_handle >= 0 && v1) {
409         retval = v1->batch(v1, local_handle, flags, period_ns, timeout);
410     } else {
411         ALOGE("IGNORING batch() call to non-API-compliant sensor handle=%d !", handle);
412     }
413     ALOGV("retval %d", retval);
414     return retval;
415 }
416 
flush(int handle)417 int sensors_poll_context_t::flush(int handle) {
418     ALOGV("flush");
419     int retval = -EINVAL;
420     int local_handle = get_local_handle(handle);
421     sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(handle);
422     if (halIsCompliant(this, handle) && local_handle >= 0 && v1) {
423         retval = v1->flush(v1, local_handle);
424     } else {
425         ALOGE("IGNORING flush() call to non-API-compliant sensor handle=%d !", handle);
426     }
427     ALOGV("retval %d", retval);
428     return retval;
429 }
430 
inject_sensor_data(const sensors_event_t * data)431 int sensors_poll_context_t::inject_sensor_data(const sensors_event_t *data) {
432     int retval = -EINVAL;
433     ALOGV("inject_sensor_data");
434     if (data->sensor == -1) {
435         // operational parameter
436         sensors_poll_device_1_t* v1 = get_primary_v1_device();
437         if (v1 && v1->common.version >= SENSORS_DEVICE_API_VERSION_1_4) {
438             retval = v1->inject_sensor_data(v1, data);
439         } else {
440             ALOGE("IGNORED inject_sensor_data(operational param) call to non-API-compliant sensor");
441             return -ENOSYS;
442         }
443     } else {
444         // Get handle for the sensor owning the event being injected
445         int local_handle = get_local_handle(data->sensor);
446         sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(data->sensor);
447         if (halIsAPILevelCompliant(this, data->sensor, SENSORS_DEVICE_API_VERSION_1_4) &&
448                 local_handle >= 0 && v1) {
449             // if specific sensor is used, we have to replace global sensor handle
450             // with local one, before passing to concrete HAL
451             sensors_event_t data_copy = *data;
452             data_copy.sensor = local_handle;
453             retval = v1->inject_sensor_data(v1, &data_copy);
454         } else {
455             ALOGE("IGNORED inject_sensor_data(type=%d, handle=%d) call to non-API-compliant sensor",
456                     data->type, data->sensor);
457             retval = -ENOSYS;
458         }
459     }
460     ALOGV("retval %d", retval);
461     return retval;
462 }
463 
register_direct_channel(const struct sensors_direct_mem_t * mem,int channel_handle)464 int sensors_poll_context_t::register_direct_channel(const struct sensors_direct_mem_t* mem,
465                                                    int channel_handle) {
466     int retval = -EINVAL;
467     ALOGV("register_direct_channel");
468     sensors_poll_device_1_t* v1 = get_primary_v1_device();
469     if (v1 && halSupportDirectSensorReport(v1)) {
470         retval = v1->register_direct_channel(v1, mem, channel_handle);
471     } else {
472         ALOGE("IGNORED register_direct_channel(mem=%p, handle=%d) call to non-API-compliant sensor",
473                 mem, channel_handle);
474         retval = -ENOSYS;
475     }
476     ALOGV("retval %d", retval);
477     return retval;
478 }
479 
config_direct_report(int sensor_handle,int channel_handle,const struct sensors_direct_cfg_t * config)480 int sensors_poll_context_t::config_direct_report(int sensor_handle,
481                                                 int channel_handle,
482                                                 const struct sensors_direct_cfg_t *config) {
483     int retval = -EINVAL;
484     ALOGV("config_direct_report");
485 
486     if (config != nullptr) {
487         int local_handle = get_local_handle(sensor_handle);
488         sensors_poll_device_1_t* v1 = get_primary_v1_device();
489         if (v1 && halSupportDirectSensorReport(v1)) {
490             retval = v1->config_direct_report(v1, local_handle, channel_handle, config);
491         } else {
492             ALOGE("IGNORED config_direct_report(sensor=%d, channel=%d, rate_level=%d) call to "
493                   "non-API-compliant sensor", sensor_handle, channel_handle, config->rate_level);
494             retval = -ENOSYS;
495         }
496     }
497     ALOGV("retval %d", retval);
498     return retval;
499 }
close()500 int sensors_poll_context_t::close() {
501     ALOGV("close");
502     for (std::vector<hw_device_t*>::iterator it = this->sub_hw_devices.begin();
503             it != this->sub_hw_devices.end(); it++) {
504         hw_device_t* dev = *it;
505         int retval = dev->close(dev);
506         ALOGV("retval %d", retval);
507     }
508     return 0;
509 }
510 
511 
device__close(struct hw_device_t * dev)512 static int device__close(struct hw_device_t *dev) {
513     pthread_mutex_lock(&init_modules_mutex);
514     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
515     if (ctx != NULL) {
516         int retval = ctx->close();
517         delete ctx;
518         return retval;
519     }
520 
521     if (sub_hw_modules != nullptr) {
522         delete sub_hw_modules;
523         sub_hw_modules = nullptr;
524     }
525 
526     if (so_handles != nullptr) {
527         for (auto handle : *so_handles) {
528             dlclose(handle);
529         }
530         delete so_handles;
531         so_handles = nullptr;
532     }
533     pthread_mutex_unlock(&init_modules_mutex);
534     return 0;
535 }
536 
device__activate(struct sensors_poll_device_t * dev,int handle,int enabled)537 static int device__activate(struct sensors_poll_device_t *dev, int handle,
538         int enabled) {
539     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
540     return ctx->activate(handle, enabled);
541 }
542 
device__setDelay(struct sensors_poll_device_t * dev,int handle,int64_t ns)543 static int device__setDelay(struct sensors_poll_device_t *dev, int handle,
544         int64_t ns) {
545     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
546     return ctx->setDelay(handle, ns);
547 }
548 
device__poll(struct sensors_poll_device_t * dev,sensors_event_t * data,int count)549 static int device__poll(struct sensors_poll_device_t *dev, sensors_event_t* data,
550         int count) {
551     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
552     return ctx->poll(data, count);
553 }
554 
device__batch(struct sensors_poll_device_1 * dev,int handle,int flags,int64_t period_ns,int64_t timeout)555 static int device__batch(struct sensors_poll_device_1 *dev, int handle,
556         int flags, int64_t period_ns, int64_t timeout) {
557     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
558     return ctx->batch(handle, flags, period_ns, timeout);
559 }
560 
device__flush(struct sensors_poll_device_1 * dev,int handle)561 static int device__flush(struct sensors_poll_device_1 *dev, int handle) {
562     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
563     return ctx->flush(handle);
564 }
565 
device__inject_sensor_data(struct sensors_poll_device_1 * dev,const sensors_event_t * data)566 static int device__inject_sensor_data(struct sensors_poll_device_1 *dev,
567         const sensors_event_t *data) {
568     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
569     return ctx->inject_sensor_data(data);
570 }
571 
device__register_direct_channel(struct sensors_poll_device_1 * dev,const struct sensors_direct_mem_t * mem,int channel_handle)572 static int device__register_direct_channel(struct sensors_poll_device_1 *dev,
573                                            const struct sensors_direct_mem_t* mem,
574                                            int channel_handle) {
575     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
576     return ctx->register_direct_channel(mem, channel_handle);
577 }
578 
device__config_direct_report(struct sensors_poll_device_1 * dev,int sensor_handle,int channel_handle,const struct sensors_direct_cfg_t * config)579 static int device__config_direct_report(struct sensors_poll_device_1 *dev,
580                                         int sensor_handle,
581                                         int channel_handle,
582                                         const struct sensors_direct_cfg_t *config) {
583     sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
584     return ctx->config_direct_report(sensor_handle, channel_handle, config);
585 }
586 
587 static int open_sensors(const struct hw_module_t* module, const char* name,
588         struct hw_device_t** device);
589 
590 /*
591  * Adds valid paths from the config file to the vector passed in.
592  * The vector must not be null.
593  */
get_so_paths()594 static std::vector<std::string> get_so_paths() {
595     std::vector<std::string> so_paths;
596 
597     const std::vector<const char *> config_path_list(
598             { MULTI_HAL_CONFIG_FILE_PATH, DEPRECATED_MULTI_HAL_CONFIG_FILE_PATH });
599 
600     std::ifstream stream;
601     const char *path = nullptr;
602     for (auto i : config_path_list) {
603         std::ifstream f(i);
604         if (f) {
605             stream = std::move(f);
606             path = i;
607             break;
608         }
609     }
610     if(!stream) {
611         ALOGW("No multihal config file found");
612         return so_paths;
613     }
614 
615     ALOGE_IF(strcmp(path, DEPRECATED_MULTI_HAL_CONFIG_FILE_PATH) == 0,
616             "Multihal configuration file path %s is not compatible with Treble "
617             "requirements. Please move it to %s.",
618             path, MULTI_HAL_CONFIG_FILE_PATH);
619 
620     ALOGV("Multihal config file found at %s", path);
621     std::string line;
622     while (std::getline(stream, line)) {
623         ALOGV("config file line: '%s'", line.c_str());
624         so_paths.push_back(line);
625     }
626     return so_paths;
627 }
628 
629 /*
630  * Ensures that the sub-module array is initialized.
631  * This can be first called from get_sensors_list or from open_sensors.
632  */
lazy_init_modules()633 static void lazy_init_modules() {
634     pthread_mutex_lock(&init_modules_mutex);
635     if (sub_hw_modules != NULL) {
636         pthread_mutex_unlock(&init_modules_mutex);
637         return;
638     }
639     std::vector<std::string> so_paths(get_so_paths());
640 
641     // dlopen the module files and cache their module symbols in sub_hw_modules
642     sub_hw_modules = new std::vector<hw_module_t *>();
643     so_handles = new std::vector<void *>();
644     dlerror(); // clear any old errors
645     const char* sym = HAL_MODULE_INFO_SYM_AS_STR;
646     for (const auto &s : so_paths) {
647         const char* path = s.c_str();
648         void* lib_handle = dlopen(path, RTLD_LAZY);
649         if (lib_handle == NULL) {
650             ALOGW("dlerror(): %s", dlerror());
651         } else {
652             ALOGI("Loaded library from %s", path);
653             ALOGV("Opening symbol \"%s\"", sym);
654             // clear old errors
655             dlerror();
656             struct hw_module_t* module = (hw_module_t*) dlsym(lib_handle, sym);
657             const char* error;
658             if ((error = dlerror()) != NULL) {
659                 ALOGW("Error calling dlsym: %s", error);
660             } else if (module == NULL) {
661                 ALOGW("module == NULL");
662             } else {
663                 ALOGV("Loaded symbols from \"%s\"", sym);
664                 sub_hw_modules->push_back(module);
665                 so_handles->push_back(lib_handle);
666                 lib_handle = nullptr;
667             }
668         }
669         if (lib_handle != nullptr) {
670             dlclose(lib_handle);
671         }
672     }
673     pthread_mutex_unlock(&init_modules_mutex);
674 }
675 
676 /*
677  * Lazy-initializes global_sensors_count, global_sensors_list, and module_sensor_handles.
678  */
lazy_init_sensors_list()679 static void lazy_init_sensors_list() {
680     ALOGV("lazy_init_sensors_list");
681     pthread_mutex_lock(&init_sensors_mutex);
682     if (global_sensors_list != NULL) {
683         // already initialized
684         pthread_mutex_unlock(&init_sensors_mutex);
685         ALOGV("lazy_init_sensors_list - early return");
686         return;
687     }
688 
689     ALOGV("lazy_init_sensors_list needs to do work");
690     lazy_init_modules();
691 
692     // Count all the sensors, then allocate an array of blanks.
693     global_sensors_count = 0;
694     const struct sensor_t *subhal_sensors_list;
695     for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
696             it != sub_hw_modules->end(); it++) {
697         struct sensors_module_t *module = (struct sensors_module_t*) *it;
698         global_sensors_count += module->get_sensors_list(module, &subhal_sensors_list);
699         ALOGV("increased global_sensors_count to %d", global_sensors_count);
700     }
701 
702     // The global_sensors_list is full of consts.
703     // Manipulate this non-const list, and point the const one to it when we're done.
704     sensor_t* mutable_sensor_list = new sensor_t[global_sensors_count];
705 
706     // index of the next sensor to set in mutable_sensor_list
707     int mutable_sensor_index = 0;
708     int module_index = 0;
709 
710     for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
711             it != sub_hw_modules->end(); it++) {
712         hw_module_t *hw_module = *it;
713         ALOGV("examine one module");
714         // Read the sub-module's sensor list.
715         struct sensors_module_t *module = (struct sensors_module_t*) hw_module;
716         int module_sensor_count = module->get_sensors_list(module, &subhal_sensors_list);
717         ALOGV("the module has %d sensors", module_sensor_count);
718 
719         // Copy the HAL's sensor list into global_sensors_list,
720         // with the handle changed to be a global handle.
721         for (int i = 0; i < module_sensor_count; i++) {
722             ALOGV("examining one sensor");
723             const struct sensor_t *local_sensor = &subhal_sensors_list[i];
724             int local_handle = local_sensor->handle;
725             memcpy(&mutable_sensor_list[mutable_sensor_index], local_sensor,
726                 sizeof(struct sensor_t));
727 
728             // sensor direct report is only for primary module
729             if (module_index != 0) {
730                 mutable_sensor_list[mutable_sensor_index].flags &=
731                     ~(SENSOR_FLAG_MASK_DIRECT_REPORT | SENSOR_FLAG_MASK_DIRECT_CHANNEL);
732             }
733 
734             // Overwrite the global version's handle with a global handle.
735             int global_handle = assign_global_handle(module_index, local_handle);
736 
737             mutable_sensor_list[mutable_sensor_index].handle = global_handle;
738             ALOGV("module_index %d, local_handle %d, global_handle %d",
739                     module_index, local_handle, global_handle);
740 
741             mutable_sensor_index++;
742         }
743         module_index++;
744     }
745     // Set the const static global_sensors_list to the mutable one allocated by this function.
746     global_sensors_list = mutable_sensor_list;
747 
748     pthread_mutex_unlock(&init_sensors_mutex);
749     ALOGV("end lazy_init_sensors_list");
750 }
751 
module__get_sensors_list(__unused struct sensors_module_t * module,struct sensor_t const ** list)752 static int module__get_sensors_list(__unused struct sensors_module_t* module,
753         struct sensor_t const** list) {
754     ALOGV("module__get_sensors_list start");
755     lazy_init_sensors_list();
756     *list = global_sensors_list;
757     ALOGV("global_sensors_count: %d", global_sensors_count);
758     for (int i = 0; i < global_sensors_count; i++) {
759         ALOGV("sensor type: %d", global_sensors_list[i].type);
760     }
761     return global_sensors_count;
762 }
763 
764 static struct hw_module_methods_t sensors_module_methods = {
765     .open = open_sensors
766 };
767 
768 struct sensors_module_t HAL_MODULE_INFO_SYM = {
769     .common = {
770         .tag = HARDWARE_MODULE_TAG,
771         .version_major = 1,
772         .version_minor = 1,
773         .id = SENSORS_HARDWARE_MODULE_ID,
774         .name = "MultiHal Sensor Module",
775         .author = "Google, Inc",
776         .methods = &sensors_module_methods,
777         .dso = NULL,
778         .reserved = {0},
779     },
780     .get_sensors_list = module__get_sensors_list
781 };
782 
get_multi_hal_module_info()783 struct sensors_module_t *get_multi_hal_module_info() {
784     return (&HAL_MODULE_INFO_SYM);
785 }
786 
open_sensors(const struct hw_module_t * hw_module,const char * name,struct hw_device_t ** hw_device_out)787 static int open_sensors(const struct hw_module_t* hw_module, const char* name,
788         struct hw_device_t** hw_device_out) {
789     ALOGV("open_sensors begin...");
790 
791     lazy_init_modules();
792 
793     // Create proxy device, to return later.
794     sensors_poll_context_t *dev = new sensors_poll_context_t();
795     memset(dev, 0, sizeof(sensors_poll_device_1_t));
796     dev->proxy_device.common.tag = HARDWARE_DEVICE_TAG;
797     dev->proxy_device.common.version = SENSORS_DEVICE_API_VERSION_1_4;
798     dev->proxy_device.common.module = const_cast<hw_module_t*>(hw_module);
799     dev->proxy_device.common.close = device__close;
800     dev->proxy_device.activate = device__activate;
801     dev->proxy_device.setDelay = device__setDelay;
802     dev->proxy_device.poll = device__poll;
803     dev->proxy_device.batch = device__batch;
804     dev->proxy_device.flush = device__flush;
805     dev->proxy_device.inject_sensor_data = device__inject_sensor_data;
806     dev->proxy_device.register_direct_channel = device__register_direct_channel;
807     dev->proxy_device.config_direct_report = device__config_direct_report;
808 
809     dev->nextReadIndex = 0;
810 
811     // Open() the subhal modules. Remember their devices in a vector parallel to sub_hw_modules.
812     for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
813             it != sub_hw_modules->end(); it++) {
814         sensors_module_t *sensors_module = (sensors_module_t*) *it;
815         struct hw_device_t* sub_hw_device;
816         int sub_open_result = sensors_module->common.methods->open(*it, name, &sub_hw_device);
817         if (!sub_open_result) {
818             if (!HAL_VERSION_IS_COMPLIANT(sub_hw_device->version)) {
819                 ALOGE("SENSORS_DEVICE_API_VERSION_1_3 or newer is required for all sensor HALs");
820                 ALOGE("This HAL reports non-compliant API level : %s",
821                         apiNumToStr(sub_hw_device->version));
822                 ALOGE("Sensors belonging to this HAL will get ignored !");
823             }
824             dev->addSubHwDevice(sub_hw_device);
825         }
826     }
827 
828     // Prepare the output param and return
829     *hw_device_out = &dev->proxy_device.common;
830     ALOGV("...open_sensors end");
831     return 0;
832 }
833