OSDN Git Service

Min/Max delay for Light and Temperature
[android-x86/hardware-intel-libsensors.git] / control.c
index 90bfde9..7d942fd 100644 (file)
--- a/control.c
+++ b/control.c
@@ -6,6 +6,7 @@
 #include <ctype.h>
 #include <fcntl.h>
 #include <pthread.h>
+#include <time.h>
 #include <sys/epoll.h>
 #include <sys/socket.h>
 #include <utils/Log.h>
@@ -40,25 +41,58 @@ static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
  *  */
 #define THREAD_REPORT_TAG_BASE 0x00010000
 
+/* When polling try to compensate for the iio overhead in
+ * order to try to get a frequency closer to the advertised one
+ */
+#define OVERHEAD_THRESHOLD 0.97
+#define ENABLE_BUFFER_RETRIES 10
+#define ENABLE_BUFFER_RETRY_DELAY_MS 10
 
 static int enable_buffer(int dev_num, int enabled)
 {
        char sysfs_path[PATH_MAX];
+       int ret, retries, millisec;
+       struct timespec req = {0};
+
+       retries = ENABLE_BUFFER_RETRIES;
+       millisec = ENABLE_BUFFER_RETRY_DELAY_MS;
+       req.tv_sec = 0;
+       req.tv_nsec = millisec * 1000000L;
 
        sprintf(sysfs_path, ENABLE_PATH, dev_num);
 
-       /* Low level, non-multiplexed, enable/disable routine */
-       return sysfs_write_int(sysfs_path, enabled);
+       while (retries--) {
+               /* Low level, non-multiplexed, enable/disable routine */
+               ret = sysfs_write_int(sysfs_path, enabled);
+               if (ret > 0)
+                       break;
+
+               ALOGE("Failed enabling buffer, retrying");
+               nanosleep(&req, (struct timespec *)NULL);
+       }
+
+       if (ret < 0) {
+               ALOGE("Could not enable buffer\n");
+               return -EIO;
+       }
+
+       return 0;
 }
 
 
-static int setup_trigger(int dev_num, const char* trigger_val)
+static void setup_trigger (int s, const char* trigger_val)
 {
        char sysfs_path[PATH_MAX];
 
-       sprintf(sysfs_path, TRIGGER_PATH, dev_num);
+       sprintf(sysfs_path, TRIGGER_PATH, sensor_info[s].dev_num);
+
+       if (trigger_val[0] != '\n')
+               ALOGI("Setting S%d (%s) trigger to %s\n", s,
+                       sensor_info[s].friendly_name, trigger_val);
+
+       sysfs_write_str(sysfs_path, trigger_val);
 
-       return sysfs_write_str(sysfs_path, trigger_val);
+       sensor_info[s].selected_trigger = trigger_val;
 }
 
 
@@ -157,7 +191,7 @@ void build_sensor_report_maps(int dev_num)
 
                /* Stop sampling - if we are recovering from hal restart */
                 enable_buffer(dev_num, 0);
-                setup_trigger(dev_num, "\n");
+                setup_trigger(s, "\n");
 
                /* Turn on channels we're aware of */
                for (c=0;c<sensor_info[s].num_channels; c++) {
@@ -334,7 +368,7 @@ static void* acquisition_routine (void* param)
         * Bionic does not provide pthread_cancel / pthread_testcancel...
         */
 
-       int s = (int) param;
+       int s = (int) (size_t) param;
        int num_fields;
        struct sensors_event_t data = {0};
        int c;
@@ -343,7 +377,9 @@ static void* acquisition_routine (void* param)
        struct timespec target_time;
        int64_t period;
 
-       ALOGV("Entering data acquisition thread for sensor %d\n", s);
+       ALOGI("Entering data acquisition thread S%d (%s): rate(%f), minDelay(%ld), maxDelay(%ld)\n",
+               s, sensor_info[s].friendly_name, sensor_info[s].sampling_rate,
+               sensor_desc[s].minDelay, sensor_desc[s].maxDelay);
 
        if (s < 0 || s >= sensor_count) {
                ALOGE("Invalid sensor handle!\n");
@@ -398,7 +434,7 @@ static void* acquisition_routine (void* param)
 
 
                period = (int64_t) (1000000000.0/ sensor_info[s].sampling_rate);
-
+               period = period * OVERHEAD_THRESHOLD;
                time_add(&target_time, &entry_time, period);
 
                /*
@@ -450,7 +486,7 @@ static void start_acquisition_thread (int s)
        ret = pthread_create(   &sensor_info[s].acquisition_thread,
                                NULL,
                                acquisition_routine,
-                               (void*) s);
+                               (void*) (size_t) s);
 }
 
 
@@ -494,6 +530,9 @@ int sensor_activate(int s, int enabled)
        int dev_num = sensor_info[s].dev_num;
        int is_poll_sensor = !sensor_info[s].num_channels;
 
+       /* Prepare the report timestamp field for the first event, see set_report_ts method */
+       sensor_info[s].report_ts = 0;
+
        /* If we want to activate gyro calibrated and gyro uncalibrated is activated
         * Deactivate gyro uncalibrated - Uncalibrated releases handler
         * Activate gyro calibrated     - Calibrated has handler
@@ -524,13 +563,13 @@ int sensor_activate(int s, int enabled)
 
                /* Stop sampling */
                enable_buffer(dev_num, 0);
-               setup_trigger(dev_num, "\n");
+               setup_trigger(s, "\n");
 
                /* If there's at least one sensor enabled on this iio device */
                if (trig_sensors_per_dev[dev_num]) {
 
                        /* Start sampling */
-                       setup_trigger(dev_num, sensor_info[s].trigger_name);
+                       setup_trigger(s, sensor_info[s].init_trigger_name);
                        enable_buffer(dev_num, 1);
                }
        }
@@ -558,6 +597,18 @@ int sensor_activate(int s, int enabled)
                                close(dev_fd);
                                device_fd[dev_num] = -1;
                        }
+
+               /* If we recorded a trail of samples for filtering, delete it */
+               if (sensor_info[s].history) {
+                       free(sensor_info[s].history);
+                       sensor_info[s].history = NULL;
+                       sensor_info[s].history_size = 0;
+                       if (sensor_info[s].history_sum) {
+                               free(sensor_info[s].history_sum);
+                               sensor_info[s].history_sum = NULL;
+                       }
+               }
+
                return 0;
        }
 
@@ -605,6 +656,113 @@ int sensor_activate(int s, int enabled)
 }
 
 
+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.
+        */
+       int catalog_index = sensor_info[s].catalog_index;
+
+       if (sensor_catalog[catalog_index].type != SENSOR_TYPE_ACCELEROMETER)
+               return 0;
+
+       if (sensor_info[s].sampling_rate < 25)
+               return 0;
+
+       return 1;
+}
+
+
+static void enable_motion_trigger (int dev_num)
+{
+       /*
+        * In the ideal case, we enumerate two triggers per iio device ; the
+        * default (periodically firing) trigger, and another one (the motion
+        * trigger) that only fires up when motion is detected. This second one
+        * allows for lesser energy consumption, but requires periodic sample
+        * duplication at the HAL level for sensors that Android defines as
+        * continuous. This "duplicate last sample" logic can only be engaged
+        * once we got a first sample for the driver, so we start with the
+        * default trigger when an iio device is first opened, then adjust the
+        * trigger when we got events for all active sensors. Unfortunately in
+        * the general case several sensors can be associated to a given iio
+        * device, they can independently be controlled, and we have to adjust
+        * the trigger in use at the iio device level depending on whether or
+        * not appropriate conditions are met at the sensor level.
+        */
+
+       int s;
+       int i;
+       int active_sensors = trig_sensors_per_dev[dev_num];
+       int candidate[MAX_SENSORS];
+       int candidate_count = 0;
+
+       if  (!active_sensors)
+               return;
+
+       /* Check that all active sensors are ready to switch */
+
+       for (s=0; s<MAX_SENSORS; s++)
+               if (sensor_info[s].dev_num == dev_num &&
+                   sensor_info[s].enable_count &&
+                   sensor_info[s].num_channels &&
+                   (!sensor_info[s].motion_trigger_name[0] ||
+                    !sensor_info[s].report_initialized ||
+                    is_fast_accelerometer(s))
+                   )
+                       return; /* Nope */
+
+       /* Record which particular sensors need to switch */
+
+       for (s=0; s<MAX_SENSORS; s++)
+               if (sensor_info[s].dev_num == dev_num &&
+                   sensor_info[s].enable_count &&
+                   sensor_info[s].num_channels &&
+                   !(sensor_info[s].quirks & QUIRK_CONTINUOUS_DRIVER) &&
+                   sensor_info[s].selected_trigger !=
+                       sensor_info[s].motion_trigger_name)
+                               candidate[candidate_count++] = s;
+
+       if (!candidate_count)
+               return;
+
+       /* Now engage the motion trigger for sensors which aren't using it */
+
+       enable_buffer(dev_num, 0);
+
+       for (i=0; i<candidate_count; i++) {
+               s = candidate[i];
+               setup_trigger(s, sensor_info[s].motion_trigger_name);
+       }
+
+       enable_buffer(dev_num, 1);
+}
+
+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_info[s].report_ts && sensor_info[s].sampling_rate &&
+               REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
+       {
+               period = (int64_t) (1000000000LL / sensor_info[s].sampling_rate);
+               maxTs = sensor_info[s].report_ts + period;
+               sensor_info[s].report_ts = (ts < maxTs ? ts : maxTs);
+       } else {
+               sensor_info[s].report_ts = ts;
+       }
+}
+
 static int integrate_device_report(int dev_num)
 {
        int len;
@@ -666,11 +824,14 @@ static int integrate_device_report(int dev_num)
                        ALOGV("Sensor %d report available (%d bytes)\n", s,
                              sr_offset);
 
-                       sensor_info[s].report_ts = ts;
+                       set_report_ts(s, ts);
                        sensor_info[s].report_pending = 1;
                        sensor_info[s].report_initialized = 1;
                }
 
+       /* Tentatively switch to an any-motion trigger if conditions are met */
+       enable_motion_trigger(dev_num);
+
        return 0;
 }
 
@@ -753,8 +914,9 @@ static void synthetize_duplicate_samples (void)
                if (!sensor_info[s].enable_count)
                        continue;
 
-               /* If the sensor can generate duplicates, leave it alone */
-               if (!(sensor_info[s].quirks & QUIRK_TERSE_DRIVER))
+               /* If the sensor is continuously firing, leave it alone */
+               if (    sensor_info[s].selected_trigger !=
+                       sensor_info[s].motion_trigger_name)
                        continue;
 
                /* If we haven't seen a sample, there's nothing to duplicate */
@@ -776,7 +938,7 @@ static void synthetize_duplicate_samples (void)
 
                if (target_ts <= current_ts) {
                        /* Mark the sensor for event generation */
-                       sensor_info[s].report_ts = current_ts;
+                       set_report_ts(s, current_ts);
                        sensor_info[s].report_pending = 1;
                }
        }
@@ -796,7 +958,7 @@ static void integrate_thread_report (uint32_t tag)
                   expected_len);
 
        if (len == expected_len) {
-               sensor_info[s].report_ts = get_timestamp();
+               set_report_ts(s, get_timestamp());
                sensor_info[s].report_pending = 1;
        }
 }
@@ -823,7 +985,8 @@ static int get_poll_wait_timeout (void)
         */
        for (s=0; s<sensor_count; s++)
                if (sensor_info[s].enable_count &&
-                   (sensor_info[s].quirks & QUIRK_TERSE_DRIVER) &&
+                   sensor_info[s].selected_trigger ==
+                   sensor_info[s].motion_trigger_name &&
                    sensor_info[s].sampling_rate) {
                        period = (int64_t) (1000000000.0 /
                                                sensor_info[s].sampling_rate);
@@ -838,14 +1001,9 @@ static int get_poll_wait_timeout (void)
 
        ms_to_wait = (target_ts - get_timestamp()) / 1000000;
 
-       /*
-        * If the target timestamp is very close or already behind us, wait
-        * nonetheless for a millisecond in order to a) avoid busy loops, and
-        * b) give a chance for the driver to report data before we repeat the
-        * last received sample.
-        */
-       if (ms_to_wait <= 0)
-               return 1;
+       /* If the target timestamp is already behind us, don't wait */
+       if (ms_to_wait < 1)
+               return 0;
 
        return ms_to_wait;
 }
@@ -859,11 +1017,15 @@ int sensor_poll(struct sensors_event_t* data, int count)
        struct epoll_event ev[MAX_DEVICES];
        int returned_events;
        int event_count;
+       int uncal_start;
 
        /* Get one or more events from our collection of sensors */
 
 return_available_sensor_reports:
 
+       /* Synthetize duplicate samples if needed */
+       synthetize_duplicate_samples();
+
        returned_events = 0;
 
        /* Check our sensor collection for available reports */
@@ -883,17 +1045,19 @@ return_available_sensor_reports:
 
                                        memcpy(&data[returned_events + event_count], &data[returned_events],
                                                        sizeof(struct sensors_event_t) * event_count);
+
+                                       uncal_start = returned_events + event_count;
                                        for (i = 0; i < event_count; i++) {
-                                               data[returned_events + i].type = SENSOR_TYPE_GYROSCOPE_UNCALIBRATED;
-                                               data[returned_events + i].sensor = sensor_info[s].pair_idx;
+                                               data[uncal_start + i].type = SENSOR_TYPE_GYROSCOPE_UNCALIBRATED;
+                                               data[uncal_start + i].sensor = sensor_info[s].pair_idx;
 
-                                               data[returned_events + i].data[0] = data[returned_events + i].data[0] + gyro_data->bias[0];
-                                               data[returned_events + i].data[1] = data[returned_events + i].data[1] + gyro_data->bias[1];
-                                               data[returned_events + i].data[2] = data[returned_events + i].data[2] + gyro_data->bias[2];
+                                               data[uncal_start + i].data[0] = data[returned_events + i].data[0] + gyro_data->bias_x;
+                                               data[uncal_start + i].data[1] = data[returned_events + i].data[1] + gyro_data->bias_y;
+                                               data[uncal_start + i].data[2] = data[returned_events + i].data[2] + gyro_data->bias_z;
 
-                                               data[returned_events + i].uncalibrated_gyro.bias[0] = gyro_data->bias[0];
-                                               data[returned_events + i].uncalibrated_gyro.bias[1] = gyro_data->bias[1];
-                                               data[returned_events + i].uncalibrated_gyro.bias[2] = gyro_data->bias[2];
+                                               data[uncal_start + i].uncalibrated_gyro.bias[0] = gyro_data->bias_x;
+                                               data[uncal_start + i].uncalibrated_gyro.bias[1] = gyro_data->bias_y;
+                                               data[uncal_start + i].uncalibrated_gyro.bias[2] = gyro_data->bias_z;
                                        }
                                        event_count <<= 1;
                        }
@@ -920,9 +1084,6 @@ await_event:
                goto await_event;
        }
 
-       /* Synthetize duplicate samples if needed */
-       synthetize_duplicate_samples();
-
        ALOGV("%d fds signalled\n", nfds);
 
        /* For each of the signalled sources */
@@ -964,7 +1125,11 @@ int sensor_set_delay(int s, int64_t ns)
        float cur_sampling_rate; /* Currently used sampling rate              */
        int per_sensor_sampling_rate;
        int per_device_sampling_rate;
-       float max_supported_rate = 0;
+       int32_t min_delay_us = sensor_desc[s].minDelay;
+       max_delay_t max_delay_us = sensor_desc[s].maxDelay;
+       float min_supported_rate = max_delay_us ? (1000000.0f / max_delay_us) : 1;
+       float max_supported_rate = 
+               (min_delay_us && min_delay_us != -1) ? (1000000.0f / min_delay_us) : 0;
        char freqs_buf[100];
        char* cursor;
        int n;
@@ -981,8 +1146,13 @@ int sensor_set_delay(int s, int64_t ns)
         * Artificially limit ourselves to 1 Hz or higher. This is mostly to
         * avoid setting up the stage for divisions by zero.
         */
-       if (new_sampling_rate < 1)
-               new_sampling_rate = 1;
+       if (new_sampling_rate < min_supported_rate)
+               new_sampling_rate = min_supported_rate;
+
+       if (max_supported_rate &&
+               new_sampling_rate > max_supported_rate) {
+               new_sampling_rate = max_supported_rate;
+       }
 
        sensor_info[s].sampling_rate = new_sampling_rate;
 
@@ -1038,9 +1208,6 @@ int sensor_set_delay(int s, int64_t ns)
                        /* Decode a single value */
                        sr = strtod(cursor, NULL);
 
-                       if (sr > max_supported_rate)
-                               max_supported_rate = sr;
-
                        /* If this matches the selected rate, we're happy */
                        if (new_sampling_rate == sr)
                                break;
@@ -1085,6 +1252,11 @@ int sensor_set_delay(int s, int64_t ns)
 
        sysfs_write_float(sysfs_path, new_sampling_rate);
 
+       /* Switch back to continuous sampling for accelerometer based games */
+       if (is_fast_accelerometer(s) && sensor_info[s].selected_trigger !=
+                                       sensor_info[s].init_trigger_name)
+               setup_trigger(s, sensor_info[s].init_trigger_name);
+
        if (trig_sensors_per_dev[dev_num])
                enable_buffer(dev_num, 1);