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 /* Coordinate with others active sensors on the same device, if any */
798 if (per_device_sampling_rate)
799 for (n=0; n<sensor_count; n++)
800 if (n != s && sensor[n].dev_num == dev_num &&
801 sensor[n].num_channels &&
803 sensor[n].sampling_rate > arb_sampling_rate)
804 arb_sampling_rate = sensor[n].sampling_rate;
806 /* Check if we have contraints on allowed sampling rates */
808 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
810 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
813 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
815 /* While we're not at the end of the string */
816 while (*cursor && cursor[0]) {
818 /* Decode a single value */
819 sr = strtod(cursor, NULL);
822 * If this matches the selected rate, we're happy.
823 * Have some tolerance to counter rounding errors and
824 * avoid needless jumps to higher rates.
826 if (fabs(arb_sampling_rate - sr) <= 0.001) {
827 arb_sampling_rate = sr;
832 * If we reached a higher value than the desired rate,
833 * adjust selected rate so it matches the first higher
834 * available one and stop parsing - this makes the
835 * assumption that rates are sorted by increasing value
836 * in the allowed frequencies string.
838 if (sr > arb_sampling_rate) {
839 arb_sampling_rate = sr;
844 while (cursor[0] && !isspace(cursor[0]))
848 while (cursor[0] && isspace(cursor[0]))
853 if (max_supported_rate &&
854 arb_sampling_rate > max_supported_rate) {
855 arb_sampling_rate = max_supported_rate;
858 /* If the desired rate is already active we're all set */
859 if (arb_sampling_rate == cur_sampling_rate)
862 ALOGI("Sensor %d (%s) sampling rate set to %g\n",
863 s, sensor[s].friendly_name, arb_sampling_rate);
865 if (trig_sensors_per_dev[dev_num])
866 enable_buffer(dev_num, 0);
868 sysfs_write_float(sysfs_path, arb_sampling_rate);
870 /* Check if it makes sense to use an alternate trigger */
871 tentative_switch_trigger(s);
873 if (trig_sensors_per_dev[dev_num])
874 enable_buffer(dev_num, 1);
881 * We go through all the virtual sensors of the base - and the base itself
882 * in order to recompute the maximum requested delay of the group and setup the base
883 * at that specific delay.
885 static int arbitrate_bases (int s)
889 float arbitrated_rate = 0;
891 if (sensor[s].directly_enabled)
892 arbitrated_rate = sensor[s].requested_rate;
894 for (i = 0; i < sensor_count; i++) {
895 for (vidx = 0; vidx < sensor[i].base_count; vidx++)
896 /* If we have a virtual sensor depending on this one - handle it */
897 if (sensor[i].base[vidx] == s &&
898 sensor[i].directly_enabled &&
899 sensor[i].requested_rate > arbitrated_rate)
900 arbitrated_rate = sensor[i].requested_rate;
903 return setup_delay_sysfs(s, arbitrated_rate);
908 * Re-assesment for delays. We need to re-asses delays for all related groups
909 * of sensors everytime a sensor enables / disables / changes frequency.
911 int arbitrate_delays (int s)
915 if (!sensor[s].is_virtual) {
916 return arbitrate_bases(s);
918 /* Is virtual sensor - go through bases */
919 for (i = 0; i < sensor[s].base_count; i++)
920 arbitrate_bases(sensor[s].base[i]);
926 int sensor_activate (int s, int enabled, int from_virtual)
928 char device_name[PATH_MAX];
929 struct epoll_event ev = {0};
932 int dev_num = sensor[s].dev_num;
933 int is_poll_sensor = !sensor[s].num_channels;
935 if (sensor[s].is_virtual) {
936 sensor_activate_virtual(s, enabled, from_virtual);
941 /* Prepare the report timestamp field for the first event, see set_report_ts method */
942 sensor[s].report_ts = 0;
944 ret = adjust_counters(s, enabled, from_virtual);
946 /* If the operation was neutral in terms of state, we're done */
952 sensor[s].event_count = 0;
953 sensor[s].meta_data_pending = 0;
955 if (enabled && (sensor[s].quirks & QUIRK_NOISY))
956 /* Initialize filtering data if required */
957 setup_noise_filtering(s);
959 if (!is_poll_sensor) {
962 enable_buffer(dev_num, 0);
963 setup_trigger(s, "\n");
965 /* If there's at least one sensor enabled on this iio device */
966 if (trig_sensors_per_dev[dev_num]) {
969 setup_trigger(s, sensor[s].init_trigger_name);
970 enable_buffer(dev_num, 1);
975 * Make sure we have a fd on the character device ; conversely, close
976 * the fd if no one is using associated sensors anymore. The assumption
977 * here is that the underlying driver will power on the relevant
978 * hardware block while someone holds a fd on the device.
980 dev_fd = device_fd[dev_num];
984 stop_acquisition_thread(s);
986 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
987 !trig_sensors_per_dev[dev_num]) {
989 * Stop watching this fd. This should be a no-op
990 * in case this fd was not in the poll set.
992 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
995 device_fd[dev_num] = -1;
998 /* Release any filtering data we may have accumulated */
999 release_noise_filtering_data(s);
1005 /* First enabled sensor on this iio device */
1006 sprintf(device_name, DEV_FILE_PATH, dev_num);
1007 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
1009 device_fd[dev_num] = dev_fd;
1012 ALOGE("Could not open fd on %s (%s)\n",
1013 device_name, strerror(errno));
1014 adjust_counters(s, 0, from_virtual);
1018 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
1020 if (!is_poll_sensor) {
1022 /* Add this iio device fd to the set of watched fds */
1023 ev.events = EPOLLIN;
1024 ev.data.u32 = dev_num;
1026 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
1029 ALOGE( "Failed adding %d to poll set (%s)\n",
1030 dev_fd, strerror(errno));
1034 /* Note: poll-mode fds are not readable */
1038 /* Ensure that on-change sensors send at least one event after enable */
1039 sensor[s].prev_val = -1;
1042 start_acquisition_thread(s);
1048 static void enable_motion_trigger (int dev_num)
1051 * In the ideal case, we enumerate two triggers per iio device ; the
1052 * default (periodically firing) trigger, and another one (the motion
1053 * trigger) that only fires up when motion is detected. This second one
1054 * allows for lesser energy consumption, but requires periodic sample
1055 * duplication at the HAL level for sensors that Android defines as
1056 * continuous. This "duplicate last sample" logic can only be engaged
1057 * once we got a first sample for the driver, so we start with the
1058 * default trigger when an iio device is first opened, then adjust the
1059 * trigger when we got events for all active sensors. Unfortunately in
1060 * the general case several sensors can be associated to a given iio
1061 * device, they can independently be controlled, and we have to adjust
1062 * the trigger in use at the iio device level depending on whether or
1063 * not appropriate conditions are met at the sensor level.
1068 int active_sensors = trig_sensors_per_dev[dev_num];
1069 int candidate[MAX_SENSORS];
1070 int candidate_count = 0;
1072 if (!active_sensors)
1075 /* Check that all active sensors are ready to switch */
1077 for (s=0; s<MAX_SENSORS; s++)
1078 if (sensor[s].dev_num == dev_num &&
1080 sensor[s].num_channels &&
1081 (!sensor[s].motion_trigger_name[0] ||
1082 !sensor[s].report_initialized ||
1083 is_fast_accelerometer(s) ||
1084 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS))
1088 /* Record which particular sensors need to switch */
1090 for (s=0; s<MAX_SENSORS; s++)
1091 if (sensor[s].dev_num == dev_num &&
1093 sensor[s].num_channels &&
1094 sensor[s].selected_trigger !=
1095 sensor[s].motion_trigger_name)
1096 candidate[candidate_count++] = s;
1098 if (!candidate_count)
1101 /* Now engage the motion trigger for sensors which aren't using it */
1103 enable_buffer(dev_num, 0);
1105 for (i=0; i<candidate_count; i++) {
1107 setup_trigger(s, sensor[s].motion_trigger_name);
1110 enable_buffer(dev_num, 1);
1115 * CTS acceptable thresholds:
1116 * EventGapVerification.java: (th <= 1.8)
1117 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
1119 #define THRESHOLD 1.10
1120 #define MAX_DELAY 500000000 /* 500 ms */
1122 void set_report_ts(int s, int64_t ts)
1124 int64_t maxTs, period;
1127 * A bit of a hack to please a bunch of cts tests. They
1128 * expect the timestamp to be exacly according to the set-up
1129 * frequency but if we're simply getting the timestamp at hal level
1130 * this may not be the case. Perhaps we'll get rid of this when
1131 * we'll be reading the timestamp from the iio channel for all sensors
1133 if (sensor[s].report_ts && sensor[s].sampling_rate &&
1134 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
1136 period = (int64_t) (1000000000LL / sensor[s].sampling_rate);
1137 maxTs = sensor[s].report_ts + THRESHOLD * period;
1138 /* If we're too far behind get back on track */
1139 if (ts - maxTs >= MAX_DELAY)
1141 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
1143 sensor[s].report_ts = ts;
1148 static void stamp_reports (int dev_num, int64_t ts)
1152 for (s=0; s<MAX_SENSORS; s++)
1153 if (sensor[s].dev_num == dev_num &&
1155 set_report_ts(s, ts);
1159 static int integrate_device_report (int dev_num)
1163 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1165 unsigned char *target;
1166 unsigned char *source;
1169 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1170 int64_t boot_to_rt_delta;
1172 /* There's an incoming report on the specified iio device char dev fd */
1174 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1175 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1179 if (device_fd[dev_num] == -1) {
1180 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1184 len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]);
1187 ALOGE("Could not read report from iio device %d (%s)\n",
1188 dev_num, strerror(errno));
1192 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1194 /* Map device report to sensor reports */
1196 for (s=0; s<MAX_SENSORS; s++)
1197 if (sensor[s].dev_num == dev_num &&
1202 /* Copy data from device to sensor report buffer */
1203 for (c=0; c<sensor[s].num_channels; c++) {
1205 target = sensor[s].report_buffer +
1208 source = buf + sensor[s].channel[c].offset;
1210 size = sensor[s].channel[c].size;
1212 memcpy(target, source, size);
1217 ALOGV("Sensor %d report available (%d bytes)\n", s,
1220 sensor[s].report_pending = DATA_TRIGGER;
1221 sensor[s].report_initialized = 1;
1223 ts_offset += sr_offset;
1226 /* Tentatively switch to an any-motion trigger if conditions are met */
1227 enable_motion_trigger(dev_num);
1229 /* If no iio timestamp channel was detected for this device, bail out */
1230 if (!has_iio_ts[dev_num]) {
1231 stamp_reports(dev_num, get_timestamp_boot());
1235 /* Don't trust the timestamp channel in any-motion mode */
1236 for (s=0; s<MAX_SENSORS; s++)
1237 if (sensor[s].dev_num == dev_num &&
1239 sensor[s].selected_trigger ==
1240 sensor[s].motion_trigger_name) {
1241 stamp_reports(dev_num, get_timestamp_boot());
1245 /* Align on a 64 bits boundary */
1246 ts_offset = (ts_offset + 7)/8*8;
1248 /* If we read an amount of data consistent with timestamp presence */
1249 if (len == expected_dev_report_size[dev_num])
1250 ts = *(int64_t*) (buf + ts_offset);
1253 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1254 stamp_reports(dev_num, get_timestamp_boot());
1258 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1260 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1262 stamp_reports(dev_num, ts + boot_to_rt_delta);
1268 static int propagate_vsensor_report (int s, struct sensors_event_t *data)
1270 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1272 memcpy(data, &sensor[s].sample, sizeof(struct sensors_event_t));
1275 data->type = sensor[s].type;
1280 static int propagate_sensor_report (int s, struct sensors_event_t *data)
1282 /* There's a sensor report pending for this sensor ; transmit it */
1284 int num_fields = get_field_count(s);
1286 unsigned char* current_sample;
1288 /* If there's nothing to return... we're done */
1292 memset(data, 0, sizeof(sensors_event_t));
1294 data->version = sizeof(sensors_event_t);
1296 data->type = sensor[s].type;
1297 data->timestamp = sensor[s].report_ts;
1299 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1301 current_sample = sensor[s].report_buffer;
1303 /* If this is a poll sensor */
1304 if (!sensor[s].num_channels) {
1305 /* Use the data provided by the acquisition thread */
1306 ALOGV("Reporting data from worker thread for S%d\n", s);
1307 memcpy(data->data, current_sample, num_fields * sizeof(float));
1311 /* Convert the data into the expected Android-level format */
1312 for (c=0; c<num_fields; c++) {
1314 data->data[c] = sensor[s].ops.transform
1315 (s, c, current_sample);
1317 ALOGV("\tfield %d: %f\n", c, data->data[c]);
1318 current_sample += sensor[s].channel[c].size;
1322 * The finalize routine, in addition to its late sample processing duty,
1323 * has the final say on whether or not the sample gets sent to Android.
1325 return sensor[s].ops.finalize(s, data);
1329 static void synthetize_duplicate_samples (void)
1332 * Some sensor types (ex: gyroscope) are defined as continuously firing
1333 * by Android, despite the fact that we can be dealing with iio drivers
1334 * that only report events for new samples. For these we generate
1335 * reports periodically, duplicating the last data we got from the
1336 * driver. This is not necessary for polling sensors.
1344 for (s=0; s<sensor_count; s++) {
1346 /* Ignore disabled sensors */
1350 /* If the sensor is continuously firing, leave it alone */
1351 if (sensor[s].selected_trigger !=
1352 sensor[s].motion_trigger_name)
1355 /* If we haven't seen a sample, there's nothing to duplicate */
1356 if (!sensor[s].report_initialized)
1359 /* If a sample was recently buffered, leave it alone too */
1360 if (sensor[s].report_pending)
1363 /* We also need a valid sampling rate to be configured */
1364 if (!sensor[s].sampling_rate)
1367 period = (int64_t) (1000000000.0/ sensor[s].sampling_rate);
1369 current_ts = get_timestamp_boot();
1370 target_ts = sensor[s].report_ts + period;
1372 if (target_ts <= current_ts) {
1373 /* Mark the sensor for event generation */
1374 set_report_ts(s, current_ts);
1375 sensor[s].report_pending = DATA_DUPLICATE;
1381 static void integrate_thread_report (uint32_t tag)
1383 int s = tag - THREAD_REPORT_TAG_BASE;
1387 unsigned char current_sample[MAX_SENSOR_REPORT_SIZE];
1389 expected_len = sizeof(int64_t) + get_field_count(s) * sizeof(float);
1391 len = read(sensor[s].thread_data_fd[0],
1395 memcpy(×tamp, current_sample, sizeof(int64_t));
1396 memcpy(sensor[s].report_buffer, sizeof(int64_t) + current_sample,
1397 expected_len - sizeof(int64_t));
1399 if (len == expected_len) {
1400 set_report_ts(s, timestamp);
1401 sensor[s].report_pending = DATA_SYSFS;
1406 static int get_poll_wait_timeout (void)
1409 * Compute an appropriate timeout value, in ms, for the epoll_wait
1410 * call that's going to await for iio device reports and incoming
1411 * reports from our sensor sysfs data reader threads.
1415 int64_t target_ts = INT64_MAX;
1420 * Check if we're dealing with a driver that only send events when
1421 * there is motion, despite the fact that the associated Android sensor
1422 * type is continuous rather than on-change. In that case we have to
1423 * duplicate events. Check deadline for the nearest upcoming event.
1425 for (s=0; s<sensor_count; s++)
1426 if (is_enabled(s) &&
1427 sensor[s].selected_trigger ==
1428 sensor[s].motion_trigger_name &&
1429 sensor[s].sampling_rate) {
1430 period = (int64_t) (1000000000.0 /
1431 sensor[s].sampling_rate);
1433 if (sensor[s].report_ts + period < target_ts)
1434 target_ts = sensor[s].report_ts + period;
1437 /* If we don't have such a driver to deal with */
1438 if (target_ts == INT64_MAX)
1439 return -1; /* Infinite wait */
1441 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1443 /* If the target timestamp is already behind us, don't wait */
1451 int sensor_poll (struct sensors_event_t* data, int count)
1456 struct epoll_event ev[MAX_DEVICES];
1457 int returned_events;
1461 /* Get one or more events from our collection of sensors */
1462 return_available_sensor_reports:
1464 /* Synthetize duplicate samples if needed */
1465 synthetize_duplicate_samples();
1467 returned_events = 0;
1468 /* Check our sensor collection for available reports */
1469 for (s=0; s<sensor_count && returned_events < count; s++) {
1470 if (sensor[s].report_pending) {
1473 if (sensor[s].is_virtual)
1474 event_count = propagate_vsensor_report(s, &data[returned_events]);
1476 /* Report this event if it looks OK */
1477 event_count = propagate_sensor_report(s, &data[returned_events]);
1481 sensor[s].report_pending = 0;
1482 returned_events += event_count;
1484 * If the sample was deemed invalid or unreportable,
1485 * e.g. had the same value as the previously reported
1486 * value for a 'on change' sensor, silently drop it.
1489 while (sensor[s].meta_data_pending) {
1490 /* See sensors.h on these */
1491 data[returned_events].version = META_DATA_VERSION;
1492 data[returned_events].sensor = 0;
1493 data[returned_events].type = SENSOR_TYPE_META_DATA;
1494 data[returned_events].reserved0 = 0;
1495 data[returned_events].timestamp = 0;
1496 data[returned_events].meta_data.sensor = s;
1497 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1499 sensor[s].meta_data_pending--;
1502 if (returned_events)
1503 return returned_events;
1507 ALOGV("Awaiting sensor data\n");
1509 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1512 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1516 ALOGV("%d fds signalled\n", nfds);
1518 /* For each of the signalled sources */
1519 for (i=0; i<nfds; i++)
1520 if (ev[i].events == EPOLLIN)
1521 switch (ev[i].data.u32) {
1522 case 0 ... MAX_DEVICES-1:
1523 /* Read report from iio char dev fd */
1524 integrate_device_report(ev[i].data.u32);
1527 case THREAD_REPORT_TAG_BASE ...
1528 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1529 /* Get report from acquisition thread */
1530 integrate_thread_report(ev[i].data.u32);
1534 ALOGW("Unexpected event source!\n");
1538 goto return_available_sensor_reports;
1542 int sensor_set_delay (int s, int64_t ns)
1544 float requested_sampling_rate;
1547 ALOGE("Invalid delay requested on sensor %d: %lld\n", s, ns);
1551 requested_sampling_rate = 1000000000.0/ns;
1553 ALOGV("Entering set delay S%d (%s): current rate: %f, requested: %f\n",
1554 s, sensor[s].friendly_name, sensor[s].sampling_rate,
1555 requested_sampling_rate);
1557 sensor[s].requested_rate = requested_sampling_rate;
1559 return arbitrate_delays(s);
1563 int sensor_flush (int s)
1565 /* If one shot or not enabled return -EINVAL */
1566 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1569 sensor[s].meta_data_pending++;
1574 int allocate_control_data (void)
1578 for (i=0; i<MAX_DEVICES; i++)
1581 poll_fd = epoll_create(MAX_DEVICES);
1583 if (poll_fd == -1) {
1584 ALOGE("Can't create epoll instance for iio sensors!\n");
1592 void delete_control_data (void)