OSDN Git Service

STPK-1429 Unblock poll loop when a sensor gets enabled
[android-x86/hardware-intel-libsensors.git] / control.c
1 /*
2  * Copyright (C) 2014 Intel Corporation.
3  */
4
5 #include <fcntl.h>
6 #include <sys/epoll.h>
7 #include <sys/socket.h>
8 #include <utils/Log.h>
9 #include <hardware/sensors.h>
10 #include "control.h"
11 #include "enumeration.h"
12 #include "utils.h"
13 #include "transform.h"
14
15 /* Currently active sensors count, per device */
16 static int poll_sensors_per_dev[MAX_DEVICES];   /* poll-mode sensors */
17 static int trig_sensors_per_dev[MAX_DEVICES];   /* trigger, event based */
18
19 static int device_fd[MAX_DEVICES];   /* fd on the /dev/iio:deviceX file */
20
21 static int poll_fd; /* epoll instance covering all enabled sensors */
22
23 static int poll_socket_pair[2]; /* used to unblock the poll loop */
24
25 /* Timestamp for the moment when we last exited a poll operation */
26 static int64_t last_poll_exit_ts;
27
28 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
29
30 /* Cap the time between poll operations to this, to counter runaway polls */
31 #define POLL_MIN_INTERVAL 10000 /* uS */
32
33 #define INVALID_DEV_NUM ((uint32_t) -1)
34
35
36 static int enable_buffer(int dev_num, int enabled)
37 {
38         char sysfs_path[PATH_MAX];
39
40         sprintf(sysfs_path, ENABLE_PATH, dev_num);
41
42         /* Low level, non-multiplexed, enable/disable routine */
43         return sysfs_write_int(sysfs_path, enabled);
44 }
45
46
47 static int setup_trigger(int dev_num, const char* trigger_val)
48 {
49         char sysfs_path[PATH_MAX];
50
51         sprintf(sysfs_path, TRIGGER_PATH, dev_num);
52
53         return sysfs_write_str(sysfs_path, trigger_val);
54 }
55
56
57 static void refresh_sensor_report_maps(int dev_num)
58 {
59         /*
60          * Read sysfs files from a iio device's scan_element directory, and
61          * build a couple of tables from that data. These tables will tell, for
62          * each sensor, where to gather relevant data in a device report, i.e.
63          * the structure that we read from the /dev/iio:deviceX file in order to
64          * sensor report, itself being the data that we return to Android when a
65          * sensor poll completes. The mapping should be straightforward in the
66          * case where we have a single sensor active per iio device but, this is
67          * not the general case. In general several sensors can be handled
68          * through a single iio device, and the _en, _index and _type syfs
69          * entries all concur to paint a picture of what the structure of the
70          * device report is.
71          */
72
73         int s;
74         int c;
75         int n;
76         int i;
77         int ch_enabled;
78         int ch_index;
79         char* ch_spec;
80         char spec_buf[MAX_TYPE_SPEC_LEN];
81         struct datum_info_t* ch_info;
82         int size;
83         char sysfs_path[PATH_MAX];
84         int active_channels;
85         int offset;
86         int channel_count;
87         int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
88         int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
89         int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
90
91         active_channels = 0;
92
93         /* For each sensor that is linked to this device */
94         for (s=0; s<sensor_count; s++) {
95                 if (sensor_info[s].dev_num != dev_num)
96                         continue;
97
98                 i = sensor_info[s].catalog_index;
99
100                 /* Read channel status through syfs attributes */
101                 for (c=0; c<sensor_info[s].num_channels; c++) {
102
103                         /* Read _en file */
104                         sprintf(sysfs_path, CHANNEL_PATH "%s",
105                                 sensor_info[s].dev_num,
106                                 sensor_catalog[i].channel[c].en_path);
107
108                         n = sysfs_read_int(sysfs_path, &ch_enabled);
109
110                         if (n == -1) {
111                                 ALOGW(  "Failed to read _en flag: %s\n",
112                                 sysfs_path);
113                                 continue;
114                         }
115
116                         if (!ch_enabled != 1) {
117                                 sensor_info[s].channel[c].size = 0;
118                         }
119
120                         /* Read _type file */
121                         sprintf(sysfs_path, CHANNEL_PATH "%s",
122                                 sensor_info[s].dev_num,
123                                 sensor_catalog[i].channel[c].type_path);
124
125                         n = sysfs_read_str(sysfs_path, spec_buf, 
126                                                 sizeof(spec_buf));
127
128                         if (n == -1) {
129                                         ALOGW(  "Failed to read type: %s\n",
130                                         sysfs_path);
131                                         continue;
132                                 }
133
134                         ch_spec = sensor_info[s].channel[c].type_spec;
135
136                         memcpy(ch_spec, spec_buf, sizeof(spec_buf));
137
138                         ch_info = &sensor_info[s].channel[c].type_info;
139
140                         size = decode_type_spec(ch_spec, ch_info);
141
142                         /* Read _index file */
143                         sprintf(sysfs_path, CHANNEL_PATH "%s",
144                                 sensor_info[s].dev_num,
145                                 sensor_catalog[i].channel[c].index_path);
146
147                         n = sysfs_read_int(sysfs_path, &ch_index);
148
149                         if (n == -1) {
150                                         ALOGW(  "Failed to read index: %s\n",
151                                                 sysfs_path);
152                                         continue;
153                                 }
154
155                         if (ch_index >= MAX_SENSORS) {
156                                 ALOGE("Index out of bounds!: %s\n", sysfs_path);
157                                 continue;
158                         }
159
160                         /* Record what this index is about */
161
162                         sensor_handle_from_index [ch_index] = s;
163                         channel_number_from_index[ch_index] = c;
164                         channel_size_from_index  [ch_index] = size;
165
166                         active_channels++;
167                 }
168         }
169
170         ALOGI("Found %d enabled channels for iio device %d\n", active_channels,
171                 dev_num);
172
173         /*
174          * Now that we know which channels are enabled, their sizes and their
175          * ordering, update channels offsets within device report. Note: there
176          * is a possibility that several sensors share the same index, with
177          * their data fields being isolated by masking and shifting as specified
178          * through the real bits and shift values in type attributes. This case
179          * is not currently supported. Also, the code below assumes no hole in
180          * the sequence of indices, so it is dependent on discovery of all
181          * sensors.
182          */
183          offset = 0;
184          for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
185                 s =     sensor_handle_from_index[i];
186                 c =     channel_number_from_index[i];
187                 size =  channel_size_from_index[i];
188
189                 if (!size)
190                         continue;
191
192                 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
193                       s, c, offset, size, sensor_info[s].channel[c].type_spec);
194
195                 sensor_info[s].channel[c].offset        = offset;
196                 sensor_info[s].channel[c].size          = size;
197
198                 offset += size;
199          }
200 }
201
202
203 int adjust_counters (int s, int enabled)
204 {
205         /*
206          * Adjust counters based on sensor enable action. Return values are:
207          * -1 if there's an inconsistency: abort action in this case
208          *  0 if the operation was completed and we're all set
209          *  1 if we toggled the state of the sensor and there's work left
210          */
211
212         int dev_num = sensor_info[s].dev_num;
213
214         /* Refcount per sensor, in terms of enable count */
215         if (enabled) {
216                 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
217                         s, dev_num, sensor_info[s].internal_name);
218
219                 sensor_info[s].enable_count++;
220
221                 if (sensor_info[s].enable_count != 1)
222                         return 0; /* The sensor was, and remains, in use */
223         } else {
224                 if (sensor_info[s].enable_count == 0)
225                         return -1; /* Spurious disable call */
226
227                 ALOGI("Disabling sensor %d (iio device %d)\n", s, dev_num);
228
229                 sensor_info[s].enable_count--;
230
231                 if (sensor_info[s].enable_count > 0)
232                         return 0; /* The sensor was, and remains, in use */
233
234                 /* Sensor disabled, clear up pending data */
235
236                 sensor_info[s].report_pending = 0;
237                 memset(sensor_info[s].report_buffer, 0, MAX_SENSOR_REPORT_SIZE);
238         }
239
240         /* We changed the state of a sensor - adjust per iio device counters */
241
242         /* If this is a regular event-driven sensor */
243         if (sensor_info[s].num_channels) {
244
245                         if (enabled)
246                                 trig_sensors_per_dev[dev_num]++;
247                         else
248                                 trig_sensors_per_dev[dev_num]--;
249
250                         return 1;
251                 }
252
253         if (enabled) {
254                 active_poll_sensors++;
255                 poll_sensors_per_dev[dev_num]++;
256                 return 1;
257         }
258
259         active_poll_sensors--;
260         poll_sensors_per_dev[dev_num]--;
261         return 1;
262 }
263
264
265 int sensor_activate(int s, int enabled)
266 {
267         char sysfs_path[PATH_MAX];
268         char device_name[PATH_MAX];
269         char trigger_name[MAX_NAME_SIZE + 16];
270         int c;
271         struct epoll_event ev = {0};
272         int dev_fd;
273         int ret;
274         int dev_num = sensor_info[s].dev_num;
275         int i = sensor_info[s].catalog_index;
276         int is_poll_sensor = !sensor_info[s].num_channels;
277
278         ret = adjust_counters(s, enabled);
279
280         /* If the operation was neutral in terms of state, we're done */
281         if (ret <= 0)
282                 return ret;
283
284         if (!is_poll_sensor) {
285                 /* Changes have to be made while the buffer is turned off */
286                 enable_buffer(dev_num, 0);
287
288                 /* Configure trigger */
289                 switch (trig_sensors_per_dev[dev_num]) {
290                         case 0:
291                                 setup_trigger(dev_num, "none");
292                                 break;
293
294                         case 1:
295                                 sprintf(trigger_name, "%s-dev%d",
296                                         sensor_info[s].internal_name, dev_num);
297
298                                 setup_trigger(dev_num, trigger_name);
299                                 break;
300
301                         default:
302                                 /* The trigger is already set */
303                                 break;
304                 }
305
306                 /*
307                  * Turn channels associated to this sensor on or off, and update
308                  * the channels maps for all sensors associated to this device.
309                  */
310                 for (c=0;c<sensor_info[s].num_channels; c++) {
311                         sprintf(sysfs_path, CHANNEL_PATH "%s",
312                                 sensor_info[s].dev_num,
313                                 sensor_catalog[i].channel[c].en_path);
314
315                         sysfs_write_int(sysfs_path, enabled);
316                 }
317
318                 /* If there's at least one sensor left */
319                 if (trig_sensors_per_dev[dev_num]) {
320                         refresh_sensor_report_maps(dev_num);
321                         enable_buffer(dev_num, 1);
322                 }
323         }
324
325         /*
326          * Make sure we have a fd on the character device ; conversely, close
327          * the fd if no one is using associated sensor anymore. The assumption
328          * here is that the underlying driver will power on the relevant
329          * hardware block while someone hold a fd on the device.
330          */
331         dev_fd = device_fd[dev_num];
332
333         if (!enabled) {
334                 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
335                         !trig_sensors_per_dev[dev_num]) {
336                                 /*
337                                  * Stop watching this fd. This should be a no-op
338                                  * in case this fd was not in the poll set.
339                                  */
340                                 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
341
342                                 close(dev_fd);
343                                 device_fd[dev_num] = -1;
344                         }
345                 return 0;
346         }
347
348         if (dev_fd == -1) {
349                 /* First enabled sensor on this iio device */
350                 sprintf(device_name, DEV_FILE_PATH, dev_num);
351                 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
352
353                 device_fd[dev_num] = dev_fd;
354
355                 if (dev_fd == -1) {
356                         ALOGE("Could not open fd on %s (%s)\n",
357                               device_name, strerror(errno));
358                         adjust_counters(s, 0);
359                         return -1;
360                 }
361
362                 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
363
364                 if (!is_poll_sensor) {
365
366                         /* Add this iio device fd to the set of watched fds */
367                         ev.events = EPOLLIN;
368                         ev.data.u32 = dev_num;
369
370                         ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
371
372                         if (ret == -1) {
373                                 ALOGE(  "Failed adding %d to poll set (%s)\n",
374                                         dev_fd, strerror(errno));
375                                 return -1;
376                         }
377
378                         /* Note: poll-mode fds are not readable */
379                 }
380         }
381
382         /* Release the polling loop so an updated timeout gets used */
383         write(poll_socket_pair[1], "", 1);
384
385         return 0;
386 }
387
388
389 static int integrate_device_report(int dev_num)
390 {
391         int len;
392         int s,c;
393         unsigned char buf[MAX_SENSOR_REPORT_SIZE * MAX_SENSORS] = { 0 };
394         int sr_offset;
395         unsigned char *target;
396         unsigned char *source;
397         int size;
398         int expected_size = 0;
399
400         /* There's an incoming report on the specified fd */
401
402         if (dev_num < 0 || dev_num >= MAX_DEVICES ||
403                 !trig_sensors_per_dev[dev_num]) {
404                 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
405                 return -1;
406         }
407
408         for (s=0; s<MAX_SENSORS; s++)
409                 if (sensor_info[s].dev_num == dev_num)
410                         for (c=0; c<sensor_info[s].num_channels; c++)
411                                 expected_size += sensor_info[s].channel[c].size;
412
413         len = read(device_fd[dev_num], buf, expected_size);
414
415         if (len == -1) {
416                 ALOGE("Could not read report from iio device %d (%s)\n",
417                       dev_num, strerror(errno));
418                 return -1;
419         }
420
421         ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
422
423         for (s=0; s<MAX_SENSORS; s++)
424                 if (sensor_info[s].dev_num == dev_num) {
425                         sr_offset = 0;
426
427                         /* Copy data from device to sensor report buffer */
428                         for (c=0; c<sensor_info[s].num_channels; c++) {
429
430                                 target = sensor_info[s].report_buffer +
431                                         sr_offset;
432
433                                 source = buf + sensor_info[s].channel[c].offset;
434
435                                 size = sensor_info[s].channel[c].size;
436
437                                 memcpy(target, source, size);
438
439                                 sr_offset += size;
440                         }
441
442                         if (sensor_info[s].enable_count) {
443                                 ALOGV("Sensor %d report available (%d bytes)\n",
444                                       s, sr_offset);
445
446                                 sensor_info[s].report_pending = 1;
447                         }
448                 }
449
450         return 0;
451 }
452
453
454 static float acquire_immediate_value(int s, int c)
455 {
456         char sysfs_path[PATH_MAX];
457         float val;
458         int ret;
459         int dev_num = sensor_info[s].dev_num;
460         int i = sensor_info[s].catalog_index;
461         const char* raw_path = sensor_catalog[i].channel[c].raw_path;
462         const char* input_path = sensor_catalog[i].channel[c].input_path;
463         float scale = sensor_info[s].scale;
464         float offset = sensor_info[s].offset;
465
466         /* Acquire a sample value for sensor s / channel c through sysfs */
467
468         if (input_path[0]) {
469                 sprintf(sysfs_path, BASE_PATH "%s", dev_num, input_path);
470                 ret = sysfs_read_float(sysfs_path, &val);
471
472                 if (!ret) {
473                         return val;
474                 }
475         };
476
477         if (!raw_path[0])
478                 return 0;
479
480         sprintf(sysfs_path, BASE_PATH "%s", dev_num, raw_path);
481         ret = sysfs_read_float(sysfs_path, &val);
482
483         if (ret == -1)
484                 return 0;
485
486         return (val + offset) * scale;
487 }
488
489
490 static void propagate_sensor_report(int s, struct sensors_event_t* data)
491 {
492         /* There's a sensor report pending for this sensor ; transmit it */
493
494         int catalog_index = sensor_info[s].catalog_index;
495         int sensor_type = sensor_catalog[catalog_index].type;
496         int num_fields;
497         int c;
498         unsigned char* current_sample;
499
500         memset(data, 0, sizeof(sensors_event_t));
501
502         data->version = sizeof(sensors_event_t);
503         data->sensor = s;
504         data->type = sensor_type;
505         data->timestamp = get_timestamp();
506
507         switch (sensor_type) {
508                 case SENSOR_TYPE_ACCELEROMETER:         /* m/s^2        */
509                 case SENSOR_TYPE_MAGNETIC_FIELD:        /* micro-tesla  */
510                 case SENSOR_TYPE_ORIENTATION:           /* degrees      */
511                 case SENSOR_TYPE_GYROSCOPE:             /* radians/s    */
512                         num_fields = 3;
513                         break;
514
515                 case SENSOR_TYPE_LIGHT:                 /* SI lux units */
516                 case SENSOR_TYPE_AMBIENT_TEMPERATURE:   /* °C          */
517                 case SENSOR_TYPE_TEMPERATURE:           /* °C          */
518                 case SENSOR_TYPE_PROXIMITY:             /* centimeters  */
519                 case SENSOR_TYPE_PRESSURE:              /* hecto-pascal */
520                 case SENSOR_TYPE_RELATIVE_HUMIDITY:     /* percent */
521                         num_fields = 1;
522                         break;
523
524                 case SENSOR_TYPE_ROTATION_VECTOR:
525                         num_fields = 4;
526                         break;
527
528                 case SENSOR_TYPE_DEVICE_PRIVATE_BASE:   /* hidden for now */
529                         num_fields = 0;
530                         break;
531
532                 default:
533                         ALOGE("Unknown sensor type!\n");
534                         num_fields = 0;
535                         break;
536         }
537
538         ALOGV("Sample on sensor %d (type %d):\n", s, sensor_type);
539
540         /* If we're dealing with a poll-mode sensor */
541         if (!sensor_info[s].num_channels) {
542
543                 /* Read values through sysfs rather than from a report buffer */
544                 for (c=0; c<num_fields; c++) {
545
546                         data->data[c] = acquire_immediate_value(s, c);
547
548                         ALOGV("\tfield %d: %f\n", c, data->data[c]);
549                 }
550
551                 finalize_sample(s, data);
552                 return;
553         }
554
555         /* Convert the data into the expected Android-level format */
556
557         current_sample = sensor_info[s].report_buffer;
558
559         for (c=0; c<num_fields; c++) {
560
561                 data->data[c] = transform_sample(s, c, current_sample);
562
563                 ALOGV("\tfield %d: %f\n", c, data->data[c]);
564                 current_sample += sensor_info[s].channel[c].size;
565         }
566
567         finalize_sample(s, data);
568 }
569
570
571 static int get_poll_time (void)
572 {
573         if (!active_poll_sensors)
574                 return -1;      /* Infinite wait */
575
576         return 100;     /* ms ... this needs to be dynamic */
577 }
578
579
580 static void acknowledge_release (void)
581 {
582         /* A write to our socket circuit was performed to release epoll */
583         char buf;
584         read(poll_socket_pair[0], &buf, 1);
585 }
586
587
588 int sensor_poll(struct sensors_event_t* data, int count)
589 {
590         int s;
591         int i;
592         int nfds;
593         int delta;
594         struct epoll_event ev[MAX_DEVICES];
595
596         /* Get one or more events from our collection of sensors */
597
598 return_first_available_sensor_report:
599
600         /* If there's at least one available report */
601         for (s=0; s<sensor_count; s++)
602                 if (sensor_info[s].report_pending) {
603
604                         /* Return that up */
605                         propagate_sensor_report(s, data);
606                         sensor_info[s].report_pending = 0;
607                         ALOGV("Report on sensor %d\n", s);
608                         return 1;
609                 }
610 await_event:
611
612         /* Keep a minimum time interval between poll operations */
613         delta = (get_timestamp() - last_poll_exit_ts)/1000;
614
615         if (delta > 0 && delta < POLL_MIN_INTERVAL)
616                 usleep(POLL_MIN_INTERVAL - delta);
617
618         ALOGV("Awaiting sensor data\n");
619
620         nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_time());
621
622         last_poll_exit_ts = get_timestamp();
623
624         if (nfds == -1) {
625                 ALOGI("epoll_wait returned -1 (%s)\n", strerror(errno));
626                 goto await_event;
627         }
628
629         ALOGV("%d fds signalled\n", nfds);
630
631         /* For each of the devices for which a report is available */
632         for (i=0; i<nfds; i++)
633                 if (ev[i].events == EPOLLIN) {
634                         if (ev[i].data.u32 == INVALID_DEV_NUM) {
635                                 acknowledge_release();
636                                 goto await_event;
637                         } else
638                                 /* Read report */
639                                 integrate_device_report(ev[i].data.u32);
640                 }
641
642         /* It's a good time to invalidate poll-mode sensor values */
643         if (active_poll_sensors)
644                 for (s=0; s<sensor_count; s++)
645                         if (sensor_info[s].enable_count &&
646                                 !sensor_info[s].num_channels)
647                                         sensor_info[s].report_pending = 1;
648
649         goto return_first_available_sensor_report;
650 }
651
652
653 int sensor_set_delay(int s, int64_t ns)
654 {
655         /* Set the rate at which a specific sensor should report events */
656
657         /* See Android sensors.h for indication on sensor trigger modes */
658
659         char sysfs_path[PATH_MAX];
660         int dev_num             =       sensor_info[s].dev_num;
661         int i                   =       sensor_info[s].catalog_index;
662         const char *prefix      =       sensor_catalog[i].tag;
663         int new_sampling_rate   =       (int) (1000000000L/ns);
664         int cur_sampling_rate;
665
666         ALOGI("sensor_set_delay: sampling rate set to %d\n", new_sampling_rate);
667
668         sprintf(sysfs_path, COMMON_SAMPLING_PATH, dev_num, prefix);
669
670         if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1)
671                 if (new_sampling_rate != cur_sampling_rate) {
672
673                         if (trig_sensors_per_dev[dev_num])
674                                 enable_buffer(dev_num, 0);
675
676                         sysfs_write_int(sysfs_path, new_sampling_rate);
677
678                         if (trig_sensors_per_dev[dev_num])
679                                 enable_buffer(dev_num, 1);
680         }
681
682         sensor_info[s].sampling_rate = new_sampling_rate;
683
684         /* Release the polling loop so an updated timeout value gets used */
685         write(poll_socket_pair[1], "", 1);
686
687         return 0;
688 }
689
690
691 int allocate_control_data (void)
692 {
693         int i;
694         struct epoll_event ev = {0};
695
696         for (i=0; i<MAX_DEVICES; i++)
697                 device_fd[i] = -1;
698
699         poll_fd = epoll_create(MAX_DEVICES);
700
701         if (poll_fd == -1) {
702                 ALOGE("Can't create epoll instance for iio sensors!\n");
703                 return -1;
704         }
705
706         /* Create and add "unblocking" fd to the set of watched fds */
707
708         if (socketpair(AF_UNIX, SOCK_STREAM, 0, poll_socket_pair) == -1) {
709                 ALOGE("Can't create socket pair for iio sensors!\n");
710                 close(poll_fd);
711                 return -1;
712         }
713
714         ev.events = EPOLLIN;
715         ev.data.u32 = INVALID_DEV_NUM;
716
717         epoll_ctl(poll_fd, EPOLL_CTL_ADD, poll_socket_pair[0], &ev);
718
719         return poll_fd;
720 }
721
722
723 void delete_control_data (void)
724 {
725 }