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
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)
63 /* If we were enabled by Android no sample drops */
65 sensor[s].directly_enabled = 1;
68 * If we got here it means we were not previously directly enabled - we may
69 * or may not be now, whatever the case if we already had references we
72 if (sensor[s].ref_count)
78 /* Spurious disable call */
82 /* We're requesting disable for a virtual sensor but the base is still active */
83 if (from_virtual && sensor[s].directly_enabled)
86 /* If it's disable, and it's from Android, and we still have ref counts */
87 if (!from_virtual && sensor[s].ref_count) {
88 sensor[s].directly_enabled = 0;
92 /*If perhaps we are from virtual but we're disabling it*/
93 sensor[s].directly_enabled = 0;
99 static int enable_buffer(int dev_num, int enabled)
101 char sysfs_path[PATH_MAX];
102 int ret, retries, millisec;
103 struct timespec req = {0};
105 retries = ENABLE_BUFFER_RETRIES;
106 millisec = ENABLE_BUFFER_RETRY_DELAY_MS;
108 req.tv_nsec = millisec * 1000000L;
110 sprintf(sysfs_path, ENABLE_PATH, dev_num);
113 /* Low level, non-multiplexed, enable/disable routine */
114 ret = sysfs_write_int(sysfs_path, enabled);
118 ALOGE("Failed enabling buffer, retrying");
119 nanosleep(&req, (struct timespec *)NULL);
123 ALOGE("Could not enable buffer\n");
131 static int setup_trigger (int s, const char* trigger_val)
133 char sysfs_path[PATH_MAX];
134 int ret = -1, attempts = 5;
136 sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
138 if (trigger_val[0] != '\n')
139 ALOGI("Setting S%d (%s) trigger to %s\n", s,
140 sensor[s].friendly_name, trigger_val);
142 while (ret == -1 && attempts) {
143 ret = sysfs_write_str(sysfs_path, trigger_val);
148 sensor[s].selected_trigger = trigger_val;
150 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s,
151 sensor[s].friendly_name, trigger_val);
156 static void enable_iio_timestamp (int dev_num, int known_channels)
158 /* Check if we have a dedicated iio timestamp channel */
160 char spec_buf[MAX_TYPE_SPEC_LEN];
161 char sysfs_path[PATH_MAX];
164 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
166 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
171 if (strcmp(spec_buf, "le:s64/64>>0"))
174 /* OK, type is int64_t as expected, in little endian representation */
176 sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
178 if (sysfs_read_int(sysfs_path, &n))
181 /* Check that the timestamp comes after the other fields we read */
182 if (n != known_channels)
185 /* Try enabling that channel */
186 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
188 sysfs_write_int(sysfs_path, 1);
190 if (sysfs_read_int(sysfs_path, &n))
194 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
195 has_iio_ts[dev_num] = 1;
200 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN],
201 struct datum_info_t *type_info)
203 /* Return size in bytes for this type specification, or -1 in error */
206 unsigned int realbits, storagebits, shift;
209 /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
211 tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u",
212 &endianness, &sign, &realbits, &storagebits, &shift);
215 (endianness != 'b' && endianness != 'l') ||
216 (sign != 'u' && sign != 's') ||
217 realbits > storagebits ||
218 (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
219 ALOGE("Invalid iio channel type spec: %s\n", type_buf);
223 type_info->endianness = endianness;
224 type_info->sign = sign;
225 type_info->realbits = (short) realbits;
226 type_info->storagebits = (short) storagebits;
227 type_info->shift = (short) shift;
229 return storagebits / 8;
233 void build_sensor_report_maps (int dev_num)
236 * Read sysfs files from a iio device's scan_element directory, and
237 * build a couple of tables from that data. These tables will tell, for
238 * each sensor, where to gather relevant data in a device report, i.e.
239 * the structure that we read from the /dev/iio:deviceX file in order to
240 * sensor report, itself being the data that we return to Android when a
241 * sensor poll completes. The mapping should be straightforward in the
242 * case where we have a single sensor active per iio device but, this is
243 * not the general case. In general several sensors can be handled
244 * through a single iio device, and the _en, _index and _type syfs
245 * entries all concur to paint a picture of what the structure of the
255 char spec_buf[MAX_TYPE_SPEC_LEN];
256 struct datum_info_t* ch_info;
258 char sysfs_path[PATH_MAX];
261 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
262 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
263 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
267 /* For each sensor that is linked to this device */
268 for (s=0; s<sensor_count; s++) {
269 if (sensor[s].dev_num != dev_num)
272 i = sensor[s].catalog_index;
274 /* Read channel details through sysfs attributes */
275 for (c=0; c<sensor[s].num_channels; c++) {
277 /* Read _type file */
278 sprintf(sysfs_path, CHANNEL_PATH "%s",
280 sensor_catalog[i].channel[c].type_path);
282 n = sysfs_read_str(sysfs_path, spec_buf,
286 ALOGW( "Failed to read type: %s\n",
291 ch_spec = sensor[s].channel[c].type_spec;
293 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
295 ch_info = &sensor[s].channel[c].type_info;
297 size = decode_type_spec(ch_spec, ch_info);
299 /* Read _index file */
300 sprintf(sysfs_path, CHANNEL_PATH "%s",
302 sensor_catalog[i].channel[c].index_path);
304 n = sysfs_read_int(sysfs_path, &ch_index);
307 ALOGW( "Failed to read index: %s\n",
312 if (ch_index >= MAX_SENSORS) {
313 ALOGE("Index out of bounds!: %s\n", sysfs_path);
317 /* Record what this index is about */
319 sensor_handle_from_index [ch_index] = s;
320 channel_number_from_index[ch_index] = c;
321 channel_size_from_index [ch_index] = size;
326 /* Stop sampling - if we are recovering from hal restart */
327 enable_buffer(dev_num, 0);
328 setup_trigger(s, "\n");
330 /* Turn on channels we're aware of */
331 for (c=0;c<sensor[s].num_channels; c++) {
332 sprintf(sysfs_path, CHANNEL_PATH "%s",
334 sensor_catalog[i].channel[c].en_path);
335 sysfs_write_int(sysfs_path, 1);
339 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
342 * Now that we know which channels are defined, their sizes and their
343 * ordering, update channels offsets within device report. Note: there
344 * is a possibility that several sensors share the same index, with
345 * their data fields being isolated by masking and shifting as specified
346 * through the real bits and shift values in type attributes. This case
347 * is not currently supported. Also, the code below assumes no hole in
348 * the sequence of indices, so it is dependent on discovery of all
352 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
353 s = sensor_handle_from_index[i];
354 c = channel_number_from_index[i];
355 size = channel_size_from_index[i];
360 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
361 s, c, offset, size, sensor[s].channel[c].type_spec);
363 sensor[s].channel[c].offset = offset;
364 sensor[s].channel[c].size = size;
369 /* Enable the timestamp channel if there is one available */
370 enable_iio_timestamp(dev_num, known_channels);
372 /* Add padding and timestamp size if it's enabled on this iio device */
373 if (has_iio_ts[dev_num])
374 offset = (offset+7)/8*8 + sizeof(int64_t);
376 expected_dev_report_size[dev_num] = offset;
377 ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
379 if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
380 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n",
381 dev_num, expected_dev_report_size[dev_num]);
383 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
388 int adjust_counters (int s, int enabled, int from_virtual)
391 * Adjust counters based on sensor enable action. Return values are:
392 * -1 if there's an inconsistency: abort action in this case
393 * 0 if the operation was completed and we're all set
394 * 1 if we toggled the state of the sensor and there's work left
397 int dev_num = sensor[s].dev_num;
399 if (!check_state_change(s, enabled, from_virtual))
403 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
404 s, dev_num, sensor[s].friendly_name);
406 switch (sensor[s].type) {
407 case SENSOR_TYPE_MAGNETIC_FIELD:
408 compass_read_data(&sensor[s]);
411 case SENSOR_TYPE_GYROSCOPE:
412 gyro_cal_init(&sensor[s]);
416 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
417 sensor[s].friendly_name);
419 /* Sensor disabled, lower report available flag */
420 sensor[s].report_pending = 0;
422 if (sensor[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
423 compass_store_data(&sensor[s]);
425 if(sensor[s].type == SENSOR_TYPE_GYROSCOPE)
426 gyro_store_data(&sensor[s]);
429 /* We changed the state of a sensor - adjust per iio device counters */
430 /* If this is a regular event-driven sensor */
431 if (sensor[s].num_channels) {
434 trig_sensors_per_dev[dev_num]++;
436 trig_sensors_per_dev[dev_num]--;
442 active_poll_sensors++;
443 poll_sensors_per_dev[dev_num]++;
447 active_poll_sensors--;
448 poll_sensors_per_dev[dev_num]--;
453 static int get_field_count (int s)
455 switch (sensor[s].type) {
456 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
457 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
458 case SENSOR_TYPE_ORIENTATION: /* degrees */
459 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
460 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
463 case SENSOR_TYPE_LIGHT: /* SI lux units */
464 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
465 case SENSOR_TYPE_TEMPERATURE: /* °C */
466 case SENSOR_TYPE_PROXIMITY: /* centimeters */
467 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
468 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
471 case SENSOR_TYPE_ROTATION_VECTOR:
475 ALOGE("Unknown sensor type!\n");
476 return 0; /* Drop sample */
481 static void* acquisition_routine (void* param)
484 * Data acquisition routine run in a dedicated thread, covering a single
485 * sensor. This loop will periodically retrieve sampling data through
486 * sysfs, then package it as a sample and transfer it to our master poll
487 * loop through a report fd. Checks for a cancellation signal quite
488 * frequently, as the thread may be disposed of at any time. Note that
489 * Bionic does not provide pthread_cancel / pthread_testcancel...
492 int s = (int) (size_t) param;
493 int num_fields, sample_size;
494 struct sensors_event_t data = {0};
497 struct timespec target_time;
498 int64_t timestamp, period, start, stop;
500 if (s < 0 || s >= sensor_count) {
501 ALOGE("Invalid sensor handle!\n");
505 ALOGI("Entering data acquisition thread S%d (%s): rate(%f), ts(%lld)\n", s,
506 sensor[s].friendly_name, sensor[s].sampling_rate, sensor[s].report_ts);
508 if (sensor[s].sampling_rate <= 0) {
509 ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
510 s, sensor[s].sampling_rate);
514 num_fields = get_field_count(s);
515 sample_size = sizeof(int64_t) + num_fields * sizeof(float);
518 * Each condition variable is associated to a mutex that has to be
519 * locked by the thread that's waiting on it. We use these condition
520 * variables to get the acquisition threads out of sleep quickly after
521 * the sampling rate is adjusted, or the sensor is disabled.
523 pthread_mutex_lock(&thread_release_mutex[s]);
525 /* Pinpoint the moment we start sampling */
526 timestamp = get_timestamp_monotonic();
528 /* Check and honor termination requests */
529 while (sensor[s].thread_data_fd[1] != -1) {
530 start = get_timestamp_boot();
531 /* Read values through sysfs */
532 for (c=0; c<num_fields; c++) {
533 data.data[c] = acquire_immediate_value(s, c);
534 /* Check and honor termination requests */
535 if (sensor[s].thread_data_fd[1] == -1)
538 stop = get_timestamp_boot();
539 data.timestamp = start/2 + stop/2;
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],
546 &data.timestamp, sample_size);
548 if (ret != sample_size)
549 ALOGE("S%d acquisition thread: tried to write %d, ret: %d\n",
550 s, sample_size, ret);
553 /* Check and honor termination requests */
554 if (sensor[s].thread_data_fd[1] == -1)
557 /* Recalculate period asumming sensor[s].sampling_rate
558 * can be changed dynamically during the thread run */
559 if (sensor[s].sampling_rate <= 0) {
560 ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
561 s, sensor[s].sampling_rate);
565 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
567 set_timestamp(&target_time, timestamp);
570 * Wait until the sampling time elapses, or a rate change is
571 * signaled, or a thread exit is requested.
573 ret = pthread_cond_timedwait( &thread_release_cond[s],
574 &thread_release_mutex[s],
579 ALOGV("Acquisition thread for S%d exiting\n", s);
580 pthread_mutex_unlock(&thread_release_mutex[s]);
586 static void start_acquisition_thread (int s)
588 int incoming_data_fd;
591 struct epoll_event ev = {0};
593 ALOGV("Initializing acquisition context for sensor %d\n", s);
595 /* Create condition variable and mutex for quick thread release */
596 ret = pthread_condattr_init(&thread_cond_attr[s]);
597 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
598 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
599 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
601 /* Create a pipe for inter thread communication */
602 ret = pipe(sensor[s].thread_data_fd);
604 incoming_data_fd = sensor[s].thread_data_fd[0];
607 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
609 /* Add incoming side of pipe to our poll set, with a suitable tag */
610 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
612 /* Create and start worker thread */
613 ret = pthread_create( &sensor[s].acquisition_thread,
620 static void stop_acquisition_thread (int s)
622 int incoming_data_fd = sensor[s].thread_data_fd[0];
623 int outgoing_data_fd = sensor[s].thread_data_fd[1];
625 ALOGV("Tearing down acquisition context for sensor %d\n", s);
627 /* Delete the incoming side of the pipe from our poll set */
628 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
630 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
631 sensor[s].thread_data_fd[0] = -1;
632 sensor[s].thread_data_fd[1] = -1;
634 /* Close both sides of our pipe */
635 close(incoming_data_fd);
636 close(outgoing_data_fd);
638 /* Stop acquisition thread and clean up thread handle */
639 pthread_cond_signal(&thread_release_cond[s]);
640 pthread_join(sensor[s].acquisition_thread, NULL);
642 /* Clean up our sensor descriptor */
643 sensor[s].acquisition_thread = -1;
645 /* Delete condition variable and mutex */
646 pthread_cond_destroy(&thread_release_cond[s]);
647 pthread_mutex_destroy(&thread_release_mutex[s]);
651 static void sensor_activate_virtual (int s, int enabled, int from_virtual)
655 sensor[s].event_count = 0;
656 sensor[s].meta_data_pending = 0;
658 if (!check_state_change(s, enabled, from_virtual))
661 /* Enable all the base sensors for this virtual one */
662 for (i = 0; i < sensor[s].base_count; i++) {
663 base = sensor[s].base[i];
664 sensor_activate(base, enabled, 1);
665 sensor[base].ref_count++;
670 /* Sensor disabled, lower report available flag */
671 sensor[s].report_pending = 0;
673 for (i = 0; i < sensor[s].base_count; i++) {
674 base = sensor[s].base[i];
675 sensor_activate(base, enabled, 1);
676 sensor[base].ref_count--;
682 static int is_fast_accelerometer (int s)
685 * Some games don't react well to accelerometers using any-motion
686 * triggers. Even very low thresholds seem to trip them, and they tend
687 * to request fairly high event rates. Favor continuous triggers if the
688 * sensor is an accelerometer and uses a sampling rate of at least 25.
691 if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
694 if (sensor[s].sampling_rate < 25)
701 static void tentative_switch_trigger (int s)
704 * Under certain situations it may be beneficial to use an alternate
707 * - for applications using the accelerometer with high sampling rates,
708 * prefer the continuous trigger over the any-motion one, to avoid
709 * jumps related to motion thresholds
712 if (is_fast_accelerometer(s) &&
713 !(sensor[s].quirks & QUIRK_TERSE_DRIVER) &&
714 sensor[s].selected_trigger ==
715 sensor[s].motion_trigger_name)
716 setup_trigger(s, sensor[s].init_trigger_name);
720 static int setup_delay_sysfs (int s, float new_sampling_rate)
722 /* Set the rate at which a specific sensor should report events */
724 /* See Android sensors.h for indication on sensor trigger modes */
726 char sysfs_path[PATH_MAX];
727 char avail_sysfs_path[PATH_MAX];
728 float cur_sampling_rate; /* Currently used sampling rate */
729 int dev_num = sensor[s].dev_num;
730 int i = sensor[s].catalog_index;
731 const char *prefix = sensor_catalog[i].tag;
732 int per_sensor_sampling_rate;
733 int per_device_sampling_rate;
734 int32_t min_delay_us = sensor_desc[s].minDelay;
735 max_delay_t max_delay_us = sensor_desc[s].maxDelay;
736 float min_supported_rate = max_delay_us ? (1000000.0 / max_delay_us) : 1;
737 float max_supported_rate =
738 (min_delay_us && min_delay_us != -1) ? (1000000.0 / min_delay_us) : 0;
744 if (new_sampling_rate < min_supported_rate)
745 new_sampling_rate = min_supported_rate;
747 if (max_supported_rate &&
748 new_sampling_rate > max_supported_rate) {
749 new_sampling_rate = max_supported_rate;
752 sensor[s].sampling_rate = new_sampling_rate;
754 /* If we're dealing with a poll-mode sensor */
755 if (!sensor[s].num_channels) {
756 /* Interrupt current sleep so the new sampling gets used */
757 pthread_cond_signal(&thread_release_cond[s]);
761 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
763 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
764 per_sensor_sampling_rate = 1;
765 per_device_sampling_rate = 0;
767 per_sensor_sampling_rate = 0;
769 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
771 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
772 per_device_sampling_rate = 1;
774 per_device_sampling_rate = 0;
777 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
778 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
782 /* Coordinate with others active sensors on the same device, if any */
783 if (per_device_sampling_rate)
784 for (n=0; n<sensor_count; n++)
785 if (n != s && sensor[n].dev_num == dev_num &&
786 sensor[n].num_channels &&
788 sensor[n].sampling_rate > new_sampling_rate)
789 new_sampling_rate= sensor[n].sampling_rate;
791 /* Check if we have contraints on allowed sampling rates */
793 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
795 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
798 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
800 /* While we're not at the end of the string */
801 while (*cursor && cursor[0]) {
803 /* Decode a single value */
804 sr = strtod(cursor, NULL);
806 /* If this matches the selected rate, we're happy */
807 if (new_sampling_rate == sr)
811 * If we reached a higher value than the desired rate,
812 * adjust selected rate so it matches the first higher
813 * available one and stop parsing - this makes the
814 * assumption that rates are sorted by increasing value
815 * in the allowed frequencies string.
817 if (sr > new_sampling_rate) {
818 new_sampling_rate = sr;
823 while (cursor[0] && !isspace(cursor[0]))
827 while (cursor[0] && isspace(cursor[0]))
832 if (max_supported_rate &&
833 new_sampling_rate > max_supported_rate) {
834 new_sampling_rate = max_supported_rate;
837 /* If the desired rate is already active we're all set */
838 if (new_sampling_rate == cur_sampling_rate)
841 ALOGI("Sensor %d sampling rate set to %g\n", s, new_sampling_rate);
843 if (trig_sensors_per_dev[dev_num])
844 enable_buffer(dev_num, 0);
846 sysfs_write_float(sysfs_path, new_sampling_rate);
848 /* Check if it makes sense to use an alternate trigger */
849 tentative_switch_trigger(s);
851 if (trig_sensors_per_dev[dev_num])
852 enable_buffer(dev_num, 1);
859 * We go through all the virtual sensors of the base - and the base itself
860 * in order to recompute the maximum requested delay of the group and setup the base
861 * at that specific delay.
863 static int arbitrate_bases (int s)
867 float arbitrated_rate = 0;
869 if (sensor[s].directly_enabled)
870 arbitrated_rate = sensor[s].requested_rate;
872 for (i = 0; i < sensor_count; i++) {
873 for (vidx = 0; vidx < sensor[i].base_count; vidx++)
874 /* If we have a virtual sensor depending on this one - handle it */
875 if (sensor[i].base[vidx] == s &&
876 sensor[i].directly_enabled &&
877 sensor[i].requested_rate > arbitrated_rate)
878 arbitrated_rate = sensor[i].requested_rate;
881 return setup_delay_sysfs(s, arbitrated_rate);
886 * Re-assesment for delays. We need to re-asses delays for all related groups
887 * of sensors everytime a sensor enables / disables / changes frequency.
889 int arbitrate_delays (int s)
893 if (!sensor[s].is_virtual) {
894 return arbitrate_bases(s);
896 /* Is virtual sensor - go through bases */
897 for (i = 0; i < sensor[s].base_count; i++)
898 arbitrate_bases(sensor[s].base[i]);
904 int sensor_activate (int s, int enabled, int from_virtual)
906 char device_name[PATH_MAX];
907 struct epoll_event ev = {0};
910 int dev_num = sensor[s].dev_num;
911 int is_poll_sensor = !sensor[s].num_channels;
913 if (sensor[s].is_virtual) {
914 sensor_activate_virtual(s, enabled, from_virtual);
919 /* Prepare the report timestamp field for the first event, see set_report_ts method */
920 sensor[s].report_ts = 0;
921 ret = adjust_counters(s, enabled, from_virtual);
923 /* If the operation was neutral in terms of state, we're done */
929 sensor[s].event_count = 0;
930 sensor[s].meta_data_pending = 0;
932 if (enabled && (sensor[s].quirks & QUIRK_NOISY))
933 /* Initialize filtering data if required */
934 setup_noise_filtering(s);
936 if (!is_poll_sensor) {
939 enable_buffer(dev_num, 0);
940 setup_trigger(s, "\n");
942 /* If there's at least one sensor enabled on this iio device */
943 if (trig_sensors_per_dev[dev_num]) {
946 setup_trigger(s, sensor[s].init_trigger_name);
947 enable_buffer(dev_num, 1);
952 * Make sure we have a fd on the character device ; conversely, close
953 * the fd if no one is using associated sensors anymore. The assumption
954 * here is that the underlying driver will power on the relevant
955 * hardware block while someone holds a fd on the device.
957 dev_fd = device_fd[dev_num];
961 stop_acquisition_thread(s);
963 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
964 !trig_sensors_per_dev[dev_num]) {
966 * Stop watching this fd. This should be a no-op
967 * in case this fd was not in the poll set.
969 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
972 device_fd[dev_num] = -1;
975 /* Release any filtering data we may have accumulated */
976 release_noise_filtering_data(s);
982 /* First enabled sensor on this iio device */
983 sprintf(device_name, DEV_FILE_PATH, dev_num);
984 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
986 device_fd[dev_num] = dev_fd;
989 ALOGE("Could not open fd on %s (%s)\n",
990 device_name, strerror(errno));
991 adjust_counters(s, 0, from_virtual);
995 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
997 if (!is_poll_sensor) {
999 /* Add this iio device fd to the set of watched fds */
1000 ev.events = EPOLLIN;
1001 ev.data.u32 = dev_num;
1003 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
1006 ALOGE( "Failed adding %d to poll set (%s)\n",
1007 dev_fd, strerror(errno));
1011 /* Note: poll-mode fds are not readable */
1015 /* Ensure that on-change sensors send at least one event after enable */
1016 sensor[s].prev_val = -1;
1019 start_acquisition_thread(s);
1025 static void enable_motion_trigger (int dev_num)
1028 * In the ideal case, we enumerate two triggers per iio device ; the
1029 * default (periodically firing) trigger, and another one (the motion
1030 * trigger) that only fires up when motion is detected. This second one
1031 * allows for lesser energy consumption, but requires periodic sample
1032 * duplication at the HAL level for sensors that Android defines as
1033 * continuous. This "duplicate last sample" logic can only be engaged
1034 * once we got a first sample for the driver, so we start with the
1035 * default trigger when an iio device is first opened, then adjust the
1036 * trigger when we got events for all active sensors. Unfortunately in
1037 * the general case several sensors can be associated to a given iio
1038 * device, they can independently be controlled, and we have to adjust
1039 * the trigger in use at the iio device level depending on whether or
1040 * not appropriate conditions are met at the sensor level.
1045 int active_sensors = trig_sensors_per_dev[dev_num];
1046 int candidate[MAX_SENSORS];
1047 int candidate_count = 0;
1049 if (!active_sensors)
1052 /* Check that all active sensors are ready to switch */
1054 for (s=0; s<MAX_SENSORS; s++)
1055 if (sensor[s].dev_num == dev_num &&
1057 sensor[s].num_channels &&
1058 (!sensor[s].motion_trigger_name[0] ||
1059 !sensor[s].report_initialized ||
1060 is_fast_accelerometer(s) ||
1061 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS))
1065 /* Record which particular sensors need to switch */
1067 for (s=0; s<MAX_SENSORS; s++)
1068 if (sensor[s].dev_num == dev_num &&
1070 sensor[s].num_channels &&
1071 sensor[s].selected_trigger !=
1072 sensor[s].motion_trigger_name)
1073 candidate[candidate_count++] = s;
1075 if (!candidate_count)
1078 /* Now engage the motion trigger for sensors which aren't using it */
1080 enable_buffer(dev_num, 0);
1082 for (i=0; i<candidate_count; i++) {
1084 setup_trigger(s, sensor[s].motion_trigger_name);
1087 enable_buffer(dev_num, 1);
1092 * CTS acceptable thresholds:
1093 * EventGapVerification.java: (th <= 1.8)
1094 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
1096 #define THRESHOLD 1.10
1097 #define MAX_DELAY 500000000 /* 500 ms */
1099 void set_report_ts(int s, int64_t ts)
1101 int64_t maxTs, period;
1104 * A bit of a hack to please a bunch of cts tests. They
1105 * expect the timestamp to be exacly according to the set-up
1106 * frequency but if we're simply getting the timestamp at hal level
1107 * this may not be the case. Perhaps we'll get rid of this when
1108 * we'll be reading the timestamp from the iio channel for all sensors
1110 if (sensor[s].report_ts && sensor[s].sampling_rate &&
1111 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
1113 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
1114 maxTs = sensor[s].report_ts + THRESHOLD * period;
1115 /* If we're too far behind get back on track */
1116 if (ts - maxTs >= MAX_DELAY)
1118 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
1120 sensor[s].report_ts = ts;
1125 static void stamp_reports (int dev_num, int64_t ts)
1129 for (s=0; s<MAX_SENSORS; s++)
1130 if (sensor[s].dev_num == dev_num &&
1132 set_report_ts(s, ts);
1136 static int integrate_device_report (int dev_num)
1140 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1142 unsigned char *target;
1143 unsigned char *source;
1146 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1147 int64_t boot_to_rt_delta;
1149 /* There's an incoming report on the specified iio device char dev fd */
1151 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1152 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1156 if (device_fd[dev_num] == -1) {
1157 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1161 len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]);
1164 ALOGE("Could not read report from iio device %d (%s)\n",
1165 dev_num, strerror(errno));
1169 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1171 /* Map device report to sensor reports */
1173 for (s=0; s<MAX_SENSORS; s++)
1174 if (sensor[s].dev_num == dev_num &&
1179 /* Copy data from device to sensor report buffer */
1180 for (c=0; c<sensor[s].num_channels; c++) {
1182 target = sensor[s].report_buffer +
1185 source = buf + sensor[s].channel[c].offset;
1187 size = sensor[s].channel[c].size;
1189 memcpy(target, source, size);
1194 ALOGV("Sensor %d report available (%d bytes)\n", s,
1197 sensor[s].report_pending = DATA_TRIGGER;
1198 sensor[s].report_initialized = 1;
1200 ts_offset += sr_offset;
1203 /* Tentatively switch to an any-motion trigger if conditions are met */
1204 enable_motion_trigger(dev_num);
1206 /* If no iio timestamp channel was detected for this device, bail out */
1207 if (!has_iio_ts[dev_num]) {
1208 stamp_reports(dev_num, get_timestamp_boot());
1212 /* Don't trust the timestamp channel in any-motion mode */
1213 for (s=0; s<MAX_SENSORS; s++)
1214 if (sensor[s].dev_num == dev_num &&
1216 sensor[s].selected_trigger ==
1217 sensor[s].motion_trigger_name) {
1218 stamp_reports(dev_num, get_timestamp_boot());
1222 /* Align on a 64 bits boundary */
1223 ts_offset = (ts_offset + 7)/8*8;
1225 /* If we read an amount of data consistent with timestamp presence */
1226 if (len == expected_dev_report_size[dev_num])
1227 ts = *(int64_t*) (buf + ts_offset);
1230 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1231 stamp_reports(dev_num, get_timestamp_boot());
1235 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1237 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1239 stamp_reports(dev_num, ts + boot_to_rt_delta);
1245 static int propagate_vsensor_report (int s, struct sensors_event_t *data)
1247 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1249 memcpy(data, &sensor[s].sample, sizeof(struct sensors_event_t));
1252 data->type = sensor[s].type;
1257 static int propagate_sensor_report (int s, struct sensors_event_t *data)
1259 /* There's a sensor report pending for this sensor ; transmit it */
1261 int num_fields = get_field_count(s);
1263 unsigned char* current_sample;
1265 /* If there's nothing to return... we're done */
1269 memset(data, 0, sizeof(sensors_event_t));
1271 data->version = sizeof(sensors_event_t);
1273 data->type = sensor[s].type;
1274 data->timestamp = sensor[s].report_ts;
1276 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1278 current_sample = sensor[s].report_buffer;
1280 /* If this is a poll sensor */
1281 if (!sensor[s].num_channels) {
1282 /* Use the data provided by the acquisition thread */
1283 ALOGV("Reporting data from worker thread for S%d\n", s);
1284 memcpy(data->data, current_sample, num_fields * sizeof(float));
1288 /* Convert the data into the expected Android-level format */
1289 for (c=0; c<num_fields; c++) {
1291 data->data[c] = sensor[s].ops.transform
1292 (s, c, current_sample);
1294 ALOGV("\tfield %d: %f\n", c, data->data[c]);
1295 current_sample += sensor[s].channel[c].size;
1299 * The finalize routine, in addition to its late sample processing duty,
1300 * has the final say on whether or not the sample gets sent to Android.
1302 return sensor[s].ops.finalize(s, data);
1306 static void synthetize_duplicate_samples (void)
1309 * Some sensor types (ex: gyroscope) are defined as continuously firing
1310 * by Android, despite the fact that we can be dealing with iio drivers
1311 * that only report events for new samples. For these we generate
1312 * reports periodically, duplicating the last data we got from the
1313 * driver. This is not necessary for polling sensors.
1321 for (s=0; s<sensor_count; s++) {
1323 /* Ignore disabled sensors */
1327 /* If the sensor is continuously firing, leave it alone */
1328 if (sensor[s].selected_trigger !=
1329 sensor[s].motion_trigger_name)
1332 /* If we haven't seen a sample, there's nothing to duplicate */
1333 if (!sensor[s].report_initialized)
1336 /* If a sample was recently buffered, leave it alone too */
1337 if (sensor[s].report_pending)
1340 /* We also need a valid sampling rate to be configured */
1341 if (!sensor[s].sampling_rate)
1344 period = (int64_t) (1000000000.0/ sensor[s].sampling_rate);
1346 current_ts = get_timestamp_boot();
1347 target_ts = sensor[s].report_ts + period;
1349 if (target_ts <= current_ts) {
1350 /* Mark the sensor for event generation */
1351 set_report_ts(s, current_ts);
1352 sensor[s].report_pending = DATA_DUPLICATE;
1358 static void integrate_thread_report (uint32_t tag)
1360 int s = tag - THREAD_REPORT_TAG_BASE;
1364 unsigned char current_sample[MAX_SENSOR_REPORT_SIZE];
1366 expected_len = sizeof(int64_t) + get_field_count(s) * sizeof(float);
1368 len = read(sensor[s].thread_data_fd[0],
1372 memcpy(×tamp, current_sample, sizeof(int64_t));
1373 memcpy(sensor[s].report_buffer, sizeof(int64_t) + current_sample,
1374 expected_len - sizeof(int64_t));
1376 if (len == expected_len) {
1377 set_report_ts(s, timestamp);
1378 sensor[s].report_pending = DATA_SYSFS;
1383 static int get_poll_wait_timeout (void)
1386 * Compute an appropriate timeout value, in ms, for the epoll_wait
1387 * call that's going to await for iio device reports and incoming
1388 * reports from our sensor sysfs data reader threads.
1392 int64_t target_ts = INT64_MAX;
1397 * Check if we're dealing with a driver that only send events when
1398 * there is motion, despite the fact that the associated Android sensor
1399 * type is continuous rather than on-change. In that case we have to
1400 * duplicate events. Check deadline for the nearest upcoming event.
1402 for (s=0; s<sensor_count; s++)
1403 if (is_enabled(s) &&
1404 sensor[s].selected_trigger ==
1405 sensor[s].motion_trigger_name &&
1406 sensor[s].sampling_rate) {
1407 period = (int64_t) (1000000000.0 /
1408 sensor[s].sampling_rate);
1410 if (sensor[s].report_ts + period < target_ts)
1411 target_ts = sensor[s].report_ts + period;
1414 /* If we don't have such a driver to deal with */
1415 if (target_ts == INT64_MAX)
1416 return -1; /* Infinite wait */
1418 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1420 /* If the target timestamp is already behind us, don't wait */
1428 int sensor_poll (struct sensors_event_t* data, int count)
1433 struct epoll_event ev[MAX_DEVICES];
1434 int returned_events;
1438 /* Get one or more events from our collection of sensors */
1439 return_available_sensor_reports:
1441 /* Synthetize duplicate samples if needed */
1442 synthetize_duplicate_samples();
1444 returned_events = 0;
1445 /* Check our sensor collection for available reports */
1446 for (s=0; s<sensor_count && returned_events < count; s++) {
1447 if (sensor[s].report_pending) {
1450 if (sensor[s].is_virtual)
1451 event_count = propagate_vsensor_report(s, &data[returned_events]);
1453 /* Report this event if it looks OK */
1454 event_count = propagate_sensor_report(s, &data[returned_events]);
1458 sensor[s].report_pending = 0;
1459 returned_events += event_count;
1461 * If the sample was deemed invalid or unreportable,
1462 * e.g. had the same value as the previously reported
1463 * value for a 'on change' sensor, silently drop it.
1466 while (sensor[s].meta_data_pending) {
1467 /* See sensors.h on these */
1468 data[returned_events].version = META_DATA_VERSION;
1469 data[returned_events].sensor = 0;
1470 data[returned_events].type = SENSOR_TYPE_META_DATA;
1471 data[returned_events].reserved0 = 0;
1472 data[returned_events].timestamp = 0;
1473 data[returned_events].meta_data.sensor = s;
1474 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1476 sensor[s].meta_data_pending--;
1479 if (returned_events)
1480 return returned_events;
1484 ALOGV("Awaiting sensor data\n");
1486 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1489 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1493 ALOGV("%d fds signalled\n", nfds);
1495 /* For each of the signalled sources */
1496 for (i=0; i<nfds; i++)
1497 if (ev[i].events == EPOLLIN)
1498 switch (ev[i].data.u32) {
1499 case 0 ... MAX_DEVICES-1:
1500 /* Read report from iio char dev fd */
1501 integrate_device_report(ev[i].data.u32);
1504 case THREAD_REPORT_TAG_BASE ...
1505 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1506 /* Get report from acquisition thread */
1507 integrate_thread_report(ev[i].data.u32);
1511 ALOGW("Unexpected event source!\n");
1515 goto return_available_sensor_reports;
1519 int sensor_set_delay (int s, int64_t ns)
1521 float new_sampling_rate; /* Granted sampling rate after arbitration */
1524 ALOGE("Rejecting non-positive delay request on sensor %d,required delay: %lld\n", s, ns);
1528 new_sampling_rate = 1000000000LL/ns;
1530 ALOGV("Entering set delay S%d (%s): old rate(%f), new rate(%f)\n",
1531 s, sensor[s].friendly_name, sensor[s].sampling_rate,
1534 sensor[s].requested_rate = new_sampling_rate;
1536 return arbitrate_delays(s);
1540 int sensor_flush (int s)
1542 /* If one shot or not enabled return -EINVAL */
1543 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1546 sensor[s].meta_data_pending++;
1551 int allocate_control_data (void)
1555 for (i=0; i<MAX_DEVICES; i++)
1558 poll_fd = epoll_create(MAX_DEVICES);
1560 if (poll_fd == -1) {
1561 ALOGE("Can't create epoll instance for iio sensors!\n");
1569 void delete_control_data (void)