OSDN Git Service

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