OSDN Git Service

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