OSDN Git Service

iio-sensors: Fix build warnings
[android-x86/hardware-intel-libsensors.git] / control.c
1 /*
2  * Copyright (C) 2014 Intel Corporation.
3  */
4
5 #include <stdlib.h>
6 #include <ctype.h>
7 #include <fcntl.h>
8 #include <pthread.h>
9 #include <time.h>
10 #include <math.h>
11 #include <sys/epoll.h>
12 #include <sys/socket.h>
13 #include <utils/Log.h>
14 #include <hardware/sensors.h>
15 #include "control.h"
16 #include "enumeration.h"
17 #include "utils.h"
18 #include "transform.h"
19 #include "calibration.h"
20 #include "description.h"
21 #include "filtering.h"
22
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                         */
26
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  */
31
32 static int active_poll_sensors;                         /* Number of enabled poll-mode sensors          */
33
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];
38
39 /*
40  * We associate tags to each of our poll set entries. These tags have the following values:
41  * - a iio device number if the fd is a iio character device fd
42  * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a pipe used by a sysfs data acquisition thread
43  */
44 #define THREAD_REPORT_TAG_BASE          1000
45
46 /* If buffer enable fails, we may want to retry a few times before giving up */
47 #define ENABLE_BUFFER_RETRIES           3
48 #define ENABLE_BUFFER_RETRY_DELAY_MS    10
49
50
51 inline int is_enabled (int s)
52 {
53         return sensor[s].directly_enabled || sensor[s].ref_count;
54 }
55
56
57 static int check_state_change (int s, int enabled, int from_virtual)
58 {
59         if (enabled) {
60                 if (sensor[s].directly_enabled)
61                         return 0;                       /* We're being enabled but already were directly activated: no change. */
62
63                 if (!from_virtual)
64                         sensor[s].directly_enabled = 1; /* We're being directly enabled */
65
66                 if (sensor[s].ref_count)
67                         return 0;                       /* We were already indirectly enabled */
68
69                 return 1;                               /* Do continue enabling this sensor */
70         }
71
72         if (!is_enabled(s))
73                 return 0;                               /* We are being disabled but already were: no change */
74
75         if (from_virtual && sensor[s].directly_enabled)
76                 return 0;                               /* We're indirectly disabled but the base is still active */
77
78         sensor[s].directly_enabled = 0;                 /* We're now directly disabled */
79
80         if (!from_virtual && sensor[s].ref_count)
81                 return 0;                               /* We still have ref counts */
82
83         return 1;                                       /* Do continue disabling this sensor */
84 }
85
86
87 static int enable_buffer (int dev_num, int enabled)
88 {
89         char sysfs_path[PATH_MAX];
90         int retries = ENABLE_BUFFER_RETRIES;
91
92         sprintf(sysfs_path, ENABLE_PATH, dev_num);
93
94         while (retries) {
95                 /* Low level, non-multiplexed, enable/disable routine */
96                 if (sysfs_write_int(sysfs_path, enabled) > 0)
97                         return 0;
98
99                 ALOGE("Failed enabling buffer on dev%d, retrying", dev_num);
100                 usleep(ENABLE_BUFFER_RETRY_DELAY_MS*1000);
101                 retries--;
102         }
103
104         ALOGE("Could not enable buffer\n");
105         return -EIO;
106 }
107
108
109 static int setup_trigger (int s, const char* trigger_val)
110 {
111         char sysfs_path[PATH_MAX];
112         int ret = -1, attempts = 5;
113
114         sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
115
116         if (trigger_val[0] != '\n')
117                 ALOGI("Setting S%d (%s) trigger to %s\n", s, sensor[s].friendly_name, trigger_val);
118
119         while (ret == -1 && attempts) {
120                 ret = sysfs_write_str(sysfs_path, trigger_val);
121                 attempts--;
122         }
123
124         if (ret != -1)
125                 sensor[s].selected_trigger = trigger_val;
126         else
127                 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, sensor[s].friendly_name, trigger_val);
128         return ret;
129 }
130
131
132 static void enable_iio_timestamp (int dev_num, int known_channels)
133 {
134         /* Check if we have a dedicated iio timestamp channel */
135
136         char spec_buf[MAX_TYPE_SPEC_LEN];
137         char sysfs_path[PATH_MAX];
138         int n;
139
140         sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
141
142         n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
143
144         if (n <= 0)
145                 return;
146
147         if (strcmp(spec_buf, "le:s64/64>>0"))
148                 return;
149
150         /* OK, type is int64_t as expected, in little endian representation */
151
152         sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
153
154         if (sysfs_read_int(sysfs_path, &n))
155                 return;
156
157         /* Check that the timestamp comes after the other fields we read */
158         if (n != known_channels)
159                 return;
160
161         /* Try enabling that channel */
162         sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
163
164         sysfs_write_int(sysfs_path, 1);
165
166         if (sysfs_read_int(sysfs_path, &n))
167                 return;
168
169         if (n) {
170                 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
171                 has_iio_ts[dev_num] = 1;
172         }
173 }
174
175
176 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], datum_info_t *type_info)
177 {
178         /* Return size in bytes for this type specification, or -1 in error */
179         char sign;
180         char endianness;
181         unsigned int realbits, storagebits, shift;
182         int tokens;
183
184         /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
185
186         tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", &endianness, &sign, &realbits, &storagebits, &shift);
187
188         if (tokens != 5 || (endianness != 'b' && endianness != 'l') || (sign != 'u' && sign != 's') ||
189             realbits > storagebits || (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
190                         ALOGE("Invalid iio channel type spec: %s\n", type_buf);
191                         return -1;
192         }
193
194         type_info->endianness   =               endianness;
195         type_info->sign         =               sign;
196         type_info->realbits     =       (short) realbits;
197         type_info->storagebits  =       (short) storagebits;
198         type_info->shift        =       (short) shift;
199
200         return storagebits / 8;
201 }
202
203
204 void build_sensor_report_maps (int dev_num)
205 {
206         /*
207          * Read sysfs files from a iio device's scan_element directory, and build a couple of tables from that data. These tables will tell, for
208          * each sensor, where to gather relevant data in a device report, i.e. the structure that we read from the /dev/iio:deviceX file in order to
209          * sensor report, itself being the data that we return to Android when a sensor poll completes. The mapping should be straightforward in the
210          * case where we have a single sensor active per iio device but, this is not the general case. In general several sensors can be handled
211          * through a single iio device, and the _en, _index and _type syfs entries all concur to paint a picture of what the structure of the
212          * device report is.
213          */
214
215         int s;
216         int c;
217         int n;
218         int i;
219         int ch_index;
220         char* ch_spec;
221         char spec_buf[MAX_TYPE_SPEC_LEN];
222         datum_info_t* ch_info;
223         int size;
224         char sysfs_path[PATH_MAX];
225         int known_channels;
226         int offset;
227         int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
228         int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
229         int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
230
231         known_channels = 0;
232
233         /* For each sensor that is linked to this device */
234         for (s=0; s<sensor_count; s++) {
235                 if (sensor[s].dev_num != dev_num)
236                         continue;
237
238                 i = sensor[s].catalog_index;
239
240                 /* Read channel details through sysfs attributes */
241                 for (c=0; c<sensor[s].num_channels; c++) {
242
243                         /* Read _type file */
244                         sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].type_path);
245
246                         n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
247
248                         if (n == -1) {
249                                         ALOGW(  "Failed to read type: %s\n", sysfs_path);
250                                         continue;
251                         }
252
253                         ch_spec = sensor[s].channel[c].type_spec;
254
255                         memcpy(ch_spec, spec_buf, sizeof(spec_buf));
256
257                         ch_info = &sensor[s].channel[c].type_info;
258
259                         size = decode_type_spec(ch_spec, ch_info);
260
261                         /* Read _index file */
262                         sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].index_path);
263
264                         n = sysfs_read_int(sysfs_path, &ch_index);
265
266                         if (n == -1) {
267                                         ALOGW(  "Failed to read index: %s\n", sysfs_path);
268                                         continue;
269                         }
270
271                         if (ch_index >= MAX_SENSORS) {
272                                 ALOGE("Index out of bounds!: %s\n", sysfs_path);
273                                 continue;
274                         }
275
276                         /* Record what this index is about */
277
278                         sensor_handle_from_index [ch_index] = s;
279                         channel_number_from_index[ch_index] = c;
280                         channel_size_from_index  [ch_index] = size;
281
282                         known_channels++;
283                 }
284
285                 /* Stop sampling - if we are recovering from hal restart */
286                 enable_buffer(dev_num, 0);
287                 setup_trigger(s, "\n");
288
289                 /* Turn on channels we're aware of */
290                 for (c=0;c<sensor[s].num_channels; c++) {
291                         sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].en_path);
292                         sysfs_write_int(sysfs_path, 1);
293                 }
294         }
295
296         ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
297
298         /*
299          * Now that we know which channels are defined, their sizes and their ordering, update channels offsets within device report. Note: there
300          * is a possibility that several sensors share the same index, with their data fields being isolated by masking and shifting as specified
301          * through the real bits and shift values in type attributes. This case is not currently supported. Also, the code below assumes no hole in
302          * the sequence of indices, so it is dependent on discovery of all sensors.
303          */
304          offset = 0;
305
306          for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
307                 s =     sensor_handle_from_index[i];
308                 c =     channel_number_from_index[i];
309                 size =  channel_size_from_index[i];
310
311                 if (!size)
312                         continue;
313
314                 ALOGI("S%d C%d : offset %d, size %d, type %s\n", s, c, offset, size, sensor[s].channel[c].type_spec);
315
316                 sensor[s].channel[c].offset     = offset;
317                 sensor[s].channel[c].size               = size;
318
319                 offset += size;
320          }
321
322         /* Enable the timestamp channel if there is one available */
323         enable_iio_timestamp(dev_num, known_channels);
324
325         /* Add padding and timestamp size if it's enabled on this iio device */
326         if (has_iio_ts[dev_num])
327                 offset = (offset+7)/8*8 + sizeof(int64_t);
328
329         expected_dev_report_size[dev_num] = offset;
330         ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
331
332         if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
333                 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", dev_num, expected_dev_report_size[dev_num]);
334
335                 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
336         }
337 }
338
339
340 int adjust_counters (int s, int enabled, int from_virtual)
341 {
342         /*
343          * Adjust counters based on sensor enable action. Return values are:
344          *  0 if the operation was completed and we're all set
345          *  1 if we toggled the state of the sensor and there's work left
346          */
347
348         int dev_num = sensor[s].dev_num;
349
350         if (!check_state_change(s, enabled, from_virtual))
351                 return 0; /* The state of the sensor remains the same: we're done */
352
353         if (enabled) {
354                 ALOGI("Enabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
355
356                 switch (sensor[s].type) {
357                         case SENSOR_TYPE_MAGNETIC_FIELD:
358                                 compass_read_data(&sensor[s]);
359                                 break;
360
361                         case SENSOR_TYPE_GYROSCOPE:
362                                 gyro_cal_init(&sensor[s]);
363                                 break;
364                 }
365         } else {
366                 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
367
368                 /* Sensor disabled, lower report available flag */
369                 sensor[s].report_pending = 0;
370
371                 if (sensor[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
372                         compass_store_data(&sensor[s]);
373
374                 if (sensor[s].type == SENSOR_TYPE_GYROSCOPE)
375                         gyro_store_data(&sensor[s]);
376         }
377
378         /* We changed the state of a sensor: adjust device ref counts */
379
380         if (!sensor[s].is_polling) {
381
382                         if (enabled)
383                                 trig_sensors_per_dev[dev_num]++;
384                         else
385                                 trig_sensors_per_dev[dev_num]--;
386
387                         return 1;
388         }
389
390         if (enabled) {
391                 active_poll_sensors++;
392                 poll_sensors_per_dev[dev_num]++;
393                 return 1;
394         }
395
396         active_poll_sensors--;
397         poll_sensors_per_dev[dev_num]--;
398         return 1;
399 }
400
401
402 static int get_field_count (int s)
403 {
404         switch (sensor[s].type) {
405                 case SENSOR_TYPE_ACCELEROMETER:         /* m/s^2        */
406                 case SENSOR_TYPE_MAGNETIC_FIELD:        /* micro-tesla  */
407                 case SENSOR_TYPE_ORIENTATION:           /* degrees      */
408                 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
409                 case SENSOR_TYPE_GYROSCOPE:             /* radians/s    */
410                         return 3;
411
412                 case SENSOR_TYPE_LIGHT:                 /* SI lux units */
413                 case SENSOR_TYPE_AMBIENT_TEMPERATURE:   /* Â°C          */
414                 case SENSOR_TYPE_TEMPERATURE:           /* Â°C          */
415                 case SENSOR_TYPE_PROXIMITY:             /* centimeters  */
416                 case SENSOR_TYPE_PRESSURE:              /* hecto-pascal */
417                 case SENSOR_TYPE_RELATIVE_HUMIDITY:     /* percent */
418                         return 1;
419
420                 case SENSOR_TYPE_ROTATION_VECTOR:
421                         return 4;
422
423                 default:
424                         ALOGE("Unknown sensor type!\n");
425                         return 0;                       /* Drop sample */
426         }
427 }
428
429 /*
430  *  CTS acceptable thresholds:
431  *      EventGapVerification.java: (th <= 1.8)
432  *      FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
433  */
434 #define THRESHOLD 1.10
435 #define MAX_DELAY 500000000 /* 500 ms */
436
437 void set_report_ts(int s, int64_t ts)
438 {
439         int64_t maxTs, period;
440
441         /*
442         *  A bit of a hack to please a bunch of cts tests. They
443         *  expect the timestamp to be exacly according to the set-up
444         *  frequency but if we're simply getting the timestamp at hal level
445         *  this may not be the case. Perhaps we'll get rid of this when
446         *  we'll be reading the timestamp from the iio channel for all sensors
447         */
448         if (sensor[s].report_ts && sensor[s].sampling_rate &&
449                 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
450         {
451                 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
452                 maxTs = sensor[s].report_ts + THRESHOLD * period;
453                 /* If we're too far behind get back on track */
454                 if (ts - maxTs >= MAX_DELAY)
455                         maxTs = ts;
456                 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
457         } else {
458                 sensor[s].report_ts = ts;
459         }
460 }
461
462 static void* acquisition_routine (void* param)
463 {
464         /*
465          * Data acquisition routine run in a dedicated thread, covering a single sensor. This loop will periodically retrieve sampling data through
466          * sysfs, then package it as a sample and transfer it to our master poll loop through a report fd. Checks for a cancellation signal quite
467          * frequently, as the thread may be disposed of at any time. Note that Bionic does not provide pthread_cancel / pthread_testcancel...
468          */
469
470         int s = (int) (size_t) param;
471         int num_fields;
472         sensors_event_t data = {0};
473         int c;
474         int ret;
475         struct timespec target_time;
476         int64_t timestamp, period, start, stop;
477
478         if (s < 0 || s >= sensor_count) {
479                 ALOGE("Invalid sensor handle!\n");
480                 return NULL;
481         }
482
483         ALOGI("Entering S%d (%s) data acquisition thread: rate:%g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate);
484
485         if (sensor[s].sampling_rate <= 0) {
486                 ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", s, sensor[s].sampling_rate);
487                 return NULL;
488         }
489
490         /* Initialize data fields that will be shared by all sensor reports */
491         data.version    = sizeof(sensors_event_t);
492         data.sensor     = s;
493         data.type       = sensor[s].type;
494
495         num_fields = get_field_count(s);
496
497         /*
498          * Each condition variable is associated to a mutex that has to be locked by the thread that's waiting on it. We use these condition
499          * variables to get the acquisition threads out of sleep quickly after the sampling rate is adjusted, or the sensor is disabled.
500          */
501         pthread_mutex_lock(&thread_release_mutex[s]);
502
503         /* Pinpoint the moment we start sampling */
504         timestamp = get_timestamp_monotonic();
505
506         /* Check and honor termination requests */
507         while (sensor[s].thread_data_fd[1] != -1) {
508                 start = get_timestamp_boot();
509
510                 /* Read values through sysfs */
511                 for (c=0; c<num_fields; c++) {
512                         data.data[c] = acquire_immediate_value(s, c);
513
514                         /* Check and honor termination requests */
515                         if (sensor[s].thread_data_fd[1] == -1)
516                                 goto exit;
517                 }
518                 stop = get_timestamp_boot();
519                 set_report_ts(s, start/2 + stop/2);
520                 data.timestamp = sensor[s].report_ts;
521                 /* If the sample looks good */
522                 if (sensor[s].ops.finalize(s, &data)) {
523
524                         /* Pipe it for transmission to poll loop */
525                         ret = write(sensor[s].thread_data_fd[1], &data, sizeof(sensors_event_t));
526
527                         if (ret != sizeof(sensors_event_t))
528                                 ALOGE("S%d write failure: wrote %d, got %d\n", s, sizeof(sensors_event_t), ret);
529                 }
530
531                 /* Check and honor termination requests */
532                 if (sensor[s].thread_data_fd[1] == -1)
533                         goto exit;
534
535                 /* Recalculate period assuming sensor[s].sampling_rate can be changed dynamically during the thread run */
536                 if (sensor[s].sampling_rate <= 0) {
537                         ALOGE("Unexpected sampling rate for sensor %d: %g\n", s, sensor[s].sampling_rate);
538                         goto exit;
539                 }
540
541                 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
542                 timestamp += period;
543                 set_timestamp(&target_time, timestamp);
544
545                 /* Wait until the sampling time elapses, or a rate change is signaled, or a thread exit is requested */
546                 ret = pthread_cond_timedwait(&thread_release_cond[s], &thread_release_mutex[s], &target_time);
547         }
548
549 exit:
550         ALOGV("Acquisition thread for S%d exiting\n", s);
551         pthread_mutex_unlock(&thread_release_mutex[s]);
552         pthread_exit(0);
553         return NULL;
554 }
555
556
557 static void start_acquisition_thread (int s)
558 {
559         int incoming_data_fd;
560         int ret;
561
562         struct epoll_event ev = {0};
563
564         ALOGV("Initializing acquisition context for sensor %d\n", s);
565
566         /* Create condition variable and mutex for quick thread release */
567         ret = pthread_condattr_init(&thread_cond_attr[s]);
568         ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
569         ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
570         ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
571
572         /* Create a pipe for inter thread communication */
573         ret = pipe(sensor[s].thread_data_fd);
574
575         incoming_data_fd = sensor[s].thread_data_fd[0];
576
577         ev.events = EPOLLIN;
578         ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
579
580         /* Add incoming side of pipe to our poll set, with a suitable tag */
581         ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
582         if (ret == -1) {
583                 ALOGE("Failed adding %d to poll set (%s)\n",
584                         incoming_data_fd, strerror(errno));
585         }
586
587         /* Create and start worker thread */
588         ret = pthread_create(&sensor[s].acquisition_thread, NULL, acquisition_routine, (void*) (size_t) s);
589 }
590
591
592 static void stop_acquisition_thread (int s)
593 {
594         int incoming_data_fd = sensor[s].thread_data_fd[0];
595         int outgoing_data_fd = sensor[s].thread_data_fd[1];
596
597         ALOGV("Tearing down acquisition context for sensor %d\n", s);
598
599         /* Delete the incoming side of the pipe from our poll set */
600         epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
601
602         /* Mark the pipe ends as invalid ; that's a cheap exit flag */
603         sensor[s].thread_data_fd[0] = -1;
604         sensor[s].thread_data_fd[1] = -1;
605
606         /* Close both sides of our pipe */
607         close(incoming_data_fd);
608         close(outgoing_data_fd);
609
610         /* Stop acquisition thread and clean up thread handle */
611         pthread_cond_signal(&thread_release_cond[s]);
612         pthread_join(sensor[s].acquisition_thread, NULL);
613
614         /* Clean up our sensor descriptor */
615         sensor[s].acquisition_thread = -1;
616
617         /* Delete condition variable and mutex */
618         pthread_cond_destroy(&thread_release_cond[s]);
619         pthread_mutex_destroy(&thread_release_mutex[s]);
620 }
621
622
623 static int is_fast_accelerometer (int s)
624 {
625         /*
626          * Some games don't react well to accelerometers using any-motion triggers. Even very low thresholds seem to trip them, and they tend to
627          * request fairly high event rates. Favor continuous triggers if the sensor is an accelerometer and uses a sampling rate of at least 25.
628          */
629
630         if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
631                 return 0;
632
633         if (sensor[s].sampling_rate < 25)
634                 return 0;
635
636         return 1;
637 }
638
639
640 static void tentative_switch_trigger (int s)
641 {
642         /*
643          * Under certain situations it may be beneficial to use an alternate trigger:
644          *
645          * - for applications using the accelerometer with high sampling rates, prefer the continuous trigger over the any-motion one, to avoid
646          *   jumps related to motion thresholds
647          */
648
649         if (is_fast_accelerometer(s) && !(sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].selected_trigger == sensor[s].motion_trigger_name)
650                 setup_trigger(s, sensor[s].init_trigger_name);
651 }
652
653
654 static float get_group_max_sampling_rate (int s)
655 {
656         /* Review the sampling rates of linked sensors and return the maximum */
657
658         int i, vi;
659
660         float arbitrated_rate = 0;
661
662         if (is_enabled(s))
663                 arbitrated_rate = sensor[s].requested_rate;
664
665         /* If any of the currently active sensors built on top of this one need a higher sampling rate, switch to this rate */
666         for (i = 0; i < sensor_count; i++)
667                 for (vi = 0; vi < sensor[i].base_count; vi++)
668                         if (sensor[i].base[vi] == s && is_enabled(i) && sensor[i].requested_rate > arbitrated_rate)     /* If sensor i depends on sensor s */
669                                 arbitrated_rate = sensor[i].requested_rate;
670
671         /* If any of the currently active sensors we rely on is using a higher sampling rate, switch to this rate */
672         for (vi = 0; vi < sensor[s].base_count; vi++) {
673                 i = sensor[s].base[vi];
674                 if (is_enabled(i) && sensor[i].requested_rate > arbitrated_rate)
675                         arbitrated_rate = sensor[i].requested_rate;
676         }
677
678         return arbitrated_rate;
679 }
680
681
682 static int sensor_set_rate (int s, float requested_rate)
683 {
684         /* Set the rate at which a specific sensor should report events. See Android sensors.h for indication on sensor trigger modes */
685
686         char sysfs_path[PATH_MAX];
687         char avail_sysfs_path[PATH_MAX];
688         int dev_num             =       sensor[s].dev_num;
689         int i                   =       sensor[s].catalog_index;
690         const char *prefix      =       sensor_catalog[i].tag;
691         int per_sensor_sampling_rate;
692         int per_device_sampling_rate;
693         char freqs_buf[100];
694         char* cursor;
695         int n;
696         float sr;
697         float group_max_sampling_rate;
698         float cur_sampling_rate; /* Currently used sampling rate              */
699         float arb_sampling_rate; /* Granted sampling rate after arbitration   */
700
701         ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, s, sensor[s].friendly_name);
702
703         sensor[s].requested_rate = requested_rate;
704
705         arb_sampling_rate = requested_rate;
706
707         if (arb_sampling_rate < sensor[s].min_supported_rate) {
708                 ALOGV("Sampling rate %g too low for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].min_supported_rate);
709                 arb_sampling_rate = sensor[s].min_supported_rate;
710         }
711
712         /* If one of the linked sensors uses a higher rate, adopt it */
713         group_max_sampling_rate = get_group_max_sampling_rate(s);
714
715         if (arb_sampling_rate < group_max_sampling_rate) {
716                 ALOGV("Using %s sampling rate to %g too due to dependency\n", sensor[s].friendly_name, arb_sampling_rate);
717                 arb_sampling_rate = group_max_sampling_rate;
718         }
719
720         if (sensor[s].max_supported_rate && arb_sampling_rate > sensor[s].max_supported_rate) {
721                 ALOGV("Sampling rate %g too high for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].max_supported_rate);
722                 arb_sampling_rate = sensor[s].max_supported_rate;
723         }
724
725         sensor[s].sampling_rate = arb_sampling_rate;
726
727         /* If the sensor is virtual, we're done */
728         if (sensor[s].is_virtual)
729                 return 0;
730
731         /* If we're dealing with a poll-mode sensor */
732         if (sensor[s].is_polling) {
733                 if (is_enabled(s))
734                         pthread_cond_signal(&thread_release_cond[s]); /* Wake up thread so the new sampling rate gets used */
735                 return 0;
736         }
737
738         sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
739
740         if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
741                 per_sensor_sampling_rate = 1;
742                 per_device_sampling_rate = 0;
743         } else {
744                 per_sensor_sampling_rate = 0;
745
746                 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
747
748                 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
749                         per_device_sampling_rate = 1;
750                 else
751                         per_device_sampling_rate = 0;
752         }
753
754         if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
755                 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
756                 return -ENOSYS;
757         }
758
759         /* Check if we have contraints on allowed sampling rates */
760
761         sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
762
763         if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0) {
764                 cursor = freqs_buf;
765
766                 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
767
768                 /* While we're not at the end of the string */
769                 while (*cursor && cursor[0]) {
770
771                         /* Decode a single value */
772                         sr = strtod(cursor, NULL);
773
774                         /* If this matches the selected rate, we're happy.  Have some tolerance for rounding errors and avoid needless jumps to higher rates */
775                         if (fabs(arb_sampling_rate - sr) <= 0.001) {
776                                 arb_sampling_rate = sr;
777                                 break;
778                         }
779
780                         /*
781                          * If we reached a higher value than the desired rate, adjust selected rate so it matches the first higher available one and
782                          * stop parsing - this makes the assumption that rates are sorted by increasing value in the allowed frequencies string.
783                          */
784                         if (sr > arb_sampling_rate) {
785                                 arb_sampling_rate = sr;
786                                 break;
787                         }
788
789                         /* Skip digits */
790                         while (cursor[0] && !isspace(cursor[0]))
791                                 cursor++;
792
793                         /* Skip spaces */
794                         while (cursor[0] && isspace(cursor[0]))
795                                         cursor++;
796                 }
797         }
798
799         if (sensor[s].max_supported_rate &&
800                 arb_sampling_rate > sensor[s].max_supported_rate) {
801                 arb_sampling_rate = sensor[s].max_supported_rate;
802         }
803
804         /* Coordinate with others active sensors on the same device, if any */
805         if (per_device_sampling_rate)
806                 for (n=0; n<sensor_count; n++)
807                         if (n != s && sensor[n].dev_num == dev_num && sensor[n].num_channels && is_enabled(n) && sensor[n].sampling_rate > arb_sampling_rate) {
808                                 ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n", sensor[s].friendly_name, sensor[n].friendly_name,
809                                                                                                           sensor[n].sampling_rate, arb_sampling_rate);
810                                 arb_sampling_rate = sensor[n].sampling_rate;
811                         }
812
813         sensor[s].sampling_rate = arb_sampling_rate;
814
815         /* Update actual sampling rate field for this sensor and others which may be sharing the same sampling rate */
816         if (per_device_sampling_rate)
817                 for (n=0; n<sensor_count; n++)
818                         if (sensor[n].dev_num == dev_num && n != s && sensor[n].num_channels)
819                                 sensor[n].sampling_rate = arb_sampling_rate;
820
821         /* If the desired rate is already active we're all set */
822         if (arb_sampling_rate == cur_sampling_rate)
823                 return 0;
824
825         ALOGI("Sensor %d (%s) sampling rate set to %g\n", s, sensor[s].friendly_name, arb_sampling_rate);
826
827         if (trig_sensors_per_dev[dev_num])
828                 enable_buffer(dev_num, 0);
829
830         sysfs_write_float(sysfs_path, arb_sampling_rate);
831
832         /* Check if it makes sense to use an alternate trigger */
833         tentative_switch_trigger(s);
834
835         if (trig_sensors_per_dev[dev_num])
836                 enable_buffer(dev_num, 1);
837
838         return 0;
839 }
840
841
842 static void reapply_sampling_rates (int s)
843 {
844         /*
845          * The specified sensor was either enabled or disabled. Other sensors in the same group may have constraints related to this sensor
846          * sampling rate on their own sampling rate, so reevaluate them by retrying to use their requested sampling rate, rather than the one
847          * that ended up being used after arbitration.
848          */
849
850         int i, j, base;
851
852         if (sensor[s].is_virtual) {
853                 /* Take care of downwards dependencies */
854                 for (i=0; i<sensor[s].base_count; i++) {
855                         base = sensor[s].base[i];
856                         sensor_set_rate(base, sensor[base].requested_rate);
857                 }
858                 return;
859         }
860
861         /* Upwards too */
862         for (i=0; i<sensor_count; i++)
863                 for (j=0; j<sensor[i].base_count; j++)
864                         if (sensor[i].base[j] == s) /* If sensor i depends on sensor s */
865                                 sensor_set_rate(i, sensor[i].requested_rate);
866 }
867
868
869 static int sensor_activate_virtual (int s, int enabled, int from_virtual)
870 {
871         int i, base;
872
873         sensor[s].event_count = 0;
874         sensor[s].meta_data_pending = 0;
875
876         if (!check_state_change(s, enabled, from_virtual))
877                 return 0;       /* The state of the sensor remains the same ; we're done */
878
879         if (enabled)
880                 ALOGI("Enabling sensor %d (%s)\n", s, sensor[s].friendly_name);
881         else
882                 ALOGI("Disabling sensor %d (%s)\n", s, sensor[s].friendly_name);
883
884         sensor[s].report_pending = 0;
885
886         for (i=0; i<sensor[s].base_count; i++) {
887
888                 base = sensor[s].base[i];
889                 sensor_activate(base, enabled, 1);
890
891                 if (enabled)
892                         sensor[base].ref_count++;
893                 else
894                         sensor[base].ref_count--;
895         }
896
897         /* Reevaluate sampling rates of linked sensors */
898         reapply_sampling_rates(s);
899         return 0;
900 }
901
902
903 int sensor_activate (int s, int enabled, int from_virtual)
904 {
905         char device_name[PATH_MAX];
906         struct epoll_event ev = {0};
907         int dev_fd;
908         int ret;
909         int dev_num = sensor[s].dev_num;
910
911         if (sensor[s].is_virtual)
912                 return sensor_activate_virtual(s, enabled, from_virtual);
913
914         /* Prepare the report timestamp field for the first event, see set_report_ts method */
915         sensor[s].report_ts = 0;
916
917         ret = adjust_counters(s, enabled, from_virtual);
918
919         /* If the operation was neutral in terms of state, we're done */
920         if (ret <= 0)
921                 return ret;
922
923         sensor[s].event_count = 0;
924         sensor[s].meta_data_pending = 0;
925
926         if (enabled)
927                 setup_noise_filtering(s);       /* Initialize filtering data if required */
928
929         if (!sensor[s].is_polling) {
930
931                 /* Stop sampling */
932                 enable_buffer(dev_num, 0);
933                 setup_trigger(s, "\n");
934
935                 /* If there's at least one sensor enabled on this iio device */
936                 if (trig_sensors_per_dev[dev_num]) {
937
938                         /* Start sampling */
939                         setup_trigger(s, sensor[s].init_trigger_name);
940                         enable_buffer(dev_num, 1);
941                 }
942         }
943
944         /*
945          * Make sure we have a fd on the character device ; conversely, close the fd if no one is using associated sensors anymore. The assumption
946          * here is that the underlying driver will power on the relevant hardware block while someone holds a fd on the device.
947          */
948         dev_fd = device_fd[dev_num];
949
950         if (!enabled) {
951                 if (sensor[s].is_polling)
952                         stop_acquisition_thread(s);
953
954                 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] && !trig_sensors_per_dev[dev_num]) {
955                                 /* Stop watching this fd. This should be a no-op in case this fd was not in the poll set. */
956                                 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
957
958                                 close(dev_fd);
959                                 device_fd[dev_num] = -1;
960                 }
961
962                 /* Release any filtering data we may have accumulated */
963                 release_noise_filtering_data(s);
964
965                 /* Reevaluate sampling rates of linked sensors */
966                 reapply_sampling_rates(s);
967                 return 0;
968         }
969
970         if (dev_fd == -1) {
971                 /* First enabled sensor on this iio device */
972                 sprintf(device_name, DEV_FILE_PATH, dev_num);
973                 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
974
975                 device_fd[dev_num] = dev_fd;
976
977                 if (dev_fd == -1) {
978                         ALOGE("Could not open fd on %s (%s)\n", device_name, strerror(errno));
979                         adjust_counters(s, 0, from_virtual);
980                         return -1;
981                 }
982
983                 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
984
985                 if (!sensor[s].is_polling) {
986
987                         /* Add this iio device fd to the set of watched fds */
988                         ev.events = EPOLLIN;
989                         ev.data.u32 = dev_num;
990
991                         ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
992
993                         if (ret == -1) {
994                                 ALOGE("Failed adding %d to poll set (%s)\n", dev_fd, strerror(errno));
995                                 return -1;
996                         }
997
998                         /* Note: poll-mode fds are not readable */
999                 }
1000         }
1001
1002         /* Ensure that on-change sensors send at least one event after enable */
1003         sensor[s].prev_val = -1;
1004
1005         if (sensor[s].is_polling)
1006                 start_acquisition_thread(s);
1007
1008         /* Reevaluate sampling rates of linked sensors */
1009         reapply_sampling_rates(s);
1010
1011         return 0;
1012 }
1013
1014
1015 static void enable_motion_trigger (int dev_num)
1016 {
1017         /*
1018          * In the ideal case, we enumerate two triggers per iio device ; the default (periodically firing) trigger, and another one (the motion
1019          * trigger) that only fires up when motion is detected. This second one allows for lesser energy consumption, but requires periodic sample
1020          * duplication at the HAL level for sensors that Android defines as continuous. This "duplicate last sample" logic can only be engaged
1021          * once we got a first sample for the driver, so we start with the default trigger when an iio device is first opened, then adjust the
1022          * trigger when we got events for all active sensors. Unfortunately in the general case several sensors can be associated to a given iio
1023          * device, they can independently be controlled, and we have to adjust the trigger in use at the iio device level depending on whether or
1024          * not appropriate conditions are met at the sensor level.
1025          */
1026
1027         int s;
1028         int i;
1029         int active_sensors = trig_sensors_per_dev[dev_num];
1030         int candidate[MAX_SENSORS];
1031         int candidate_count = 0;
1032
1033         if  (!active_sensors)
1034                 return;
1035
1036         /* Check that all active sensors are ready to switch */
1037
1038         for (s=0; s<MAX_SENSORS; s++)
1039                 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels &&
1040                     (!sensor[s].motion_trigger_name[0] || !sensor[s].report_initialized || is_fast_accelerometer(s) ||
1041                      (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS)))
1042                         return; /* Nope */
1043
1044         /* Record which particular sensors need to switch */
1045
1046         for (s=0; s<MAX_SENSORS; s++)
1047                 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels && sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1048                                 candidate[candidate_count++] = s;
1049
1050         if (!candidate_count)
1051                 return;
1052
1053         /* Now engage the motion trigger for sensors which aren't using it */
1054
1055         enable_buffer(dev_num, 0);
1056
1057         for (i=0; i<candidate_count; i++) {
1058                 s = candidate[i];
1059                 setup_trigger(s, sensor[s].motion_trigger_name);
1060         }
1061
1062         enable_buffer(dev_num, 1);
1063 }
1064
1065 static void stamp_reports (int dev_num, int64_t ts)
1066 {
1067         int s;
1068
1069         for (s=0; s<MAX_SENSORS; s++)
1070                 if (sensor[s].dev_num == dev_num && is_enabled(s) && !sensor[s].is_polling)
1071                         set_report_ts(s, ts);
1072 }
1073
1074
1075 static int integrate_device_report (int dev_num)
1076 {
1077         int len;
1078         int s,c;
1079         unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1080         int sr_offset;
1081         unsigned char *target;
1082         unsigned char *source;
1083         int size;
1084         int64_t ts = 0;
1085         int ts_offset = 0;      /* Offset of iio timestamp, if provided */
1086         int64_t boot_to_rt_delta;
1087
1088         /* There's an incoming report on the specified iio device char dev fd */
1089
1090         if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1091                 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1092                 return -1;
1093         }
1094
1095         if (device_fd[dev_num] == -1) {
1096                 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1097                 return -1;
1098         }
1099
1100         len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]);
1101
1102         if (len == -1) {
1103                 ALOGE("Could not read report from iio device %d (%s)\n", dev_num, strerror(errno));
1104                 return -1;
1105         }
1106
1107         ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1108
1109         /* Map device report to sensor reports */
1110
1111         for (s=0; s<MAX_SENSORS; s++)
1112                 if (sensor[s].dev_num == dev_num && is_enabled(s)) {
1113
1114                         sr_offset = 0;
1115
1116                         /* Copy data from device to sensor report buffer */
1117                         for (c=0; c<sensor[s].num_channels; c++) {
1118
1119                                 target = sensor[s].report_buffer + sr_offset;
1120
1121                                 source = buf + sensor[s].channel[c].offset;
1122
1123                                 size = sensor[s].channel[c].size;
1124
1125                                 memcpy(target, source, size);
1126
1127                                 sr_offset += size;
1128                         }
1129
1130                         ALOGV("Sensor %d report available (%d bytes)\n", s, sr_offset);
1131
1132                         sensor[s].report_pending = DATA_TRIGGER;
1133                         sensor[s].report_initialized = 1;
1134
1135                         ts_offset += sr_offset;
1136                 }
1137
1138         /* Tentatively switch to an any-motion trigger if conditions are met */
1139         enable_motion_trigger(dev_num);
1140
1141         /* If no iio timestamp channel was detected for this device, bail out */
1142         if (!has_iio_ts[dev_num]) {
1143                 stamp_reports(dev_num, get_timestamp_boot());
1144                 return 0;
1145         }
1146
1147         /* Don't trust the timestamp channel in any-motion mode */
1148         for (s=0; s<MAX_SENSORS; s++)
1149                 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name) {
1150                         stamp_reports(dev_num, get_timestamp_boot());
1151                         return 0;
1152                 }
1153
1154         /* Align on a 64 bits boundary */
1155         ts_offset = expected_dev_report_size[dev_num] - sizeof(int64_t);
1156
1157         /* If we read an amount of data consistent with timestamp presence */
1158         if (len == expected_dev_report_size[dev_num])
1159                 ts = *(int64_t*) (buf + ts_offset);
1160
1161         if (ts == 0) {
1162                 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1163                 stamp_reports(dev_num, get_timestamp_boot());
1164                 return 0;
1165         }
1166
1167         ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1168
1169         boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1170
1171         stamp_reports(dev_num, ts + boot_to_rt_delta);
1172
1173         return 0;
1174 }
1175
1176
1177 static int propagate_vsensor_report (int s, sensors_event_t *data)
1178 {
1179         /* There's a new report stored in sensor.sample for this sensor; transmit it */
1180
1181         memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1182
1183         data->sensor    = s;
1184         data->type      = sensor[s].type;
1185         return 1;
1186 }
1187
1188
1189 static int propagate_sensor_report (int s, sensors_event_t *data)
1190 {
1191         /* There's a sensor report pending for this sensor ; transmit it */
1192
1193         int num_fields    = get_field_count(s);
1194         int c;
1195         unsigned char* current_sample;
1196         int ret;
1197
1198         /* If there's nothing to return... we're done */
1199         if (!num_fields)
1200                 return 0;
1201
1202         ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1203
1204         if (sensor[s].is_polling) {
1205                 /* We received a good sample but we're not directly enabled so we'll drop */
1206                 if (!sensor[s].directly_enabled)
1207                         return 0;
1208                 /* Use the data provided by the acquisition thread */
1209                 ALOGV("Reporting data from worker thread for S%d\n", s);
1210                 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1211                 data->timestamp = sensor[s].report_ts;
1212                 return 1;
1213         }
1214
1215         memset(data, 0, sizeof(sensors_event_t));
1216
1217         data->version   = sizeof(sensors_event_t);
1218         data->sensor    = s;
1219         data->type      = sensor[s].type;
1220         data->timestamp = sensor[s].report_ts;
1221
1222         /* Convert the data into the expected Android-level format */
1223
1224         current_sample = sensor[s].report_buffer;
1225
1226         for (c=0; c<num_fields; c++) {
1227
1228                 data->data[c] = sensor[s].ops.transform (s, c, current_sample);
1229
1230                 ALOGV("\tfield %d: %g\n", c, data->data[c]);
1231                 current_sample += sensor[s].channel[c].size;
1232         }
1233
1234         ret = sensor[s].ops.finalize(s, data);
1235
1236         /* We will drop samples if the sensor is not directly enabled */
1237         if (!sensor[s].directly_enabled)
1238                 return 0;
1239
1240         /* The finalize routine, in addition to its late sample processing duty, has the final say on whether or not the sample gets sent to Android */
1241         return ret;
1242 }
1243
1244
1245 static void synthetize_duplicate_samples (void)
1246 {
1247         /*
1248          * Some sensor types (ex: gyroscope) are defined as continuously firing by Android, despite the fact that
1249          * we can be dealing with iio drivers that only report events for new samples. For these we generate reports
1250          * periodically, duplicating the last data we got from the driver. This is not necessary for polling sensors.
1251          */
1252
1253         int s;
1254         int64_t current_ts;
1255         int64_t target_ts;
1256         int64_t period;
1257
1258         for (s=0; s<sensor_count; s++) {
1259
1260                 /* Ignore disabled sensors */
1261                 if (!is_enabled(s))
1262                         continue;
1263
1264                 /* If the sensor is continuously firing, leave it alone */
1265                 if (sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1266                         continue;
1267
1268                 /* If we haven't seen a sample, there's nothing to duplicate */
1269                 if (!sensor[s].report_initialized)
1270                         continue;
1271
1272                 /* If a sample was recently buffered, leave it alone too */
1273                 if (sensor[s].report_pending)
1274                         continue;
1275
1276                 /* We also need a valid sampling rate to be configured */
1277                 if (!sensor[s].sampling_rate)
1278                         continue;
1279
1280                 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1281
1282                 current_ts = get_timestamp_boot();
1283                 target_ts = sensor[s].report_ts + period;
1284
1285                 if (target_ts <= current_ts) {
1286                         /* Mark the sensor for event generation */
1287                         set_report_ts(s, current_ts);
1288                         sensor[s].report_pending = DATA_DUPLICATE;
1289                 }
1290         }
1291 }
1292
1293
1294 static void integrate_thread_report (uint32_t tag)
1295 {
1296         int s = tag - THREAD_REPORT_TAG_BASE;
1297         int len;
1298
1299         len = read(sensor[s].thread_data_fd[0], &sensor[s].sample, sizeof(sensors_event_t));
1300
1301         if (len == sizeof(sensors_event_t))
1302                 sensor[s].report_pending = DATA_SYSFS;
1303 }
1304
1305
1306 static int get_poll_wait_timeout (void)
1307 {
1308         /*
1309          * Compute an appropriate timeout value, in ms, for the epoll_wait call that's going to await
1310          * for iio device reports and incoming reports from our sensor sysfs data reader threads.
1311          */
1312
1313         int s;
1314         int64_t target_ts = INT64_MAX;
1315         int64_t ms_to_wait;
1316         int64_t period;
1317
1318         /*
1319          * Check if we're dealing with a driver that only send events when there is motion, despite the fact that the associated Android sensor
1320          * type is continuous rather than on-change. In that case we have to duplicate events. Check deadline for the nearest upcoming event.
1321          */
1322         for (s=0; s<sensor_count; s++)
1323                 if (is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name && sensor[s].sampling_rate) {
1324                         period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1325
1326                         if (sensor[s].report_ts + period < target_ts)
1327                                 target_ts = sensor[s].report_ts + period;
1328                 }
1329
1330         /* If we don't have such a driver to deal with */
1331         if (target_ts == INT64_MAX)
1332                 return -1; /* Infinite wait */
1333
1334         ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1335
1336         /* If the target timestamp is already behind us, don't wait */
1337         if (ms_to_wait < 1)
1338                 return 0;
1339
1340         return ms_to_wait;
1341 }
1342
1343
1344 int sensor_poll (sensors_event_t* data, int count)
1345 {
1346         int s;
1347         int i;
1348         int nfds;
1349         struct epoll_event ev[MAX_DEVICES];
1350         int returned_events;
1351         int event_count;
1352
1353         /* Get one or more events from our collection of sensors */
1354 return_available_sensor_reports:
1355
1356         /* Synthetize duplicate samples if needed */
1357         synthetize_duplicate_samples();
1358
1359         returned_events = 0;
1360
1361         /* Check our sensor collection for available reports */
1362         for (s=0; s<sensor_count && returned_events < count; s++) {
1363
1364                 if (sensor[s].report_pending) {
1365                         event_count = 0;
1366
1367                         if (sensor[s].is_virtual)
1368                                 event_count = propagate_vsensor_report(s, &data[returned_events]);
1369                         else
1370                                 /* Report this event if it looks OK */
1371                                 event_count = propagate_sensor_report(s, &data[returned_events]);
1372
1373                         /* Lower flag */
1374                         sensor[s].report_pending = 0;
1375                         returned_events += event_count;
1376
1377                         /*
1378                          * If the sample was deemed invalid or unreportable, e.g. had the same value as the previously reported
1379                          * value for a 'on change' sensor, silently drop it.
1380                          */
1381                 }
1382
1383                 while (sensor[s].meta_data_pending) {
1384                         /* See sensors.h on these */
1385                         data[returned_events].version = META_DATA_VERSION;
1386                         data[returned_events].sensor = 0;
1387                         data[returned_events].type = SENSOR_TYPE_META_DATA;
1388                         data[returned_events].reserved0 = 0;
1389                         data[returned_events].timestamp = 0;
1390                         data[returned_events].meta_data.sensor = s;
1391                         data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1392                         returned_events++;
1393                         sensor[s].meta_data_pending--;
1394                 }
1395         }
1396
1397         if (returned_events)
1398                 return returned_events;
1399
1400 await_event:
1401
1402         ALOGV("Awaiting sensor data\n");
1403
1404         nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1405
1406         if (nfds == -1) {
1407                 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1408                 goto await_event;
1409         }
1410
1411         ALOGV("%d fds signalled\n", nfds);
1412
1413         /* For each of the signalled sources */
1414         for (i=0; i<nfds; i++)
1415                 if (ev[i].events == EPOLLIN)
1416                         switch (ev[i].data.u32) {
1417                                 case 0 ... MAX_DEVICES-1:
1418                                         /* Read report from iio char dev fd */
1419                                         integrate_device_report(ev[i].data.u32);
1420                                         break;
1421
1422                                 case THREAD_REPORT_TAG_BASE ...
1423                                      THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1424                                         /* Get report from acquisition thread */
1425                                         integrate_thread_report(ev[i].data.u32);
1426                                         break;
1427
1428                                 default:
1429                                         ALOGW("Unexpected event source!\n");
1430                                         break;
1431                         }
1432
1433         goto return_available_sensor_reports;
1434 }
1435
1436
1437 int sensor_set_delay (int s, int64_t ns)
1438 {
1439         float requested_sampling_rate;
1440
1441         if (ns <= 0) {
1442                 ALOGE("Invalid delay requested on sensor %d: %lld\n", s, ns);
1443                 return -EINVAL;
1444         }
1445
1446         requested_sampling_rate = 1000000000.0 / ns;
1447
1448         ALOGV("Entering set delay S%d (%s): current rate: %g, requested: %g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate, requested_sampling_rate);
1449
1450         /*
1451          * Only try to adjust the low level sampling rate if it's different from the current one, as set by the HAL. This saves a few sysfs
1452          * reads and writes as well as buffer enable/disable operations, since at the iio level most drivers require the buffer to be turned off
1453          * in order to accept a sampling rate change. Of course that implies that this field has to be kept up to date and that only this library
1454          * is changing the sampling rate.
1455          */
1456
1457         if (requested_sampling_rate != sensor[s].sampling_rate)
1458                 return sensor_set_rate(s, requested_sampling_rate);
1459
1460         return 0;
1461 }
1462
1463
1464 int sensor_flush (int s)
1465 {
1466         /* If one shot or not enabled return -EINVAL */
1467         if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1468                 return -EINVAL;
1469
1470         sensor[s].meta_data_pending++;
1471         return 0;
1472 }
1473
1474
1475 int allocate_control_data (void)
1476 {
1477         int i;
1478
1479         for (i=0; i<MAX_DEVICES; i++)
1480                 device_fd[i] = -1;
1481
1482         poll_fd = epoll_create(MAX_DEVICES);
1483
1484         if (poll_fd == -1) {
1485                 ALOGE("Can't create epoll instance for iio sensors!\n");
1486                 return -1;
1487         }
1488
1489         return poll_fd;
1490 }
1491
1492
1493 void delete_control_data (void)
1494 {
1495 }