2 * Copyright (C) 2014 Intel Corporation.
11 #include <sys/epoll.h>
12 #include <sys/socket.h>
13 #include <utils/Log.h>
14 #include <hardware/sensors.h>
16 #include "enumeration.h"
18 #include "transform.h"
19 #include "calibration.h"
20 #include "description.h"
21 #include "filtering.h"
23 /* Currently active sensors count, per device */
24 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
25 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
27 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
28 static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */
29 static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */
30 static int poll_fd; /* epoll instance covering all enabled sensors */
32 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
34 /* We use pthread condition variables to get worker threads out of sleep */
35 static pthread_condattr_t thread_cond_attr [MAX_SENSORS];
36 static pthread_cond_t thread_release_cond [MAX_SENSORS];
37 static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
40 * We associate tags to each of our poll set entries. These tags have the following values:
41 * - a iio device number if the fd is a iio character device fd
42 * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a pipe used by a sysfs data acquisition thread
44 #define THREAD_REPORT_TAG_BASE 1000
46 /* If buffer enable fails, we may want to retry a few times before giving up */
47 #define ENABLE_BUFFER_RETRIES 3
48 #define ENABLE_BUFFER_RETRY_DELAY_MS 10
51 inline int is_enabled (int s)
53 return sensor[s].directly_enabled || sensor[s].ref_count;
57 static int check_state_change (int s, int enabled, int from_virtual)
60 if (sensor[s].directly_enabled)
61 return 0; /* We're being enabled but already were directly activated: no change. */
64 sensor[s].directly_enabled = 1; /* We're being directly enabled */
66 if (sensor[s].ref_count)
67 return 0; /* We were already indirectly enabled */
69 return 1; /* Do continue enabling this sensor */
73 return 0; /* We are being disabled but already were: no change */
75 if (from_virtual && sensor[s].directly_enabled)
76 return 0; /* We're indirectly disabled but the base is still active */
78 sensor[s].directly_enabled = 0; /* We're now directly disabled */
80 if (!from_virtual && sensor[s].ref_count)
81 return 0; /* We still have ref counts */
83 return 1; /* Do continue disabling this sensor */
87 static int enable_buffer (int dev_num, int enabled)
89 char sysfs_path[PATH_MAX];
90 int retries = ENABLE_BUFFER_RETRIES;
92 sprintf(sysfs_path, ENABLE_PATH, dev_num);
95 /* Low level, non-multiplexed, enable/disable routine */
96 if (sysfs_write_int(sysfs_path, enabled) > 0)
99 ALOGE("Failed enabling buffer on dev%d, retrying", dev_num);
100 usleep(ENABLE_BUFFER_RETRY_DELAY_MS*1000);
104 ALOGE("Could not enable buffer\n");
109 static int setup_trigger (int s, const char* trigger_val)
111 char sysfs_path[PATH_MAX];
112 int ret = -1, attempts = 5;
114 sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
116 if (trigger_val[0] != '\n')
117 ALOGI("Setting S%d (%s) trigger to %s\n", s, sensor[s].friendly_name, trigger_val);
119 while (ret == -1 && attempts) {
120 ret = sysfs_write_str(sysfs_path, trigger_val);
125 sensor[s].selected_trigger = trigger_val;
127 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, sensor[s].friendly_name, trigger_val);
132 static int enable_sensor(int dev_num, const char *tag, int enabled)
134 char sysfs_path[PATH_MAX];
136 sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag);
137 return sysfs_write_int(sysfs_path, enabled);
140 static void enable_iio_timestamp (int dev_num, int known_channels)
142 /* Check if we have a dedicated iio timestamp channel */
144 char spec_buf[MAX_TYPE_SPEC_LEN];
145 char sysfs_path[PATH_MAX];
148 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
150 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
155 if (strcmp(spec_buf, "le:s64/64>>0"))
158 /* OK, type is int64_t as expected, in little endian representation */
160 sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
162 if (sysfs_read_int(sysfs_path, &n))
165 /* Check that the timestamp comes after the other fields we read */
166 if (n != known_channels)
169 /* Try enabling that channel */
170 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
172 sysfs_write_int(sysfs_path, 1);
174 if (sysfs_read_int(sysfs_path, &n))
178 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
179 has_iio_ts[dev_num] = 1;
184 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], datum_info_t *type_info)
186 /* Return size in bytes for this type specification, or -1 in error */
189 unsigned int realbits, storagebits, shift;
192 /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
194 tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", &endianness, &sign, &realbits, &storagebits, &shift);
196 if (tokens != 5 || (endianness != 'b' && endianness != 'l') || (sign != 'u' && sign != 's') ||
197 realbits > storagebits || (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
198 ALOGE("Invalid iio channel type spec: %s\n", type_buf);
202 type_info->endianness = endianness;
203 type_info->sign = sign;
204 type_info->realbits = (short) realbits;
205 type_info->storagebits = (short) storagebits;
206 type_info->shift = (short) shift;
208 return storagebits / 8;
212 void build_sensor_report_maps (int dev_num)
215 * Read sysfs files from a iio device's scan_element directory, and build a couple of tables from that data. These tables will tell, for
216 * each sensor, where to gather relevant data in a device report, i.e. the structure that we read from the /dev/iio:deviceX file in order to
217 * sensor report, itself being the data that we return to Android when a sensor poll completes. The mapping should be straightforward in the
218 * case where we have a single sensor active per iio device but, this is not the general case. In general several sensors can be handled
219 * through a single iio device, and the _en, _index and _type syfs entries all concur to paint a picture of what the structure of the
229 char spec_buf[MAX_TYPE_SPEC_LEN];
230 datum_info_t* ch_info;
232 char sysfs_path[PATH_MAX];
235 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
236 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
237 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
241 /* For each sensor that is linked to this device */
242 for (s=0; s<sensor_count; s++) {
243 if (sensor[s].dev_num != dev_num)
246 i = sensor[s].catalog_index;
248 /* Read channel details through sysfs attributes */
249 for (c=0; c<sensor[s].num_channels; c++) {
251 /* Read _type file */
252 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].type_path);
254 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
257 ALOGW( "Failed to read type: %s\n", sysfs_path);
261 ch_spec = sensor[s].channel[c].type_spec;
263 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
265 ch_info = &sensor[s].channel[c].type_info;
267 size = decode_type_spec(ch_spec, ch_info);
269 /* Read _index file */
270 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].index_path);
272 n = sysfs_read_int(sysfs_path, &ch_index);
275 ALOGW( "Failed to read index: %s\n", sysfs_path);
279 if (ch_index >= MAX_SENSORS) {
280 ALOGE("Index out of bounds!: %s\n", sysfs_path);
284 /* Record what this index is about */
286 sensor_handle_from_index [ch_index] = s;
287 channel_number_from_index[ch_index] = c;
288 channel_size_from_index [ch_index] = size;
293 /* Stop sampling - if we are recovering from hal restart */
294 enable_buffer(dev_num, 0);
295 setup_trigger(s, "\n");
297 /* Turn on channels we're aware of */
298 for (c=0;c<sensor[s].num_channels; c++) {
299 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].en_path);
300 sysfs_write_int(sysfs_path, 1);
304 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
307 * Now that we know which channels are defined, their sizes and their ordering, update channels offsets within device report. Note: there
308 * is a possibility that several sensors share the same index, with their data fields being isolated by masking and shifting as specified
309 * through the real bits and shift values in type attributes. This case is not currently supported. Also, the code below assumes no hole in
310 * the sequence of indices, so it is dependent on discovery of all sensors.
314 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
315 s = sensor_handle_from_index[i];
316 c = channel_number_from_index[i];
317 size = channel_size_from_index[i];
322 ALOGI("S%d C%d : offset %d, size %d, type %s\n", s, c, offset, size, sensor[s].channel[c].type_spec);
324 sensor[s].channel[c].offset = offset;
325 sensor[s].channel[c].size = size;
330 /* Enable the timestamp channel if there is one available */
331 enable_iio_timestamp(dev_num, known_channels);
333 /* Add padding and timestamp size if it's enabled on this iio device */
334 if (has_iio_ts[dev_num])
335 offset = (offset+7)/8*8 + sizeof(int64_t);
337 expected_dev_report_size[dev_num] = offset;
338 ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
340 if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
341 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", dev_num, expected_dev_report_size[dev_num]);
343 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
348 int adjust_counters (int s, int enabled, int from_virtual)
351 * Adjust counters based on sensor enable action. Return values are:
352 * 0 if the operation was completed and we're all set
353 * 1 if we toggled the state of the sensor and there's work left
354 * -1 in case of an error
357 int dev_num = sensor[s].dev_num;
359 if (!check_state_change(s, enabled, from_virtual))
360 return 0; /* The state of the sensor remains the same: we're done */
363 ALOGI("Enabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
365 switch (sensor[s].type) {
366 case SENSOR_TYPE_MAGNETIC_FIELD:
367 compass_read_data(&sensor[s]);
370 case SENSOR_TYPE_GYROSCOPE:
371 gyro_cal_init(&sensor[s]);
375 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
377 /* Sensor disabled, lower report available flag */
378 sensor[s].report_pending = 0;
380 if (sensor[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
381 compass_store_data(&sensor[s]);
383 if (sensor[s].type == SENSOR_TYPE_GYROSCOPE)
384 gyro_store_data(&sensor[s]);
387 /* We changed the state of a sensor: adjust device ref counts */
389 switch(sensor[s].mode) {
392 trig_sensors_per_dev[dev_num]++;
394 trig_sensors_per_dev[dev_num]--;
399 active_poll_sensors++;
400 poll_sensors_per_dev[dev_num]++;
403 active_poll_sensors--;
404 poll_sensors_per_dev[dev_num]--;
408 /* Invalid sensor mode */
414 static int get_field_count (int s, size_t *field_size)
416 *field_size = sizeof(float);
417 switch (sensor[s].type) {
418 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
419 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
420 case SENSOR_TYPE_ORIENTATION: /* degrees */
421 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
422 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
425 case SENSOR_TYPE_LIGHT: /* SI lux units */
426 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
427 case SENSOR_TYPE_TEMPERATURE: /* °C */
428 case SENSOR_TYPE_PROXIMITY: /* centimeters */
429 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
430 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
433 case SENSOR_TYPE_ROTATION_VECTOR:
436 case SENSOR_TYPE_STEP_COUNTER: /* number of steps */
437 *field_size = sizeof(uint64_t);
440 ALOGE("Unknown sensor type!\n");
441 return 0; /* Drop sample */
446 * CTS acceptable thresholds:
447 * EventGapVerification.java: (th <= 1.8)
448 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
450 #define THRESHOLD 1.10
451 #define MAX_DELAY 500000000 /* 500 ms */
453 void set_report_ts(int s, int64_t ts)
455 int64_t maxTs, period;
458 * A bit of a hack to please a bunch of cts tests. They
459 * expect the timestamp to be exacly according to the set-up
460 * frequency but if we're simply getting the timestamp at hal level
461 * this may not be the case. Perhaps we'll get rid of this when
462 * we'll be reading the timestamp from the iio channel for all sensors
464 if (sensor[s].report_ts && sensor[s].sampling_rate &&
465 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
467 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
468 maxTs = sensor[s].report_ts + THRESHOLD * period;
469 /* If we're too far behind get back on track */
470 if (ts - maxTs >= MAX_DELAY)
472 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
474 sensor[s].report_ts = ts;
478 static void* acquisition_routine (void* param)
481 * Data acquisition routine run in a dedicated thread, covering a single sensor. This loop will periodically retrieve sampling data through
482 * sysfs, then package it as a sample and transfer it to our master poll loop through a report fd. Checks for a cancellation signal quite
483 * frequently, as the thread may be disposed of at any time. Note that Bionic does not provide pthread_cancel / pthread_testcancel...
486 int s = (int) (size_t) param;
488 sensors_event_t data = {0};
491 struct timespec target_time;
492 int64_t timestamp, period, start, stop;
495 if (s < 0 || s >= sensor_count) {
496 ALOGE("Invalid sensor handle!\n");
500 ALOGI("Entering S%d (%s) data acquisition thread: rate:%g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate);
502 if (sensor[s].sampling_rate <= 0) {
503 ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", s, sensor[s].sampling_rate);
507 /* Initialize data fields that will be shared by all sensor reports */
508 data.version = sizeof(sensors_event_t);
510 data.type = sensor[s].type;
512 num_fields = get_field_count(s, &field_size);
515 * Each condition variable is associated to a mutex that has to be locked by the thread that's waiting on it. We use these condition
516 * variables to get the acquisition threads out of sleep quickly after the sampling rate is adjusted, or the sensor is disabled.
518 pthread_mutex_lock(&thread_release_mutex[s]);
520 /* Pinpoint the moment we start sampling */
521 timestamp = get_timestamp_monotonic();
523 /* Check and honor termination requests */
524 while (sensor[s].thread_data_fd[1] != -1) {
525 start = get_timestamp_boot();
527 /* Read values through sysfs */
528 for (c=0; c<num_fields; c++) {
529 if (field_size == sizeof(uint64_t))
530 data.u64.data[c] = acquire_immediate_uint64_value(s, c);
532 data.data[c] = acquire_immediate_float_value(s, c);
534 /* Check and honor termination requests */
535 if (sensor[s].thread_data_fd[1] == -1)
538 stop = get_timestamp_boot();
539 set_report_ts(s, start/2 + stop/2);
540 data.timestamp = sensor[s].report_ts;
541 /* If the sample looks good */
542 if (sensor[s].ops.finalize(s, &data)) {
544 /* Pipe it for transmission to poll loop */
545 ret = write(sensor[s].thread_data_fd[1], &data, sizeof(sensors_event_t));
547 if (ret != sizeof(sensors_event_t))
548 ALOGE("S%d write failure: wrote %d, got %d\n", s, sizeof(sensors_event_t), ret);
551 /* Check and honor termination requests */
552 if (sensor[s].thread_data_fd[1] == -1)
555 /* Recalculate period assuming sensor[s].sampling_rate can be changed dynamically during the thread run */
556 if (sensor[s].sampling_rate <= 0) {
557 ALOGE("Unexpected sampling rate for sensor %d: %g\n", s, sensor[s].sampling_rate);
561 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
563 set_timestamp(&target_time, timestamp);
565 /* Wait until the sampling time elapses, or a rate change is signaled, or a thread exit is requested */
566 ret = pthread_cond_timedwait(&thread_release_cond[s], &thread_release_mutex[s], &target_time);
570 ALOGV("Acquisition thread for S%d exiting\n", s);
571 pthread_mutex_unlock(&thread_release_mutex[s]);
577 static void start_acquisition_thread (int s)
579 int incoming_data_fd;
582 struct epoll_event ev = {0};
584 ALOGV("Initializing acquisition context for sensor %d\n", s);
586 /* Create condition variable and mutex for quick thread release */
587 ret = pthread_condattr_init(&thread_cond_attr[s]);
588 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
589 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
590 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
592 /* Create a pipe for inter thread communication */
593 ret = pipe(sensor[s].thread_data_fd);
595 incoming_data_fd = sensor[s].thread_data_fd[0];
598 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
600 /* Add incoming side of pipe to our poll set, with a suitable tag */
601 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
603 ALOGE("Failed adding %d to poll set (%s)\n",
604 incoming_data_fd, strerror(errno));
607 /* Create and start worker thread */
608 ret = pthread_create(&sensor[s].acquisition_thread, NULL, acquisition_routine, (void*) (size_t) s);
612 static void stop_acquisition_thread (int s)
614 int incoming_data_fd = sensor[s].thread_data_fd[0];
615 int outgoing_data_fd = sensor[s].thread_data_fd[1];
617 ALOGV("Tearing down acquisition context for sensor %d\n", s);
619 /* Delete the incoming side of the pipe from our poll set */
620 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
622 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
623 sensor[s].thread_data_fd[0] = -1;
624 sensor[s].thread_data_fd[1] = -1;
626 /* Close both sides of our pipe */
627 close(incoming_data_fd);
628 close(outgoing_data_fd);
630 /* Stop acquisition thread and clean up thread handle */
631 pthread_cond_signal(&thread_release_cond[s]);
632 pthread_join(sensor[s].acquisition_thread, NULL);
634 /* Clean up our sensor descriptor */
635 sensor[s].acquisition_thread = -1;
637 /* Delete condition variable and mutex */
638 pthread_cond_destroy(&thread_release_cond[s]);
639 pthread_mutex_destroy(&thread_release_mutex[s]);
643 static int is_fast_accelerometer (int s)
646 * Some games don't react well to accelerometers using any-motion triggers. Even very low thresholds seem to trip them, and they tend to
647 * request fairly high event rates. Favor continuous triggers if the sensor is an accelerometer and uses a sampling rate of at least 25.
650 if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
653 if (sensor[s].sampling_rate < 25)
660 static void tentative_switch_trigger (int s)
663 * Under certain situations it may be beneficial to use an alternate trigger:
665 * - for applications using the accelerometer with high sampling rates, prefer the continuous trigger over the any-motion one, to avoid
666 * jumps related to motion thresholds
669 if (is_fast_accelerometer(s) && !(sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].selected_trigger == sensor[s].motion_trigger_name)
670 setup_trigger(s, sensor[s].init_trigger_name);
674 static float get_group_max_sampling_rate (int s)
676 /* Review the sampling rates of linked sensors and return the maximum */
680 float arbitrated_rate = 0;
683 arbitrated_rate = sensor[s].requested_rate;
685 /* If any of the currently active sensors built on top of this one need a higher sampling rate, switch to this rate */
686 for (i = 0; i < sensor_count; i++)
687 for (vi = 0; vi < sensor[i].base_count; vi++)
688 if (sensor[i].base[vi] == s && is_enabled(i) && sensor[i].requested_rate > arbitrated_rate) /* If sensor i depends on sensor s */
689 arbitrated_rate = sensor[i].requested_rate;
691 /* If any of the currently active sensors we rely on is using a higher sampling rate, switch to this rate */
692 for (vi = 0; vi < sensor[s].base_count; vi++) {
693 i = sensor[s].base[vi];
694 if (is_enabled(i) && sensor[i].requested_rate > arbitrated_rate)
695 arbitrated_rate = sensor[i].requested_rate;
698 return arbitrated_rate;
702 static int sensor_set_rate (int s, float requested_rate)
704 /* Set the rate at which a specific sensor should report events. See Android sensors.h for indication on sensor trigger modes */
706 char sysfs_path[PATH_MAX];
707 char avail_sysfs_path[PATH_MAX];
708 int dev_num = sensor[s].dev_num;
709 int i = sensor[s].catalog_index;
710 const char *prefix = sensor_catalog[i].tag;
711 int per_sensor_sampling_rate;
712 int per_device_sampling_rate;
717 float group_max_sampling_rate;
718 float cur_sampling_rate; /* Currently used sampling rate */
719 float arb_sampling_rate; /* Granted sampling rate after arbitration */
721 ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, s, sensor[s].friendly_name);
723 sensor[s].requested_rate = requested_rate;
725 arb_sampling_rate = requested_rate;
727 if (arb_sampling_rate < sensor[s].min_supported_rate) {
728 ALOGV("Sampling rate %g too low for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].min_supported_rate);
729 arb_sampling_rate = sensor[s].min_supported_rate;
732 /* If one of the linked sensors uses a higher rate, adopt it */
733 group_max_sampling_rate = get_group_max_sampling_rate(s);
735 if (arb_sampling_rate < group_max_sampling_rate) {
736 ALOGV("Using %s sampling rate to %g too due to dependency\n", sensor[s].friendly_name, arb_sampling_rate);
737 arb_sampling_rate = group_max_sampling_rate;
740 if (sensor[s].max_supported_rate && arb_sampling_rate > sensor[s].max_supported_rate) {
741 ALOGV("Sampling rate %g too high for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].max_supported_rate);
742 arb_sampling_rate = sensor[s].max_supported_rate;
745 sensor[s].sampling_rate = arb_sampling_rate;
747 /* If the sensor is virtual, we're done */
748 if (sensor[s].is_virtual)
751 /* If we're dealing with a poll-mode sensor */
752 if (sensor[s].mode == MODE_POLL) {
754 pthread_cond_signal(&thread_release_cond[s]); /* Wake up thread so the new sampling rate gets used */
758 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
760 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
761 per_sensor_sampling_rate = 1;
762 per_device_sampling_rate = 0;
764 per_sensor_sampling_rate = 0;
766 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
768 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
769 per_device_sampling_rate = 1;
771 per_device_sampling_rate = 0;
774 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
775 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
779 /* Check if we have contraints on allowed sampling rates */
781 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
783 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0) {
786 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
788 /* While we're not at the end of the string */
789 while (*cursor && cursor[0]) {
791 /* Decode a single value */
792 sr = strtod(cursor, NULL);
794 /* If this matches the selected rate, we're happy. Have some tolerance for rounding errors and avoid needless jumps to higher rates */
795 if (fabs(arb_sampling_rate - sr) <= 0.001) {
796 arb_sampling_rate = sr;
801 * If we reached a higher value than the desired rate, adjust selected rate so it matches the first higher available one and
802 * stop parsing - this makes the assumption that rates are sorted by increasing value in the allowed frequencies string.
804 if (sr > arb_sampling_rate) {
805 arb_sampling_rate = sr;
810 while (cursor[0] && !isspace(cursor[0]))
814 while (cursor[0] && isspace(cursor[0]))
819 if (sensor[s].max_supported_rate &&
820 arb_sampling_rate > sensor[s].max_supported_rate) {
821 arb_sampling_rate = sensor[s].max_supported_rate;
824 /* Coordinate with others active sensors on the same device, if any */
825 if (per_device_sampling_rate)
826 for (n=0; n<sensor_count; n++)
827 if (n != s && sensor[n].dev_num == dev_num && sensor[n].num_channels && is_enabled(n) && sensor[n].sampling_rate > arb_sampling_rate) {
828 ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n", sensor[s].friendly_name, sensor[n].friendly_name,
829 sensor[n].sampling_rate, arb_sampling_rate);
830 arb_sampling_rate = sensor[n].sampling_rate;
833 sensor[s].sampling_rate = arb_sampling_rate;
835 /* Update actual sampling rate field for this sensor and others which may be sharing the same sampling rate */
836 if (per_device_sampling_rate)
837 for (n=0; n<sensor_count; n++)
838 if (sensor[n].dev_num == dev_num && n != s && sensor[n].num_channels)
839 sensor[n].sampling_rate = arb_sampling_rate;
841 /* If the desired rate is already active we're all set */
842 if (arb_sampling_rate == cur_sampling_rate)
845 ALOGI("Sensor %d (%s) sampling rate set to %g\n", s, sensor[s].friendly_name, arb_sampling_rate);
847 if (trig_sensors_per_dev[dev_num])
848 enable_buffer(dev_num, 0);
850 sysfs_write_float(sysfs_path, arb_sampling_rate);
852 /* Check if it makes sense to use an alternate trigger */
853 tentative_switch_trigger(s);
855 if (trig_sensors_per_dev[dev_num])
856 enable_buffer(dev_num, 1);
862 static void reapply_sampling_rates (int s)
865 * The specified sensor was either enabled or disabled. Other sensors in the same group may have constraints related to this sensor
866 * sampling rate on their own sampling rate, so reevaluate them by retrying to use their requested sampling rate, rather than the one
867 * that ended up being used after arbitration.
872 if (sensor[s].is_virtual) {
873 /* Take care of downwards dependencies */
874 for (i=0; i<sensor[s].base_count; i++) {
875 base = sensor[s].base[i];
876 sensor_set_rate(base, sensor[base].requested_rate);
882 for (i=0; i<sensor_count; i++)
883 for (j=0; j<sensor[i].base_count; j++)
884 if (sensor[i].base[j] == s) /* If sensor i depends on sensor s */
885 sensor_set_rate(i, sensor[i].requested_rate);
889 static int sensor_activate_virtual (int s, int enabled, int from_virtual)
893 sensor[s].event_count = 0;
894 sensor[s].meta_data_pending = 0;
896 if (!check_state_change(s, enabled, from_virtual))
897 return 0; /* The state of the sensor remains the same ; we're done */
900 ALOGI("Enabling sensor %d (%s)\n", s, sensor[s].friendly_name);
902 ALOGI("Disabling sensor %d (%s)\n", s, sensor[s].friendly_name);
904 sensor[s].report_pending = 0;
906 for (i=0; i<sensor[s].base_count; i++) {
908 base = sensor[s].base[i];
909 sensor_activate(base, enabled, 1);
912 sensor[base].ref_count++;
914 sensor[base].ref_count--;
917 /* Reevaluate sampling rates of linked sensors */
918 reapply_sampling_rates(s);
923 int sensor_activate (int s, int enabled, int from_virtual)
925 char device_name[PATH_MAX];
926 struct epoll_event ev = {0};
929 int dev_num = sensor[s].dev_num;
931 int catalog_index = sensor[s].catalog_index;
933 if (sensor[s].is_virtual)
934 return sensor_activate_virtual(s, enabled, from_virtual);
936 /* Prepare the report timestamp field for the first event, see set_report_ts method */
937 sensor[s].report_ts = 0;
939 ret = adjust_counters(s, enabled, from_virtual);
941 /* If the operation was neutral in terms of state, we're done */
945 sensor[s].event_count = 0;
946 sensor[s].meta_data_pending = 0;
949 setup_noise_filtering(s); /* Initialize filtering data if required */
951 if (sensor[s].mode == MODE_TRIGGER) {
954 enable_buffer(dev_num, 0);
955 setup_trigger(s, "\n");
957 /* If there's at least one sensor enabled on this iio device */
958 if (trig_sensors_per_dev[dev_num]) {
961 setup_trigger(s, sensor[s].init_trigger_name);
962 enable_buffer(dev_num, 1);
964 } else if (sensor[s].mode == MODE_POLL) {
965 if (sensor[s].needs_enable) {
966 enable_sensor(dev_num, sensor_catalog[catalog_index].tag, enabled);
971 * Make sure we have a fd on the character device ; conversely, close the fd if no one is using associated sensors anymore. The assumption
972 * here is that the underlying driver will power on the relevant hardware block while someone holds a fd on the device.
974 dev_fd = device_fd[dev_num];
977 if (sensor[s].mode == MODE_POLL)
978 stop_acquisition_thread(s);
980 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] && !trig_sensors_per_dev[dev_num]) {
981 /* Stop watching this fd. This should be a no-op in case this fd was not in the poll set. */
982 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
985 device_fd[dev_num] = -1;
988 /* Release any filtering data we may have accumulated */
989 release_noise_filtering_data(s);
991 /* Reevaluate sampling rates of linked sensors */
992 reapply_sampling_rates(s);
997 /* First enabled sensor on this iio device */
998 sprintf(device_name, DEV_FILE_PATH, dev_num);
999 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
1001 device_fd[dev_num] = dev_fd;
1004 ALOGE("Could not open fd on %s (%s)\n", device_name, strerror(errno));
1005 adjust_counters(s, 0, from_virtual);
1009 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
1011 if (sensor[s].mode == MODE_TRIGGER) {
1013 /* Add this iio device fd to the set of watched fds */
1014 ev.events = EPOLLIN;
1015 ev.data.u32 = dev_num;
1017 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
1020 ALOGE("Failed adding %d to poll set (%s)\n", dev_fd, strerror(errno));
1024 /* Note: poll-mode fds are not readable */
1028 /* Ensure that on-change sensors send at least one event after enable */
1029 get_field_count(s, &field_size);
1030 if (field_size == sizeof(uint64_t))
1031 sensor[s].prev_val.data64 = -1;
1033 sensor[s].prev_val.data = -1;
1035 if (sensor[s].mode == MODE_POLL)
1036 start_acquisition_thread(s);
1038 /* Reevaluate sampling rates of linked sensors */
1039 reapply_sampling_rates(s);
1045 static void enable_motion_trigger (int dev_num)
1048 * In the ideal case, we enumerate two triggers per iio device ; the default (periodically firing) trigger, and another one (the motion
1049 * trigger) that only fires up when motion is detected. This second one allows for lesser energy consumption, but requires periodic sample
1050 * duplication at the HAL level for sensors that Android defines as continuous. This "duplicate last sample" logic can only be engaged
1051 * once we got a first sample for the driver, so we start with the default trigger when an iio device is first opened, then adjust the
1052 * trigger when we got events for all active sensors. Unfortunately in the general case several sensors can be associated to a given iio
1053 * device, they can independently be controlled, and we have to adjust the trigger in use at the iio device level depending on whether or
1054 * not appropriate conditions are met at the sensor level.
1059 int active_sensors = trig_sensors_per_dev[dev_num];
1060 int candidate[MAX_SENSORS];
1061 int candidate_count = 0;
1063 if (!active_sensors)
1066 /* Check that all active sensors are ready to switch */
1068 for (s=0; s<MAX_SENSORS; s++)
1069 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels &&
1070 (!sensor[s].motion_trigger_name[0] || !sensor[s].report_initialized || is_fast_accelerometer(s) ||
1071 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS)))
1074 /* Record which particular sensors need to switch */
1076 for (s=0; s<MAX_SENSORS; s++)
1077 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels && sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1078 candidate[candidate_count++] = s;
1080 if (!candidate_count)
1083 /* Now engage the motion trigger for sensors which aren't using it */
1085 enable_buffer(dev_num, 0);
1087 for (i=0; i<candidate_count; i++) {
1089 setup_trigger(s, sensor[s].motion_trigger_name);
1092 enable_buffer(dev_num, 1);
1095 static void stamp_reports (int dev_num, int64_t ts)
1099 for (s=0; s<MAX_SENSORS; s++)
1100 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].mode != MODE_POLL)
1101 set_report_ts(s, ts);
1105 static int integrate_device_report (int dev_num)
1109 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1111 unsigned char *target;
1112 unsigned char *source;
1115 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1116 int64_t boot_to_rt_delta;
1118 /* There's an incoming report on the specified iio device char dev fd */
1120 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1121 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1125 if (device_fd[dev_num] == -1) {
1126 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1130 len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]);
1133 ALOGE("Could not read report from iio device %d (%s)\n", dev_num, strerror(errno));
1137 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1139 /* Map device report to sensor reports */
1141 for (s=0; s<MAX_SENSORS; s++)
1142 if (sensor[s].dev_num == dev_num && is_enabled(s)) {
1146 /* Copy data from device to sensor report buffer */
1147 for (c=0; c<sensor[s].num_channels; c++) {
1149 target = sensor[s].report_buffer + sr_offset;
1151 source = buf + sensor[s].channel[c].offset;
1153 size = sensor[s].channel[c].size;
1155 memcpy(target, source, size);
1160 ALOGV("Sensor %d report available (%d bytes)\n", s, sr_offset);
1162 sensor[s].report_pending = DATA_TRIGGER;
1163 sensor[s].report_initialized = 1;
1165 ts_offset += sr_offset;
1168 /* Tentatively switch to an any-motion trigger if conditions are met */
1169 enable_motion_trigger(dev_num);
1171 /* If no iio timestamp channel was detected for this device, bail out */
1172 if (!has_iio_ts[dev_num]) {
1173 stamp_reports(dev_num, get_timestamp_boot());
1177 /* Don't trust the timestamp channel in any-motion mode */
1178 for (s=0; s<MAX_SENSORS; s++)
1179 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name) {
1180 stamp_reports(dev_num, get_timestamp_boot());
1184 /* Align on a 64 bits boundary */
1185 ts_offset = expected_dev_report_size[dev_num] - sizeof(int64_t);
1187 /* If we read an amount of data consistent with timestamp presence */
1188 if (len == expected_dev_report_size[dev_num])
1189 ts = *(int64_t*) (buf + ts_offset);
1192 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1193 stamp_reports(dev_num, get_timestamp_boot());
1197 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1199 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1201 stamp_reports(dev_num, ts + boot_to_rt_delta);
1207 static int propagate_vsensor_report (int s, sensors_event_t *data)
1209 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1211 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1214 data->type = sensor[s].type;
1219 static int propagate_sensor_report (int s, sensors_event_t *data)
1221 /* There's a sensor report pending for this sensor ; transmit it */
1224 int num_fields = get_field_count(s, &field_size);
1226 unsigned char* current_sample;
1229 /* If there's nothing to return... we're done */
1233 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1235 if (sensor[s].mode == MODE_POLL) {
1236 /* We received a good sample but we're not directly enabled so we'll drop */
1237 if (!sensor[s].directly_enabled)
1239 /* Use the data provided by the acquisition thread */
1240 ALOGV("Reporting data from worker thread for S%d\n", s);
1241 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1242 data->timestamp = sensor[s].report_ts;
1246 memset(data, 0, sizeof(sensors_event_t));
1248 data->version = sizeof(sensors_event_t);
1250 data->type = sensor[s].type;
1251 data->timestamp = sensor[s].report_ts;
1253 /* Convert the data into the expected Android-level format */
1255 current_sample = sensor[s].report_buffer;
1257 for (c=0; c<num_fields; c++) {
1259 data->data[c] = sensor[s].ops.transform (s, c, current_sample);
1261 ALOGV("\tfield %d: %g\n", c, data->data[c]);
1262 current_sample += sensor[s].channel[c].size;
1265 ret = sensor[s].ops.finalize(s, data);
1267 /* We will drop samples if the sensor is not directly enabled */
1268 if (!sensor[s].directly_enabled)
1271 /* The finalize routine, in addition to its late sample processing duty, has the final say on whether or not the sample gets sent to Android */
1276 static void synthetize_duplicate_samples (void)
1279 * Some sensor types (ex: gyroscope) are defined as continuously firing by Android, despite the fact that
1280 * we can be dealing with iio drivers that only report events for new samples. For these we generate reports
1281 * periodically, duplicating the last data we got from the driver. This is not necessary for polling sensors.
1289 for (s=0; s<sensor_count; s++) {
1291 /* Ignore disabled sensors */
1295 /* If the sensor is continuously firing, leave it alone */
1296 if (sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1299 /* If we haven't seen a sample, there's nothing to duplicate */
1300 if (!sensor[s].report_initialized)
1303 /* If a sample was recently buffered, leave it alone too */
1304 if (sensor[s].report_pending)
1307 /* We also need a valid sampling rate to be configured */
1308 if (!sensor[s].sampling_rate)
1311 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1313 current_ts = get_timestamp_boot();
1314 target_ts = sensor[s].report_ts + period;
1316 if (target_ts <= current_ts) {
1317 /* Mark the sensor for event generation */
1318 set_report_ts(s, current_ts);
1319 sensor[s].report_pending = DATA_DUPLICATE;
1325 static void integrate_thread_report (uint32_t tag)
1327 int s = tag - THREAD_REPORT_TAG_BASE;
1330 len = read(sensor[s].thread_data_fd[0], &sensor[s].sample, sizeof(sensors_event_t));
1332 if (len == sizeof(sensors_event_t))
1333 sensor[s].report_pending = DATA_SYSFS;
1337 static int get_poll_wait_timeout (void)
1340 * Compute an appropriate timeout value, in ms, for the epoll_wait call that's going to await
1341 * for iio device reports and incoming reports from our sensor sysfs data reader threads.
1345 int64_t target_ts = INT64_MAX;
1350 * Check if we're dealing with a driver that only send events when there is motion, despite the fact that the associated Android sensor
1351 * type is continuous rather than on-change. In that case we have to duplicate events. Check deadline for the nearest upcoming event.
1353 for (s=0; s<sensor_count; s++)
1354 if (is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name && sensor[s].sampling_rate) {
1355 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1357 if (sensor[s].report_ts + period < target_ts)
1358 target_ts = sensor[s].report_ts + period;
1361 /* If we don't have such a driver to deal with */
1362 if (target_ts == INT64_MAX)
1363 return -1; /* Infinite wait */
1365 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1367 /* If the target timestamp is already behind us, don't wait */
1375 int sensor_poll (sensors_event_t* data, int count)
1380 struct epoll_event ev[MAX_DEVICES];
1381 int returned_events;
1384 /* Get one or more events from our collection of sensors */
1385 return_available_sensor_reports:
1387 /* Synthetize duplicate samples if needed */
1388 synthetize_duplicate_samples();
1390 returned_events = 0;
1392 /* Check our sensor collection for available reports */
1393 for (s=0; s<sensor_count && returned_events < count; s++) {
1395 if (sensor[s].report_pending) {
1398 if (sensor[s].is_virtual)
1399 event_count = propagate_vsensor_report(s, &data[returned_events]);
1401 /* Report this event if it looks OK */
1402 event_count = propagate_sensor_report(s, &data[returned_events]);
1405 sensor[s].report_pending = 0;
1406 returned_events += event_count;
1409 * If the sample was deemed invalid or unreportable, e.g. had the same value as the previously reported
1410 * value for a 'on change' sensor, silently drop it.
1414 while (sensor[s].meta_data_pending) {
1415 /* See sensors.h on these */
1416 data[returned_events].version = META_DATA_VERSION;
1417 data[returned_events].sensor = 0;
1418 data[returned_events].type = SENSOR_TYPE_META_DATA;
1419 data[returned_events].reserved0 = 0;
1420 data[returned_events].timestamp = 0;
1421 data[returned_events].meta_data.sensor = s;
1422 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1424 sensor[s].meta_data_pending--;
1428 if (returned_events)
1429 return returned_events;
1433 ALOGV("Awaiting sensor data\n");
1435 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1438 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1442 ALOGV("%d fds signalled\n", nfds);
1444 /* For each of the signalled sources */
1445 for (i=0; i<nfds; i++)
1446 if (ev[i].events == EPOLLIN)
1447 switch (ev[i].data.u32) {
1448 case 0 ... MAX_DEVICES-1:
1449 /* Read report from iio char dev fd */
1450 integrate_device_report(ev[i].data.u32);
1453 case THREAD_REPORT_TAG_BASE ...
1454 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1455 /* Get report from acquisition thread */
1456 integrate_thread_report(ev[i].data.u32);
1460 ALOGW("Unexpected event source!\n");
1464 goto return_available_sensor_reports;
1468 int sensor_set_delay (int s, int64_t ns)
1470 float requested_sampling_rate;
1473 ALOGE("Invalid delay requested on sensor %d: %lld\n", s, ns);
1477 requested_sampling_rate = 1000000000.0 / ns;
1479 ALOGV("Entering set delay S%d (%s): current rate: %g, requested: %g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate, requested_sampling_rate);
1482 * Only try to adjust the low level sampling rate if it's different from the current one, as set by the HAL. This saves a few sysfs
1483 * reads and writes as well as buffer enable/disable operations, since at the iio level most drivers require the buffer to be turned off
1484 * in order to accept a sampling rate change. Of course that implies that this field has to be kept up to date and that only this library
1485 * is changing the sampling rate.
1488 if (requested_sampling_rate != sensor[s].sampling_rate)
1489 return sensor_set_rate(s, requested_sampling_rate);
1495 int sensor_flush (int s)
1497 /* If one shot or not enabled return -EINVAL */
1498 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1501 sensor[s].meta_data_pending++;
1506 int allocate_control_data (void)
1510 for (i=0; i<MAX_DEVICES; i++)
1513 poll_fd = epoll_create(MAX_DEVICES);
1515 if (poll_fd == -1) {
1516 ALOGE("Can't create epoll instance for iio sensors!\n");
1524 void delete_control_data (void)