OSDN Git Service

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