OSDN Git Service

Merge remote-tracking branch 'origin/abt/topic/gmin/l-dev/mr1/sensors/master' into...
[android-x86/hardware-intel-libsensors.git] / enumeration.c
1 /*
2  * Copyright (C) 2014-2015 Intel Corporation.
3  */
4
5 #include <ctype.h>
6 #include <dirent.h>
7 #include <stdlib.h>
8 #include <fcntl.h>
9 #include <utils/Log.h>
10 #include <sys/stat.h>
11 #include <hardware/sensors.h>
12 #include "enumeration.h"
13 #include "description.h"
14 #include "utils.h"
15 #include "transform.h"
16 #include "description.h"
17 #include "control.h"
18 #include "calibration.h"
19
20 /*
21  * This table maps syfs entries in scan_elements directories to sensor types,
22  * and will also be used to determine other sysfs names as well as the iio
23  * device number associated to a specific sensor.
24  */
25
26  /*
27   * We duplicate entries for the uncalibrated types after their respective base
28   * sensor. This is because all sensor entries must have an associated catalog entry
29   * and also because when only the uncal sensor is active it needs to take it's data
30   * from the same iio device as the base one.
31   */
32
33 sensor_catalog_entry_t sensor_catalog[] = {
34         {
35                 .tag            = "accel",
36                 .shorthand      = "",
37                 .type           = SENSOR_TYPE_ACCELEROMETER,
38                 .num_channels   = 3,
39                 .is_virtual     = 0,
40                 .channel = {
41                         { DECLARE_NAMED_CHANNEL("accel", "x") },
42                         { DECLARE_NAMED_CHANNEL("accel", "y") },
43                         { DECLARE_NAMED_CHANNEL("accel", "z") },
44                 },
45         },
46         {
47                 .tag            = "anglvel",
48                 .shorthand      = "",
49                 .type           = SENSOR_TYPE_GYROSCOPE,
50                 .num_channels   = 3,
51                 .is_virtual     = 0,
52                 .channel = {
53                         { DECLARE_NAMED_CHANNEL("anglvel", "x") },
54                         { DECLARE_NAMED_CHANNEL("anglvel", "y") },
55                         { DECLARE_NAMED_CHANNEL("anglvel", "z") },
56                 },
57         },
58         {
59                 .tag            = "magn",
60                 .shorthand      = "",
61                 .type           = SENSOR_TYPE_MAGNETIC_FIELD,
62                 .num_channels   = 3,
63                 .is_virtual     = 0,
64                 .channel = {
65                         { DECLARE_NAMED_CHANNEL("magn", "x") },
66                         { DECLARE_NAMED_CHANNEL("magn", "y") },
67                         { DECLARE_NAMED_CHANNEL("magn", "z") },
68                 },
69         },
70         {
71                 .tag            = "intensity",
72                 .shorthand      = "",
73                 .type           = SENSOR_TYPE_INTERNAL_INTENSITY,
74                 .num_channels   = 1,
75                 .is_virtual     = 0,
76                 .channel = {
77                         { DECLARE_NAMED_CHANNEL("intensity", "both") },
78                 },
79         },
80         {
81                 .tag            = "illuminance",
82                 .shorthand      = "",
83                 .type           = SENSOR_TYPE_INTERNAL_ILLUMINANCE,
84                 .num_channels   = 1,
85                 .is_virtual     = 0,
86                 .channel = {
87                         { DECLARE_GENERIC_CHANNEL("illuminance") },
88                 },
89         },
90         {
91                 .tag            = "incli",
92                 .shorthand      = "",
93                 .type           = SENSOR_TYPE_ORIENTATION,
94                 .num_channels   = 3,
95                 .is_virtual     = 0,
96                 .channel = {
97                         { DECLARE_NAMED_CHANNEL("incli", "x") },
98                         { DECLARE_NAMED_CHANNEL("incli", "y") },
99                         { DECLARE_NAMED_CHANNEL("incli", "z") },
100                 },
101         },
102         {
103                 .tag            = "rot",
104                 .shorthand      = "",
105                 .type           = SENSOR_TYPE_ROTATION_VECTOR,
106                 .num_channels   = 4,
107                 .is_virtual     = 0,
108                 .channel = {
109                         { DECLARE_NAMED_CHANNEL("rot", "quat_x") },
110                         { DECLARE_NAMED_CHANNEL("rot", "quat_y") },
111                         { DECLARE_NAMED_CHANNEL("rot", "quat_z") },
112                         { DECLARE_NAMED_CHANNEL("rot", "quat_w") },
113                 },
114         },
115         {
116                 .tag            = "temp",
117                 .shorthand      = "",
118                 .type           = SENSOR_TYPE_AMBIENT_TEMPERATURE,
119                 .num_channels   = 1,
120                 .is_virtual     = 0,
121                 .channel = {
122                         { DECLARE_GENERIC_CHANNEL("temp") },
123                 },
124         },
125         {
126                 .tag            = "proximity",
127                 .shorthand      = "prox",
128                 .type           = SENSOR_TYPE_PROXIMITY,
129                 .num_channels   = 1,
130                 .is_virtual     = 0,
131                 .channel = {
132                         { DECLARE_GENERIC_CHANNEL("proximity") },
133                 },
134         },
135         {
136                 .tag            = "",
137                 .shorthand      = "",
138                 .type           = SENSOR_TYPE_GYROSCOPE_UNCALIBRATED,
139                 .num_channels   = 0,
140                 .is_virtual     = 1,
141                 .channel = {
142                         { DECLARE_GENERIC_CHANNEL("") },
143                 },
144
145         },
146         {
147                 .tag            = "",
148                 .shorthand      = "",
149                 .type           = SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED,
150                 .num_channels   = 0,
151                 .is_virtual     = 1,
152                 .channel = {
153                         { DECLARE_GENERIC_CHANNEL("") },
154                 },
155         },
156         {
157                 .tag            = "steps",
158                 .shorthand      = "",
159                 .type           = SENSOR_TYPE_STEP_COUNTER,
160                 .num_channels   = 1,
161                 .is_virtual     = 0,
162                 .channel = {
163                         { DECLARE_GENERIC_CHANNEL("steps") },
164                 },
165         },
166         {
167                 .tag            = "steps",
168                 .shorthand      = "",
169                 .type           = SENSOR_TYPE_STEP_DETECTOR,
170                 .num_channels   = 1,
171                 .is_virtual     = 0,
172                 .channel = {
173                         {
174                                 DECLARE_VOID_CHANNEL("steps")
175                                 .num_events = 1,
176                                 .event = {
177                                         { DECLARE_NAMED_EVENT("steps", "change") },
178                                 },
179                         },
180                 },
181         },
182         {
183                 .tag            = "proximity",
184                 .shorthand      = "prox",
185                 .type           = SENSOR_TYPE_PROXIMITY,
186                 .num_channels   = 4,
187                 .is_virtual     = 0,
188                 .channel = {
189                         {
190                                 DECLARE_VOID_CHANNEL("proximity0")
191                                 .num_events = 1,
192                                 .event = {
193                                         { DECLARE_EVENT("proximity0", "_", "", "", "thresh", "_", "either") },
194                                 },
195                         },
196                         {
197                                 DECLARE_VOID_CHANNEL("proximity1")
198                                 .num_events = 1,
199                                 .event = {
200                                         { DECLARE_EVENT("proximity1", "_", "", "", "thresh", "_", "either") },
201                                 },
202                         },
203                         {
204                                 DECLARE_VOID_CHANNEL("proximity2")
205                                 .num_events = 1,
206                                 .event = {
207                                         { DECLARE_EVENT("proximity2", "_", "", "", "thresh", "_", "either") },
208                                 },
209                         },
210                         {
211                                 DECLARE_VOID_CHANNEL("proximity3")
212                                 .num_events = 1,
213                                 .event = {
214                                         { DECLARE_EVENT("proximity3", "_", "", "", "thresh", "_", "either") },
215                                 },
216                         },
217                 },
218         },
219 };
220
221 unsigned int catalog_size = ARRAY_SIZE(sensor_catalog);
222
223 /* ACPI PLD (physical location of device) definitions, as used with sensors */
224
225 #define PANEL_FRONT     4
226 #define PANEL_BACK      5
227
228 /* We equate sensor handles to indices in these tables */
229
230 struct sensor_t sensor_desc[MAX_SENSORS];       /* Android-level descriptors */
231 sensor_info_t   sensor[MAX_SENSORS];            /* Internal descriptors      */
232 int             sensor_count;                   /* Detected sensors          */
233
234
235 /* if the sensor has an _en attribute, we need to enable it */
236 int get_needs_enable(int dev_num, const char *tag)
237 {
238         char sysfs_path[PATH_MAX];
239         int fd;
240
241         sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag);
242
243         fd = open(sysfs_path, O_RDWR);
244         if (fd == -1)
245                 return 0;
246
247         close(fd);
248         return 1;
249 }
250
251 static void setup_properties_from_pld (int s, int panel, int rotation,
252                                        int num_channels)
253 {
254         /*
255          * Generate suitable order and opt_scale directives from the PLD panel
256          * and rotation codes we got. This can later be superseded by the usual
257          * properties if necessary. Eventually we'll need to replace these
258          * mechanisms by a less convoluted one, such as a 3x3 placement matrix.
259          */
260
261         int x = 1;
262         int y = 1;
263         int z = 1;
264         int xy_swap = 0;
265         int angle = rotation * 45;
266
267         /* Only deal with 3 axis chips for now */
268         if (num_channels < 3)
269                 return;
270
271         if (panel == PANEL_BACK) {
272                 /* Chip placed on the back panel ; negate x and z */
273                 x = -x;
274                 z = -z;
275         }
276
277         switch (angle) {
278                 case 90: /* 90° clockwise: negate y then swap x,y */
279                         xy_swap = 1;
280                         y = -y;
281                         break;
282
283                 case 180: /* Upside down: negate x and y */
284                         x = -x;
285                         y = -y;
286                         break;
287
288                 case 270: /* 90° counter clockwise: negate x then swap x,y */
289                         x = -x;
290                         xy_swap = 1;
291                         break;
292         }
293
294         if (xy_swap) {
295                 sensor[s].order[0] = 1;
296                 sensor[s].order[1] = 0;
297                 sensor[s].order[2] = 2;
298                 sensor[s].quirks |= QUIRK_FIELD_ORDERING;
299         }
300
301         sensor[s].channel[0].opt_scale = x;
302         sensor[s].channel[1].opt_scale = y;
303         sensor[s].channel[2].opt_scale = z;
304 }
305
306
307 static int is_valid_pld (int panel, int rotation)
308 {
309         if (panel != PANEL_FRONT && panel != PANEL_BACK) {
310                 ALOGW("Unhandled PLD panel spec: %d\n", panel);
311                 return 0;
312         }
313
314         /* Only deal with 90° rotations for now */
315         if (rotation < 0 || rotation > 7 || (rotation & 1)) {
316                 ALOGW("Unhandled PLD rotation spec: %d\n", rotation);
317                 return 0;
318         }
319
320         return 1;
321 }
322
323
324 static int read_pld_from_properties (int s, int* panel, int* rotation)
325 {
326         int p, r;
327
328         if (sensor_get_prop(s, "panel", &p))
329                 return -1;
330
331         if (sensor_get_prop(s, "rotation", &r))
332                 return -1;
333
334         if (!is_valid_pld(p, r))
335                 return -1;
336
337         *panel = p;
338         *rotation = r;
339
340         ALOGI("S%d PLD from properties: panel=%d, rotation=%d\n", s, p, r);
341
342         return 0;
343 }
344
345
346 static int read_pld_from_sysfs (int s, int dev_num, int* panel, int* rotation)
347 {
348         char sysfs_path[PATH_MAX];
349         int p,r;
350
351         sprintf(sysfs_path, BASE_PATH "../firmware_node/pld/panel", dev_num);
352
353         if (sysfs_read_int(sysfs_path, &p))
354                 return -1;
355
356         sprintf(sysfs_path, BASE_PATH "../firmware_node/pld/rotation", dev_num);
357
358         if (sysfs_read_int(sysfs_path, &r))
359                 return -1;
360
361         if (!is_valid_pld(p, r))
362                 return -1;
363
364         *panel = p;
365         *rotation = r;
366
367         ALOGI("S%d PLD from sysfs: panel=%d, rotation=%d\n", s, p, r);
368
369         return 0;
370 }
371
372
373 static void decode_placement_information (int dev_num, int num_channels, int s)
374 {
375         /*
376          * See if we have optional "physical location of device" ACPI tags.
377          * We're only interested in panel and rotation specifiers. Use the
378          * .panel and .rotation properties in priority, and the actual ACPI
379          * values as a second source.
380          */
381
382         int panel;
383         int rotation;
384
385         if (read_pld_from_properties(s, &panel, &rotation) &&
386                 read_pld_from_sysfs(s, dev_num, &panel, &rotation))
387                         return; /* No PLD data available */
388
389         /* Map that to field ordering and scaling mechanisms */
390         setup_properties_from_pld(s, panel, rotation, num_channels);
391 }
392
393
394 static int map_internal_to_external_type (int sensor_type)
395 {
396         /* Most sensors are internally identified using the Android type, but for some we use a different type specification internally */
397
398         switch (sensor_type) {
399                 case SENSOR_TYPE_INTERNAL_ILLUMINANCE:
400                 case SENSOR_TYPE_INTERNAL_INTENSITY:
401                         return SENSOR_TYPE_LIGHT;
402
403                 default:
404                         return sensor_type;
405         }
406 }
407
408 static void populate_descriptors (int s, int sensor_type)
409 {
410         int32_t         min_delay_us;
411         max_delay_t     max_delay_us;
412
413         /* Initialize Android-visible descriptor */
414         sensor_desc[s].name             = sensor_get_name(s);
415         sensor_desc[s].vendor           = sensor_get_vendor(s);
416         sensor_desc[s].version          = sensor_get_version(s);
417         sensor_desc[s].handle           = s;
418         sensor_desc[s].type             = map_internal_to_external_type(sensor_type);
419
420         sensor_desc[s].maxRange         = sensor_get_max_range(s);
421         sensor_desc[s].resolution       = sensor_get_resolution(s);
422         sensor_desc[s].power            = sensor_get_power(s);
423         sensor_desc[s].stringType       = sensor_get_string_type(s);
424
425         /* None of our supported sensors requires a special permission */
426         sensor_desc[s].requiredPermission = "";
427
428         sensor_desc[s].flags = sensor_get_flags(s);
429         sensor_desc[s].minDelay = sensor_get_min_delay(s);
430         sensor_desc[s].maxDelay = sensor_get_max_delay(s);
431
432         ALOGV("Sensor %d (%s) type(%d) minD(%d) maxD(%d) flags(%2.2x)\n",
433                 s, sensor[s].friendly_name, sensor_desc[s].type,
434                 sensor_desc[s].minDelay, sensor_desc[s].maxDelay,
435                 sensor_desc[s].flags);
436
437         /* We currently do not implement batching */
438         sensor_desc[s].fifoReservedEventCount = 0;
439         sensor_desc[s].fifoMaxEventCount = 0;
440
441         min_delay_us = sensor_desc[s].minDelay;
442         max_delay_us = sensor_desc[s].maxDelay;
443
444         sensor[s].min_supported_rate = max_delay_us ? 1000000.0 / max_delay_us : 1;
445         sensor[s].max_supported_rate = min_delay_us && min_delay_us != -1 ? 1000000.0 / min_delay_us : 0;
446 }
447
448
449 static void add_virtual_sensor (int catalog_index)
450 {
451         int s;
452         int sensor_type;
453
454         if (sensor_count == MAX_SENSORS) {
455                 ALOGE("Too many sensors!\n");
456                 return;
457         }
458
459         sensor_type = sensor_catalog[catalog_index].type;
460
461         s = sensor_count;
462
463         sensor[s].is_virtual = 1;
464         sensor[s].catalog_index = catalog_index;
465         sensor[s].type          = sensor_type;
466
467         populate_descriptors(s, sensor_type);
468
469         /* Initialize fields related to sysfs reads offloading */
470         sensor[s].thread_data_fd[0]  = -1;
471         sensor[s].thread_data_fd[1]  = -1;
472         sensor[s].acquisition_thread = -1;
473
474         sensor_count++;
475 }
476
477
478 static int add_sensor (int dev_num, int catalog_index, int mode)
479 {
480         int s;
481         int sensor_type;
482         int retval;
483         char sysfs_path[PATH_MAX];
484         const char* prefix;
485         float scale;
486         int c;
487         float opt_scale;
488         const char* ch_name;
489         int num_channels;
490         char suffix[MAX_NAME_SIZE + 8];
491         int calib_bias;
492
493         if (sensor_count == MAX_SENSORS) {
494                 ALOGE("Too many sensors!\n");
495                 return -1;
496         }
497
498         sensor_type = sensor_catalog[catalog_index].type;
499
500         /*
501          * At this point we could check that the expected sysfs attributes are
502          * present ; that would enable having multiple catalog entries with the
503          * same sensor type, accomodating different sets of sysfs attributes.
504          */
505
506         s = sensor_count;
507
508         sensor[s].dev_num       = dev_num;
509         sensor[s].catalog_index = catalog_index;
510         sensor[s].type          = sensor_type;
511         sensor[s].mode          = mode;
512         sensor[s].trigger_nr = -1;      /* -1 means no trigger - we'll populate these at a later time */
513
514         num_channels = sensor_catalog[catalog_index].num_channels;
515
516         if (mode == MODE_POLL)
517                 sensor[s].num_channels = 0;
518         else
519                 sensor[s].num_channels = num_channels;
520
521         /* Populate the quirks array */
522         sensor_get_quirks(s);
523
524         /* Reject interfaces that may have been disabled through a quirk for this driver */
525         if ((mode == MODE_EVENT   && (sensor[s].quirks & QUIRK_NO_EVENT_MODE)) ||
526             (mode == MODE_TRIGGER && (sensor[s].quirks & QUIRK_NO_TRIG_MODE )) ||
527             (mode == MODE_POLL    && (sensor[s].quirks & QUIRK_NO_POLL_MODE ))) {
528                 memset(&sensor[s], 0, sizeof(sensor[0]));
529                 return -1;
530         }
531
532         prefix = sensor_catalog[catalog_index].tag;
533
534         /*
535          * receiving the illumination sensor calibration inputs from
536          * the Android properties and setting it within sysfs
537          */
538         if (sensor_type == SENSOR_TYPE_INTERNAL_ILLUMINANCE) {
539                 retval = sensor_get_illumincalib(s);
540                 if (retval > 0) {
541                         sprintf(sysfs_path, ILLUMINATION_CALIBPATH, dev_num);
542                         sysfs_write_int(sysfs_path, retval);
543                 }
544         }
545
546         /*
547          * See if we have optional calibration biases for each of the channels of this sensor. These would be expressed using properties like
548          * iio.accel.y.calib_bias = -1, or possibly something like iio.temp.calib_bias if the sensor has a single channel. This value gets stored in the
549          * relevant calibbias sysfs file if that file can be located and then used internally by the iio sensor driver.
550          */
551
552         if (num_channels) {
553                 for (c = 0; c < num_channels; c++) {
554                         ch_name = sensor_catalog[catalog_index].channel[c].name;
555                         sprintf(suffix, "%s.calib_bias", ch_name);
556                         if (!sensor_get_prop(s, suffix, &calib_bias) && calib_bias) {
557                                 sprintf(suffix, "%s_%s", prefix, sensor_catalog[catalog_index].channel[c].name);
558                                 sprintf(sysfs_path, SENSOR_CALIB_BIAS_PATH, dev_num, suffix);
559                                 sysfs_write_int(sysfs_path, calib_bias);
560                         }
561                 }
562         } else
563                 if (!sensor_get_prop(s, "calib_bias", &calib_bias) && calib_bias) {
564                                 sprintf(sysfs_path, SENSOR_CALIB_BIAS_PATH, dev_num, prefix);
565                                 sysfs_write_int(sysfs_path, calib_bias);
566                         }
567
568         /* Read name attribute, if available */
569         sprintf(sysfs_path, NAME_PATH, dev_num);
570         sysfs_read_str(sysfs_path, sensor[s].internal_name, MAX_NAME_SIZE);
571
572         /* See if we have general offsets and scale values for this sensor */
573
574         sprintf(sysfs_path, SENSOR_OFFSET_PATH, dev_num, prefix);
575         sysfs_read_float(sysfs_path, &sensor[s].offset);
576
577         sprintf(sysfs_path, SENSOR_SCALE_PATH, dev_num, prefix);
578         if (!sensor_get_fl_prop(s, "scale", &scale)) {
579                 /*
580                  * There is a chip preferred scale specified,
581                  * so try to store it in sensor's scale file
582                  */
583                 if (sysfs_write_float(sysfs_path, scale) == -1 && errno == ENOENT) {
584                         ALOGE("Failed to store scale[%g] into %s - file is missing", scale, sysfs_path);
585                         /* Store failed, try to store the scale into channel specific file */
586                         for (c = 0; c < num_channels; c++)
587                         {
588                                 sprintf(sysfs_path, BASE_PATH "%s", dev_num,
589                                         sensor_catalog[catalog_index].channel[c].scale_path);
590                                 if (sysfs_write_float(sysfs_path, scale) == -1)
591                                         ALOGE("Failed to store scale[%g] into %s", scale, sysfs_path);
592                         }
593                 }
594         }
595
596         sprintf(sysfs_path, SENSOR_SCALE_PATH, dev_num, prefix);
597         if (!sysfs_read_float(sysfs_path, &scale)) {
598                 sensor[s].scale = scale;
599                 ALOGV("Scale path:%s scale:%g dev_num:%d\n",
600                                         sysfs_path, scale, dev_num);
601         } else {
602                 sensor[s].scale = 1;
603
604                 /* Read channel specific scale if any*/
605                 for (c = 0; c < num_channels; c++)
606                 {
607                         sprintf(sysfs_path, BASE_PATH "%s", dev_num,
608                            sensor_catalog[catalog_index].channel[c].scale_path);
609
610                         if (!sysfs_read_float(sysfs_path, &scale)) {
611                                 sensor[s].channel[c].scale = scale;
612                                 sensor[s].scale = 0;
613
614                                 ALOGV(  "Scale path:%s "
615                                         "channel scale:%g dev_num:%d\n",
616                                         sysfs_path, scale, dev_num);
617                         }
618                 }
619         }
620
621         /* Set default scaling - if num_channels is zero, we have one channel */
622
623         sensor[s].channel[0].opt_scale = 1;
624
625         for (c = 1; c < num_channels; c++)
626                 sensor[s].channel[c].opt_scale = 1;
627
628         for (c = 0; c < num_channels; c++) {
629                 /* Check the presence of the channel's input_path */
630                 sprintf(sysfs_path, BASE_PATH "%s", dev_num,
631                         sensor_catalog[catalog_index].channel[c].input_path);
632                 sensor[s].channel[c].input_path_present = (access(sysfs_path, R_OK) != -1);
633                 /* Check the presence of the channel's raw_path */
634                 sprintf(sysfs_path, BASE_PATH "%s", dev_num,
635                         sensor_catalog[catalog_index].channel[c].raw_path);
636                 sensor[s].channel[c].raw_path_present = (access(sysfs_path, R_OK) != -1);
637         }
638
639         if (sensor_get_mounting_matrix(s, sensor[s].mounting_matrix))
640                 sensor[s].quirks |= QUIRK_MOUNTING_MATRIX;
641         else
642                 /* Read ACPI _PLD attributes for this sensor, if there are any */
643                 decode_placement_information(dev_num, num_channels, s);
644
645         /*
646          * See if we have optional correction scaling factors for each of the
647          * channels of this sensor. These would be expressed using properties
648          * like iio.accel.y.opt_scale = -1. In case of a single channel we also
649          * support things such as iio.temp.opt_scale = -1. Note that this works
650          * for all types of sensors, and whatever transform is selected, on top
651          * of any previous conversions.
652          */
653
654         if (num_channels) {
655                 for (c = 0; c < num_channels; c++) {
656                         ch_name = sensor_catalog[catalog_index].channel[c].name;
657                         sprintf(suffix, "%s.opt_scale", ch_name);
658                         if (!sensor_get_fl_prop(s, suffix, &opt_scale))
659                                 sensor[s].channel[c].opt_scale = opt_scale;
660                 }
661         } else {
662                 if (!sensor_get_fl_prop(s, "opt_scale", &opt_scale))
663                         sensor[s].channel[0].opt_scale = opt_scale;
664         }
665
666         populate_descriptors(s, sensor_type);
667
668         if (sensor[s].internal_name[0] == '\0') {
669                 /*
670                  * In case the kernel-mode driver doesn't expose a name for
671                  * the iio device, use (null)-dev%d as the trigger name...
672                  * This can be considered a kernel-mode iio driver bug.
673                  */
674                 ALOGW("Using null trigger on sensor %d (dev %d)\n", s, dev_num);
675                 strcpy(sensor[s].internal_name, "(null)");
676         }
677
678         switch (sensor_type) {
679                 case SENSOR_TYPE_ACCELEROMETER:
680                         /* Only engage accelerometer bias compensation if really needed */
681                         if (sensor_get_quirks(s) & QUIRK_BIASED)
682                                 sensor[s].cal_data = calloc(1, sizeof(accel_cal_t));
683                         break;
684
685                         case SENSOR_TYPE_GYROSCOPE:
686                         sensor[s].cal_data = malloc(sizeof(gyro_cal_t));
687                         break;
688
689                 case SENSOR_TYPE_MAGNETIC_FIELD:
690                         sensor[s].cal_data = malloc(sizeof(compass_cal_t));
691                         break;
692         }
693
694         sensor[s].max_cal_level = sensor_get_cal_steps(s);
695
696         /* Select one of the available sensor sample processing styles */
697         select_transform(s);
698
699         /* Initialize fields related to sysfs reads offloading */
700         sensor[s].thread_data_fd[0]  = -1;
701         sensor[s].thread_data_fd[1]  = -1;
702         sensor[s].acquisition_thread = -1;
703
704         /* Check if we have a special ordering property on this sensor */
705         if (sensor_get_order(s, sensor[s].order))
706                 sensor[s].quirks |= QUIRK_FIELD_ORDERING;
707
708         sensor[s].needs_enable = get_needs_enable(dev_num, sensor_catalog[catalog_index].tag);
709
710         sensor_count++;
711         return 0;
712 }
713
714 static void virtual_sensors_check (void)
715 {
716         int i;
717         int has_acc = 0;
718         int has_gyr = 0;
719         int has_mag = 0;
720         int has_rot = 0;
721         int has_ori = 0;
722         int gyro_cal_idx = 0;
723         int magn_cal_idx = 0;
724         unsigned int j;
725
726         for (i=0; i<sensor_count; i++)
727                 switch (sensor[i].type) {
728                         case SENSOR_TYPE_ACCELEROMETER:
729                                 has_acc = 1;
730                                 break;
731                         case SENSOR_TYPE_GYROSCOPE:
732                                 has_gyr = 1;
733                                 gyro_cal_idx = i;
734                                 break;
735                         case SENSOR_TYPE_MAGNETIC_FIELD:
736                                 has_mag = 1;
737                                 magn_cal_idx = i;
738                                 break;
739                         case SENSOR_TYPE_ORIENTATION:
740                                 has_ori = 1;
741                                 break;
742                         case SENSOR_TYPE_ROTATION_VECTOR:
743                                 has_rot = 1;
744                                 break;
745                 }
746
747         for (j=0; j<catalog_size; j++)
748                 switch (sensor_catalog[j].type) {
749                         /*
750                          * If we have accel + gyro + magn but no rotation vector sensor,
751                          * SensorService replaces the HAL provided orientation sensor by the
752                          * AOSP version... provided we report one. So initialize a virtual
753                          * orientation sensor with zero values, which will get replaced. See:
754                          * frameworks/native/services/sensorservice/SensorService.cpp, looking
755                          * for SENSOR_TYPE_ROTATION_VECTOR; that code should presumably fall
756                          * back to mUserSensorList.add instead of replaceAt, but accommodate it.
757                          */
758
759                         case SENSOR_TYPE_ORIENTATION:
760                                 if (has_acc && has_gyr && has_mag && !has_rot && !has_ori)
761                                         add_sensor(0, j, MODE_POLL);
762                                 break;
763                         case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
764                                 if (has_gyr) {
765                                         sensor[sensor_count].base_count = 1;
766                                         sensor[sensor_count].base[0] = gyro_cal_idx;
767                                         add_virtual_sensor(j);
768                                 }
769                                 break;
770                         case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
771                                 if (has_mag) {
772                                         sensor[sensor_count].base_count = 1;
773                                         sensor[sensor_count].base[0] = magn_cal_idx;
774                                         add_virtual_sensor(j);
775                                 }
776                                 break;
777                         default:
778                                 break;
779                 }
780 }
781
782
783 static void propose_new_trigger (int s, char trigger_name[MAX_NAME_SIZE],
784                                  int sensor_name_len)
785 {
786         /*
787          * A new trigger has been enumerated for this sensor. Check if it makes sense to use it over the currently selected one,
788          *  and select it if it is so. The format is something like sensor_name-dev0.
789          */
790
791         const char *suffix = trigger_name + sensor_name_len + 1;
792
793         /* dev is the default, and lowest priority; no need to update */
794         if (!memcmp(suffix, "dev", 3))
795                 return;
796
797         /* If we found any-motion trigger, record it */
798
799         if (!memcmp(suffix, "any-motion-", 11)) {
800                 strcpy(sensor[s].motion_trigger_name, trigger_name);
801                 return;
802         }
803
804         /* If we found a hrtimer trigger, record it */
805         if (!memcmp(suffix, "hr-dev", 6)) {
806                 strcpy(sensor[s].hrtimer_trigger_name, trigger_name);
807                 return;
808         }
809         /*
810          * It's neither the default "dev" nor an "any-motion" one. Make sure we use this though, as we may not have any other indication of the name
811          * of the trigger to use with this sensor.
812          */
813         strcpy(sensor[s].init_trigger_name, trigger_name);
814 }
815
816
817 static void update_sensor_matching_trigger_name (char name[MAX_NAME_SIZE], int* updated, int trigger)
818 {
819         /*
820          * Check if we have a sensor matching the specified trigger name, which should then begin with the sensor name, and end with a number
821          * equal to the iio device number the sensor is associated to. If so, update the string we're going to write to trigger/current_trigger
822          * when enabling this sensor.
823          */
824
825         int s;
826         int dev_num;
827         int len;
828         char* cursor;
829         int sensor_name_len;
830
831         /*
832          * First determine the iio device number this trigger refers to. We expect the last few characters (typically one) of the trigger name
833          * to be this number, so perform a few checks.
834          */
835         len = strnlen(name, MAX_NAME_SIZE);
836
837         if (len < 2)
838                 return;
839
840         cursor = name + len - 1;
841
842         if (!isdigit(*cursor))
843                 return;
844
845         while (len && isdigit(*cursor)) {
846                 len--;
847                 cursor--;
848         }
849
850         dev_num = atoi(cursor+1);
851
852         /* See if that matches a sensor */
853         for (s=0; s<sensor_count; s++)
854                 if (sensor[s].dev_num == dev_num) {
855
856                         sensor_name_len = strlen(sensor[s].internal_name);
857
858                         if (!strncmp(name, sensor[s].internal_name, sensor_name_len))
859                                 /* Switch to new trigger if appropriate */
860                                 propose_new_trigger(s, name, sensor_name_len);
861                                 updated[s] = 1;
862                                 sensor[s].trigger_nr = trigger;
863                 }
864 }
865
866 static int create_hrtimer_trigger(int s, int trigger)
867 {
868         struct stat dir_status;
869         char buf[MAX_NAME_SIZE];
870         char hrtimer_path[PATH_MAX];
871         char hrtimer_name[MAX_NAME_SIZE];
872
873         snprintf(buf, MAX_NAME_SIZE, "hrtimer-%s-hr-dev%d", sensor[s].internal_name, sensor[s].dev_num);
874         snprintf(hrtimer_name, MAX_NAME_SIZE, "%s-hr-dev%d", sensor[s].internal_name, sensor[s].dev_num);
875         snprintf(hrtimer_path, PATH_MAX, "%s%s", CONFIGFS_TRIGGER_PATH, buf);
876
877         /* Get parent dir status */
878         if (stat(CONFIGFS_TRIGGER_PATH, &dir_status))
879                 return -1;
880
881         /* Create hrtimer with the same access rights as it's parent */
882         if (mkdir(hrtimer_path, dir_status.st_mode))
883                 if (errno != EEXIST)
884                         return -1;
885
886         strncpy (sensor[s].hrtimer_trigger_name, hrtimer_name, MAX_NAME_SIZE);
887         sensor[s].trigger_nr = trigger;
888         return 0;
889 }
890
891 static void setup_trigger_names (void)
892 {
893         char filename[PATH_MAX];
894         char buf[MAX_NAME_SIZE];
895         int s;
896         int trigger;
897         int ret;
898         int updated[MAX_SENSORS] = {0};
899
900         /* By default, use the name-dev convention that most drivers use */
901         for (s=0; s<sensor_count; s++)
902                 snprintf(sensor[s].init_trigger_name, MAX_NAME_SIZE, "%s-dev%d", sensor[s].internal_name, sensor[s].dev_num);
903
904         /* Now have a look to /sys/bus/iio/devices/triggerX entries */
905
906         for (trigger=0; trigger<MAX_TRIGGERS; trigger++) {
907
908                 snprintf(filename, sizeof(filename), TRIGGER_FILE_PATH, trigger);
909
910                 ret = sysfs_read_str(filename, buf, sizeof(buf));
911
912                 if (ret < 0)
913                         break;
914
915                 /* Record initial and any-motion triggers names */
916                 update_sensor_matching_trigger_name(buf, updated, trigger);
917         }
918
919
920         /* If we don't have any other trigger exposed and quirk hrtimer is set setup the hrtimer name here  - and create it also */
921         for (s=0; s<sensor_count && trigger<MAX_TRIGGERS; s++) {
922                 if ((sensor[s].quirks & QUIRK_HRTIMER) && !updated[s]) {
923                         create_hrtimer_trigger(s, trigger);
924                         trigger++;
925                 }
926         }
927
928         /*
929          * Certain drivers expose only motion triggers even though they should be continous. For these, use the default trigger name as the motion
930          * trigger. The code generating intermediate events is dependent on motion_trigger_name being set to a non empty string.
931          */
932
933         for (s=0; s<sensor_count; s++)
934                 if ((sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].motion_trigger_name[0] == '\0')
935                         strcpy(sensor[s].motion_trigger_name, sensor[s].init_trigger_name);
936
937         for (s=0; s<sensor_count; s++)
938                 if (sensor[s].mode == MODE_TRIGGER) {
939                         ALOGI("Sensor %d (%s) default trigger: %s\n", s, sensor[s].friendly_name, sensor[s].init_trigger_name);
940                         if (sensor[s].motion_trigger_name[0])
941                                 ALOGI("Sensor %d (%s) motion trigger: %s\n", s, sensor[s].friendly_name, sensor[s].motion_trigger_name);
942                         if (sensor[s].hrtimer_trigger_name[0])
943                                 ALOGI("Sensor %d (%s) hrtimer trigger: %s\n", s, sensor[s].friendly_name, sensor[s].hrtimer_trigger_name);
944                 }
945 }
946
947
948 static int catalog_index_from_sensor_type (int type)
949 {
950         /* Return first matching catalog entry index for selected type */
951         unsigned int i;
952
953         for (i=0; i<catalog_size; i++)
954                 if (sensor_catalog[i].type == type)
955                         return i;
956
957         return -1;
958 }
959
960
961 static void post_process_sensor_list (char poll_map[catalog_size], char trig_map[catalog_size], char event_map[catalog_size])
962 {
963         int illuminance_cat_index = catalog_index_from_sensor_type(SENSOR_TYPE_INTERNAL_ILLUMINANCE);
964         int intensity_cat_index   = catalog_index_from_sensor_type(SENSOR_TYPE_INTERNAL_INTENSITY);
965         int illuminance_found     = poll_map[illuminance_cat_index] || trig_map[illuminance_cat_index] || event_map[illuminance_cat_index];
966
967         /* If an illumimance sensor has been reported */
968         if (illuminance_found) {
969                 /* Hide any intensity sensors we can have for the same iio device */
970                 poll_map [intensity_cat_index     ] = 0;
971                 trig_map [intensity_cat_index     ] = 0;
972                 event_map[intensity_cat_index     ] = 0;
973                 return;
974         }
975 }
976
977
978 void enumerate_sensors (void)
979 {
980         /*
981          * Discover supported sensors and allocate control structures for them. Multiple sensors can potentially rely on a single iio device (each
982          * using their own channels). We can't have multiple sensors of the same type on the same device. In case of detection as both a poll-mode
983          * and trigger-based sensor, use the trigger usage mode.
984          */
985         char poll_sensors[catalog_size];
986         char trig_sensors[catalog_size];
987         char event_sensors[catalog_size];
988         int dev_num;
989         unsigned int i;
990         int trig_found;
991
992         for (dev_num=0; dev_num<MAX_DEVICES; dev_num++) {
993                 trig_found = 0;
994
995                 discover_sensors(dev_num, BASE_PATH, poll_sensors, check_poll_sensors);
996                 discover_sensors(dev_num, CHANNEL_PATH, trig_sensors, check_trig_sensors);
997                 discover_sensors(dev_num, EVENTS_PATH, event_sensors, check_event_sensors);
998
999                 /* Hide specific sensor types if appropriate */
1000                 post_process_sensor_list(poll_sensors, trig_sensors, event_sensors);
1001
1002                 for (i=0; i<catalog_size; i++) {
1003                         /* Try using events interface */
1004                         if (event_sensors[i] && !add_sensor(dev_num, i, MODE_EVENT))
1005                                 continue;
1006
1007                         /* Then trigger */
1008                         if (trig_sensors[i] && !add_sensor(dev_num, i, MODE_TRIGGER)) {
1009                                 trig_found = 1;
1010                                 continue;
1011                         }
1012
1013                         /* Try polling otherwise */
1014                         if (poll_sensors[i])
1015                                 add_sensor(dev_num, i, MODE_POLL);
1016                 }
1017
1018                 if (trig_found)
1019                         build_sensor_report_maps(dev_num);
1020         }
1021
1022         ALOGI("Discovered %d sensors\n", sensor_count);
1023
1024         /* Set up default - as well as custom - trigger names */
1025         setup_trigger_names();
1026
1027         virtual_sensors_check();
1028 }
1029
1030
1031 void delete_enumeration_data (void)
1032 {
1033         int i;
1034         for (i = 0; i < sensor_count; i++)
1035                 if (sensor[i].cal_data) {
1036                         free(sensor[i].cal_data);
1037                         sensor[i].cal_data = NULL;
1038                         sensor[i].cal_level = 0;
1039                 }
1040
1041         /* Reset sensor count */
1042         sensor_count = 0;
1043 }
1044
1045
1046 int get_sensors_list (__attribute__((unused)) struct sensors_module_t* module,
1047                       struct sensor_t const** list)
1048 {
1049         *list = sensor_desc;
1050         return sensor_count;
1051 }
1052