This repository has been archived by the owner on Nov 26, 2022. It is now read-only.
forked from intel/android-iio-sensors-hal
-
Notifications
You must be signed in to change notification settings - Fork 2
/
control.c
1756 lines (1348 loc) · 50.5 KB
/
control.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
// Copyright (c) 2015 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <utils/Log.h>
#include <hardware/sensors.h>
#include <linux/ioctl.h>
#include "control.h"
#include "enumeration.h"
#include "utils.h"
#include "transform.h"
#include "calibration.h"
#include "description.h"
#include "filtering.h"
#ifndef __NO_EVENTS__
#include <linux/iio/events.h>
#include <linux/iio/types.h>
#endif
#include <errno.h>
/* Currently active sensors count, per device */
static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
static int events_fd[MAX_DEVICES]; /* fd on the /sys/bus/iio/devices/iio:deviceX/events/<event_name> file */
static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */
static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */
static int poll_fd; /* epoll instance covering all enabled sensors */
static int active_poll_sensors; /* Number of enabled poll-mode sensors */
static int flush_event_fd[2]; /* Pipe used for flush signaling */
/* We use pthread condition variables to get worker threads out of sleep */
static pthread_condattr_t thread_cond_attr [MAX_SENSORS];
static pthread_cond_t thread_release_cond [MAX_SENSORS];
static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
#define FLUSH_REPORT_TAG 900
/*
* We associate tags to each of our poll set entries. These tags have the following values:
* - a iio device number if the fd is a iio character device fd
* - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a pipe used by a sysfs data acquisition thread
*/
#define THREAD_REPORT_TAG_BASE 1000
/* If buffer enable fails, we may want to retry a few times before giving up */
#define ENABLE_BUFFER_RETRIES 3
#define ENABLE_BUFFER_RETRY_DELAY_MS 10
inline int is_enabled (int s)
{
return sensor[s].directly_enabled || sensor[s].ref_count;
}
static int check_state_change (int s, int enabled, int from_virtual)
{
if (enabled) {
if (sensor[s].directly_enabled)
return 0; /* We're being enabled but already were directly activated: no change. */
if (!from_virtual)
sensor[s].directly_enabled = 1; /* We're being directly enabled */
if (sensor[s].ref_count)
return 0; /* We were already indirectly enabled */
return 1; /* Do continue enabling this sensor */
}
if (!is_enabled(s))
return 0; /* We are being disabled but already were: no change */
if (from_virtual && sensor[s].directly_enabled)
return 0; /* We're indirectly disabled but the base is still active */
sensor[s].directly_enabled = 0; /* We're now directly disabled */
if (!from_virtual && sensor[s].ref_count)
return 0; /* We still have ref counts */
return 1; /* Do continue disabling this sensor */
}
static int enable_buffer (int dev_num, int enabled)
{
char sysfs_path[PATH_MAX];
int retries = ENABLE_BUFFER_RETRIES;
sprintf(sysfs_path, ENABLE_PATH, dev_num);
while (retries) {
/* Low level, non-multiplexed, enable/disable routine */
if (sysfs_write_int(sysfs_path, enabled) > 0)
return 0;
ALOGE("Failed enabling buffer on dev%d, retrying", dev_num);
usleep(ENABLE_BUFFER_RETRY_DELAY_MS*1000);
retries--;
}
ALOGE("Could not enable buffer\n");
return -EIO;
}
static int setup_trigger (int s, const char* trigger_val)
{
char sysfs_path[PATH_MAX];
int ret = -1, attempts = 5;
sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
if (trigger_val[0] != '\n')
ALOGI("Setting S%d (%s) trigger to %s\n", s, sensor[s].friendly_name, trigger_val);
while (ret == -1 && attempts) {
ret = sysfs_write_str(sysfs_path, trigger_val);
attempts--;
}
if (ret != -1)
sensor[s].selected_trigger = trigger_val;
else
ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, sensor[s].friendly_name, trigger_val);
return ret;
}
static int enable_event(int dev_num, const char *name, int enabled)
{
char sysfs_path[PATH_MAX];
sprintf(sysfs_path, EVENTS_PATH "%s", dev_num, name);
return sysfs_write_int(sysfs_path, enabled);
}
static int enable_sensor(int dev_num, const char *tag, int enabled)
{
char sysfs_path[PATH_MAX];
sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag);
return sysfs_write_int(sysfs_path, enabled);
}
static void enable_iio_timestamp (int dev_num, int known_channels)
{
/* Check if we have a dedicated iio timestamp channel */
char spec_buf[MAX_TYPE_SPEC_LEN];
char sysfs_path[PATH_MAX];
int n;
sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
if (n <= 0)
return;
if (strcmp(spec_buf, "le:s64/64>>0"))
return;
/* OK, type is int64_t as expected, in little endian representation */
sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
if (sysfs_read_int(sysfs_path, &n))
return;
/* Check that the timestamp comes after the other fields we read */
if (n != known_channels)
return;
/* Try enabling that channel */
sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
sysfs_write_int(sysfs_path, 1);
if (sysfs_read_int(sysfs_path, &n))
return;
if (n) {
ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
has_iio_ts[dev_num] = 1;
}
}
static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], datum_info_t *type_info)
{
/* Return size in bytes for this type specification, or -1 in error */
char sign;
char endianness;
unsigned int realbits, storagebits, shift;
int tokens;
/* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", &endianness, &sign, &realbits, &storagebits, &shift);
if (tokens != 5 || (endianness != 'b' && endianness != 'l') || (sign != 'u' && sign != 's') ||
realbits > storagebits || (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
ALOGE("Invalid iio channel type spec: %s\n", type_buf);
return -1;
}
type_info->endianness = endianness;
type_info->sign = sign;
type_info->realbits = (short) realbits;
type_info->storagebits = (short) storagebits;
type_info->shift = (short) shift;
return storagebits / 8;
}
void build_sensor_report_maps (int dev_num)
{
/*
* Read sysfs files from a iio device's scan_element directory, and build a couple of tables from that data. These tables will tell, for
* each sensor, where to gather relevant data in a device report, i.e. the structure that we read from the /dev/iio:deviceX file in order to
* sensor report, itself being the data that we return to Android when a sensor poll completes. The mapping should be straightforward in the
* case where we have a single sensor active per iio device but, this is not the general case. In general several sensors can be handled
* through a single iio device, and the _en, _index and _type syfs entries all concur to paint a picture of what the structure of the
* device report is.
*/
int s;
int c;
int n;
int i;
int ch_index;
char* ch_spec;
char spec_buf[MAX_TYPE_SPEC_LEN];
datum_info_t* ch_info;
int size;
char sysfs_path[PATH_MAX];
int known_channels;
int offset;
int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
known_channels = 0;
/* For each sensor that is linked to this device */
for (s=0; s<sensor_count; s++) {
if (sensor[s].dev_num != dev_num)
continue;
i = sensor[s].catalog_index;
/* Read channel details through sysfs attributes */
for (c=0; c<sensor[s].num_channels; c++) {
/* Read _type file */
sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].type_path);
n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
if (n == -1) {
ALOGW( "Failed to read type: %s\n", sysfs_path);
continue;
}
ch_spec = sensor[s].channel[c].type_spec;
memcpy(ch_spec, spec_buf, sizeof(spec_buf));
ch_info = &sensor[s].channel[c].type_info;
size = decode_type_spec(ch_spec, ch_info);
/* Read _index file */
sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].index_path);
n = sysfs_read_int(sysfs_path, &ch_index);
if (n == -1) {
ALOGW( "Failed to read index: %s\n", sysfs_path);
continue;
}
if (ch_index >= MAX_SENSORS) {
ALOGE("Index out of bounds!: %s\n", sysfs_path);
continue;
}
/* Record what this index is about */
sensor_handle_from_index [ch_index] = s;
channel_number_from_index[ch_index] = c;
channel_size_from_index [ch_index] = size;
known_channels++;
}
sensor_update_max_range(s);
/* Stop sampling - if we are recovering from hal restart */
enable_buffer(dev_num, 0);
setup_trigger(s, "\n");
/* Turn on channels we're aware of */
for (c=0;c<sensor[s].num_channels; c++) {
sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].en_path);
sysfs_write_int(sysfs_path, 1);
}
}
ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
/*
* Now that we know which channels are defined, their sizes and their ordering, update channels offsets within device report. Note: there
* is a possibility that several sensors share the same index, with their data fields being isolated by masking and shifting as specified
* through the real bits and shift values in type attributes. This case is not currently supported. Also, the code below assumes no hole in
* the sequence of indices, so it is dependent on discovery of all sensors.
*/
offset = 0;
for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
s = sensor_handle_from_index[i];
c = channel_number_from_index[i];
size = channel_size_from_index[i];
if (!size)
continue;
ALOGI("S%d C%d : offset %d, size %d, type %s\n", s, c, offset, size, sensor[s].channel[c].type_spec);
sensor[s].channel[c].offset = offset;
sensor[s].channel[c].size = size;
offset += size;
}
/* Enable the timestamp channel if there is one available */
enable_iio_timestamp(dev_num, known_channels);
/* Add padding and timestamp size if it's enabled on this iio device */
if (has_iio_ts[dev_num])
offset = (offset+7)/8*8 + sizeof(int64_t);
expected_dev_report_size[dev_num] = offset;
ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", dev_num, expected_dev_report_size[dev_num]);
expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
}
}
int adjust_counters (int s, int enabled, int from_virtual)
{
/*
* Adjust counters based on sensor enable action. Return values are:
* 0 if the operation was completed and we're all set
* 1 if we toggled the state of the sensor and there's work left
* -1 in case of an error
*/
int dev_num = sensor[s].dev_num;
if (!check_state_change(s, enabled, from_virtual))
return 0; /* The state of the sensor remains the same: we're done */
if (enabled) {
ALOGI("Enabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
switch (sensor[s].type) {
case SENSOR_TYPE_ACCELEROMETER:
accel_cal_init(s);
break;
case SENSOR_TYPE_MAGNETIC_FIELD:
compass_read_data(s);
break;
case SENSOR_TYPE_GYROSCOPE:
gyro_cal_init(s);
break;
}
} else {
ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
/* Sensor disabled, lower report available flag */
sensor[s].report_pending = 0;
/* Save calibration data to persistent storage */
switch (sensor[s].type) {
case SENSOR_TYPE_ACCELEROMETER:
accel_cal_store(s);
break;
case SENSOR_TYPE_MAGNETIC_FIELD:
compass_store_data(s);
break;
case SENSOR_TYPE_GYROSCOPE:
gyro_store_data(s);
break;
}
}
/* We changed the state of a sensor: adjust device ref counts */
switch(sensor[s].mode) {
case MODE_TRIGGER:
if (enabled)
trig_sensors_per_dev[dev_num]++;
else
trig_sensors_per_dev[dev_num]--;
return 1;
case MODE_POLL:
if (enabled) {
active_poll_sensors++;
poll_sensors_per_dev[dev_num]++;
return 1;
} else {
active_poll_sensors--;
poll_sensors_per_dev[dev_num]--;
return 1;
}
case MODE_EVENT:
return 1;
default:
/* Invalid sensor mode */
return -1;
}
}
static int get_field_count (int s, size_t *field_size)
{
*field_size = sizeof(float);
switch (sensor[s].type) {
case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
case SENSOR_TYPE_ORIENTATION: /* degrees */
case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
case SENSOR_TYPE_GYROSCOPE: /* radians/s */
return 3;
case SENSOR_TYPE_INTERNAL_INTENSITY:
case SENSOR_TYPE_INTERNAL_ILLUMINANCE:
case SENSOR_TYPE_LIGHT: /* SI lux units */
case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
case SENSOR_TYPE_TEMPERATURE: /* °C */
case SENSOR_TYPE_PROXIMITY: /* centimeters */
case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
case SENSOR_TYPE_STEP_DETECTOR: /* event: always 1 */
return 1;
case SENSOR_TYPE_ROTATION_VECTOR:
return 4;
case SENSOR_TYPE_STEP_COUNTER: /* number of steps */
*field_size = sizeof(uint64_t);
return 1;
default:
ALOGE("Unknown sensor type!\n");
return 0; /* Drop sample */
}
}
/*
* CTS acceptable thresholds:
* EventGapVerification.java: (th <= 1.8)
* FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
*/
#define THRESHOLD 1.10
#define MAX_DELAY 500000000 /* 500 ms */
void set_report_ts(int s, int64_t ts)
{
int64_t maxTs, period;
/*
* A bit of a hack to please a bunch of cts tests. They
* expect the timestamp to be exacly according to the set-up
* frequency but if we're simply getting the timestamp at hal level
* this may not be the case. Perhaps we'll get rid of this when
* we'll be reading the timestamp from the iio channel for all sensors
*/
if (sensor[s].report_ts && sensor[s].sampling_rate &&
REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
{
period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
maxTs = sensor[s].report_ts + THRESHOLD * period;
/* If we're too far behind get back on track */
if (ts - maxTs >= MAX_DELAY)
maxTs = ts;
sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
} else {
sensor[s].report_ts = ts;
}
}
static void* acquisition_routine (void* param)
{
/*
* Data acquisition routine run in a dedicated thread, covering a single sensor. This loop will periodically retrieve sampling data through
* sysfs, then package it as a sample and transfer it to our master poll loop through a report fd. Checks for a cancellation signal quite
* frequently, as the thread may be disposed of at any time. Note that Bionic does not provide pthread_cancel / pthread_testcancel...
*/
int s = (int) (size_t) param;
int num_fields;
sensors_event_t data = {0};
int c;
int ret;
struct timespec target_time;
int64_t timestamp, period, start, stop;
size_t field_size;
if (s < 0 || s >= sensor_count) {
ALOGE("Invalid sensor handle!\n");
return NULL;
}
ALOGI("Entering S%d (%s) data acquisition thread: rate:%g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate);
if (sensor[s].sampling_rate <= 0) {
ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", s, sensor[s].sampling_rate);
return NULL;
}
/* Initialize data fields that will be shared by all sensor reports */
data.version = sizeof(sensors_event_t);
data.sensor = s;
data.type = sensor_desc[s].type;
num_fields = get_field_count(s, &field_size);
/*
* Each condition variable is associated to a mutex that has to be locked by the thread that's waiting on it. We use these condition
* variables to get the acquisition threads out of sleep quickly after the sampling rate is adjusted, or the sensor is disabled.
*/
pthread_mutex_lock(&thread_release_mutex[s]);
/* Pinpoint the moment we start sampling */
timestamp = get_timestamp_monotonic();
/* Check and honor termination requests */
while (sensor[s].thread_data_fd[1] != -1) {
start = get_timestamp_boot();
/* Read values through sysfs */
for (c=0; c<num_fields; c++) {
if (field_size == sizeof(uint64_t))
data.u64.data[c] = acquire_immediate_uint64_value(s, c);
else
data.data[c] = acquire_immediate_float_value(s, c);
/* Check and honor termination requests */
if (sensor[s].thread_data_fd[1] == -1)
goto exit;
}
stop = get_timestamp_boot();
set_report_ts(s, start/2 + stop/2);
data.timestamp = sensor[s].report_ts;
/* If the sample looks good */
if (sensor[s].ops.finalize(s, &data)) {
/* Pipe it for transmission to poll loop */
ret = write(sensor[s].thread_data_fd[1], &data, sizeof(sensors_event_t));
if (ret != sizeof(sensors_event_t))
ALOGE("S%d write failure: wrote %zd, got %d\n", s, sizeof(sensors_event_t), ret);
}
/* Check and honor termination requests */
if (sensor[s].thread_data_fd[1] == -1)
goto exit;
/* Recalculate period assuming sensor[s].sampling_rate can be changed dynamically during the thread run */
if (sensor[s].sampling_rate <= 0) {
ALOGE("Unexpected sampling rate for sensor %d: %g\n", s, sensor[s].sampling_rate);
goto exit;
}
period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
timestamp += period;
set_timestamp(&target_time, timestamp);
/* Wait until the sampling time elapses, or a rate change is signaled, or a thread exit is requested */
ret = pthread_cond_timedwait(&thread_release_cond[s], &thread_release_mutex[s], &target_time);
}
exit:
ALOGV("Acquisition thread for S%d exiting\n", s);
pthread_mutex_unlock(&thread_release_mutex[s]);
pthread_exit(0);
return NULL;
}
static void start_acquisition_thread (int s)
{
int incoming_data_fd;
int ret;
struct epoll_event ev = {0};
ALOGV("Initializing acquisition context for sensor %d\n", s);
/* Create condition variable and mutex for quick thread release */
ret = pthread_condattr_init(&thread_cond_attr[s]);
ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
/* Create a pipe for inter thread communication */
ret = pipe(sensor[s].thread_data_fd);
incoming_data_fd = sensor[s].thread_data_fd[0];
ev.events = EPOLLIN;
ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
/* Add incoming side of pipe to our poll set, with a suitable tag */
ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
if (ret == -1) {
ALOGE("Failed adding %d to poll set (%s)\n",
incoming_data_fd, strerror(errno));
}
/* Create and start worker thread */
ret = pthread_create(&sensor[s].acquisition_thread, NULL, acquisition_routine, (void*) (size_t) s);
}
static void stop_acquisition_thread (int s)
{
int incoming_data_fd = sensor[s].thread_data_fd[0];
int outgoing_data_fd = sensor[s].thread_data_fd[1];
ALOGV("Tearing down acquisition context for sensor %d\n", s);
/* Delete the incoming side of the pipe from our poll set */
epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
/* Mark the pipe ends as invalid ; that's a cheap exit flag */
sensor[s].thread_data_fd[0] = -1;
sensor[s].thread_data_fd[1] = -1;
/* Close both sides of our pipe */
close(incoming_data_fd);
close(outgoing_data_fd);
/* Stop acquisition thread and clean up thread handle */
pthread_cond_signal(&thread_release_cond[s]);
pthread_join(sensor[s].acquisition_thread, NULL);
/* Clean up our sensor descriptor */
sensor[s].acquisition_thread = -1;
/* Delete condition variable and mutex */
pthread_cond_destroy(&thread_release_cond[s]);
pthread_mutex_destroy(&thread_release_mutex[s]);
}
static int is_fast_accelerometer (int s)
{
/*
* Some games don't react well to accelerometers using any-motion triggers. Even very low thresholds seem to trip them, and they tend to
* request fairly high event rates. Favor continuous triggers if the sensor is an accelerometer and uses a sampling rate of at least 25.
*/
if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
return 0;
if (sensor[s].sampling_rate < 25)
return 0;
return 1;
}
static void tentative_switch_trigger (int s)
{
/*
* Under certain situations it may be beneficial to use an alternate trigger:
*
* - for applications using the accelerometer with high sampling rates, prefer the continuous trigger over the any-motion one, to avoid
* jumps related to motion thresholds
*/
if (is_fast_accelerometer(s) && !(sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].selected_trigger == sensor[s].motion_trigger_name)
setup_trigger(s, sensor[s].init_trigger_name);
}
static float get_group_max_sampling_rate (int s)
{
/* Review the sampling rates of linked sensors and return the maximum */
int i, vi;
float arbitrated_rate = 0;
if (is_enabled(s))
arbitrated_rate = sensor[s].requested_rate;
/* If any of the currently active sensors built on top of this one need a higher sampling rate, switch to this rate */
for (i = 0; i < sensor_count; i++)
for (vi = 0; vi < sensor[i].base_count; vi++)
if (sensor[i].base[vi] == s && is_enabled(i) && sensor[i].requested_rate > arbitrated_rate) /* If sensor i depends on sensor s */
arbitrated_rate = sensor[i].requested_rate;
/* If any of the currently active sensors we rely on is using a higher sampling rate, switch to this rate */
for (vi = 0; vi < sensor[s].base_count; vi++) {
i = sensor[s].base[vi];
if (is_enabled(i) && sensor[i].requested_rate > arbitrated_rate)
arbitrated_rate = sensor[i].requested_rate;
}
return arbitrated_rate;
}
extern float sensor_get_max_freq (int s);
static float select_closest_available_rate(int s, float requested_rate)
{
float sr;
int j;
float selected_rate = 0;
float max_rate_from_prop = sensor_get_max_freq(s);
if (!sensor[s].avail_freqs_count)
return requested_rate;
for (j = 0; j < sensor[s].avail_freqs_count; j++) {
sr = sensor[s].avail_freqs[j];
/* If this matches the selected rate, we're happy. Have some tolerance for rounding errors and avoid needless jumps to higher rates */
if ((fabs(requested_rate - sr) <= 0.01) && (sr <= max_rate_from_prop)) {
return sr;
}
/* Select rate if it's less than max freq */
if ((sr > selected_rate) && (sr <= max_rate_from_prop)) {
selected_rate = sr;
}
/*
* If we reached a higher value than the desired rate, adjust selected rate so it matches the first higher available one and
* stop parsing - this makes the assumption that rates are sorted by increasing value in the allowed frequencies string.
*/
if (sr > requested_rate) {
return selected_rate;
}
}
/* Check for wrong values */
if (selected_rate < 0.1) {
return requested_rate;
} else {
return selected_rate;
}
}
static int sensor_set_rate (int s, float requested_rate)
{
/* Set the rate at which a specific sensor should report events. See Android sensors.h for indication on sensor trigger modes */
char sysfs_path[PATH_MAX];
int dev_num = sensor[s].dev_num;
int i = sensor[s].catalog_index;
const char *prefix = sensor_catalog[i].tag;
int per_sensor_sampling_rate;
int per_device_sampling_rate;
int n;
float sr;
float group_max_sampling_rate;
float cur_sampling_rate; /* Currently used sampling rate */
float arb_sampling_rate; /* Granted sampling rate after arbitration */
char hrtimer_sampling_path[PATH_MAX];
char trigger_path[PATH_MAX];
ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, s, sensor[s].friendly_name);
sensor[s].requested_rate = requested_rate;
arb_sampling_rate = requested_rate;
if (arb_sampling_rate < sensor[s].min_supported_rate) {
ALOGV("Sampling rate %g too low for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].min_supported_rate);
arb_sampling_rate = sensor[s].min_supported_rate;
}
/* If one of the linked sensors uses a higher rate, adopt it */
group_max_sampling_rate = get_group_max_sampling_rate(s);
if (arb_sampling_rate < group_max_sampling_rate) {
ALOGV("Using %s sampling rate to %g too due to dependency\n", sensor[s].friendly_name, arb_sampling_rate);
arb_sampling_rate = group_max_sampling_rate;
}
if (sensor[s].max_supported_rate && arb_sampling_rate > sensor[s].max_supported_rate) {
ALOGV("Sampling rate %g too high for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].max_supported_rate);
arb_sampling_rate = sensor[s].max_supported_rate;
}
sensor[s].sampling_rate = arb_sampling_rate;
/* If the sensor is virtual, we're done */
if (sensor[s].is_virtual)
return 0;
/* If we're dealing with a poll-mode sensor */
if (sensor[s].mode == MODE_POLL) {
if (is_enabled(s))
pthread_cond_signal(&thread_release_cond[s]); /* Wake up thread so the new sampling rate gets used */
return 0;
}
sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
per_sensor_sampling_rate = 1;
per_device_sampling_rate = 0;
} else {
per_sensor_sampling_rate = 0;
sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
per_device_sampling_rate = 1;
else
per_device_sampling_rate = 0;
}
if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
ALOGE("No way to adjust sampling rate on sensor %d\n", s);
return -ENOSYS;
}
if (sensor[s].hrtimer_trigger_name[0] != '\0') {
snprintf(trigger_path, PATH_MAX, "%s%s%d/", IIO_DEVICES, "trigger", sensor[s].trigger_nr);
snprintf(hrtimer_sampling_path, PATH_MAX, "%s%s", trigger_path, "sampling_frequency");
/* Enforce frequency update when software trigger
* frequency and current sampling rate are different */
if (sysfs_read_float(hrtimer_sampling_path, &sr) != -1 && sr != cur_sampling_rate)
cur_sampling_rate = -1;
} else {
arb_sampling_rate = select_closest_available_rate(s, arb_sampling_rate);
}
/* Record the rate that was agreed upon with the sensor taken in isolation ; this avoid uncontrolled ripple effects between colocated sensor rates */
sensor[s].semi_arbitrated_rate = arb_sampling_rate;
/* Coordinate with others active sensors on the same device, if any */
if (per_device_sampling_rate)
for (n=0; n<sensor_count; n++)
if (n != s && sensor[n].dev_num == dev_num && sensor[n].num_channels && is_enabled(n) &&
sensor[n].semi_arbitrated_rate > arb_sampling_rate) {
ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n", sensor[s].friendly_name, sensor[n].friendly_name,
sensor[n].semi_arbitrated_rate, arb_sampling_rate);
arb_sampling_rate = sensor[n].semi_arbitrated_rate;
}
sensor[s].sampling_rate = arb_sampling_rate;
/* Update actual sampling rate field for this sensor and others which may be sharing the same sampling rate */
if (per_device_sampling_rate)
for (n=0; n<sensor_count; n++)
if (sensor[n].dev_num == dev_num && n != s && sensor[n].num_channels)
sensor[n].sampling_rate = arb_sampling_rate;
/* If the desired rate is already active we're all set */
if (arb_sampling_rate == cur_sampling_rate)
return 0;
ALOGI("Sensor %d (%s) sampling rate set to %g\n", s, sensor[s].friendly_name, arb_sampling_rate);
if (sensor[s].hrtimer_trigger_name[0] != '\0')
sysfs_write_float(hrtimer_sampling_path, ceilf(arb_sampling_rate));
if (trig_sensors_per_dev[dev_num])
enable_buffer(dev_num, 0);
if (sensor[s].hrtimer_trigger_name[0] != '\0') {
sysfs_write_float(sysfs_path, select_closest_available_rate(s, arb_sampling_rate));
} else {
sysfs_write_float(sysfs_path, arb_sampling_rate);
}
/* Check if it makes sense to use an alternate trigger */
tentative_switch_trigger(s);
if (trig_sensors_per_dev[dev_num])
enable_buffer(dev_num, 1);
return 0;
}
static void reapply_sampling_rates (int s)
{
/*
* The specified sensor was either enabled or disabled. Other sensors in the same group may have constraints related to this sensor
* sampling rate on their own sampling rate, so reevaluate them by retrying to use their requested sampling rate, rather than the one
* that ended up being used after arbitration.
*/
int i, j, base;
if (sensor[s].is_virtual) {
/* Take care of downwards dependencies */
for (i=0; i<sensor[s].base_count; i++) {
base = sensor[s].base[i];
sensor_set_rate(base, sensor[base].requested_rate);
}
return;
}
/* Upwards too */
for (i=0; i<sensor_count; i++)
for (j=0; j<sensor[i].base_count; j++)
if (sensor[i].base[j] == s) /* If sensor i depends on sensor s */
sensor_set_rate(i, sensor[i].requested_rate);
}
static int sensor_activate_virtual (int s, int enabled, int from_virtual)
{
int i, base;
sensor[s].event_count = 0;
sensor[s].meta_data_pending = 0;
if (!check_state_change(s, enabled, from_virtual))
return 0; /* The state of the sensor remains the same ; we're done */
if (enabled)
ALOGI("Enabling sensor %d (%s)\n", s, sensor[s].friendly_name);
else
ALOGI("Disabling sensor %d (%s)\n", s, sensor[s].friendly_name);
sensor[s].report_pending = 0;
for (i=0; i<sensor[s].base_count; i++) {
base = sensor[s].base[i];
sensor_activate(base, enabled, 1);
if (enabled)
sensor[base].ref_count++;
else
sensor[base].ref_count--;
}
/* Reevaluate sampling rates of linked sensors */
reapply_sampling_rates(s);
return 0;
}
int sensor_activate (int s, int enabled, int from_virtual)
{
char device_name[PATH_MAX];
struct epoll_event ev = {0};
int dev_fd, event_fd;
int ret, c, d;
int dev_num = sensor[s].dev_num;
size_t field_size;
int catalog_index = sensor[s].catalog_index;