OSDN Git Service

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