OSDN Git Service

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