OSDN Git Service

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