OSDN Git Service

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