OSDN Git Service

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