OSDN Git Service

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