OSDN Git Service

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