Merge "[SurfaceFlinger] Remove getDisplayBrightnessSupport." into qt-dev
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index a5cc0df..dbb4f22 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -534,7 +534,7 @@
         }
         AddRuntimeArg(target_sdk_version_arg);
         if (enable_hidden_api_checks) {
-            AddRuntimeArg("-Xhidden-api-checks");
+            AddRuntimeArg("-Xhidden-api-policy:enabled");
         }
 
         if (dex_metadata_fd > -1) {
diff --git a/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl b/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl
index b1c577e..70ed80d 100644
--- a/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl
+++ b/libs/binder/aidl/android/content/pm/IPackageManagerNative.aidl
@@ -66,15 +66,12 @@
     const int LOCATION_VENDOR = 0x2;
     /*  ApplicationInfo.isProduct() == true */
     const int LOCATION_PRODUCT = 0x4;
-    /*  ApplicationInfo.isProductServices() == true */
-    const int LOCATION_PRODUCT_SERVICES = 0x8;
 
     /**
      * Returns a set of bitflags about package location.
      * LOCATION_SYSTEM: getApplicationInfo(packageName).isSystemApp()
      * LOCATION_VENDOR: getApplicationInfo(packageName).isVendor()
      * LOCATION_PRODUCT: getApplicationInfo(packageName).isProduct()
-     * LOCATION_PRODUCT_SERVICES: getApplicationInfo(packageName).isProductService()
      */
     int getLocationFlags(in @utf8InCpp String packageName);
 }
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index 4ff69c5..c94c6b3 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -1007,14 +1007,6 @@
         mCallbackCondition.notify_all();
     }
 
-    // Wait without lock held
-    if (connectedApi == NATIVE_WINDOW_API_EGL) {
-        // Waiting here allows for two full buffers to be queued but not a
-        // third. In the event that frames take varying time, this makes a
-        // small trade-off in favor of latency rather than throughput.
-        lastQueuedFence->waitForever("Throttling EGL Production");
-    }
-
     // Update and get FrameEventHistory.
     nsecs_t postedTime = systemTime(SYSTEM_TIME_MONOTONIC);
     NewFrameEventsEntry newFrameEventsEntry = {
@@ -1026,6 +1018,14 @@
     addAndGetFrameTimestamps(&newFrameEventsEntry,
             getFrameTimestamps ? &output->frameTimestamps : nullptr);
 
+    // Wait without lock held
+    if (connectedApi == NATIVE_WINDOW_API_EGL) {
+        // Waiting here allows for two full buffers to be queued but not a
+        // third. In the event that frames take varying time, this makes a
+        // small trade-off in favor of latency rather than throughput.
+        lastQueuedFence->waitForever("Throttling EGL Production");
+    }
+
     return NO_ERROR;
 }
 
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index 93b4191..e6eb327 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -829,8 +829,9 @@
     mDefaultHeight = output.height;
     mNextFrameNumber = output.nextFrameNumber;
 
-    // Disable transform hint if sticky transform is set.
-    if (mStickyTransform == 0) {
+    // Ignore transform hint if sticky transform is set or transform to display inverse flag is
+    // set.
+    if (mStickyTransform == 0 && !transformToDisplayInverse()) {
         mTransformHint = output.transformHint;
     }
 
@@ -1271,6 +1272,11 @@
     return getConsumerUsage(usage);
 }
 
+bool Surface::transformToDisplayInverse() {
+    return (mTransform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) ==
+            NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+}
+
 int Surface::connect(int api) {
     static sp<IProducerListener> listener = new DummyProducerListener();
     return connect(api, listener);
@@ -1293,8 +1299,10 @@
         mDefaultHeight = output.height;
         mNextFrameNumber = output.nextFrameNumber;
 
-        // Disable transform hint if sticky transform is set.
-        if (mStickyTransform == 0) {
+        // Ignore transform hint if sticky transform is set or transform to display inverse flag is
+        // set. Transform hint should be ignored if the client is expected to always submit buffers
+        // in the same orientation.
+        if (mStickyTransform == 0 && !transformToDisplayInverse()) {
             mTransformHint = output.transformHint;
         }
 
@@ -1591,6 +1599,13 @@
     ATRACE_CALL();
     ALOGV("Surface::setBuffersTransform");
     Mutex::Autolock lock(mMutex);
+    // Ensure NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY is sticky. If the client sets the flag, do not
+    // override it until the surface is disconnected. This is a temporary workaround for camera
+    // until they switch to using Buffer State Layers. Currently if client sets the buffer transform
+    // it may be overriden by the buffer producer when the producer sets the buffer transform.
+    if (transformToDisplayInverse()) {
+        transform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+    }
     mTransform = transform;
     return NO_ERROR;
 }
diff --git a/libs/gui/include/gui/Surface.h b/libs/gui/include/gui/Surface.h
index 248e105..0c471bb 100644
--- a/libs/gui/include/gui/Surface.h
+++ b/libs/gui/include/gui/Surface.h
@@ -230,6 +230,7 @@
     int dispatchGetWideColorSupport(va_list args);
     int dispatchGetHdrSupport(va_list args);
     int dispatchGetConsumerUsage64(va_list args);
+    bool transformToDisplayInverse();
 
 protected:
     virtual int dequeueBuffer(ANativeWindowBuffer** buffer, int* fenceFd);
diff --git a/libs/input/VelocityTracker.cpp b/libs/input/VelocityTracker.cpp
index 42d774e..c6cc4fc 100644
--- a/libs/input/VelocityTracker.cpp
+++ b/libs/input/VelocityTracker.cpp
@@ -382,7 +382,16 @@
 
 void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
         const VelocityTracker::Position* positions) {
-    if (++mIndex == HISTORY_SIZE) {
+    if (mMovements[mIndex].eventTime != eventTime) {
+        // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
+        // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
+        // the new pointer. If the eventtimes for both events are identical, just update the data
+        // for this time.
+        // We only compare against the last value, as it is likely that addMovement is called
+        // in chronological order as events occur.
+        mIndex++;
+    }
+    if (mIndex == HISTORY_SIZE) {
         mIndex = 0;
     }
 
@@ -1017,7 +1026,16 @@
 
 void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
         const VelocityTracker::Position* positions) {
-    if (++mIndex == HISTORY_SIZE) {
+    if (mMovements[mIndex].eventTime != eventTime) {
+        // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
+        // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
+        // the new pointer. If the eventtimes for both events are identical, just update the data
+        // for this time.
+        // We only compare against the last value, as it is likely that addMovement is called
+        // in chronological order as events occur.
+        mIndex++;
+    }
+    if (mIndex == HISTORY_SIZE) {
         mIndex = 0;
     }
 
diff --git a/libs/input/tests/VelocityTracker_test.cpp b/libs/input/tests/VelocityTracker_test.cpp
index a106451..368446f 100644
--- a/libs/input/tests/VelocityTracker_test.cpp
+++ b/libs/input/tests/VelocityTracker_test.cpp
@@ -17,12 +17,14 @@
 #define LOG_TAG "VelocityTracker_test"
 
 #include <array>
+#include <chrono>
 #include <math.h>
 
 #include <android-base/stringprintf.h>
 #include <gtest/gtest.h>
 #include <input/VelocityTracker.h>
 
+using namespace std::chrono_literals;
 using android::base::StringPrintf;
 
 namespace android {
@@ -66,60 +68,136 @@
     EXPECT_NEAR_BY_FRACTION(actual, target, COEFFICIENT_TOLERANCE);
 }
 
-static void failWithMessage(std::string message) {
-    FAIL() << message; // cannot do this directly from a non-void function
-}
-
 struct Position {
-    nsecs_t time;
     float x;
     float y;
+
+    /**
+     * If both values are NAN, then this is considered to be an empty entry (no pointer data).
+     * If only one of the values is NAN, this is still a valid entry,
+     * because we may only care about a single axis.
+     */
+    bool isValid() const {
+        return !(isnan(x) && isnan(y));
+    }
 };
 
-static std::unique_ptr<MotionEvent> createSimpleMotionEvent(
-        const std::vector<Position>& positions) {
-    /**
-     * Only populate the basic fields of a MotionEvent, such as time and a single axis
-     * Designed for use with manually-defined tests.
-     */
-    if (positions.empty()) {
-        failWithMessage("Need at least 1 sample to create a MotionEvent. Received empty vector.");
+struct MotionEventEntry {
+    std::chrono::nanoseconds eventTime;
+    std::vector<Position> positions;
+};
+
+static BitSet32 getValidPointers(const std::vector<Position>& positions) {
+    BitSet32 pointers;
+    for (size_t i = 0; i < positions.size(); i++) {
+        if (positions[i].isValid()) {
+            pointers.markBit(i);
+        }
     }
-
-    std::unique_ptr<MotionEvent> event = std::make_unique<MotionEvent>();
-
-    constexpr size_t pointerCount = 1;
-    PointerCoords coords[pointerCount];
-    coords[0].clear();
-
-    PointerProperties properties[pointerCount];
-    properties[0].id = DEFAULT_POINTER_ID;
-    properties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
-
-    // First sample added separately with initialize
-    coords[0].setAxisValue(AMOTION_EVENT_AXIS_X, positions[0].x);
-    coords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, positions[0].y);
-    event->initialize(0 /*deviceId*/, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID,
-            AMOTION_EVENT_ACTION_MOVE, 0 /*actionButton*/, 0 /*flags*/,
-            AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0 /*buttonState*/, MotionClassification::NONE,
-            0 /*xOffset*/, 0 /*yOffset*/, 0 /*xPrecision*/, 0 /*yPrecision*/,
-            0 /*downTime*/, positions[0].time, pointerCount, properties, coords);
-
-    for (size_t i = 1; i < positions.size(); i++) {
-        coords[0].setAxisValue(AMOTION_EVENT_AXIS_X, positions[i].x);
-        coords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, positions[i].y);
-        event->addSample(positions[i].time, coords);
-    }
-    return event;
+    return pointers;
 }
 
-static void computeAndCheckVelocity(const std::vector<Position>& positions,
-            int32_t axis, float targetVelocity) {
-    VelocityTracker vt(nullptr);
+static uint32_t getChangingPointerId(BitSet32 pointers, BitSet32 otherPointers) {
+    BitSet32 difference(pointers.value ^ otherPointers.value);
+    uint32_t pointerId = difference.clearFirstMarkedBit();
+    EXPECT_EQ(0U, difference.value) << "Only 1 pointer can enter or leave at a time";
+    return pointerId;
+}
+
+static int32_t resolveAction(const std::vector<Position>& lastPositions,
+        const std::vector<Position>& currentPositions,
+        const std::vector<Position>& nextPositions) {
+    BitSet32 pointers = getValidPointers(currentPositions);
+    const uint32_t pointerCount = pointers.count();
+
+    BitSet32 lastPointers = getValidPointers(lastPositions);
+    const uint32_t lastPointerCount = lastPointers.count();
+    if (lastPointerCount < pointerCount) {
+        // A new pointer is down
+        uint32_t pointerId = getChangingPointerId(pointers, lastPointers);
+        return AMOTION_EVENT_ACTION_POINTER_DOWN |
+                (pointerId << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
+    }
+
+    BitSet32 nextPointers = getValidPointers(nextPositions);
+    const uint32_t nextPointerCount = nextPointers.count();
+    if (pointerCount > nextPointerCount) {
+        // An existing pointer is leaving
+        uint32_t pointerId = getChangingPointerId(pointers, nextPointers);
+        return AMOTION_EVENT_ACTION_POINTER_UP |
+                (pointerId << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
+    }
+
+    return AMOTION_EVENT_ACTION_MOVE;
+}
+
+static std::vector<MotionEvent> createMotionEventStream(
+        const std::vector<MotionEventEntry>& motions) {
+    if (motions.empty()) {
+        ADD_FAILURE() << "Need at least 1 sample to create a MotionEvent. Received empty vector.";
+    }
+
+    std::vector<MotionEvent> events;
+    for (size_t i = 0; i < motions.size(); i++) {
+        const MotionEventEntry& entry = motions[i];
+        BitSet32 pointers = getValidPointers(entry.positions);
+        const uint32_t pointerCount = pointers.count();
+
+        int32_t action;
+        if (i == 0) {
+            action = AMOTION_EVENT_ACTION_DOWN;
+            EXPECT_EQ(1U, pointerCount) << "First event should only have 1 pointer";
+        } else if (i == motions.size() - 1) {
+            EXPECT_EQ(1U, pointerCount) << "Last event should only have 1 pointer";
+            action = AMOTION_EVENT_ACTION_UP;
+        } else {
+            const MotionEventEntry& previousEntry = motions[i-1];
+            const MotionEventEntry& nextEntry = motions[i+1];
+            action = resolveAction(previousEntry.positions, entry.positions, nextEntry.positions);
+        }
+
+        PointerCoords coords[pointerCount];
+        PointerProperties properties[pointerCount];
+        uint32_t pointerIndex = 0;
+        while(!pointers.isEmpty()) {
+            uint32_t pointerId = pointers.clearFirstMarkedBit();
+
+            coords[pointerIndex].clear();
+            // We are treating column positions as pointerId
+            EXPECT_TRUE(entry.positions[pointerId].isValid()) <<
+                    "The entry at pointerId must be valid";
+            coords[pointerIndex].setAxisValue(AMOTION_EVENT_AXIS_X, entry.positions[pointerId].x);
+            coords[pointerIndex].setAxisValue(AMOTION_EVENT_AXIS_Y, entry.positions[pointerId].y);
+
+            properties[pointerIndex].id = pointerId;
+            properties[pointerIndex].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
+            pointerIndex++;
+        }
+        EXPECT_EQ(pointerIndex, pointerCount);
+
+        MotionEvent event;
+        event.initialize(0 /*deviceId*/, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID,
+                action, 0 /*actionButton*/, 0 /*flags*/,
+                AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0 /*buttonState*/,
+                MotionClassification::NONE,
+                0 /*xOffset*/, 0 /*yOffset*/, 0 /*xPrecision*/, 0 /*yPrecision*/,
+                0 /*downTime*/, entry.eventTime.count(), pointerCount, properties, coords);
+
+        events.emplace_back(event);
+    }
+
+    return events;
+}
+
+static void computeAndCheckVelocity(const char* strategy,
+        const std::vector<MotionEventEntry>& motions, int32_t axis, float targetVelocity) {
+    VelocityTracker vt(strategy);
     float Vx, Vy;
 
-    std::unique_ptr<MotionEvent> event = createSimpleMotionEvent(positions);
-    vt.addMovement(event.get());
+    std::vector<MotionEvent> events = createMotionEventStream(motions);
+    for (MotionEvent event : events) {
+        vt.addMovement(&event);
+    }
 
     vt.getVelocity(DEFAULT_POINTER_ID, &Vx, &Vy);
 
@@ -135,11 +213,13 @@
     }
 }
 
-static void computeAndCheckQuadraticEstimate(const std::vector<Position>& positions,
+static void computeAndCheckQuadraticEstimate(const std::vector<MotionEventEntry>& motions,
         const std::array<float, 3>& coefficients) {
     VelocityTracker vt("lsq2");
-    std::unique_ptr<MotionEvent> event = createSimpleMotionEvent(positions);
-    vt.addMovement(event.get());
+    std::vector<MotionEvent> events = createMotionEventStream(motions);
+    for (MotionEvent event : events) {
+        vt.addMovement(&event);
+    }
     VelocityTracker::Estimator estimator;
     EXPECT_TRUE(vt.getEstimator(0, &estimator));
     for (size_t i = 0; i< coefficients.size(); i++) {
@@ -151,37 +231,41 @@
 /*
  * ================== VelocityTracker tests generated manually =====================================
  */
- // @todo Currently disabled, enable when switching away from lsq2 VelocityTrackerStrategy
-TEST_F(VelocityTrackerTest, DISABLED_ThreePointsPositiveVelocityTest) {
+TEST_F(VelocityTrackerTest, ThreePointsPositiveVelocityTest) {
     // Same coordinate is reported 2 times in a row
     // It is difficult to determine the correct answer here, but at least the direction
     // of the reported velocity should be positive.
-    std::vector<Position> values = {
-        { 0, 273, NAN },
-        { 12585000, 293, NAN },
-        { 14730000, 293, NAN },
+    std::vector<MotionEventEntry> motions = {
+        {0ms, {{ 273, NAN}}},
+        {12585us, {{293, NAN}}},
+        {14730us, {{293, NAN}}},
+        {14730us, {{293, NAN}}}, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 1600);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 1600);
 }
 
 TEST_F(VelocityTrackerTest, ThreePointsZeroVelocityTest) {
     // Same coordinate is reported 3 times in a row
-    std::vector<Position> values = {
-        { 0, 293, NAN },
-        { 6132000, 293, NAN },
-        { 11283000, 293, NAN },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{293, NAN}} },
+        { 6132us, {{293, NAN}} },
+        { 11283us, {{293, NAN}} },
+        { 11283us, {{293, NAN}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 0);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 0);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, 0);
 }
 
 TEST_F(VelocityTrackerTest, ThreePointsLinearVelocityTest) {
     // Fixed velocity at 5 points per 10 milliseconds
-    std::vector<Position> values = {
-        { 0, 0, NAN },
-        { 10000000, 5, NAN },
-        { 20000000, 10, NAN },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{0, NAN}} },
+        { 10ms, {{5, NAN}} },
+        { 20ms, {{10, NAN}} },
+        { 20ms, {{10, NAN}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 500);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 500);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, 500);
 }
 
 
@@ -193,23 +277,26 @@
  * Also record all calls to VelocityTracker::clear().
  * Finally, record the output of VelocityTracker::getVelocity(...)
  * This will give you the necessary data to create a new test.
+ *
+ * Another good way to generate this data is to use 'dumpsys input' just after the event has
+ * occurred.
  */
 
 // --------------- Recorded by hand on swordfish ---------------------------------------------------
-// @todo Currently disabled, enable when switching away from lsq2 VelocityTrackerStrategy
-TEST_F(VelocityTrackerTest, DISABLED_SwordfishFlingDown) {
+TEST_F(VelocityTrackerTest, SwordfishFlingDown) {
     // Recording of a fling on Swordfish that could cause a fling in the wrong direction
-    std::vector<Position> values = {
-        { 0, 271, 96 },
-        { 16071042, 269.786346, 106.922775 },
-        { 35648403, 267.983063, 156.660034 },
-        { 52313925, 262.638397, 220.339081 },
-        { 68976522, 266.138824, 331.581116 },
-        { 85639375, 274.79245, 428.113159 },
-        { 96948871, 274.79245, 428.113159 },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{271, 96}} },
+        { 16071042ns, {{269.786346, 106.922775}} },
+        { 35648403ns, {{267.983063, 156.660034}} },
+        { 52313925ns, {{262.638397, 220.339081}} },
+        { 68976522ns, {{266.138824, 331.581116}} },
+        { 85639375ns, {{274.79245, 428.113159}} },
+        { 96948871ns, {{274.79245, 428.113159}} },
+        { 96948871ns, {{274.79245, 428.113159}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 623.577637);
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 8523.348633);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 623.577637);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 5970.7309);
 }
 
 // --------------- Recorded by hand on sailfish, generated by a script -----------------------------
@@ -231,439 +318,484 @@
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpSlow1) {
     // Sailfish - fling up - slow - 1
-    std::vector<Position> values = {
-        { 235089067457000, 528.00, 983.00 },
-        { 235089084684000, 527.00, 981.00 },
-        { 235089093349000, 527.00, 977.00 },
-        { 235089095677625, 527.00, 975.93 },
-        { 235089101859000, 527.00, 970.00 },
-        { 235089110378000, 528.00, 960.00 },
-        { 235089112497111, 528.25, 957.51 },
-        { 235089118760000, 531.00, 946.00 },
-        { 235089126686000, 535.00, 931.00 },
-        { 235089129316820, 536.33, 926.02 },
-        { 235089135199000, 540.00, 914.00 },
-        { 235089144297000, 546.00, 896.00 },
-        { 235089146136443, 547.21, 892.36 },
-        { 235089152923000, 553.00, 877.00 },
-        { 235089160784000, 559.00, 851.00 },
-        { 235089162955851, 560.66, 843.82 },
+    std::vector<MotionEventEntry> motions = {
+        { 235089067457000ns, {{528.00, 983.00}} },
+        { 235089084684000ns, {{527.00, 981.00}} },
+        { 235089093349000ns, {{527.00, 977.00}} },
+        { 235089095677625ns, {{527.00, 975.93}} },
+        { 235089101859000ns, {{527.00, 970.00}} },
+        { 235089110378000ns, {{528.00, 960.00}} },
+        { 235089112497111ns, {{528.25, 957.51}} },
+        { 235089118760000ns, {{531.00, 946.00}} },
+        { 235089126686000ns, {{535.00, 931.00}} },
+        { 235089129316820ns, {{536.33, 926.02}} },
+        { 235089135199000ns, {{540.00, 914.00}} },
+        { 235089144297000ns, {{546.00, 896.00}} },
+        { 235089146136443ns, {{547.21, 892.36}} },
+        { 235089152923000ns, {{553.00, 877.00}} },
+        { 235089160784000ns, {{559.00, 851.00}} },
+        { 235089162955851ns, {{560.66, 843.82}} },
+        { 235089162955851ns, {{560.66, 843.82}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 872.794617); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 951.698181); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -3604.819336); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -3044.966064); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 872.794617);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, 951.698181);
+    computeAndCheckVelocity("impulse",motions, AMOTION_EVENT_AXIS_Y, -3604.819336);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -3044.966064);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpSlow2) {
     // Sailfish - fling up - slow - 2
-    std::vector<Position> values = {
-        { 235110560704000, 522.00, 1107.00 },
-        { 235110575764000, 522.00, 1107.00 },
-        { 235110584385000, 522.00, 1107.00 },
-        { 235110588421179, 521.52, 1106.52 },
-        { 235110592830000, 521.00, 1106.00 },
-        { 235110601385000, 520.00, 1104.00 },
-        { 235110605088160, 519.14, 1102.27 },
-        { 235110609952000, 518.00, 1100.00 },
-        { 235110618353000, 517.00, 1093.00 },
-        { 235110621755146, 516.60, 1090.17 },
-        { 235110627010000, 517.00, 1081.00 },
-        { 235110634785000, 518.00, 1063.00 },
-        { 235110638422450, 518.87, 1052.58 },
-        { 235110643161000, 520.00, 1039.00 },
-        { 235110651767000, 524.00, 1011.00 },
-        { 235110655089581, 525.54, 1000.19 },
-        { 235110660368000, 530.00, 980.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235110560704000ns, {{522.00, 1107.00}} },
+        { 235110575764000ns, {{522.00, 1107.00}} },
+        { 235110584385000ns, {{522.00, 1107.00}} },
+        { 235110588421179ns, {{521.52, 1106.52}} },
+        { 235110592830000ns, {{521.00, 1106.00}} },
+        { 235110601385000ns, {{520.00, 1104.00}} },
+        { 235110605088160ns, {{519.14, 1102.27}} },
+        { 235110609952000ns, {{518.00, 1100.00}} },
+        { 235110618353000ns, {{517.00, 1093.00}} },
+        { 235110621755146ns, {{516.60, 1090.17}} },
+        { 235110627010000ns, {{517.00, 1081.00}} },
+        { 235110634785000ns, {{518.00, 1063.00}} },
+        { 235110638422450ns, {{518.87, 1052.58}} },
+        { 235110643161000ns, {{520.00, 1039.00}} },
+        { 235110651767000ns, {{524.00, 1011.00}} },
+        { 235110655089581ns, {{525.54, 1000.19}} },
+        { 235110660368000ns, {{530.00, 980.00}} },
+        { 235110660368000ns, {{530.00, 980.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -4096.583008); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -3455.094238); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -4096.583008);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -3455.094238);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpSlow3) {
     // Sailfish - fling up - slow - 3
-    std::vector<Position> values = {
-        { 792536237000, 580.00, 1317.00 },
-        { 792541538987, 580.63, 1311.94 },
-        { 792544613000, 581.00, 1309.00 },
-        { 792552301000, 583.00, 1295.00 },
-        { 792558362309, 585.13, 1282.92 },
-        { 792560828000, 586.00, 1278.00 },
-        { 792569446000, 589.00, 1256.00 },
-        { 792575185095, 591.54, 1241.41 },
-        { 792578491000, 593.00, 1233.00 },
-        { 792587044000, 597.00, 1211.00 },
-        { 792592008172, 600.28, 1195.92 },
-        { 792594616000, 602.00, 1188.00 },
-        { 792603129000, 607.00, 1167.00 },
-        { 792608831290, 609.48, 1155.83 },
-        { 792612321000, 611.00, 1149.00 },
-        { 792620768000, 615.00, 1131.00 },
-        { 792625653873, 617.32, 1121.73 },
-        { 792629200000, 619.00, 1115.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 792536237000ns, {{580.00, 1317.00}} },
+        { 792541538987ns, {{580.63, 1311.94}} },
+        { 792544613000ns, {{581.00, 1309.00}} },
+        { 792552301000ns, {{583.00, 1295.00}} },
+        { 792558362309ns, {{585.13, 1282.92}} },
+        { 792560828000ns, {{586.00, 1278.00}} },
+        { 792569446000ns, {{589.00, 1256.00}} },
+        { 792575185095ns, {{591.54, 1241.41}} },
+        { 792578491000ns, {{593.00, 1233.00}} },
+        { 792587044000ns, {{597.00, 1211.00}} },
+        { 792592008172ns, {{600.28, 1195.92}} },
+        { 792594616000ns, {{602.00, 1188.00}} },
+        { 792603129000ns, {{607.00, 1167.00}} },
+        { 792608831290ns, {{609.48, 1155.83}} },
+        { 792612321000ns, {{611.00, 1149.00}} },
+        { 792620768000ns, {{615.00, 1131.00}} },
+        { 792625653873ns, {{617.32, 1121.73}} },
+        { 792629200000ns, {{619.00, 1115.00}} },
+        { 792629200000ns, {{619.00, 1115.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 574.33429); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 617.40564); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -2361.982666); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -2500.055664); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 574.33429);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, 617.40564);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -2361.982666);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -2500.055664);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpFaster1) {
     // Sailfish - fling up - faster - 1
-    std::vector<Position> values = {
-        { 235160420675000, 610.00, 1042.00 },
-        { 235160428220000, 609.00, 1026.00 },
-        { 235160436544000, 609.00, 1024.00 },
-        { 235160441852394, 609.64, 1020.82 },
-        { 235160444878000, 610.00, 1019.00 },
-        { 235160452673000, 613.00, 1006.00 },
-        { 235160458519743, 617.18, 992.06 },
-        { 235160461061000, 619.00, 986.00 },
-        { 235160469798000, 627.00, 960.00 },
-        { 235160475186713, 632.22, 943.02 },
-        { 235160478051000, 635.00, 934.00 },
-        { 235160486489000, 644.00, 906.00 },
-        { 235160491853697, 649.56, 890.56 },
-        { 235160495177000, 653.00, 881.00 },
-        { 235160504148000, 662.00, 858.00 },
-        { 235160509231495, 666.81, 845.37 },
-        { 235160512603000, 670.00, 837.00 },
-        { 235160520366000, 679.00, 814.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235160420675000ns, {{610.00, 1042.00}} },
+        { 235160428220000ns, {{609.00, 1026.00}} },
+        { 235160436544000ns, {{609.00, 1024.00}} },
+        { 235160441852394ns, {{609.64, 1020.82}} },
+        { 235160444878000ns, {{610.00, 1019.00}} },
+        { 235160452673000ns, {{613.00, 1006.00}} },
+        { 235160458519743ns, {{617.18, 992.06}} },
+        { 235160461061000ns, {{619.00, 986.00}} },
+        { 235160469798000ns, {{627.00, 960.00}} },
+        { 235160475186713ns, {{632.22, 943.02}} },
+        { 235160478051000ns, {{635.00, 934.00}} },
+        { 235160486489000ns, {{644.00, 906.00}} },
+        { 235160491853697ns, {{649.56, 890.56}} },
+        { 235160495177000ns, {{653.00, 881.00}} },
+        { 235160504148000ns, {{662.00, 858.00}} },
+        { 235160509231495ns, {{666.81, 845.37}} },
+        { 235160512603000ns, {{670.00, 837.00}} },
+        { 235160520366000ns, {{679.00, 814.00}} },
+        { 235160520366000ns, {{679.00, 814.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 1274.141724); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 1438.53186); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -3877.35498); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -3695.859619); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 1274.141724);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, 1438.53186);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -3001.4348);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -3695.859619);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpFaster2) {
     // Sailfish - fling up - faster - 2
-    std::vector<Position> values = {
-        { 847153808000, 576.00, 1264.00 },
-        { 847171174000, 576.00, 1262.00 },
-        { 847179640000, 576.00, 1257.00 },
-        { 847185187540, 577.41, 1249.22 },
-        { 847187487000, 578.00, 1246.00 },
-        { 847195710000, 581.00, 1227.00 },
-        { 847202027059, 583.93, 1209.40 },
-        { 847204324000, 585.00, 1203.00 },
-        { 847212672000, 590.00, 1176.00 },
-        { 847218861395, 594.36, 1157.11 },
-        { 847221190000, 596.00, 1150.00 },
-        { 847230484000, 602.00, 1124.00 },
-        { 847235701400, 607.56, 1103.83 },
-        { 847237986000, 610.00, 1095.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 847153808000ns, {{576.00, 1264.00}} },
+        { 847171174000ns, {{576.00, 1262.00}} },
+        { 847179640000ns, {{576.00, 1257.00}} },
+        { 847185187540ns, {{577.41, 1249.22}} },
+        { 847187487000ns, {{578.00, 1246.00}} },
+        { 847195710000ns, {{581.00, 1227.00}} },
+        { 847202027059ns, {{583.93, 1209.40}} },
+        { 847204324000ns, {{585.00, 1203.00}} },
+        { 847212672000ns, {{590.00, 1176.00}} },
+        { 847218861395ns, {{594.36, 1157.11}} },
+        { 847221190000ns, {{596.00, 1150.00}} },
+        { 847230484000ns, {{602.00, 1124.00}} },
+        { 847235701400ns, {{607.56, 1103.83}} },
+        { 847237986000ns, {{610.00, 1095.00}} },
+        { 847237986000ns, {{610.00, 1095.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -4280.07959); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -4241.004395); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -4280.07959);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -4241.004395);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpFaster3) {
     // Sailfish - fling up - faster - 3
-    std::vector<Position> values = {
-        { 235200532789000, 507.00, 1084.00 },
-        { 235200549221000, 507.00, 1083.00 },
-        { 235200557841000, 507.00, 1081.00 },
-        { 235200558051189, 507.00, 1080.95 },
-        { 235200566314000, 507.00, 1078.00 },
-        { 235200574876586, 508.97, 1070.12 },
-        { 235200575006000, 509.00, 1070.00 },
-        { 235200582900000, 514.00, 1054.00 },
-        { 235200591276000, 525.00, 1023.00 },
-        { 235200591701829, 525.56, 1021.42 },
-        { 235200600064000, 542.00, 976.00 },
-        { 235200608519000, 563.00, 911.00 },
-        { 235200608527086, 563.02, 910.94 },
-        { 235200616933000, 590.00, 844.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235200532789000ns, {{507.00, 1084.00}} },
+        { 235200549221000ns, {{507.00, 1083.00}} },
+        { 235200557841000ns, {{507.00, 1081.00}} },
+        { 235200558051189ns, {{507.00, 1080.95}} },
+        { 235200566314000ns, {{507.00, 1078.00}} },
+        { 235200574876586ns, {{508.97, 1070.12}} },
+        { 235200575006000ns, {{509.00, 1070.00}} },
+        { 235200582900000ns, {{514.00, 1054.00}} },
+        { 235200591276000ns, {{525.00, 1023.00}} },
+        { 235200591701829ns, {{525.56, 1021.42}} },
+        { 235200600064000ns, {{542.00, 976.00}} },
+        { 235200608519000ns, {{563.00, 911.00}} },
+        { 235200608527086ns, {{563.02, 910.94}} },
+        { 235200616933000ns, {{590.00, 844.00}} },
+        { 235200616933000ns, {{590.00, 844.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -8715.686523); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -7639.026367); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -8715.686523);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -7639.026367);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpFast1) {
     // Sailfish - fling up - fast - 1
-    std::vector<Position> values = {
-        { 920922149000, 561.00, 1412.00 },
-        { 920930185000, 559.00, 1377.00 },
-        { 920930262463, 558.98, 1376.66 },
-        { 920938547000, 559.00, 1371.00 },
-        { 920947096857, 562.91, 1342.68 },
-        { 920947302000, 563.00, 1342.00 },
-        { 920955502000, 577.00, 1272.00 },
-        { 920963931021, 596.87, 1190.54 },
-        { 920963987000, 597.00, 1190.00 },
-        { 920972530000, 631.00, 1093.00 },
-        { 920980765511, 671.31, 994.68 },
-        { 920980906000, 672.00, 993.00 },
-        { 920989261000, 715.00, 903.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 920922149000ns, {{561.00, 1412.00}} },
+        { 920930185000ns, {{559.00, 1377.00}} },
+        { 920930262463ns, {{558.98, 1376.66}} },
+        { 920938547000ns, {{559.00, 1371.00}} },
+        { 920947096857ns, {{562.91, 1342.68}} },
+        { 920947302000ns, {{563.00, 1342.00}} },
+        { 920955502000ns, {{577.00, 1272.00}} },
+        { 920963931021ns, {{596.87, 1190.54}} },
+        { 920963987000ns, {{597.00, 1190.00}} },
+        { 920972530000ns, {{631.00, 1093.00}} },
+        { 920980765511ns, {{671.31, 994.68}} },
+        { 920980906000ns, {{672.00, 993.00}} },
+        { 920989261000ns, {{715.00, 903.00}} },
+        { 920989261000ns, {{715.00, 903.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 5670.329102); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, 5991.866699); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -13021.101562); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -15093.995117); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 5670.329102);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, 5991.866699);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -13021.101562);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -15093.995117);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpFast2) {
     // Sailfish - fling up - fast - 2
-    std::vector<Position> values = {
-        { 235247153233000, 518.00, 1168.00 },
-        { 235247170452000, 517.00, 1167.00 },
-        { 235247178908000, 515.00, 1159.00 },
-        { 235247179556213, 514.85, 1158.39 },
-        { 235247186821000, 515.00, 1125.00 },
-        { 235247195265000, 521.00, 1051.00 },
-        { 235247196389476, 521.80, 1041.15 },
-        { 235247203649000, 538.00, 932.00 },
-        { 235247212253000, 571.00, 794.00 },
-        { 235247213222491, 574.72, 778.45 },
-        { 235247220736000, 620.00, 641.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235247153233000ns, {{518.00, 1168.00}} },
+        { 235247170452000ns, {{517.00, 1167.00}} },
+        { 235247178908000ns, {{515.00, 1159.00}} },
+        { 235247179556213ns, {{514.85, 1158.39}} },
+        { 235247186821000ns, {{515.00, 1125.00}} },
+        { 235247195265000ns, {{521.00, 1051.00}} },
+        { 235247196389476ns, {{521.80, 1041.15}} },
+        { 235247203649000ns, {{538.00, 932.00}} },
+        { 235247212253000ns, {{571.00, 794.00}} },
+        { 235247213222491ns, {{574.72, 778.45}} },
+        { 235247220736000ns, {{620.00, 641.00}} },
+        { 235247220736000ns, {{620.00, 641.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -20286.958984); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -20494.587891); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -20286.958984);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -20494.587891);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingUpFast3) {
     // Sailfish - fling up - fast - 3
-    std::vector<Position> values = {
-        { 235302568736000, 529.00, 1167.00 },
-        { 235302576644000, 523.00, 1140.00 },
-        { 235302579395063, 520.91, 1130.61 },
-        { 235302585140000, 522.00, 1130.00 },
-        { 235302593615000, 527.00, 1065.00 },
-        { 235302596207444, 528.53, 1045.12 },
-        { 235302602102000, 559.00, 872.00 },
-        { 235302610545000, 652.00, 605.00 },
-        { 235302613019881, 679.26, 526.73 },
+    std::vector<MotionEventEntry> motions = {
+        { 235302568736000ns, {{529.00, 1167.00}} },
+        { 235302576644000ns, {{523.00, 1140.00}} },
+        { 235302579395063ns, {{520.91, 1130.61}} },
+        { 235302585140000ns, {{522.00, 1130.00}} },
+        { 235302593615000ns, {{527.00, 1065.00}} },
+        { 235302596207444ns, {{528.53, 1045.12}} },
+        { 235302602102000ns, {{559.00, 872.00}} },
+        { 235302610545000ns, {{652.00, 605.00}} },
+        { 235302613019881ns, {{679.26, 526.73}} },
+        { 235302613019881ns, {{679.26, 526.73}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -39295.941406); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, -36461.421875); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, -39295.941406);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -36461.421875);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownSlow1) {
     // Sailfish - fling down - slow - 1
-    std::vector<Position> values = {
-        { 235655749552755, 582.00, 432.49 },
-        { 235655750638000, 582.00, 433.00 },
-        { 235655758865000, 582.00, 440.00 },
-        { 235655766221523, 581.16, 448.43 },
-        { 235655767594000, 581.00, 450.00 },
-        { 235655776044000, 580.00, 462.00 },
-        { 235655782890696, 579.18, 474.35 },
-        { 235655784360000, 579.00, 477.00 },
-        { 235655792795000, 578.00, 496.00 },
-        { 235655799559531, 576.27, 515.04 },
-        { 235655800612000, 576.00, 518.00 },
-        { 235655809535000, 574.00, 542.00 },
-        { 235655816988015, 572.17, 564.86 },
-        { 235655817685000, 572.00, 567.00 },
-        { 235655825981000, 569.00, 595.00 },
-        { 235655833808653, 566.26, 620.60 },
-        { 235655834541000, 566.00, 623.00 },
-        { 235655842893000, 563.00, 649.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235655749552755ns, {{582.00, 432.49}} },
+        { 235655750638000ns, {{582.00, 433.00}} },
+        { 235655758865000ns, {{582.00, 440.00}} },
+        { 235655766221523ns, {{581.16, 448.43}} },
+        { 235655767594000ns, {{581.00, 450.00}} },
+        { 235655776044000ns, {{580.00, 462.00}} },
+        { 235655782890696ns, {{579.18, 474.35}} },
+        { 235655784360000ns, {{579.00, 477.00}} },
+        { 235655792795000ns, {{578.00, 496.00}} },
+        { 235655799559531ns, {{576.27, 515.04}} },
+        { 235655800612000ns, {{576.00, 518.00}} },
+        { 235655809535000ns, {{574.00, 542.00}} },
+        { 235655816988015ns, {{572.17, 564.86}} },
+        { 235655817685000ns, {{572.00, 567.00}} },
+        { 235655825981000ns, {{569.00, 595.00}} },
+        { 235655833808653ns, {{566.26, 620.60}} },
+        { 235655834541000ns, {{566.00, 623.00}} },
+        { 235655842893000ns, {{563.00, 649.00}} },
+        { 235655842893000ns, {{563.00, 649.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -419.749695); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -398.303894); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 3309.016357); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 3969.099854); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, -419.749695);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, -398.303894);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 3309.016357);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 3969.099854);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownSlow2) {
     // Sailfish - fling down - slow - 2
-    std::vector<Position> values = {
-        { 235671152083370, 485.24, 558.28 },
-        { 235671154126000, 485.00, 559.00 },
-        { 235671162497000, 484.00, 566.00 },
-        { 235671168750511, 483.27, 573.29 },
-        { 235671171071000, 483.00, 576.00 },
-        { 235671179390000, 482.00, 588.00 },
-        { 235671185417210, 481.31, 598.98 },
-        { 235671188173000, 481.00, 604.00 },
-        { 235671196371000, 480.00, 624.00 },
-        { 235671202084196, 479.27, 639.98 },
-        { 235671204235000, 479.00, 646.00 },
-        { 235671212554000, 478.00, 673.00 },
-        { 235671219471011, 476.39, 697.12 },
-        { 235671221159000, 476.00, 703.00 },
-        { 235671229592000, 474.00, 734.00 },
-        { 235671236281462, 472.43, 758.38 },
-        { 235671238098000, 472.00, 765.00 },
-        { 235671246532000, 470.00, 799.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235671152083370ns, {{485.24, 558.28}} },
+        { 235671154126000ns, {{485.00, 559.00}} },
+        { 235671162497000ns, {{484.00, 566.00}} },
+        { 235671168750511ns, {{483.27, 573.29}} },
+        { 235671171071000ns, {{483.00, 576.00}} },
+        { 235671179390000ns, {{482.00, 588.00}} },
+        { 235671185417210ns, {{481.31, 598.98}} },
+        { 235671188173000ns, {{481.00, 604.00}} },
+        { 235671196371000ns, {{480.00, 624.00}} },
+        { 235671202084196ns, {{479.27, 639.98}} },
+        { 235671204235000ns, {{479.00, 646.00}} },
+        { 235671212554000ns, {{478.00, 673.00}} },
+        { 235671219471011ns, {{476.39, 697.12}} },
+        { 235671221159000ns, {{476.00, 703.00}} },
+        { 235671229592000ns, {{474.00, 734.00}} },
+        { 235671236281462ns, {{472.43, 758.38}} },
+        { 235671238098000ns, {{472.00, 765.00}} },
+        { 235671246532000ns, {{470.00, 799.00}} },
+        { 235671246532000ns, {{470.00, 799.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -262.80426); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -243.665344); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4215.682129); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4587.986816); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, -262.80426);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, -243.665344);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 4215.682129);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 4587.986816);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownSlow3) {
     // Sailfish - fling down - slow - 3
-    std::vector<Position> values = {
-        { 170983201000, 557.00, 533.00 },
-        { 171000668000, 556.00, 534.00 },
-        { 171007359750, 554.73, 535.27 },
-        { 171011197000, 554.00, 536.00 },
-        { 171017660000, 552.00, 540.00 },
-        { 171024201831, 549.97, 544.73 },
-        { 171027333000, 549.00, 547.00 },
-        { 171034603000, 545.00, 557.00 },
-        { 171041043371, 541.98, 567.55 },
-        { 171043147000, 541.00, 571.00 },
-        { 171051052000, 536.00, 586.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 170983201000ns, {{557.00, 533.00}} },
+        { 171000668000ns, {{556.00, 534.00}} },
+        { 171007359750ns, {{554.73, 535.27}} },
+        { 171011197000ns, {{554.00, 536.00}} },
+        { 171017660000ns, {{552.00, 540.00}} },
+        { 171024201831ns, {{549.97, 544.73}} },
+        { 171027333000ns, {{549.00, 547.00}} },
+        { 171034603000ns, {{545.00, 557.00}} },
+        { 171041043371ns, {{541.98, 567.55}} },
+        { 171043147000ns, {{541.00, 571.00}} },
+        { 171051052000ns, {{536.00, 586.00}} },
+        { 171051052000ns, {{536.00, 586.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -723.413513); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -651.038452); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 2091.502441); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 1934.517456); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, -723.413513);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, -651.038452);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 2091.502441);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 1934.517456);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownFaster1) {
     // Sailfish - fling down - faster - 1
-    std::vector<Position> values = {
-        { 235695280333000, 558.00, 451.00 },
-        { 235695283971237, 558.43, 454.45 },
-        { 235695289038000, 559.00, 462.00 },
-        { 235695297388000, 561.00, 478.00 },
-        { 235695300638465, 561.83, 486.25 },
-        { 235695305265000, 563.00, 498.00 },
-        { 235695313591000, 564.00, 521.00 },
-        { 235695317305492, 564.43, 532.68 },
-        { 235695322181000, 565.00, 548.00 },
-        { 235695330709000, 565.00, 577.00 },
-        { 235695333972227, 565.00, 588.10 },
-        { 235695339250000, 565.00, 609.00 },
-        { 235695347839000, 565.00, 642.00 },
-        { 235695351313257, 565.00, 656.18 },
-        { 235695356412000, 565.00, 677.00 },
-        { 235695364899000, 563.00, 710.00 },
-        { 235695368118682, 562.24, 722.52 },
-        { 235695373403000, 564.00, 744.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235695280333000ns, {{558.00, 451.00}} },
+        { 235695283971237ns, {{558.43, 454.45}} },
+        { 235695289038000ns, {{559.00, 462.00}} },
+        { 235695297388000ns, {{561.00, 478.00}} },
+        { 235695300638465ns, {{561.83, 486.25}} },
+        { 235695305265000ns, {{563.00, 498.00}} },
+        { 235695313591000ns, {{564.00, 521.00}} },
+        { 235695317305492ns, {{564.43, 532.68}} },
+        { 235695322181000ns, {{565.00, 548.00}} },
+        { 235695330709000ns, {{565.00, 577.00}} },
+        { 235695333972227ns, {{565.00, 588.10}} },
+        { 235695339250000ns, {{565.00, 609.00}} },
+        { 235695347839000ns, {{565.00, 642.00}} },
+        { 235695351313257ns, {{565.00, 656.18}} },
+        { 235695356412000ns, {{565.00, 677.00}} },
+        { 235695364899000ns, {{563.00, 710.00}} },
+        { 235695368118682ns, {{562.24, 722.52}} },
+        { 235695373403000ns, {{564.00, 744.00}} },
+        { 235695373403000ns, {{564.00, 744.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4254.639648); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4698.415039); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 4254.639648);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 4698.415039);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownFaster2) {
     // Sailfish - fling down - faster - 2
-    std::vector<Position> values = {
-        { 235709624766000, 535.00, 579.00 },
-        { 235709642256000, 534.00, 580.00 },
-        { 235709643350278, 533.94, 580.06 },
-        { 235709650760000, 532.00, 584.00 },
-        { 235709658615000, 530.00, 593.00 },
-        { 235709660170495, 529.60, 594.78 },
-        { 235709667095000, 527.00, 606.00 },
-        { 235709675616000, 524.00, 628.00 },
-        { 235709676983261, 523.52, 631.53 },
-        { 235709684289000, 521.00, 652.00 },
-        { 235709692763000, 518.00, 682.00 },
-        { 235709693804993, 517.63, 685.69 },
-        { 235709701438000, 515.00, 709.00 },
-        { 235709709830000, 512.00, 739.00 },
-        { 235709710626776, 511.72, 741.85 },
+    std::vector<MotionEventEntry> motions = {
+        { 235709624766000ns, {{535.00, 579.00}} },
+        { 235709642256000ns, {{534.00, 580.00}} },
+        { 235709643350278ns, {{533.94, 580.06}} },
+        { 235709650760000ns, {{532.00, 584.00}} },
+        { 235709658615000ns, {{530.00, 593.00}} },
+        { 235709660170495ns, {{529.60, 594.78}} },
+        { 235709667095000ns, {{527.00, 606.00}} },
+        { 235709675616000ns, {{524.00, 628.00}} },
+        { 235709676983261ns, {{523.52, 631.53}} },
+        { 235709684289000ns, {{521.00, 652.00}} },
+        { 235709692763000ns, {{518.00, 682.00}} },
+        { 235709693804993ns, {{517.63, 685.69}} },
+        { 235709701438000ns, {{515.00, 709.00}} },
+        { 235709709830000ns, {{512.00, 739.00}} },
+        { 235709710626776ns, {{511.72, 741.85}} },
+        { 235709710626776ns, {{511.72, 741.85}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -430.440247); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -447.600311); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 3953.859375); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4316.155273); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, -430.440247);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, -447.600311);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 3953.859375);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 4316.155273);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownFaster3) {
     // Sailfish - fling down - faster - 3
-    std::vector<Position> values = {
-        { 235727628927000, 540.00, 440.00 },
-        { 235727636810000, 537.00, 454.00 },
-        { 235727646176000, 536.00, 454.00 },
-        { 235727653586628, 535.12, 456.65 },
-        { 235727654557000, 535.00, 457.00 },
-        { 235727663024000, 534.00, 465.00 },
-        { 235727670410103, 533.04, 479.45 },
-        { 235727670691000, 533.00, 480.00 },
-        { 235727679255000, 531.00, 501.00 },
-        { 235727687233704, 529.09, 526.73 },
-        { 235727687628000, 529.00, 528.00 },
-        { 235727696113000, 526.00, 558.00 },
-        { 235727704057546, 523.18, 588.98 },
-        { 235727704576000, 523.00, 591.00 },
-        { 235727713099000, 520.00, 626.00 },
-        { 235727720880776, 516.33, 655.36 },
-        { 235727721580000, 516.00, 658.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235727628927000ns, {{540.00, 440.00}} },
+        { 235727636810000ns, {{537.00, 454.00}} },
+        { 235727646176000ns, {{536.00, 454.00}} },
+        { 235727653586628ns, {{535.12, 456.65}} },
+        { 235727654557000ns, {{535.00, 457.00}} },
+        { 235727663024000ns, {{534.00, 465.00}} },
+        { 235727670410103ns, {{533.04, 479.45}} },
+        { 235727670691000ns, {{533.00, 480.00}} },
+        { 235727679255000ns, {{531.00, 501.00}} },
+        { 235727687233704ns, {{529.09, 526.73}} },
+        { 235727687628000ns, {{529.00, 528.00}} },
+        { 235727696113000ns, {{526.00, 558.00}} },
+        { 235727704057546ns, {{523.18, 588.98}} },
+        { 235727704576000ns, {{523.00, 591.00}} },
+        { 235727713099000ns, {{520.00, 626.00}} },
+        { 235727720880776ns, {{516.33, 655.36}} },
+        { 235727721580000ns, {{516.00, 658.00}} },
+        { 235727721580000ns, {{516.00, 658.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4484.617676); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 4927.92627); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 4484.617676);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 4927.92627);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownFast1) {
     // Sailfish - fling down - fast - 1
-    std::vector<Position> values = {
-        { 235762352849000, 467.00, 286.00 },
-        { 235762360250000, 443.00, 344.00 },
-        { 235762362787412, 434.77, 363.89 },
-        { 235762368807000, 438.00, 359.00 },
-        { 235762377220000, 425.00, 423.00 },
-        { 235762379608561, 421.31, 441.17 },
-        { 235762385698000, 412.00, 528.00 },
-        { 235762394133000, 406.00, 648.00 },
-        { 235762396429369, 404.37, 680.67 },
+    std::vector<MotionEventEntry> motions = {
+        { 235762352849000ns, {{467.00, 286.00}} },
+        { 235762360250000ns, {{443.00, 344.00}} },
+        { 235762362787412ns, {{434.77, 363.89}} },
+        { 235762368807000ns, {{438.00, 359.00}} },
+        { 235762377220000ns, {{425.00, 423.00}} },
+        { 235762379608561ns, {{421.31, 441.17}} },
+        { 235762385698000ns, {{412.00, 528.00}} },
+        { 235762394133000ns, {{406.00, 648.00}} },
+        { 235762396429369ns, {{404.37, 680.67}} },
+        { 235762396429369ns, {{404.37, 680.67}} }, //ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 19084.931641); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 16064.685547); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 14227.0224);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 16064.685547);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownFast2) {
     // Sailfish - fling down - fast - 2
-    std::vector<Position> values = {
-        { 235772487188000, 576.00, 204.00 },
-        { 235772495159000, 553.00, 236.00 },
-        { 235772503568000, 551.00, 240.00 },
-        { 235772508192247, 545.55, 254.17 },
-        { 235772512051000, 541.00, 266.00 },
-        { 235772520794000, 520.00, 337.00 },
-        { 235772525015263, 508.92, 394.43 },
-        { 235772529174000, 498.00, 451.00 },
-        { 235772537635000, 484.00, 589.00 },
+    std::vector<MotionEventEntry> motions = {
+        { 235772487188000ns, {{576.00, 204.00}} },
+        { 235772495159000ns, {{553.00, 236.00}} },
+        { 235772503568000ns, {{551.00, 240.00}} },
+        { 235772508192247ns, {{545.55, 254.17}} },
+        { 235772512051000ns, {{541.00, 266.00}} },
+        { 235772520794000ns, {{520.00, 337.00}} },
+        { 235772525015263ns, {{508.92, 394.43}} },
+        { 235772529174000ns, {{498.00, 451.00}} },
+        { 235772537635000ns, {{484.00, 589.00}} },
+        { 235772537635000ns, {{484.00, 589.00}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 18660.048828); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 16918.439453); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 18660.048828);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 16918.439453);
 }
 
 
 TEST_F(VelocityTrackerTest, SailfishFlingDownFast3) {
     // Sailfish - fling down - fast - 3
-    std::vector<Position> values = {
-        { 507650295000, 628.00, 233.00 },
-        { 507658234000, 605.00, 269.00 },
-        { 507666784000, 601.00, 274.00 },
-        { 507669660483, 599.65, 275.68 },
-        { 507675427000, 582.00, 308.00 },
-        { 507683740000, 541.00, 404.00 },
-        { 507686506238, 527.36, 435.95 },
-        { 507692220000, 487.00, 581.00 },
-        { 507700707000, 454.00, 792.00 },
-        { 507703352649, 443.71, 857.77 },
+    std::vector<MotionEventEntry> motions = {
+        { 507650295000ns, {{628.00, 233.00}} },
+        { 507658234000ns, {{605.00, 269.00}} },
+        { 507666784000ns, {{601.00, 274.00}} },
+        { 507669660483ns, {{599.65, 275.68}} },
+        { 507675427000ns, {{582.00, 308.00}} },
+        { 507683740000ns, {{541.00, 404.00}} },
+        { 507686506238ns, {{527.36, 435.95}} },
+        { 507692220000ns, {{487.00, 581.00}} },
+        { 507700707000ns, {{454.00, 792.00}} },
+        { 507703352649ns, {{443.71, 857.77}} },
+        { 507703352649ns, {{443.71, 857.77}} }, // ACTION_UP
     };
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -6772.508301); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_X, -6388.48877); // lsq2
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 29765.908203); // impulse
-    computeAndCheckVelocity(values, AMOTION_EVENT_AXIS_Y, 28354.796875); // lsq2
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, -4111.8173);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, -6388.48877);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 29765.908203);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, 28354.796875);
 }
 
-/*
+/**
+ * ================== Multiple pointers ============================================================
+ *
+ * Three fingers quickly tap the screen. Since this is a tap, the velocities should be zero.
+ * If the events with POINTER_UP or POINTER_DOWN are not handled correctly (these should not be
+ * part of the fitted data), this can cause large velocity values to be reported instead.
+ */
+TEST_F(VelocityTrackerTest, LeastSquaresVelocityTrackerStrategyEstimator_ThreeFingerTap) {
+    std::vector<MotionEventEntry> motions = {
+        { 0us,      {{1063, 1128}, {NAN, NAN}, {NAN, NAN}} },
+        { 10800us,  {{1063, 1128}, {682, 1318}, {NAN, NAN}} }, // POINTER_DOWN
+        { 10800us,  {{1063, 1128}, {682, 1318}, {397, 1747}} }, // POINTER_DOWN
+        { 267300us, {{1063, 1128}, {682, 1318}, {397, 1747}} }, // POINTER_UP
+        { 267300us, {{1063, 1128}, {NAN, NAN}, {397, 1747}} }, // POINTER_UP
+        { 272700us, {{1063, 1128}, {NAN, NAN}, {NAN, NAN}} },
+    };
+
+    // Velocity should actually be zero, but we expect 0.016 here instead.
+    // This is close enough to zero, and is likely caused by division by a very small number.
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_X, -0.016);
+    computeAndCheckVelocity("lsq2", motions, AMOTION_EVENT_AXIS_Y, -0.016);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_X, 0);
+    computeAndCheckVelocity("impulse", motions, AMOTION_EVENT_AXIS_Y, 0);
+}
+
+/**
+ * ================== Tests for least squares fitting ==============================================
+ *
  * Special care must be taken when constructing tests for LeastSquaresVelocityTrackerStrategy
  * getEstimator function. In particular:
  * - inside the function, time gets converted from nanoseconds to seconds
@@ -687,85 +819,90 @@
  * In the test, we would convert these coefficients to (0*(1E3)^0, 0*(1E3)^1, 1*(1E3)^2).
  */
 TEST_F(VelocityTrackerTest, LeastSquaresVelocityTrackerStrategyEstimator_Constant) {
-    std::vector<Position> values = {
-        { 0000000, 1, 1 }, // 0 s
-        { 1000000, 1, 1 }, // 0.001 s
-        { 2000000, 1, 1 }, // 0.002 s
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{1, 1}} }, // 0 s
+        { 1ms, {{1, 1}} }, // 0.001 s
+        { 2ms, {{1, 1}} }, // 0.002 s
+        { 2ms, {{1, 1}} }, // ACTION_UP
     };
     // The data used for the fit will be as follows:
     // time(s), position
     // -0.002, 1
     // -0.001, 1
-    // -0.000, 1
-    computeAndCheckQuadraticEstimate(values, std::array<float, 3>({1, 0, 0}));
+    // -0.ms, 1
+    computeAndCheckQuadraticEstimate(motions, std::array<float, 3>({1, 0, 0}));
 }
 
 /*
  * Straight line y = x :: the constant and quadratic coefficients are zero.
  */
 TEST_F(VelocityTrackerTest, LeastSquaresVelocityTrackerStrategyEstimator_Linear) {
-    std::vector<Position> values = {
-        { 0000000, -2, -2 },
-        { 1000000, -1, -1 },
-        { 2000000, -0, -0 },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{-2, -2}} },
+        { 1ms, {{-1, -1}} },
+        { 2ms, {{-0, -0}} },
+        { 2ms, {{-0, -0}} }, // ACTION_UP
     };
     // The data used for the fit will be as follows:
     // time(s), position
     // -0.002, -2
     // -0.001, -1
     // -0.000,  0
-    computeAndCheckQuadraticEstimate(values, std::array<float, 3>({0, 1E3, 0}));
+    computeAndCheckQuadraticEstimate(motions, std::array<float, 3>({0, 1E3, 0}));
 }
 
 /*
  * Parabola
  */
 TEST_F(VelocityTrackerTest, LeastSquaresVelocityTrackerStrategyEstimator_Parabolic) {
-    std::vector<Position> values = {
-        { 0000000, 1, 1 },
-        { 1000000, 4, 4 },
-        { 2000000, 8, 8 },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{1, 1}} },
+        { 1ms, {{4, 4}} },
+        { 2ms, {{8, 8}} },
+        { 2ms, {{8, 8}} }, // ACTION_UP
     };
     // The data used for the fit will be as follows:
     // time(s), position
     // -0.002, 1
     // -0.001, 4
     // -0.000, 8
-    computeAndCheckQuadraticEstimate(values, std::array<float, 3>({8, 4.5E3, 0.5E6}));
+    computeAndCheckQuadraticEstimate(motions, std::array<float, 3>({8, 4.5E3, 0.5E6}));
 }
 
 /*
  * Parabola
  */
 TEST_F(VelocityTrackerTest, LeastSquaresVelocityTrackerStrategyEstimator_Parabolic2) {
-    std::vector<Position> values = {
-        { 0000000, 1, 1 },
-        { 1000000, 4, 4 },
-        { 2000000, 9, 9 },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{1, 1}} },
+        { 1ms, {{4, 4}} },
+        { 2ms, {{9, 9}} },
+        { 2ms, {{9, 9}} }, // ACTION_UP
     };
     // The data used for the fit will be as follows:
     // time(s), position
     // -0.002, 1
     // -0.001, 4
     // -0.000, 9
-    computeAndCheckQuadraticEstimate(values, std::array<float, 3>({9, 6E3, 1E6}));
+    computeAndCheckQuadraticEstimate(motions, std::array<float, 3>({9, 6E3, 1E6}));
 }
 
 /*
  * Parabola :: y = x^2 :: the constant and linear coefficients are zero.
  */
 TEST_F(VelocityTrackerTest, LeastSquaresVelocityTrackerStrategyEstimator_Parabolic3) {
-    std::vector<Position> values = {
-        { 0000000, 4, 4 },
-        { 1000000, 1, 1 },
-        { 2000000, 0, 0 },
+    std::vector<MotionEventEntry> motions = {
+        { 0ms, {{4, 4}} },
+        { 1ms, {{1, 1}} },
+        { 2ms, {{0, 0}} },
+        { 2ms, {{0, 0}} }, // ACTION_UP
     };
     // The data used for the fit will be as follows:
     // time(s), position
     // -0.002, 4
     // -0.001, 1
     // -0.000, 0
-    computeAndCheckQuadraticEstimate(values, std::array<float, 3>({0, 0E3, 1E6}));
+    computeAndCheckQuadraticEstimate(motions, std::array<float, 3>({0, 0E3, 1E6}));
 }
 
 } // namespace android
diff --git a/libs/ui/Gralloc3.cpp b/libs/ui/Gralloc3.cpp
index 7f8e57c..eb43765 100644
--- a/libs/ui/Gralloc3.cpp
+++ b/libs/ui/Gralloc3.cpp
@@ -28,7 +28,7 @@
 #pragma clang diagnostic pop
 
 using android::hardware::graphics::allocator::V3_0::IAllocator;
-using android::hardware::graphics::common::V1_1::BufferUsage;
+using android::hardware::graphics::common::V1_2::BufferUsage;
 using android::hardware::graphics::mapper::V3_0::BufferDescriptor;
 using android::hardware::graphics::mapper::V3_0::Error;
 using android::hardware::graphics::mapper::V3_0::IMapper;
@@ -44,11 +44,7 @@
     static const uint64_t validUsageBits = []() -> uint64_t {
         uint64_t bits = 0;
         for (const auto bit :
-             hardware::hidl_enum_range<hardware::graphics::common::V1_0::BufferUsage>()) {
-            bits = bits | bit;
-        }
-        for (const auto bit :
-             hardware::hidl_enum_range<hardware::graphics::common::V1_1::BufferUsage>()) {
+             hardware::hidl_enum_range<hardware::graphics::common::V1_2::BufferUsage>()) {
             bits = bits | bit;
         }
         return bits;
@@ -71,7 +67,7 @@
     outDescriptorInfo->width = width;
     outDescriptorInfo->height = height;
     outDescriptorInfo->layerCount = layerCount;
-    outDescriptorInfo->format = static_cast<hardware::graphics::common::V1_1::PixelFormat>(format);
+    outDescriptorInfo->format = static_cast<hardware::graphics::common::V1_2::PixelFormat>(format);
     outDescriptorInfo->usage = usage;
 }
 
diff --git a/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp b/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp
index 8bb0c6a..34cb3e1 100644
--- a/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp
+++ b/opengl/tools/glgen/stubs/egl/EGL15cHeader.cpp
@@ -35,16 +35,6 @@
 static jclass eglsurfaceClass;
 static jclass eglconfigClass;
 static jclass eglcontextClass;
-static jclass bufferClass;
-static jclass nioAccessClass;
-
-static jfieldID positionID;
-static jfieldID limitID;
-static jfieldID elementSizeShiftID;
-
-static jmethodID getBasePointerID;
-static jmethodID getBaseArrayID;
-static jmethodID getBaseArrayOffsetID;
 
 static jmethodID egldisplayGetHandleID;
 static jmethodID eglconfigGetHandleID;
@@ -116,24 +106,6 @@
     _env->SetStaticObjectField(eglClass, noSurfaceFieldID, eglNoSurfaceObject);
 
     // EGL 1.5 init
-    jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess");
-    nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal);
-
-    jclass bufferClassLocal = _env->FindClass("java/nio/Buffer");
-    bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal);
-
-    getBasePointerID = _env->GetStaticMethodID(nioAccessClass,
-            "getBasePointer", "(Ljava/nio/Buffer;)J");
-    getBaseArrayID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;");
-    getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArrayOffset", "(Ljava/nio/Buffer;)I");
-
-    positionID = _env->GetFieldID(bufferClass, "position", "I");
-    limitID = _env->GetFieldID(bufferClass, "limit", "I");
-    elementSizeShiftID =
-        _env->GetFieldID(bufferClass, "_elementSizeShift", "I");
-
     jclass eglimageClassLocal = _env->FindClass("android/opengl/EGLImage");
     eglimageClass = (jclass) _env->NewGlobalRef(eglimageClassLocal);
     jclass eglsyncClassLocal = _env->FindClass("android/opengl/EGLSync");
@@ -160,23 +132,17 @@
     jint elementSizeShift;
     jlong pointer;
 
-    position = _env->GetIntField(buffer, positionID);
-    limit = _env->GetIntField(buffer, limitID);
-    elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
     *remaining = (limit - position) << elementSizeShift;
-    pointer = _env->CallStaticLongMethod(nioAccessClass,
-            getBasePointerID, buffer);
     if (pointer != 0L) {
-        *array = NULL;
+        *array = nullptr;
+        pointer += position << elementSizeShift;
         return reinterpret_cast<void*>(pointer);
     }
 
-    *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
-            getBaseArrayID, buffer);
-    *offset = _env->CallStaticIntMethod(nioAccessClass,
-            getBaseArrayOffsetID, buffer);
-
-    return NULL;
+    *array = jniGetNioBufferBaseArray(_env, buffer);
+    *offset = jniGetNioBufferBaseArrayOffset(_env, buffer);
+    return nullptr;
 }
 
 static void
diff --git a/opengl/tools/glgen/stubs/gles11/common.cpp b/opengl/tools/glgen/stubs/gles11/common.cpp
index 51e62ed..e763b4e 100644
--- a/opengl/tools/glgen/stubs/gles11/common.cpp
+++ b/opengl/tools/glgen/stubs/gles11/common.cpp
@@ -4,15 +4,6 @@
 #include <utils/misc.h>
 #include <assert.h>
 
-static jclass nioAccessClass;
-static jclass bufferClass;
-static jmethodID getBasePointerID;
-static jmethodID getBaseArrayID;
-static jmethodID getBaseArrayOffsetID;
-static jfieldID positionID;
-static jfieldID limitID;
-static jfieldID elementSizeShiftID;
-
 
 /* special calls implemented in Android's GLES wrapper used to more
  * efficiently bound-check passed arrays */
@@ -47,28 +38,9 @@
 #endif
 }
 
-/* Cache method IDs each time the class is loaded. */
-
 static void
 nativeClassInit(JNIEnv *_env, jclass glImplClass)
 {
-    jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess");
-    nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal);
-
-    jclass bufferClassLocal = _env->FindClass("java/nio/Buffer");
-    bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal);
-
-    getBasePointerID = _env->GetStaticMethodID(nioAccessClass,
-            "getBasePointer", "(Ljava/nio/Buffer;)J");
-    getBaseArrayID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;");
-    getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArrayOffset", "(Ljava/nio/Buffer;)I");
-
-    positionID = _env->GetFieldID(bufferClass, "position", "I");
-    limitID = _env->GetFieldID(bufferClass, "limit", "I");
-    elementSizeShiftID =
-        _env->GetFieldID(bufferClass, "_elementSizeShift", "I");
 }
 
 static void *
@@ -79,23 +51,17 @@
     jint elementSizeShift;
     jlong pointer;
 
-    position = _env->GetIntField(buffer, positionID);
-    limit = _env->GetIntField(buffer, limitID);
-    elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
     *remaining = (limit - position) << elementSizeShift;
-    pointer = _env->CallStaticLongMethod(nioAccessClass,
-            getBasePointerID, buffer);
     if (pointer != 0L) {
-        *array = NULL;
+        *array = nullptr;
+        pointer += position << elementSizeShift;
         return reinterpret_cast<void*>(pointer);
     }
 
-    *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
-            getBaseArrayID, buffer);
-    *offset = _env->CallStaticIntMethod(nioAccessClass,
-            getBaseArrayOffsetID, buffer);
-
-    return NULL;
+    *array = jniGetNioBufferBaseArray(_env, buffer);
+    *offset = jniGetNioBufferBaseArrayOffset(_env, buffer);
+    return nullptr;
 }
 
 class ByteArrayGetter {
@@ -217,16 +183,18 @@
 
 static void *
 getDirectBufferPointer(JNIEnv *_env, jobject buffer) {
-    char* buf = (char*) _env->GetDirectBufferAddress(buffer);
-    if (buf) {
-        jint position = _env->GetIntField(buffer, positionID);
-        jint elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
-        buf += position << elementSizeShift;
-    } else {
+    jint position;
+    jint limit;
+    jint elementSizeShift;
+    jlong pointer;
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
+    if (pointer == 0) {
         jniThrowException(_env, "java/lang/IllegalArgumentException",
                           "Must use a native order direct Buffer");
+        return nullptr;
     }
-    return (void*) buf;
+    pointer += position << elementSizeShift;
+    return reinterpret_cast<void*>(pointer);
 }
 
 // --------------------------------------------------------------------------
diff --git a/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp b/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp
index c808fe9..c12efc3 100644
--- a/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp
+++ b/opengl/tools/glgen/stubs/jsr239/GLCHeader.cpp
@@ -64,16 +64,7 @@
         GLsizei stride, const GLvoid *pointer, GLsizei count);
 }
 
-static jclass nioAccessClass;
-static jclass bufferClass;
 static jclass G11ImplClass;
-static jmethodID getBasePointerID;
-static jmethodID getBaseArrayID;
-static jmethodID getBaseArrayOffsetID;
-static jmethodID allowIndirectBuffersID;
-static jfieldID positionID;
-static jfieldID limitID;
-static jfieldID elementSizeShiftID;
 static jfieldID haveCheckedExtensionsID;
 static jfieldID have_OES_blend_equation_separateID;
 static jfieldID have_OES_blend_subtractID;
@@ -85,12 +76,6 @@
 static void
 nativeClassInit(JNIEnv *_env, jclass glImplClass)
 {
-    jclass nioAccessClassLocal = _env->FindClass("java/nio/NIOAccess");
-    nioAccessClass = (jclass) _env->NewGlobalRef(nioAccessClassLocal);
-
-    jclass bufferClassLocal = _env->FindClass("java/nio/Buffer");
-    bufferClass = (jclass) _env->NewGlobalRef(bufferClassLocal);
-
     jclass g11impClassLocal = _env->FindClass("com/google/android/gles_jni/GLImpl");
     G11ImplClass = (jclass) _env->NewGlobalRef(g11impClassLocal);
     haveCheckedExtensionsID =  _env->GetFieldID(G11ImplClass, "haveCheckedExtensions", "Z");
@@ -98,19 +83,6 @@
     have_OES_blend_subtractID =  _env->GetFieldID(G11ImplClass, "have_OES_blend_subtract", "Z");
     have_OES_framebuffer_objectID =  _env->GetFieldID(G11ImplClass, "have_OES_framebuffer_object", "Z");
     have_OES_texture_cube_mapID =  _env->GetFieldID(G11ImplClass, "have_OES_texture_cube_map", "Z");
-
-    getBasePointerID = _env->GetStaticMethodID(nioAccessClass,
-            "getBasePointer", "(Ljava/nio/Buffer;)J");
-    getBaseArrayID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArray", "(Ljava/nio/Buffer;)Ljava/lang/Object;");
-    getBaseArrayOffsetID = _env->GetStaticMethodID(nioAccessClass,
-            "getBaseArrayOffset", "(Ljava/nio/Buffer;)I");
-    allowIndirectBuffersID = _env->GetStaticMethodID(g11impClassLocal,
-            "allowIndirectBuffers", "(Ljava/lang/String;)Z");
-    positionID = _env->GetFieldID(bufferClass, "position", "I");
-    limitID = _env->GetFieldID(bufferClass, "limit", "I");
-    elementSizeShiftID =
-        _env->GetFieldID(bufferClass, "_elementSizeShift", "I");
 }
 
 static void *
@@ -121,28 +93,17 @@
     jint elementSizeShift;
     jlong pointer;
 
-    position = _env->GetIntField(buffer, positionID);
-    limit = _env->GetIntField(buffer, limitID);
-    elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
     *remaining = (limit - position) << elementSizeShift;
-    pointer = _env->CallStaticLongMethod(nioAccessClass,
-            getBasePointerID, buffer);
     if (pointer != 0L) {
-        *offset = 0;
-        *array = NULL;
-        return reinterpret_cast<void *>(pointer);
+        *array = nullptr;
+        pointer += position << elementSizeShift;
+        return reinterpret_cast<void*>(pointer);
     }
 
-    *array = (jarray) _env->CallStaticObjectMethod(nioAccessClass,
-            getBaseArrayID, buffer);
-    if (*array == NULL) {
-        *offset = 0;
-        return (void*) NULL;
-    }
-    *offset = _env->CallStaticIntMethod(nioAccessClass,
-            getBaseArrayOffsetID, buffer);
-
-    return NULL;
+    *array = jniGetNioBufferBaseArray(_env, buffer);
+    *offset = jniGetNioBufferBaseArrayOffset(_env, buffer);
+    return nullptr;
 }
 
 static void
@@ -156,42 +117,24 @@
 extern char*  __progname;
 }
 
-static bool
-allowIndirectBuffers(JNIEnv *_env) {
-    static jint sIndirectBufferCompatability;
-    if (sIndirectBufferCompatability == 0) {
-        jobject appName = _env->NewStringUTF(::__progname);
-        sIndirectBufferCompatability = _env->CallStaticBooleanMethod(G11ImplClass, allowIndirectBuffersID, appName) ? 2 : 1;
-    }
-    return sIndirectBufferCompatability == 2;
-}
-
 static void *
 getDirectBufferPointer(JNIEnv *_env, jobject buffer) {
-    if (!buffer) {
-        return NULL;
+    if (buffer == nullptr) {
+        return nullptr;
     }
-    void* buf = _env->GetDirectBufferAddress(buffer);
-    if (buf) {
-        jint position = _env->GetIntField(buffer, positionID);
-        jint elementSizeShift = _env->GetIntField(buffer, elementSizeShiftID);
-        buf = ((char*) buf) + (position << elementSizeShift);
-    } else {
-        if (allowIndirectBuffers(_env)) {
-            jarray array = 0;
-            jint remaining;
-            jint offset;
-            buf = getPointer(_env, buffer, &array, &remaining, &offset);
-            if (array) {
-                releasePointer(_env, array, buf, 0);
-            }
-            buf = (char*)buf + offset;
-        } else {
-            jniThrowException(_env, "java/lang/IllegalArgumentException",
-                              "Must use a native order direct Buffer");
-        }
+
+    jint position;
+    jint limit;
+    jint elementSizeShift;
+    jlong pointer;
+    pointer = jniGetNioBufferFields(_env, buffer, &position, &limit, &elementSizeShift);
+    if (pointer == 0) {
+        jniThrowException(_env, "java/lang/IllegalArgumentException",
+                          "Must use a native order direct Buffer");
+        return nullptr;
     }
-    return buf;
+    pointer += position << elementSizeShift;
+    return reinterpret_cast<void*>(pointer);
 }
 
 static int
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index e3dfde4..cbdd473 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -565,11 +565,11 @@
     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
         return BAD_VALUE;
     }
-    if (args.size() == 3 && args[0] == String16("set-uid-state")) {
+    if (args[0] == String16("set-uid-state")) {
         return handleSetUidState(args, err);
-    } else if (args.size() == 2 && args[0] == String16("reset-uid-state")) {
+    } else if (args[0] == String16("reset-uid-state")) {
         return handleResetUidState(args, err);
-    } else if (args.size() == 2 && args[0] == String16("get-uid-state")) {
+    } else if (args[0] == String16("get-uid-state")) {
         return handleGetUidState(args, out, err);
     } else if (args.size() == 1 && args[0] == String16("help")) {
         printHelp(out);
@@ -579,14 +579,32 @@
     return BAD_VALUE;
 }
 
-status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
+static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
     PermissionController pc;
-    int uid = pc.getPackageUid(args[1], 0);
+    uid = pc.getPackageUid(packageName, 0);
     if (uid <= 0) {
-        ALOGE("Unknown package: '%s'", String8(args[1]).string());
-        dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
+        ALOGE("Unknown package: '%s'", String8(packageName).string());
+        dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
         return BAD_VALUE;
     }
+
+    if (userId < 0) {
+        ALOGE("Invalid user: %d", userId);
+        dprintf(err, "Invalid user: %d\n", userId);
+        return BAD_VALUE;
+    }
+
+    uid = multiuser_get_uid(userId, uid);
+    return NO_ERROR;
+}
+
+status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
+    // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
+    if (!(args.size() == 3 || args.size() == 5)) {
+        printHelp(err);
+        return BAD_VALUE;
+    }
+
     bool active = false;
     if (args[2] == String16("active")) {
         active = true;
@@ -594,30 +612,59 @@
         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
         return BAD_VALUE;
     }
+
+    int userId = 0;
+    if (args.size() == 5 && args[3] == String16("--user")) {
+        userId = atoi(String8(args[4]));
+    }
+
+    uid_t uid;
+    if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
+        return BAD_VALUE;
+    }
+
     mUidPolicy->addOverrideUid(uid, active);
     return NO_ERROR;
 }
 
 status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
-    PermissionController pc;
-    int uid = pc.getPackageUid(args[1], 0);
-    if (uid < 0) {
-        ALOGE("Unknown package: '%s'", String8(args[1]).string());
-        dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
+    // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
+    if (!(args.size() == 2 || args.size() == 4)) {
+        printHelp(err);
         return BAD_VALUE;
     }
+
+    int userId = 0;
+    if (args.size() == 4 && args[2] == String16("--user")) {
+        userId = atoi(String8(args[3]));
+    }
+
+    uid_t uid;
+    if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
+        return BAD_VALUE;
+    }
+
     mUidPolicy->removeOverrideUid(uid);
     return NO_ERROR;
 }
 
 status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
-    PermissionController pc;
-    int uid = pc.getPackageUid(args[1], 0);
-    if (uid < 0) {
-        ALOGE("Unknown package: '%s'", String8(args[1]).string());
-        dprintf(err, "Unknown package: '%s'\n", String8(args[1]).string());
+    // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
+    if (!(args.size() == 2 || args.size() == 4)) {
+        printHelp(err);
         return BAD_VALUE;
     }
+
+    int userId = 0;
+    if (args.size() == 4 && args[2] == String16("--user")) {
+        userId = atoi(String8(args[3]));
+    }
+
+    uid_t uid;
+    if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
+        return BAD_VALUE;
+    }
+
     if (mUidPolicy->isUidActive(uid)) {
         return dprintf(out, "active\n");
     } else {
@@ -627,9 +674,9 @@
 
 status_t SensorService::printHelp(int out) {
     return dprintf(out, "Sensor service commands:\n"
-        "  get-uid-state <PACKAGE> gets the uid state\n"
-        "  set-uid-state <PACKAGE> <active|idle> overrides the uid state\n"
-        "  reset-uid-state <PACKAGE> clears the uid state override\n"
+        "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
+        "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
+        "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
         "  help print this message\n");
 }
 
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index fbfe05d..5076967 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -23,6 +23,7 @@
 #include <binder/BinderService.h>
 #include <binder/IUidObserver.h>
 #include <cutils/compiler.h>
+#include <cutils/multiuser.h>
 #include <sensor/ISensorServer.h>
 #include <sensor/ISensorEventConnection.h>
 #include <sensor/Sensor.h>
diff --git a/services/surfaceflinger/CompositionEngine/Android.bp b/services/surfaceflinger/CompositionEngine/Android.bp
index e86d35d..6f076ad 100644
--- a/services/surfaceflinger/CompositionEngine/Android.bp
+++ b/services/surfaceflinger/CompositionEngine/Android.bp
@@ -68,6 +68,7 @@
         "mock/DisplaySurface.cpp",
         "mock/Layer.cpp",
         "mock/LayerFE.cpp",
+        "mock/NativeWindow.cpp",
         "mock/Output.cpp",
         "mock/OutputLayer.cpp",
         "mock/RenderSurface.cpp",
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/NativeWindow.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/NativeWindow.h
new file mode 100644
index 0000000..714d2f7
--- /dev/null
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/NativeWindow.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <gmock/gmock.h>
+#include <system/window.h>
+#include <ui/ANativeObjectBase.h>
+#include <ui/GraphicTypes.h>
+#include <ui/PixelFormat.h>
+
+namespace android::compositionengine::mock {
+
+/* ------------------------------------------------------------------------
+ * Mock NativeWindow
+ *
+ * An intentionally simplified Mock which implements a minimal subset of the full
+ * ANativeWindow interface.
+ */
+class NativeWindow : public ANativeObjectBase<ANativeWindow, NativeWindow, RefBase> {
+public:
+    NativeWindow();
+    ~NativeWindow();
+
+    MOCK_METHOD1(setSwapInterval, int(int));
+    MOCK_METHOD2(dequeueBuffer, int(struct ANativeWindowBuffer**, int*));
+    MOCK_METHOD2(cancelBuffer, int(struct ANativeWindowBuffer*, int));
+    MOCK_METHOD2(queueBuffer, int(struct ANativeWindowBuffer*, int));
+    MOCK_CONST_METHOD2(query, int(int, int*));
+    MOCK_METHOD1(connect, int(int));
+    MOCK_METHOD1(disconnect, int(int));
+    MOCK_METHOD1(lockBuffer_DEPRECATED, int(struct ANativeWindowBuffer*));
+    MOCK_METHOD1(setBuffersFormat, int(PixelFormat));
+    MOCK_METHOD1(setBuffersDataSpace, int(ui::Dataspace));
+    MOCK_METHOD1(setUsage, int(uint64_t));
+};
+
+} // namespace android::compositionengine::mock
diff --git a/services/surfaceflinger/CompositionEngine/mock/NativeWindow.cpp b/services/surfaceflinger/CompositionEngine/mock/NativeWindow.cpp
new file mode 100644
index 0000000..d0cc8ef
--- /dev/null
+++ b/services/surfaceflinger/CompositionEngine/mock/NativeWindow.cpp
@@ -0,0 +1,121 @@
+
+/*
+ * Copyright 2019 The Android Open Source Project
+ *
+ * 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 "compositionengine/mock/NativeWindow.h"
+#include <log/log.h>
+
+namespace android::compositionengine::mock {
+
+static int forwardSetSwapInterval(ANativeWindow* window, int interval) {
+    return static_cast<NativeWindow*>(window)->setSwapInterval(interval);
+}
+
+static int forwardDequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer, int* fenceFd) {
+    return static_cast<NativeWindow*>(window)->dequeueBuffer(buffer, fenceFd);
+}
+
+static int forwardCancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
+    return static_cast<NativeWindow*>(window)->cancelBuffer(buffer, fenceFd);
+}
+
+static int forwardQueueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
+    return static_cast<NativeWindow*>(window)->queueBuffer(buffer, fenceFd);
+}
+
+static int forwardQuery(const ANativeWindow* window, int what, int* value) {
+    return static_cast<const NativeWindow*>(window)->query(what, value);
+}
+
+static int forwardPerform(ANativeWindow* window, int operation, ...) {
+    va_list args;
+    va_start(args, operation);
+    int result = NO_ERROR;
+    switch (operation) {
+        case NATIVE_WINDOW_API_CONNECT: {
+            int api = va_arg(args, int);
+            result = static_cast<NativeWindow*>(window)->connect(api);
+            break;
+        }
+        case NATIVE_WINDOW_SET_BUFFERS_FORMAT: {
+            PixelFormat format = va_arg(args, PixelFormat);
+            result = static_cast<NativeWindow*>(window)->setBuffersFormat(format);
+            break;
+        }
+        case NATIVE_WINDOW_SET_BUFFERS_DATASPACE: {
+            ui::Dataspace dataspace = static_cast<ui::Dataspace>(va_arg(args, int));
+            result = static_cast<NativeWindow*>(window)->setBuffersDataSpace(dataspace);
+            break;
+        }
+        case NATIVE_WINDOW_SET_USAGE: {
+            // Note: Intentionally widens usage from 32 to 64 bits so we
+            // just have one implementation.
+            uint64_t usage = va_arg(args, uint32_t);
+            result = static_cast<NativeWindow*>(window)->setUsage(usage);
+            break;
+        }
+        case NATIVE_WINDOW_SET_USAGE64: {
+            uint64_t usage = va_arg(args, uint64_t);
+            result = static_cast<NativeWindow*>(window)->setUsage(usage);
+            break;
+        }
+        case NATIVE_WINDOW_API_DISCONNECT: {
+            int api = va_arg(args, int);
+            result = static_cast<NativeWindow*>(window)->disconnect(api);
+            break;
+        }
+        default:
+            LOG_ALWAYS_FATAL("Unexpected operation %d", operation);
+            break;
+    }
+
+    va_end(args);
+    return result;
+}
+
+static int forwardDequeueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer** buffer) {
+    int ignoredFenceFd = -1;
+    return static_cast<NativeWindow*>(window)->dequeueBuffer(buffer, &ignoredFenceFd);
+}
+
+static int forwardCancelBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
+    return static_cast<NativeWindow*>(window)->cancelBuffer(buffer, -1);
+}
+
+static int forwardLockBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
+    return static_cast<NativeWindow*>(window)->lockBuffer_DEPRECATED(buffer);
+}
+
+static int forwardQueueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
+    return static_cast<NativeWindow*>(window)->queueBuffer(buffer, -1);
+}
+
+NativeWindow::NativeWindow() {
+    ANativeWindow::setSwapInterval = &forwardSetSwapInterval;
+    ANativeWindow::dequeueBuffer = &forwardDequeueBuffer;
+    ANativeWindow::cancelBuffer = &forwardCancelBuffer;
+    ANativeWindow::queueBuffer = &forwardQueueBuffer;
+    ANativeWindow::query = &forwardQuery;
+    ANativeWindow::perform = &forwardPerform;
+
+    ANativeWindow::dequeueBuffer_DEPRECATED = &forwardDequeueBufferDeprecated;
+    ANativeWindow::cancelBuffer_DEPRECATED = &forwardCancelBufferDeprecated;
+    ANativeWindow::lockBuffer_DEPRECATED = &forwardLockBufferDeprecated;
+    ANativeWindow::queueBuffer_DEPRECATED = &forwardQueueBufferDeprecated;
+}
+NativeWindow::~NativeWindow() = default;
+
+} // namespace android::compositionengine::mock
diff --git a/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp b/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp
index b4dfba1..b5a6678 100644
--- a/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/RenderSurface.cpp
@@ -52,9 +52,14 @@
         mDisplay(display),
         mNativeWindow(args.nativeWindow),
         mDisplaySurface(args.displaySurface),
-        mSize(args.displayWidth, args.displayHeight) {}
+        mSize(args.displayWidth, args.displayHeight) {
+    LOG_ALWAYS_FATAL_IF(!mNativeWindow);
+}
 
-RenderSurface::~RenderSurface() = default;
+RenderSurface::~RenderSurface() {
+    ANativeWindow* const window = mNativeWindow.get();
+    native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
+}
 
 bool RenderSurface::isValid() const {
     return mSize.isValid();
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index cd2d454..33444a5 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -22,9 +22,9 @@
 #include <compositionengine/RenderSurfaceCreationArgs.h>
 #include <compositionengine/impl/Display.h>
 #include <compositionengine/mock/CompositionEngine.h>
+#include <compositionengine/mock/NativeWindow.h>
 #include <compositionengine/mock/RenderSurface.h>
 #include <gtest/gtest.h>
-#include <system/window.h>
 
 #include "MockHWComposer.h"
 
@@ -43,6 +43,7 @@
 
     StrictMock<android::mock::HWComposer> mHwComposer;
     StrictMock<mock::CompositionEngine> mCompositionEngine;
+    sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
     impl::Display mDisplay{mCompositionEngine,
                            DisplayCreationArgsBuilder().setDisplayId(DEFAULT_DISPLAY_ID).build()};
 };
@@ -199,8 +200,9 @@
  */
 
 TEST_F(DisplayTest, createRenderSurfaceSetsRenderSurface) {
+    EXPECT_CALL(*mNativeWindow, disconnect(NATIVE_WINDOW_API_EGL)).WillRepeatedly(Return(NO_ERROR));
     EXPECT_TRUE(mDisplay.getRenderSurface() == nullptr);
-    mDisplay.createRenderSurface(RenderSurfaceCreationArgs{640, 480, nullptr, nullptr});
+    mDisplay.createRenderSurface(RenderSurfaceCreationArgs{640, 480, mNativeWindow, nullptr});
     EXPECT_TRUE(mDisplay.getRenderSurface() != nullptr);
 }
 
diff --git a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
index 84af9b9..9960478 100644
--- a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
@@ -22,11 +22,10 @@
 #include <compositionengine/mock/CompositionEngine.h>
 #include <compositionengine/mock/Display.h>
 #include <compositionengine/mock/DisplaySurface.h>
+#include <compositionengine/mock/NativeWindow.h>
 #include <compositionengine/mock/OutputLayer.h>
 #include <gtest/gtest.h>
 #include <renderengine/mock/RenderEngine.h>
-#include <system/window.h>
-#include <ui/ANativeObjectBase.h>
 
 #include "MockHWComposer.h"
 
@@ -34,123 +33,6 @@
 namespace {
 
 /* ------------------------------------------------------------------------
- * MockNativeWindow
- *
- * An intentionally simplified Mock which implements a minimal subset of the full
- * ANativeWindow interface.
- */
-
-class MockNativeWindow : public ANativeObjectBase<ANativeWindow, MockNativeWindow, RefBase> {
-public:
-    MockNativeWindow() {
-        ANativeWindow::setSwapInterval = &forwardSetSwapInterval;
-        ANativeWindow::dequeueBuffer = &forwardDequeueBuffer;
-        ANativeWindow::cancelBuffer = &forwardCancelBuffer;
-        ANativeWindow::queueBuffer = &forwardQueueBuffer;
-        ANativeWindow::query = &forwardQuery;
-        ANativeWindow::perform = &forwardPerform;
-
-        ANativeWindow::dequeueBuffer_DEPRECATED = &forwardDequeueBufferDeprecated;
-        ANativeWindow::cancelBuffer_DEPRECATED = &forwardCancelBufferDeprecated;
-        ANativeWindow::lockBuffer_DEPRECATED = &forwardLockBufferDeprecated;
-        ANativeWindow::queueBuffer_DEPRECATED = &forwardQueueBufferDeprecated;
-    }
-
-    MOCK_METHOD1(setSwapInterval, int(int));
-    MOCK_METHOD2(dequeueBuffer, int(struct ANativeWindowBuffer**, int*));
-    MOCK_METHOD2(cancelBuffer, int(struct ANativeWindowBuffer*, int));
-    MOCK_METHOD2(queueBuffer, int(struct ANativeWindowBuffer*, int));
-    MOCK_CONST_METHOD2(query, int(int, int*));
-    MOCK_METHOD1(connect, int(int));
-    MOCK_METHOD1(lockBuffer_DEPRECATED, int(struct ANativeWindowBuffer*));
-    MOCK_METHOD1(setBuffersFormat, int(PixelFormat));
-    MOCK_METHOD1(setBuffersDataSpace, int(ui::Dataspace));
-    MOCK_METHOD1(setUsage, int(uint64_t));
-
-    static void unexpectedCall(...) { LOG_ALWAYS_FATAL("Unexpected ANativeWindow API call"); }
-
-    static int forwardSetSwapInterval(ANativeWindow* window, int interval) {
-        return getSelf(window)->setSwapInterval(interval);
-    }
-
-    static int forwardDequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer,
-                                    int* fenceFd) {
-        return getSelf(window)->dequeueBuffer(buffer, fenceFd);
-    }
-
-    static int forwardCancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer,
-                                   int fenceFd) {
-        return getSelf(window)->cancelBuffer(buffer, fenceFd);
-    }
-
-    static int forwardQueueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer, int fenceFd) {
-        return getSelf(window)->queueBuffer(buffer, fenceFd);
-    }
-
-    static int forwardQuery(const ANativeWindow* window, int what, int* value) {
-        return getSelf(window)->query(what, value);
-    }
-
-    static int forwardPerform(ANativeWindow* window, int operation, ...) {
-        va_list args;
-        va_start(args, operation);
-        int result = NO_ERROR;
-        switch (operation) {
-            case NATIVE_WINDOW_API_CONNECT: {
-                int api = va_arg(args, int);
-                result = getSelf(window)->connect(api);
-                break;
-            }
-            case NATIVE_WINDOW_SET_BUFFERS_FORMAT: {
-                PixelFormat format = va_arg(args, PixelFormat);
-                result = getSelf(window)->setBuffersFormat(format);
-                break;
-            }
-            case NATIVE_WINDOW_SET_BUFFERS_DATASPACE: {
-                ui::Dataspace dataspace = static_cast<ui::Dataspace>(va_arg(args, int));
-                result = getSelf(window)->setBuffersDataSpace(dataspace);
-                break;
-            }
-            case NATIVE_WINDOW_SET_USAGE: {
-                // Note: Intentionally widens usage from 32 to 64 bits so we
-                // just have one implementation.
-                uint64_t usage = va_arg(args, uint32_t);
-                result = getSelf(window)->setUsage(usage);
-                break;
-            }
-            case NATIVE_WINDOW_SET_USAGE64: {
-                uint64_t usage = va_arg(args, uint64_t);
-                result = getSelf(window)->setUsage(usage);
-                break;
-            }
-            default:
-                LOG_ALWAYS_FATAL("Unexpected operation %d", operation);
-                break;
-        }
-
-        va_end(args);
-        return result;
-    }
-
-    static int forwardDequeueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer** buffer) {
-        int ignoredFenceFd = -1;
-        return getSelf(window)->dequeueBuffer(buffer, &ignoredFenceFd);
-    }
-
-    static int forwardCancelBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
-        return getSelf(window)->cancelBuffer(buffer, -1);
-    }
-
-    static int forwardLockBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
-        return getSelf(window)->lockBuffer_DEPRECATED(buffer);
-    }
-
-    static int forwardQueueBufferDeprecated(ANativeWindow* window, ANativeWindowBuffer* buffer) {
-        return getSelf(window)->queueBuffer(buffer, -1);
-    }
-};
-
-/* ------------------------------------------------------------------------
  * RenderSurfaceTest
  */
 
@@ -175,6 +57,8 @@
         EXPECT_CALL(mDisplay, getName()).WillRepeatedly(ReturnRef(DEFAULT_DISPLAY_NAME));
         EXPECT_CALL(mCompositionEngine, getHwComposer).WillRepeatedly(ReturnRef(mHwComposer));
         EXPECT_CALL(mCompositionEngine, getRenderEngine).WillRepeatedly(ReturnRef(mRenderEngine));
+        EXPECT_CALL(*mNativeWindow, disconnect(NATIVE_WINDOW_API_EGL))
+                .WillRepeatedly(Return(NO_ERROR));
     }
     ~RenderSurfaceTest() override = default;
 
@@ -182,7 +66,7 @@
     StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
     StrictMock<mock::CompositionEngine> mCompositionEngine;
     StrictMock<mock::Display> mDisplay;
-    sp<MockNativeWindow> mNativeWindow = new StrictMock<MockNativeWindow>();
+    sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
     sp<mock::DisplaySurface> mDisplaySurface = new StrictMock<mock::DisplaySurface>();
     impl::RenderSurface mSurface{mCompositionEngine, mDisplay,
                                  RenderSurfaceCreationArgs{DEFAULT_DISPLAY_WIDTH,
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 2bbac72..1527c34 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -1230,10 +1230,8 @@
 
 void Layer::updateTransformHint(const sp<const DisplayDevice>& display) const {
     uint32_t orientation = 0;
-    // Disable setting transform hint if the debug flag is set or if the
-    // getTransformToDisplayInverse flag is set and the client wants to submit buffers
-    // in one orientation.
-    if (!mFlinger->mDebugDisableTransformHint && !getTransformToDisplayInverse()) {
+    // Disable setting transform hint if the debug flag is set.
+    if (!mFlinger->mDebugDisableTransformHint) {
         // The transform hint is used to improve performance, but we can
         // only have a single transform hint, it cannot
         // apply to all displays.
diff --git a/services/surfaceflinger/Scheduler/PhaseOffsets.cpp b/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
index 7e2b03d..16f6729 100644
--- a/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
+++ b/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
@@ -86,8 +86,9 @@
     mHighRefreshRateOffsets.late = {highFpsLateSfOffsetNs, highFpsLateAppOffsetNs};
 }
 
-PhaseOffsets::Offsets PhaseOffsets::getCurrentOffsets() const {
-    switch (mRefreshRateType) {
+PhaseOffsets::Offsets PhaseOffsets::getOffsetsForRefreshRate(
+        android::scheduler::RefreshRateConfigs::RefreshRateType refreshRateType) const {
+    switch (refreshRateType) {
         case RefreshRateConfigs::RefreshRateType::PERFORMANCE:
             return mHighRefreshRateOffsets;
         default:
diff --git a/services/surfaceflinger/Scheduler/PhaseOffsets.h b/services/surfaceflinger/Scheduler/PhaseOffsets.h
index a85660a..08747a5 100644
--- a/services/surfaceflinger/Scheduler/PhaseOffsets.h
+++ b/services/surfaceflinger/Scheduler/PhaseOffsets.h
@@ -42,6 +42,8 @@
 
     virtual nsecs_t getCurrentAppOffset() = 0;
     virtual nsecs_t getCurrentSfOffset() = 0;
+    virtual Offsets getOffsetsForRefreshRate(
+            RefreshRateConfigs::RefreshRateType refreshRateType) const = 0;
     virtual Offsets getCurrentOffsets() const = 0;
     virtual void setRefreshRateType(RefreshRateConfigs::RefreshRateType refreshRateType) = 0;
     virtual void dump(std::string& result) const = 0;
@@ -55,8 +57,14 @@
     nsecs_t getCurrentAppOffset() override;
     nsecs_t getCurrentSfOffset() override;
 
+    // Returns early, early GL, and late offsets for Apps and SF for a given refresh rate.
+    Offsets getOffsetsForRefreshRate(
+            RefreshRateConfigs::RefreshRateType refreshRateType) const override;
+
     // Returns early, early GL, and late offsets for Apps and SF.
-    Offsets getCurrentOffsets() const override;
+    Offsets getCurrentOffsets() const override {
+        return getOffsetsForRefreshRate(mRefreshRateType);
+    }
 
     // This function should be called when the device is switching between different
     // refresh rates, to properly update the offsets.
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
index eb9ae35..d730058 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
@@ -47,6 +47,8 @@
         std::string name;
         // Refresh rate in frames per second, rounded to the nearest integer.
         uint32_t fps = 0;
+        // config Id (returned from HWC2::Display::Config::getId())
+        hwc2_config_t id;
     };
 
     // TODO(b/122916473): Get this information from configs prepared by vendors, instead of
@@ -62,13 +64,24 @@
         return nullptr;
     }
 
+    RefreshRateType getRefreshRateType(hwc2_config_t id) const {
+        for (const auto& [type, refreshRate] : mRefreshRates) {
+            if (refreshRate->id == id) {
+                return type;
+            }
+        }
+
+        return RefreshRateType::DEFAULT;
+    }
+
     void populate(const std::vector<std::shared_ptr<const HWC2::Display::Config>>& configs) {
         mRefreshRates.clear();
 
         // This is the rate that HWC encapsulates right now when the device is in DOZE mode.
         mRefreshRates.emplace(RefreshRateType::POWER_SAVING,
                               std::make_shared<RefreshRate>(
-                                      RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0}));
+                                      RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0,
+                                                  HWC2_SCREEN_OFF_CONFIG_ID}));
 
         if (configs.size() < 1) {
             ALOGE("Device does not have valid configs. Config size is 0.");
@@ -91,11 +104,12 @@
         nsecs_t vsyncPeriod = configIdToVsyncPeriod[0].second;
         if (vsyncPeriod != 0) {
             const float fps = 1e9 / vsyncPeriod;
+            const int configId = configIdToVsyncPeriod[0].first;
             mRefreshRates.emplace(RefreshRateType::DEFAULT,
                                   std::make_shared<RefreshRate>(
-                                          RefreshRate{configIdToVsyncPeriod[0].first,
-                                                      base::StringPrintf("%2.ffps", fps),
-                                                      static_cast<uint32_t>(fps)}));
+                                          RefreshRate{configId, base::StringPrintf("%2.ffps", fps),
+                                                      static_cast<uint32_t>(fps),
+                                                      configs.at(configId)->getId()}));
         }
 
         if (configs.size() < 2) {
@@ -107,11 +121,12 @@
         vsyncPeriod = configIdToVsyncPeriod[1].second;
         if (vsyncPeriod != 0) {
             const float fps = 1e9 / vsyncPeriod;
+            const int configId = configIdToVsyncPeriod[1].first;
             mRefreshRates.emplace(RefreshRateType::PERFORMANCE,
                                   std::make_shared<RefreshRate>(
-                                          RefreshRate{configIdToVsyncPeriod[1].first,
-                                                      base::StringPrintf("%2.ffps", fps),
-                                                      static_cast<uint32_t>(fps)}));
+                                          RefreshRate{configId, base::StringPrintf("%2.ffps", fps),
+                                                      static_cast<uint32_t>(fps),
+                                                      configs.at(configId)->getId()}));
         }
     }
 
diff --git a/services/surfaceflinger/Scheduler/SchedulerUtils.h b/services/surfaceflinger/Scheduler/SchedulerUtils.h
index a935cac..3bf3922 100644
--- a/services/surfaceflinger/Scheduler/SchedulerUtils.h
+++ b/services/surfaceflinger/Scheduler/SchedulerUtils.h
@@ -34,6 +34,7 @@
 // the config is not visible to SF, and is completely maintained by HWC. However, we would
 // still like to keep track of time when the device is in this config.
 static constexpr int SCREEN_OFF_CONFIG_ID = -1;
+static constexpr uint32_t HWC2_SCREEN_OFF_CONFIG_ID = 0xffffffff;
 
 // This number is used when we try to determine how long does a given layer stay relevant.
 // Currently it is set to 100ms, because that would indicate 10Hz rendering.
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 53c615f..6063555 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -860,7 +860,9 @@
         info.xdpi = xdpi;
         info.ydpi = ydpi;
         info.fps = 1e9 / hwConfig->getVsyncPeriod();
-        info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
+        const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
+        const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
+        info.appVsyncOffset = offset.late.app;
 
         // This is how far in advance a buffer must be queued for
         // presentation at a given time.  If you want a buffer to appear
@@ -874,8 +876,7 @@
         //
         // We add an additional 1ms to allow for processing time and
         // differences between the ideal and actual refresh rate.
-        info.presentationDeadline =
-                hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
+        info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
 
         // All non-virtual displays are currently considered secure.
         info.secure = true;
diff --git a/services/surfaceflinger/TimeStats/TimeStats.cpp b/services/surfaceflinger/TimeStats/TimeStats.cpp
index 78c6e74..740099e 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.cpp
+++ b/services/surfaceflinger/TimeStats/TimeStats.cpp
@@ -291,6 +291,9 @@
     std::lock_guard<std::mutex> lock(mMutex);
     if (!mTimeStatsTracker.count(layerID)) return;
     LayerRecord& layerRecord = mTimeStatsTracker[layerID];
+    if (layerRecord.waitData < 0 ||
+        layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+        return;
     TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
     if (timeRecord.frameTime.frameNumber == frameNumber) {
         timeRecord.frameTime.latchTime = latchTime;
@@ -306,6 +309,9 @@
     std::lock_guard<std::mutex> lock(mMutex);
     if (!mTimeStatsTracker.count(layerID)) return;
     LayerRecord& layerRecord = mTimeStatsTracker[layerID];
+    if (layerRecord.waitData < 0 ||
+        layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+        return;
     TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
     if (timeRecord.frameTime.frameNumber == frameNumber) {
         timeRecord.frameTime.desiredTime = desiredTime;
@@ -321,6 +327,9 @@
     std::lock_guard<std::mutex> lock(mMutex);
     if (!mTimeStatsTracker.count(layerID)) return;
     LayerRecord& layerRecord = mTimeStatsTracker[layerID];
+    if (layerRecord.waitData < 0 ||
+        layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+        return;
     TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
     if (timeRecord.frameTime.frameNumber == frameNumber) {
         timeRecord.frameTime.acquireTime = acquireTime;
@@ -338,6 +347,9 @@
     std::lock_guard<std::mutex> lock(mMutex);
     if (!mTimeStatsTracker.count(layerID)) return;
     LayerRecord& layerRecord = mTimeStatsTracker[layerID];
+    if (layerRecord.waitData < 0 ||
+        layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+        return;
     TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
     if (timeRecord.frameTime.frameNumber == frameNumber) {
         timeRecord.acquireFence = acquireFence;
@@ -353,6 +365,9 @@
     std::lock_guard<std::mutex> lock(mMutex);
     if (!mTimeStatsTracker.count(layerID)) return;
     LayerRecord& layerRecord = mTimeStatsTracker[layerID];
+    if (layerRecord.waitData < 0 ||
+        layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+        return;
     TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
     if (timeRecord.frameTime.frameNumber == frameNumber) {
         timeRecord.frameTime.presentTime = presentTime;
@@ -374,6 +389,9 @@
     std::lock_guard<std::mutex> lock(mMutex);
     if (!mTimeStatsTracker.count(layerID)) return;
     LayerRecord& layerRecord = mTimeStatsTracker[layerID];
+    if (layerRecord.waitData < 0 ||
+        layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
+        return;
     TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
     if (timeRecord.frameTime.frameNumber == frameNumber) {
         timeRecord.presentFence = presentFence;
diff --git a/services/surfaceflinger/TransactionCompletedThread.cpp b/services/surfaceflinger/TransactionCompletedThread.cpp
index 6b2b583..34df606 100644
--- a/services/surfaceflinger/TransactionCompletedThread.cpp
+++ b/services/surfaceflinger/TransactionCompletedThread.cpp
@@ -144,6 +144,9 @@
         } else {
             ALOGW("cannot find listener in mPendingTransactions");
         }
+        if (listener->second.size() == 0) {
+            mPendingTransactions.erase(listener);
+        }
 
         status_t err = addCallbackHandle(handle);
         if (err != NO_ERROR) {
@@ -231,7 +234,9 @@
 
                 // If we are still waiting on the callback handles for this transaction, stop
                 // here because all transaction callbacks for the same listener must come in order
-                if (mPendingTransactions[listener].count(transactionStats.callbackIds) != 0) {
+                auto pendingTransactions = mPendingTransactions.find(listener);
+                if (pendingTransactions != mPendingTransactions.end() &&
+                    pendingTransactions->second.count(transactionStats.callbackIds) != 0) {
                     break;
                 }
 
diff --git a/services/surfaceflinger/tests/Android.bp b/services/surfaceflinger/tests/Android.bp
index f121a95..003ae7f 100644
--- a/services/surfaceflinger/tests/Android.bp
+++ b/services/surfaceflinger/tests/Android.bp
@@ -22,6 +22,7 @@
         "Stress_test.cpp",
         "SurfaceInterceptor_test.cpp",
         "Transaction_test.cpp",
+        "VirtualDisplay_test.cpp",
     ],
     data: ["SurfaceFlinger_test.filter"],
     static_libs: [
diff --git a/services/surfaceflinger/tests/SurfaceFlinger_test.filter b/services/surfaceflinger/tests/SurfaceFlinger_test.filter
index be862c9..5ebae1e 100644
--- a/services/surfaceflinger/tests/SurfaceFlinger_test.filter
+++ b/services/surfaceflinger/tests/SurfaceFlinger_test.filter
@@ -1,5 +1,5 @@
 {
         "presubmit": {
-            "filter": "CredentialsTest.*:SurfaceFlingerStress.*:SurfaceInterceptorTest.*:LayerTransactionTest.*:LayerTypeTransactionTest.*:LayerUpdateTest.*:GeometryLatchingTest.*:CropLatchingTest.*:ChildLayerTest.*:ScreenCaptureTest.*:ScreenCaptureChildOnlyTest.*:DereferenceSurfaceControlTest.*:BoundlessLayerTest.*:MultiDisplayLayerBoundsTest.*"
+            "filter": "CredentialsTest.*:SurfaceFlingerStress.*:SurfaceInterceptorTest.*:LayerTransactionTest.*:LayerTypeTransactionTest.*:LayerUpdateTest.*:GeometryLatchingTest.*:CropLatchingTest.*:ChildLayerTest.*:ScreenCaptureTest.*:ScreenCaptureChildOnlyTest.*:DereferenceSurfaceControlTest.*:BoundlessLayerTest.*:MultiDisplayLayerBoundsTest.*:InvalidHandleTest.*:VirtualDisplayTest.*"
         }
 }
diff --git a/services/surfaceflinger/tests/VirtualDisplay_test.cpp b/services/surfaceflinger/tests/VirtualDisplay_test.cpp
new file mode 100644
index 0000000..9fd2227
--- /dev/null
+++ b/services/surfaceflinger/tests/VirtualDisplay_test.cpp
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * 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 <binder/Binder.h>
+
+#include <gtest/gtest.h>
+#include <gui/GLConsumer.h>
+#include <gui/Surface.h>
+#include <gui/SurfaceComposerClient.h>
+
+namespace android {
+namespace {
+
+class VirtualDisplayTest : public ::testing::Test {
+protected:
+    void SetUp() override {
+        sp<IGraphicBufferConsumer> consumer;
+
+        BufferQueue::createBufferQueue(&mProducer, &consumer);
+        consumer->setConsumerName(String8("Virtual disp consumer"));
+        consumer->setDefaultBufferSize(100, 100);
+
+        mGLConsumer = new GLConsumer(consumer, GLConsumer::TEXTURE_EXTERNAL, true, false);
+    }
+
+    sp<IGraphicBufferProducer> mProducer;
+    sp<GLConsumer> mGLConsumer;
+};
+
+TEST_F(VirtualDisplayTest, VirtualDisplayDestroyedSurfaceReuse) {
+    sp<IBinder> virtualDisplay =
+            SurfaceComposerClient::createDisplay(String8("VirtualDisplay"), false /*secure*/);
+
+    SurfaceComposerClient::Transaction t;
+    t.setDisplaySurface(virtualDisplay, mProducer);
+    t.apply(true);
+
+    SurfaceComposerClient::destroyDisplay(virtualDisplay);
+    virtualDisplay.clear();
+    // Sync here to ensure the display was completely destroyed in SF
+    t.apply(true);
+
+    sp<Surface> surface = new Surface(mProducer);
+    sp<ANativeWindow> window(surface);
+
+    ASSERT_EQ(NO_ERROR, native_window_api_connect(window.get(), NATIVE_WINDOW_API_EGL));
+}
+
+} // namespace
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index a13b888..97f9e6a 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -358,6 +358,9 @@
                 .WillRepeatedly(Return(0));
         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64))
                 .WillRepeatedly(Return(0));
+        EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT))
+                .WillRepeatedly(Return(0));
+
         return injector;
     }
 
@@ -376,6 +379,8 @@
                 .WillRepeatedly(Return(0));
         EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64))
                 .WillRepeatedly(Return(0));
+        EXPECT_CALL(*test->mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT))
+                .WillRepeatedly(Return(0));
     }
 
     static void setupFramebufferConsumerBufferQueueCallExpectations(DisplayTransactionTest* test) {
@@ -1198,6 +1203,7 @@
         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
         EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
+        EXPECT_CALL(*mNativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
         auto displayDevice = mInjector.inject();
 
         displayDevice->getCompositionDisplay()
@@ -2141,6 +2147,7 @@
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
+    EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
     display.inject();
 
     // There is a change to the viewport state
@@ -2185,6 +2192,7 @@
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_BUFFERS_FORMAT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_CONNECT)).Times(1);
     EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_SET_USAGE64)).Times(1);
+    EXPECT_CALL(*nativeWindow, perform(NATIVE_WINDOW_API_DISCONNECT)).Times(1);
     display.inject();
 
     // There is a change to the viewport state
diff --git a/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h b/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h
index 0739f15..cfa8337 100644
--- a/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h
+++ b/services/surfaceflinger/tests/unittests/FakePhaseOffsets.h
@@ -33,6 +33,11 @@
     nsecs_t getCurrentAppOffset() override { return FAKE_PHASE_OFFSET_NS; }
     nsecs_t getCurrentSfOffset() override { return FAKE_PHASE_OFFSET_NS; }
 
+    PhaseOffsets::Offsets getOffsetsForRefreshRate(
+            RefreshRateConfigs::RefreshRateType /*refreshRateType*/) const override {
+        return getCurrentOffsets();
+    }
+
     // Returns early, early GL, and late offsets for Apps and SF.
     PhaseOffsets::Offsets getCurrentOffsets() const override {
         return Offsets{{FAKE_PHASE_OFFSET_NS, FAKE_PHASE_OFFSET_NS},
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
index 8b37c22..5067fe8 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
@@ -37,7 +37,9 @@
 class RefreshRateConfigsTest : public testing::Test {
 protected:
     static constexpr int CONFIG_ID_60 = 0;
+    static constexpr hwc2_config_t HWC2_CONFIG_ID_60 = 0;
     static constexpr int CONFIG_ID_90 = 1;
+    static constexpr hwc2_config_t HWC2_CONFIG_ID_90 = 1;
     static constexpr int64_t VSYNC_60 = 16666667;
     static constexpr int64_t VSYNC_90 = 11111111;
 
@@ -81,7 +83,8 @@
     ASSERT_EQ(rates.end(), rates.find(RefreshRateType::PERFORMANCE));
     ASSERT_EQ(rates.end(), rates.find(RefreshRateType::DEFAULT));
 
-    RefreshRate expectedConfig = RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0};
+    RefreshRate expectedConfig =
+            RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0, HWC2_SCREEN_OFF_CONFIG_ID};
     assertRatesEqual(expectedConfig, *powerSavingRate->second);
 
     ASSERT_TRUE(mConfigs.getRefreshRate(RefreshRateType::POWER_SAVING));
@@ -109,9 +112,10 @@
     ASSERT_NE(rates.end(), defaultRate);
     ASSERT_EQ(rates.end(), rates.find(RefreshRateType::PERFORMANCE));
 
-    RefreshRate expectedPowerSavingConfig = RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0};
+    RefreshRate expectedPowerSavingConfig =
+            RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0, HWC2_SCREEN_OFF_CONFIG_ID};
     assertRatesEqual(expectedPowerSavingConfig, *powerSavingRate->second);
-    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60};
+    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60, HWC2_CONFIG_ID_60};
     assertRatesEqual(expectedDefaultConfig, *defaultRate->second);
 
     ASSERT_TRUE(mConfigs.getRefreshRate(RefreshRateType::POWER_SAVING));
@@ -145,11 +149,13 @@
     ASSERT_NE(rates.end(), defaultRate);
     ASSERT_NE(rates.end(), performanceRate);
 
-    RefreshRate expectedPowerSavingConfig = RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0};
+    RefreshRate expectedPowerSavingConfig =
+            RefreshRate{SCREEN_OFF_CONFIG_ID, "ScreenOff", 0, HWC2_SCREEN_OFF_CONFIG_ID};
     assertRatesEqual(expectedPowerSavingConfig, *powerSavingRate->second);
-    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60};
+    RefreshRate expectedDefaultConfig = RefreshRate{CONFIG_ID_60, "60fps", 60, HWC2_CONFIG_ID_60};
     assertRatesEqual(expectedDefaultConfig, *defaultRate->second);
-    RefreshRate expectedPerformanceConfig = RefreshRate{CONFIG_ID_90, "90fps", 90};
+    RefreshRate expectedPerformanceConfig =
+            RefreshRate{CONFIG_ID_90, "90fps", 90, HWC2_CONFIG_ID_90};
     assertRatesEqual(expectedPerformanceConfig, *performanceRate->second);
 
     ASSERT_TRUE(mConfigs.getRefreshRate(RefreshRateType::POWER_SAVING));
diff --git a/vulkan/libvulkan/code-generator.tmpl b/vulkan/libvulkan/code-generator.tmpl
index f04eb03..bdd3573 100644
--- a/vulkan/libvulkan/code-generator.tmpl
+++ b/vulkan/libvulkan/code-generator.tmpl
@@ -703,6 +703,7 @@
 {{Macro "driver.InterceptedExtensions"}}
 VK_KHR_get_physical_device_properties2
 VK_ANDROID_external_memory_android_hardware_buffer
+VK_KHR_bind_memory2
 {{end}}
 
 
@@ -750,6 +751,9 @@
     {{else if eq $.Name "vkGetInstanceProcAddr"}}true
     {{else if eq $.Name "vkGetDeviceProcAddr"}}true
 
+    {{/* VK_KHR_swapchain v69 requirement */}}
+    {{else if eq $.Name "vkBindImageMemory2"}}true
+    {{else if eq $.Name "vkBindImageMemory2KHR"}}true
     {{end}}
 
     {{$ext := GetAnnotation $ "extension"}}
@@ -985,6 +989,10 @@
     {{else if eq $.Name "vkGetPhysicalDeviceProperties"}}true
     {{else if eq $.Name "vkGetPhysicalDeviceProperties2"}}true
     {{else if eq $.Name "vkGetPhysicalDeviceProperties2KHR"}}true
+
+    {{/* VK_KHR_swapchain v69 requirement */}}
+    {{else if eq $.Name "vkBindImageMemory2"}}true
+    {{else if eq $.Name "vkBindImageMemory2KHR"}}true
     {{end}}
 
     {{$ext := GetAnnotation $ "extension"}}
diff --git a/vulkan/libvulkan/driver.cpp b/vulkan/libvulkan/driver.cpp
index b3259de..491d4d1 100644
--- a/vulkan/libvulkan/driver.cpp
+++ b/vulkan/libvulkan/driver.cpp
@@ -537,6 +537,7 @@
                 // Extensions we don't need to do anything about at this level
                 break;
 
+            case ProcHook::KHR_bind_memory2:
             case ProcHook::KHR_incremental_present:
             case ProcHook::KHR_shared_presentable_image:
             case ProcHook::KHR_swapchain:
@@ -577,6 +578,7 @@
                 // return now as these extensions do not require HAL support
                 return;
             case ProcHook::EXT_hdr_metadata:
+            case ProcHook::KHR_bind_memory2:
                 hook_extensions_.set(ext_bit);
                 break;
             case ProcHook::ANDROID_external_memory_android_hardware_buffer:
diff --git a/vulkan/libvulkan/driver_gen.cpp b/vulkan/libvulkan/driver_gen.cpp
index ec98b9f..574c327 100644
--- a/vulkan/libvulkan/driver_gen.cpp
+++ b/vulkan/libvulkan/driver_gen.cpp
@@ -137,6 +137,15 @@
     }
 }
 
+VKAPI_ATTR VkResult checkedBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR* pBindInfos) {
+    if (GetData(device).hook_extensions[ProcHook::KHR_bind_memory2]) {
+        return BindImageMemory2KHR(device, bindInfoCount, pBindInfos);
+    } else {
+        Logger(device).Err(device, "VK_KHR_bind_memory2 not enabled. vkBindImageMemory2KHR not executed.");
+        return VK_SUCCESS;
+    }
+}
+
 // clang-format on
 
 const ProcHook g_proc_hooks[] = {
@@ -170,6 +179,20 @@
         nullptr,
     },
     {
+        "vkBindImageMemory2",
+        ProcHook::DEVICE,
+        ProcHook::EXTENSION_CORE,
+        reinterpret_cast<PFN_vkVoidFunction>(BindImageMemory2),
+        nullptr,
+    },
+    {
+        "vkBindImageMemory2KHR",
+        ProcHook::DEVICE,
+        ProcHook::KHR_bind_memory2,
+        reinterpret_cast<PFN_vkVoidFunction>(BindImageMemory2KHR),
+        reinterpret_cast<PFN_vkVoidFunction>(checkedBindImageMemory2KHR),
+    },
+    {
         "vkCreateAndroidSurfaceKHR",
         ProcHook::INSTANCE,
         ProcHook::KHR_android_surface,
@@ -458,6 +481,7 @@
     if (strcmp(name, "VK_KHR_get_surface_capabilities2") == 0) return ProcHook::KHR_get_surface_capabilities2;
     if (strcmp(name, "VK_KHR_get_physical_device_properties2") == 0) return ProcHook::KHR_get_physical_device_properties2;
     if (strcmp(name, "VK_ANDROID_external_memory_android_hardware_buffer") == 0) return ProcHook::ANDROID_external_memory_android_hardware_buffer;
+    if (strcmp(name, "VK_KHR_bind_memory2") == 0) return ProcHook::KHR_bind_memory2;
     // clang-format on
     return ProcHook::EXTENSION_UNKNOWN;
 }
@@ -517,11 +541,13 @@
     INIT_PROC(true, dev, CreateImage);
     INIT_PROC(true, dev, DestroyImage);
     INIT_PROC(true, dev, AllocateCommandBuffers);
+    INIT_PROC(false, dev, BindImageMemory2);
     INIT_PROC(false, dev, GetDeviceQueue2);
     INIT_PROC_EXT(ANDROID_native_buffer, false, dev, GetSwapchainGrallocUsageANDROID);
     INIT_PROC_EXT(ANDROID_native_buffer, false, dev, GetSwapchainGrallocUsage2ANDROID);
     INIT_PROC_EXT(ANDROID_native_buffer, true, dev, AcquireImageANDROID);
     INIT_PROC_EXT(ANDROID_native_buffer, true, dev, QueueSignalReleaseImageANDROID);
+    INIT_PROC_EXT(KHR_bind_memory2, true, dev, BindImageMemory2KHR);
     // clang-format on
 
     return success;
diff --git a/vulkan/libvulkan/driver_gen.h b/vulkan/libvulkan/driver_gen.h
index 14c3aba..3faf6c0 100644
--- a/vulkan/libvulkan/driver_gen.h
+++ b/vulkan/libvulkan/driver_gen.h
@@ -46,6 +46,7 @@
         KHR_get_surface_capabilities2,
         KHR_get_physical_device_properties2,
         ANDROID_external_memory_android_hardware_buffer,
+        KHR_bind_memory2,
 
         EXTENSION_CORE,  // valid bit
         EXTENSION_COUNT,
@@ -85,11 +86,13 @@
     PFN_vkCreateImage CreateImage;
     PFN_vkDestroyImage DestroyImage;
     PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
+    PFN_vkBindImageMemory2 BindImageMemory2;
     PFN_vkGetDeviceQueue2 GetDeviceQueue2;
     PFN_vkGetSwapchainGrallocUsageANDROID GetSwapchainGrallocUsageANDROID;
     PFN_vkGetSwapchainGrallocUsage2ANDROID GetSwapchainGrallocUsage2ANDROID;
     PFN_vkAcquireImageANDROID AcquireImageANDROID;
     PFN_vkQueueSignalReleaseImageANDROID QueueSignalReleaseImageANDROID;
+    PFN_vkBindImageMemory2KHR BindImageMemory2KHR;
     // clang-format on
 };
 
diff --git a/vulkan/libvulkan/swapchain.cpp b/vulkan/libvulkan/swapchain.cpp
index 73fc7b2..bc00190 100644
--- a/vulkan/libvulkan/swapchain.cpp
+++ b/vulkan/libvulkan/swapchain.cpp
@@ -16,17 +16,19 @@
 
 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
 
-#include <algorithm>
-
+#include <android/hardware/graphics/common/1.0/types.h>
 #include <grallocusage/GrallocUsageConversion.h>
 #include <log/log.h>
-#include <ui/BufferQueueDefs.h>
 #include <sync/sync.h>
+#include <system/window.h>
+#include <ui/BufferQueueDefs.h>
 #include <utils/StrongPointer.h>
 #include <utils/Trace.h>
 #include <utils/Vector.h>
-#include <system/window.h>
-#include <android/hardware/graphics/common/1.0/types.h>
+
+#include <algorithm>
+#include <unordered_set>
+#include <vector>
 
 #include "driver.h"
 
@@ -1818,5 +1820,106 @@
     return;
 }
 
+static void InterceptBindImageMemory2(
+    uint32_t bind_info_count,
+    const VkBindImageMemoryInfo* bind_infos,
+    std::vector<VkNativeBufferANDROID>* out_native_buffers,
+    std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
+    out_native_buffers->clear();
+    out_bind_infos->clear();
+
+    if (!bind_info_count)
+        return;
+
+    std::unordered_set<uint32_t> intercepted_indexes;
+
+    for (uint32_t idx = 0; idx < bind_info_count; idx++) {
+        auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
+            bind_infos[idx].pNext);
+        while (info &&
+               info->sType !=
+                   VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
+            info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
+                info->pNext);
+        }
+
+        if (!info)
+            continue;
+
+        ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
+                    "swapchain handle must not be NULL");
+        const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
+        ALOG_ASSERT(
+            info->imageIndex < swapchain->num_images,
+            "imageIndex must be less than the number of images in swapchain");
+
+        ANativeWindowBuffer* buffer =
+            swapchain->images[info->imageIndex].buffer.get();
+        VkNativeBufferANDROID native_buffer = {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wold-style-cast"
+            .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
+#pragma clang diagnostic pop
+            .pNext = bind_infos[idx].pNext,
+            .handle = buffer->handle,
+            .stride = buffer->stride,
+            .format = buffer->format,
+            .usage = int(buffer->usage),
+        };
+        // Reserve enough space to avoid letting re-allocation invalidate the
+        // addresses of the elements inside.
+        out_native_buffers->reserve(bind_info_count);
+        out_native_buffers->emplace_back(native_buffer);
+
+        // Reserve the space now since we know how much is needed now.
+        out_bind_infos->reserve(bind_info_count);
+        out_bind_infos->emplace_back(bind_infos[idx]);
+        out_bind_infos->back().pNext = &out_native_buffers->back();
+
+        intercepted_indexes.insert(idx);
+    }
+
+    if (intercepted_indexes.empty())
+        return;
+
+    for (uint32_t idx = 0; idx < bind_info_count; idx++) {
+        if (intercepted_indexes.count(idx))
+            continue;
+        out_bind_infos->emplace_back(bind_infos[idx]);
+    }
+}
+
+VKAPI_ATTR
+VkResult BindImageMemory2(VkDevice device,
+                          uint32_t bindInfoCount,
+                          const VkBindImageMemoryInfo* pBindInfos) {
+    ATRACE_CALL();
+
+    // out_native_buffers is for maintaining the lifecycle of the constructed
+    // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
+    std::vector<VkNativeBufferANDROID> out_native_buffers;
+    std::vector<VkBindImageMemoryInfo> out_bind_infos;
+    InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
+                              &out_bind_infos);
+    return GetData(device).driver.BindImageMemory2(
+        device, bindInfoCount,
+        out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
+}
+
+VKAPI_ATTR
+VkResult BindImageMemory2KHR(VkDevice device,
+                             uint32_t bindInfoCount,
+                             const VkBindImageMemoryInfo* pBindInfos) {
+    ATRACE_CALL();
+
+    std::vector<VkNativeBufferANDROID> out_native_buffers;
+    std::vector<VkBindImageMemoryInfo> out_bind_infos;
+    InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
+                              &out_bind_infos);
+    return GetData(device).driver.BindImageMemory2KHR(
+        device, bindInfoCount,
+        out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
+}
+
 }  // namespace driver
 }  // namespace vulkan
diff --git a/vulkan/libvulkan/swapchain.h b/vulkan/libvulkan/swapchain.h
index ed5718c..4912ef1 100644
--- a/vulkan/libvulkan/swapchain.h
+++ b/vulkan/libvulkan/swapchain.h
@@ -44,6 +44,8 @@
 VKAPI_ATTR void SetHdrMetadataEXT(VkDevice device, uint32_t swapchainCount, const VkSwapchainKHR* pSwapchains, const VkHdrMetadataEXT* pHdrMetadataEXTs);
 VKAPI_ATTR VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkSurfaceCapabilities2KHR* pSurfaceCapabilities);
 VKAPI_ATTR VkResult GetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats);
+VKAPI_ATTR VkResult BindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos);
+VKAPI_ATTR VkResult BindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos);
 // clang-format on
 
 }  // namespace driver