OSDN Git Service

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