OSDN Git Service

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