OSDN Git Service

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