OSDN Git Service

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