Avoid excessive KGSL maps

Hook MIN_UNDEQUEUED_BUFFERS if possible to avoid thrashing kgsl
maps when render_ahead is being used

Bug: 143555869
Test: verified kgsl maps only happened once per buffer
Change-Id: I985fae0a9a7635be3a1cf6177186e5541a1169df
diff --git a/libs/hwui/renderthread/ReliableSurface.cpp b/libs/hwui/renderthread/ReliableSurface.cpp
index 8a0b4e8..dcf1fc1 100644
--- a/libs/hwui/renderthread/ReliableSurface.cpp
+++ b/libs/hwui/renderthread/ReliableSurface.cpp
@@ -19,6 +19,7 @@
 #include <log/log_main.h>
 #include <private/android/AHardwareBufferHelpers.h>
 // TODO: this should be including apex instead.
+#include <system/window.h>
 #include <vndk/window.h>
 
 namespace android::uirenderer::renderthread {
@@ -44,6 +45,7 @@
     ANativeWindow_setDequeueBufferInterceptor(mWindow, nullptr, nullptr);
     ANativeWindow_setQueueBufferInterceptor(mWindow, nullptr, nullptr);
     ANativeWindow_setPerformInterceptor(mWindow, nullptr, nullptr);
+    ANativeWindow_setQueryInterceptor(mWindow, nullptr, nullptr);
     ANativeWindow_release(mWindow);
 }
 
@@ -63,6 +65,10 @@
     result = ANativeWindow_setPerformInterceptor(mWindow, hook_perform, this);
     LOG_ALWAYS_FATAL_IF(result != NO_ERROR, "Failed to set perform interceptor: error = %d",
                         result);
+
+    result = ANativeWindow_setQueryInterceptor(mWindow, hook_query, this);
+    LOG_ALWAYS_FATAL_IF(result != NO_ERROR, "Failed to set query interceptor: error = %d",
+                        result);
 }
 
 int ReliableSurface::reserveNext() {
@@ -249,9 +255,29 @@
             case ANATIVEWINDOW_PERFORM_SET_BUFFERS_FORMAT:
                 rs->mFormat = static_cast<AHardwareBuffer_Format>(va_arg(args, int32_t));
                 break;
+            case NATIVE_WINDOW_SET_BUFFER_COUNT:
+                size_t bufferCount = va_arg(args, size_t);
+                if (bufferCount >= rs->mExpectedBufferCount) {
+                    rs->mDidSetExtraBuffers = true;
+                } else {
+                    ALOGD("HOOK FAILED! Expected %zd got = %zd", rs->mExpectedBufferCount, bufferCount);
+                }
+                break;
         }
     }
     return result;
 }
 
+int ReliableSurface::hook_query(const ANativeWindow *window, ANativeWindow_queryFn query,
+        void *data, int what, int *value) {
+    ReliableSurface* rs = reinterpret_cast<ReliableSurface*>(data);
+    int result = query(window, what, value);
+    if (what == ANATIVEWINDOW_QUERY_MIN_UNDEQUEUED_BUFFERS && result == OK) {
+        std::lock_guard _lock{rs->mMutex};
+        *value += rs->mExtraBuffers;
+        rs->mExpectedBufferCount = *value + 2;
+    }
+    return result;
+}
+
 };  // namespace android::uirenderer::renderthread