OSDN Git Service

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