OSDN Git Service

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