OSDN Git Service

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