OSDN Git Service

GMINL-2659: Keep recent events history for fusion-like processing
[android-x86/hardware-intel-libsensors.git] / control.c
index 2fc6c33..b7ed570 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>
@@ -27,9 +28,12 @@ static int poll_fd; /* epoll instance covering all enabled sensors */
 
 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
 
+int64_t ts_delta; /* delta between SystemClock.getNanos and our timestamp */
+
 /* We use pthread condition variables to get worker threads out of sleep */
-static pthread_cond_t  thread_release_cond     [MAX_SENSORS];
-static pthread_mutex_t thread_release_mutex    [MAX_SENSORS];
+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];
 
 /*
  * We associate tags to each of our poll set entries. These tags have the
@@ -40,25 +44,63 @@ static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
  *  */
 #define THREAD_REPORT_TAG_BASE 0x00010000
 
+#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 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_info[s].dev_num);
 
-       sprintf(sysfs_path, TRIGGER_PATH, dev_num);
+       if (trigger_val[0] != '\n')
+               ALOGI("Setting S%d (%s) trigger to %s\n", s,
+                       sensor_info[s].friendly_name, trigger_val);
+
+       while (ret == -1 && attempts) {
+               ret = sysfs_write_str(sysfs_path, trigger_val);
+               attempts--;
+       }
 
-       return sysfs_write_str(sysfs_path, trigger_val);
+       if (ret != -1)
+               sensor_info[s].selected_trigger = trigger_val;
+       else
+               ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s,
+                       sensor_info[s].friendly_name, trigger_val);
+       return ret;
 }
 
 
@@ -157,7 +199,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++) {
@@ -210,8 +252,6 @@ int adjust_counters (int s, int enabled)
         */
 
        int dev_num = sensor_info[s].dev_num;
-       int catalog_index = sensor_info[s].catalog_index;
-       int sensor_type = sensor_catalog[catalog_index].type;
 
        /* Refcount per sensor, in terms of enable count */
        if (enabled) {
@@ -223,7 +263,7 @@ int adjust_counters (int s, int enabled)
                if (sensor_info[s].enable_count > 1)
                        return 0; /* The sensor was, and remains, in use */
 
-               switch (sensor_type) {
+               switch (sensor_info[s].type) {
                        case SENSOR_TYPE_MAGNETIC_FIELD:
                                compass_read_data(&sensor_info[s]);
                                break;
@@ -248,13 +288,17 @@ int adjust_counters (int s, int enabled)
                /* Sensor disabled, lower report available flag */
                sensor_info[s].report_pending = 0;
 
-               if (sensor_type == SENSOR_TYPE_MAGNETIC_FIELD)
+               if (sensor_info[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
                        compass_store_data(&sensor_info[s]);
+
+               if(sensor_info[s].type == SENSOR_TYPE_GYROSCOPE ||
+                       sensor_info[s].type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED)
+                       gyro_store_data(&sensor_info[s]);
        }
 
 
        /* If uncalibrated type and pair is already active don't adjust counters */
-       if (sensor_type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED &&
+       if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED &&
                sensor_info[sensor_info[s].pair_idx].enable_count != 0)
                        return 0;
 
@@ -285,10 +329,7 @@ int adjust_counters (int s, int enabled)
 
 static int get_field_count (int s)
 {
-       int catalog_index = sensor_info[s].catalog_index;
-       int sensor_type   = sensor_catalog[catalog_index].type;
-
-       switch (sensor_type) {
+       switch (sensor_info[s].type) {
                case SENSOR_TYPE_ACCELEROMETER:         /* m/s^2        */
                case SENSOR_TYPE_MAGNETIC_FIELD:        /* micro-tesla  */
                case SENSOR_TYPE_ORIENTATION:           /* degrees      */
@@ -314,15 +355,6 @@ static int get_field_count (int s)
 }
 
 
-static void time_add(struct timespec *out, struct timespec *in, int64_t ns)
-{
-       int64_t target_ts = 1000000000LL * in->tv_sec + in->tv_nsec + ns;
-
-       out->tv_sec = target_ts / 1000000000;
-       out->tv_nsec = target_ts % 1000000000;
-}
-
-
 static void* acquisition_routine (void* param)
 {
        /*
@@ -334,28 +366,30 @@ static void* acquisition_routine (void* param)
         * Bionic does not provide pthread_cancel / pthread_testcancel...
         */
 
-       int s = (int) param;
-       int num_fields;
+       int s = (int) (size_t) param;
+       int num_fields, sample_size;
        struct sensors_event_t data = {0};
        int c;
        int ret;
-       struct timespec entry_time;
        struct timespec target_time;
-       int64_t period;
-
-       ALOGV("Entering data acquisition thread for sensor %d\n", s);
+       int64_t timestamp, period;
 
        if (s < 0 || s >= sensor_count) {
                ALOGE("Invalid sensor handle!\n");
                return NULL;
        }
 
-       if (!sensor_info[s].sampling_rate) {
-               ALOGE("Zero rate in acquisition routine for sensor %d\n", s);
+       ALOGI("Entering data acquisition thread S%d (%s): rate(%f), ts(%lld)\n", s,
+               sensor_info[s].friendly_name, sensor_info[s].sampling_rate, sensor_info[s].report_ts);
+
+       if (sensor_info[s].sampling_rate <= 0) {
+               ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
+                       s, sensor_info[s].sampling_rate);
                return NULL;
        }
 
        num_fields = get_field_count(s);
+       sample_size = num_fields * sizeof(float);
 
        /*
         * Each condition variable is associated to a mutex that has to be
@@ -365,22 +399,18 @@ static void* acquisition_routine (void* param)
         */
        pthread_mutex_lock(&thread_release_mutex[s]);
 
-       while (1) {
-               /* Pinpoint the moment we start sampling */
-               clock_gettime(CLOCK_REALTIME, &entry_time);
+       /* Pinpoint the moment we start sampling */
+       timestamp = get_timestamp_monotonic();
 
-               ALOGV("Acquiring sample data for sensor %d through sysfs\n", s);
+       /* Check and honor termination requests */
+       while (sensor_info[s].thread_data_fd[1] != -1) {
 
                /* Read values through sysfs */
                for (c=0; c<num_fields; c++) {
                        data.data[c] = acquire_immediate_value(s, c);
-
                        /* Check and honor termination requests */
                        if (sensor_info[s].thread_data_fd[1] == -1)
                                goto exit;
-
-                       ALOGV("\tfield %d: %f\n", c, data.data[c]);
-
                }
 
                /* If the sample looks good */
@@ -388,18 +418,27 @@ static void* acquisition_routine (void* param)
 
                        /* Pipe it for transmission to poll loop */
                        ret = write(    sensor_info[s].thread_data_fd[1],
-                                       data.data,
-                                       num_fields * sizeof(float));
+                                       data.data, sample_size);
+                       if (ret != sample_size)
+                               ALOGE("S%d acquisition thread: tried to write %d, ret: %d\n",
+                                       s, sample_size, ret);
                }
 
                /* Check and honor termination requests */
                if (sensor_info[s].thread_data_fd[1] == -1)
                        goto exit;
 
+               /* Recalculate period asumming sensor_info[s].sampling_rate
+                * can be changed dynamically during the thread run */
+               if (sensor_info[s].sampling_rate <= 0) {
+                       ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
+                               s, sensor_info[s].sampling_rate);
+                       goto exit;
+               }
 
-               period = 1000000000LL / sensor_info[s].sampling_rate;
-
-               time_add(&target_time, &entry_time, period);
+               period = (int64_t) (1000000000LL / sensor_info[s].sampling_rate);
+               timestamp += period;
+               set_timestamp(&target_time, timestamp);
 
                /*
                 * Wait until the sampling time elapses, or a rate change is
@@ -408,10 +447,6 @@ static void* acquisition_routine (void* param)
                ret = pthread_cond_timedwait(   &thread_release_cond[s],
                                                &thread_release_mutex[s],
                                                &target_time);
-
-               /* Check and honor termination requests */
-               if (sensor_info[s].thread_data_fd[1] == -1)
-                               goto exit;
        }
 
 exit:
@@ -432,7 +467,9 @@ static void start_acquisition_thread (int s)
        ALOGV("Initializing acquisition context for sensor %d\n", s);
 
        /* Create condition variable and mutex for quick thread release */
-       ret = pthread_cond_init(&thread_release_cond[s], NULL);
+       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 */
@@ -450,7 +487,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);
 }
 
 
@@ -488,13 +525,17 @@ static void stop_acquisition_thread (int s)
 int sensor_activate(int s, int enabled)
 {
        char device_name[PATH_MAX];
-       char trigger_name[MAX_NAME_SIZE + 16];
        struct epoll_event ev = {0};
        int dev_fd;
        int ret;
        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;
+       ts_delta = load_timestamp_sys_clock() - get_timestamp_monotonic();
+
+
        /* If we want to activate gyro calibrated and gyro uncalibrated is activated
         * Deactivate gyro uncalibrated - Uncalibrated releases handler
         * Activate gyro calibrated     - Calibrated has handler
@@ -505,7 +546,7 @@ int sensor_activate(int s, int enabled)
         * Deactivate gyro calibrated   - Calibrated releases handler
         * Reactivate gyro uncalibrated - Uncalibrated has handler */
 
-       if (sensor_catalog[sensor_info[s].catalog_index].type == SENSOR_TYPE_GYROSCOPE &&
+       if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE &&
                sensor_info[s].pair_idx && sensor_info[sensor_info[s].pair_idx].enable_count != 0) {
 
                                sensor_activate(sensor_info[s].pair_idx, 0);
@@ -525,15 +566,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]) {
-                       sprintf(trigger_name, "%s-dev%d",
-                                       sensor_info[s].internal_name, dev_num);
 
                        /* Start sampling */
-                       setup_trigger(dev_num, trigger_name);
+                       setup_trigger(s, sensor_info[s].init_trigger_name);
                        enable_buffer(dev_num, 1);
                }
        }
@@ -561,6 +600,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;
        }
 
@@ -608,7 +659,120 @@ int sensor_activate(int s, int enabled)
 }
 
 
-static int integrate_device_report(int dev_num)
+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_info[s].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) ||
+                    (sensor_info[s].quirks & QUIRK_FORCE_CONTINUOUS))
+                   )
+                       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].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);
+}
+
+/* CTS acceptable thresholds:
+ *     EventGapVerification.java: (th <= 1.8)
+ *     FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
+ */
+#define THRESHOLD 1.10
+void set_report_ts(int s, int64_t ts)
+{
+       int64_t maxTs, period;
+       int catalog_index = sensor_info[s].catalog_index;
+       int is_accel      = (sensor_catalog[catalog_index].type == SENSOR_TYPE_ACCELEROMETER);
+
+       /*
+       *  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 + (is_accel ? 1 : THRESHOLD) * 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;
        int s,c;
@@ -617,7 +781,6 @@ static int integrate_device_report(int dev_num)
        unsigned char *target;
        unsigned char *source;
        int size;
-       int64_t ts;
 
        /* There's an incoming report on the specified iio device char dev fd */
 
@@ -631,7 +794,7 @@ static int integrate_device_report(int dev_num)
                return -1;
        }
 
-       ts = get_timestamp();
+
 
        len = read(device_fd[dev_num], buf, MAX_SENSOR_REPORT_SIZE);
 
@@ -643,6 +806,8 @@ static int integrate_device_report(int dev_num)
 
        ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
 
+       /* Map device report to sensor reports */
+
        for (s=0; s<MAX_SENSORS; s++)
                if (sensor_info[s].dev_num == dev_num &&
                    sensor_info[s].enable_count) {
@@ -667,20 +832,22 @@ 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;
-                       sensor_info[s].report_pending = 1;
+                       set_report_ts(s, get_timestamp());
+                       sensor_info[s].report_pending = DATA_TRIGGER;
+                       sensor_info[s].report_initialized = 1;
                }
 
+       /* Tentatively switch to an any-motion trigger if conditions are met */
+       enable_motion_trigger(dev_num);
+
        return 0;
 }
 
 
-static int propagate_sensor_report(int s, struct sensors_event_t  *data)
+static int propagate_sensor_report (int s, struct sensors_event_t  *data)
 {
        /* There's a sensor report pending for this sensor ; transmit it */
 
-       int catalog_index = sensor_info[s].catalog_index;
-       int sensor_type   = sensor_catalog[catalog_index].type;
        int num_fields    = get_field_count(s);
        int c;
        unsigned char* current_sample;
@@ -691,7 +858,7 @@ static int propagate_sensor_report(int s, struct sensors_event_t  *data)
 
 
        /* Only return uncalibrated event if also gyro active */
-       if (sensor_type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED &&
+       if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED &&
                sensor_info[sensor_info[s].pair_idx].enable_count != 0)
                        return 0;
 
@@ -699,10 +866,10 @@ static int propagate_sensor_report(int s, struct sensors_event_t  *data)
 
        data->version   = sizeof(sensors_event_t);
        data->sensor    = s;
-       data->type      = sensor_type;
+       data->type      = sensor_info[s].type;
        data->timestamp = sensor_info[s].report_ts;
 
-       ALOGV("Sample on sensor %d (type %d):\n", s, sensor_type);
+       ALOGV("Sample on sensor %d (type %d):\n", s, sensor_info[s].type);
 
        current_sample = sensor_info[s].report_buffer;
 
@@ -732,6 +899,58 @@ static int propagate_sensor_report(int s, struct sensors_event_t  *data)
 }
 
 
+static void synthetize_duplicate_samples (void)
+{
+       /*
+        * Some sensor types (ex: gyroscope) are defined as continuously firing
+        * by Android, despite the fact that we can be dealing with iio drivers
+        * that only report events for new samples. For these we generate
+        * reports periodically, duplicating the last data we got from the
+        * driver. This is not necessary for polling sensors.
+        */
+
+       int s;
+       int64_t current_ts;
+       int64_t target_ts;
+       int64_t period;
+
+       for (s=0; s<sensor_count; s++) {
+
+               /* Ignore disabled sensors */
+               if (!sensor_info[s].enable_count)
+                       continue;
+
+               /* 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 */
+               if (!sensor_info[s].report_initialized)
+                       continue;
+
+               /* If a sample was recently buffered, leave it alone too */
+               if (sensor_info[s].report_pending)
+                       continue;
+
+               /* We also need a valid sampling rate to be configured */
+               if (!sensor_info[s].sampling_rate)
+                       continue;
+
+               period = (int64_t) (1000000000.0/ sensor_info[s].sampling_rate);
+
+               current_ts = get_timestamp();
+               target_ts = sensor_info[s].report_ts + period;
+
+               if (target_ts <= current_ts) {
+                       /* Mark the sensor for event generation */
+                       set_report_ts(s, current_ts);
+                       sensor_info[s].report_pending = DATA_DUPLICATE;
+               }
+       }
+}
+
+
 static void integrate_thread_report (uint32_t tag)
 {
        int s = tag - THREAD_REPORT_TAG_BASE;
@@ -745,12 +964,57 @@ static void integrate_thread_report (uint32_t tag)
                   expected_len);
 
        if (len == expected_len) {
-               sensor_info[s].report_ts = get_timestamp();
-               sensor_info[s].report_pending = 1;
+               set_report_ts(s, get_timestamp());
+               sensor_info[s].report_pending = DATA_SYSFS;
        }
 }
 
 
+static int get_poll_wait_timeout (void)
+{
+       /*
+        * Compute an appropriate timeout value, in ms, for the epoll_wait
+        * call that's going to await for iio device reports and incoming
+        * reports from our sensor sysfs data reader threads.
+        */
+
+       int s;
+       int64_t target_ts = INT64_MAX;
+       int64_t ms_to_wait;
+       int64_t period;
+
+       /*
+        * Check if we're dealing with a driver that only send events when
+        * there is motion, despite the fact that the associated Android sensor
+        * type is continuous rather than on-change. In that case we have to
+        * duplicate events. Check deadline for the nearest upcoming event.
+        */
+       for (s=0; s<sensor_count; s++)
+               if (sensor_info[s].enable_count &&
+                   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);
+
+                       if (sensor_info[s].report_ts + period < target_ts)
+                               target_ts = sensor_info[s].report_ts + period;
+               }
+
+       /* If we don't have such a driver to deal with */
+       if (target_ts == INT64_MAX)
+               return -1; /* Infinite wait */
+
+       ms_to_wait = (target_ts - get_timestamp()) / 1000000;
+
+       /* If the target timestamp is already behind us, don't wait */
+       if (ms_to_wait < 1)
+               return 0;
+
+       return ms_to_wait;
+}
+
+
 int sensor_poll(struct sensors_event_t* data, int count)
 {
        int s;
@@ -759,41 +1023,48 @@ 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 */
-       for (s=0; s<sensor_count && returned_events < count; s++)
+       for (s=0; s<sensor_count && returned_events < count; s++) {
                if (sensor_info[s].report_pending) {
                        event_count = 0;
-                       /* Lower flag */
-                       sensor_info[s].report_pending = 0;
 
                        /* Report this event if it looks OK */
                        event_count = propagate_sensor_report(s, &data[returned_events]);
 
+                       /* Lower flag */
+                       sensor_info[s].report_pending = 0;
+
                        /* Duplicate only if both cal & uncal are active */
-                       if (sensor_catalog[sensor_info[s].catalog_index].type == SENSOR_TYPE_GYROSCOPE &&
+                       if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE &&
                                        sensor_info[s].pair_idx && sensor_info[sensor_info[s].pair_idx].enable_count != 0) {
                                        struct gyro_cal* gyro_data = (struct gyro_cal*) sensor_info[s].cal_data;
 
                                        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;
                        }
@@ -805,7 +1076,19 @@ return_available_sensor_reports:
                         * value for a 'on change' sensor, silently drop it.
                         */
                }
-
+               while (sensor_info[s].meta_data_pending) {
+                       /* See sensors.h on these */
+                       data[returned_events].version = META_DATA_VERSION;
+                       data[returned_events].sensor = 0;
+                       data[returned_events].type = SENSOR_TYPE_META_DATA;
+                       data[returned_events].reserved0 = 0;
+                       data[returned_events].timestamp = 0;
+                       data[returned_events].meta_data.sensor = s;
+                       data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
+                       returned_events++;
+                       sensor_info[s].meta_data_pending--;
+               }
+       }
        if (returned_events)
                return returned_events;
 
@@ -813,10 +1096,10 @@ await_event:
 
        ALOGV("Awaiting sensor data\n");
 
-       nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, -1);
+       nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
 
        if (nfds == -1) {
-               ALOGI("epoll_wait returned -1 (%s)\n", strerror(errno));
+               ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
                goto await_event;
        }
 
@@ -846,6 +1129,25 @@ await_event:
 }
 
 
+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_info[s].quirks & QUIRK_TERSE_DRIVER) &&
+                       sensor_info[s].selected_trigger ==
+                               sensor_info[s].motion_trigger_name)
+               setup_trigger(s, sensor_info[s].init_trigger_name);
+}
+
+
 int sensor_set_delay(int s, int64_t ns)
 {
        /* Set the rate at which a specific sensor should report events */
@@ -861,25 +1163,38 @@ 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;
        float sr;
 
-       if (!ns) {
-               ALOGE("Rejecting zero delay request on sensor %d\n", s);
+       if (ns <= 0) {
+               ALOGE("Rejecting non-positive delay request on sensor %d, required delay: %lld\n", s, ns);
                return -EINVAL;
        }
 
        new_sampling_rate = 1000000000LL/ns;
 
+       ALOGV("Entering set delay S%d (%s): old rate(%f), new rate(%f)\n",
+               s, sensor_info[s].friendly_name, sensor_info[s].sampling_rate,
+               new_sampling_rate);
+
        /*
         * 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;
 
@@ -935,9 +1250,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;
@@ -964,13 +1276,11 @@ int sensor_set_delay(int s, int64_t ns)
                }
        }
 
-
        if (max_supported_rate &&
                new_sampling_rate > max_supported_rate) {
                new_sampling_rate = max_supported_rate;
        }
 
-
        /* If the desired rate is already active we're all set */
        if (new_sampling_rate == cur_sampling_rate)
                return 0;
@@ -982,12 +1292,25 @@ int sensor_set_delay(int s, int64_t ns)
 
        sysfs_write_float(sysfs_path, new_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;
 }
 
+int sensor_flush (int s)
+{
+       /* If one shot or not enabled return -EINVAL */
+       if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE ||
+               sensor_info[s].enable_count == 0)
+               return -EINVAL;
+
+       sensor_info[s].meta_data_pending++;
+       return 0;
+}
 
 int allocate_control_data (void)
 {