OSDN Git Service

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