OSDN Git Service

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