OSDN Git Service

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