OSDN Git Service

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