OSDN Git Service

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