OSDN Git Service

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