OSDN Git Service

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