2 * Copyright (C) 2014 Intel Corporation.
10 #include <sys/epoll.h>
11 #include <sys/socket.h>
12 #include <utils/Log.h>
13 #include <hardware/sensors.h>
15 #include "enumeration.h"
17 #include "transform.h"
18 #include "calibration.h"
19 #include "description.h"
20 #include "filtering.h"
22 /* Currently active sensors count, per device */
23 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
24 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
26 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
27 static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */
28 static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */
29 static int poll_fd; /* epoll instance covering all enabled sensors */
31 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
33 /* We use pthread condition variables to get worker threads out of sleep */
34 static pthread_condattr_t thread_cond_attr [MAX_SENSORS];
35 static pthread_cond_t thread_release_cond [MAX_SENSORS];
36 static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
39 * We associate tags to each of our poll set entries. These tags have the
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
43 * pipe used by a sysfs data acquisition thread
45 #define THREAD_REPORT_TAG_BASE 0x00010000
47 #define ENABLE_BUFFER_RETRIES 10
48 #define ENABLE_BUFFER_RETRY_DELAY_MS 10
50 inline int is_enabled(int s)
52 return (sensor[s].directly_enabled || sensor[s].ref_count);
55 static int check_state_change(int s, int enabled, int from_virtual)
58 if (sensor[s].directly_enabled)
61 /* If we were enabled by Android no sample drops */
63 sensor[s].directly_enabled = 1;
66 * If we got here it means we were not previously directly enabled - we may
67 * or may not be now, whatever the case if we already had references we
70 if (sensor[s].ref_count)
76 /* Spurious disable call */
80 /* We're requesting disable for a virtual sensor but the base is still active */
81 if (from_virtual && sensor[s].directly_enabled)
84 /* If it's disable, and it's from Android, and we still have ref counts */
85 if (!from_virtual && sensor[s].ref_count) {
86 sensor[s].directly_enabled = 0;
90 /*If perhaps we are from virtual but we're disabling it*/
91 sensor[s].directly_enabled = 0;
95 static int enable_buffer(int dev_num, int enabled)
97 char sysfs_path[PATH_MAX];
98 int ret, retries, millisec;
99 struct timespec req = {0};
101 retries = ENABLE_BUFFER_RETRIES;
102 millisec = ENABLE_BUFFER_RETRY_DELAY_MS;
104 req.tv_nsec = millisec * 1000000L;
106 sprintf(sysfs_path, ENABLE_PATH, dev_num);
109 /* Low level, non-multiplexed, enable/disable routine */
110 ret = sysfs_write_int(sysfs_path, enabled);
114 ALOGE("Failed enabling buffer, retrying");
115 nanosleep(&req, (struct timespec *)NULL);
119 ALOGE("Could not enable buffer\n");
127 static int setup_trigger (int s, const char* trigger_val)
129 char sysfs_path[PATH_MAX];
130 int ret = -1, attempts = 5;
132 sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
134 if (trigger_val[0] != '\n')
135 ALOGI("Setting S%d (%s) trigger to %s\n", s,
136 sensor[s].friendly_name, trigger_val);
138 while (ret == -1 && attempts) {
139 ret = sysfs_write_str(sysfs_path, trigger_val);
144 sensor[s].selected_trigger = trigger_val;
146 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s,
147 sensor[s].friendly_name, trigger_val);
152 static void enable_iio_timestamp (int dev_num, int known_channels)
154 /* Check if we have a dedicated iio timestamp channel */
156 char spec_buf[MAX_TYPE_SPEC_LEN];
157 char sysfs_path[PATH_MAX];
160 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
162 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
167 if (strcmp(spec_buf, "le:s64/64>>0"))
170 /* OK, type is int64_t as expected, in little endian representation */
172 sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
174 if (sysfs_read_int(sysfs_path, &n))
177 /* Check that the timestamp comes after the other fields we read */
178 if (n != known_channels)
181 /* Try enabling that channel */
182 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
184 sysfs_write_int(sysfs_path, 1);
186 if (sysfs_read_int(sysfs_path, &n))
190 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
191 has_iio_ts[dev_num] = 1;
196 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN],
197 struct datum_info_t *type_info)
199 /* Return size in bytes for this type specification, or -1 in error */
202 unsigned int realbits, storagebits, shift;
205 /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
207 tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u",
208 &endianness, &sign, &realbits, &storagebits, &shift);
211 (endianness != 'b' && endianness != 'l') ||
212 (sign != 'u' && sign != 's') ||
213 realbits > storagebits ||
214 (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
215 ALOGE("Invalid iio channel type spec: %s\n", type_buf);
219 type_info->endianness = endianness;
220 type_info->sign = sign;
221 type_info->realbits = (short) realbits;
222 type_info->storagebits = (short) storagebits;
223 type_info->shift = (short) shift;
225 return storagebits / 8;
229 void build_sensor_report_maps (int dev_num)
232 * Read sysfs files from a iio device's scan_element directory, and
233 * build a couple of tables from that data. These tables will tell, for
234 * each sensor, where to gather relevant data in a device report, i.e.
235 * the structure that we read from the /dev/iio:deviceX file in order to
236 * sensor report, itself being the data that we return to Android when a
237 * sensor poll completes. The mapping should be straightforward in the
238 * case where we have a single sensor active per iio device but, this is
239 * not the general case. In general several sensors can be handled
240 * through a single iio device, and the _en, _index and _type syfs
241 * entries all concur to paint a picture of what the structure of the
251 char spec_buf[MAX_TYPE_SPEC_LEN];
252 struct datum_info_t* ch_info;
254 char sysfs_path[PATH_MAX];
257 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
258 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
259 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
263 /* For each sensor that is linked to this device */
264 for (s=0; s<sensor_count; s++) {
265 if (sensor[s].dev_num != dev_num)
268 i = sensor[s].catalog_index;
270 /* Read channel details through sysfs attributes */
271 for (c=0; c<sensor[s].num_channels; c++) {
273 /* Read _type file */
274 sprintf(sysfs_path, CHANNEL_PATH "%s",
276 sensor_catalog[i].channel[c].type_path);
278 n = sysfs_read_str(sysfs_path, spec_buf,
282 ALOGW( "Failed to read type: %s\n",
287 ch_spec = sensor[s].channel[c].type_spec;
289 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
291 ch_info = &sensor[s].channel[c].type_info;
293 size = decode_type_spec(ch_spec, ch_info);
295 /* Read _index file */
296 sprintf(sysfs_path, CHANNEL_PATH "%s",
298 sensor_catalog[i].channel[c].index_path);
300 n = sysfs_read_int(sysfs_path, &ch_index);
303 ALOGW( "Failed to read index: %s\n",
308 if (ch_index >= MAX_SENSORS) {
309 ALOGE("Index out of bounds!: %s\n", sysfs_path);
313 /* Record what this index is about */
315 sensor_handle_from_index [ch_index] = s;
316 channel_number_from_index[ch_index] = c;
317 channel_size_from_index [ch_index] = size;
322 /* Stop sampling - if we are recovering from hal restart */
323 enable_buffer(dev_num, 0);
324 setup_trigger(s, "\n");
326 /* Turn on channels we're aware of */
327 for (c=0;c<sensor[s].num_channels; c++) {
328 sprintf(sysfs_path, CHANNEL_PATH "%s",
330 sensor_catalog[i].channel[c].en_path);
331 sysfs_write_int(sysfs_path, 1);
335 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
338 * Now that we know which channels are defined, their sizes and their
339 * ordering, update channels offsets within device report. Note: there
340 * is a possibility that several sensors share the same index, with
341 * their data fields being isolated by masking and shifting as specified
342 * through the real bits and shift values in type attributes. This case
343 * is not currently supported. Also, the code below assumes no hole in
344 * the sequence of indices, so it is dependent on discovery of all
348 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
349 s = sensor_handle_from_index[i];
350 c = channel_number_from_index[i];
351 size = channel_size_from_index[i];
356 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
357 s, c, offset, size, sensor[s].channel[c].type_spec);
359 sensor[s].channel[c].offset = offset;
360 sensor[s].channel[c].size = size;
365 /* Enable the timestamp channel if there is one available */
366 enable_iio_timestamp(dev_num, known_channels);
368 /* Add padding and timestamp size if it's enabled on this iio device */
369 if (has_iio_ts[dev_num])
370 offset = (offset+7)/8*8 + sizeof(int64_t);
372 expected_dev_report_size[dev_num] = offset;
373 ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
375 if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
376 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n",
377 dev_num, expected_dev_report_size[dev_num]);
379 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
384 int adjust_counters (int s, int enabled, int from_virtual)
387 * Adjust counters based on sensor enable action. Return values are:
388 * -1 if there's an inconsistency: abort action in this case
389 * 0 if the operation was completed and we're all set
390 * 1 if we toggled the state of the sensor and there's work left
393 int dev_num = sensor[s].dev_num;
395 if (!check_state_change(s, enabled, from_virtual))
399 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
400 s, dev_num, sensor[s].friendly_name);
402 switch (sensor[s].type) {
403 case SENSOR_TYPE_MAGNETIC_FIELD:
404 compass_read_data(&sensor[s]);
407 case SENSOR_TYPE_GYROSCOPE:
408 gyro_cal_init(&sensor[s]);
412 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
413 sensor[s].friendly_name);
415 /* Sensor disabled, lower report available flag */
416 sensor[s].report_pending = 0;
418 if (sensor[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
419 compass_store_data(&sensor[s]);
421 if(sensor[s].type == SENSOR_TYPE_GYROSCOPE)
422 gyro_store_data(&sensor[s]);
425 /* We changed the state of a sensor - adjust per iio device counters */
426 /* If this is a regular event-driven sensor */
427 if (sensor[s].num_channels) {
430 trig_sensors_per_dev[dev_num]++;
432 trig_sensors_per_dev[dev_num]--;
438 active_poll_sensors++;
439 poll_sensors_per_dev[dev_num]++;
443 active_poll_sensors--;
444 poll_sensors_per_dev[dev_num]--;
449 static int get_field_count (int s)
451 switch (sensor[s].type) {
452 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
453 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
454 case SENSOR_TYPE_ORIENTATION: /* degrees */
455 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
456 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
459 case SENSOR_TYPE_LIGHT: /* SI lux units */
460 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
461 case SENSOR_TYPE_TEMPERATURE: /* °C */
462 case SENSOR_TYPE_PROXIMITY: /* centimeters */
463 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
464 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
467 case SENSOR_TYPE_ROTATION_VECTOR:
471 ALOGE("Unknown sensor type!\n");
472 return 0; /* Drop sample */
477 static void* acquisition_routine (void* param)
480 * Data acquisition routine run in a dedicated thread, covering a single
481 * sensor. This loop will periodically retrieve sampling data through
482 * sysfs, then package it as a sample and transfer it to our master poll
483 * loop through a report fd. Checks for a cancellation signal quite
484 * frequently, as the thread may be disposed of at any time. Note that
485 * Bionic does not provide pthread_cancel / pthread_testcancel...
488 int s = (int) (size_t) param;
489 int num_fields, sample_size;
490 struct sensors_event_t data = {0};
493 struct timespec target_time;
494 int64_t timestamp, period, start, stop;
496 if (s < 0 || s >= sensor_count) {
497 ALOGE("Invalid sensor handle!\n");
501 ALOGI("Entering data acquisition thread S%d (%s): rate(%f), ts(%lld)\n", s,
502 sensor[s].friendly_name, sensor[s].sampling_rate, sensor[s].report_ts);
504 if (sensor[s].sampling_rate <= 0) {
505 ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
506 s, sensor[s].sampling_rate);
510 num_fields = get_field_count(s);
511 sample_size = sizeof(int64_t) + num_fields * sizeof(float);
514 * Each condition variable is associated to a mutex that has to be
515 * 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
517 * the sampling rate is adjusted, or the sensor is disabled.
519 pthread_mutex_lock(&thread_release_mutex[s]);
521 /* Pinpoint the moment we start sampling */
522 timestamp = get_timestamp_monotonic();
524 /* Check and honor termination requests */
525 while (sensor[s].thread_data_fd[1] != -1) {
526 start = get_timestamp_boot();
527 /* Read values through sysfs */
528 for (c=0; c<num_fields; c++) {
529 data.data[c] = acquire_immediate_value(s, c);
530 /* Check and honor termination requests */
531 if (sensor[s].thread_data_fd[1] == -1)
534 stop = get_timestamp_boot();
535 data.timestamp = start/2 + stop/2;
537 /* If the sample looks good */
538 if (sensor[s].ops.finalize(s, &data)) {
540 /* Pipe it for transmission to poll loop */
541 ret = write( sensor[s].thread_data_fd[1],
542 &data.timestamp, sample_size);
544 if (ret != sample_size)
545 ALOGE("S%d acquisition thread: tried to write %d, ret: %d\n",
546 s, sample_size, ret);
549 /* Check and honor termination requests */
550 if (sensor[s].thread_data_fd[1] == -1)
553 /* Recalculate period asumming sensor[s].sampling_rate
554 * can be changed dynamically during the thread run */
555 if (sensor[s].sampling_rate <= 0) {
556 ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
557 s, sensor[s].sampling_rate);
561 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
563 set_timestamp(&target_time, timestamp);
566 * Wait until the sampling time elapses, or a rate change is
567 * signaled, or a thread exit is requested.
569 ret = pthread_cond_timedwait( &thread_release_cond[s],
570 &thread_release_mutex[s],
575 ALOGV("Acquisition thread for S%d exiting\n", s);
576 pthread_mutex_unlock(&thread_release_mutex[s]);
582 static void start_acquisition_thread (int s)
584 int incoming_data_fd;
587 struct epoll_event ev = {0};
589 ALOGV("Initializing acquisition context for sensor %d\n", s);
591 /* Create condition variable and mutex for quick thread release */
592 ret = pthread_condattr_init(&thread_cond_attr[s]);
593 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
594 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
595 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
597 /* Create a pipe for inter thread communication */
598 ret = pipe(sensor[s].thread_data_fd);
600 incoming_data_fd = sensor[s].thread_data_fd[0];
603 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
605 /* Add incoming side of pipe to our poll set, with a suitable tag */
606 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
608 /* Create and start worker thread */
609 ret = pthread_create( &sensor[s].acquisition_thread,
616 static void stop_acquisition_thread (int s)
618 int incoming_data_fd = sensor[s].thread_data_fd[0];
619 int outgoing_data_fd = sensor[s].thread_data_fd[1];
621 ALOGV("Tearing down acquisition context for sensor %d\n", s);
623 /* Delete the incoming side of the pipe from our poll set */
624 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
626 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
627 sensor[s].thread_data_fd[0] = -1;
628 sensor[s].thread_data_fd[1] = -1;
630 /* Close both sides of our pipe */
631 close(incoming_data_fd);
632 close(outgoing_data_fd);
634 /* Stop acquisition thread and clean up thread handle */
635 pthread_cond_signal(&thread_release_cond[s]);
636 pthread_join(sensor[s].acquisition_thread, NULL);
638 /* Clean up our sensor descriptor */
639 sensor[s].acquisition_thread = -1;
641 /* Delete condition variable and mutex */
642 pthread_cond_destroy(&thread_release_cond[s]);
643 pthread_mutex_destroy(&thread_release_mutex[s]);
646 static void sensor_activate_virtual(int s, int enabled, int from_virtual)
650 sensor[s].event_count = 0;
651 sensor[s].meta_data_pending = 0;
653 if (!check_state_change(s, enabled, from_virtual))
656 /* Enable all the base sensors for this virtual one */
657 for (i = 0; i < sensor[s].base_count; i++) {
658 base = sensor[s].base_idx[i];
659 sensor_activate(base, enabled, 1);
660 sensor[base].ref_count++;
665 /* Sensor disabled, lower report available flag */
666 sensor[s].report_pending = 0;
668 for (i = 0; i < sensor[s].base_count; i++) {
669 base = sensor[s].base_idx[i];
670 sensor_activate(base, enabled, 1);
671 sensor[base].ref_count--;
677 static int is_fast_accelerometer (int s)
680 * Some games don't react well to accelerometers using any-motion
681 * triggers. Even very low thresholds seem to trip them, and they tend
682 * to request fairly high event rates. Favor continuous triggers if the
683 * sensor is an accelerometer and uses a sampling rate of at least 25.
686 if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
689 if (sensor[s].sampling_rate < 25)
695 static void tentative_switch_trigger (int s)
698 * Under certain situations it may be beneficial to use an alternate
701 * - for applications using the accelerometer with high sampling rates,
702 * prefer the continuous trigger over the any-motion one, to avoid
703 * jumps related to motion thresholds
706 if (is_fast_accelerometer(s) &&
707 !(sensor[s].quirks & QUIRK_TERSE_DRIVER) &&
708 sensor[s].selected_trigger ==
709 sensor[s].motion_trigger_name)
710 setup_trigger(s, sensor[s].init_trigger_name);
713 static int setup_delay_sysfs(int s, float new_sampling_rate)
715 /* Set the rate at which a specific sensor should report events */
717 /* See Android sensors.h for indication on sensor trigger modes */
719 char sysfs_path[PATH_MAX];
720 char avail_sysfs_path[PATH_MAX];
721 float cur_sampling_rate; /* Currently used sampling rate */
722 int dev_num = sensor[s].dev_num;
723 int i = sensor[s].catalog_index;
724 const char *prefix = sensor_catalog[i].tag;
725 int per_sensor_sampling_rate;
726 int per_device_sampling_rate;
727 int32_t min_delay_us = sensor_desc[s].minDelay;
728 max_delay_t max_delay_us = sensor_desc[s].maxDelay;
729 float min_supported_rate = max_delay_us ? (1000000.0 / max_delay_us) : 1;
730 float max_supported_rate =
731 (min_delay_us && min_delay_us != -1) ? (1000000.0 / min_delay_us) : 0;
737 if (new_sampling_rate < min_supported_rate)
738 new_sampling_rate = min_supported_rate;
740 if (max_supported_rate &&
741 new_sampling_rate > max_supported_rate) {
742 new_sampling_rate = max_supported_rate;
745 sensor[s].sampling_rate = new_sampling_rate;
747 /* If we're dealing with a poll-mode sensor */
748 if (!sensor[s].num_channels) {
749 /* Interrupt current sleep so the new sampling gets used */
750 pthread_cond_signal(&thread_release_cond[s]);
754 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
756 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
757 per_sensor_sampling_rate = 1;
758 per_device_sampling_rate = 0;
760 per_sensor_sampling_rate = 0;
762 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
764 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
765 per_device_sampling_rate = 1;
767 per_device_sampling_rate = 0;
770 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
771 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
775 /* Coordinate with others active sensors on the same device, if any */
776 if (per_device_sampling_rate)
777 for (n=0; n<sensor_count; n++)
778 if (n != s && sensor[n].dev_num == dev_num &&
779 sensor[n].num_channels &&
781 sensor[n].sampling_rate > new_sampling_rate)
782 new_sampling_rate= sensor[n].sampling_rate;
784 /* Check if we have contraints on allowed sampling rates */
786 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
788 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
791 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
793 /* While we're not at the end of the string */
794 while (*cursor && cursor[0]) {
796 /* Decode a single value */
797 sr = strtod(cursor, NULL);
799 /* If this matches the selected rate, we're happy */
800 if (new_sampling_rate == sr)
804 * If we reached a higher value than the desired rate,
805 * adjust selected rate so it matches the first higher
806 * available one and stop parsing - this makes the
807 * assumption that rates are sorted by increasing value
808 * in the allowed frequencies string.
810 if (sr > new_sampling_rate) {
811 new_sampling_rate = sr;
816 while (cursor[0] && !isspace(cursor[0]))
820 while (cursor[0] && isspace(cursor[0]))
825 if (max_supported_rate &&
826 new_sampling_rate > max_supported_rate) {
827 new_sampling_rate = max_supported_rate;
830 /* If the desired rate is already active we're all set */
831 if (new_sampling_rate == cur_sampling_rate)
834 ALOGI("Sensor %d sampling rate set to %g\n", s, new_sampling_rate);
836 if (trig_sensors_per_dev[dev_num])
837 enable_buffer(dev_num, 0);
839 sysfs_write_float(sysfs_path, new_sampling_rate);
841 /* Check if it makes sense to use an alternate trigger */
842 tentative_switch_trigger(s);
844 if (trig_sensors_per_dev[dev_num])
845 enable_buffer(dev_num, 1);
850 * We go through all the virtual sensors of the base - and the base itself
851 * in order to recompute the maximum requested delay of the group and setup the base
852 * at that specific delay.
854 static int arbitrate_bases (int s)
858 float arbitrated_rate = 0;
860 if (sensor[s].directly_enabled)
861 arbitrated_rate = sensor[s].requested_rate;
863 for (i = 0; i < sensor_count; i++) {
864 for (vidx = 0; vidx < sensor[i].base_count; vidx++)
865 /* If we have a virtual sensor depending on this one - handle it */
866 if (sensor[i].base_idx[vidx] == s &&
867 sensor[i].directly_enabled &&
868 sensor[i].requested_rate > arbitrated_rate)
869 arbitrated_rate = sensor[i].requested_rate;
872 return setup_delay_sysfs(s, arbitrated_rate);
876 * Re-assesment for delays. We need to re-asses delays for all related groups
877 * of sensors everytime a sensor enables / disables / changes frequency.
879 int arbitrate_delays (int s)
883 if (!sensor[s].is_virtual) {
884 return arbitrate_bases(s);
886 /* Is virtual sensor - go through bases */
887 for (i = 0; i < sensor[s].base_count; i++)
888 arbitrate_bases(sensor[s].base_idx[i]);
892 int sensor_activate(int s, int enabled, int from_virtual)
894 char device_name[PATH_MAX];
895 struct epoll_event ev = {0};
898 int dev_num = sensor[s].dev_num;
899 int is_poll_sensor = !sensor[s].num_channels;
901 if (sensor[s].is_virtual) {
902 sensor_activate_virtual(s, enabled, from_virtual);
907 /* Prepare the report timestamp field for the first event, see set_report_ts method */
908 sensor[s].report_ts = 0;
909 ret = adjust_counters(s, enabled, from_virtual);
911 /* If the operation was neutral in terms of state, we're done */
917 sensor[s].event_count = 0;
918 sensor[s].meta_data_pending = 0;
920 if (enabled && (sensor[s].quirks & QUIRK_NOISY))
921 /* Initialize filtering data if required */
922 setup_noise_filtering(s);
924 if (!is_poll_sensor) {
927 enable_buffer(dev_num, 0);
928 setup_trigger(s, "\n");
930 /* If there's at least one sensor enabled on this iio device */
931 if (trig_sensors_per_dev[dev_num]) {
934 setup_trigger(s, sensor[s].init_trigger_name);
935 enable_buffer(dev_num, 1);
940 * Make sure we have a fd on the character device ; conversely, close
941 * the fd if no one is using associated sensors anymore. The assumption
942 * here is that the underlying driver will power on the relevant
943 * hardware block while someone holds a fd on the device.
945 dev_fd = device_fd[dev_num];
949 stop_acquisition_thread(s);
951 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
952 !trig_sensors_per_dev[dev_num]) {
954 * Stop watching this fd. This should be a no-op
955 * in case this fd was not in the poll set.
957 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
960 device_fd[dev_num] = -1;
963 /* Release any filtering data we may have accumulated */
964 release_noise_filtering_data(s);
970 /* First enabled sensor on this iio device */
971 sprintf(device_name, DEV_FILE_PATH, dev_num);
972 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
974 device_fd[dev_num] = dev_fd;
977 ALOGE("Could not open fd on %s (%s)\n",
978 device_name, strerror(errno));
979 adjust_counters(s, 0, from_virtual);
983 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
985 if (!is_poll_sensor) {
987 /* Add this iio device fd to the set of watched fds */
989 ev.data.u32 = dev_num;
991 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
994 ALOGE( "Failed adding %d to poll set (%s)\n",
995 dev_fd, strerror(errno));
999 /* Note: poll-mode fds are not readable */
1003 /* Ensure that on-change sensors send at least one event after enable */
1004 sensor[s].prev_val = -1;
1007 start_acquisition_thread(s);
1013 static void enable_motion_trigger (int dev_num)
1016 * In the ideal case, we enumerate two triggers per iio device ; the
1017 * default (periodically firing) trigger, and another one (the motion
1018 * trigger) that only fires up when motion is detected. This second one
1019 * allows for lesser energy consumption, but requires periodic sample
1020 * duplication at the HAL level for sensors that Android defines as
1021 * continuous. This "duplicate last sample" logic can only be engaged
1022 * once we got a first sample for the driver, so we start with the
1023 * default trigger when an iio device is first opened, then adjust the
1024 * trigger when we got events for all active sensors. Unfortunately in
1025 * the general case several sensors can be associated to a given iio
1026 * device, they can independently be controlled, and we have to adjust
1027 * the trigger in use at the iio device level depending on whether or
1028 * not appropriate conditions are met at the sensor level.
1033 int active_sensors = trig_sensors_per_dev[dev_num];
1034 int candidate[MAX_SENSORS];
1035 int candidate_count = 0;
1037 if (!active_sensors)
1040 /* Check that all active sensors are ready to switch */
1042 for (s=0; s<MAX_SENSORS; s++)
1043 if (sensor[s].dev_num == dev_num &&
1045 sensor[s].num_channels &&
1046 (!sensor[s].motion_trigger_name[0] ||
1047 !sensor[s].report_initialized ||
1048 is_fast_accelerometer(s) ||
1049 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS))
1053 /* Record which particular sensors need to switch */
1055 for (s=0; s<MAX_SENSORS; s++)
1056 if (sensor[s].dev_num == dev_num &&
1058 sensor[s].num_channels &&
1059 sensor[s].selected_trigger !=
1060 sensor[s].motion_trigger_name)
1061 candidate[candidate_count++] = s;
1063 if (!candidate_count)
1066 /* Now engage the motion trigger for sensors which aren't using it */
1068 enable_buffer(dev_num, 0);
1070 for (i=0; i<candidate_count; i++) {
1072 setup_trigger(s, sensor[s].motion_trigger_name);
1075 enable_buffer(dev_num, 1);
1078 /* CTS acceptable thresholds:
1079 * EventGapVerification.java: (th <= 1.8)
1080 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
1082 #define THRESHOLD 1.10
1083 #define MAX_DELAY 500000000 /* 500 ms */
1085 void set_report_ts(int s, int64_t ts)
1087 int64_t maxTs, period;
1090 * A bit of a hack to please a bunch of cts tests. They
1091 * expect the timestamp to be exacly according to the set-up
1092 * frequency but if we're simply getting the timestamp at hal level
1093 * this may not be the case. Perhaps we'll get rid of this when
1094 * we'll be reading the timestamp from the iio channel for all sensors
1096 if (sensor[s].report_ts && sensor[s].sampling_rate &&
1097 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
1099 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
1100 maxTs = sensor[s].report_ts + THRESHOLD * period;
1101 /* If we're too far behind get back on track */
1102 if (ts - maxTs >= MAX_DELAY)
1104 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
1106 sensor[s].report_ts = ts;
1111 static void stamp_reports (int dev_num, int64_t ts)
1115 for (s=0; s<MAX_SENSORS; s++)
1116 if (sensor[s].dev_num == dev_num &&
1118 set_report_ts(s, ts);
1122 static int integrate_device_report (int dev_num)
1126 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1128 unsigned char *target;
1129 unsigned char *source;
1132 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1133 int64_t boot_to_rt_delta;
1135 /* There's an incoming report on the specified iio device char dev fd */
1137 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1138 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1142 if (device_fd[dev_num] == -1) {
1143 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1147 len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]);
1150 ALOGE("Could not read report from iio device %d (%s)\n",
1151 dev_num, strerror(errno));
1155 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1157 /* Map device report to sensor reports */
1159 for (s=0; s<MAX_SENSORS; s++)
1160 if (sensor[s].dev_num == dev_num &&
1165 /* Copy data from device to sensor report buffer */
1166 for (c=0; c<sensor[s].num_channels; c++) {
1168 target = sensor[s].report_buffer +
1171 source = buf + sensor[s].channel[c].offset;
1173 size = sensor[s].channel[c].size;
1175 memcpy(target, source, size);
1180 ALOGV("Sensor %d report available (%d bytes)\n", s,
1183 sensor[s].report_pending = DATA_TRIGGER;
1184 sensor[s].report_initialized = 1;
1186 ts_offset += sr_offset;
1189 /* Tentatively switch to an any-motion trigger if conditions are met */
1190 enable_motion_trigger(dev_num);
1192 /* If no iio timestamp channel was detected for this device, bail out */
1193 if (!has_iio_ts[dev_num]) {
1194 stamp_reports(dev_num, get_timestamp_boot());
1198 /* Don't trust the timestamp channel in any-motion mode */
1199 for (s=0; s<MAX_SENSORS; s++)
1200 if (sensor[s].dev_num == dev_num &&
1202 sensor[s].selected_trigger ==
1203 sensor[s].motion_trigger_name) {
1204 stamp_reports(dev_num, get_timestamp_boot());
1208 /* Align on a 64 bits boundary */
1209 ts_offset = (ts_offset + 7)/8*8;
1211 /* If we read an amount of data consistent with timestamp presence */
1212 if (len == expected_dev_report_size[dev_num])
1213 ts = *(int64_t*) (buf + ts_offset);
1216 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1217 stamp_reports(dev_num, get_timestamp_boot());
1221 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1223 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1225 stamp_reports(dev_num, ts + boot_to_rt_delta);
1230 static int propagate_vsensor_report (int s, struct sensors_event_t *data)
1232 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1234 memcpy(data, &sensor[s].sample, sizeof(struct sensors_event_t));
1237 data->type = sensor[s].type;
1241 static int propagate_sensor_report (int s, struct sensors_event_t *data)
1243 /* There's a sensor report pending for this sensor ; transmit it */
1245 int num_fields = get_field_count(s);
1247 unsigned char* current_sample;
1249 /* If there's nothing to return... we're done */
1253 memset(data, 0, sizeof(sensors_event_t));
1255 data->version = sizeof(sensors_event_t);
1257 data->type = sensor[s].type;
1258 data->timestamp = sensor[s].report_ts;
1260 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1262 current_sample = sensor[s].report_buffer;
1264 /* If this is a poll sensor */
1265 if (!sensor[s].num_channels) {
1266 /* Use the data provided by the acquisition thread */
1267 ALOGV("Reporting data from worker thread for S%d\n", s);
1268 memcpy(data->data, current_sample, num_fields * sizeof(float));
1272 /* Convert the data into the expected Android-level format */
1273 for (c=0; c<num_fields; c++) {
1275 data->data[c] = sensor[s].ops.transform
1276 (s, c, current_sample);
1278 ALOGV("\tfield %d: %f\n", c, data->data[c]);
1279 current_sample += sensor[s].channel[c].size;
1283 * The finalize routine, in addition to its late sample processing duty,
1284 * has the final say on whether or not the sample gets sent to Android.
1286 return sensor[s].ops.finalize(s, data);
1290 static void synthetize_duplicate_samples (void)
1293 * Some sensor types (ex: gyroscope) are defined as continuously firing
1294 * by Android, despite the fact that we can be dealing with iio drivers
1295 * that only report events for new samples. For these we generate
1296 * reports periodically, duplicating the last data we got from the
1297 * driver. This is not necessary for polling sensors.
1305 for (s=0; s<sensor_count; s++) {
1307 /* Ignore disabled sensors */
1311 /* If the sensor is continuously firing, leave it alone */
1312 if (sensor[s].selected_trigger !=
1313 sensor[s].motion_trigger_name)
1316 /* If we haven't seen a sample, there's nothing to duplicate */
1317 if (!sensor[s].report_initialized)
1320 /* If a sample was recently buffered, leave it alone too */
1321 if (sensor[s].report_pending)
1324 /* We also need a valid sampling rate to be configured */
1325 if (!sensor[s].sampling_rate)
1328 period = (int64_t) (1000000000.0/ sensor[s].sampling_rate);
1330 current_ts = get_timestamp_boot();
1331 target_ts = sensor[s].report_ts + period;
1333 if (target_ts <= current_ts) {
1334 /* Mark the sensor for event generation */
1335 set_report_ts(s, current_ts);
1336 sensor[s].report_pending = DATA_DUPLICATE;
1342 static void integrate_thread_report (uint32_t tag)
1344 int s = tag - THREAD_REPORT_TAG_BASE;
1348 unsigned char current_sample[MAX_SENSOR_REPORT_SIZE];
1350 expected_len = sizeof(int64_t) + get_field_count(s) * sizeof(float);
1352 len = read(sensor[s].thread_data_fd[0],
1356 memcpy(×tamp, current_sample, sizeof(int64_t));
1357 memcpy(sensor[s].report_buffer, sizeof(int64_t) + current_sample,
1358 expected_len - sizeof(int64_t));
1360 if (len == expected_len) {
1361 set_report_ts(s, timestamp);
1362 sensor[s].report_pending = DATA_SYSFS;
1367 static int get_poll_wait_timeout (void)
1370 * Compute an appropriate timeout value, in ms, for the epoll_wait
1371 * call that's going to await for iio device reports and incoming
1372 * reports from our sensor sysfs data reader threads.
1376 int64_t target_ts = INT64_MAX;
1381 * Check if we're dealing with a driver that only send events when
1382 * there is motion, despite the fact that the associated Android sensor
1383 * type is continuous rather than on-change. In that case we have to
1384 * duplicate events. Check deadline for the nearest upcoming event.
1386 for (s=0; s<sensor_count; s++)
1387 if (is_enabled(s) &&
1388 sensor[s].selected_trigger ==
1389 sensor[s].motion_trigger_name &&
1390 sensor[s].sampling_rate) {
1391 period = (int64_t) (1000000000.0 /
1392 sensor[s].sampling_rate);
1394 if (sensor[s].report_ts + period < target_ts)
1395 target_ts = sensor[s].report_ts + period;
1398 /* If we don't have such a driver to deal with */
1399 if (target_ts == INT64_MAX)
1400 return -1; /* Infinite wait */
1402 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1404 /* If the target timestamp is already behind us, don't wait */
1412 int sensor_poll(struct sensors_event_t* data, int count)
1417 struct epoll_event ev[MAX_DEVICES];
1418 int returned_events;
1422 /* Get one or more events from our collection of sensors */
1423 return_available_sensor_reports:
1425 /* Synthetize duplicate samples if needed */
1426 synthetize_duplicate_samples();
1428 returned_events = 0;
1429 /* Check our sensor collection for available reports */
1430 for (s=0; s<sensor_count && returned_events < count; s++) {
1431 if (sensor[s].report_pending) {
1434 if (sensor[s].is_virtual)
1435 event_count = propagate_vsensor_report(s, &data[returned_events]);
1437 /* Report this event if it looks OK */
1438 event_count = propagate_sensor_report(s, &data[returned_events]);
1442 sensor[s].report_pending = 0;
1443 returned_events += event_count;
1445 * If the sample was deemed invalid or unreportable,
1446 * e.g. had the same value as the previously reported
1447 * value for a 'on change' sensor, silently drop it.
1450 while (sensor[s].meta_data_pending) {
1451 /* See sensors.h on these */
1452 data[returned_events].version = META_DATA_VERSION;
1453 data[returned_events].sensor = 0;
1454 data[returned_events].type = SENSOR_TYPE_META_DATA;
1455 data[returned_events].reserved0 = 0;
1456 data[returned_events].timestamp = 0;
1457 data[returned_events].meta_data.sensor = s;
1458 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1460 sensor[s].meta_data_pending--;
1463 if (returned_events)
1464 return returned_events;
1468 ALOGV("Awaiting sensor data\n");
1470 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1473 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1477 ALOGV("%d fds signalled\n", nfds);
1479 /* For each of the signalled sources */
1480 for (i=0; i<nfds; i++)
1481 if (ev[i].events == EPOLLIN)
1482 switch (ev[i].data.u32) {
1483 case 0 ... MAX_DEVICES-1:
1484 /* Read report from iio char dev fd */
1485 integrate_device_report(ev[i].data.u32);
1488 case THREAD_REPORT_TAG_BASE ...
1489 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1490 /* Get report from acquisition thread */
1491 integrate_thread_report(ev[i].data.u32);
1495 ALOGW("Unexpected event source!\n");
1499 goto return_available_sensor_reports;
1502 int sensor_set_delay(int s, int64_t ns)
1504 float new_sampling_rate; /* Granted sampling rate after arbitration */
1507 ALOGE("Rejecting non-positive delay request on sensor %d,required delay: %lld\n", s, ns);
1511 new_sampling_rate = 1000000000LL/ns;
1513 ALOGV("Entering set delay S%d (%s): old rate(%f), new rate(%f)\n",
1514 s, sensor[s].friendly_name, sensor[s].sampling_rate,
1517 sensor[s].requested_rate = new_sampling_rate;
1519 return arbitrate_delays(s);
1522 int sensor_flush (int s)
1524 /* If one shot or not enabled return -EINVAL */
1525 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1528 sensor[s].meta_data_pending++;
1532 int allocate_control_data (void)
1536 for (i=0; i<MAX_DEVICES; i++)
1539 poll_fd = epoll_create(MAX_DEVICES);
1541 if (poll_fd == -1) {
1542 ALOGE("Can't create epoll instance for iio sensors!\n");
1550 void delete_control_data (void)