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