OSDN Git Service

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