OSDN Git Service

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