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
42 * - a iio device number if the fd is a iio character device fd
43 * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a
44 * pipe used by a sysfs data acquisition thread
46 #define THREAD_REPORT_TAG_BASE 0x00010000
48 #define ENABLE_BUFFER_RETRIES 10
49 #define ENABLE_BUFFER_RETRY_DELAY_MS 10
52 inline int is_enabled (int s)
54 return sensor[s].directly_enabled || sensor[s].ref_count;
58 static int check_state_change (int s, int enabled, int from_virtual)
61 if (sensor[s].directly_enabled)
63 * We're being enabled but already were
64 * directly activated: no change.
69 /* We're being directly enabled */
70 sensor[s].directly_enabled = 1;
72 if (sensor[s].ref_count)
73 /* We were already indirectly enabled */
76 return 1; /* Do continue enabling this sensor */
80 /* We are being disabled but already were: no change */
83 if (from_virtual && sensor[s].directly_enabled)
84 /* We're indirectly disabled but the base is still active */
87 /* If it's disable, and it's from Android, and we still have ref counts */
88 if (!from_virtual && sensor[s].ref_count) {
89 sensor[s].directly_enabled = 0;
93 /*If perhaps we are from virtual but we're disabling it*/
94 sensor[s].directly_enabled = 0;
96 return 1; /* Do continue disabling this sensor */
100 static int enable_buffer(int dev_num, int enabled)
102 char sysfs_path[PATH_MAX];
103 int ret, retries, millisec;
104 struct timespec req = {0};
106 retries = ENABLE_BUFFER_RETRIES;
107 millisec = ENABLE_BUFFER_RETRY_DELAY_MS;
109 req.tv_nsec = millisec * 1000000L;
111 sprintf(sysfs_path, ENABLE_PATH, dev_num);
114 /* Low level, non-multiplexed, enable/disable routine */
115 ret = sysfs_write_int(sysfs_path, enabled);
119 ALOGE("Failed enabling buffer, retrying");
120 nanosleep(&req, (struct timespec *)NULL);
124 ALOGE("Could not enable buffer\n");
132 static int setup_trigger (int s, const char* trigger_val)
134 char sysfs_path[PATH_MAX];
135 int ret = -1, attempts = 5;
137 sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
139 if (trigger_val[0] != '\n')
140 ALOGI("Setting S%d (%s) trigger to %s\n", s,
141 sensor[s].friendly_name, trigger_val);
143 while (ret == -1 && attempts) {
144 ret = sysfs_write_str(sysfs_path, trigger_val);
149 sensor[s].selected_trigger = trigger_val;
151 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s,
152 sensor[s].friendly_name, trigger_val);
157 static void enable_iio_timestamp (int dev_num, int known_channels)
159 /* Check if we have a dedicated iio timestamp channel */
161 char spec_buf[MAX_TYPE_SPEC_LEN];
162 char sysfs_path[PATH_MAX];
165 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
167 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
172 if (strcmp(spec_buf, "le:s64/64>>0"))
175 /* OK, type is int64_t as expected, in little endian representation */
177 sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
179 if (sysfs_read_int(sysfs_path, &n))
182 /* Check that the timestamp comes after the other fields we read */
183 if (n != known_channels)
186 /* Try enabling that channel */
187 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
189 sysfs_write_int(sysfs_path, 1);
191 if (sysfs_read_int(sysfs_path, &n))
195 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
196 has_iio_ts[dev_num] = 1;
201 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN],
202 struct datum_info_t *type_info)
204 /* Return size in bytes for this type specification, or -1 in error */
207 unsigned int realbits, storagebits, shift;
210 /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
212 tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u",
213 &endianness, &sign, &realbits, &storagebits, &shift);
216 (endianness != 'b' && endianness != 'l') ||
217 (sign != 'u' && sign != 's') ||
218 realbits > storagebits ||
219 (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
220 ALOGE("Invalid iio channel type spec: %s\n", type_buf);
224 type_info->endianness = endianness;
225 type_info->sign = sign;
226 type_info->realbits = (short) realbits;
227 type_info->storagebits = (short) storagebits;
228 type_info->shift = (short) shift;
230 return storagebits / 8;
234 void build_sensor_report_maps (int dev_num)
237 * Read sysfs files from a iio device's scan_element directory, and
238 * build a couple of tables from that data. These tables will tell, for
239 * each sensor, where to gather relevant data in a device report, i.e.
240 * the structure that we read from the /dev/iio:deviceX file in order to
241 * sensor report, itself being the data that we return to Android when a
242 * sensor poll completes. The mapping should be straightforward in the
243 * case where we have a single sensor active per iio device but, this is
244 * not the general case. In general several sensors can be handled
245 * through a single iio device, and the _en, _index and _type syfs
246 * entries all concur to paint a picture of what the structure of the
256 char spec_buf[MAX_TYPE_SPEC_LEN];
257 struct datum_info_t* ch_info;
259 char sysfs_path[PATH_MAX];
262 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
263 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
264 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
268 /* For each sensor that is linked to this device */
269 for (s=0; s<sensor_count; s++) {
270 if (sensor[s].dev_num != dev_num)
273 i = sensor[s].catalog_index;
275 /* Read channel details through sysfs attributes */
276 for (c=0; c<sensor[s].num_channels; c++) {
278 /* Read _type file */
279 sprintf(sysfs_path, CHANNEL_PATH "%s",
281 sensor_catalog[i].channel[c].type_path);
283 n = sysfs_read_str(sysfs_path, spec_buf,
287 ALOGW( "Failed to read type: %s\n",
292 ch_spec = sensor[s].channel[c].type_spec;
294 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
296 ch_info = &sensor[s].channel[c].type_info;
298 size = decode_type_spec(ch_spec, ch_info);
300 /* Read _index file */
301 sprintf(sysfs_path, CHANNEL_PATH "%s",
303 sensor_catalog[i].channel[c].index_path);
305 n = sysfs_read_int(sysfs_path, &ch_index);
308 ALOGW( "Failed to read index: %s\n",
313 if (ch_index >= MAX_SENSORS) {
314 ALOGE("Index out of bounds!: %s\n", sysfs_path);
318 /* Record what this index is about */
320 sensor_handle_from_index [ch_index] = s;
321 channel_number_from_index[ch_index] = c;
322 channel_size_from_index [ch_index] = size;
327 /* Stop sampling - if we are recovering from hal restart */
328 enable_buffer(dev_num, 0);
329 setup_trigger(s, "\n");
331 /* Turn on channels we're aware of */
332 for (c=0;c<sensor[s].num_channels; c++) {
333 sprintf(sysfs_path, CHANNEL_PATH "%s",
335 sensor_catalog[i].channel[c].en_path);
336 sysfs_write_int(sysfs_path, 1);
340 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
343 * Now that we know which channels are defined, their sizes and their
344 * ordering, update channels offsets within device report. Note: there
345 * is a possibility that several sensors share the same index, with
346 * their data fields being isolated by masking and shifting as specified
347 * through the real bits and shift values in type attributes. This case
348 * is not currently supported. Also, the code below assumes no hole in
349 * the sequence of indices, so it is dependent on discovery of all
353 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
354 s = sensor_handle_from_index[i];
355 c = channel_number_from_index[i];
356 size = channel_size_from_index[i];
361 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
362 s, c, offset, size, sensor[s].channel[c].type_spec);
364 sensor[s].channel[c].offset = offset;
365 sensor[s].channel[c].size = size;
370 /* Enable the timestamp channel if there is one available */
371 enable_iio_timestamp(dev_num, known_channels);
373 /* Add padding and timestamp size if it's enabled on this iio device */
374 if (has_iio_ts[dev_num])
375 offset = (offset+7)/8*8 + sizeof(int64_t);
377 expected_dev_report_size[dev_num] = offset;
378 ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
380 if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
381 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n",
382 dev_num, expected_dev_report_size[dev_num]);
384 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
389 int adjust_counters (int s, int enabled, int from_virtual)
392 * Adjust counters based on sensor enable action. Return values are:
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))
400 /* The state of the sensor remains the same: we're done */
404 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
405 s, dev_num, sensor[s].friendly_name);
407 switch (sensor[s].type) {
408 case SENSOR_TYPE_MAGNETIC_FIELD:
409 compass_read_data(&sensor[s]);
412 case SENSOR_TYPE_GYROSCOPE:
413 gyro_cal_init(&sensor[s]);
417 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
418 sensor[s].friendly_name);
420 /* Sensor disabled, lower report available flag */
421 sensor[s].report_pending = 0;
423 if (sensor[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
424 compass_store_data(&sensor[s]);
426 if (sensor[s].type == SENSOR_TYPE_GYROSCOPE)
427 gyro_store_data(&sensor[s]);
430 /* We changed the state of a sensor: adjust device ref counts */
432 if (sensor[s].num_channels) {
435 trig_sensors_per_dev[dev_num]++;
437 trig_sensors_per_dev[dev_num]--;
443 active_poll_sensors++;
444 poll_sensors_per_dev[dev_num]++;
448 active_poll_sensors--;
449 poll_sensors_per_dev[dev_num]--;
454 static int get_field_count (int s)
456 switch (sensor[s].type) {
457 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
458 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
459 case SENSOR_TYPE_ORIENTATION: /* degrees */
460 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
461 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
464 case SENSOR_TYPE_LIGHT: /* SI lux units */
465 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
466 case SENSOR_TYPE_TEMPERATURE: /* °C */
467 case SENSOR_TYPE_PROXIMITY: /* centimeters */
468 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
469 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
472 case SENSOR_TYPE_ROTATION_VECTOR:
476 ALOGE("Unknown sensor type!\n");
477 return 0; /* Drop sample */
482 static void* acquisition_routine (void* param)
485 * Data acquisition routine run in a dedicated thread, covering a single
486 * sensor. This loop will periodically retrieve sampling data through
487 * sysfs, then package it as a sample and transfer it to our master poll
488 * loop through a report fd. Checks for a cancellation signal quite
489 * frequently, as the thread may be disposed of at any time. Note that
490 * Bionic does not provide pthread_cancel / pthread_testcancel...
493 int s = (int) (size_t) param;
494 int num_fields, sample_size;
495 struct sensors_event_t data = {0};
498 struct timespec target_time;
499 int64_t timestamp, period, start, stop;
501 if (s < 0 || s >= sensor_count) {
502 ALOGE("Invalid sensor handle!\n");
506 ALOGI("Entering data acquisition thread S%d (%s), rate:%g\n",
507 s, sensor[s].friendly_name, sensor[s].sampling_rate);
509 if (sensor[s].sampling_rate <= 0) {
510 ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n",
511 s, sensor[s].sampling_rate);
515 num_fields = get_field_count(s);
516 sample_size = sizeof(int64_t) + num_fields * sizeof(float);
519 * Each condition variable is associated to a mutex that has to be
520 * locked by the thread that's waiting on it. We use these condition
521 * variables to get the acquisition threads out of sleep quickly after
522 * the sampling rate is adjusted, or the sensor is disabled.
524 pthread_mutex_lock(&thread_release_mutex[s]);
526 /* Pinpoint the moment we start sampling */
527 timestamp = get_timestamp_monotonic();
529 /* Check and honor termination requests */
530 while (sensor[s].thread_data_fd[1] != -1) {
531 start = get_timestamp_boot();
532 /* Read values through sysfs */
533 for (c=0; c<num_fields; c++) {
534 data.data[c] = acquire_immediate_value(s, c);
535 /* Check and honor termination requests */
536 if (sensor[s].thread_data_fd[1] == -1)
539 stop = get_timestamp_boot();
540 data.timestamp = start/2 + stop/2;
542 /* If the sample looks good */
543 if (sensor[s].ops.finalize(s, &data)) {
545 /* Pipe it for transmission to poll loop */
546 ret = write( sensor[s].thread_data_fd[1],
547 &data.timestamp, sample_size);
549 if (ret != sample_size)
550 ALOGE("S%d write failure: wrote %d, got %d\n",
551 s, sample_size, ret);
554 /* Check and honor termination requests */
555 if (sensor[s].thread_data_fd[1] == -1)
558 /* Recalculate period asumming sensor[s].sampling_rate
559 * can be changed dynamically during the thread run */
560 if (sensor[s].sampling_rate <= 0) {
561 ALOGE("Unexpected sampling rate for sensor %d: %g\n",
562 s, sensor[s].sampling_rate);
566 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
568 set_timestamp(&target_time, timestamp);
571 * Wait until the sampling time elapses, or a rate change is
572 * signaled, or a thread exit is requested.
574 ret = pthread_cond_timedwait( &thread_release_cond[s],
575 &thread_release_mutex[s],
580 ALOGV("Acquisition thread for S%d exiting\n", s);
581 pthread_mutex_unlock(&thread_release_mutex[s]);
587 static void start_acquisition_thread (int s)
589 int incoming_data_fd;
592 struct epoll_event ev = {0};
594 ALOGV("Initializing acquisition context for sensor %d\n", s);
596 /* Create condition variable and mutex for quick thread release */
597 ret = pthread_condattr_init(&thread_cond_attr[s]);
598 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
599 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
600 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
602 /* Create a pipe for inter thread communication */
603 ret = pipe(sensor[s].thread_data_fd);
605 incoming_data_fd = sensor[s].thread_data_fd[0];
608 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
610 /* Add incoming side of pipe to our poll set, with a suitable tag */
611 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
613 /* Create and start worker thread */
614 ret = pthread_create( &sensor[s].acquisition_thread,
621 static void stop_acquisition_thread (int s)
623 int incoming_data_fd = sensor[s].thread_data_fd[0];
624 int outgoing_data_fd = sensor[s].thread_data_fd[1];
626 ALOGV("Tearing down acquisition context for sensor %d\n", s);
628 /* Delete the incoming side of the pipe from our poll set */
629 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
631 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
632 sensor[s].thread_data_fd[0] = -1;
633 sensor[s].thread_data_fd[1] = -1;
635 /* Close both sides of our pipe */
636 close(incoming_data_fd);
637 close(outgoing_data_fd);
639 /* Stop acquisition thread and clean up thread handle */
640 pthread_cond_signal(&thread_release_cond[s]);
641 pthread_join(sensor[s].acquisition_thread, NULL);
643 /* Clean up our sensor descriptor */
644 sensor[s].acquisition_thread = -1;
646 /* Delete condition variable and mutex */
647 pthread_cond_destroy(&thread_release_cond[s]);
648 pthread_mutex_destroy(&thread_release_mutex[s]);
652 static void sensor_activate_virtual (int s, int enabled, int from_virtual)
656 sensor[s].event_count = 0;
657 sensor[s].meta_data_pending = 0;
659 if (!check_state_change(s, enabled, from_virtual))
662 /* Enable all the base sensors for this virtual one */
663 for (i = 0; i < sensor[s].base_count; i++) {
664 base = sensor[s].base[i];
665 sensor_activate(base, enabled, 1);
666 sensor[base].ref_count++;
671 /* Sensor disabled, lower report available flag */
672 sensor[s].report_pending = 0;
674 for (i = 0; i < sensor[s].base_count; i++) {
675 base = sensor[s].base[i];
676 sensor_activate(base, enabled, 1);
677 sensor[base].ref_count--;
683 static int is_fast_accelerometer (int s)
686 * Some games don't react well to accelerometers using any-motion
687 * triggers. Even very low thresholds seem to trip them, and they tend
688 * to request fairly high event rates. Favor continuous triggers if the
689 * sensor is an accelerometer and uses a sampling rate of at least 25.
692 if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
695 if (sensor[s].sampling_rate < 25)
702 static void tentative_switch_trigger (int s)
705 * Under certain situations it may be beneficial to use an alternate
708 * - for applications using the accelerometer with high sampling rates,
709 * prefer the continuous trigger over the any-motion one, to avoid
710 * jumps related to motion thresholds
713 if (is_fast_accelerometer(s) &&
714 !(sensor[s].quirks & QUIRK_TERSE_DRIVER) &&
715 sensor[s].selected_trigger ==
716 sensor[s].motion_trigger_name)
717 setup_trigger(s, sensor[s].init_trigger_name);
721 static int setup_delay_sysfs (int s, float requested_rate)
723 /* 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 int dev_num = sensor[s].dev_num;
729 int i = sensor[s].catalog_index;
730 const char *prefix = sensor_catalog[i].tag;
731 int per_sensor_sampling_rate;
732 int per_device_sampling_rate;
733 int32_t min_delay_us = sensor_desc[s].minDelay;
734 max_delay_t max_delay_us = sensor_desc[s].maxDelay;
735 float min_supported_rate = max_delay_us ? 1000000.0/max_delay_us : 1;
736 float max_supported_rate =
737 min_delay_us && min_delay_us != -1 ? 1000000.0/min_delay_us : 0;
742 float cur_sampling_rate; /* Currently used sampling rate */
743 float arb_sampling_rate; /* Granted sampling rate after arbitration */
745 ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate,
746 s, sensor[s].friendly_name);
748 sensor[s].requested_rate = requested_rate;
750 arb_sampling_rate = requested_rate;
752 if (arb_sampling_rate < min_supported_rate) {
753 ALOGV("Sampling rate %g too low for %s, using %g instead\n",
754 arb_sampling_rate, sensor[s].friendly_name,
757 arb_sampling_rate = min_supported_rate;
760 if (max_supported_rate && arb_sampling_rate > max_supported_rate) {
761 ALOGV("Sampling rate %g too high for %s, using %g instead\n",
762 arb_sampling_rate, sensor[s].friendly_name, max_supported_rate);
763 arb_sampling_rate = max_supported_rate;
766 sensor[s].sampling_rate = arb_sampling_rate;
768 /* If we're dealing with a poll-mode sensor */
769 if (!sensor[s].num_channels) {
771 /* Wake up thread so the new sampling rate gets used */
772 pthread_cond_signal(&thread_release_cond[s]);
776 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
778 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
779 per_sensor_sampling_rate = 1;
780 per_device_sampling_rate = 0;
782 per_sensor_sampling_rate = 0;
784 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
786 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
787 per_device_sampling_rate = 1;
789 per_device_sampling_rate = 0;
792 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
793 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
797 /* Check if we have contraints on allowed sampling rates */
799 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
801 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
804 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
806 /* While we're not at the end of the string */
807 while (*cursor && cursor[0]) {
809 /* Decode a single value */
810 sr = strtod(cursor, NULL);
813 * If this matches the selected rate, we're happy.
814 * Have some tolerance to counter rounding errors and
815 * avoid needless jumps to higher rates.
817 if (fabs(arb_sampling_rate - sr) <= 0.001) {
818 arb_sampling_rate = sr;
823 * If we reached a higher value than the desired rate,
824 * adjust selected rate so it matches the first higher
825 * available one and stop parsing - this makes the
826 * assumption that rates are sorted by increasing value
827 * in the allowed frequencies string.
829 if (sr > arb_sampling_rate) {
830 arb_sampling_rate = sr;
835 while (cursor[0] && !isspace(cursor[0]))
839 while (cursor[0] && isspace(cursor[0]))
844 if (max_supported_rate &&
845 arb_sampling_rate > max_supported_rate) {
846 arb_sampling_rate = max_supported_rate;
850 /* Coordinate with others active sensors on the same device, if any */
851 if (per_device_sampling_rate)
852 for (n=0; n<sensor_count; n++)
853 if (n != s && sensor[n].dev_num == dev_num &&
854 sensor[n].num_channels && is_enabled(n) &&
855 sensor[n].sampling_rate > arb_sampling_rate) {
856 ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n"
857 , sensor[s].friendly_name, sensor[n].friendly_name,
858 sensor[n].sampling_rate, arb_sampling_rate);
859 arb_sampling_rate = sensor[n].sampling_rate;
862 sensor[s].sampling_rate = arb_sampling_rate;
865 * Update actual sampling rate field for this sensor and others which
866 * may be sharing the same sampling rate.
868 if (per_device_sampling_rate)
869 for (n=0; n<sensor_count; n++)
870 if (sensor[n].dev_num == dev_num && n != s &&
871 sensor[n].num_channels)
872 sensor[n].sampling_rate = arb_sampling_rate;
874 /* If the desired rate is already active we're all set */
875 if (arb_sampling_rate == cur_sampling_rate)
878 ALOGI("Sensor %d (%s) sampling rate set to %g\n",
879 s, sensor[s].friendly_name, arb_sampling_rate);
881 if (trig_sensors_per_dev[dev_num])
882 enable_buffer(dev_num, 0);
884 sysfs_write_float(sysfs_path, arb_sampling_rate);
886 /* Check if it makes sense to use an alternate trigger */
887 tentative_switch_trigger(s);
889 if (trig_sensors_per_dev[dev_num])
890 enable_buffer(dev_num, 1);
897 * We go through all the virtual sensors of the base - and the base itself
898 * in order to recompute the maximum requested delay of the group and setup the base
899 * at that specific delay.
901 static int arbitrate_bases (int s)
905 float arbitrated_rate = 0;
907 if (sensor[s].directly_enabled)
908 arbitrated_rate = sensor[s].requested_rate;
910 for (i = 0; i < sensor_count; i++) {
911 for (vidx = 0; vidx < sensor[i].base_count; vidx++)
912 /* If we have a virtual sensor depending on this one - handle it */
913 if (sensor[i].base[vidx] == s &&
914 sensor[i].directly_enabled &&
915 sensor[i].requested_rate > arbitrated_rate)
916 arbitrated_rate = sensor[i].requested_rate;
919 return setup_delay_sysfs(s, arbitrated_rate);
924 * Re-assesment for delays. We need to re-asses delays for all related groups
925 * of sensors everytime a sensor enables / disables / changes frequency.
927 int arbitrate_delays (int s)
931 if (!sensor[s].is_virtual) {
932 return arbitrate_bases(s);
934 /* Is virtual sensor - go through bases */
935 for (i = 0; i < sensor[s].base_count; i++)
936 arbitrate_bases(sensor[s].base[i]);
942 int sensor_activate (int s, int enabled, int from_virtual)
944 char device_name[PATH_MAX];
945 struct epoll_event ev = {0};
948 int dev_num = sensor[s].dev_num;
949 int is_poll_sensor = !sensor[s].num_channels;
951 if (sensor[s].is_virtual) {
952 sensor_activate_virtual(s, enabled, from_virtual);
957 /* Prepare the report timestamp field for the first event, see set_report_ts method */
958 sensor[s].report_ts = 0;
960 ret = adjust_counters(s, enabled, from_virtual);
962 /* If the operation was neutral in terms of state, we're done */
968 sensor[s].event_count = 0;
969 sensor[s].meta_data_pending = 0;
971 if (enabled && (sensor[s].quirks & QUIRK_NOISY))
972 /* Initialize filtering data if required */
973 setup_noise_filtering(s);
975 if (!is_poll_sensor) {
978 enable_buffer(dev_num, 0);
979 setup_trigger(s, "\n");
981 /* If there's at least one sensor enabled on this iio device */
982 if (trig_sensors_per_dev[dev_num]) {
985 setup_trigger(s, sensor[s].init_trigger_name);
986 enable_buffer(dev_num, 1);
991 * Make sure we have a fd on the character device ; conversely, close
992 * the fd if no one is using associated sensors anymore. The assumption
993 * here is that the underlying driver will power on the relevant
994 * hardware block while someone holds a fd on the device.
996 dev_fd = device_fd[dev_num];
1000 stop_acquisition_thread(s);
1002 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
1003 !trig_sensors_per_dev[dev_num]) {
1005 * Stop watching this fd. This should be a no-op
1006 * in case this fd was not in the poll set.
1008 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
1011 device_fd[dev_num] = -1;
1014 /* Release any filtering data we may have accumulated */
1015 release_noise_filtering_data(s);
1021 /* First enabled sensor on this iio device */
1022 sprintf(device_name, DEV_FILE_PATH, dev_num);
1023 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
1025 device_fd[dev_num] = dev_fd;
1028 ALOGE("Could not open fd on %s (%s)\n",
1029 device_name, strerror(errno));
1030 adjust_counters(s, 0, from_virtual);
1034 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
1036 if (!is_poll_sensor) {
1038 /* Add this iio device fd to the set of watched fds */
1039 ev.events = EPOLLIN;
1040 ev.data.u32 = dev_num;
1042 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
1045 ALOGE( "Failed adding %d to poll set (%s)\n",
1046 dev_fd, strerror(errno));
1050 /* Note: poll-mode fds are not readable */
1054 /* Ensure that on-change sensors send at least one event after enable */
1055 sensor[s].prev_val = -1;
1058 start_acquisition_thread(s);
1064 static void enable_motion_trigger (int dev_num)
1067 * In the ideal case, we enumerate two triggers per iio device ; the
1068 * default (periodically firing) trigger, and another one (the motion
1069 * trigger) that only fires up when motion is detected. This second one
1070 * allows for lesser energy consumption, but requires periodic sample
1071 * duplication at the HAL level for sensors that Android defines as
1072 * continuous. This "duplicate last sample" logic can only be engaged
1073 * once we got a first sample for the driver, so we start with the
1074 * default trigger when an iio device is first opened, then adjust the
1075 * trigger when we got events for all active sensors. Unfortunately in
1076 * the general case several sensors can be associated to a given iio
1077 * device, they can independently be controlled, and we have to adjust
1078 * the trigger in use at the iio device level depending on whether or
1079 * not appropriate conditions are met at the sensor level.
1084 int active_sensors = trig_sensors_per_dev[dev_num];
1085 int candidate[MAX_SENSORS];
1086 int candidate_count = 0;
1088 if (!active_sensors)
1091 /* Check that all active sensors are ready to switch */
1093 for (s=0; s<MAX_SENSORS; s++)
1094 if (sensor[s].dev_num == dev_num &&
1096 sensor[s].num_channels &&
1097 (!sensor[s].motion_trigger_name[0] ||
1098 !sensor[s].report_initialized ||
1099 is_fast_accelerometer(s) ||
1100 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS))
1104 /* Record which particular sensors need to switch */
1106 for (s=0; s<MAX_SENSORS; s++)
1107 if (sensor[s].dev_num == dev_num &&
1109 sensor[s].num_channels &&
1110 sensor[s].selected_trigger !=
1111 sensor[s].motion_trigger_name)
1112 candidate[candidate_count++] = s;
1114 if (!candidate_count)
1117 /* Now engage the motion trigger for sensors which aren't using it */
1119 enable_buffer(dev_num, 0);
1121 for (i=0; i<candidate_count; i++) {
1123 setup_trigger(s, sensor[s].motion_trigger_name);
1126 enable_buffer(dev_num, 1);
1131 * CTS acceptable thresholds:
1132 * EventGapVerification.java: (th <= 1.8)
1133 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
1135 #define THRESHOLD 1.10
1136 #define MAX_DELAY 500000000 /* 500 ms */
1138 void set_report_ts(int s, int64_t ts)
1140 int64_t maxTs, period;
1143 * A bit of a hack to please a bunch of cts tests. They
1144 * expect the timestamp to be exacly according to the set-up
1145 * frequency but if we're simply getting the timestamp at hal level
1146 * this may not be the case. Perhaps we'll get rid of this when
1147 * we'll be reading the timestamp from the iio channel for all sensors
1149 if (sensor[s].report_ts && sensor[s].sampling_rate &&
1150 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
1152 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
1153 maxTs = sensor[s].report_ts + THRESHOLD * period;
1154 /* If we're too far behind get back on track */
1155 if (ts - maxTs >= MAX_DELAY)
1157 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
1159 sensor[s].report_ts = ts;
1164 static void stamp_reports (int dev_num, int64_t ts)
1168 for (s=0; s<MAX_SENSORS; s++)
1169 if (sensor[s].dev_num == dev_num &&
1171 set_report_ts(s, ts);
1175 static int integrate_device_report (int dev_num)
1179 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1181 unsigned char *target;
1182 unsigned char *source;
1185 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1186 int64_t boot_to_rt_delta;
1188 /* There's an incoming report on the specified iio device char dev fd */
1190 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1191 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1195 if (device_fd[dev_num] == -1) {
1196 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1200 len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]);
1203 ALOGE("Could not read report from iio device %d (%s)\n",
1204 dev_num, strerror(errno));
1208 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1210 /* Map device report to sensor reports */
1212 for (s=0; s<MAX_SENSORS; s++)
1213 if (sensor[s].dev_num == dev_num &&
1218 /* Copy data from device to sensor report buffer */
1219 for (c=0; c<sensor[s].num_channels; c++) {
1221 target = sensor[s].report_buffer +
1224 source = buf + sensor[s].channel[c].offset;
1226 size = sensor[s].channel[c].size;
1228 memcpy(target, source, size);
1233 ALOGV("Sensor %d report available (%d bytes)\n", s,
1236 sensor[s].report_pending = DATA_TRIGGER;
1237 sensor[s].report_initialized = 1;
1239 ts_offset += sr_offset;
1242 /* Tentatively switch to an any-motion trigger if conditions are met */
1243 enable_motion_trigger(dev_num);
1245 /* If no iio timestamp channel was detected for this device, bail out */
1246 if (!has_iio_ts[dev_num]) {
1247 stamp_reports(dev_num, get_timestamp_boot());
1251 /* Don't trust the timestamp channel in any-motion mode */
1252 for (s=0; s<MAX_SENSORS; s++)
1253 if (sensor[s].dev_num == dev_num &&
1255 sensor[s].selected_trigger ==
1256 sensor[s].motion_trigger_name) {
1257 stamp_reports(dev_num, get_timestamp_boot());
1261 /* Align on a 64 bits boundary */
1262 ts_offset = (ts_offset + 7)/8*8;
1264 /* If we read an amount of data consistent with timestamp presence */
1265 if (len == expected_dev_report_size[dev_num])
1266 ts = *(int64_t*) (buf + ts_offset);
1269 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1270 stamp_reports(dev_num, get_timestamp_boot());
1274 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1276 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1278 stamp_reports(dev_num, ts + boot_to_rt_delta);
1284 static int propagate_vsensor_report (int s, struct sensors_event_t *data)
1286 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1288 memcpy(data, &sensor[s].sample, sizeof(struct sensors_event_t));
1291 data->type = sensor[s].type;
1296 static int propagate_sensor_report (int s, struct sensors_event_t *data)
1298 /* There's a sensor report pending for this sensor ; transmit it */
1300 int num_fields = get_field_count(s);
1302 unsigned char* current_sample;
1304 /* If there's nothing to return... we're done */
1308 memset(data, 0, sizeof(sensors_event_t));
1310 data->version = sizeof(sensors_event_t);
1312 data->type = sensor[s].type;
1313 data->timestamp = sensor[s].report_ts;
1315 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1317 current_sample = sensor[s].report_buffer;
1319 /* If this is a poll sensor */
1320 if (!sensor[s].num_channels) {
1321 /* Use the data provided by the acquisition thread */
1322 ALOGV("Reporting data from worker thread for S%d\n", s);
1323 memcpy(data->data, current_sample, num_fields * sizeof(float));
1327 /* Convert the data into the expected Android-level format */
1328 for (c=0; c<num_fields; c++) {
1330 data->data[c] = sensor[s].ops.transform
1331 (s, c, current_sample);
1333 ALOGV("\tfield %d: %f\n", c, data->data[c]);
1334 current_sample += sensor[s].channel[c].size;
1338 * The finalize routine, in addition to its late sample processing duty,
1339 * has the final say on whether or not the sample gets sent to Android.
1341 return sensor[s].ops.finalize(s, data);
1345 static void synthetize_duplicate_samples (void)
1348 * Some sensor types (ex: gyroscope) are defined as continuously firing
1349 * by Android, despite the fact that we can be dealing with iio drivers
1350 * that only report events for new samples. For these we generate
1351 * reports periodically, duplicating the last data we got from the
1352 * driver. This is not necessary for polling sensors.
1360 for (s=0; s<sensor_count; s++) {
1362 /* Ignore disabled sensors */
1366 /* If the sensor is continuously firing, leave it alone */
1367 if (sensor[s].selected_trigger !=
1368 sensor[s].motion_trigger_name)
1371 /* If we haven't seen a sample, there's nothing to duplicate */
1372 if (!sensor[s].report_initialized)
1375 /* If a sample was recently buffered, leave it alone too */
1376 if (sensor[s].report_pending)
1379 /* We also need a valid sampling rate to be configured */
1380 if (!sensor[s].sampling_rate)
1383 period = (int64_t) (1000000000.0/ sensor[s].sampling_rate);
1385 current_ts = get_timestamp_boot();
1386 target_ts = sensor[s].report_ts + period;
1388 if (target_ts <= current_ts) {
1389 /* Mark the sensor for event generation */
1390 set_report_ts(s, current_ts);
1391 sensor[s].report_pending = DATA_DUPLICATE;
1397 static void integrate_thread_report (uint32_t tag)
1399 int s = tag - THREAD_REPORT_TAG_BASE;
1403 unsigned char current_sample[MAX_SENSOR_REPORT_SIZE];
1405 expected_len = sizeof(int64_t) + get_field_count(s) * sizeof(float);
1407 len = read(sensor[s].thread_data_fd[0],
1411 memcpy(×tamp, current_sample, sizeof(int64_t));
1412 memcpy(sensor[s].report_buffer, sizeof(int64_t) + current_sample,
1413 expected_len - sizeof(int64_t));
1415 if (len == expected_len) {
1416 set_report_ts(s, timestamp);
1417 sensor[s].report_pending = DATA_SYSFS;
1422 static int get_poll_wait_timeout (void)
1425 * Compute an appropriate timeout value, in ms, for the epoll_wait
1426 * call that's going to await for iio device reports and incoming
1427 * reports from our sensor sysfs data reader threads.
1431 int64_t target_ts = INT64_MAX;
1436 * Check if we're dealing with a driver that only send events when
1437 * there is motion, despite the fact that the associated Android sensor
1438 * type is continuous rather than on-change. In that case we have to
1439 * duplicate events. Check deadline for the nearest upcoming event.
1441 for (s=0; s<sensor_count; s++)
1442 if (is_enabled(s) &&
1443 sensor[s].selected_trigger ==
1444 sensor[s].motion_trigger_name &&
1445 sensor[s].sampling_rate) {
1446 period = (int64_t) (1000000000.0 /
1447 sensor[s].sampling_rate);
1449 if (sensor[s].report_ts + period < target_ts)
1450 target_ts = sensor[s].report_ts + period;
1453 /* If we don't have such a driver to deal with */
1454 if (target_ts == INT64_MAX)
1455 return -1; /* Infinite wait */
1457 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1459 /* If the target timestamp is already behind us, don't wait */
1467 int sensor_poll (struct sensors_event_t* data, int count)
1472 struct epoll_event ev[MAX_DEVICES];
1473 int returned_events;
1477 /* Get one or more events from our collection of sensors */
1478 return_available_sensor_reports:
1480 /* Synthetize duplicate samples if needed */
1481 synthetize_duplicate_samples();
1483 returned_events = 0;
1484 /* Check our sensor collection for available reports */
1485 for (s=0; s<sensor_count && returned_events < count; s++) {
1486 if (sensor[s].report_pending) {
1489 if (sensor[s].is_virtual)
1490 event_count = propagate_vsensor_report(s, &data[returned_events]);
1492 /* Report this event if it looks OK */
1493 event_count = propagate_sensor_report(s, &data[returned_events]);
1497 sensor[s].report_pending = 0;
1498 returned_events += event_count;
1500 * If the sample was deemed invalid or unreportable,
1501 * e.g. had the same value as the previously reported
1502 * value for a 'on change' sensor, silently drop it.
1505 while (sensor[s].meta_data_pending) {
1506 /* See sensors.h on these */
1507 data[returned_events].version = META_DATA_VERSION;
1508 data[returned_events].sensor = 0;
1509 data[returned_events].type = SENSOR_TYPE_META_DATA;
1510 data[returned_events].reserved0 = 0;
1511 data[returned_events].timestamp = 0;
1512 data[returned_events].meta_data.sensor = s;
1513 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1515 sensor[s].meta_data_pending--;
1518 if (returned_events)
1519 return returned_events;
1523 ALOGV("Awaiting sensor data\n");
1525 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1528 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1532 ALOGV("%d fds signalled\n", nfds);
1534 /* For each of the signalled sources */
1535 for (i=0; i<nfds; i++)
1536 if (ev[i].events == EPOLLIN)
1537 switch (ev[i].data.u32) {
1538 case 0 ... MAX_DEVICES-1:
1539 /* Read report from iio char dev fd */
1540 integrate_device_report(ev[i].data.u32);
1543 case THREAD_REPORT_TAG_BASE ...
1544 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1545 /* Get report from acquisition thread */
1546 integrate_thread_report(ev[i].data.u32);
1550 ALOGW("Unexpected event source!\n");
1554 goto return_available_sensor_reports;
1558 int sensor_set_delay (int s, int64_t ns)
1560 float requested_sampling_rate;
1563 ALOGE("Invalid delay requested on sensor %d: %lld\n", s, ns);
1567 requested_sampling_rate = 1000000000.0/ns;
1569 ALOGV("Entering set delay S%d (%s): current rate: %f, requested: %f\n",
1570 s, sensor[s].friendly_name, sensor[s].sampling_rate,
1571 requested_sampling_rate);
1573 sensor[s].requested_rate = requested_sampling_rate;
1575 return arbitrate_delays(s);
1579 int sensor_flush (int s)
1581 /* If one shot or not enabled return -EINVAL */
1582 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1585 sensor[s].meta_data_pending++;
1590 int allocate_control_data (void)
1594 for (i=0; i<MAX_DEVICES; i++)
1597 poll_fd = epoll_create(MAX_DEVICES);
1599 if (poll_fd == -1) {
1600 ALOGE("Can't create epoll instance for iio sensors!\n");
1608 void delete_control_data (void)