Merge "Check whether pointer has stopped at liftoff"
diff --git a/libs/gui/GLConsumerUtils.cpp b/libs/gui/GLConsumerUtils.cpp
index 7a06c3d..a1c69e7 100644
--- a/libs/gui/GLConsumerUtils.cpp
+++ b/libs/gui/GLConsumerUtils.cpp
@@ -27,6 +27,13 @@
 void GLConsumer::computeTransformMatrix(float outTransform[16],
         const sp<GraphicBuffer>& buf, const Rect& cropRect, uint32_t transform,
         bool filtering) {
+    computeTransformMatrix(outTransform, buf->getWidth(), buf->getHeight(), buf->getPixelFormat(),
+                           cropRect, transform, filtering);
+}
+
+void GLConsumer::computeTransformMatrix(float outTransform[16], float bufferWidth,
+                                        float bufferHeight, PixelFormat pixelFormat,
+                                        const Rect& cropRect, uint32_t transform, bool filtering) {
     // Transform matrices
     static const mat4 mtxFlipH(
         -1, 0, 0, 0,
@@ -60,8 +67,6 @@
 
     if (!cropRect.isEmpty()) {
         float tx = 0.0f, ty = 0.0f, sx = 1.0f, sy = 1.0f;
-        float bufferWidth = buf->getWidth();
-        float bufferHeight = buf->getHeight();
         float shrinkAmount = 0.0f;
         if (filtering) {
             // In order to prevent bilinear sampling beyond the edge of the
@@ -70,7 +75,7 @@
             // off each end, but because the chroma channels of YUV420 images
             // are subsampled we may need to shrink the crop region by a whole
             // texel on each side.
-            switch (buf->getPixelFormat()) {
+            switch (pixelFormat) {
                 case PIXEL_FORMAT_RGBA_8888:
                 case PIXEL_FORMAT_RGBX_8888:
                 case PIXEL_FORMAT_RGBA_FP16:
diff --git a/libs/gui/include/gui/GLConsumer.h b/libs/gui/include/gui/GLConsumer.h
index 2f538ff..ba268ab 100644
--- a/libs/gui/include/gui/GLConsumer.h
+++ b/libs/gui/include/gui/GLConsumer.h
@@ -138,6 +138,10 @@
             const sp<GraphicBuffer>& buf, const Rect& cropRect,
             uint32_t transform, bool filtering);
 
+    static void computeTransformMatrix(float outTransform[16], float bufferWidth,
+                                       float bufferHeight, PixelFormat pixelFormat,
+                                       const Rect& cropRect, uint32_t transform, bool filtering);
+
     // Scale the crop down horizontally or vertically such that it has the
     // same aspect ratio as the buffer does.
     static Rect scaleDownCrop(const Rect& crop, uint32_t bufferWidth,
diff --git a/services/surfaceflinger/BufferLayer.cpp b/services/surfaceflinger/BufferLayer.cpp
index d9c89cd..fb15f1d 100644
--- a/services/surfaceflinger/BufferLayer.cpp
+++ b/services/surfaceflinger/BufferLayer.cpp
@@ -738,10 +738,14 @@
 }
 
 void BufferLayer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) {
-    GLConsumer::computeTransformMatrix(outMatrix,
-                                       mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer()
-                                                           : nullptr,
-                                       mBufferInfo.mCrop, mBufferInfo.mTransform, filteringEnabled);
+    sp<GraphicBuffer> buffer = getBuffer();
+    if (!buffer) {
+        ALOGE("Buffer should not be null!");
+        return;
+    }
+    GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
+                                       buffer->getPixelFormat(), mBufferInfo.mCrop,
+                                       mBufferInfo.mTransform, filteringEnabled);
 }
 
 void BufferLayer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
diff --git a/services/surfaceflinger/BufferQueueLayer.h b/services/surfaceflinger/BufferQueueLayer.h
index e1c80d5..f7a4fd2 100644
--- a/services/surfaceflinger/BufferQueueLayer.h
+++ b/services/surfaceflinger/BufferQueueLayer.h
@@ -35,8 +35,6 @@
  */
 class BufferQueueLayer : public BufferLayer {
 public:
-    // Only call while mStateLock is held
-    explicit BufferQueueLayer(const LayerCreationArgs&);
     ~BufferQueueLayer() override;
 
     // Implements Layer.
@@ -92,6 +90,8 @@
     };
 
 private:
+    // Goodbye
+    explicit BufferQueueLayer(const LayerCreationArgs&);
 
     bool latchSidebandStream(bool& recomputeVisibleRegions) override;
     void setTransformHint(ui::Transform::RotationFlags displayTransformHint) override;
diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp
index cccf907..ea856e4 100644
--- a/services/surfaceflinger/CompositionEngine/src/Display.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp
@@ -261,7 +261,7 @@
     }
 
     if (isPowerHintSessionEnabled()) {
-        mPowerAdvisor->setValidateTiming(mId, startTime, systemTime());
+        mPowerAdvisor->setHwcValidateTiming(mId, startTime, systemTime());
         mPowerAdvisor->setRequiresClientComposition(mId, requiresClientComposition);
     }
 
@@ -371,7 +371,7 @@
         if (!getCompositionEngine().getHwComposer().getComposer()->isSupported(
                     Hwc2::Composer::OptionalFeature::ExpectedPresentTime) &&
             getState().previousPresentFence->getSignalTime() != Fence::SIGNAL_TIME_PENDING) {
-            mPowerAdvisor->setPresentDelayedTime(mId, getState().earliestPresentTime);
+            mPowerAdvisor->setHwcPresentDelayedTime(mId, getState().earliestPresentTime);
         }
     }
 
@@ -379,7 +379,7 @@
                                    getState().previousPresentFence);
 
     if (isPowerHintSessionEnabled()) {
-        mPowerAdvisor->setPresentTiming(mId, startTime, systemTime());
+        mPowerAdvisor->setHwcPresentTiming(mId, startTime, systemTime());
     }
 
     fences.presentFence = hwc.getPresentFence(*halDisplayIdOpt);
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h b/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h
index c8b6d44..579636f 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h
@@ -45,17 +45,17 @@
     MOCK_METHOD(bool, startPowerHintSession, (const std::vector<int32_t>& threadIds), (override));
     MOCK_METHOD(void, setGpuFenceTime,
                 (DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime), (override));
-    MOCK_METHOD(void, setValidateTiming,
+    MOCK_METHOD(void, setHwcValidateTiming,
                 (DisplayId displayId, nsecs_t valiateStartTime, nsecs_t validateEndTime),
                 (override));
-    MOCK_METHOD(void, setPresentTiming,
+    MOCK_METHOD(void, setHwcPresentTiming,
                 (DisplayId displayId, nsecs_t presentStartTime, nsecs_t presentEndTime),
                 (override));
     MOCK_METHOD(void, setSkippedValidate, (DisplayId displayId, bool skipped), (override));
     MOCK_METHOD(void, setRequiresClientComposition,
                 (DisplayId displayId, bool requiresClientComposition), (override));
     MOCK_METHOD(void, setExpectedPresentTime, (nsecs_t expectedPresentTime), (override));
-    MOCK_METHOD(void, setPresentDelayedTime,
+    MOCK_METHOD(void, setHwcPresentDelayedTime,
                 (DisplayId displayId,
                  std::chrono::steady_clock::time_point earliestFrameStartTime));
     MOCK_METHOD(void, setFrameDelay, (nsecs_t frameDelayDuration), (override));
diff --git a/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp b/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp
index 4c0a942..f844845 100644
--- a/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp
+++ b/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp
@@ -287,18 +287,18 @@
     displayData.gpuStartTime = systemTime();
 }
 
-void PowerAdvisor::setValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
-                                     nsecs_t validateEndTime) {
+void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
+                                        nsecs_t validateEndTime) {
     DisplayTimingData& displayData = mDisplayTimingData[displayId];
-    displayData.validateStartTime = validateStartTime;
-    displayData.validateEndTime = validateEndTime;
+    displayData.hwcValidateStartTime = validateStartTime;
+    displayData.hwcValidateEndTime = validateEndTime;
 }
 
-void PowerAdvisor::setPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
-                                    nsecs_t presentEndTime) {
+void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
+                                       nsecs_t presentEndTime) {
     DisplayTimingData& displayData = mDisplayTimingData[displayId];
-    displayData.presentStartTime = presentStartTime;
-    displayData.presentEndTime = presentEndTime;
+    displayData.hwcPresentStartTime = presentStartTime;
+    displayData.hwcPresentEndTime = presentEndTime;
 }
 
 void PowerAdvisor::setSkippedValidate(DisplayId displayId, bool skipped) {
@@ -318,9 +318,9 @@
     mFrameDelayDuration = frameDelayDuration;
 }
 
-void PowerAdvisor::setPresentDelayedTime(
+void PowerAdvisor::setHwcPresentDelayedTime(
         DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) {
-    mDisplayTimingData[displayId].presentDelayedTime =
+    mDisplayTimingData[displayId].hwcPresentDelayedTime =
             (earliestFrameStartTime - std::chrono::steady_clock::now()).count() + systemTime();
 }
 
@@ -331,10 +331,11 @@
 void PowerAdvisor::setCompositeEnd(nsecs_t compositeEnd) {
     mLastCompositeEndTime = compositeEnd;
     // calculate the postcomp time here as well
-    std::vector<DisplayId>&& displays = getOrderedDisplayIds(&DisplayTimingData::presentEndTime);
+    std::vector<DisplayId>&& displays = getOrderedDisplayIds(&DisplayTimingData::hwcPresentEndTime);
     DisplayTimingData& timingData = mDisplayTimingData[displays.back()];
     mLastPostcompDuration = compositeEnd -
-            (timingData.skippedValidate ? *timingData.validateEndTime : *timingData.presentEndTime);
+            (timingData.skippedValidate ? *timingData.hwcValidateEndTime
+                                        : *timingData.hwcPresentEndTime);
 }
 
 void PowerAdvisor::setDisplays(std::vector<DisplayId>& displayIds) {
@@ -390,7 +391,7 @@
     // The timing info for the previously calculated display, if there was one
     std::optional<DisplayTimeline> previousDisplayReferenceTiming;
     std::vector<DisplayId>&& displayIds =
-            getOrderedDisplayIds(&DisplayTimingData::presentStartTime);
+            getOrderedDisplayIds(&DisplayTimingData::hwcPresentStartTime);
     DisplayTimeline referenceTiming, estimatedTiming;
 
     // Iterate over the displays in the same order they are presented
@@ -402,27 +403,26 @@
         auto& displayData = mDisplayTimingData.at(displayId);
         referenceTiming = displayData.calculateDisplayTimeline(referenceFenceTime);
 
-        // If this is the first display, add the pre-present time to the total
+        // If this is the first display, include the duration before hwc present starts
         if (!previousDisplayReferenceTiming.has_value()) {
-            estimatedEndTime += referenceTiming.prePresentTime - referenceFrameStartTime;
-        } else { // Otherwise add last display's postprocessing time to the total
-            estimatedEndTime += referenceTiming.prePresentTime -
-                    previousDisplayReferenceTiming->postPresentTime;
+            estimatedEndTime += referenceTiming.hwcPresentStartTime - referenceFrameStartTime;
+        } else { // Otherwise add the time since last display's hwc present finished
+            estimatedEndTime += referenceTiming.hwcPresentStartTime -
+                    previousDisplayReferenceTiming->hwcPresentEndTime;
         }
 
         estimatedTiming = referenceTiming.estimateTimelineFromReference(mExpectedPresentTimes[-1],
                                                                         estimatedEndTime);
         // Update predicted present finish time with this display's present time
-        estimatedEndTime = estimatedTiming.postPresentTime;
+        estimatedEndTime = estimatedTiming.hwcPresentEndTime;
 
         // Track how long we spent waiting for the fence, can be excluded from the timing estimate
-        idleDuration += estimatedTiming.probablyWaitsForFence
-                ? mExpectedPresentTimes[-1] - estimatedTiming.preFenceWaitTime
+        idleDuration += estimatedTiming.probablyWaitsForReleaseFence
+                ? mExpectedPresentTimes[-1] - estimatedTiming.releaseFenceWaitStartTime
                 : 0;
 
         // Track how long we spent waiting to present, can be excluded from the timing estimate
-        idleDuration +=
-                !earlyHint ? referenceTiming.presentStartTime - referenceTiming.prePresentTime : 0;
+        idleDuration += earlyHint ? 0 : referenceTiming.hwcPresentDelayDuration;
 
         // Estimate the reference frame's gpu timing
         auto gpuTiming = displayData.estimateGpuTiming(previousValidGpuEndTime);
@@ -431,7 +431,7 @@
 
             // Estimate the prediction frame's gpu end time from the reference frame
             estimatedGpuEndTime =
-                    std::max(estimatedTiming.prePresentTime, estimatedGpuEndTime.value_or(0)) +
+                    std::max(estimatedTiming.hwcPresentStartTime, estimatedGpuEndTime.value_or(0)) +
                     gpuTiming->duration;
         }
         previousDisplayReferenceTiming = referenceTiming;
@@ -470,48 +470,55 @@
 PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimeline::estimateTimelineFromReference(
         nsecs_t fenceTime, nsecs_t displayStartTime) {
     DisplayTimeline estimated;
-    estimated.prePresentTime = displayStartTime;
+    estimated.hwcPresentStartTime = displayStartTime;
 
     // We don't predict waiting for vsync alignment yet
-    estimated.presentStartTime = estimated.prePresentTime;
+    estimated.hwcPresentDelayDuration = 0;
 
     // For now just re-use last frame's post-present duration and assume it will not change much
     // How long we expect to run before we start waiting for the fence
-    estimated.preFenceWaitTime = estimated.presentStartTime + (preFenceWaitTime - presentStartTime);
-    estimated.probablyWaitsForFence = fenceTime > estimated.preFenceWaitTime;
-    estimated.postPresentTime = postFenceDuration +
-            (estimated.probablyWaitsForFence ? fenceTime : estimated.preFenceWaitTime);
+    // If it's the early hint we exclude time we spent waiting for a vsync, otherwise don't
+    estimated.releaseFenceWaitStartTime = estimated.hwcPresentStartTime +
+            (releaseFenceWaitStartTime - (hwcPresentStartTime + hwcPresentDelayDuration));
+    estimated.probablyWaitsForReleaseFence = fenceTime > estimated.releaseFenceWaitStartTime;
+    estimated.hwcPresentEndTime = postReleaseFenceHwcPresentDuration +
+            (estimated.probablyWaitsForReleaseFence ? fenceTime
+                                                    : estimated.releaseFenceWaitStartTime);
     return estimated;
 }
 
 PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
         nsecs_t fenceTime) {
     DisplayTimeline timeline;
-    // How long between calling present from flinger and trying to wait on the fence in HWC
-    const nsecs_t preFenceWaitDelay =
-            (skippedValidate ? kPrefenceDelaySkippedValidate : kPrefenceDelayValidated).count();
+    // How long between calling hwc present and trying to wait on the fence
+    const nsecs_t fenceWaitStartDelay =
+            (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated)
+                    .count();
 
-    // Did our reference frame wait for an earliest present time before calling the HWC
-    const bool waitedOnPresentTime = presentDelayedTime.has_value() &&
-            *presentDelayedTime > *presentStartTime && *presentDelayedTime < *presentEndTime;
+    // Did our reference frame wait for an appropriate vsync before calling into hwc
+    const bool waitedOnHwcPresentTime = hwcPresentDelayedTime.has_value() &&
+            *hwcPresentDelayedTime > *hwcPresentStartTime &&
+            *hwcPresentDelayedTime < *hwcPresentEndTime;
 
     // Use validate start here if we skipped it because we did validate + present together
-    timeline.prePresentTime = skippedValidate ? *validateStartTime : *presentStartTime;
+    timeline.hwcPresentStartTime = skippedValidate ? *hwcValidateStartTime : *hwcPresentStartTime;
 
     // Use validate end here if we skipped it because we did validate + present together
-    timeline.postPresentTime = skippedValidate ? *validateEndTime : *presentEndTime;
+    timeline.hwcPresentEndTime = skippedValidate ? *hwcValidateEndTime : *hwcPresentEndTime;
 
-    // When we think we started waiting for the fence after calling into present
-    // This is after any time spent waiting for the earliest present time
-    timeline.presentStartTime =
-            (waitedOnPresentTime ? *presentDelayedTime : timeline.prePresentTime);
-    timeline.preFenceWaitTime = timeline.presentStartTime + preFenceWaitDelay;
-    timeline.probablyWaitsForFence =
-            fenceTime > timeline.preFenceWaitTime && fenceTime < timeline.postPresentTime;
+    // How long hwc present was delayed waiting for the next appropriate vsync
+    timeline.hwcPresentDelayDuration =
+            (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0);
+    // When we started waiting for the release fence after calling into hwc present
+    timeline.releaseFenceWaitStartTime =
+            timeline.hwcPresentStartTime + timeline.hwcPresentDelayDuration + fenceWaitStartDelay;
+    timeline.probablyWaitsForReleaseFence = fenceTime > timeline.releaseFenceWaitStartTime &&
+            fenceTime < timeline.hwcPresentEndTime;
 
-    // How long we ran after we finished waiting for the fence but before present happened
-    timeline.postFenceDuration = timeline.postPresentTime -
-            (timeline.probablyWaitsForFence ? fenceTime : timeline.preFenceWaitTime);
+    // How long we ran after we finished waiting for the fence but before hwc present finished
+    timeline.postReleaseFenceHwcPresentDuration = timeline.hwcPresentEndTime -
+            (timeline.probablyWaitsForReleaseFence ? fenceTime
+                                                   : timeline.releaseFenceWaitStartTime);
     return timeline;
 }
 
diff --git a/services/surfaceflinger/DisplayHardware/PowerAdvisor.h b/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
index 8e1e33f..bdc7927 100644
--- a/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
+++ b/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
@@ -64,20 +64,20 @@
     virtual bool startPowerHintSession(const std::vector<int32_t>& threadIds) = 0;
     // Provides PowerAdvisor with a copy of the gpu fence so it can determine the gpu end time
     virtual void setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime) = 0;
-    // Reports the start and end times of a present call this frame for a given display
-    virtual void setValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
-                                   nsecs_t validateEndTime) = 0;
-    // Reports the start and end times of a present call this frame for a given display
-    virtual void setPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
-                                  nsecs_t presentEndTime) = 0;
+    // Reports the start and end times of a hwc validate call this frame for a given display
+    virtual void setHwcValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
+                                      nsecs_t validateEndTime) = 0;
+    // Reports the start and end times of a hwc present call this frame for a given display
+    virtual void setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
+                                     nsecs_t presentEndTime) = 0;
     virtual void setExpectedPresentTime(nsecs_t expectedPresentTime) = 0;
     // Reports whether a display used client composition this frame
     virtual void setRequiresClientComposition(DisplayId displayId,
                                               bool requiresClientComposition) = 0;
     // Reports whether a given display skipped validation this frame
     virtual void setSkippedValidate(DisplayId displayId, bool skipped) = 0;
-    // Reports how much a given display delayed its present call this frame
-    virtual void setPresentDelayedTime(
+    // Reports when a hwc present is delayed, and the time that it will resume
+    virtual void setHwcPresentDelayedTime(
             DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) = 0;
     // Reports the start delay for SurfaceFlinger this frame
     virtual void setFrameDelay(nsecs_t frameDelayDuration) = 0;
@@ -132,14 +132,14 @@
     void enablePowerHint(bool enabled) override;
     bool startPowerHintSession(const std::vector<int32_t>& threadIds) override;
     void setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime);
-    void setValidateTiming(DisplayId displayId, nsecs_t valiateStartTime,
-                           nsecs_t validateEndTime) override;
-    void setPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
-                          nsecs_t presentEndTime) override;
+    void setHwcValidateTiming(DisplayId displayId, nsecs_t valiateStartTime,
+                              nsecs_t validateEndTime) override;
+    void setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
+                             nsecs_t presentEndTime) override;
     void setSkippedValidate(DisplayId displayId, bool skipped) override;
     void setRequiresClientComposition(DisplayId displayId, bool requiresClientComposition) override;
     void setExpectedPresentTime(nsecs_t expectedPresentTime) override;
-    void setPresentDelayedTime(
+    void setHwcPresentDelayedTime(
             DisplayId displayId,
             std::chrono::steady_clock::time_point earliestFrameStartTime) override;
 
@@ -166,17 +166,19 @@
 
     // Higher-level timing data used for estimation
     struct DisplayTimeline {
-        nsecs_t prePresentTime = -1;
-        nsecs_t postPresentTime = -1;
-        // Usually equals prePresentTime but can be delayed if we wait for the next valid vsync
-        nsecs_t presentStartTime = -1;
-        // When we think we started waiting for the fence after calling into present and
+        // The start of hwc present, or the start of validate if it happened there instead
+        nsecs_t hwcPresentStartTime = -1;
+        // The end of hwc present or validate, whichever one actually presented
+        nsecs_t hwcPresentEndTime = -1;
+        // How long the actual hwc present was delayed after hwcPresentStartTime
+        nsecs_t hwcPresentDelayDuration = 0;
+        // When we think we started waiting for the release fence after calling into hwc present and
         // after potentially waiting for the earliest present time
-        nsecs_t preFenceWaitTime = -1;
-        // How long we ran after we finished waiting for the fence but before present happened
-        nsecs_t postFenceDuration = 0;
+        nsecs_t releaseFenceWaitStartTime = -1;
+        // How long we ran after we finished waiting for the fence but before hwc present finished
+        nsecs_t postReleaseFenceHwcPresentDuration = 0;
         // Are we likely to have waited for the present fence during composition
-        bool probablyWaitsForFence = false;
+        bool probablyWaitsForReleaseFence = false;
         // Estimate one frame's timeline from that of a previous frame
         DisplayTimeline estimateTimelineFromReference(nsecs_t fenceTime, nsecs_t displayStartTime);
     };
@@ -192,11 +194,11 @@
         std::optional<nsecs_t> gpuStartTime;
         std::optional<nsecs_t> lastValidGpuEndTime;
         std::optional<nsecs_t> lastValidGpuStartTime;
-        std::optional<nsecs_t> presentStartTime;
-        std::optional<nsecs_t> presentEndTime;
-        std::optional<nsecs_t> validateStartTime;
-        std::optional<nsecs_t> validateEndTime;
-        std::optional<nsecs_t> presentDelayedTime;
+        std::optional<nsecs_t> hwcPresentStartTime;
+        std::optional<nsecs_t> hwcPresentEndTime;
+        std::optional<nsecs_t> hwcValidateStartTime;
+        std::optional<nsecs_t> hwcValidateEndTime;
+        std::optional<nsecs_t> hwcPresentDelayedTime;
         bool usedClientComposition = false;
         bool skippedValidate = false;
         // Calculate high-level timing milestones from more granular display timing data
@@ -258,13 +260,13 @@
 
     // An adjustable safety margin which moves the "target" earlier to allow flinger to
     // go a bit over without dropping a frame, especially since we can't measure
-    // the exact time HWC finishes composition so "actual" durations are measured
+    // the exact time hwc finishes composition so "actual" durations are measured
     // from the end of present() instead, which is a bit later.
     static constexpr const std::chrono::nanoseconds kTargetSafetyMargin = 1ms;
 
     // How long we expect hwc to run after the present call until it waits for the fence
-    static constexpr const std::chrono::nanoseconds kPrefenceDelayValidated = 150us;
-    static constexpr const std::chrono::nanoseconds kPrefenceDelaySkippedValidate = 250us;
+    static constexpr const std::chrono::nanoseconds kFenceWaitStartDelayValidated = 150us;
+    static constexpr const std::chrono::nanoseconds kFenceWaitStartDelaySkippedValidate = 250us;
 };
 
 class AidlPowerHalWrapper : public PowerAdvisor::HalWrapper {
diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
index b81b445..cf97643 100644
--- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
+++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
@@ -109,8 +109,8 @@
     return new ContainerLayer(args);
 }
 
-sp<BufferQueueLayer> DefaultFactory::createBufferQueueLayer(const LayerCreationArgs& args) {
-    return new BufferQueueLayer(args);
+sp<BufferQueueLayer> DefaultFactory::createBufferQueueLayer(const LayerCreationArgs&) {
+    return nullptr;
 }
 
 sp<BufferStateLayer> DefaultFactory::createBufferStateLayer(const LayerCreationArgs& args) {
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
index da60a69..1a91a69 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
@@ -319,7 +319,7 @@
     LayerCreationArgs args(flinger.flinger(), client,
                            mFdp.ConsumeRandomLengthString(kRandomStringLength) /*name*/,
                            mFdp.ConsumeIntegral<uint16_t>() /*layerFlags*/, LayerMetadata());
-    sp<Layer> layer = new BufferQueueLayer(args);
+    sp<Layer> layer = new BufferStateLayer(args);
 
     layer->setFrameRateSelectionPriority(mFdp.ConsumeIntegral<int16_t>());
 }
diff --git a/services/surfaceflinger/tests/unittests/CompositionTest.cpp b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
index bbfedc7..19eaa19 100644
--- a/services/surfaceflinger/tests/unittests/CompositionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
@@ -37,7 +37,6 @@
 #include <system/window.h>
 #include <utils/String8.h>
 
-#include "BufferQueueLayer.h"
 #include "ContainerLayer.h"
 #include "DisplayRenderArea.h"
 #include "EffectLayer.h"
@@ -492,65 +491,31 @@
     static constexpr IComposerClient::BlendMode BLENDMODE =
             IComposerClient::BlendMode::PREMULTIPLIED;
 
-    static void enqueueBuffer(CompositionTest*, sp<BufferQueueLayer> layer) {
-        auto producer = layer->getProducer();
-
-        IGraphicBufferProducer::QueueBufferOutput qbo;
-        status_t result = producer->connect(nullptr, NATIVE_WINDOW_API_EGL, false, &qbo);
-        if (result != NO_ERROR) {
-            ALOGE("Failed to connect() (%d)", result);
-            return;
-        }
-
-        int slot;
-        sp<Fence> fence;
-        result = producer->dequeueBuffer(&slot, &fence, LayerProperties::WIDTH,
-                                         LayerProperties::HEIGHT, LayerProperties::FORMAT,
-                                         LayerProperties::USAGE, nullptr, nullptr);
-        if (result != IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
-            ALOGE("Failed to dequeueBuffer() (%d)", result);
-            return;
-        }
-
-        sp<GraphicBuffer> buffer;
-        result = producer->requestBuffer(slot, &buffer);
-        if (result != NO_ERROR) {
-            ALOGE("Failed to requestBuffer() (%d)", result);
-            return;
-        }
-
-        IGraphicBufferProducer::QueueBufferInput qbi(systemTime(), false /* isAutoTimestamp */,
-                                                     LayerProperties::DATASPACE,
-                                                     Rect(LayerProperties::WIDTH,
-                                                          LayerProperties::HEIGHT),
-                                                     LayerProperties::SCALING_MODE,
-                                                     LayerProperties::TRANSFORM, Fence::NO_FENCE);
-        result = producer->queueBuffer(slot, qbi, &qbo);
-        if (result != NO_ERROR) {
-            ALOGE("Failed to queueBuffer (%d)", result);
-            return;
-        }
-    }
-
-    static void setupLatchedBuffer(CompositionTest* test, sp<BufferQueueLayer> layer) {
-        // TODO: Eliminate the complexity of actually creating a buffer
-        layer->setSizeForTest(LayerProperties::WIDTH, LayerProperties::HEIGHT);
-        status_t err =
-                layer->setDefaultBufferProperties(LayerProperties::WIDTH, LayerProperties::HEIGHT,
-                                                  LayerProperties::FORMAT);
-        ASSERT_EQ(NO_ERROR, err);
+    static void setupLatchedBuffer(CompositionTest* test, sp<BufferStateLayer> layer) {
         Mock::VerifyAndClear(test->mRenderEngine);
 
-        EXPECT_CALL(*test->mFlinger.scheduler(), scheduleFrame()).Times(1);
-        enqueueBuffer(test, layer);
-        Mock::VerifyAndClearExpectations(test->mFlinger.scheduler());
+        const auto buffer = std::make_shared<
+                renderengine::mock::FakeExternalTexture>(LayerProperties::WIDTH,
+                                                         LayerProperties::HEIGHT,
+                                                         DEFAULT_TEXTURE_ID,
+                                                         LayerProperties::FORMAT,
+                                                         LayerProperties::USAGE |
+                                                                 GraphicBuffer::USAGE_HW_TEXTURE);
+
+        auto& layerDrawingState = test->mFlinger.mutableLayerDrawingState(layer);
+        layerDrawingState.crop = Rect(0, 0, LayerProperties::HEIGHT, LayerProperties::WIDTH);
+        layerDrawingState.buffer = buffer;
+        layerDrawingState.acquireFence = Fence::NO_FENCE;
+        layerDrawingState.dataspace = ui::Dataspace::UNKNOWN;
+        layer->setSurfaceDamageRegion(
+                Region(Rect(LayerProperties::HEIGHT, LayerProperties::WIDTH)));
 
         bool ignoredRecomputeVisibleRegions;
         layer->latchBuffer(ignoredRecomputeVisibleRegions, 0, 0);
         Mock::VerifyAndClear(test->mRenderEngine);
     }
 
-    static void setupLayerState(CompositionTest* test, sp<BufferQueueLayer> layer) {
+    static void setupLayerState(CompositionTest* test, sp<BufferStateLayer> layer) {
         setupLatchedBuffer(test, layer);
     }
 
@@ -736,7 +701,7 @@
     using Base = BaseLayerProperties<SidebandLayerProperties>;
     static constexpr IComposerClient::BlendMode BLENDMODE = IComposerClient::BlendMode::NONE;
 
-    static void setupLayerState(CompositionTest* test, sp<BufferQueueLayer> layer) {
+    static void setupLayerState(CompositionTest* test, sp<BufferStateLayer> layer) {
         sp<NativeHandle> stream =
                 NativeHandle::create(reinterpret_cast<native_handle_t*>(DEFAULT_SIDEBAND_STREAM),
                                      false);
@@ -818,14 +783,14 @@
 struct CursorLayerProperties : public BaseLayerProperties<CursorLayerProperties> {
     using Base = BaseLayerProperties<CursorLayerProperties>;
 
-    static void setupLayerState(CompositionTest* test, sp<BufferQueueLayer> layer) {
+    static void setupLayerState(CompositionTest* test, sp<BufferStateLayer> layer) {
         Base::setupLayerState(test, layer);
         test->mFlinger.setLayerPotentialCursor(layer, true);
     }
 };
 
 struct NoLayerVariant {
-    using FlingerLayerType = sp<BufferQueueLayer>;
+    using FlingerLayerType = sp<BufferStateLayer>;
 
     static FlingerLayerType createLayer(CompositionTest*) { return FlingerLayerType(); }
     static void injectLayer(CompositionTest*, FlingerLayerType) {}
@@ -932,17 +897,17 @@
 template <typename LayerProperties>
 struct BufferLayerVariant : public BaseLayerVariant<LayerProperties> {
     using Base = BaseLayerVariant<LayerProperties>;
-    using FlingerLayerType = sp<BufferQueueLayer>;
+    using FlingerLayerType = sp<BufferStateLayer>;
 
     static FlingerLayerType createLayer(CompositionTest* test) {
         test->mFlinger.mutableTexturePool().push_back(DEFAULT_TEXTURE_ID);
 
         FlingerLayerType layer =
-                Base::template createLayerWithFactory<BufferQueueLayer>(test, [test]() {
+                Base::template createLayerWithFactory<BufferStateLayer>(test, [test]() {
                     LayerCreationArgs args(test->mFlinger.flinger(), sp<Client>(), "test-layer",
                                            LayerProperties::LAYER_FLAGS, LayerMetadata());
                     args.textureName = test->mFlinger.mutableTexturePool().back();
-                    return new BufferQueueLayer(args);
+                    return new BufferStateLayer(args);
                 });
 
         LayerProperties::setupLayerState(test, layer);
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h
index 05cc544..e347883 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h
@@ -43,17 +43,17 @@
     MOCK_METHOD(bool, startPowerHintSession, (const std::vector<int32_t>& threadIds), (override));
     MOCK_METHOD(void, setGpuFenceTime,
                 (DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime), (override));
-    MOCK_METHOD(void, setValidateTiming,
+    MOCK_METHOD(void, setHwcValidateTiming,
                 (DisplayId displayId, nsecs_t valiateStartTime, nsecs_t validateEndTime),
                 (override));
-    MOCK_METHOD(void, setPresentTiming,
+    MOCK_METHOD(void, setHwcPresentTiming,
                 (DisplayId displayId, nsecs_t presentStartTime, nsecs_t presentEndTime),
                 (override));
     MOCK_METHOD(void, setSkippedValidate, (DisplayId displayId, bool skipped), (override));
     MOCK_METHOD(void, setRequiresClientComposition,
                 (DisplayId displayId, bool requiresClientComposition), (override));
     MOCK_METHOD(void, setExpectedPresentTime, (nsecs_t expectedPresentTime), (override));
-    MOCK_METHOD(void, setPresentDelayedTime,
+    MOCK_METHOD(void, setHwcPresentDelayedTime,
                 (DisplayId displayId,
                  std::chrono::steady_clock::time_point earliestFrameStartTime));
     MOCK_METHOD(void, setFrameDelay, (nsecs_t frameDelayDuration), (override));