OSDN Git Service

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