Merge remote-tracking branch 'gitlab/main' into HEAD am: 84fa73c0d4 am: 82288efb3a

Original change: https://android-review.googlesource.com/c/platform/external/drm_hwcomposer/+/1714669

Change-Id: If18723bda10941e12869cd0d586bfc7f6acaa69a
diff --git a/.ci/.common.sh b/.ci/.common.sh
new file mode 100644
index 0000000..93f7f95
--- /dev/null
+++ b/.ci/.common.sh
@@ -0,0 +1,42 @@
+INCLUDE_DIRS="-I. -I../libdrm/include/drm -Iinclude -I/usr/include/libdrm -I./.ci/android_headers -I./tests/test_include"
+
+CLANG="clang++-11"
+CLANG_TIDY="clang-tidy-11"
+
+CXXARGS="-fPIC -Wall -Werror -DPLATFORM_SDK_VERSION=30 -D__ANDROID_API__=30 -Wsign-promo -Wimplicit-fallthrough"
+CXXARGS+=" -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS -Wno-gnu-include-next "
+CXXARGS+=" -fvisibility-inlines-hidden -std=gnu++17 -DHWC2_USE_CPP11 -DHWC2_INCLUDE_STRINGIFICATION -fexceptions -fno-rtti"
+
+BUILD_FILES=(
+backend/BackendClient.cpp
+backend/Backend.cpp
+backend/BackendManager.cpp
+backend/BackendRCarDu.cpp
+bufferinfo/BufferInfoGetter.cpp
+#bufferinfo/BufferInfoMapperMetadata.cpp
+bufferinfo/legacy/BufferInfoImagination.cpp
+bufferinfo/legacy/BufferInfoLibdrm.cpp
+bufferinfo/legacy/BufferInfoMaliHisi.cpp
+bufferinfo/legacy/BufferInfoMaliMediatek.cpp
+bufferinfo/legacy/BufferInfoMaliMeson.cpp
+bufferinfo/legacy/BufferInfoMinigbm.cpp
+compositor/DrmDisplayComposition.cpp
+compositor/DrmDisplayCompositor.cpp
+compositor/Planner.cpp
+drm/DrmConnector.cpp
+drm/DrmCrtc.cpp
+drm/DrmDevice.cpp
+drm/DrmEncoder.cpp
+drm/DrmEventListener.cpp
+drm/DrmGenericImporter.cpp
+drm/DrmMode.cpp
+drm/DrmPlane.cpp
+drm/DrmProperty.cpp
+DrmHwcTwo.cpp
+drm/ResourceManager.cpp
+drm/VSyncWorker.cpp
+tests/worker_test.cpp
+utils/autolock.cpp
+#utils/hwcutils.cpp
+utils/Worker.cpp
+)
diff --git a/.gitlab-ci-checkcommit.sh b/.ci/.gitlab-ci-checkcommit.sh
similarity index 81%
rename from .gitlab-ci-checkcommit.sh
rename to .ci/.gitlab-ci-checkcommit.sh
index c1c524d..817afa7 100755
--- a/.gitlab-ci-checkcommit.sh
+++ b/.ci/.gitlab-ci-checkcommit.sh
@@ -50,9 +50,15 @@
 		exit 1
 	fi
 
-	git show "$h" -- | clang-format-diff-5.0 -p 1 -style=file > format-fixup.patch
-	if [ -s  format-fixup.patch ]; then
-		cat format-fixup.patch >&2
+	git show "$h" -- | clang-format-diff-11 -p 1 -style=file > /tmp/format-fixup.patch
+	if [ -s  /tmp/format-fixup.patch ]; then
+		cat /tmp/format-fixup.patch >&2
+		exit 1
+	fi
+
+	find -name "*.bp" -exec bpfmt -d -s {} \; > /tmp/bpfmt.patch
+	if [ -s  /tmp/bpfmt.patch ]; then
+		cat /tmp/bpfmt.patch >&2
 		exit 1
 	fi
 done
diff --git a/.ci/.gitlab-ci-clang-build.sh b/.ci/.gitlab-ci-clang-build.sh
new file mode 100755
index 0000000..1070365
--- /dev/null
+++ b/.ci/.gitlab-ci-clang-build.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+. ./.ci/.common.sh
+
+set -xe
+
+for source in "${BUILD_FILES[@]}"
+do
+    filename=$(basename -- "$source")
+    $CLANG $source $INCLUDE_DIRS $CXXARGS -c -o /tmp/"${filename%.*}.o"
+done
diff --git a/.ci/.gitlab-ci-clang-tidy-coarse.sh b/.ci/.gitlab-ci-clang-tidy-coarse.sh
new file mode 100755
index 0000000..de0c024
--- /dev/null
+++ b/.ci/.gitlab-ci-clang-tidy-coarse.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+. ./.ci/.common.sh
+
+TIDY_COARSE_CHECKS="-*,android-*,bugprone-*,cert-*,clang-analyzer-*,"
+TIDY_COARSE_CHECKS+="cppcoreguidelines-*,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-pro-bounds-array-to-pointer-decay,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-pro-bounds-constant-array-index,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-pro-bounds-pointer-arithmetic,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-pro-type-cstyle-cast,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-pro-type-union-access,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-pro-type-vararg,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-avoid-magic-numbers,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-macro-usage,"
+TIDY_COARSE_CHECKS+="-cppcoreguidelines-avoid-c-arrays,"
+TIDY_COARSE_CHECKS+="google-*,"
+TIDY_COARSE_CHECKS+="-google-readability-braces-around-statements,"
+TIDY_COARSE_CHECKS+="-google-readability-casting,"
+TIDY_COARSE_CHECKS+="misc-*,"
+TIDY_COARSE_CHECKS+="modernize-*,"
+TIDY_COARSE_CHECKS+="-modernize-avoid-c-arrays,"
+TIDY_COARSE_CHECKS+="-modernize-use-trailing-return-type,"
+TIDY_COARSE_CHECKS+="performance-*,"
+TIDY_COARSE_CHECKS+="portability-*,"
+TIDY_COARSE_CHECKS+="readability-*,"
+TIDY_COARSE_CHECKS+="-readability-braces-around-statements,"
+TIDY_COARSE_CHECKS+="-readability-convert-member-functions-to-static,"
+TIDY_COARSE_CHECKS+="-readability-implicit-bool-conversion,"
+TIDY_COARSE_CHECKS+="-readability-magic-numbers,"
+TIDY_COARSE_CHECKS+="-readability-use-anyofallof"
+
+TIDY_FILES=( "${BUILD_FILES[@]}" )
+
+set -xe
+
+for source in "${TIDY_FILES[@]}"
+do
+    $CLANG_TIDY $source --checks=$TIDY_COARSE_CHECKS -- -x c++ $INCLUDE_DIRS $CXXARGS
+done
diff --git a/.ci/.gitlab-ci-clang-tidy-fine.sh b/.ci/.gitlab-ci-clang-tidy-fine.sh
new file mode 100755
index 0000000..644f621
--- /dev/null
+++ b/.ci/.gitlab-ci-clang-tidy-fine.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+. ./.ci/.common.sh
+
+TIDY_FILES=(
+utils/log.h
+utils/properties.h
+)
+
+set -xe
+
+for source in "${TIDY_FILES[@]}"
+do
+    $CLANG_TIDY $source -- -x c++ $INCLUDE_DIRS $CXXARGS
+done
diff --git a/.ci/android_headers/cutils/compiler.h b/.ci/android_headers/cutils/compiler.h
new file mode 100644
index 0000000..5754666
--- /dev/null
+++ b/.ci/android_headers/cutils/compiler.h
@@ -0,0 +1,45 @@
+// clang-format off
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef ANDROID_CUTILS_COMPILER_H
+#define ANDROID_CUTILS_COMPILER_H
+
+/*
+ * helps the compiler's optimizer predicting branches
+ */
+
+#ifdef __cplusplus
+#   define CC_LIKELY( exp )    (__builtin_expect( !!(exp), true ))
+#   define CC_UNLIKELY( exp )  (__builtin_expect( !!(exp), false ))
+#else
+#   define CC_LIKELY( exp )    (__builtin_expect( !!(exp), 1 ))
+#   define CC_UNLIKELY( exp )  (__builtin_expect( !!(exp), 0 ))
+#endif
+
+/**
+ * exports marked symbols
+ *
+ * if used on a C++ class declaration, this macro must be inserted
+ * after the "class" keyword. For instance:
+ *
+ * template <typename TYPE>
+ * class ANDROID_API Singleton { }
+ */
+
+#define ANDROID_API __attribute__((visibility("default")))
+
+#endif // ANDROID_CUTILS_COMPILER_H
diff --git a/.ci/android_headers/cutils/native_handle.h b/.ci/android_headers/cutils/native_handle.h
new file mode 100644
index 0000000..4f500f6
--- /dev/null
+++ b/.ci/android_headers/cutils/native_handle.h
@@ -0,0 +1,107 @@
+// clang-format off
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef NATIVE_HANDLE_H_
+#define NATIVE_HANDLE_H_
+
+#include <stdalign.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define NATIVE_HANDLE_MAX_FDS 1024
+#define NATIVE_HANDLE_MAX_INTS 1024
+
+/* Declare a char array for use with native_handle_init */
+#define NATIVE_HANDLE_DECLARE_STORAGE(name, maxFds, maxInts) \
+    alignas(native_handle_t) char (name)[                            \
+      sizeof(native_handle_t) + sizeof(int) * ((maxFds) + (maxInts))]
+
+typedef struct native_handle
+{
+    int version;        /* sizeof(native_handle_t) */
+    int numFds;         /* number of file-descriptors at &data[0] */
+    int numInts;        /* number of ints at &data[numFds] */
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wzero-length-array"
+#endif
+    int data[0];        /* numFds + numInts ints */
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+} native_handle_t;
+
+typedef const native_handle_t* buffer_handle_t;
+
+/*
+ * native_handle_close
+ * 
+ * closes the file descriptors contained in this native_handle_t
+ * 
+ * return 0 on success, or a negative error code on failure
+ * 
+ */
+int native_handle_close(const native_handle_t* h);
+
+/*
+ * native_handle_init
+ *
+ * Initializes a native_handle_t from storage.  storage must be declared with
+ * NATIVE_HANDLE_DECLARE_STORAGE.  numFds and numInts must not respectively
+ * exceed maxFds and maxInts used to declare the storage.
+ */
+native_handle_t* native_handle_init(char* storage, int numFds, int numInts);
+
+/*
+ * native_handle_create
+ *
+ * creates a native_handle_t and initializes it. must be destroyed with
+ * native_handle_delete(). Note that numFds must be <= NATIVE_HANDLE_MAX_FDS,
+ * numInts must be <= NATIVE_HANDLE_MAX_INTS, and both must be >= 0.
+ *
+ */
+native_handle_t* native_handle_create(int numFds, int numInts);
+
+/*
+ * native_handle_clone
+ *
+ * creates a native_handle_t and initializes it from another native_handle_t.
+ * Must be destroyed with native_handle_delete().
+ *
+ */
+native_handle_t* native_handle_clone(const native_handle_t* handle);
+
+/*
+ * native_handle_delete
+ * 
+ * frees a native_handle_t allocated with native_handle_create().
+ * This ONLY frees the memory allocated for the native_handle_t, but doesn't
+ * close the file descriptors; which can be achieved with native_handle_close().
+ * 
+ * return 0 on success, or a negative error code on failure
+ * 
+ */
+int native_handle_delete(native_handle_t* h);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* NATIVE_HANDLE_H_ */
diff --git a/.ci/android_headers/cutils/trace.h b/.ci/android_headers/cutils/trace.h
new file mode 100644
index 0000000..54265a7
--- /dev/null
+++ b/.ci/android_headers/cutils/trace.h
@@ -0,0 +1,247 @@
+// clang-format off
+/*
+ * Copyright (C) 2012 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.
+ */
+
+#ifndef _LIBS_CUTILS_TRACE_H
+#define _LIBS_CUTILS_TRACE_H
+
+#include <inttypes.h>
+#include <stdatomic.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <cutils/compiler.h>
+
+__BEGIN_DECLS
+
+/**
+ * The ATRACE_TAG macro can be defined before including this header to trace
+ * using one of the tags defined below.  It must be defined to one of the
+ * following ATRACE_TAG_* macros.  The trace tag is used to filter tracing in
+ * userland to avoid some of the runtime cost of tracing when it is not desired.
+ *
+ * Defining ATRACE_TAG to be ATRACE_TAG_ALWAYS will result in the tracing always
+ * being enabled - this should ONLY be done for debug code, as userland tracing
+ * has a performance cost even when the trace is not being recorded.  Defining
+ * ATRACE_TAG to be ATRACE_TAG_NEVER or leaving ATRACE_TAG undefined will result
+ * in the tracing always being disabled.
+ *
+ * ATRACE_TAG_HAL should be bitwise ORed with the relevant tags for tracing
+ * within a hardware module.  For example a camera hardware module would set:
+ * #define ATRACE_TAG  (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
+ *
+ * Keep these in sync with frameworks/base/core/java/android/os/Trace.java.
+ */
+#define ATRACE_TAG_NEVER            0       // This tag is never enabled.
+#define ATRACE_TAG_ALWAYS           (1<<0)  // This tag is always enabled.
+#define ATRACE_TAG_GRAPHICS         (1<<1)
+#define ATRACE_TAG_INPUT            (1<<2)
+#define ATRACE_TAG_VIEW             (1<<3)
+#define ATRACE_TAG_WEBVIEW          (1<<4)
+#define ATRACE_TAG_WINDOW_MANAGER   (1<<5)
+#define ATRACE_TAG_ACTIVITY_MANAGER (1<<6)
+#define ATRACE_TAG_SYNC_MANAGER     (1<<7)
+#define ATRACE_TAG_AUDIO            (1<<8)
+#define ATRACE_TAG_VIDEO            (1<<9)
+#define ATRACE_TAG_CAMERA           (1<<10)
+#define ATRACE_TAG_HAL              (1<<11)
+#define ATRACE_TAG_APP              (1<<12)
+#define ATRACE_TAG_RESOURCES        (1<<13)
+#define ATRACE_TAG_DALVIK           (1<<14)
+#define ATRACE_TAG_RS               (1<<15)
+#define ATRACE_TAG_BIONIC           (1<<16)
+#define ATRACE_TAG_POWER            (1<<17)
+#define ATRACE_TAG_PACKAGE_MANAGER  (1<<18)
+#define ATRACE_TAG_SYSTEM_SERVER    (1<<19)
+#define ATRACE_TAG_DATABASE         (1<<20)
+#define ATRACE_TAG_NETWORK          (1<<21)
+#define ATRACE_TAG_ADB              (1<<22)
+#define ATRACE_TAG_VIBRATOR         (1<<23)
+#define ATRACE_TAG_AIDL             (1<<24)
+#define ATRACE_TAG_NNAPI            (1<<25)
+#define ATRACE_TAG_RRO              (1<<26)
+#define ATRACE_TAG_LAST             ATRACE_TAG_RRO
+
+// Reserved for initialization.
+#define ATRACE_TAG_NOT_READY        (1ULL<<63)
+
+#define ATRACE_TAG_VALID_MASK ((ATRACE_TAG_LAST - 1) | ATRACE_TAG_LAST)
+
+#ifndef ATRACE_TAG
+#define ATRACE_TAG ATRACE_TAG_NEVER
+#elif ATRACE_TAG > ATRACE_TAG_VALID_MASK
+#error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h
+#endif
+
+/**
+ * Opens the trace file for writing and reads the property for initial tags.
+ * The atrace.tags.enableflags property sets the tags to trace.
+ * This function should not be explicitly called, the first call to any normal
+ * trace function will cause it to be run safely.
+ */
+void atrace_setup();
+
+/**
+ * If tracing is ready, set atrace_enabled_tags to the system property
+ * debug.atrace.tags.enableflags. Can be used as a sysprop change callback.
+ */
+void atrace_update_tags();
+
+/**
+ * Set whether the process is debuggable.  By default the process is not
+ * considered debuggable.  If the process is not debuggable then application-
+ * level tracing is not allowed unless the ro.debuggable system property is
+ * set to '1'.
+ */
+void atrace_set_debuggable(bool debuggable);
+
+/**
+ * Set whether tracing is enabled for the current process.  This is used to
+ * prevent tracing within the Zygote process.
+ */
+void atrace_set_tracing_enabled(bool enabled);
+
+/**
+ * This is always set to false. This forces code that uses an old version
+ * of this header to always call into atrace_setup, in which we call
+ * atrace_init unconditionally.
+ */
+extern atomic_bool atrace_is_ready;
+
+/**
+ * Set of ATRACE_TAG flags to trace for, initialized to ATRACE_TAG_NOT_READY.
+ * A value of zero indicates setup has failed.
+ * Any other nonzero value indicates setup has succeeded, and tracing is on.
+ */
+extern uint64_t atrace_enabled_tags;
+
+/**
+ * Handle to the kernel's trace buffer, initialized to -1.
+ * Any other value indicates setup has succeeded, and is a valid fd for tracing.
+ */
+extern int atrace_marker_fd;
+
+/**
+ * atrace_init readies the process for tracing by opening the trace_marker file.
+ * Calling any trace function causes this to be run, so calling it is optional.
+ * This can be explicitly run to avoid setup delay on first trace function.
+ */
+#define ATRACE_INIT() atrace_init()
+#define ATRACE_GET_ENABLED_TAGS() atrace_get_enabled_tags()
+
+void atrace_init();
+uint64_t atrace_get_enabled_tags();
+
+/**
+ * Test if a given tag is currently enabled.
+ * Returns nonzero if the tag is enabled, otherwise zero.
+ * It can be used as a guard condition around more expensive trace calculations.
+ */
+#define ATRACE_ENABLED() atrace_is_tag_enabled(ATRACE_TAG)
+static inline uint64_t atrace_is_tag_enabled(uint64_t tag)
+{
+    return atrace_get_enabled_tags() & tag;
+}
+
+/**
+ * Trace the beginning of a context.  name is used to identify the context.
+ * This is often used to time function execution.
+ */
+#define ATRACE_BEGIN(name) atrace_begin(ATRACE_TAG, name)
+static inline void atrace_begin(uint64_t tag, const char* name)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_begin_body(const char*);
+        atrace_begin_body(name);
+    }
+}
+
+/**
+ * Trace the end of a context.
+ * This should match up (and occur after) a corresponding ATRACE_BEGIN.
+ */
+#define ATRACE_END() atrace_end(ATRACE_TAG)
+static inline void atrace_end(uint64_t tag)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_end_body();
+        atrace_end_body();
+    }
+}
+
+/**
+ * Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END
+ * contexts, asynchronous events do not need to be nested. The name describes
+ * the event, and the cookie provides a unique identifier for distinguishing
+ * simultaneous events. The name and cookie used to begin an event must be
+ * used to end it.
+ */
+#define ATRACE_ASYNC_BEGIN(name, cookie) \
+    atrace_async_begin(ATRACE_TAG, name, cookie)
+static inline void atrace_async_begin(uint64_t tag, const char* name,
+        int32_t cookie)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_async_begin_body(const char*, int32_t);
+        atrace_async_begin_body(name, cookie);
+    }
+}
+
+/**
+ * Trace the end of an asynchronous event.
+ * This should have a corresponding ATRACE_ASYNC_BEGIN.
+ */
+#define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie)
+static inline void atrace_async_end(uint64_t tag, const char* name, int32_t cookie)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_async_end_body(const char*, int32_t);
+        atrace_async_end_body(name, cookie);
+    }
+}
+
+/**
+ * Traces an integer counter value.  name is used to identify the counter.
+ * This can be used to track how a value changes over time.
+ */
+#define ATRACE_INT(name, value) atrace_int(ATRACE_TAG, name, value)
+static inline void atrace_int(uint64_t tag, const char* name, int32_t value)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_int_body(const char*, int32_t);
+        atrace_int_body(name, value);
+    }
+}
+
+/**
+ * Traces a 64-bit integer counter value.  name is used to identify the
+ * counter. This can be used to track how a value changes over time.
+ */
+#define ATRACE_INT64(name, value) atrace_int64(ATRACE_TAG, name, value)
+static inline void atrace_int64(uint64_t tag, const char* name, int64_t value)
+{
+    if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
+        void atrace_int64_body(const char*, int64_t);
+        atrace_int64_body(name, value);
+    }
+}
+
+__END_DECLS
+
+#endif // _LIBS_CUTILS_TRACE_H
diff --git a/.ci/android_headers/gralloc_handle.h b/.ci/android_headers/gralloc_handle.h
new file mode 100644
index 0000000..4a7c9dd
--- /dev/null
+++ b/.ci/android_headers/gralloc_handle.h
@@ -0,0 +1,112 @@
+// clang-format off
+/*
+ * Copyright (C) 2010-2011 Chia-I Wu <olvaffe@gmail.com>
+ * Copyright (C) 2010-2011 LunarG Inc.
+ * Copyright (C) 2016 Linaro, Ltd., Rob Herring <robh@kernel.org>
+ * Copyright (C) 2018 Collabora, Robert Foss <robert.foss@collabora.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ANDROID_GRALLOC_HANDLE_H__
+#define __ANDROID_GRALLOC_HANDLE_H__
+
+#include <cutils/native_handle.h>
+#include <stdint.h>
+
+/* support users of drm_gralloc/gbm_gralloc */
+#define gralloc_gbm_handle_t gralloc_handle_t
+#define gralloc_drm_handle_t gralloc_handle_t
+
+struct gralloc_handle_t {
+	native_handle_t base;
+
+	/* dma-buf file descriptor
+	 * Must be located first since, native_handle_t is allocated
+	 * using native_handle_create(), which allocates space for
+	 * sizeof(native_handle_t) + sizeof(int) * (numFds + numInts)
+	 * numFds = GRALLOC_HANDLE_NUM_FDS
+	 * numInts = GRALLOC_HANDLE_NUM_INTS
+	 * Where numFds represents the number of FDs and
+	 * numInts represents the space needed for the
+	 * remainder of this struct.
+	 * And the FDs are expected to be found first following
+	 * native_handle_t.
+	 */
+	int prime_fd;
+
+	/* api variables */
+	uint32_t magic; /* differentiate between allocator impls */
+	uint32_t version; /* api version */
+
+	uint32_t width; /* width of buffer in pixels */
+	uint32_t height; /* height of buffer in pixels */
+	uint32_t format; /* pixel format (Android) */
+	uint32_t usage; /* android libhardware usage flags */
+
+	uint32_t stride; /* the stride in bytes */
+	int data_owner; /* owner of data (for validation) */
+	uint64_t modifier __attribute__((aligned(8))); /* buffer modifiers */
+
+	union {
+		void *data; /* pointer to struct gralloc_gbm_bo_t */
+		uint64_t reserved;
+	} __attribute__((aligned(8)));
+};
+
+#define GRALLOC_HANDLE_VERSION 4
+#define GRALLOC_HANDLE_MAGIC 0x60585350
+#define GRALLOC_HANDLE_NUM_FDS 1
+#define GRALLOC_HANDLE_NUM_INTS (	\
+	((sizeof(struct gralloc_handle_t) - sizeof(native_handle_t))/sizeof(int))	\
+	 - GRALLOC_HANDLE_NUM_FDS)
+
+static inline struct gralloc_handle_t *gralloc_handle(buffer_handle_t handle)
+{
+	return (struct gralloc_handle_t *)handle;
+}
+
+/**
+ * Create a buffer handle.
+ */
+static inline native_handle_t *gralloc_handle_create(int32_t width,
+                                                     int32_t height,
+                                                     int32_t hal_format,
+                                                     int32_t usage)
+{
+	struct gralloc_handle_t *handle;
+	native_handle_t *nhandle = native_handle_create(GRALLOC_HANDLE_NUM_FDS,
+							GRALLOC_HANDLE_NUM_INTS);
+
+	if (!nhandle)
+		return NULL;
+
+	handle = gralloc_handle(nhandle);
+	handle->magic = GRALLOC_HANDLE_MAGIC;
+	handle->version = GRALLOC_HANDLE_VERSION;
+	handle->width = width;
+	handle->height = height;
+	handle->format = hal_format;
+	handle->usage = usage;
+	handle->prime_fd = -1;
+
+	return nhandle;
+}
+
+#endif
diff --git a/.ci/android_headers/hardware/gralloc.h b/.ci/android_headers/hardware/gralloc.h
new file mode 100644
index 0000000..260140e
--- /dev/null
+++ b/.ci/android_headers/hardware/gralloc.h
@@ -0,0 +1,451 @@
+// clang-format off
+/*
+ * Copyright (C) 2008 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.
+ */
+
+
+#ifndef ANDROID_GRALLOC_INTERFACE_H
+#define ANDROID_GRALLOC_INTERFACE_H
+
+#include <system/graphics.h>
+#include <hardware/hardware.h>
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <cutils/native_handle.h>
+
+#include <hardware/hardware.h>
+#if 0 /* Header below is not used by drm_hwcomposer */
+#include <hardware/fb.h>
+#endif
+
+__BEGIN_DECLS
+
+/**
+ * Module versioning information for the Gralloc hardware module, based on
+ * gralloc_module_t.common.module_api_version.
+ *
+ * Version History:
+ *
+ * GRALLOC_MODULE_API_VERSION_0_1:
+ * Initial Gralloc hardware module API.
+ *
+ * GRALLOC_MODULE_API_VERSION_0_2:
+ * Add support for flexible YCbCr format with (*lock_ycbcr)() method.
+ *
+ * GRALLOC_MODULE_API_VERSION_0_3:
+ * Add support for fence passing to/from lock/unlock.
+ */
+
+#define GRALLOC_MODULE_API_VERSION_0_1  HARDWARE_MODULE_API_VERSION(0, 1)
+#define GRALLOC_MODULE_API_VERSION_0_2  HARDWARE_MODULE_API_VERSION(0, 2)
+#define GRALLOC_MODULE_API_VERSION_0_3  HARDWARE_MODULE_API_VERSION(0, 3)
+
+#define GRALLOC_DEVICE_API_VERSION_0_1  HARDWARE_DEVICE_API_VERSION(0, 1)
+
+/**
+ * The id of this module
+ */
+#define GRALLOC_HARDWARE_MODULE_ID "gralloc"
+
+/**
+ * Name of the graphics device to open
+ */
+
+#define GRALLOC_HARDWARE_GPU0 "gpu0"
+
+enum {
+    /* buffer is never read in software */
+    GRALLOC_USAGE_SW_READ_NEVER         = 0x00000000U,
+    /* buffer is rarely read in software */
+    GRALLOC_USAGE_SW_READ_RARELY        = 0x00000002U,
+    /* buffer is often read in software */
+    GRALLOC_USAGE_SW_READ_OFTEN         = 0x00000003U,
+    /* mask for the software read values */
+    GRALLOC_USAGE_SW_READ_MASK          = 0x0000000FU,
+
+    /* buffer is never written in software */
+    GRALLOC_USAGE_SW_WRITE_NEVER        = 0x00000000U,
+    /* buffer is rarely written in software */
+    GRALLOC_USAGE_SW_WRITE_RARELY       = 0x00000020U,
+    /* buffer is often written in software */
+    GRALLOC_USAGE_SW_WRITE_OFTEN        = 0x00000030U,
+    /* mask for the software write values */
+    GRALLOC_USAGE_SW_WRITE_MASK         = 0x000000F0U,
+
+    /* buffer will be used as an OpenGL ES texture */
+    GRALLOC_USAGE_HW_TEXTURE            = 0x00000100U,
+    /* buffer will be used as an OpenGL ES render target */
+    GRALLOC_USAGE_HW_RENDER             = 0x00000200U,
+    /* buffer will be used by the 2D hardware blitter */
+    GRALLOC_USAGE_HW_2D                 = 0x00000400U,
+    /* buffer will be used by the HWComposer HAL module */
+    GRALLOC_USAGE_HW_COMPOSER           = 0x00000800U,
+    /* buffer will be used with the framebuffer device */
+    GRALLOC_USAGE_HW_FB                 = 0x00001000U,
+
+    /* buffer should be displayed full-screen on an external display when
+     * possible */
+    GRALLOC_USAGE_EXTERNAL_DISP         = 0x00002000U,
+
+    /* Must have a hardware-protected path to external display sink for
+     * this buffer.  If a hardware-protected path is not available, then
+     * either don't composite only this buffer (preferred) to the
+     * external sink, or (less desirable) do not route the entire
+     * composition to the external sink.  */
+    GRALLOC_USAGE_PROTECTED             = 0x00004000U,
+
+    /* buffer may be used as a cursor */
+    GRALLOC_USAGE_CURSOR                = 0x00008000U,
+
+    /* buffer will be used with the HW video encoder */
+    GRALLOC_USAGE_HW_VIDEO_ENCODER      = 0x00010000U,
+    /* buffer will be written by the HW camera pipeline */
+    GRALLOC_USAGE_HW_CAMERA_WRITE       = 0x00020000U,
+    /* buffer will be read by the HW camera pipeline */
+    GRALLOC_USAGE_HW_CAMERA_READ        = 0x00040000U,
+    /* buffer will be used as part of zero-shutter-lag queue */
+    GRALLOC_USAGE_HW_CAMERA_ZSL         = 0x00060000U,
+    /* mask for the camera access values */
+    GRALLOC_USAGE_HW_CAMERA_MASK        = 0x00060000U,
+    /* mask for the software usage bit-mask */
+    GRALLOC_USAGE_HW_MASK               = 0x00071F00U,
+
+    /* buffer will be used as a RenderScript Allocation */
+    GRALLOC_USAGE_RENDERSCRIPT          = 0x00100000U,
+
+    /* Set by the consumer to indicate to the producer that they may attach a
+     * buffer that they did not detach from the BufferQueue. Will be filtered
+     * out by GRALLOC_USAGE_ALLOC_MASK, so gralloc modules will not need to
+     * handle this flag. */
+    GRALLOC_USAGE_FOREIGN_BUFFERS       = 0x00200000U,
+
+    /* buffer will be used as input to HW HEIC image encoder */
+    GRALLOC_USAGE_HW_IMAGE_ENCODER      = 0x08000000U,
+
+    /* Mask of all flags which could be passed to a gralloc module for buffer
+     * allocation. Any flags not in this mask do not need to be handled by
+     * gralloc modules. */
+    GRALLOC_USAGE_ALLOC_MASK            = ~(GRALLOC_USAGE_FOREIGN_BUFFERS),
+
+    /* implementation-specific private usage flags */
+    GRALLOC_USAGE_PRIVATE_0             = 0x10000000U,
+    GRALLOC_USAGE_PRIVATE_1             = 0x20000000U,
+    GRALLOC_USAGE_PRIVATE_2             = 0x40000000U,
+    GRALLOC_USAGE_PRIVATE_3             = 0x80000000U,
+    GRALLOC_USAGE_PRIVATE_MASK          = 0xF0000000U,
+};
+
+/*****************************************************************************/
+
+/**
+ * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
+ * and the fields of this data structure must begin with hw_module_t
+ * followed by module specific information.
+ */
+typedef struct gralloc_module_t {
+    struct hw_module_t common;
+    
+    /*
+     * (*registerBuffer)() must be called before a buffer_handle_t that has not
+     * been created with (*alloc_device_t::alloc)() can be used.
+     * 
+     * This is intended to be used with buffer_handle_t's that have been
+     * received in this process through IPC.
+     * 
+     * This function checks that the handle is indeed a valid one and prepares
+     * it for use with (*lock)() and (*unlock)().
+     * 
+     * It is not necessary to call (*registerBuffer)() on a handle created 
+     * with (*alloc_device_t::alloc)().
+     * 
+     * returns an error if this buffer_handle_t is not valid.
+     */
+    int (*registerBuffer)(struct gralloc_module_t const* module,
+            buffer_handle_t handle);
+
+    /*
+     * (*unregisterBuffer)() is called once this handle is no longer needed in
+     * this process. After this call, it is an error to call (*lock)(),
+     * (*unlock)(), or (*registerBuffer)().
+     * 
+     * This function doesn't close or free the handle itself; this is done
+     * by other means, usually through libcutils's native_handle_close() and
+     * native_handle_free(). 
+     * 
+     * It is an error to call (*unregisterBuffer)() on a buffer that wasn't
+     * explicitly registered first.
+     */
+    int (*unregisterBuffer)(struct gralloc_module_t const* module,
+            buffer_handle_t handle);
+    
+    /*
+     * The (*lock)() method is called before a buffer is accessed for the 
+     * specified usage. This call may block, for instance if the h/w needs
+     * to finish rendering or if CPU caches need to be synchronized.
+     * 
+     * The caller promises to modify only pixels in the area specified 
+     * by (l,t,w,h).
+     * 
+     * The content of the buffer outside of the specified area is NOT modified
+     * by this call.
+     *
+     * If usage specifies GRALLOC_USAGE_SW_*, vaddr is filled with the address
+     * of the buffer in virtual memory.
+     *
+     * Note calling (*lock)() on HAL_PIXEL_FORMAT_YCbCr_*_888 buffers will fail
+     * and return -EINVAL.  These buffers must be locked with (*lock_ycbcr)()
+     * instead.
+     *
+     * THREADING CONSIDERATIONS:
+     *
+     * It is legal for several different threads to lock a buffer from 
+     * read access, none of the threads are blocked.
+     * 
+     * However, locking a buffer simultaneously for write or read/write is
+     * undefined, but:
+     * - shall not result in termination of the process
+     * - shall not block the caller
+     * It is acceptable to return an error or to leave the buffer's content
+     * into an indeterminate state.
+     *
+     * If the buffer was created with a usage mask incompatible with the
+     * requested usage flags here, -EINVAL is returned. 
+     * 
+     */
+    
+    int (*lock)(struct gralloc_module_t const* module,
+            buffer_handle_t handle, int usage,
+            int l, int t, int w, int h,
+            void** vaddr);
+
+    
+    /*
+     * The (*unlock)() method must be called after all changes to the buffer
+     * are completed.
+     */
+    
+    int (*unlock)(struct gralloc_module_t const* module,
+            buffer_handle_t handle);
+
+
+    /* reserved for future use */
+    int (*perform)(struct gralloc_module_t const* module,
+            int operation, ... );
+
+    /*
+     * The (*lock_ycbcr)() method is like the (*lock)() method, with the
+     * difference that it fills a struct ycbcr with a description of the buffer
+     * layout, and zeroes out the reserved fields.
+     *
+     * If the buffer format is not compatible with a flexible YUV format (e.g.
+     * the buffer layout cannot be represented with the ycbcr struct), it
+     * will return -EINVAL.
+     *
+     * This method must work on buffers with HAL_PIXEL_FORMAT_YCbCr_*_888
+     * if supported by the device, as well as with any other format that is
+     * requested by the multimedia codecs when they are configured with a
+     * flexible-YUV-compatible color-format with android native buffers.
+     *
+     * Note that this method may also be called on buffers of other formats,
+     * including non-YUV formats.
+     *
+     * Added in GRALLOC_MODULE_API_VERSION_0_2.
+     */
+
+    int (*lock_ycbcr)(struct gralloc_module_t const* module,
+            buffer_handle_t handle, int usage,
+            int l, int t, int w, int h,
+            struct android_ycbcr *ycbcr);
+
+    /*
+     * The (*lockAsync)() method is like the (*lock)() method except
+     * that the buffer's sync fence object is passed into the lock
+     * call instead of requiring the caller to wait for completion.
+     *
+     * The gralloc implementation takes ownership of the fenceFd and
+     * is responsible for closing it when no longer needed.
+     *
+     * Added in GRALLOC_MODULE_API_VERSION_0_3.
+     */
+    int (*lockAsync)(struct gralloc_module_t const* module,
+            buffer_handle_t handle, int usage,
+            int l, int t, int w, int h,
+            void** vaddr, int fenceFd);
+
+    /*
+     * The (*unlockAsync)() method is like the (*unlock)() method
+     * except that a buffer sync fence object is returned from the
+     * lock call, representing the completion of any pending work
+     * performed by the gralloc implementation.
+     *
+     * The caller takes ownership of the fenceFd and is responsible
+     * for closing it when no longer needed.
+     *
+     * Added in GRALLOC_MODULE_API_VERSION_0_3.
+     */
+    int (*unlockAsync)(struct gralloc_module_t const* module,
+            buffer_handle_t handle, int* fenceFd);
+
+    /*
+     * The (*lockAsync_ycbcr)() method is like the (*lock_ycbcr)()
+     * method except that the buffer's sync fence object is passed
+     * into the lock call instead of requiring the caller to wait for
+     * completion.
+     *
+     * The gralloc implementation takes ownership of the fenceFd and
+     * is responsible for closing it when no longer needed.
+     *
+     * Added in GRALLOC_MODULE_API_VERSION_0_3.
+     */
+    int (*lockAsync_ycbcr)(struct gralloc_module_t const* module,
+            buffer_handle_t handle, int usage,
+            int l, int t, int w, int h,
+            struct android_ycbcr *ycbcr, int fenceFd);
+
+    /* getTransportSize(..., outNumFds, outNumInts)
+     * This function is mandatory on devices running IMapper2.1 or higher.
+     *
+     * Get the transport size of a buffer. An imported buffer handle is a raw
+     * buffer handle with the process-local runtime data appended. This
+     * function, for example, allows a caller to omit the process-local
+     * runtime data at the tail when serializing the imported buffer handle.
+     *
+     * Note that a client might or might not omit the process-local runtime
+     * data when sending an imported buffer handle. The mapper must support
+     * both cases on the receiving end.
+     */
+    int32_t (*getTransportSize)(
+            struct gralloc_module_t const* module, buffer_handle_t handle, uint32_t *outNumFds,
+            uint32_t *outNumInts);
+
+    /* validateBufferSize(..., w, h, format, usage, stride)
+     * This function is mandatory on devices running IMapper2.1 or higher.
+     *
+     * Validate that the buffer can be safely accessed by a caller who assumes
+     * the specified width, height, format, usage, and stride. This must at least validate
+     * that the buffer size is large enough. Validating the buffer against
+     * individual buffer attributes is optional.
+     */
+    int32_t (*validateBufferSize)(
+            struct gralloc_module_t const* device, buffer_handle_t handle,
+            uint32_t w, uint32_t h, int32_t format, int usage,
+            uint32_t stride);
+
+    /* reserved for future use */
+    void* reserved_proc[1];
+
+} gralloc_module_t;
+
+/*****************************************************************************/
+
+/**
+ * Every device data structure must begin with hw_device_t
+ * followed by module specific public methods and attributes.
+ */
+
+typedef struct alloc_device_t {
+    struct hw_device_t common;
+
+    /* 
+     * (*alloc)() Allocates a buffer in graphic memory with the requested
+     * parameters and returns a buffer_handle_t and the stride in pixels to
+     * allow the implementation to satisfy hardware constraints on the width
+     * of a pixmap (eg: it may have to be multiple of 8 pixels). 
+     * The CALLER TAKES OWNERSHIP of the buffer_handle_t.
+     *
+     * If format is HAL_PIXEL_FORMAT_YCbCr_420_888, the returned stride must be
+     * 0, since the actual strides are available from the android_ycbcr
+     * structure.
+     * 
+     * Returns 0 on success or -errno on error.
+     */
+    
+    int (*alloc)(struct alloc_device_t* dev,
+            int w, int h, int format, int usage,
+            buffer_handle_t* handle, int* stride);
+
+    /*
+     * (*free)() Frees a previously allocated buffer. 
+     * Behavior is undefined if the buffer is still mapped in any process,
+     * but shall not result in termination of the program or security breaches
+     * (allowing a process to get access to another process' buffers).
+     * THIS FUNCTION TAKES OWNERSHIP of the buffer_handle_t which becomes
+     * invalid after the call. 
+     * 
+     * Returns 0 on success or -errno on error.
+     */
+    int (*free)(struct alloc_device_t* dev,
+            buffer_handle_t handle);
+
+    /* This hook is OPTIONAL.
+     *
+     * If non NULL it will be caused by SurfaceFlinger on dumpsys
+     */
+    void (*dump)(struct alloc_device_t *dev, char *buff, int buff_len);
+
+    void* reserved_proc[7];
+} alloc_device_t;
+
+
+/** convenience API for opening and closing a supported device */
+
+static inline int gralloc_open(const struct hw_module_t* module, 
+        struct alloc_device_t** device) {
+    return module->methods->open(module, 
+            GRALLOC_HARDWARE_GPU0, TO_HW_DEVICE_T_OPEN(device));
+}
+
+static inline int gralloc_close(struct alloc_device_t* device) {
+    return device->common.close(&device->common);
+}
+
+/**
+ * map_usage_to_memtrack should be called after allocating a gralloc buffer.
+ *
+ * @param usage - it is the flag used when alloc function is called.
+ *
+ * This function maps the gralloc usage flags to appropriate memtrack bucket.
+ * GrallocHAL implementers and users should make an additional ION_IOCTL_TAG
+ * call using the memtrack tag returned by this function. This will help the
+ * in-kernel memtack to categorize the memory allocated by different processes
+ * according to their usage.
+ *
+ */
+static inline const char* map_usage_to_memtrack(uint32_t usage) {
+    usage &= GRALLOC_USAGE_ALLOC_MASK;
+
+    if ((usage & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
+        return "camera";
+    } else if ((usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) != 0 ||
+            (usage & GRALLOC_USAGE_EXTERNAL_DISP) != 0) {
+        return "video";
+    } else if ((usage & GRALLOC_USAGE_HW_RENDER) != 0 ||
+            (usage & GRALLOC_USAGE_HW_TEXTURE) != 0) {
+        return "gl";
+    } else if ((usage & GRALLOC_USAGE_HW_CAMERA_READ) != 0) {
+        return "camera";
+    } else if ((usage & GRALLOC_USAGE_SW_READ_MASK) != 0 ||
+            (usage & GRALLOC_USAGE_SW_WRITE_MASK) != 0) {
+        return "cpu";
+    }
+    return "graphics";
+}
+
+__END_DECLS
+
+#endif  // ANDROID_GRALLOC_INTERFACE_H
diff --git a/.ci/android_headers/hardware/hardware.h b/.ci/android_headers/hardware/hardware.h
new file mode 100644
index 0000000..a6d9ad9
--- /dev/null
+++ b/.ci/android_headers/hardware/hardware.h
@@ -0,0 +1,245 @@
+// clang-format off
+/*
+ * Copyright (C) 2008 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.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_HARDWARE_H
+#define ANDROID_INCLUDE_HARDWARE_HARDWARE_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+#include <cutils/native_handle.h>
+#include <system/graphics.h>
+
+__BEGIN_DECLS
+
+/*
+ * Value for the hw_module_t.tag field
+ */
+
+#define MAKE_TAG_CONSTANT(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D))
+
+#define HARDWARE_MODULE_TAG MAKE_TAG_CONSTANT('H', 'W', 'M', 'T')
+#define HARDWARE_DEVICE_TAG MAKE_TAG_CONSTANT('H', 'W', 'D', 'T')
+
+#define HARDWARE_MAKE_API_VERSION(maj,min) \
+            ((((maj) & 0xff) << 8) | ((min) & 0xff))
+
+#define HARDWARE_MAKE_API_VERSION_2(maj,min,hdr) \
+            ((((maj) & 0xff) << 24) | (((min) & 0xff) << 16) | ((hdr) & 0xffff))
+#define HARDWARE_API_VERSION_2_MAJ_MIN_MASK 0xffff0000
+#define HARDWARE_API_VERSION_2_HEADER_MASK  0x0000ffff
+
+
+/*
+ * The current HAL API version.
+ *
+ * All module implementations must set the hw_module_t.hal_api_version field
+ * to this value when declaring the module with HAL_MODULE_INFO_SYM.
+ *
+ * Note that previous implementations have always set this field to 0.
+ * Therefore, libhardware HAL API will always consider versions 0.0 and 1.0
+ * to be 100% binary compatible.
+ *
+ */
+#define HARDWARE_HAL_API_VERSION HARDWARE_MAKE_API_VERSION(1, 0)
+
+/*
+ * Helper macros for module implementors.
+ *
+ * The derived modules should provide convenience macros for supported
+ * versions so that implementations can explicitly specify module/device
+ * versions at definition time.
+ *
+ * Use this macro to set the hw_module_t.module_api_version field.
+ */
+#define HARDWARE_MODULE_API_VERSION(maj,min) HARDWARE_MAKE_API_VERSION(maj,min)
+#define HARDWARE_MODULE_API_VERSION_2(maj,min,hdr) HARDWARE_MAKE_API_VERSION_2(maj,min,hdr)
+
+/*
+ * Use this macro to set the hw_device_t.version field
+ */
+#define HARDWARE_DEVICE_API_VERSION(maj,min) HARDWARE_MAKE_API_VERSION(maj,min)
+#define HARDWARE_DEVICE_API_VERSION_2(maj,min,hdr) HARDWARE_MAKE_API_VERSION_2(maj,min,hdr)
+
+struct hw_module_t;
+struct hw_module_methods_t;
+struct hw_device_t;
+
+/**
+ * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
+ * and the fields of this data structure must begin with hw_module_t
+ * followed by module specific information.
+ */
+typedef struct hw_module_t {
+    /** tag must be initialized to HARDWARE_MODULE_TAG */
+    uint32_t tag;
+
+    /**
+     * The API version of the implemented module. The module owner is
+     * responsible for updating the version when a module interface has
+     * changed.
+     *
+     * The derived modules such as gralloc and audio own and manage this field.
+     * The module user must interpret the version field to decide whether or
+     * not to inter-operate with the supplied module implementation.
+     * For example, SurfaceFlinger is responsible for making sure that
+     * it knows how to manage different versions of the gralloc-module API,
+     * and AudioFlinger must know how to do the same for audio-module API.
+     *
+     * The module API version should include a major and a minor component.
+     * For example, version 1.0 could be represented as 0x0100. This format
+     * implies that versions 0x0100-0x01ff are all API-compatible.
+     *
+     * In the future, libhardware will expose a hw_get_module_version()
+     * (or equivalent) function that will take minimum/maximum supported
+     * versions as arguments and would be able to reject modules with
+     * versions outside of the supplied range.
+     */
+    uint16_t module_api_version;
+#define version_major module_api_version
+    /**
+     * version_major/version_minor defines are supplied here for temporary
+     * source code compatibility. They will be removed in the next version.
+     * ALL clients must convert to the new version format.
+     */
+
+    /**
+     * The API version of the HAL module interface. This is meant to
+     * version the hw_module_t, hw_module_methods_t, and hw_device_t
+     * structures and definitions.
+     *
+     * The HAL interface owns this field. Module users/implementations
+     * must NOT rely on this value for version information.
+     *
+     * Presently, 0 is the only valid value.
+     */
+    uint16_t hal_api_version;
+#define version_minor hal_api_version
+
+    /** Identifier of module */
+    const char *id;
+
+    /** Name of this module */
+    const char *name;
+
+    /** Author/owner/implementor of the module */
+    const char *author;
+
+    /** Modules methods */
+    struct hw_module_methods_t* methods;
+
+    /** module's dso */
+    void* dso;
+
+#ifdef __LP64__
+    uint64_t reserved[32-7];
+#else
+    /** padding to 128 bytes, reserved for future use */
+    uint32_t reserved[32-7];
+#endif
+
+} hw_module_t;
+
+typedef struct hw_module_methods_t {
+    /** Open a specific device */
+    int (*open)(const struct hw_module_t* module, const char* id,
+            struct hw_device_t** device);
+
+} hw_module_methods_t;
+
+/**
+ * Every device data structure must begin with hw_device_t
+ * followed by module specific public methods and attributes.
+ */
+typedef struct hw_device_t {
+    /** tag must be initialized to HARDWARE_DEVICE_TAG */
+    uint32_t tag;
+
+    /**
+     * Version of the module-specific device API. This value is used by
+     * the derived-module user to manage different device implementations.
+     *
+     * The module user is responsible for checking the module_api_version
+     * and device version fields to ensure that the user is capable of
+     * communicating with the specific module implementation.
+     *
+     * One module can support multiple devices with different versions. This
+     * can be useful when a device interface changes in an incompatible way
+     * but it is still necessary to support older implementations at the same
+     * time. One such example is the Camera 2.0 API.
+     *
+     * This field is interpreted by the module user and is ignored by the
+     * HAL interface itself.
+     */
+    uint32_t version;
+
+    /** reference to the module this device belongs to */
+    struct hw_module_t* module;
+
+    /** padding reserved for future use */
+#ifdef __LP64__
+    uint64_t reserved[12];
+#else
+    uint32_t reserved[12];
+#endif
+
+    /** Close this device */
+    int (*close)(struct hw_device_t* device);
+
+} hw_device_t;
+
+#ifdef __cplusplus
+#define TO_HW_DEVICE_T_OPEN(x) reinterpret_cast<struct hw_device_t**>(x)
+#else
+#define TO_HW_DEVICE_T_OPEN(x) (struct hw_device_t**)(x)
+#endif
+
+/**
+ * Name of the hal_module_info
+ */
+#define HAL_MODULE_INFO_SYM         HMI
+
+/**
+ * Name of the hal_module_info as a string
+ */
+#define HAL_MODULE_INFO_SYM_AS_STR  "HMI"
+
+/**
+ * Get the module info associated with a module by id.
+ *
+ * @return: 0 == success, <0 == error and *module == NULL
+ */
+int hw_get_module(const char *id, const struct hw_module_t **module);
+
+/**
+ * Get the module info associated with a module instance by class 'class_id'
+ * and instance 'inst'.
+ *
+ * Some modules types necessitate multiple instances. For example audio supports
+ * multiple concurrent interfaces and thus 'audio' is the module class
+ * and 'primary' or 'a2dp' are module interfaces. This implies that the files
+ * providing these modules would be named audio.primary.<variant>.so and
+ * audio.a2dp.<variant>.so
+ *
+ * @return: 0 == success, <0 == error and *module == NULL
+ */
+int hw_get_module_by_class(const char *class_id, const char *inst,
+                           const struct hw_module_t **module);
+
+__END_DECLS
+
+#endif  /* ANDROID_INCLUDE_HARDWARE_HARDWARE_H */
diff --git a/.ci/android_headers/hardware/hwcomposer.h b/.ci/android_headers/hardware/hwcomposer.h
new file mode 100644
index 0000000..fd083d9
--- /dev/null
+++ b/.ci/android_headers/hardware/hwcomposer.h
@@ -0,0 +1,799 @@
+// clang-format off
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H
+#define ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+#include <hardware/gralloc.h>
+#include <hardware/hardware.h>
+#include <cutils/native_handle.h>
+
+#include <hardware/hwcomposer_defs.h>
+
+__BEGIN_DECLS
+
+/*****************************************************************************/
+
+/* for compatibility */
+#define HWC_MODULE_API_VERSION      HWC_MODULE_API_VERSION_0_1
+#define HWC_DEVICE_API_VERSION      HWC_DEVICE_API_VERSION_0_1
+#define HWC_API_VERSION             HWC_DEVICE_API_VERSION
+
+/*****************************************************************************/
+
+typedef struct hwc_layer_1 {
+    /*
+     * compositionType is used to specify this layer's type and is set by either
+     * the hardware composer implementation, or by the caller (see below).
+     *
+     *  This field is always reset to HWC_BACKGROUND or HWC_FRAMEBUFFER
+     *  before (*prepare)() is called when the HWC_GEOMETRY_CHANGED flag is
+     *  also set, otherwise, this field is preserved between (*prepare)()
+     *  calls.
+     *
+     * HWC_BACKGROUND
+     *   Always set by the caller before calling (*prepare)(), this value
+     *   indicates this is a special "background" layer. The only valid field
+     *   is backgroundColor.
+     *   The HWC can toggle this value to HWC_FRAMEBUFFER to indicate it CANNOT
+     *   handle the background color.
+     *
+     *
+     * HWC_FRAMEBUFFER_TARGET
+     *   Always set by the caller before calling (*prepare)(), this value
+     *   indicates this layer is the framebuffer surface used as the target of
+     *   OpenGL ES composition. If the HWC sets all other layers to HWC_OVERLAY
+     *   or HWC_BACKGROUND, then no OpenGL ES composition will be done, and
+     *   this layer should be ignored during set().
+     *
+     *   This flag (and the framebuffer surface layer) will only be used if the
+     *   HWC version is HWC_DEVICE_API_VERSION_1_1 or higher. In older versions,
+     *   the OpenGL ES target surface is communicated by the (dpy, sur) fields
+     *   in hwc_compositor_device_1_t.
+     *
+     *   This value cannot be set by the HWC implementation.
+     *
+     *
+     * HWC_FRAMEBUFFER
+     *   Set by the caller before calling (*prepare)() ONLY when the
+     *   HWC_GEOMETRY_CHANGED flag is also set.
+     *
+     *   Set by the HWC implementation during (*prepare)(), this indicates
+     *   that the layer will be drawn into the framebuffer using OpenGL ES.
+     *   The HWC can toggle this value to HWC_OVERLAY to indicate it will
+     *   handle the layer.
+     *
+     *
+     * HWC_OVERLAY
+     *   Set by the HWC implementation during (*prepare)(), this indicates
+     *   that the layer will be handled by the HWC (ie: it must not be
+     *   composited with OpenGL ES).
+     *
+     *
+     * HWC_SIDEBAND
+     *   Set by the caller before calling (*prepare)(), this value indicates
+     *   the contents of this layer come from a sideband video stream.
+     *
+     *   The h/w composer is responsible for receiving new image buffers from
+     *   the stream at the appropriate time (e.g. synchronized to a separate
+     *   audio stream), compositing them with the current contents of other
+     *   layers, and displaying the resulting image. This happens
+     *   independently of the normal prepare/set cycle. The prepare/set calls
+     *   only happen when other layers change, or when properties of the
+     *   sideband layer such as position or size change.
+     *
+     *   If the h/w composer can't handle the layer as a sideband stream for
+     *   some reason (e.g. unsupported scaling/blending/rotation, or too many
+     *   sideband layers) it can set compositionType to HWC_FRAMEBUFFER in
+     *   (*prepare)(). However, doing so will result in the layer being shown
+     *   as a solid color since the platform is not currently able to composite
+     *   sideband layers with the GPU. This may be improved in future
+     *   versions of the platform.
+     *
+     *
+     * HWC_CURSOR_OVERLAY
+     *   Set by the HWC implementation during (*prepare)(), this value
+     *   indicates the layer's composition will now be handled by the HWC.
+     *   Additionally, the client can now asynchronously update the on-screen
+     *   position of this layer using the setCursorPositionAsync() api.
+     */
+    int32_t compositionType;
+
+    /*
+     * hints is bit mask set by the HWC implementation during (*prepare)().
+     * It is preserved between (*prepare)() calls, unless the
+     * HWC_GEOMETRY_CHANGED flag is set, in which case it is reset to 0.
+     *
+     * see hwc_layer_t::hints
+     */
+    uint32_t hints;
+
+    /* see hwc_layer_t::flags */
+    uint32_t flags;
+
+    union {
+        /* color of the background.  hwc_color_t.a is ignored */
+        hwc_color_t backgroundColor;
+
+        struct {
+            union {
+                /* When compositionType is HWC_FRAMEBUFFER, HWC_OVERLAY,
+                 * HWC_FRAMEBUFFER_TARGET, this is the handle of the buffer to
+                 * compose. This handle is guaranteed to have been allocated
+                 * from gralloc using the GRALLOC_USAGE_HW_COMPOSER usage flag.
+                 * If the layer's handle is unchanged across two consecutive
+                 * prepare calls and the HWC_GEOMETRY_CHANGED flag is not set
+                 * for the second call then the HWComposer implementation may
+                 * assume that the contents of the buffer have not changed. */
+                buffer_handle_t handle;
+
+                /* When compositionType is HWC_SIDEBAND, this is the handle
+                 * of the sideband video stream to compose. */
+                const native_handle_t* sidebandStream;
+            };
+
+            /* transformation to apply to the buffer during composition */
+            uint32_t transform;
+
+            /* blending to apply during composition */
+            int32_t blending;
+
+            /* area of the source to consider, the origin is the top-left corner of
+             * the buffer. As of HWC_DEVICE_API_VERSION_1_3, sourceRect uses floats.
+             * If the h/w can't support a non-integer source crop rectangle, it should
+             * punt to OpenGL ES composition.
+             */
+            union {
+                // crop rectangle in integer (pre HWC_DEVICE_API_VERSION_1_3)
+                hwc_rect_t sourceCropi;
+                hwc_rect_t sourceCrop; // just for source compatibility
+                // crop rectangle in floats (as of HWC_DEVICE_API_VERSION_1_3)
+                hwc_frect_t sourceCropf;
+            };
+
+            /* where to composite the sourceCrop onto the display. The sourceCrop
+             * is scaled using linear filtering to the displayFrame. The origin is the
+             * top-left corner of the screen.
+             */
+            hwc_rect_t displayFrame;
+
+            /* visible region in screen space. The origin is the
+             * top-left corner of the screen.
+             * The visible region INCLUDES areas overlapped by a translucent layer.
+             */
+            hwc_region_t visibleRegionScreen;
+
+            /* Sync fence object that will be signaled when the buffer's
+             * contents are available. May be -1 if the contents are already
+             * available. This field is only valid during set(), and should be
+             * ignored during prepare(). The set() call must not wait for the
+             * fence to be signaled before returning, but the HWC must wait for
+             * all buffers to be signaled before reading from them.
+             *
+             * HWC_FRAMEBUFFER layers will never have an acquire fence, since
+             * reads from them are complete before the framebuffer is ready for
+             * display.
+             *
+             * HWC_SIDEBAND layers will never have an acquire fence, since
+             * synchronization is handled through implementation-defined
+             * sideband mechanisms.
+             *
+             * The HWC takes ownership of the acquireFenceFd and is responsible
+             * for closing it when no longer needed.
+             */
+            int acquireFenceFd;
+
+            /* During set() the HWC must set this field to a file descriptor for
+             * a sync fence object that will signal after the HWC has finished
+             * reading from the buffer. The field is ignored by prepare(). Each
+             * layer should have a unique file descriptor, even if more than one
+             * refer to the same underlying fence object; this allows each to be
+             * closed independently.
+             *
+             * If buffer reads can complete at significantly different times,
+             * then using independent fences is preferred. For example, if the
+             * HWC handles some layers with a blit engine and others with
+             * overlays, then the blit layers can be reused immediately after
+             * the blit completes, but the overlay layers can't be reused until
+             * a subsequent frame has been displayed.
+             *
+             * Since HWC doesn't read from HWC_FRAMEBUFFER layers, it shouldn't
+             * produce a release fence for them. The releaseFenceFd will be -1
+             * for these layers when set() is called.
+             *
+             * Since HWC_SIDEBAND buffers don't pass through the HWC client,
+             * the HWC shouldn't produce a release fence for them. The
+             * releaseFenceFd will be -1 for these layers when set() is called.
+             *
+             * The HWC client taks ownership of the releaseFenceFd and is
+             * responsible for closing it when no longer needed.
+             */
+            int releaseFenceFd;
+
+            /*
+             * Availability: HWC_DEVICE_API_VERSION_1_2
+             *
+             * Alpha value applied to the whole layer. The effective
+             * value of each pixel is computed as:
+             *
+             *   if (blending == HWC_BLENDING_PREMULT)
+             *      pixel.rgb = pixel.rgb * planeAlpha / 255
+             *   pixel.a = pixel.a * planeAlpha / 255
+             *
+             * Then blending proceeds as usual according to the "blending"
+             * field above.
+             *
+             * NOTE: planeAlpha applies to YUV layers as well:
+             *
+             *   pixel.rgb = yuv_to_rgb(pixel.yuv)
+             *   if (blending == HWC_BLENDING_PREMULT)
+             *      pixel.rgb = pixel.rgb * planeAlpha / 255
+             *   pixel.a = planeAlpha
+             *
+             *
+             * IMPLEMENTATION NOTE:
+             *
+             * If the source image doesn't have an alpha channel, then
+             * the h/w can use the HWC_BLENDING_COVERAGE equations instead of
+             * HWC_BLENDING_PREMULT and simply set the alpha channel to
+             * planeAlpha.
+             *
+             * e.g.:
+             *
+             *   if (blending == HWC_BLENDING_PREMULT)
+             *      blending = HWC_BLENDING_COVERAGE;
+             *   pixel.a = planeAlpha;
+             *
+             */
+            uint8_t planeAlpha;
+
+            /* Pad to 32 bits */
+            uint8_t _pad[3];
+
+            /*
+             * Availability: HWC_DEVICE_API_VERSION_1_5
+             *
+             * This defines the region of the source buffer that has been
+             * modified since the last frame.
+             *
+             * If surfaceDamage.numRects > 0, then it may be assumed that any
+             * portion of the source buffer not covered by one of the rects has
+             * not been modified this frame. If surfaceDamage.numRects == 0,
+             * then the whole source buffer must be treated as if it had been
+             * modified.
+             *
+             * If the layer's contents are not modified relative to the prior
+             * prepare/set cycle, surfaceDamage will contain exactly one empty
+             * rect ([0, 0, 0, 0]).
+             *
+             * The damage rects are relative to the pre-transformed buffer, and
+             * their origin is the top-left corner.
+             */
+            hwc_region_t surfaceDamage;
+        };
+    };
+
+#ifdef __LP64__
+    /*
+     * For 64-bit mode, this struct is 120 bytes (and 8-byte aligned), and needs
+     * to be padded as such to maintain binary compatibility.
+     */
+    uint8_t reserved[120 - 112];
+#else
+    /*
+     * For 32-bit mode, this struct is 96 bytes, and needs to be padded as such
+     * to maintain binary compatibility.
+     */
+    uint8_t reserved[96 - 84];
+#endif
+
+} hwc_layer_1_t;
+
+/* This represents a display, typically an EGLDisplay object */
+typedef void* hwc_display_t;
+
+/* This represents a surface, typically an EGLSurface object  */
+typedef void* hwc_surface_t;
+
+/*
+ * hwc_display_contents_1_t::flags values
+ */
+enum {
+    /*
+     * HWC_GEOMETRY_CHANGED is set by SurfaceFlinger to indicate that the list
+     * passed to (*prepare)() has changed by more than just the buffer handles
+     * and acquire fences.
+     */
+    HWC_GEOMETRY_CHANGED = 0x00000001,
+};
+
+/*
+ * Description of the contents to output on a display.
+ *
+ * This is the top-level structure passed to the prepare and set calls to
+ * negotiate and commit the composition of a display image.
+ */
+typedef struct hwc_display_contents_1 {
+    /* File descriptor referring to a Sync HAL fence object which will signal
+     * when this composition is retired. For a physical display, a composition
+     * is retired when it has been replaced on-screen by a subsequent set. For
+     * a virtual display, the composition is retired when the writes to
+     * outputBuffer are complete and can be read. The fence object is created
+     * and returned by the set call; this field will be -1 on entry to prepare
+     * and set. SurfaceFlinger will close the returned file descriptor.
+     */
+    int retireFenceFd;
+
+    union {
+        /* Fields only relevant for HWC_DEVICE_VERSION_1_0. */
+        struct {
+            /* (dpy, sur) is the target of SurfaceFlinger's OpenGL ES
+             * composition for HWC_DEVICE_VERSION_1_0. They aren't relevant to
+             * prepare. The set call should commit this surface atomically to
+             * the display along with any overlay layers.
+             */
+            hwc_display_t dpy;
+            hwc_surface_t sur;
+        };
+
+        /* These fields are used for virtual displays when the h/w composer
+         * version is at least HWC_DEVICE_VERSION_1_3. */
+        struct {
+            /* outbuf is the buffer that receives the composed image for
+             * virtual displays. Writes to the outbuf must wait until
+             * outbufAcquireFenceFd signals. A fence that will signal when
+             * writes to outbuf are complete should be returned in
+             * retireFenceFd.
+             *
+             * This field is set before prepare(), so properties of the buffer
+             * can be used to decide which layers can be handled by h/w
+             * composer.
+             *
+             * If prepare() sets all layers to FRAMEBUFFER, then GLES
+             * composition will happen directly to the output buffer. In this
+             * case, both outbuf and the FRAMEBUFFER_TARGET layer's buffer will
+             * be the same, and set() has no work to do besides managing fences.
+             *
+             * If the TARGET_FORCE_HWC_FOR_VIRTUAL_DISPLAYS board config
+             * variable is defined (not the default), then this behavior is
+             * changed: if all layers are marked for FRAMEBUFFER, GLES
+             * composition will take place to a scratch framebuffer, and
+             * h/w composer must copy it to the output buffer. This allows the
+             * h/w composer to do format conversion if there are cases where
+             * that is more desirable than doing it in the GLES driver or at the
+             * virtual display consumer.
+             *
+             * If some or all layers are marked OVERLAY, then the framebuffer
+             * and output buffer will be different. As with physical displays,
+             * the framebuffer handle will not change between frames if all
+             * layers are marked for OVERLAY.
+             */
+            buffer_handle_t outbuf;
+
+            /* File descriptor for a fence that will signal when outbuf is
+             * ready to be written. The h/w composer is responsible for closing
+             * this when no longer needed.
+             *
+             * Will be -1 whenever outbuf is NULL, or when the outbuf can be
+             * written immediately.
+             */
+            int outbufAcquireFenceFd;
+        };
+    };
+
+    /* List of layers that will be composed on the display. The buffer handles
+     * in the list will be unique. If numHwLayers is 0, all composition will be
+     * performed by SurfaceFlinger.
+     */
+    uint32_t flags;
+    size_t numHwLayers;
+    hwc_layer_1_t hwLayers[0];
+
+} hwc_display_contents_1_t;
+
+/* see hwc_composer_device::registerProcs()
+ * All of the callbacks are required and non-NULL unless otherwise noted.
+ */
+typedef struct hwc_procs {
+    /*
+     * (*invalidate)() triggers a screen refresh, in particular prepare and set
+     * will be called shortly after this call is made. Note that there is
+     * NO GUARANTEE that the screen refresh will happen after invalidate()
+     * returns (in particular, it could happen before).
+     * invalidate() is GUARANTEED TO NOT CALL BACK into the h/w composer HAL and
+     * it is safe to call invalidate() from any of hwc_composer_device
+     * hooks, unless noted otherwise.
+     */
+    void (*invalidate)(const struct hwc_procs* procs);
+
+    /*
+     * (*vsync)() is called by the h/w composer HAL when a vsync event is
+     * received and HWC_EVENT_VSYNC is enabled on a display
+     * (see: hwc_event_control).
+     *
+     * the "disp" parameter indicates which display the vsync event is for.
+     * the "timestamp" parameter is the system monotonic clock timestamp in
+     *   nanosecond of when the vsync event happened.
+     *
+     * vsync() is GUARANTEED TO NOT CALL BACK into the h/w composer HAL.
+     *
+     * It is expected that vsync() is called from a thread of at least
+     * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible,
+     * typically less than 0.5 ms.
+     *
+     * It is a (silent) error to have HWC_EVENT_VSYNC enabled when calling
+     * hwc_composer_device.set(..., 0, 0, 0) (screen off). The implementation
+     * can either stop or continue to process VSYNC events, but must not
+     * crash or cause other problems.
+     */
+    void (*vsync)(const struct hwc_procs* procs, int disp, int64_t timestamp);
+
+    /*
+     * (*hotplug)() is called by the h/w composer HAL when a display is
+     * connected or disconnected. The PRIMARY display is always connected and
+     * the hotplug callback should not be called for it.
+     *
+     * The disp parameter indicates which display type this event is for.
+     * The connected parameter indicates whether the display has just been
+     *   connected (1) or disconnected (0).
+     *
+     * The hotplug() callback may call back into the h/w composer on the same
+     * thread to query refresh rate and dpi for the display. Additionally,
+     * other threads may be calling into the h/w composer while the callback
+     * is in progress.
+     *
+     * The h/w composer must serialize calls to the hotplug callback; only
+     * one thread may call it at a time.
+     *
+     * This callback will be NULL if the h/w composer is using
+     * HWC_DEVICE_API_VERSION_1_0.
+     */
+    void (*hotplug)(const struct hwc_procs* procs, int disp, int connected);
+
+} hwc_procs_t;
+
+
+/*****************************************************************************/
+
+typedef struct hwc_module {
+    /**
+     * Common methods of the hardware composer module.  This *must* be the first member of
+     * hwc_module as users of this structure will cast a hw_module_t to
+     * hwc_module pointer in contexts where it's known the hw_module_t references a
+     * hwc_module.
+     */
+    struct hw_module_t common;
+} hwc_module_t;
+
+#define HWC_ERROR (-1)
+typedef struct hwc_composer_device_1 {
+    /**
+     * Common methods of the hardware composer device.  This *must* be the first member of
+     * hwc_composer_device_1 as users of this structure will cast a hw_device_t to
+     * hwc_composer_device_1 pointer in contexts where it's known the hw_device_t references a
+     * hwc_composer_device_1.
+     */
+    struct hw_device_t common;
+
+    /*
+     * (*prepare)() is called for each frame before composition and is used by
+     * SurfaceFlinger to determine what composition steps the HWC can handle.
+     *
+     * (*prepare)() can be called more than once, the last call prevails.
+     *
+     * The HWC responds by setting the compositionType field in each layer to
+     * either HWC_FRAMEBUFFER, HWC_OVERLAY, or HWC_CURSOR_OVERLAY. For the
+     * HWC_FRAMEBUFFER type, composition for the layer is handled by
+     * SurfaceFlinger with OpenGL ES. For the latter two overlay types,
+     * the HWC will have to handle the layer's composition. compositionType
+     * and hints are preserved between (*prepare)() calles unless the
+     * HWC_GEOMETRY_CHANGED flag is set.
+     *
+     * (*prepare)() is called with HWC_GEOMETRY_CHANGED to indicate that the
+     * list's geometry has changed, that is, when more than just the buffer's
+     * handles have been updated. Typically this happens (but is not limited to)
+     * when a window is added, removed, resized or moved. In this case
+     * compositionType and hints are reset to their default value.
+     *
+     * For HWC 1.0, numDisplays will always be one, and displays[0] will be
+     * non-NULL.
+     *
+     * For HWC 1.1, numDisplays will always be HWC_NUM_PHYSICAL_DISPLAY_TYPES.
+     * Entries for unsupported or disabled/disconnected display types will be
+     * NULL.
+     *
+     * In HWC 1.3, numDisplays may be up to HWC_NUM_DISPLAY_TYPES. The extra
+     * entries correspond to enabled virtual displays, and will be non-NULL.
+     *
+     * returns: 0 on success. An negative error code on error. If an error is
+     * returned, SurfaceFlinger will assume that none of the layer will be
+     * handled by the HWC.
+     */
+    int (*prepare)(struct hwc_composer_device_1 *dev,
+                    size_t numDisplays, hwc_display_contents_1_t** displays);
+
+    /*
+     * (*set)() is used in place of eglSwapBuffers(), and assumes the same
+     * functionality, except it also commits the work list atomically with
+     * the actual eglSwapBuffers().
+     *
+     * The layer lists are guaranteed to be the same as the ones returned from
+     * the last call to (*prepare)().
+     *
+     * When this call returns the caller assumes that the displays will be
+     * updated in the near future with the content of their work lists, without
+     * artifacts during the transition from the previous frame.
+     *
+     * A display with zero layers indicates that the entire composition has
+     * been handled by SurfaceFlinger with OpenGL ES. In this case, (*set)()
+     * behaves just like eglSwapBuffers().
+     *
+     * For HWC 1.0, numDisplays will always be one, and displays[0] will be
+     * non-NULL.
+     *
+     * For HWC 1.1, numDisplays will always be HWC_NUM_PHYSICAL_DISPLAY_TYPES.
+     * Entries for unsupported or disabled/disconnected display types will be
+     * NULL.
+     *
+     * In HWC 1.3, numDisplays may be up to HWC_NUM_DISPLAY_TYPES. The extra
+     * entries correspond to enabled virtual displays, and will be non-NULL.
+     *
+     * IMPORTANT NOTE: There is an implicit layer containing opaque black
+     * pixels behind all the layers in the list. It is the responsibility of
+     * the hwcomposer module to make sure black pixels are output (or blended
+     * from).
+     *
+     * IMPORTANT NOTE: In the event of an error this call *MUST* still cause
+     * any fences returned in the previous call to set to eventually become
+     * signaled.  The caller may have already issued wait commands on these
+     * fences, and having set return without causing those fences to signal
+     * will likely result in a deadlock.
+     *
+     * returns: 0 on success. A negative error code on error:
+     *    HWC_EGL_ERROR: eglGetError() will provide the proper error code (only
+     *        allowed prior to HWComposer 1.1)
+     *    Another code for non EGL errors.
+     */
+    int (*set)(struct hwc_composer_device_1 *dev,
+                size_t numDisplays, hwc_display_contents_1_t** displays);
+
+    /*
+     * eventControl(..., event, enabled)
+     * Enables or disables h/w composer events for a display.
+     *
+     * eventControl can be called from any thread and takes effect
+     * immediately.
+     *
+     *  Supported events are:
+     *      HWC_EVENT_VSYNC
+     *
+     * returns -EINVAL if the "event" parameter is not one of the value above
+     * or if the "enabled" parameter is not 0 or 1.
+     */
+    int (*eventControl)(struct hwc_composer_device_1* dev, int disp,
+            int event, int enabled);
+
+    union {
+        /*
+         * For HWC 1.3 and earlier, the blank() interface is used.
+         *
+         * blank(..., blank)
+         * Blanks or unblanks a display's screen.
+         *
+         * Turns the screen off when blank is nonzero, on when blank is zero.
+         * Multiple sequential calls with the same blank value must be
+         * supported.
+         * The screen state transition must be be complete when the function
+         * returns.
+         *
+         * returns 0 on success, negative on error.
+         */
+        int (*blank)(struct hwc_composer_device_1* dev, int disp, int blank);
+
+        /*
+         * For HWC 1.4 and above, setPowerMode() will be used in place of
+         * blank().
+         *
+         * setPowerMode(..., mode)
+         * Sets the display screen's power state.
+         *
+         * Refer to the documentation of the HWC_POWER_MODE_* constants
+         * for information about each power mode.
+         *
+         * The functionality is similar to the blank() command in previous
+         * versions of HWC, but with support for more power states.
+         *
+         * The display driver is expected to retain and restore the low power
+         * state of the display while entering and exiting from suspend.
+         *
+         * Multiple sequential calls with the same mode value must be supported.
+         *
+         * The screen state transition must be be complete when the function
+         * returns.
+         *
+         * returns 0 on success, negative on error.
+         */
+        int (*setPowerMode)(struct hwc_composer_device_1* dev, int disp,
+                int mode);
+    };
+
+    /*
+     * Used to retrieve information about the h/w composer
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int (*query)(struct hwc_composer_device_1* dev, int what, int* value);
+
+    /*
+     * (*registerProcs)() registers callbacks that the h/w composer HAL can
+     * later use. It will be called immediately after the composer device is
+     * opened with non-NULL procs. It is FORBIDDEN to call any of the callbacks
+     * from within registerProcs(). registerProcs() must save the hwc_procs_t
+     * pointer which is needed when calling a registered callback.
+     */
+    void (*registerProcs)(struct hwc_composer_device_1* dev,
+            hwc_procs_t const* procs);
+
+    /*
+     * This field is OPTIONAL and can be NULL.
+     *
+     * If non NULL it will be called by SurfaceFlinger on dumpsys
+     */
+    void (*dump)(struct hwc_composer_device_1* dev, char *buff, int buff_len);
+
+    /*
+     * (*getDisplayConfigs)() returns handles for the configurations available
+     * on the connected display. These handles must remain valid as long as the
+     * display is connected.
+     *
+     * Configuration handles are written to configs. The number of entries
+     * allocated by the caller is passed in *numConfigs; getDisplayConfigs must
+     * not try to write more than this number of config handles. On return, the
+     * total number of configurations available for the display is returned in
+     * *numConfigs. If *numConfigs is zero on entry, then configs may be NULL.
+     *
+     * Hardware composers implementing HWC_DEVICE_API_VERSION_1_3 or prior
+     * shall choose one configuration to activate and report it as the first
+     * entry in the returned list. Reporting the inactive configurations is not
+     * required.
+     *
+     * HWC_DEVICE_API_VERSION_1_4 and later provide configuration management
+     * through SurfaceFlinger, and hardware composers implementing these APIs
+     * must also provide getActiveConfig and setActiveConfig. Hardware composers
+     * implementing these API versions may choose not to activate any
+     * configuration, leaving configuration selection to higher levels of the
+     * framework.
+     *
+     * Returns 0 on success or a negative error code on error. If disp is a
+     * hotpluggable display type and no display is connected, an error shall be
+     * returned.
+     *
+     * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_1 and later.
+     * It shall be NULL for previous versions.
+     */
+    int (*getDisplayConfigs)(struct hwc_composer_device_1* dev, int disp,
+            uint32_t* configs, size_t* numConfigs);
+
+    /*
+     * (*getDisplayAttributes)() returns attributes for a specific config of a
+     * connected display. The config parameter is one of the config handles
+     * returned by getDisplayConfigs.
+     *
+     * The list of attributes to return is provided in the attributes
+     * parameter, terminated by HWC_DISPLAY_NO_ATTRIBUTE. The value for each
+     * requested attribute is written in order to the values array. The
+     * HWC_DISPLAY_NO_ATTRIBUTE attribute does not have a value, so the values
+     * array will have one less value than the attributes array.
+     *
+     * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_1 and later.
+     * It shall be NULL for previous versions.
+     *
+     * If disp is a hotpluggable display type and no display is connected,
+     * or if config is not a valid configuration for the display, a negative
+     * error code shall be returned.
+     */
+    int (*getDisplayAttributes)(struct hwc_composer_device_1* dev, int disp,
+            uint32_t config, const uint32_t* attributes, int32_t* values);
+
+    /*
+     * (*getActiveConfig)() returns the index of the configuration that is
+     * currently active on the connected display. The index is relative to
+     * the list of configuration handles returned by getDisplayConfigs. If there
+     * is no active configuration, HWC_ERROR shall be returned.
+     *
+     * Returns the configuration index on success or HWC_ERROR on error.
+     *
+     * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_4 and later.
+     * It shall be NULL for previous versions.
+     */
+    int (*getActiveConfig)(struct hwc_composer_device_1* dev, int disp);
+
+    /*
+     * (*setActiveConfig)() instructs the hardware composer to switch to the
+     * display configuration at the given index in the list of configuration
+     * handles returned by getDisplayConfigs.
+     *
+     * If this function returns without error, any subsequent calls to
+     * getActiveConfig shall return the index set by this function until one
+     * of the following occurs:
+     *   1) Another successful call of this function
+     *   2) The display is disconnected
+     *
+     * Returns 0 on success or a negative error code on error. If disp is a
+     * hotpluggable display type and no display is connected, or if index is
+     * outside of the range of hardware configurations returned by
+     * getDisplayConfigs, an error shall be returned.
+     *
+     * This field is REQUIRED for HWC_DEVICE_API_VERSION_1_4 and later.
+     * It shall be NULL for previous versions.
+     */
+    int (*setActiveConfig)(struct hwc_composer_device_1* dev, int disp,
+            int index);
+    /*
+     * Asynchronously update the location of the cursor layer.
+     *
+     * Within the standard prepare()/set() composition loop, the client
+     * (surfaceflinger) can request that a given layer uses dedicated cursor
+     * composition hardware by specifiying the HWC_IS_CURSOR_LAYER flag. Only
+     * one layer per display can have this flag set. If the layer is suitable
+     * for the platform's cursor hardware, hwcomposer will return from prepare()
+     * a composition type of HWC_CURSOR_OVERLAY for that layer. This indicates
+     * not only that the client is not responsible for compositing that layer,
+     * but also that the client can continue to update the position of that layer
+     * after a call to set(). This can reduce the visible latency of mouse
+     * movement to visible, on-screen cursor updates. Calls to
+     * setCursorPositionAsync() may be made from a different thread doing the
+     * prepare()/set() composition loop, but care must be taken to not interleave
+     * calls of setCursorPositionAsync() between calls of set()/prepare().
+     *
+     * Notes:
+     * - Only one layer per display can be specified as a cursor layer with
+     *   HWC_IS_CURSOR_LAYER.
+     * - hwcomposer will only return one layer per display as HWC_CURSOR_OVERLAY
+     * - This returns 0 on success or -errno on error.
+     * - This field is optional for HWC_DEVICE_API_VERSION_1_4 and later. It
+     *   should be null for previous versions.
+     */
+    int (*setCursorPositionAsync)(struct hwc_composer_device_1 *dev, int disp, int x_pos, int y_pos);
+
+    /*
+     * Reserved for future use. Must be NULL.
+     */
+    void* reserved_proc[1];
+
+} hwc_composer_device_1_t;
+
+/** convenience API for opening and closing a device */
+
+static inline int hwc_open_1(const struct hw_module_t* module,
+        hwc_composer_device_1_t** device) {
+    return module->methods->open(module,
+            HWC_HARDWARE_COMPOSER, TO_HW_DEVICE_T_OPEN(device));
+}
+
+static inline int hwc_close_1(hwc_composer_device_1_t* device) {
+    return device->common.close(&device->common);
+}
+
+/*****************************************************************************/
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_H */
diff --git a/.ci/android_headers/hardware/hwcomposer2.h b/.ci/android_headers/hardware/hwcomposer2.h
new file mode 100644
index 0000000..df5670f
--- /dev/null
+++ b/.ci/android_headers/hardware/hwcomposer2.h
@@ -0,0 +1,3183 @@
+// clang-format off
+/*
+ * Copyright 2015 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.
+ */
+
+#ifndef ANDROID_HARDWARE_HWCOMPOSER2_H
+#define ANDROID_HARDWARE_HWCOMPOSER2_H
+
+#include <sys/cdefs.h>
+
+#include <hardware/hardware.h>
+
+#include "hwcomposer_defs.h"
+
+/* Missing in glibc, pull from BIONIC */
+#if defined(__cplusplus)
+#define __BIONIC_CAST(_k,_t,_v) (_k<_t>(_v))
+#else
+#define __BIONIC_CAST(_k,_t,_v) ((_t) (_v))
+#endif
+
+__BEGIN_DECLS
+
+/*
+ * Enums
+ *
+ * For most of these enums, there is an invalid value defined to be 0. This is
+ * an attempt to catch uninitialized fields, and these values should not be
+ * used.
+ */
+
+/* Display attributes queryable through getDisplayAttribute */
+typedef enum {
+    HWC2_ATTRIBUTE_INVALID = 0,
+
+    /* Dimensions in pixels */
+    HWC2_ATTRIBUTE_WIDTH = 1,
+    HWC2_ATTRIBUTE_HEIGHT = 2,
+
+    /* Vsync period in nanoseconds */
+    HWC2_ATTRIBUTE_VSYNC_PERIOD = 3,
+
+    /* Dots per thousand inches (DPI * 1000). Scaling by 1000 allows these
+     * numbers to be stored in an int32_t without losing too much precision. If
+     * the DPI for a configuration is unavailable or is considered unreliable,
+     * the device may return -1 instead */
+    HWC2_ATTRIBUTE_DPI_X = 4,
+    HWC2_ATTRIBUTE_DPI_Y = 5,
+
+    /* The configuration group this config is associated to.
+     * Switching between configurations within the same group may be done seamlessly
+     * in some conditions via setActiveConfigWithConstraints. */
+    HWC2_ATTRIBUTE_CONFIG_GROUP = 7,
+} hwc2_attribute_t;
+
+/* Blend modes, settable per layer */
+typedef enum {
+    HWC2_BLEND_MODE_INVALID = 0,
+
+    /* colorOut = colorSrc */
+    HWC2_BLEND_MODE_NONE = 1,
+
+    /* colorOut = colorSrc + colorDst * (1 - alphaSrc) */
+    HWC2_BLEND_MODE_PREMULTIPLIED = 2,
+
+    /* colorOut = colorSrc * alphaSrc + colorDst * (1 - alphaSrc) */
+    HWC2_BLEND_MODE_COVERAGE = 3,
+} hwc2_blend_mode_t;
+
+/* See the 'Callbacks' section for more detailed descriptions of what these
+ * functions do */
+typedef enum {
+    HWC2_CALLBACK_INVALID = 0,
+    HWC2_CALLBACK_HOTPLUG = 1,
+    HWC2_CALLBACK_REFRESH = 2,
+    HWC2_CALLBACK_VSYNC = 3,
+    HWC2_CALLBACK_VSYNC_2_4 = 4,
+    HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED = 5,
+    HWC2_CALLBACK_SEAMLESS_POSSIBLE = 6,
+} hwc2_callback_descriptor_t;
+
+/* Optional capabilities which may be supported by some devices. The particular
+ * set of supported capabilities for a given device may be retrieved using
+ * getCapabilities. */
+typedef enum {
+    HWC2_CAPABILITY_INVALID = 0,
+
+    /* Specifies that the device supports sideband stream layers, for which
+     * buffer content updates and other synchronization will not be provided
+     * through the usual validate/present cycle and must be handled by an
+     * external implementation-defined mechanism. Only changes to layer state
+     * (such as position, size, etc.) need to be performed through the
+     * validate/present cycle. */
+    HWC2_CAPABILITY_SIDEBAND_STREAM = 1,
+
+    /* Specifies that the device will apply a color transform even when either
+     * the client or the device has chosen that all layers should be composed by
+     * the client. This will prevent the client from applying the color
+     * transform during its composition step. */
+    HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM = 2,
+
+    /* Specifies that the present fence must not be used as an accurate
+     * representation of the actual present time of a frame.
+     * This capability must never be set by HWC2 devices.
+     * This capability may be set for HWC1 devices that use the
+     * HWC2On1Adapter where emulation of the present fence using the retire
+     * fence is not feasible.
+     * In the future, CTS tests will require present time to be reliable.
+     */
+    HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE = 3,
+
+    /* Specifies that a device is able to skip the validateDisplay call before
+     * receiving a call to presentDisplay. The client will always skip
+     * validateDisplay and try to call presentDisplay regardless of the changes
+     * in the properties of the layers. If the device returns anything else than
+     * HWC2_ERROR_NONE, it will call validateDisplay then presentDisplay again.
+     * For this capability to be worthwhile the device implementation of
+     * presentDisplay should fail as fast as possible in the case a
+     * validateDisplay step is needed.
+     */
+    HWC2_CAPABILITY_SKIP_VALIDATE = 4,
+} hwc2_capability_t;
+
+/* Possible composition types for a given layer */
+typedef enum {
+    HWC2_COMPOSITION_INVALID = 0,
+
+    /* The client will composite this layer into the client target buffer
+     * (provided to the device through setClientTarget).
+     *
+     * The device must not request any composition type changes for layers of
+     * this type. */
+    HWC2_COMPOSITION_CLIENT = 1,
+
+    /* The device will handle the composition of this layer through a hardware
+     * overlay or other similar means.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * HWC2_COMPOSITION_CLIENT. */
+    HWC2_COMPOSITION_DEVICE = 2,
+
+    /* The device will render this layer using the color set through
+     * setLayerColor. If this functionality is not supported on a layer that the
+     * client sets to HWC2_COMPOSITION_SOLID_COLOR, the device must request that
+     * the composition type of that layer is changed to HWC2_COMPOSITION_CLIENT
+     * upon the next call to validateDisplay.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * HWC2_COMPOSITION_CLIENT. */
+    HWC2_COMPOSITION_SOLID_COLOR = 3,
+
+    /* Similar to DEVICE, but the position of this layer may also be set
+     * asynchronously through setCursorPosition. If this functionality is not
+     * supported on a layer that the client sets to HWC2_COMPOSITION_CURSOR, the
+     * device must request that the composition type of that layer is changed to
+     * HWC2_COMPOSITION_CLIENT upon the next call to validateDisplay.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * either HWC2_COMPOSITION_DEVICE or HWC2_COMPOSITION_CLIENT. Changing to
+     * HWC2_COMPOSITION_DEVICE will prevent the use of setCursorPosition but
+     * still permit the device to composite the layer. */
+    HWC2_COMPOSITION_CURSOR = 4,
+
+    /* The device will handle the composition of this layer, as well as its
+     * buffer updates and content synchronization. Only supported on devices
+     * which provide HWC2_CAPABILITY_SIDEBAND_STREAM.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * either HWC2_COMPOSITION_DEVICE or HWC2_COMPOSITION_CLIENT, but it is
+     * unlikely that content will display correctly in these cases. */
+    HWC2_COMPOSITION_SIDEBAND = 5,
+} hwc2_composition_t;
+
+/* Possible connection options from the hotplug callback */
+typedef enum {
+    HWC2_CONNECTION_INVALID = 0,
+
+    /* The display has been connected */
+    HWC2_CONNECTION_CONNECTED = 1,
+
+    /* The display has been disconnected */
+    HWC2_CONNECTION_DISCONNECTED = 2,
+} hwc2_connection_t;
+
+/* Display requests returned by getDisplayRequests */
+typedef enum {
+    /* Instructs the client to provide a new client target buffer, even if no
+     * layers are marked for client composition. */
+    HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET = 1 << 0,
+
+    /* Instructs the client to write the result of client composition directly
+     * into the virtual display output buffer. If any of the layers are not
+     * marked as HWC2_COMPOSITION_CLIENT or the given display is not a virtual
+     * display, this request has no effect. */
+    HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT = 1 << 1,
+} hwc2_display_request_t;
+
+/* Display types returned by getDisplayType */
+typedef enum {
+    HWC2_DISPLAY_TYPE_INVALID = 0,
+
+    /* All physical displays, including both internal displays and hotpluggable
+     * external displays */
+    HWC2_DISPLAY_TYPE_PHYSICAL = 1,
+
+    /* Virtual displays created by createVirtualDisplay */
+    HWC2_DISPLAY_TYPE_VIRTUAL = 2,
+} hwc2_display_type_t;
+
+/* Physical display types returned by getDisplayConnectionType */
+typedef enum {
+    HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL = 0,
+    HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL = 1,
+} hwc2_display_connection_type_t;
+
+/* Return codes from all functions */
+typedef enum {
+    HWC2_ERROR_NONE = 0,
+    HWC2_ERROR_BAD_CONFIG,
+    HWC2_ERROR_BAD_DISPLAY,
+    HWC2_ERROR_BAD_LAYER,
+    HWC2_ERROR_BAD_PARAMETER,
+    HWC2_ERROR_HAS_CHANGES,
+    HWC2_ERROR_NO_RESOURCES,
+    HWC2_ERROR_NOT_VALIDATED,
+    HWC2_ERROR_UNSUPPORTED,
+    HWC2_ERROR_SEAMLESS_NOT_ALLOWED,
+    HWC2_ERROR_SEAMLESS_NOT_POSSIBLE,
+} hwc2_error_t;
+
+/* Function descriptors for use with getFunction */
+typedef enum {
+    HWC2_FUNCTION_INVALID = 0,
+    HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES,
+    HWC2_FUNCTION_CREATE_LAYER,
+    HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY,
+    HWC2_FUNCTION_DESTROY_LAYER,
+    HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY,
+    HWC2_FUNCTION_DUMP,
+    HWC2_FUNCTION_GET_ACTIVE_CONFIG,
+    HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES,
+    HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT,
+    HWC2_FUNCTION_GET_COLOR_MODES,
+    HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE,
+    HWC2_FUNCTION_GET_DISPLAY_CONFIGS,
+    HWC2_FUNCTION_GET_DISPLAY_NAME,
+    HWC2_FUNCTION_GET_DISPLAY_REQUESTS,
+    HWC2_FUNCTION_GET_DISPLAY_TYPE,
+    HWC2_FUNCTION_GET_DOZE_SUPPORT,
+    HWC2_FUNCTION_GET_HDR_CAPABILITIES,
+    HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT,
+    HWC2_FUNCTION_GET_RELEASE_FENCES,
+    HWC2_FUNCTION_PRESENT_DISPLAY,
+    HWC2_FUNCTION_REGISTER_CALLBACK,
+    HWC2_FUNCTION_SET_ACTIVE_CONFIG,
+    HWC2_FUNCTION_SET_CLIENT_TARGET,
+    HWC2_FUNCTION_SET_COLOR_MODE,
+    HWC2_FUNCTION_SET_COLOR_TRANSFORM,
+    HWC2_FUNCTION_SET_CURSOR_POSITION,
+    HWC2_FUNCTION_SET_LAYER_BLEND_MODE,
+    HWC2_FUNCTION_SET_LAYER_BUFFER,
+    HWC2_FUNCTION_SET_LAYER_COLOR,
+    HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE,
+    HWC2_FUNCTION_SET_LAYER_DATASPACE,
+    HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME,
+    HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA,
+    HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM,
+    HWC2_FUNCTION_SET_LAYER_SOURCE_CROP,
+    HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE,
+    HWC2_FUNCTION_SET_LAYER_TRANSFORM,
+    HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION,
+    HWC2_FUNCTION_SET_LAYER_Z_ORDER,
+    HWC2_FUNCTION_SET_OUTPUT_BUFFER,
+    HWC2_FUNCTION_SET_POWER_MODE,
+    HWC2_FUNCTION_SET_VSYNC_ENABLED,
+    HWC2_FUNCTION_VALIDATE_DISPLAY,
+    HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR,
+    HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA,
+    HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS,
+    HWC2_FUNCTION_SET_READBACK_BUFFER,
+    HWC2_FUNCTION_GET_READBACK_BUFFER_ATTRIBUTES,
+    HWC2_FUNCTION_GET_READBACK_BUFFER_FENCE,
+    HWC2_FUNCTION_GET_RENDER_INTENTS,
+    HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT,
+    HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX,
+
+    // composer 2.3
+    HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA,
+    HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES,
+    HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM,
+    HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES,
+    HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED,
+    HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE,
+    HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS,
+    HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT,
+    HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS,
+
+    // composer 2.4
+    HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE,
+    HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD,
+    HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS,
+    HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE,
+    HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES,
+    HWC2_FUNCTION_SET_CONTENT_TYPE,
+    HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY,
+    HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA,
+    HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY,
+} hwc2_function_descriptor_t;
+
+/* Layer requests returned from getDisplayRequests */
+typedef enum {
+    /* The client should clear its target with transparent pixels where this
+     * layer would be. The client may ignore this request if the layer must be
+     * blended. */
+    HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET = 1 << 0,
+} hwc2_layer_request_t;
+
+/* Power modes for use with setPowerMode */
+typedef enum {
+    /* The display is fully off (blanked) */
+    HWC2_POWER_MODE_OFF = 0,
+
+    /* These are optional low power modes. getDozeSupport may be called to
+     * determine whether a given display supports these modes. */
+
+    /* The display is turned on and configured in a low power state that is
+     * suitable for presenting ambient information to the user, possibly with
+     * lower fidelity than HWC2_POWER_MODE_ON, but with greater efficiency. */
+    HWC2_POWER_MODE_DOZE = 1,
+
+    /* The display is configured as in HWC2_POWER_MODE_DOZE but may stop
+     * applying display updates from the client. This is effectively a hint to
+     * the device that drawing to the display has been suspended and that the
+     * the device should remain on in a low power state and continue displaying
+     * its current contents indefinitely until the power mode changes.
+     *
+     * This mode may also be used as a signal to enable hardware-based doze
+     * functionality. In this case, the device is free to take over the display
+     * and manage it autonomously to implement a low power always-on display. */
+    HWC2_POWER_MODE_DOZE_SUSPEND = 3,
+
+    /* The display is fully on */
+    HWC2_POWER_MODE_ON = 2,
+} hwc2_power_mode_t;
+
+typedef enum {
+    HWC2_CONTENT_TYPE_NONE = 0,
+    HWC2_CONTENT_TYPE_GRAPHICS = 1,
+    HWC2_CONTENT_TYPE_PHOTO = 2,
+    HWC2_CONTENT_TYPE_CINEMA = 3,
+    HWC2_CONTENT_TYPE_GAME = 4,
+} hwc2_content_type_t;
+
+/* Vsync values passed to setVsyncEnabled */
+typedef enum {
+    HWC2_VSYNC_INVALID = 0,
+
+    /* Enable vsync */
+    HWC2_VSYNC_ENABLE = 1,
+
+    /* Disable vsync */
+    HWC2_VSYNC_DISABLE = 2,
+} hwc2_vsync_t;
+
+/* MUST match HIDL's V2_2::IComposerClient::PerFrameMetadataKey */
+typedef enum {
+    /* SMPTE ST 2084:2014.
+     * Coordinates defined in CIE 1931 xy chromaticity space
+     */
+    HWC2_DISPLAY_RED_PRIMARY_X = 0,
+    HWC2_DISPLAY_RED_PRIMARY_Y = 1,
+    HWC2_DISPLAY_GREEN_PRIMARY_X = 2,
+    HWC2_DISPLAY_GREEN_PRIMARY_Y = 3,
+    HWC2_DISPLAY_BLUE_PRIMARY_X = 4,
+    HWC2_DISPLAY_BLUE_PRIMARY_Y = 5,
+    HWC2_WHITE_POINT_X = 6,
+    HWC2_WHITE_POINT_Y = 7,
+    /* SMPTE ST 2084:2014.
+     * Units: nits
+     * max as defined by ST 2048: 10,000 nits
+     */
+    HWC2_MAX_LUMINANCE = 8,
+    HWC2_MIN_LUMINANCE = 9,
+
+    /* CTA 861.3
+     * Units: nits
+     */
+    HWC2_MAX_CONTENT_LIGHT_LEVEL = 10,
+    HWC2_MAX_FRAME_AVERAGE_LIGHT_LEVEL = 11,
+} hwc2_per_frame_metadata_key_t;
+
+/* SetDisplayedContentSampling values passed to setDisplayedContentSamplingEnabled */
+typedef enum {
+    HWC2_DISPLAYED_CONTENT_SAMPLING_INVALID = 0,
+
+    /* Enable displayed content sampling */
+    HWC2_DISPLAYED_CONTENT_SAMPLING_ENABLE = 1,
+
+    /* Disable displayed content sampling */
+    HWC2_DISPLAYED_CONTENT_SAMPLING_DISABLE = 2,
+} hwc2_displayed_content_sampling_t;
+
+typedef enum {
+    HWC2_FORMAT_COMPONENT_0 = 1 << 0, /* The first component (eg, for RGBA_8888, this is R) */
+    HWC2_FORMAT_COMPONENT_1 = 1 << 1, /* The second component (eg, for RGBA_8888, this is G) */
+    HWC2_FORMAT_COMPONENT_2 = 1 << 2, /* The third component (eg, for RGBA_8888, this is B) */
+    HWC2_FORMAT_COMPONENT_3 = 1 << 3, /* The fourth component (eg, for RGBA_8888, this is A) */
+} hwc2_format_color_component_t;
+
+/* Optional display capabilities which may be supported by some displays.
+ * The particular set of supported capabilities for a given display may be
+ * retrieved using getDisplayCapabilities. */
+typedef enum {
+    HWC2_DISPLAY_CAPABILITY_INVALID = 0,
+
+    /**
+     * Specifies that the display must apply a color transform even when either
+     * the client or the device has chosen that all layers should be composed by
+     * the client. This prevents the client from applying the color transform
+     * during its composition step.
+     * If getDisplayCapabilities is supported, the global capability
+     * HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM is ignored.
+     * If getDisplayCapabilities is not supported, and the global capability
+     * HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM is returned by getCapabilities,
+     * then all displays must be treated as having
+     * HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM.
+     */
+    HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM = 1,
+
+    /**
+     * Specifies that the display supports PowerMode::DOZE and
+     * PowerMode::DOZE_SUSPEND. DOZE_SUSPEND may not provide any benefit
+     * over DOZE (see the definition of PowerMode for more information),
+     * but if both DOZE and DOZE_SUSPEND are no different from
+     * PowerMode::ON, the device must not claim support.
+     * HWC2_DISPLAY_CAPABILITY_DOZE must be returned by getDisplayCapabilities
+     * when getDozeSupport indicates the display supports PowerMode::DOZE and
+     * PowerMode::DOZE_SUSPEND.
+     */
+    HWC2_DISPLAY_CAPABILITY_DOZE = 2,
+
+    /**
+     * Specified that the display supports brightness operations.
+     */
+    HWC2_DISPLAY_CAPABILITY_BRIGHTNESS = 3,
+
+    /**
+     * Specifies that the display supports a low latency mode. If the connection
+     * to the display is via HDMI, this specifies whether Auto Low Latency Mode
+     * is supported. If, instead, there is an internal connection to the display,
+     * then this specifies that the display has some other custom low latency
+     * mode.
+     */
+    HWC2_DISPLAY_CAPABILITY_AUTO_LOW_LATENCY_MODE = 5,
+} hwc2_display_capability_t;
+
+/*
+ * Stringification Functions
+ */
+
+#ifdef HWC2_INCLUDE_STRINGIFICATION
+
+static inline const char* getAttributeName(hwc2_attribute_t attribute) {
+    switch (attribute) {
+        case HWC2_ATTRIBUTE_INVALID: return "Invalid";
+        case HWC2_ATTRIBUTE_WIDTH: return "Width";
+        case HWC2_ATTRIBUTE_HEIGHT: return "Height";
+        case HWC2_ATTRIBUTE_VSYNC_PERIOD: return "VsyncPeriod";
+        case HWC2_ATTRIBUTE_DPI_X: return "DpiX";
+        case HWC2_ATTRIBUTE_DPI_Y: return "DpiY";
+        case HWC2_ATTRIBUTE_CONFIG_GROUP: return "ConfigGroup";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getBlendModeName(hwc2_blend_mode_t mode) {
+    switch (mode) {
+        case HWC2_BLEND_MODE_INVALID: return "Invalid";
+        case HWC2_BLEND_MODE_NONE: return "None";
+        case HWC2_BLEND_MODE_PREMULTIPLIED: return "Premultiplied";
+        case HWC2_BLEND_MODE_COVERAGE: return "Coverage";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getCallbackDescriptorName(
+        hwc2_callback_descriptor_t desc) {
+    switch (desc) {
+        case HWC2_CALLBACK_INVALID: return "Invalid";
+        case HWC2_CALLBACK_HOTPLUG: return "Hotplug";
+        case HWC2_CALLBACK_REFRESH: return "Refresh";
+        case HWC2_CALLBACK_VSYNC: return "Vsync";
+        case HWC2_CALLBACK_VSYNC_2_4: return "Vsync2.4";
+        case HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED: return "VsyncPeriodTimingChanged";
+        case HWC2_CALLBACK_SEAMLESS_POSSIBLE: return "SeamlessPossible";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getCapabilityName(hwc2_capability_t capability) {
+    switch (capability) {
+        case HWC2_CAPABILITY_INVALID: return "Invalid";
+        case HWC2_CAPABILITY_SIDEBAND_STREAM: return "SidebandStream";
+        case HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM:
+                return "SkipClientColorTransform";
+        case HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE:
+                return "PresentFenceIsNotReliable";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getCompositionName(hwc2_composition_t composition) {
+    switch (composition) {
+        case HWC2_COMPOSITION_INVALID: return "Invalid";
+        case HWC2_COMPOSITION_CLIENT: return "Client";
+        case HWC2_COMPOSITION_DEVICE: return "Device";
+        case HWC2_COMPOSITION_SOLID_COLOR: return "SolidColor";
+        case HWC2_COMPOSITION_CURSOR: return "Cursor";
+        case HWC2_COMPOSITION_SIDEBAND: return "Sideband";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getConnectionName(hwc2_connection_t connection) {
+    switch (connection) {
+        case HWC2_CONNECTION_INVALID: return "Invalid";
+        case HWC2_CONNECTION_CONNECTED: return "Connected";
+        case HWC2_CONNECTION_DISCONNECTED: return "Disconnected";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayRequestName(
+        hwc2_display_request_t request) {
+    switch (__BIONIC_CAST(static_cast, int, request)) {
+        case 0: return "None";
+        case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET: return "FlipClientTarget";
+        case HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT:
+            return "WriteClientTargetToOutput";
+        case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET |
+                HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT:
+            return "FlipClientTarget|WriteClientTargetToOutput";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayTypeName(hwc2_display_type_t type) {
+    switch (type) {
+        case HWC2_DISPLAY_TYPE_INVALID: return "Invalid";
+        case HWC2_DISPLAY_TYPE_PHYSICAL: return "Physical";
+        case HWC2_DISPLAY_TYPE_VIRTUAL: return "Virtual";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayConnectionTypeName(hwc2_display_connection_type_t type) {
+    switch (type) {
+        case HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL: return "Internal";
+        case HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL: return "External";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getErrorName(hwc2_error_t error) {
+    switch (error) {
+        case HWC2_ERROR_NONE: return "None";
+        case HWC2_ERROR_BAD_CONFIG: return "BadConfig";
+        case HWC2_ERROR_BAD_DISPLAY: return "BadDisplay";
+        case HWC2_ERROR_BAD_LAYER: return "BadLayer";
+        case HWC2_ERROR_BAD_PARAMETER: return "BadParameter";
+        case HWC2_ERROR_HAS_CHANGES: return "HasChanges";
+        case HWC2_ERROR_NO_RESOURCES: return "NoResources";
+        case HWC2_ERROR_NOT_VALIDATED: return "NotValidated";
+        case HWC2_ERROR_UNSUPPORTED: return "Unsupported";
+        case HWC2_ERROR_SEAMLESS_NOT_ALLOWED: return "SeamlessNotAllowed";
+        case HWC2_ERROR_SEAMLESS_NOT_POSSIBLE: return "SeamlessNotPossible";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getFunctionDescriptorName(
+        hwc2_function_descriptor_t desc) {
+    switch (desc) {
+        case HWC2_FUNCTION_INVALID: return "Invalid";
+        case HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES:
+            return "AcceptDisplayChanges";
+        case HWC2_FUNCTION_CREATE_LAYER: return "CreateLayer";
+        case HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY:
+            return "CreateVirtualDisplay";
+        case HWC2_FUNCTION_DESTROY_LAYER: return "DestroyLayer";
+        case HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY:
+            return "DestroyVirtualDisplay";
+        case HWC2_FUNCTION_DUMP: return "Dump";
+        case HWC2_FUNCTION_GET_ACTIVE_CONFIG: return "GetActiveConfig";
+        case HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES:
+            return "GetChangedCompositionTypes";
+        case HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT:
+            return "GetClientTargetSupport";
+        case HWC2_FUNCTION_GET_COLOR_MODES: return "GetColorModes";
+        case HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE: return "GetDisplayAttribute";
+        case HWC2_FUNCTION_GET_DISPLAY_CONFIGS: return "GetDisplayConfigs";
+        case HWC2_FUNCTION_GET_DISPLAY_NAME: return "GetDisplayName";
+        case HWC2_FUNCTION_GET_DISPLAY_REQUESTS: return "GetDisplayRequests";
+        case HWC2_FUNCTION_GET_DISPLAY_TYPE: return "GetDisplayType";
+        case HWC2_FUNCTION_GET_DOZE_SUPPORT: return "GetDozeSupport";
+        case HWC2_FUNCTION_GET_HDR_CAPABILITIES: return "GetHdrCapabilities";
+        case HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT:
+            return "GetMaxVirtualDisplayCount";
+        case HWC2_FUNCTION_GET_RELEASE_FENCES: return "GetReleaseFences";
+        case HWC2_FUNCTION_PRESENT_DISPLAY: return "PresentDisplay";
+        case HWC2_FUNCTION_REGISTER_CALLBACK: return "RegisterCallback";
+        case HWC2_FUNCTION_SET_ACTIVE_CONFIG: return "SetActiveConfig";
+        case HWC2_FUNCTION_SET_CLIENT_TARGET: return "SetClientTarget";
+        case HWC2_FUNCTION_SET_COLOR_MODE: return "SetColorMode";
+        case HWC2_FUNCTION_SET_COLOR_TRANSFORM: return "SetColorTransform";
+        case HWC2_FUNCTION_SET_CURSOR_POSITION: return "SetCursorPosition";
+        case HWC2_FUNCTION_SET_LAYER_BLEND_MODE: return "SetLayerBlendMode";
+        case HWC2_FUNCTION_SET_LAYER_BUFFER: return "SetLayerBuffer";
+        case HWC2_FUNCTION_SET_LAYER_COLOR: return "SetLayerColor";
+        case HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE:
+            return "SetLayerCompositionType";
+        case HWC2_FUNCTION_SET_LAYER_DATASPACE: return "SetLayerDataspace";
+        case HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME:
+            return "SetLayerDisplayFrame";
+        case HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA: return "SetLayerPlaneAlpha";
+        case HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM:
+            return "SetLayerSidebandStream";
+        case HWC2_FUNCTION_SET_LAYER_SOURCE_CROP: return "SetLayerSourceCrop";
+        case HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE:
+            return "SetLayerSurfaceDamage";
+        case HWC2_FUNCTION_SET_LAYER_TRANSFORM: return "SetLayerTransform";
+        case HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION:
+            return "SetLayerVisibleRegion";
+        case HWC2_FUNCTION_SET_LAYER_Z_ORDER: return "SetLayerZOrder";
+        case HWC2_FUNCTION_SET_OUTPUT_BUFFER: return "SetOutputBuffer";
+        case HWC2_FUNCTION_SET_POWER_MODE: return "SetPowerMode";
+        case HWC2_FUNCTION_SET_VSYNC_ENABLED: return "SetVsyncEnabled";
+        case HWC2_FUNCTION_VALIDATE_DISPLAY: return "ValidateDisplay";
+        case HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR: return "SetLayerFloatColor";
+        case HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA: return "SetLayerPerFrameMetadata";
+        case HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS: return "GetPerFrameMetadataKeys";
+        case HWC2_FUNCTION_SET_READBACK_BUFFER: return "SetReadbackBuffer";
+        case HWC2_FUNCTION_GET_READBACK_BUFFER_ATTRIBUTES: return "GetReadbackBufferAttributes";
+        case HWC2_FUNCTION_GET_READBACK_BUFFER_FENCE: return "GetReadbackBufferFence";
+        case HWC2_FUNCTION_GET_RENDER_INTENTS: return "GetRenderIntents";
+        case HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT: return "SetColorModeWithRenderIntent";
+        case HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX: return "GetDataspaceSaturationMatrix";
+
+        // composer 2.3
+        case HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA: return "GetDisplayIdentificationData";
+        case HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES: return "GetDisplayCapabilities";
+        case HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM: return "SetLayerColorTransform";
+        case HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: return "GetDisplayedContentSamplingAttributes";
+        case HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED: return "SetDisplayedContentSamplingEnabled";
+        case HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE: return "GetDisplayedContentSample";
+        case HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS: return "SetLayerPerFrameMetadataBlobs";
+        case HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT: return "GetDisplayBrightnessSupport";
+        case HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS: return "SetDisplayBrightness";
+
+        // composer 2.4
+        case HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE: return "GetDisplayConnectionType";
+        case HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD: return "GetDisplayVsyncPeriod";
+        case HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS: return "SetActiveConfigWithConstraints";
+        case HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE: return "SetAutoLowLatencyMode";
+        case HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES: return "GetSupportedContentTypes";
+        case HWC2_FUNCTION_SET_CONTENT_TYPE: return "SetContentType";
+        case HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY: return "GetClientTargetProperty";
+        case HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA: return "SetLayerGenericMetadata";
+        case HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY: return "GetLayerGenericMetadataKey";
+
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getLayerRequestName(hwc2_layer_request_t request) {
+    switch (__BIONIC_CAST(static_cast, int, request)) {
+        case 0: return "None";
+        case HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET: return "ClearClientTarget";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getPowerModeName(hwc2_power_mode_t mode) {
+    switch (mode) {
+        case HWC2_POWER_MODE_OFF: return "Off";
+        case HWC2_POWER_MODE_DOZE_SUSPEND: return "DozeSuspend";
+        case HWC2_POWER_MODE_DOZE: return "Doze";
+        case HWC2_POWER_MODE_ON: return "On";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getContentTypeName(hwc2_content_type_t contentType) {
+    switch(contentType) {
+        case HWC2_CONTENT_TYPE_NONE: return "None";
+        case HWC2_CONTENT_TYPE_GRAPHICS: return "Graphics";
+        case HWC2_CONTENT_TYPE_PHOTO: return "Photo";
+        case HWC2_CONTENT_TYPE_CINEMA: return "Cinema";
+        case HWC2_CONTENT_TYPE_GAME: return "Game";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getTransformName(hwc_transform_t transform) {
+    switch (__BIONIC_CAST(static_cast, int, transform)) {
+        case 0: return "None";
+        case HWC_TRANSFORM_FLIP_H: return "FlipH";
+        case HWC_TRANSFORM_FLIP_V: return "FlipV";
+        case HWC_TRANSFORM_ROT_90: return "Rotate90";
+        case HWC_TRANSFORM_ROT_180: return "Rotate180";
+        case HWC_TRANSFORM_ROT_270: return "Rotate270";
+        case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
+        case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getVsyncName(hwc2_vsync_t vsync) {
+    switch (vsync) {
+        case HWC2_VSYNC_INVALID: return "Invalid";
+        case HWC2_VSYNC_ENABLE: return "Enable";
+        case HWC2_VSYNC_DISABLE: return "Disable";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayedContentSamplingName(
+        hwc2_displayed_content_sampling_t sampling) {
+    switch (sampling) {
+        case HWC2_DISPLAYED_CONTENT_SAMPLING_INVALID: return "Invalid";
+        case HWC2_DISPLAYED_CONTENT_SAMPLING_ENABLE: return "Enable";
+        case HWC2_DISPLAYED_CONTENT_SAMPLING_DISABLE: return "Disable";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getFormatColorComponentName(hwc2_format_color_component_t component) {
+    switch (component) {
+        case HWC2_FORMAT_COMPONENT_0: return "FirstComponent";
+        case HWC2_FORMAT_COMPONENT_1: return "SecondComponent";
+        case HWC2_FORMAT_COMPONENT_2: return "ThirdComponent";
+        case HWC2_FORMAT_COMPONENT_3: return "FourthComponent";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayCapabilityName(hwc2_display_capability_t capability) {
+    switch (capability) {
+        case HWC2_DISPLAY_CAPABILITY_INVALID: return "Invalid";
+        case HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM:
+            return "SkipClientColorTransform";
+        case HWC2_DISPLAY_CAPABILITY_DOZE:
+            return "Doze";
+        case HWC2_DISPLAY_CAPABILITY_BRIGHTNESS:
+            return "Brightness";
+        case HWC2_DISPLAY_CAPABILITY_AUTO_LOW_LATENCY_MODE:
+            return "AutoLowLatencyMode";
+        default:
+            return "Unknown";
+    }
+}
+
+#define TO_STRING(E, T, printer) \
+    inline std::string to_string(E value) { return printer(value); } \
+    inline std::string to_string(T value) { return to_string(static_cast<E>(value)); }
+#else // !HWC2_INCLUDE_STRINGIFICATION
+#define TO_STRING(name, printer)
+#endif // HWC2_INCLUDE_STRINGIFICATION
+
+/*
+ * C++11 features
+ */
+
+#ifdef HWC2_USE_CPP11
+__END_DECLS
+
+#ifdef HWC2_INCLUDE_STRINGIFICATION
+#include <string>
+#endif
+
+namespace HWC2 {
+
+enum class Attribute : int32_t {
+    Invalid = HWC2_ATTRIBUTE_INVALID,
+    Width = HWC2_ATTRIBUTE_WIDTH,
+    Height = HWC2_ATTRIBUTE_HEIGHT,
+    VsyncPeriod = HWC2_ATTRIBUTE_VSYNC_PERIOD,
+    DpiX = HWC2_ATTRIBUTE_DPI_X,
+    DpiY = HWC2_ATTRIBUTE_DPI_Y,
+    ConfigGroup = HWC2_ATTRIBUTE_CONFIG_GROUP,
+};
+TO_STRING(hwc2_attribute_t, Attribute, getAttributeName)
+
+enum class BlendMode : int32_t {
+    Invalid = HWC2_BLEND_MODE_INVALID,
+    None = HWC2_BLEND_MODE_NONE,
+    Premultiplied = HWC2_BLEND_MODE_PREMULTIPLIED,
+    Coverage = HWC2_BLEND_MODE_COVERAGE,
+};
+TO_STRING(hwc2_blend_mode_t, BlendMode, getBlendModeName)
+
+enum class Callback : int32_t {
+    Invalid = HWC2_CALLBACK_INVALID,
+    Hotplug = HWC2_CALLBACK_HOTPLUG,
+    Refresh = HWC2_CALLBACK_REFRESH,
+    Vsync = HWC2_CALLBACK_VSYNC,
+    Vsync_2_4 = HWC2_CALLBACK_VSYNC_2_4,
+    VsyncPeriodTimingChanged = HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED,
+    SeamlessPossible = HWC2_CALLBACK_SEAMLESS_POSSIBLE,
+};
+TO_STRING(hwc2_callback_descriptor_t, Callback, getCallbackDescriptorName)
+
+enum class Capability : int32_t {
+    Invalid = HWC2_CAPABILITY_INVALID,
+    SidebandStream = HWC2_CAPABILITY_SIDEBAND_STREAM,
+    SkipClientColorTransform = HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM,
+    PresentFenceIsNotReliable = HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE,
+    SkipValidate = HWC2_CAPABILITY_SKIP_VALIDATE,
+};
+TO_STRING(hwc2_capability_t, Capability, getCapabilityName)
+
+enum class Composition : int32_t {
+    Invalid = HWC2_COMPOSITION_INVALID,
+    Client = HWC2_COMPOSITION_CLIENT,
+    Device = HWC2_COMPOSITION_DEVICE,
+    SolidColor = HWC2_COMPOSITION_SOLID_COLOR,
+    Cursor = HWC2_COMPOSITION_CURSOR,
+    Sideband = HWC2_COMPOSITION_SIDEBAND,
+};
+TO_STRING(hwc2_composition_t, Composition, getCompositionName)
+
+enum class Connection : int32_t {
+    Invalid = HWC2_CONNECTION_INVALID,
+    Connected = HWC2_CONNECTION_CONNECTED,
+    Disconnected = HWC2_CONNECTION_DISCONNECTED,
+};
+TO_STRING(hwc2_connection_t, Connection, getConnectionName)
+
+enum class DisplayRequest : int32_t {
+    FlipClientTarget = HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET,
+    WriteClientTargetToOutput =
+        HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT,
+};
+TO_STRING(hwc2_display_request_t, DisplayRequest, getDisplayRequestName)
+
+enum class DisplayType : int32_t {
+    Invalid = HWC2_DISPLAY_TYPE_INVALID,
+    Physical = HWC2_DISPLAY_TYPE_PHYSICAL,
+    Virtual = HWC2_DISPLAY_TYPE_VIRTUAL,
+};
+TO_STRING(hwc2_display_type_t, DisplayType, getDisplayTypeName)
+
+enum class DisplayConnectionType : uint32_t {
+    Internal = HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL,
+    External = HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL,
+};
+TO_STRING(hwc2_display_connection_type_t, DisplayConnectionType, getDisplayConnectionTypeName)
+
+enum class Error : int32_t {
+    None = HWC2_ERROR_NONE,
+    BadConfig = HWC2_ERROR_BAD_CONFIG,
+    BadDisplay = HWC2_ERROR_BAD_DISPLAY,
+    BadLayer = HWC2_ERROR_BAD_LAYER,
+    BadParameter = HWC2_ERROR_BAD_PARAMETER,
+    HasChanges = HWC2_ERROR_HAS_CHANGES,
+    NoResources = HWC2_ERROR_NO_RESOURCES,
+    NotValidated = HWC2_ERROR_NOT_VALIDATED,
+    Unsupported = HWC2_ERROR_UNSUPPORTED,
+    SeamlessNotAllowed = HWC2_ERROR_SEAMLESS_NOT_ALLOWED,
+    SeamlessNotPossible = HWC2_ERROR_SEAMLESS_NOT_POSSIBLE,
+};
+TO_STRING(hwc2_error_t, Error, getErrorName)
+
+enum class FunctionDescriptor : int32_t {
+    Invalid = HWC2_FUNCTION_INVALID,
+    AcceptDisplayChanges = HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES,
+    CreateLayer = HWC2_FUNCTION_CREATE_LAYER,
+    CreateVirtualDisplay = HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY,
+    DestroyLayer = HWC2_FUNCTION_DESTROY_LAYER,
+    DestroyVirtualDisplay = HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY,
+    Dump = HWC2_FUNCTION_DUMP,
+    GetActiveConfig = HWC2_FUNCTION_GET_ACTIVE_CONFIG,
+    GetChangedCompositionTypes = HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES,
+    GetClientTargetSupport = HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT,
+    GetColorModes = HWC2_FUNCTION_GET_COLOR_MODES,
+    GetDisplayAttribute = HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE,
+    GetDisplayConfigs = HWC2_FUNCTION_GET_DISPLAY_CONFIGS,
+    GetDisplayName = HWC2_FUNCTION_GET_DISPLAY_NAME,
+    GetDisplayRequests = HWC2_FUNCTION_GET_DISPLAY_REQUESTS,
+    GetDisplayType = HWC2_FUNCTION_GET_DISPLAY_TYPE,
+    GetDozeSupport = HWC2_FUNCTION_GET_DOZE_SUPPORT,
+    GetHdrCapabilities = HWC2_FUNCTION_GET_HDR_CAPABILITIES,
+    GetMaxVirtualDisplayCount = HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT,
+    GetReleaseFences = HWC2_FUNCTION_GET_RELEASE_FENCES,
+    PresentDisplay = HWC2_FUNCTION_PRESENT_DISPLAY,
+    RegisterCallback = HWC2_FUNCTION_REGISTER_CALLBACK,
+    SetActiveConfig = HWC2_FUNCTION_SET_ACTIVE_CONFIG,
+    SetClientTarget = HWC2_FUNCTION_SET_CLIENT_TARGET,
+    SetColorMode = HWC2_FUNCTION_SET_COLOR_MODE,
+    SetColorTransform = HWC2_FUNCTION_SET_COLOR_TRANSFORM,
+    SetCursorPosition = HWC2_FUNCTION_SET_CURSOR_POSITION,
+    SetLayerBlendMode = HWC2_FUNCTION_SET_LAYER_BLEND_MODE,
+    SetLayerBuffer = HWC2_FUNCTION_SET_LAYER_BUFFER,
+    SetLayerColor = HWC2_FUNCTION_SET_LAYER_COLOR,
+    SetLayerCompositionType = HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE,
+    SetLayerDataspace = HWC2_FUNCTION_SET_LAYER_DATASPACE,
+    SetLayerDisplayFrame = HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME,
+    SetLayerPlaneAlpha = HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA,
+    SetLayerSidebandStream = HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM,
+    SetLayerSourceCrop = HWC2_FUNCTION_SET_LAYER_SOURCE_CROP,
+    SetLayerSurfaceDamage = HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE,
+    SetLayerTransform = HWC2_FUNCTION_SET_LAYER_TRANSFORM,
+    SetLayerVisibleRegion = HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION,
+    SetLayerZOrder = HWC2_FUNCTION_SET_LAYER_Z_ORDER,
+    SetOutputBuffer = HWC2_FUNCTION_SET_OUTPUT_BUFFER,
+    SetPowerMode = HWC2_FUNCTION_SET_POWER_MODE,
+    SetVsyncEnabled = HWC2_FUNCTION_SET_VSYNC_ENABLED,
+    ValidateDisplay = HWC2_FUNCTION_VALIDATE_DISPLAY,
+    SetLayerFloatColor = HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR,
+    SetLayerPerFrameMetadata = HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA,
+    GetPerFrameMetadataKeys = HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS,
+    SetReadbackBuffer = HWC2_FUNCTION_SET_READBACK_BUFFER,
+    GetReadbackBufferAttributes = HWC2_FUNCTION_GET_READBACK_BUFFER_ATTRIBUTES,
+    GetReadbackBufferFence = HWC2_FUNCTION_GET_READBACK_BUFFER_FENCE,
+    GetRenderIntents = HWC2_FUNCTION_GET_RENDER_INTENTS,
+    SetColorModeWithRenderIntent = HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT,
+    GetDataspaceSaturationMatrix = HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX,
+
+    // composer 2.3
+    GetDisplayIdentificationData = HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA,
+    GetDisplayCapabilities = HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES,
+    SetLayerColorTransform = HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM,
+    GetDisplayedContentSamplingAttributes = HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES,
+    SetDisplayedContentSamplingEnabled = HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED,
+    GetDisplayedContentSample = HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE,
+    SetLayerPerFrameMetadataBlobs = HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS,
+    GetDisplayBrightnessSupport = HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT,
+    SetDisplayBrightness = HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS,
+
+    // composer 2.4
+    GetDisplayConnectionType = HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE,
+    GetDisplayVsyncPeriod = HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD,
+    SetActiveConfigWithConstraints = HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS,
+    SetAutoLowLatencyMode = HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE,
+    GetSupportedContentTypes = HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES,
+    SetContentType = HWC2_FUNCTION_SET_CONTENT_TYPE,
+    GetClientTargetProperty = HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY,
+    SetLayerGenericMetadata = HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA,
+    GetLayerGenericMetadataKey = HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY,
+};
+TO_STRING(hwc2_function_descriptor_t, FunctionDescriptor,
+        getFunctionDescriptorName)
+
+enum class LayerRequest : int32_t {
+    ClearClientTarget = HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET,
+};
+TO_STRING(hwc2_layer_request_t, LayerRequest, getLayerRequestName)
+
+enum class PowerMode : int32_t {
+    Off = HWC2_POWER_MODE_OFF,
+    DozeSuspend = HWC2_POWER_MODE_DOZE_SUSPEND,
+    Doze = HWC2_POWER_MODE_DOZE,
+    On = HWC2_POWER_MODE_ON,
+};
+TO_STRING(hwc2_power_mode_t, PowerMode, getPowerModeName)
+
+enum class ContentType : int32_t {
+    None = HWC2_CONTENT_TYPE_NONE,
+    Graphics = HWC2_CONTENT_TYPE_GRAPHICS,
+    Photo = HWC2_CONTENT_TYPE_PHOTO,
+    Cinema = HWC2_CONTENT_TYPE_CINEMA,
+    Game = HWC2_CONTENT_TYPE_GAME,
+};
+TO_STRING(hwc2_content_type_t, ContentType, getContentTypeName)
+
+enum class Transform : int32_t {
+    None = 0,
+    FlipH = HWC_TRANSFORM_FLIP_H,
+    FlipV = HWC_TRANSFORM_FLIP_V,
+    Rotate90 = HWC_TRANSFORM_ROT_90,
+    Rotate180 = HWC_TRANSFORM_ROT_180,
+    Rotate270 = HWC_TRANSFORM_ROT_270,
+    FlipHRotate90 = HWC_TRANSFORM_FLIP_H_ROT_90,
+    FlipVRotate90 = HWC_TRANSFORM_FLIP_V_ROT_90,
+};
+TO_STRING(hwc_transform_t, Transform, getTransformName)
+
+enum class Vsync : int32_t {
+    Invalid = HWC2_VSYNC_INVALID,
+    Enable = HWC2_VSYNC_ENABLE,
+    Disable = HWC2_VSYNC_DISABLE,
+};
+TO_STRING(hwc2_vsync_t, Vsync, getVsyncName)
+
+enum class DisplayCapability : int32_t {
+    Invalid = HWC2_DISPLAY_CAPABILITY_INVALID,
+    SkipClientColorTransform = HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM,
+    Doze = HWC2_DISPLAY_CAPABILITY_DOZE,
+    Brightness = HWC2_DISPLAY_CAPABILITY_BRIGHTNESS,
+    AutoLowLatencyMode = HWC2_DISPLAY_CAPABILITY_AUTO_LOW_LATENCY_MODE,
+};
+TO_STRING(hwc2_display_capability_t, DisplayCapability, getDisplayCapabilityName)
+
+} // namespace HWC2
+
+__BEGIN_DECLS
+#endif // HWC2_USE_CPP11
+
+/*
+ * Typedefs
+ */
+
+typedef void (*hwc2_function_pointer_t)();
+
+typedef void* hwc2_callback_data_t;
+typedef uint32_t hwc2_config_t;
+typedef uint64_t hwc2_display_t;
+typedef uint64_t hwc2_layer_t;
+typedef uint32_t hwc2_vsync_period_t;
+
+/*
+ * Device Struct
+ */
+
+typedef struct hwc2_device {
+    /* Must be the first member of this struct, since a pointer to this struct
+     * will be generated by casting from a hw_device_t* */
+    struct hw_device_t common;
+
+    /* getCapabilities(..., outCount, outCapabilities)
+     *
+     * Provides a list of capabilities (described in the definition of
+     * hwc2_capability_t above) supported by this device. This list must
+     * not change after the device has been loaded.
+     *
+     * Parameters:
+     *   outCount - if outCapabilities was NULL, the number of capabilities
+     *       which would have been returned; if outCapabilities was not NULL,
+     *       the number of capabilities returned, which must not exceed the
+     *       value stored in outCount prior to the call
+     *   outCapabilities - a list of capabilities supported by this device; may
+     *       be NULL, in which case this function must write into outCount the
+     *       number of capabilities which would have been written into
+     *       outCapabilities
+     */
+    void (*getCapabilities)(struct hwc2_device* device, uint32_t* outCount,
+            int32_t* /*hwc2_capability_t*/ outCapabilities);
+
+    /* getFunction(..., descriptor)
+     *
+     * Returns a function pointer which implements the requested description.
+     *
+     * Parameters:
+     *   descriptor - the function to return
+     *
+     * Returns either a function pointer implementing the requested descriptor
+     *   or NULL if the described function is not supported by this device.
+     */
+    hwc2_function_pointer_t (*getFunction)(struct hwc2_device* device,
+            int32_t /*hwc2_function_descriptor_t*/ descriptor);
+} hwc2_device_t;
+
+static inline int hwc2_open(const struct hw_module_t* module,
+        hwc2_device_t** device) {
+    return module->methods->open(module, HWC_HARDWARE_COMPOSER,
+            TO_HW_DEVICE_T_OPEN(device));
+}
+
+static inline int hwc2_close(hwc2_device_t* device) {
+    return device->common.close(&device->common);
+}
+
+/*
+ * Callbacks
+ *
+ * All of these callbacks take as their first parameter the callbackData which
+ * was provided at the time of callback registration, so this parameter is
+ * omitted from the described parameter lists.
+ */
+
+/* hotplug(..., display, connected)
+ * Descriptor: HWC2_CALLBACK_HOTPLUG
+ * Will be provided to all HWC2 devices
+ *
+ * Notifies the client that the given display has either been connected or
+ * disconnected. Every active display (even a built-in physical display) must
+ * trigger at least one hotplug notification, even if it only occurs immediately
+ * after callback registration.
+ *
+ * The client may call back into the device on the same thread to query display
+ * properties (such as width, height, and vsync period), and other threads may
+ * call into the device while the callback is in progress. The device must
+ * serialize calls to this callback such that only one thread is calling it at a
+ * time.
+ *
+ * Displays which have been connected are assumed to be in HWC2_POWER_MODE_OFF,
+ * and the vsync callback should not be called for a display until vsync has
+ * been enabled with setVsyncEnabled.
+ *
+ * Parameters:
+ *   display - the display which has been hotplugged
+ *   connected - whether the display has been connected or disconnected
+ */
+typedef void (*HWC2_PFN_HOTPLUG)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int32_t /*hwc2_connection_t*/ connected);
+
+/* refresh(..., display)
+ * Descriptor: HWC2_CALLBACK_REFRESH
+ * Will be provided to all HWC2 devices
+ *
+ * Notifies the client to trigger a screen refresh. This forces all layer state
+ * for this display to be resent, and the display to be validated and presented,
+ * even if there have been no changes.
+ *
+ * This refresh will occur some time after the callback is initiated, but not
+ * necessarily before it returns. This thread, however, is guaranteed not to
+ * call back into the device, thus it is safe to trigger this callback from
+ * other functions which call into the device.
+ *
+ * Parameters:
+ *   display - the display to refresh
+ */
+typedef void (*HWC2_PFN_REFRESH)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display);
+
+/* vsync(..., display, timestamp)
+ * Descriptor: HWC2_CALLBACK_VSYNC
+ * Will be provided to all HWC2 devices
+ *
+ * Notifies the client that a vsync event has occurred. This callback must
+ * only be triggered when vsync is enabled for this display (through
+ * setVsyncEnabled).
+ *
+ * This callback should be triggered from a thread of at least
+ * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically
+ * less than 0.5 ms. This thread is guaranteed not to call back into the device.
+ *
+ * Parameters:
+ *   display - the display which has received a vsync event
+ *   timestamp - the CLOCK_MONOTONIC time at which the vsync event occurred, in
+ *       nanoseconds
+ */
+typedef void (*HWC2_PFN_VSYNC)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int64_t timestamp);
+
+/* vsync_2_4(..., display, timestamp, vsyncPeriodNanos)
+ * Descriptor: HWC2_CALLBACK_VSYNC_2_4
+ * Required for HWC2 devices for composer 2.4
+ *
+ * Notifies the client that a vsync event has occurred. This callback must
+ * only be triggered when vsync is enabled for this display (through
+ * setVsyncEnabled).
+ *
+ * This callback should be triggered from a thread of at least
+ * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically
+ * less than 0.5 ms. This thread is guaranteed not to call back into the device.
+ *
+ * Parameters:
+ *   display - the display which has received a vsync event
+ *   timestamp - the CLOCK_MONOTONIC time at which the vsync event occurred, in
+ *       nanoseconds
+ *   vsyncPeriodNanos - the display vsync period in nanoseconds i.e. the next onVsync2_4 is
+ *   expected to be called vsyncPeriod nanoseconds after this call.
+ */
+typedef void (*HWC2_PFN_VSYNC_2_4)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int64_t timestamp, hwc2_vsync_period_t vsyncPeriodNanos);
+
+/* vsyncPeriodTimingChanged(..., display, updated_timeline)
+ * Descriptor: HWC2_CALLBACK_VSYNC_PERIOD_TIMING_CHANGED
+ * Optional for HWC2 devices for composer 2.4
+ *
+ * Notifies the client that the previously reported timing for vsync period change has been
+ * updated. This may occur if the composer missed the deadline for changing the vsync period
+ * or the client submitted a refresh frame too late.
+ *
+ * This callback should be triggered from a thread of at least
+ * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically
+ * less than 0.5 ms. This thread is guaranteed not to call back into the device.
+ *
+ * Parameters:
+ *   display - the display which has received a vsync event
+ *   updated_timeline - new timeline for the vsync period change
+ */
+typedef void (*HWC2_PFN_VSYNC_PERIOD_TIMING_CHANGED)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, hwc_vsync_period_change_timeline_t* updated_timeline);
+
+/* SeamlessPossible(..., display)
+ * Descriptor: HWC2_CALLBACK_SEAMLESS_POSSIBLE
+ * Optional for HWC2 devices for composer 2.4
+ *
+ * Notifies the client that the conditions which previously led to returning SEAMLESS_NOT_POSSIBLE
+ * from setActiveConfigWithConstraints have changed and now seamless may be possible. Client should
+ * retry calling setActiveConfigWithConstraints.
+ *
+ *
+ * Parameters:
+ *   display - a display setActiveConfigWithConstraints previously failed with
+ *             SEAMLESS_NOT_POSSIBLE.
+ */
+typedef void (*HWC2_PFN_SEAMLESS_POSSIBLE)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display);
+
+/*
+ * Device Functions
+ *
+ * All of these functions take as their first parameter a device pointer, so
+ * this parameter is omitted from the described parameter lists.
+ */
+
+/* createVirtualDisplay(..., width, height, format, outDisplay)
+ * Descriptor: HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Creates a new virtual display with the given width and height. The format
+ * passed into this function is the default format requested by the consumer of
+ * the virtual display output buffers. If a different format will be returned by
+ * the device, it should be returned in this parameter so it can be set properly
+ * when handing the buffers to the consumer.
+ *
+ * The display will be assumed to be on from the time the first frame is
+ * presented until the display is destroyed.
+ *
+ * Parameters:
+ *   width - width in pixels
+ *   height - height in pixels
+ *   format - prior to the call, the default output buffer format selected by
+ *       the consumer; after the call, the format the device will produce
+ *   outDisplay - the newly-created virtual display; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_UNSUPPORTED - the width or height is too large for the device to
+ *       be able to create a virtual display
+ *   HWC2_ERROR_NO_RESOURCES - the device is unable to create a new virtual
+ *       display at this time
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_CREATE_VIRTUAL_DISPLAY)(
+        hwc2_device_t* device, uint32_t width, uint32_t height,
+        int32_t* /*android_pixel_format_t*/ format, hwc2_display_t* outDisplay);
+
+/* destroyVirtualDisplay(..., display)
+ * Descriptor: HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Destroys a virtual display. After this call all resources consumed by this
+ * display may be freed by the device and any operations performed on this
+ * display should fail.
+ *
+ * Parameters:
+ *   display - the virtual display to destroy
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the display handle which was passed in does not
+ *       refer to a virtual display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_DESTROY_VIRTUAL_DISPLAY)(
+        hwc2_device_t* device, hwc2_display_t display);
+
+/* dump(..., outSize, outBuffer)
+ * Descriptor: HWC2_FUNCTION_DUMP
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves implementation-defined debug information, which will be displayed
+ * during, for example, `dumpsys SurfaceFlinger`.
+ *
+ * If called with outBuffer == NULL, the device should store a copy of the
+ * desired output and return its length in bytes in outSize. If the device
+ * already has a stored copy, that copy should be purged and replaced with a
+ * fresh copy.
+ *
+ * If called with outBuffer != NULL, the device should copy its stored version
+ * of the output into outBuffer and store how many bytes of data it copied into
+ * outSize. Prior to this call, the client will have populated outSize with the
+ * maximum number of bytes outBuffer can hold. The device must not write more
+ * than this amount into outBuffer. If the device does not currently have a
+ * stored copy, then it should return 0 in outSize.
+ *
+ * Any data written into outBuffer need not be null-terminated.
+ *
+ * Parameters:
+ *   outSize - if outBuffer was NULL, the number of bytes needed to copy the
+ *       device's stored output; if outBuffer was not NULL, the number of bytes
+ *       written into it, which must not exceed the value stored in outSize
+ *       prior to the call; pointer will be non-NULL
+ *   outBuffer - the buffer to write the dump output into; may be NULL as
+ *       described above; data written into this buffer need not be
+ *       null-terminated
+ */
+typedef void (*HWC2_PFN_DUMP)(hwc2_device_t* device, uint32_t* outSize,
+        char* outBuffer);
+
+/* getMaxVirtualDisplayCount(...)
+ * Descriptor: HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the maximum number of virtual displays supported by this device
+ * (which may be 0). The client will not attempt to create more than this many
+ * virtual displays on this device. This number must not change for the lifetime
+ * of the device.
+ */
+typedef uint32_t (*HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT)(
+        hwc2_device_t* device);
+
+/* registerCallback(..., descriptor, callbackData, pointer)
+ * Descriptor: HWC2_FUNCTION_REGISTER_CALLBACK
+ * Must be provided by all HWC2 devices
+ *
+ * Provides a callback for the device to call. All callbacks take a callbackData
+ * item as the first parameter, so this value should be stored with the callback
+ * for later use. The callbackData may differ from one callback to another. If
+ * this function is called multiple times with the same descriptor, later
+ * callbacks replace earlier ones.
+ *
+ * Parameters:
+ *   descriptor - which callback should be set
+ *   callBackdata - opaque data which must be passed back through the callback
+ *   pointer - a non-NULL function pointer corresponding to the descriptor
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_PARAMETER - descriptor was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_REGISTER_CALLBACK)(
+        hwc2_device_t* device,
+        int32_t /*hwc2_callback_descriptor_t*/ descriptor,
+        hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer);
+
+/* getDataspaceSaturationMatrix(..., dataspace, outMatrix)
+ * Descriptor: HWC2_FUNCTION_GET_DATASPACE_SATURATION_MATRIX
+ * Provided by HWC2 devices which don't return nullptr function pointer.
+ *
+ * Get the saturation matrix of the specified dataspace. The saturation matrix
+ * can be used to approximate the dataspace saturation operation performed by
+ * the HWC2 device when non-colorimetric mapping is allowed. It is to be
+ * applied on linear pixel values.
+ *
+ * Parameters:
+ *   dataspace - the dataspace to query for
+ *   outMatrix - a column-major 4x4 matrix (16 floats). It must be an identity
+ *       matrix unless dataspace is HAL_DATASPACE_SRGB_LINEAR.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_PARAMETER - dataspace was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DATASPACE_SATURATION_MATRIX)(
+        hwc2_device_t* device, int32_t /*android_dataspace_t*/ dataspace,
+        float* outMatrix);
+
+/*
+ * Display Functions
+ *
+ * All of these functions take as their first two parameters a device pointer
+ * and a display handle, so these parameters are omitted from the described
+ * parameter lists.
+ */
+
+/* acceptDisplayChanges(...)
+ * Descriptor: HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES
+ * Must be provided by all HWC2 devices
+ *
+ * Accepts the changes required by the device from the previous validateDisplay
+ * call (which may be queried using getChangedCompositionTypes) and revalidates
+ * the display. This function is equivalent to requesting the changed types from
+ * getChangedCompositionTypes, setting those types on the corresponding layers,
+ * and then calling validateDisplay again.
+ *
+ * After this call it must be valid to present this display. Calling this after
+ * validateDisplay returns 0 changes must succeed with HWC2_ERROR_NONE, but
+ * should have no other effect.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_ACCEPT_DISPLAY_CHANGES)(
+        hwc2_device_t* device, hwc2_display_t display);
+
+/* createLayer(..., outLayer)
+ * Descriptor: HWC2_FUNCTION_CREATE_LAYER
+ * Must be provided by all HWC2 devices
+ *
+ * Creates a new layer on the given display.
+ *
+ * Parameters:
+ *   outLayer - the handle of the new layer; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NO_RESOURCES - the device was unable to create this layer
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_CREATE_LAYER)(hwc2_device_t* device,
+        hwc2_display_t display, hwc2_layer_t* outLayer);
+
+/* destroyLayer(..., layer)
+ * Descriptor: HWC2_FUNCTION_DESTROY_LAYER
+ * Must be provided by all HWC2 devices
+ *
+ * Destroys the given layer.
+ *
+ * Parameters:
+ *   layer - the handle of the layer to destroy
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_DESTROY_LAYER)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer);
+
+/* getActiveConfig(..., outConfig)
+ * Descriptor: HWC2_FUNCTION_GET_ACTIVE_CONFIG
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves which display configuration is currently active.
+ *
+ * If no display configuration is currently active, this function must return
+ * HWC2_ERROR_BAD_CONFIG and place no configuration handle in outConfig. It is
+ * the responsibility of the client to call setActiveConfig with a valid
+ * configuration before attempting to present anything on the display.
+ *
+ * Parameters:
+ *   outConfig - the currently active display configuration; pointer will be
+ *       non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - no configuration is currently active
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_ACTIVE_CONFIG)(
+        hwc2_device_t* device, hwc2_display_t display,
+        hwc2_config_t* outConfig);
+
+/* getChangedCompositionTypes(..., outNumElements, outLayers, outTypes)
+ * Descriptor: HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves the layers for which the device requires a different composition
+ * type than had been set prior to the last call to validateDisplay. The client
+ * will either update its state with these types and call acceptDisplayChanges,
+ * or will set new types and attempt to validate the display again.
+ *
+ * outLayers and outTypes may be NULL to retrieve the number of elements which
+ * will be returned. The number of elements returned must be the same as the
+ * value returned in outNumTypes from the last call to validateDisplay.
+ *
+ * Parameters:
+ *   outNumElements - if outLayers or outTypes were NULL, the number of layers
+ *       and types which would have been returned; if both were non-NULL, the
+ *       number of elements returned in outLayers and outTypes, which must not
+ *       exceed the value stored in outNumElements prior to the call; pointer
+ *       will be non-NULL
+ *   outLayers - an array of layer handles
+ *   outTypes - an array of composition types, each corresponding to an element
+ *       of outLayers
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES)(
+        hwc2_device_t* device, hwc2_display_t display,
+        uint32_t* outNumElements, hwc2_layer_t* outLayers,
+        int32_t* /*hwc2_composition_t*/ outTypes);
+
+/* getClientTargetSupport(..., width, height, format, dataspace)
+ * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT
+ * Must be provided by all HWC2 devices
+ *
+ * Returns whether a client target with the given properties can be handled by
+ * the device.
+ *
+ * The valid formats can be found in android_pixel_format_t in
+ * <system/graphics.h>.
+ *
+ * For more about dataspaces, see setLayerDataspace.
+ *
+ * This function must return true for a client target with width and height
+ * equal to the active display configuration dimensions,
+ * HAL_PIXEL_FORMAT_RGBA_8888, and HAL_DATASPACE_UNKNOWN. It is not required to
+ * return true for any other configuration.
+ *
+ * Parameters:
+ *   width - client target width in pixels
+ *   height - client target height in pixels
+ *   format - client target format
+ *   dataspace - client target dataspace, as described in setLayerDataspace
+ *
+ * Returns HWC2_ERROR_NONE if the given configuration is supported or one of the
+ * following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_UNSUPPORTED - the given configuration is not supported
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CLIENT_TARGET_SUPPORT)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t width,
+        uint32_t height, int32_t /*android_pixel_format_t*/ format,
+        int32_t /*android_dataspace_t*/ dataspace);
+
+/* getColorModes(..., outNumModes, outModes)
+ * Descriptor: HWC2_FUNCTION_GET_COLOR_MODES
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the color modes supported on this display.
+ *
+ * The valid color modes can be found in android_color_mode_t in
+ * <system/graphics.h>. All HWC2 devices must support at least
+ * HAL_COLOR_MODE_NATIVE.
+ *
+ * outNumModes may be NULL to retrieve the number of modes which will be
+ * returned.
+ *
+ * Parameters:
+ *   outNumModes - if outModes was NULL, the number of modes which would have
+ *       been returned; if outModes was not NULL, the number of modes returned,
+ *       which must not exceed the value stored in outNumModes prior to the
+ *       call; pointer will be non-NULL
+ *   outModes - an array of color modes
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_COLOR_MODES)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumModes,
+        int32_t* /*android_color_mode_t*/ outModes);
+
+/* getRenderIntents(..., mode, outNumIntents, outIntents)
+ * Descriptor: HWC2_FUNCTION_GET_RENDER_INTENTS
+ * Provided by HWC2 devices which don't return nullptr function pointer.
+ *
+ * Returns the render intents supported on this display.
+ *
+ * The valid render intents can be found in android_render_intent_v1_1_t in
+ * <system/graphics.h>. All HWC2 devices must support at least
+ * HAL_RENDER_INTENT_COLORIMETRIC.
+ *
+ * outNumIntents may be NULL to retrieve the number of intents which will be
+ * returned.
+ *
+ * Parameters:
+ *   mode - the color mode to query the render intents for
+ *   outNumIntents - if outIntents was NULL, the number of intents which would
+ *       have been returned; if outIntents was not NULL, the number of intents
+ *       returned, which must not exceed the value stored in outNumIntents
+ *       prior to the call; pointer will be non-NULL
+ *   outIntents - an array of render intents
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_RENDER_INTENTS)(
+        hwc2_device_t* device, hwc2_display_t display, int32_t mode,
+        uint32_t* outNumIntents,
+        int32_t* /*android_render_intent_v1_1_t*/ outIntents);
+
+/* getDisplayAttribute(..., config, attribute, outValue)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE
+ * Must be provided by all HWC2 devices
+ *
+ * Returns a display attribute value for a particular display configuration.
+ *
+ * Any attribute which is not supported or for which the value is unknown by the
+ * device must return a value of -1.
+ *
+ * Parameters:
+ *   config - the display configuration for which to return attribute values
+ *   attribute - the attribute to query
+ *   outValue - the value of the attribute; the pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - config does not name a valid configuration for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_ATTRIBUTE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config,
+        int32_t /*hwc2_attribute_t*/ attribute, int32_t* outValue);
+
+/* getDisplayConfigs(..., outNumConfigs, outConfigs)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONFIGS
+ * Must be provided by all HWC2 devices
+ *
+ * Returns handles for all of the valid display configurations on this display.
+ *
+ * outConfigs may be NULL to retrieve the number of elements which will be
+ * returned.
+ *
+ * Parameters:
+ *   outNumConfigs - if outConfigs was NULL, the number of configurations which
+ *       would have been returned; if outConfigs was not NULL, the number of
+ *       configurations returned, which must not exceed the value stored in
+ *       outNumConfigs prior to the call; pointer will be non-NULL
+ *   outConfigs - an array of configuration handles
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CONFIGS)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumConfigs,
+        hwc2_config_t* outConfigs);
+
+/* getDisplayName(..., outSize, outName)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_NAME
+ * Must be provided by all HWC2 devices
+ *
+ * Returns a human-readable version of the display's name.
+ *
+ * outName may be NULL to retrieve the length of the name.
+ *
+ * Parameters:
+ *   outSize - if outName was NULL, the number of bytes needed to return the
+ *       name if outName was not NULL, the number of bytes written into it,
+ *       which must not exceed the value stored in outSize prior to the call;
+ *       pointer will be non-NULL
+ *   outName - the display's name
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_NAME)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outSize,
+        char* outName);
+
+/* getDisplayRequests(..., outDisplayRequests, outNumElements, outLayers,
+ *     outLayerRequests)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_REQUESTS
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the display requests and the layer requests required for the last
+ * validated configuration.
+ *
+ * Display requests provide information about how the client should handle the
+ * client target. Layer requests provide information about how the client
+ * should handle an individual layer.
+ *
+ * If outLayers or outLayerRequests is NULL, the required number of layers and
+ * requests must be returned in outNumElements, but this number may also be
+ * obtained from validateDisplay as outNumRequests (outNumElements must be equal
+ * to the value returned in outNumRequests from the last call to
+ * validateDisplay).
+ *
+ * Parameters:
+ *   outDisplayRequests - the display requests for the current validated state
+ *   outNumElements - if outLayers or outLayerRequests were NULL, the number of
+ *       elements which would have been returned, which must be equal to the
+ *       value returned in outNumRequests from the last validateDisplay call on
+ *       this display; if both were not NULL, the number of elements in
+ *       outLayers and outLayerRequests, which must not exceed the value stored
+ *       in outNumElements prior to the call; pointer will be non-NULL
+ *   outLayers - an array of layers which all have at least one request
+ *   outLayerRequests - the requests corresponding to each element of outLayers
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_REQUESTS)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* /*hwc2_display_request_t*/ outDisplayRequests,
+        uint32_t* outNumElements, hwc2_layer_t* outLayers,
+        int32_t* /*hwc2_layer_request_t*/ outLayerRequests);
+
+/* getDisplayType(..., outType)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_TYPE
+ * Must be provided by all HWC2 devices
+ *
+ * Returns whether the given display is a physical or virtual display.
+ *
+ * Parameters:
+ *   outType - the type of the display; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_TYPE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* /*hwc2_display_type_t*/ outType);
+
+/* getDisplayIdentificationData(..., outPort, outDataSize, outData)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA
+ * Optional for HWC2 devices
+ *
+ * If supported, getDisplayIdentificationData returns the port and data that
+ * describe a physical display. The port is a unique number that identifies a
+ * physical connector (e.g. eDP, HDMI) for display output. The data blob is
+ * parsed to determine its format, typically EDID 1.3 as specified in VESA
+ * E-EDID Standard Release A Revision 1.
+ *
+ * Devices for which display identification is unsupported must return null when
+ * getFunction is called with HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA.
+ *
+ * Parameters:
+ *   outPort - the connector to which the display is connected;
+ *             pointer will be non-NULL
+ *   outDataSize - if outData is NULL, the size in bytes of the data which would
+ *       have been returned; if outData is not NULL, the size of outData, which
+ *       must not exceed the value stored in outDataSize prior to the call;
+ *       pointer will be non-NULL
+ *   outData - the EDID 1.3 blob identifying the display
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_IDENTIFICATION_DATA)(
+        hwc2_device_t* device, hwc2_display_t display, uint8_t* outPort,
+        uint32_t* outDataSize, uint8_t* outData);
+
+/* getDozeSupport(..., outSupport)
+ * Descriptor: HWC2_FUNCTION_GET_DOZE_SUPPORT
+ * Must be provided by all HWC2 devices
+ *
+ * Returns whether the given display supports HWC2_POWER_MODE_DOZE and
+ * HWC2_POWER_MODE_DOZE_SUSPEND. DOZE_SUSPEND may not provide any benefit over
+ * DOZE (see the definition of hwc2_power_mode_t for more information), but if
+ * both DOZE and DOZE_SUSPEND are no different from HWC2_POWER_MODE_ON, the
+ * device should not claim support.
+ *
+ * Parameters:
+ *   outSupport - whether the display supports doze modes (1 for yes, 0 for no);
+ *       pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DOZE_SUPPORT)(
+        hwc2_device_t* device, hwc2_display_t display, int32_t* outSupport);
+
+/* getHdrCapabilities(..., outNumTypes, outTypes, outMaxLuminance,
+ *     outMaxAverageLuminance, outMinLuminance)
+ * Descriptor: HWC2_FUNCTION_GET_HDR_CAPABILITIES
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the high dynamic range (HDR) capabilities of the given display, which
+ * are invariant with regard to the active configuration.
+ *
+ * Displays which are not HDR-capable must return no types in outTypes and set
+ * outNumTypes to 0.
+ *
+ * If outTypes is NULL, the required number of HDR types must be returned in
+ * outNumTypes.
+ *
+ * Parameters:
+ *   outNumTypes - if outTypes was NULL, the number of types which would have
+ *       been returned; if it was not NULL, the number of types stored in
+ *       outTypes, which must not exceed the value stored in outNumTypes prior
+ *       to the call; pointer will be non-NULL
+ *   outTypes - an array of HDR types, may have 0 elements if the display is not
+ *       HDR-capable
+ *   outMaxLuminance - the desired content maximum luminance for this display in
+ *       cd/m^2; pointer will be non-NULL
+ *   outMaxAverageLuminance - the desired content maximum frame-average
+ *       luminance for this display in cd/m^2; pointer will be non-NULL
+ *   outMinLuminance - the desired content minimum luminance for this display in
+ *       cd/m^2; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_HDR_CAPABILITIES)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumTypes,
+        int32_t* /*android_hdr_t*/ outTypes, float* outMaxLuminance,
+        float* outMaxAverageLuminance, float* outMinLuminance);
+
+/* getReleaseFences(..., outNumElements, outLayers, outFences)
+ * Descriptor: HWC2_FUNCTION_GET_RELEASE_FENCES
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves the release fences for device layers on this display which will
+ * receive new buffer contents this frame.
+ *
+ * A release fence is a file descriptor referring to a sync fence object which
+ * will be signaled after the device has finished reading from the buffer
+ * presented in the prior frame. This indicates that it is safe to start writing
+ * to the buffer again. If a given layer's fence is not returned from this
+ * function, it will be assumed that the buffer presented on the previous frame
+ * is ready to be written.
+ *
+ * The fences returned by this function should be unique for each layer (even if
+ * they point to the same underlying sync object), and ownership of the fences
+ * is transferred to the client, which is responsible for closing them.
+ *
+ * If outLayers or outFences is NULL, the required number of layers and fences
+ * must be returned in outNumElements.
+ *
+ * Parameters:
+ *   outNumElements - if outLayers or outFences were NULL, the number of
+ *       elements which would have been returned; if both were not NULL, the
+ *       number of elements in outLayers and outFences, which must not exceed
+ *       the value stored in outNumElements prior to the call; pointer will be
+ *       non-NULL
+ *   outLayers - an array of layer handles
+ *   outFences - an array of sync fence file descriptors as described above,
+ *       each corresponding to an element of outLayers
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_RELEASE_FENCES)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumElements,
+        hwc2_layer_t* outLayers, int32_t* outFences);
+
+/* presentDisplay(..., outPresentFence)
+ * Descriptor: HWC2_FUNCTION_PRESENT_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Presents the current display contents on the screen (or in the case of
+ * virtual displays, into the output buffer).
+ *
+ * Prior to calling this function, the display must be successfully validated
+ * with validateDisplay. Note that setLayerBuffer and setLayerSurfaceDamage
+ * specifically do not count as layer state, so if there are no other changes
+ * to the layer state (or to the buffer's properties as described in
+ * setLayerBuffer), then it is safe to call this function without first
+ * validating the display.
+ *
+ * If this call succeeds, outPresentFence will be populated with a file
+ * descriptor referring to a present sync fence object. For physical displays,
+ * this fence will be signaled at the vsync when the result of composition of
+ * this frame starts to appear (for video-mode panels) or starts to transfer to
+ * panel memory (for command-mode panels). For virtual displays, this fence will
+ * be signaled when writes to the output buffer have completed and it is safe to
+ * read from it.
+ *
+ * Parameters:
+ *   outPresentFence - a sync fence file descriptor as described above; pointer
+ *       will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NO_RESOURCES - no valid output buffer has been set for a virtual
+ *       display
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not successfully been called
+ *       for this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_PRESENT_DISPLAY)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* outPresentFence);
+
+/* setActiveConfig(..., config)
+ * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the active configuration for this display. Upon returning, the given
+ * display configuration should be active and remain so until either this
+ * function is called again or the display is disconnected.
+ *
+ * Parameters:
+ *   config - the new display configuration
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - the configuration handle passed in is not valid for
+ *       this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_ACTIVE_CONFIG)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config);
+
+/* setClientTarget(..., target, acquireFence, dataspace, damage)
+ * Descriptor: HWC2_FUNCTION_SET_CLIENT_TARGET
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the buffer handle which will receive the output of client composition.
+ * Layers marked as HWC2_COMPOSITION_CLIENT will be composited into this buffer
+ * prior to the call to presentDisplay, and layers not marked as
+ * HWC2_COMPOSITION_CLIENT should be composited with this buffer by the device.
+ *
+ * The buffer handle provided may be null if no layers are being composited by
+ * the client. This must not result in an error (unless an invalid display
+ * handle is also provided).
+ *
+ * Also provides a file descriptor referring to an acquire sync fence object,
+ * which will be signaled when it is safe to read from the client target buffer.
+ * If it is already safe to read from this buffer, -1 may be passed instead.
+ * The device must ensure that it is safe for the client to close this file
+ * descriptor at any point after this function is called.
+ *
+ * For more about dataspaces, see setLayerDataspace.
+ *
+ * The damage parameter describes a surface damage region as defined in the
+ * description of setLayerSurfaceDamage.
+ *
+ * Will be called before presentDisplay if any of the layers are marked as
+ * HWC2_COMPOSITION_CLIENT. If no layers are so marked, then it is not
+ * necessary to call this function. It is not necessary to call validateDisplay
+ * after changing the target through this function.
+ *
+ * Parameters:
+ *   target - the new target buffer
+ *   acquireFence - a sync fence file descriptor as described above
+ *   dataspace - the dataspace of the buffer, as described in setLayerDataspace
+ *   damage - the surface damage region
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the new target handle was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_CLIENT_TARGET)(
+        hwc2_device_t* device, hwc2_display_t display, buffer_handle_t target,
+        int32_t acquireFence, int32_t /*android_dataspace_t*/ dataspace,
+        hwc_region_t damage);
+
+/* setColorMode(..., mode)
+ * Descriptor: HWC2_FUNCTION_SET_COLOR_MODE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the color mode of the given display.
+ *
+ * This must be called outside of validateDisplay/presentDisplay, and it takes
+ * effect on next presentDisplay.
+ *
+ * The valid color modes can be found in android_color_mode_t in
+ * <system/graphics.h>. All HWC2 devices must support at least
+ * HAL_COLOR_MODE_NATIVE, and displays are assumed to be in this mode upon
+ * hotplug.
+ *
+ * Parameters:
+ *   mode - the mode to set
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - mode is not a valid color mode
+ *   HWC2_ERROR_UNSUPPORTED - mode is not supported on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_MODE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*android_color_mode_t*/ mode);
+
+/* setColorModeWithIntent(..., mode, intent)
+ * Descriptor: HWC2_FUNCTION_SET_COLOR_MODE_WITH_RENDER_INTENT
+ * Provided by HWC2 devices which don't return nullptr function pointer.
+ *
+ * This must be called outside of validateDisplay/presentDisplay, and it takes
+ * effect on next presentDisplay.
+ *
+ * The valid color modes and render intents can be found in
+ * android_color_mode_t and android_render_intent_v1_1_t in
+ * <system/graphics.h>. All HWC2 devices must support at least
+ * HAL_COLOR_MODE_NATIVE and HAL_RENDER_INTENT_COLORIMETRIC, and displays are
+ * assumed to be in this mode and intent upon hotplug.
+ *
+ * Parameters:
+ *   mode - the mode to set
+ *   intent - the intent to set
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - mode/intent is not a valid color mode or
+ *       render intent
+ *   HWC2_ERROR_UNSUPPORTED - mode or intent is not supported on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_MODE_WITH_RENDER_INTENT)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*android_color_mode_t*/ mode,
+        int32_t /*android_render_intent_v1_1_t */ intent);
+
+/* setColorTransform(..., matrix, hint)
+ * Descriptor: HWC2_FUNCTION_SET_COLOR_TRANSFORM
+ * Must be provided by all HWC2 devices
+ *
+ * Sets a color transform which will be applied after composition.
+ *
+ * If hint is not HAL_COLOR_TRANSFORM_ARBITRARY, then the device may use the
+ * hint to apply the desired color transform instead of using the color matrix
+ * directly.
+ *
+ * If the device is not capable of either using the hint or the matrix to apply
+ * the desired color transform, it should force all layers to client composition
+ * during validateDisplay.
+ *
+ * If HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM is present, then the client
+ * will never apply the color transform during client composition, even if all
+ * layers are being composed by the client.
+ *
+ * The matrix provided is an affine color transformation of the following form:
+ *
+ * |r.r r.g r.b 0|
+ * |g.r g.g g.b 0|
+ * |b.r b.g b.b 0|
+ * |Tr  Tg  Tb  1|
+ *
+ * This matrix will be provided in row-major form: {r.r, r.g, r.b, 0, g.r, ...}.
+ *
+ * Given a matrix of this form and an input color [R_in, G_in, B_in], the output
+ * color [R_out, G_out, B_out] will be:
+ *
+ * R_out = R_in * r.r + G_in * g.r + B_in * b.r + Tr
+ * G_out = R_in * r.g + G_in * g.g + B_in * b.g + Tg
+ * B_out = R_in * r.b + G_in * g.b + B_in * b.b + Tb
+ *
+ * Parameters:
+ *   matrix - a 4x4 transform matrix (16 floats) as described above
+ *   hint - a hint value which may be used instead of the given matrix unless it
+ *       is HAL_COLOR_TRANSFORM_ARBITRARY
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - hint is not a valid color transform hint
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_TRANSFORM)(
+        hwc2_device_t* device, hwc2_display_t display, const float* matrix,
+        int32_t /*android_color_transform_t*/ hint);
+
+/* getPerFrameMetadataKeys(..., outKeys)
+ * Descriptor: HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS
+ * Optional for HWC2 devices
+ *
+ * If supported (getFunction(HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS) is non-null),
+ * getPerFrameMetadataKeys returns the list of supported PerFrameMetadataKeys
+ * which are invariant with regard to the active configuration.
+ *
+ * Devices which are not HDR-capable, must return null when getFunction is called
+ * with HWC2_FUNCTION_GET_PER_FRAME_METADATA_KEYS.
+ *
+ * If outKeys is NULL, the required number of PerFrameMetadataKey keys
+ * must be returned in outNumKeys.
+ *
+ * Parameters:
+ *   outNumKeys - if outKeys is NULL, the number of keys which would have
+ *       been returned; if outKeys is not NULL, the number of keys stored in
+ *       outKeys, which must not exceed the value stored in outNumKeys prior
+ *       to the call; pointer will be non-NULL
+ *   outKeys - an array of hwc2_per_frame_metadata_key_t keys
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_PER_FRAME_METADATA_KEYS)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumKeys,
+        int32_t* /*hwc2_per_frame_metadata_key_t*/ outKeys);
+
+/* setOutputBuffer(..., buffer, releaseFence)
+ * Descriptor: HWC2_FUNCTION_SET_OUTPUT_BUFFER
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the output buffer for a virtual display. That is, the buffer to which
+ * the composition result will be written.
+ *
+ * Also provides a file descriptor referring to a release sync fence object,
+ * which will be signaled when it is safe to write to the output buffer. If it
+ * is already safe to write to the output buffer, -1 may be passed instead. The
+ * device must ensure that it is safe for the client to close this file
+ * descriptor at any point after this function is called.
+ *
+ * Must be called at least once before presentDisplay, but does not have any
+ * interaction with layer state or display validation.
+ *
+ * Parameters:
+ *   buffer - the new output buffer
+ *   releaseFence - a sync fence file descriptor as described above
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the new output buffer handle was invalid
+ *   HWC2_ERROR_UNSUPPORTED - display does not refer to a virtual display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_OUTPUT_BUFFER)(
+        hwc2_device_t* device, hwc2_display_t display, buffer_handle_t buffer,
+        int32_t releaseFence);
+
+/* setPowerMode(..., mode)
+ * Descriptor: HWC2_FUNCTION_SET_POWER_MODE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the power mode of the given display. The transition must be complete
+ * when this function returns. It is valid to call this function multiple times
+ * with the same power mode.
+ *
+ * All displays must support HWC2_POWER_MODE_ON and HWC2_POWER_MODE_OFF. Whether
+ * a display supports HWC2_POWER_MODE_DOZE or HWC2_POWER_MODE_DOZE_SUSPEND may
+ * be queried using getDozeSupport.
+ *
+ * Parameters:
+ *   mode - the new power mode
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - mode was not a valid power mode
+ *   HWC2_ERROR_UNSUPPORTED - mode was a valid power mode, but is not supported
+ *       on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_POWER_MODE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*hwc2_power_mode_t*/ mode);
+
+/* getReadbackBufferAttributes(..., outFormat, outDataspace)
+ * Optional for HWC2 devices
+ *
+ * Returns the format which should be used when allocating a buffer for use by
+ * device readback as well as the dataspace in which its contents should be
+ * interpreted.
+ *
+ * If readback is not supported by this HWC implementation, this call will also
+ * be able to return HWC2_ERROR_UNSUPPORTED so we can fall back to another method.
+ * Returning NULL to a getFunction request for this function will also indicate
+ * that readback is not supported.
+ *
+ * The width and height of this buffer will be those of the currently-active
+ * display configuration, and the usage flags will consist of the following:
+ *   BufferUsage::CPU_READ | BufferUsage::GPU_TEXTURE |
+ *   BufferUsage::COMPOSER_OUTPUT
+ *
+ * The format and dataspace provided must be sufficient such that if a
+ * correctly-configured buffer is passed into setReadbackBuffer, filled by
+ * the device, and then displayed by the client as a full-screen buffer, the
+ * output of the display remains the same (subject to the note about protected
+ * content in the description of setReadbackBuffer).
+ *
+ * If the active configuration or color mode of this display has changed since
+ * the previous call to this function, it will be called again prior to setting
+ * a readback buffer such that the returned format and dataspace can be updated
+ * accordingly.
+ *
+ * Parameters:
+ *   outFormat - the format the client should use when allocating a device
+ *       readback buffer; pointer will be non-NULL
+ *   outDataspace - the dataspace the client will use when interpreting the
+ *       contents of a device readback buffer; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *
+ * See also:
+ *   setReadbackBuffer
+ *   getReadbackBufferFence
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_READBACK_BUFFER_ATTRIBUTES)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* /*android_pixel_format_t*/ outFormat,
+        int32_t* /*android_dataspace_t*/ outDataspace);
+
+/* getReadbackBufferFence(..., outFence)
+ * Optional for HWC2 devices
+ *
+ * Returns an acquire sync fence file descriptor which will signal when the
+ * buffer provided to setReadbackBuffer has been filled by the device and is
+ * safe for the client to read.
+ *
+ * If it is already safe to read from this buffer, -1 may be returned instead.
+ * The client takes ownership of this file descriptor and is responsible for
+ * closing it when it is no longer needed.
+ *
+ * This function will be called immediately after the composition cycle being
+ * captured into the readback buffer. The complete ordering of a readback buffer
+ * capture is as follows:
+ *
+ *   getReadbackBufferAttributes
+ *   // Readback buffer is allocated
+ *   // Many frames may pass
+ *
+ *   setReadbackBuffer
+ *   validateDisplay
+ *   presentDisplay
+ *   getReadbackBufferFence
+ *   // Implicitly wait on the acquire fence before accessing the buffer
+ *
+ * Parameters:
+ *   outFence - a sync fence file descriptor as described above; pointer
+ *       will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NO_RESOURCES - the readback operation was successful, but
+ *       resulted in a different validate result than would have occurred
+ *       without readback
+ *   HWC2_ERROR_UNSUPPORTED - the readback operation was unsuccessful because
+ *       of resource constraints, the presence of protected content, or other
+ *       reasons; -1 must be returned in outFence
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_READBACK_BUFFER_FENCE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* outFence);
+
+/* setReadbackBuffer(..., buffer, releaseFence)
+ * Optional for HWC2 devices
+ *
+ * Sets the readback buffer to be filled with the contents of the next
+ * composition performed for this display (i.e., the contents present at the
+ * time of the next validateDisplay/presentDisplay cycle).
+ *
+ * This buffer will have been allocated as described in
+ * getReadbackBufferAttributes and will be interpreted as being in the dataspace
+ * provided by the same.
+ *
+ * If there is hardware protected content on the display at the time of the next
+ * composition, the area of the readback buffer covered by such content must be
+ * completely black. Any areas of the buffer not covered by such content may
+ * optionally be black as well.
+ *
+ * The release fence file descriptor provided works identically to the one
+ * described for setOutputBuffer.
+ *
+ * This function will not be called between any call to validateDisplay and a
+ * subsequent call to presentDisplay.
+ *
+ * Parameters:
+ *   buffer - the new readback buffer
+ *   releaseFence - a sync fence file descriptor as described in setOutputBuffer
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the new readback buffer handle was invalid
+ *
+ * See also:
+ *   getReadbackBufferAttributes
+ *   getReadbackBufferFence
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_READBACK_BUFFER)(
+        hwc2_device_t* device, hwc2_display_t display,
+        buffer_handle_t buffer, int32_t releaseFence);
+
+/* setVsyncEnabled(..., enabled)
+ * Descriptor: HWC2_FUNCTION_SET_VSYNC_ENABLED
+ * Must be provided by all HWC2 devices
+ *
+ * Enables or disables the vsync signal for the given display. Virtual displays
+ * never generate vsync callbacks, and any attempt to enable vsync for a virtual
+ * display though this function must return HWC2_ERROR_NONE and have no other
+ * effect.
+ *
+ * Parameters:
+ *   enabled - whether to enable or disable vsync
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - enabled was an invalid value
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_VSYNC_ENABLED)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*hwc2_vsync_t*/ enabled);
+
+/* validateDisplay(..., outNumTypes, outNumRequests)
+ * Descriptor: HWC2_FUNCTION_VALIDATE_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Instructs the device to inspect all of the layer state and determine if
+ * there are any composition type changes necessary before presenting the
+ * display. Permitted changes are described in the definition of
+ * hwc2_composition_t above.
+ *
+ * Also returns the number of layer requests required
+ * by the given layer configuration.
+ *
+ * Parameters:
+ *   outNumTypes - the number of composition type changes required by the
+ *       device; if greater than 0, the client must either set and validate new
+ *       types, or call acceptDisplayChanges to accept the changes returned by
+ *       getChangedCompositionTypes; must be the same as the number of changes
+ *       returned by getChangedCompositionTypes (see the declaration of that
+ *       function for more information); pointer will be non-NULL
+ *   outNumRequests - the number of layer requests required by this layer
+ *       configuration; must be equal to the number of layer requests returned
+ *       by getDisplayRequests (see the declaration of that function for
+ *       more information); pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE if no changes are necessary and it is safe to present
+ * the display using the current layer state. Otherwise returns one of the
+ * following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_HAS_CHANGES - outNumTypes was greater than 0 (see parameter list
+ *       for more information)
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_VALIDATE_DISPLAY)(
+        hwc2_device_t* device, hwc2_display_t display,
+        uint32_t* outNumTypes, uint32_t* outNumRequests);
+
+/*
+ * Layer Functions
+ *
+ * These are functions which operate on layers, but which do not modify state
+ * that must be validated before use. See also 'Layer State Functions' below.
+ *
+ * All of these functions take as their first three parameters a device pointer,
+ * a display handle for the display which contains the layer, and a layer
+ * handle, so these parameters are omitted from the described parameter lists.
+ */
+
+/* setCursorPosition(..., x, y)
+ * Descriptor: HWC2_FUNCTION_SET_CURSOR_POSITION
+ * Must be provided by all HWC2 devices
+ *
+ * Asynchonously sets the position of a cursor layer.
+ *
+ * Prior to validateDisplay, a layer may be marked as HWC2_COMPOSITION_CURSOR.
+ * If validation succeeds (i.e., the device does not request a composition
+ * change for that layer), then once a buffer has been set for the layer and it
+ * has been presented, its position may be set by this function at any time
+ * between presentDisplay and any subsequent validateDisplay calls for this
+ * display.
+ *
+ * Once validateDisplay is called, this function will not be called again until
+ * the validate/present sequence is completed.
+ *
+ * May be called from any thread so long as it is not interleaved with the
+ * validate/present sequence as described above.
+ *
+ * Parameters:
+ *   x - the new x coordinate (in pixels from the left of the screen)
+ *   y - the new y coordinate (in pixels from the top of the screen)
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_LAYER - the layer is invalid or is not currently marked as
+ *       HWC2_COMPOSITION_CURSOR
+ *   HWC2_ERROR_NOT_VALIDATED - the device is currently in the middle of the
+ *       validate/present sequence
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_CURSOR_POSITION)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t x, int32_t y);
+
+/* setLayerBuffer(..., buffer, acquireFence)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_BUFFER
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the buffer handle to be displayed for this layer. If the buffer
+ * properties set at allocation time (width, height, format, and usage) have not
+ * changed since the previous frame, it is not necessary to call validateDisplay
+ * before calling presentDisplay unless new state needs to be validated in the
+ * interim.
+ *
+ * Also provides a file descriptor referring to an acquire sync fence object,
+ * which will be signaled when it is safe to read from the given buffer. If it
+ * is already safe to read from the buffer, -1 may be passed instead. The
+ * device must ensure that it is safe for the client to close this file
+ * descriptor at any point after this function is called.
+ *
+ * This function must return HWC2_ERROR_NONE and have no other effect if called
+ * for a layer with a composition type of HWC2_COMPOSITION_SOLID_COLOR (because
+ * it has no buffer) or HWC2_COMPOSITION_SIDEBAND or HWC2_COMPOSITION_CLIENT
+ * (because synchronization and buffer updates for these layers are handled
+ * elsewhere).
+ *
+ * Parameters:
+ *   buffer - the buffer handle to set
+ *   acquireFence - a sync fence file descriptor as described above
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the buffer handle passed in was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_BUFFER)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        buffer_handle_t buffer, int32_t acquireFence);
+
+/* setLayerSurfaceDamage(..., damage)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE
+ * Must be provided by all HWC2 devices
+ *
+ * Provides the region of the source buffer which has been modified since the
+ * last frame. This region does not need to be validated before calling
+ * presentDisplay.
+ *
+ * Once set through this function, the damage region remains the same until a
+ * subsequent call to this function.
+ *
+ * If damage.numRects > 0, then it may be assumed that any portion of the source
+ * buffer not covered by one of the rects has not been modified this frame. If
+ * damage.numRects == 0, then the whole source buffer must be treated as if it
+ * has been modified.
+ *
+ * If the layer's contents are not modified relative to the prior frame, damage
+ * will contain exactly one empty rect([0, 0, 0, 0]).
+ *
+ * The damage rects are relative to the pre-transformed buffer, and their origin
+ * is the top-left corner. They will not exceed the dimensions of the latched
+ * buffer.
+ *
+ * Parameters:
+ *   damage - the new surface damage region
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SURFACE_DAMAGE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_region_t damage);
+
+/* setLayerPerFrameMetadata(..., numMetadata, metadata)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA
+ * Optional for HWC2 devices
+ *
+ * If supported (getFunction(HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA) is
+ * non-null), sets the metadata for the given display for all following
+ * frames.
+ *
+ * Upon returning from this function, the metadata change must have
+ * fully taken effect.
+ *
+ * This function will only be called if getPerFrameMetadataKeys is non-NULL
+ * and returns at least one key.
+ *
+ * Parameters:
+ *   numElements is the number of elements in each of the keys and metadata arrays
+ *   keys is a pointer to the array of keys.
+ *   outMetadata is a pointer to the corresponding array of metadata.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - metadata is not valid
+ *   HWC2_ERROR_UNSUPPORTED - metadata is not supported on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PER_FRAME_METADATA)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        uint32_t numElements, const int32_t* /*hw2_per_frame_metadata_key_t*/ keys,
+        const float* metadata);
+
+/* setLayerPerFrameMetadataBlobs(...,numElements, keys, sizes, blobs)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS
+ * Optional for HWC2 devices
+ *
+ * If supported, (getFunction(HWC2_FUNCTION_SET_LAYER_PER_FRAME_METADATA_BLOBS)
+ * is non-null), sets the metadata for the given display and layer.
+ *
+ * Upon returning from this function, the metadata change must have fully taken
+ * effect.
+ *
+ * This function must only be called if getPerFrameMetadataKeys is non-NULL
+ * and returns at least one key that corresponds to a blob type.
+ *
+ * Current valid blob type keys are: HDR10_PLUS_SEI
+ *
+ * Parameters:
+ *   numElements is the number of elements in each of the keys, sizes, and
+ *   metadata arrays
+ *   keys is a pointer to an array of keys.  Current valid keys are those listed
+ *   above as valid blob type keys.
+ *   sizes is a pointer to an array of unsigned ints specifying the sizes of
+ *   each metadata blob
+ *   metadata is a pointer to a blob of data holding all blobs contiguously in
+ *   memory
+ *
+ *   Returns HWC2_ERROR_NONE or one of the following erros:
+ *     HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *     HWC2_ERROR_BAD_PARAMETER - sizes of keys and metadata parameters does
+ *     not match numElements, numElements < 0, or keys contains a
+ *     non-valid key (see above for current valid blob type keys).
+ *     HWC2_ERROR_UNSUPPORTED - metadata is not supported on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PER_FRAME_METADATA_BLOBS)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        uint32_t numElements, const int32_t* keys, const uint32_t* sizes,
+        const uint8_t* metadata);
+/*
+ * Layer State Functions
+ *
+ * These functions modify the state of a given layer. They do not take effect
+ * until the display configuration is successfully validated with
+ * validateDisplay and the display contents are presented with presentDisplay.
+ *
+ * All of these functions take as their first three parameters a device pointer,
+ * a display handle for the display which contains the layer, and a layer
+ * handle, so these parameters are omitted from the described parameter lists.
+ */
+
+/* setLayerBlendMode(..., mode)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_BLEND_MODE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the blend mode of the given layer.
+ *
+ * Parameters:
+ *   mode - the new blend mode
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid blend mode was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_BLEND_MODE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*hwc2_blend_mode_t*/ mode);
+
+/* setLayerColor(..., color)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_COLOR
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the color of the given layer. If the composition type of the layer is
+ * not HWC2_COMPOSITION_SOLID_COLOR, this call must return HWC2_ERROR_NONE and
+ * have no other effect.
+ *
+ * Parameters:
+ *   color - the new color
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COLOR)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_color_t color);
+
+/* setLayerFloatColor(..., color)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_FLOAT_COLOR
+ * Provided by HWC2 devices which don't return nullptr function pointer.
+ *
+ * Sets the color of the given layer. If the composition type of the layer is
+ * not HWC2_COMPOSITION_SOLID_COLOR, this call must return HWC2_ERROR_NONE and
+ * have no other effect.
+ *
+ * Parameters:
+ *   color - the new color in float type, rage is [0.0, 1.0], the colorspace is
+ *   defined by the dataspace that gets set by calling setLayerDataspace.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_FLOAT_COLOR)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_float_color_t color);
+
+/* setLayerCompositionType(..., type)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the desired composition type of the given layer. During validateDisplay,
+ * the device may request changes to the composition types of any of the layers
+ * as described in the definition of hwc2_composition_t above.
+ *
+ * Parameters:
+ *   type - the new composition type
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid composition type was passed in
+ *   HWC2_ERROR_UNSUPPORTED - a valid composition type was passed in, but it is
+ *       not supported by this device
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COMPOSITION_TYPE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*hwc2_composition_t*/ type);
+
+/* setLayerDataspace(..., dataspace)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_DATASPACE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the dataspace that the current buffer on this layer is in.
+ *
+ * The dataspace provides more information about how to interpret the buffer
+ * contents, such as the encoding standard and color transform.
+ *
+ * See the values of android_dataspace_t in <system/graphics.h> for more
+ * information.
+ *
+ * Parameters:
+ *   dataspace - the new dataspace
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_DATASPACE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*android_dataspace_t*/ dataspace);
+
+/* setLayerDisplayFrame(..., frame)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the display frame (the portion of the display covered by a layer) of the
+ * given layer. This frame will not exceed the display dimensions.
+ *
+ * Parameters:
+ *   frame - the new display frame
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_DISPLAY_FRAME)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_rect_t frame);
+
+/* setLayerPlaneAlpha(..., alpha)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA
+ * Must be provided by all HWC2 devices
+ *
+ * Sets an alpha value (a floating point value in the range [0.0, 1.0]) which
+ * will be applied to the whole layer. It can be conceptualized as a
+ * preprocessing step which applies the following function:
+ *   if (blendMode == HWC2_BLEND_MODE_PREMULTIPLIED)
+ *       out.rgb = in.rgb * planeAlpha
+ *   out.a = in.a * planeAlpha
+ *
+ * If the device does not support this operation on a layer which is marked
+ * HWC2_COMPOSITION_DEVICE, it must request a composition type change to
+ * HWC2_COMPOSITION_CLIENT upon the next validateDisplay call.
+ *
+ * Parameters:
+ *   alpha - the plane alpha value to apply
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PLANE_ALPHA)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        float alpha);
+
+/* setLayerSidebandStream(..., stream)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM
+ * Provided by HWC2 devices which support HWC2_CAPABILITY_SIDEBAND_STREAM
+ *
+ * Sets the sideband stream for this layer. If the composition type of the given
+ * layer is not HWC2_COMPOSITION_SIDEBAND, this call must return HWC2_ERROR_NONE
+ * and have no other effect.
+ *
+ * Parameters:
+ *   stream - the new sideband stream
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid sideband stream was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SIDEBAND_STREAM)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        const native_handle_t* stream);
+
+/* setLayerSourceCrop(..., crop)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_SOURCE_CROP
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the source crop (the portion of the source buffer which will fill the
+ * display frame) of the given layer. This crop rectangle will not exceed the
+ * dimensions of the latched buffer.
+ *
+ * If the device is not capable of supporting a true float source crop (i.e., it
+ * will truncate or round the floats to integers), it should set this layer to
+ * HWC2_COMPOSITION_CLIENT when crop is non-integral for the most accurate
+ * rendering.
+ *
+ * If the device cannot support float source crops, but still wants to handle
+ * the layer, it should use the following code (or similar) to convert to
+ * an integer crop:
+ *   intCrop.left = (int) ceilf(crop.left);
+ *   intCrop.top = (int) ceilf(crop.top);
+ *   intCrop.right = (int) floorf(crop.right);
+ *   intCrop.bottom = (int) floorf(crop.bottom);
+ *
+ * Parameters:
+ *   crop - the new source crop
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SOURCE_CROP)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_frect_t crop);
+
+/* setLayerTransform(..., transform)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_TRANSFORM
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the transform (rotation/flip) of the given layer.
+ *
+ * Parameters:
+ *   transform - the new transform
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid transform was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_TRANSFORM)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*hwc_transform_t*/ transform);
+
+/* setLayerVisibleRegion(..., visible)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION
+ * Must be provided by all HWC2 devices
+ *
+ * Specifies the portion of the layer that is visible, including portions under
+ * translucent areas of other layers. The region is in screen space, and will
+ * not exceed the dimensions of the screen.
+ *
+ * Parameters:
+ *   visible - the new visible region, in screen space
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_VISIBLE_REGION)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_region_t visible);
+
+/* setLayerZOrder(..., z)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_Z_ORDER
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the desired Z order (height) of the given layer. A layer with a greater
+ * Z value occludes a layer with a lesser Z value.
+ *
+ * Parameters:
+ *   z - the new Z order
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_Z_ORDER)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        uint32_t z);
+
+/* setLayerColorTransform(..., matrix)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_COLOR_TRANSFORM
+ * Optional by all HWC2 devices
+ *
+ * Sets a matrix for color transform which will be applied on this layer
+ * before composition.
+ *
+ * If the device is not capable of apply the matrix on this layer, it must force
+ * this layer to client composition during VALIDATE_DISPLAY.
+ *
+ * The matrix provided is an affine color transformation of the following form:
+ *
+ * |r.r r.g r.b 0|
+ * |g.r g.g g.b 0|
+ * |b.r b.g b.b 0|
+ * |Tr  Tg  Tb  1|
+ *
+ * This matrix must be provided in row-major form:
+ *
+ * {r.r, r.g, r.b, 0, g.r, ...}.
+ *
+ * Given a matrix of this form and an input color [R_in, G_in, B_in],
+ * the input color must first be converted to linear space
+ * [R_linear, G_linear, B_linear], then the output linear color
+ * [R_out_linear, G_out_linear, B_out_linear] will be:
+ *
+ * R_out_linear = R_linear * r.r + G_linear * g.r + B_linear * b.r + Tr
+ * G_out_linear = R_linear * r.g + G_linear * g.g + B_linear * b.g + Tg
+ * B_out_linear = R_linear * r.b + G_linear * g.b + B_linear * b.b + Tb
+ *
+ * [R_out_linear, G_out_linear, B_out_linear] must then be converted to
+ * gamma space: [R_out, G_out, B_out] before blending.
+ *
+ * Parameters:
+ *   matrix - a 4x4 transform matrix (16 floats) as described above
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COLOR_TRANSFORM)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        const float* matrix);
+
+/* getDisplayedContentSamplingAttributes(...,
+ *      format, dataspace, supported_components, max_frames)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES
+ * Optional by all HWC2 devices
+ *
+ * Query for what types of color sampling the hardware supports.
+ *
+ * Parameters:
+ *   format - The format of the sampled pixels; pointer will be non-NULL
+ *   dataspace - The dataspace of the sampled pixels; pointer will be non-NULL
+ *   supported_components - The mask of which components can be sampled; pointer
+ *      will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY when an invalid display was passed in, or
+ *   HWC2_ERROR_UNSUPPORTED when there is no efficient way to sample.
+ */
+typedef int32_t (*HWC2_PFN_GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* /* android_pixel_format_t */ format,
+        int32_t* /* android_dataspace_t */ dataspace,
+        uint8_t* /* mask of android_component_t */ supported_components);
+
+/* setDisplayedContentSamplingEnabled(..., enabled)
+ * Descriptor: HWC2_FUNCTION_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED
+ * Optional by all HWC2 devices
+ *
+ * Enables or disables the collection of color content statistics
+ * on this display.
+ *
+ * Sampling occurs on the contents of the final composition on this display
+ * (i.e., the contents presented on screen).
+ *
+ * Sampling support is optional, and is set to DISABLE by default.
+ * On each call to ENABLE, all collected statistics will be reset.
+ *
+ * Sample data can be queried via getDisplayedContentSample().
+ *
+ * Parameters:
+ *   enabled - indicates whether to enable or disable sampling.
+ *   component_mask - The mask of which components should be sampled.
+ *      If zero, all supported components are to be enabled.
+ *   max_frames - is the maximum number of frames that should be stored before
+ *      discard. The sample represents the most-recently posted frames.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY when an invalid display handle was passed in,
+ *   HWC2_ERROR_BAD_PARAMETER when enabled was an invalid value, or
+ *   HWC2_ERROR_NO_RESOURCES when the requested ringbuffer size via max_frames
+ *                           was not available.
+ *   HWC2_ERROR_UNSUPPORTED when there is no efficient way to sample.
+ */
+typedef int32_t (*HWC2_PFN_SET_DISPLAYED_CONTENT_SAMPLING_ENABLED)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*hwc2_displayed_content_sampling_t*/ enabled,
+        uint8_t /* mask of android_component_t */ component_mask,
+        uint64_t max_frames);
+
+/* getDisplayedContentSample(..., component, max_frames, timestamp,
+ *     samples_size, samples, frame_count)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAYED_CONTENT_SAMPLE
+ * Optional by all HWC2 devices
+ *
+ * Collects the results of display content color sampling for display.
+ *
+ * Collection of data can occur whether the sampling is in ENABLE or
+ * DISABLE state.
+ *
+ * Parameters:
+ * max_frames - is the maximum number of frames that should be represented in
+ *      the sample. The sample represents the most-recently posted frames.
+ *      If max_frames is 0, all frames are to be represented by the sample.
+ * timestamp - is the timestamp after which any frames were posted that should
+ *      be included in the sample. Timestamp is CLOCK_MONOTONIC.
+ *      If timestamp is 0, do not filter from the sample by time.
+ * frame_count - The number of frames represented by this sample; pointer will
+ *      be non-NULL.
+ * samples_size - The sizes of the color histogram representing the color
+ *      sampling. Sample_sizes are indexed in the same order as
+ *      HWC2_FORMAT_COMPONENT_.
+ * samples - The arrays of data corresponding to the sampling data. Samples are
+ *      indexed in the same order as HWC2_FORMAT_COMPONENT_.
+ *      The size of each sample is the samples_size for the same index.
+ *      Each components sample is an array that is to be filled with the
+ *      evenly-weighted buckets of a histogram counting how many times a pixel
+ *      of the given component was displayed onscreen. Caller owns the data and
+ *      pointer may be NULL to query samples_size.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY   when an invalid display was passed in, or
+ *   HWC2_ERROR_UNSUPPORTED   when there is no efficient way to sample, or
+ *   HWC2_ERROR_BAD_PARAMETER when the component is not supported by the hardware.
+ */
+typedef int32_t (*HWC2_PFN_GET_DISPLAYED_CONTENT_SAMPLE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        uint64_t max_frames, uint64_t timestamp,
+        uint64_t* frame_count, int32_t samples_size[4], uint64_t* samples[4]);
+
+/* getDisplayCapabilities(..., outCapabilities)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES
+ * Required for HWC2 devices for composer 2.3
+ * Optional for HWC2 devices for composer 2.1 and 2.2
+ *
+ * getDisplayCapabilities returns a list of supported capabilities
+ * (as described in the definition of Capability above).
+ * This list must not change after initialization.
+ *
+ * Parameters:
+ *   outNumCapabilities - if outCapabilities was nullptr, returns the number of capabilities
+ *       if outCapabilities was not nullptr, returns the number of capabilities stored in
+ *       outCapabilities, which must not exceed the value stored in outNumCapabilities prior
+ *       to the call; pointer will be non-NULL
+ *   outCapabilities - a list of supported capabilities.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CAPABILITIES)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumCapabilities,
+        uint32_t* outCapabilities);
+
+/* Use getDisplayCapabilities instead. If brightness is supported, must return
+ * DisplayCapability::BRIGHTNESS as one of the display capabilities via getDisplayCapabilities.
+ * Only use getDisplayCapabilities as the source of truth to query brightness support.
+ *
+ * getDisplayBrightnessSupport(displayToken)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT
+ * Required for HWC2 devices for composer 2.3
+ * Optional for HWC2 devices for composer 2.1 and 2.2
+ *
+ * getDisplayBrightnessSupport returns whether brightness operations are supported on a display.
+ *
+ * Parameters:
+ *   outSupport - whether the display supports operations.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY when the display is invalid.
+ */
+typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_GET_DISPLAY_BRIGHTNESS_SUPPORT)(hwc2_device_t* device,
+        hwc2_display_t display, bool* outSupport);
+
+/* setDisplayBrightness(displayToken, brightnesss)
+ * Descriptor: HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS
+ * Required for HWC2 devices for composer 2.3
+ * Optional for HWC2 devices for composer 2.1 and 2.2
+ *
+ * setDisplayBrightness sets the brightness of a display.
+ *
+ * Parameters:
+ *   brightness - a number between 0.0f (minimum brightness) and 1.0f (maximum brightness), or
+ *          -1.0f to turn the backlight off.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY   when the display is invalid, or
+ *   HWC2_ERROR_UNSUPPORTED   when brightness operations are not supported, or
+ *   HWC2_ERROR_BAD_PARAMETER when the brightness is invalid, or
+ *   HWC2_ERROR_NO_RESOURCES  when the brightness cannot be applied.
+ */
+typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_DISPLAY_BRIGHTNESS)(hwc2_device_t* device,
+        hwc2_display_t display, float brightness);
+
+/* Composer 2.4 additions */
+
+/* getDisplayConnectionType(..., outType)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE
+ * Optional for all HWC2 devices
+ *
+ * Returns whether the given physical display is internal or external.
+ *
+ * Parameters:
+ *   outType - the connection type of the display; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY when the display is invalid or virtual.
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CONNECTION_TYPE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        uint32_t* /*hwc2_display_connection_type_t*/ outType);
+
+/* getDisplayVsyncPeriod(..., outVsyncPeriods)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD
+ * Required for HWC2 devices for composer 2.4
+ *
+ * Retrieves which vsync period the display is currently using.
+ *
+ * If no display configuration is currently active, this function must
+ * return BAD_CONFIG. If a vsync period is about to change due to a
+ * setActiveConfigWithConstraints call, this function must return the current vsync period
+ * until the change has taken place.
+ *
+ * Parameters:
+ *     outVsyncPeriod - the current vsync period of the display.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - no configuration is currently active
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_VSYNC_PERIOD)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_vsync_period_t* outVsyncPeriod);
+
+/* setActiveConfigWithConstraints(...,
+ *                                config,
+ *                                vsyncPeriodChangeConstraints,
+ *                                outTimeline)
+ * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS
+ * Required for HWC2 devices for composer 2.4
+ *
+ * Sets the active configuration and the refresh rate for this display.
+ * If the new config shares the same config group as the current config,
+ * only the vsync period shall change.
+ * Upon returning, the given display configuration, except vsync period, must be active and
+ * remain so until either this function is called again or the display is disconnected.
+ * When the display starts to refresh at the new vsync period, onVsync_2_4 callback must be
+ * called with the new vsync period.
+ *
+ * Parameters:
+ *     config - the new display configuration.
+ *     vsyncPeriodChangeConstraints - constraints required for changing vsync period:
+ *                                    desiredTimeNanos - the time in CLOCK_MONOTONIC after
+ *                                                       which the vsync period may change
+ *                                                       (i.e., the vsync period must not change
+ *                                                       before this time).
+ *                                    seamlessRequired - if true, requires that the vsync period
+ *                                                       change must happen seamlessly without
+ *                                                       a noticeable visual artifact.
+ *                                                       When the conditions change and it may be
+ *                                                       possible to change the vsync period
+ *                                                       seamlessly, HWC2_CALLBACK_SEAMLESS_POSSIBLE
+ *                                                       callback must be called to indicate that
+ *                                                       caller should retry.
+ *     outTimeline - the timeline for the vsync period change.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in.
+ *   HWC2_ERROR_BAD_CONFIG - an invalid configuration handle passed in.
+ *   HWC2_ERROR_SEAMLESS_NOT_ALLOWED - when seamlessRequired was true but config provided doesn't
+     *                                 share the same config group as the current config.
+ *   HWC2_ERROR_SEAMLESS_NOT_POSSIBLE - when seamlessRequired was true but the display cannot
+ *                                      achieve the vsync period change without a noticeable
+ *                                      visual artifact.
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config,
+        hwc_vsync_period_change_constraints_t* vsyncPeriodChangeConstraints,
+        hwc_vsync_period_change_timeline_t* outTimeline);
+
+/* setAutoLowLatencyMode(displayToken, on)
+ * Descriptor: HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE
+ * Optional for HWC2 devices
+ *
+ * setAutoLowLatencyMode requests that the display goes into low latency mode. If the display
+ * is connected via HDMI 2.1, then Auto Low Latency Mode should be triggered. If the display is
+ * internally connected, then a custom low latency mode should be triggered (if available).
+ *
+ * Parameters:
+ *   on - indicates whether to turn low latency mode on (=true) or off (=false)
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - when the display is invalid, or
+ *   HWC2_ERROR_UNSUPPORTED - when the display does not support any low latency mode
+ */
+typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_AUTO_LOW_LATENCY_MODE)(hwc2_device_t* device,
+        hwc2_display_t display, bool on);
+
+/* getSupportedContentTypes(..., outSupportedContentTypes)
+ * Descriptor: HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES
+ * Optional for HWC2 devices
+ *
+ * getSupportedContentTypes returns a list of supported content types
+ * (as described in the definition of ContentType above).
+ * This list must not change after initialization.
+ *
+ * Parameters:
+ *   outNumSupportedContentTypes - if outSupportedContentTypes was nullptr, returns the number
+ *       of supported content types; if outSupportedContentTypes was not nullptr, returns the
+ *       number of capabilities stored in outSupportedContentTypes, which must not exceed the
+ *       value stored in outNumSupportedContentTypes prior to the call; pointer will be non-NULL
+ *   outSupportedContentTypes - a list of supported content types.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_GET_SUPPORTED_CONTENT_TYPES)(hwc2_device_t* device,
+        hwc2_display_t display, uint32_t* outNumSupportedContentTypes, uint32_t* outSupportedContentTypes);
+
+/* setContentType(displayToken, contentType)
+ * Descriptor: HWC2_FUNCTION_SET_CONTENT_TYPE
+ * Optional for HWC2 devices
+ *
+ * setContentType instructs the display that the content being shown is of the given contentType
+ * (one of GRAPHICS, PHOTO, CINEMA, GAME).
+ *
+ * According to the HDMI 1.4 specification, supporting all content types is optional. Whether
+ * the display supports a given content type is reported by getSupportedContentTypes.
+ *
+ * Parameters:
+ *   contentType - the type of content that is currently being shown on the display
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - when the display is invalid, or
+ *   HWC2_ERROR_UNSUPPORTED - when the given content type is a valid content type, but is not
+ *                            supported on this display, or
+ *   HWC2_ERROR_BAD_PARAMETER - when the given content type is invalid
+ */
+typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_CONTENT_TYPE)(hwc2_device_t* device,
+        hwc2_display_t display, int32_t /* hwc2_content_type_t */ contentType);
+
+/* getClientTargetProperty(..., outClientTargetProperty)
+ * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY
+ * Optional for HWC2 devices
+ *
+ * Retrieves the client target properties for which the hardware composer
+ * requests after the last call to validateDisplay. The client must set the
+ * properties of the client target to match the returned values.
+ * When this API is implemented, if client composition is needed, the hardware
+ * composer must return meaningful client target property with dataspace not
+ * setting to UNKNOWN.
+ * When the returned dataspace is set to UNKNOWN, it means hardware composer
+ * requests nothing, the client must ignore the returned client target property
+ * structrue.
+ *
+ * Parameters:
+ *   outClientTargetProperty - the client target properties that hardware
+ *       composer requests. If dataspace field is set to UNKNOWN, it means
+ *       the hardware composer requests nothing, the client must ignore the
+ *       returned client target property structure.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CLIENT_TARGET_PROPERTY)(
+        hwc2_device_t* device, hwc2_display_t display,
+        hwc_client_target_property_t* outClientTargetProperty);
+
+/* setLayerGenericMetadata(..., keyLength, key, mandatory, valueLength, value)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_GENERIC_METADATA
+ * Optional for HWC2 devices for composer 2.4+
+ *
+ * setLayerGenericMetadata sets a piece of generic metadata for the given layer.
+ * If this function is called twice with the same key but different values, the
+ * newer value must override the older one. Calling this function with
+ * valueLength == 0 must reset that key's metadata as if it had not been set.
+ *
+ * A given piece of metadata may either be mandatory or a hint (non-mandatory)
+ * as indicated by the `mandatory` parameter. Mandatory metadata may affect the
+ * composition result, which is to say that it may cause a visible change in the
+ * final image. By contrast, hints may only affect the composition strategy,
+ * such as which layers are composited by the client, but must not cause a
+ * visible change in the final image.
+ *
+ * This implies that if the device does not understand a given key:
+ * - If the key is marked as mandatory, it must mark this layer for client
+ *   composition in order to ensure the correct composition result
+ * - If the key is a hint, the metadata provided may be ignored
+ *
+ * Parameters:
+ *   keyLength - the length of the key parameter
+ *   key - the metadata key
+ *   mandatory - indicates whether this particular key represents mandatory
+ *       metadata or a hint, as described above
+ *   valueLength - the length of the value parameter
+ *   value - the metadata value
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an unsupported key was passed in, or the value
+ *       does not conform to the expected format for the key
+ */
+typedef int32_t /*hwc_error_t*/ (*HWC2_PFN_SET_LAYER_GENERIC_METADATA)(hwc2_device_t* device,
+        hwc2_display_t display, hwc2_layer_t layer, uint32_t keyLength, const char* key,
+        bool mandatory, uint32_t valueLength, const uint8_t* value);
+
+/* getLayerGenericMetadataKey(..., keyIndex, outKeyLength, outKey, outMandatory)
+ * Descriptor: HWC2_FUNCTION_GET_LAYER_GENERIC_METADATA_KEY
+ * Optional for HWC2 devices for composer 2.4+
+ *
+ * getLayerGenericMetadataKey allows the client to query which metadata keys are
+ * supported by the composer implementation. Only keys in this list will be
+ * passed into setLayerGenericMetadata. Additionally, the key names in this list
+ * must meet the following requirements:
+ * - Must be specified in reverse domain name notation
+ * - Must not start with 'com.android' or 'android'
+ * - Must be unique within the returned list of keys
+ * - Must correspond to a matching HIDL struct type, which defines the structure
+ *   of its values. For example, the key 'com.example.V1-3.Foo' should
+ *   correspond to a value of type com.example@1.3::Foo, which is defined in a
+ *   vendor HAL extension
+ *
+ * Client code which calls this function will look similar to this:
+ *
+ *     struct Key {
+ *         std::string name;
+ *         bool mandatory;
+ *     }
+ *
+ *     std::vector<Key> keys;
+ *     uint32_t index = 0;
+ *     uint32_t keyLength = 0;
+ *     while (true) {
+ *         getLayerGenericMetadataKey(device, index, &keyLength, nullptr, nullptr);
+ *         if (keyLength == 0) break;
+ *
+ *         Key key;
+ *         key.name.resize(keyLength);
+ *         getLayerGenericMetadataKey(device, index, &keyLength, key.name.data(), &key.mandatory);
+ *         keys.push_back(key);
+ *
+ *         ++index;
+ *     }
+ *
+ * Parameters:
+ *   keyIndex - the index of the key to retrieve. For values beyond the end of
+ *       the list of supported keys, outKeyLength should return 0, and the
+ *       client may assume that if the length is 0 for keyIndex N, then it is
+ *       also 0 for all keyIndex values > N.
+ *   outKeyLength - if outKey was nullptr, returns the length of the key to
+ *       allow the client to allocate an appropriately-sized buffer; if outKey
+ *       was not nullptr, returns the length of the returned key, which must not
+ *       exceed the value stored in outKeyLength prior to the call; pointer will
+ *       be non-null
+ *   outKey - the key at the given index, or nullptr to query the key's length
+ *   outMandatory - whether the given metadata is mandatory or not (see
+ *      setLayerGenericMetadata for more information), may be nullptr
+ */
+typedef void (*HWC2_PFN_GET_LAYER_GENERIC_METADATA_KEY)(hwc2_device_t* device, uint32_t keyIndex,
+        uint32_t* outKeyLength, char* outKey, bool* outMandatory);
+
+__END_DECLS
+
+#endif
diff --git a/.ci/android_headers/hardware/hwcomposer_defs.h b/.ci/android_headers/hardware/hwcomposer_defs.h
new file mode 100644
index 0000000..f466a36
--- /dev/null
+++ b/.ci/android_headers/hardware/hwcomposer_defs.h
@@ -0,0 +1,345 @@
+// clang-format off
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H
+#define ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+#include <hardware/gralloc.h>
+#include <hardware/hardware.h>
+#include <cutils/native_handle.h>
+
+__BEGIN_DECLS
+
+/* Shared by HWC1 and HWC2 */
+
+#define HWC_HEADER_VERSION          1
+
+#define HWC_MODULE_API_VERSION_0_1  HARDWARE_MODULE_API_VERSION(0, 1)
+
+#define HWC_DEVICE_API_VERSION_1_0  HARDWARE_DEVICE_API_VERSION_2(1, 0, HWC_HEADER_VERSION)
+#define HWC_DEVICE_API_VERSION_1_1  HARDWARE_DEVICE_API_VERSION_2(1, 1, HWC_HEADER_VERSION)
+#define HWC_DEVICE_API_VERSION_1_2  HARDWARE_DEVICE_API_VERSION_2(1, 2, HWC_HEADER_VERSION)
+#define HWC_DEVICE_API_VERSION_1_3  HARDWARE_DEVICE_API_VERSION_2(1, 3, HWC_HEADER_VERSION)
+#define HWC_DEVICE_API_VERSION_1_4  HARDWARE_DEVICE_API_VERSION_2(1, 4, HWC_HEADER_VERSION)
+#define HWC_DEVICE_API_VERSION_1_5  HARDWARE_DEVICE_API_VERSION_2(1, 5, HWC_HEADER_VERSION)
+
+#define HWC_DEVICE_API_VERSION_2_0  HARDWARE_DEVICE_API_VERSION_2(2, 0, HWC_HEADER_VERSION)
+
+/**
+ * The id of this module
+ */
+#define HWC_HARDWARE_MODULE_ID "hwcomposer"
+
+/**
+ * Name of the sensors device to open
+ */
+#define HWC_HARDWARE_COMPOSER "composer"
+
+typedef struct hwc_color {
+    uint8_t r;
+    uint8_t g;
+    uint8_t b;
+    uint8_t a;
+} hwc_color_t;
+
+typedef struct hwc_float_color {
+    float r;
+    float g;
+    float b;
+    float a;
+} hwc_float_color_t;
+
+typedef struct hwc_frect {
+    float left;
+    float top;
+    float right;
+    float bottom;
+} hwc_frect_t;
+
+typedef struct hwc_rect {
+    int left;
+    int top;
+    int right;
+    int bottom;
+} hwc_rect_t;
+
+typedef struct hwc_region {
+    size_t numRects;
+    hwc_rect_t const* rects;
+} hwc_region_t;
+
+/*
+ * hwc_layer_t::transform values
+ */
+typedef enum {
+    /* flip source image horizontally */
+    HWC_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H,
+    /* flip source image vertically */
+    HWC_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
+    /* rotate source image 90 degrees clock-wise */
+    HWC_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
+    /* rotate source image 180 degrees */
+    HWC_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
+    /* rotate source image 270 degrees clock-wise */
+    HWC_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
+    /* flip source image horizontally, the rotate 90 degrees clock-wise */
+    HWC_TRANSFORM_FLIP_H_ROT_90 = HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90,
+    /* flip source image vertically, the rotate 90 degrees clock-wise */
+    HWC_TRANSFORM_FLIP_V_ROT_90 = HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90,
+} hwc_transform_t;
+
+/* Constraints for changing vsync period */
+typedef struct hwc_vsync_period_change_constraints {
+    /* Time in CLOCK_MONOTONIC after which the vsync period may change
+     * (i.e., the vsync period must not change before this time). */
+    int64_t desiredTimeNanos;
+    /*
+     * If true, requires that the vsync period change must happen seamlessly without
+     * a noticeable visual artifact. */
+    uint8_t seamlessRequired;
+} hwc_vsync_period_change_constraints_t;
+
+/* Timing for a vsync period change. */
+typedef struct hwc_vsync_period_change_timeline {
+    /* The time in CLOCK_MONOTONIC when the new display will start to refresh at
+     * the new vsync period. */
+    int64_t newVsyncAppliedTimeNanos;
+
+    /* Set to true if the client is required to sent a frame to be displayed before
+     * the change can take place. */
+    uint8_t refreshRequired;
+
+    /* The time in CLOCK_MONOTONIC when the client is expected to send the new frame.
+     * Should be ignored if refreshRequired is false. */
+    int64_t refreshTimeNanos;
+} hwc_vsync_period_change_timeline_t;
+
+typedef struct hwc_client_target_property {
+    // The pixel format of client target requested by hardware composer.
+    int32_t pixelFormat;
+    // The dataspace of the client target requested by hardware composer.
+    int32_t dataspace;
+} hwc_client_target_property_t;
+
+/*******************************************************************************
+ * Beyond this point are things only used by HWC1, which should be ignored when
+ * implementing a HWC2 device
+ ******************************************************************************/
+
+enum {
+    /* hwc_composer_device_t::set failed in EGL */
+    HWC_EGL_ERROR = -1
+};
+
+/*
+ * hwc_layer_t::hints values
+ * Hints are set by the HAL and read by SurfaceFlinger
+ */
+enum {
+    /*
+     * HWC can set the HWC_HINT_TRIPLE_BUFFER hint to indicate to SurfaceFlinger
+     * that it should triple buffer this layer. Typically HWC does this when
+     * the layer will be unavailable for use for an extended period of time,
+     * e.g. if the display will be fetching data directly from the layer and
+     * the layer can not be modified until after the next set().
+     */
+    HWC_HINT_TRIPLE_BUFFER  = 0x00000001,
+
+    /*
+     * HWC sets HWC_HINT_CLEAR_FB to tell SurfaceFlinger that it should clear the
+     * framebuffer with transparent pixels where this layer would be.
+     * SurfaceFlinger will only honor this flag when the layer has no blending
+     *
+     */
+    HWC_HINT_CLEAR_FB       = 0x00000002
+};
+
+/*
+ * hwc_layer_t::flags values
+ * Flags are set by SurfaceFlinger and read by the HAL
+ */
+enum {
+    /*
+     * HWC_SKIP_LAYER is set by SurfaceFlinger to indicate that the HAL
+     * shall not consider this layer for composition as it will be handled
+     * by SurfaceFlinger (just as if compositionType was set to HWC_FRAMEBUFFER).
+     */
+    HWC_SKIP_LAYER = 0x00000001,
+
+    /*
+     * HWC_IS_CURSOR_LAYER is set by surfaceflinger to indicate that this
+     * layer is being used as a cursor on this particular display, and that
+     * surfaceflinger can potentially perform asynchronous position updates for
+     * this layer. If a call to prepare() returns HWC_CURSOR_OVERLAY for the
+     * composition type of this layer, then the hwcomposer will allow async
+     * position updates to this layer via setCursorPositionAsync().
+     */
+    HWC_IS_CURSOR_LAYER = 0x00000002
+};
+
+/*
+ * hwc_layer_t::compositionType values
+ */
+enum {
+    /* this layer is to be drawn into the framebuffer by SurfaceFlinger */
+    HWC_FRAMEBUFFER = 0,
+
+    /* this layer will be handled in the HWC */
+    HWC_OVERLAY = 1,
+
+    /* this is the background layer. it's used to set the background color.
+     * there is only a single background layer */
+    HWC_BACKGROUND = 2,
+
+    /* this layer holds the result of compositing the HWC_FRAMEBUFFER layers.
+     * Added in HWC_DEVICE_API_VERSION_1_1. */
+    HWC_FRAMEBUFFER_TARGET = 3,
+
+    /* this layer's contents are taken from a sideband buffer stream.
+     * Added in HWC_DEVICE_API_VERSION_1_4. */
+    HWC_SIDEBAND = 4,
+
+    /* this layer's composition will be handled by hwcomposer by dedicated
+       cursor overlay hardware. hwcomposer will also all async position updates
+       of this layer outside of the normal prepare()/set() loop. Added in
+       HWC_DEVICE_API_VERSION_1_4. */
+    HWC_CURSOR_OVERLAY =  5
+ };
+/*
+ * hwc_layer_t::blending values
+ */
+enum {
+    /* no blending */
+    HWC_BLENDING_NONE     = 0x0100,
+
+    /* ONE / ONE_MINUS_SRC_ALPHA */
+    HWC_BLENDING_PREMULT  = 0x0105,
+
+    /* SRC_ALPHA / ONE_MINUS_SRC_ALPHA */
+    HWC_BLENDING_COVERAGE = 0x0405
+};
+
+/* attributes queriable with query() */
+enum {
+    /*
+     * Must return 1 if the background layer is supported, 0 otherwise.
+     */
+    HWC_BACKGROUND_LAYER_SUPPORTED      = 0,
+
+    /*
+     * Returns the vsync period in nanoseconds.
+     *
+     * This query is not used for HWC_DEVICE_API_VERSION_1_1 and later.
+     * Instead, the per-display attribute HWC_DISPLAY_VSYNC_PERIOD is used.
+     */
+    HWC_VSYNC_PERIOD                    = 1,
+
+    /*
+     * Availability: HWC_DEVICE_API_VERSION_1_1
+     * Returns a mask of supported display types.
+     */
+    HWC_DISPLAY_TYPES_SUPPORTED         = 2,
+};
+
+/* display attributes returned by getDisplayAttributes() */
+enum {
+    /* Indicates the end of an attribute list */
+    HWC_DISPLAY_NO_ATTRIBUTE                = 0,
+
+    /* The vsync period in nanoseconds */
+    HWC_DISPLAY_VSYNC_PERIOD                = 1,
+
+    /* The number of pixels in the horizontal and vertical directions. */
+    HWC_DISPLAY_WIDTH                       = 2,
+    HWC_DISPLAY_HEIGHT                      = 3,
+
+    /* The number of pixels per thousand inches of this configuration.
+     *
+     * Scaling DPI by 1000 allows it to be stored in an int without losing
+     * too much precision.
+     *
+     * If the DPI for a configuration is unavailable or the HWC implementation
+     * considers it unreliable, it should set these attributes to zero.
+     */
+    HWC_DISPLAY_DPI_X                       = 4,
+    HWC_DISPLAY_DPI_Y                       = 5,
+
+    /* Indicates which of the vendor-defined color transforms is provided by
+     * this configuration. */
+    HWC_DISPLAY_COLOR_TRANSFORM             = 6,
+
+    /* The configuration group this config is associated to. The groups are defined
+     * to mark certain configs as similar and changing configs within a certain group
+     * may be done seamlessly in some conditions. setActiveConfigWithConstraints. */
+    HWC_DISPLAY_CONFIG_GROUP                = 7,
+};
+
+/* Allowed events for hwc_methods::eventControl() */
+enum {
+    HWC_EVENT_VSYNC     = 0
+};
+
+/* Display types and associated mask bits. */
+enum {
+    HWC_DISPLAY_PRIMARY     = 0,
+    HWC_DISPLAY_EXTERNAL    = 1,    // HDMI, DP, etc.
+    HWC_DISPLAY_VIRTUAL     = 2,
+
+    HWC_NUM_PHYSICAL_DISPLAY_TYPES = 2,
+    HWC_NUM_DISPLAY_TYPES          = 3,
+};
+
+enum {
+    HWC_DISPLAY_PRIMARY_BIT     = 1 << HWC_DISPLAY_PRIMARY,
+    HWC_DISPLAY_EXTERNAL_BIT    = 1 << HWC_DISPLAY_EXTERNAL,
+    HWC_DISPLAY_VIRTUAL_BIT     = 1 << HWC_DISPLAY_VIRTUAL,
+};
+
+/* Display power modes */
+enum {
+    /* The display is turned off (blanked). */
+    HWC_POWER_MODE_OFF      = 0,
+    /* The display is turned on and configured in a low power state
+     * that is suitable for presenting ambient information to the user,
+     * possibly with lower fidelity than normal but greater efficiency. */
+    HWC_POWER_MODE_DOZE     = 1,
+    /* The display is turned on normally. */
+    HWC_POWER_MODE_NORMAL   = 2,
+    /* The display is configured as in HWC_POWER_MODE_DOZE but may
+     * stop applying frame buffer updates from the graphics subsystem.
+     * This power mode is effectively a hint from the doze dream to
+     * tell the hardware that it is done drawing to the display for the
+     * time being and that the display should remain on in a low power
+     * state and continue showing its current contents indefinitely
+     * until the mode changes.
+     *
+     * This mode may also be used as a signal to enable hardware-based doze
+     * functionality.  In this case, the doze dream is effectively
+     * indicating that the hardware is free to take over the display
+     * and manage it autonomously to implement low power always-on display
+     * functionality. */
+    HWC_POWER_MODE_DOZE_SUSPEND  = 3,
+};
+
+/*****************************************************************************/
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_HWCOMPOSER_DEFS_H */
diff --git a/.ci/android_headers/ndk/sync.h b/.ci/android_headers/ndk/sync.h
new file mode 100644
index 0000000..2ca389b
--- /dev/null
+++ b/.ci/android_headers/ndk/sync.h
@@ -0,0 +1,111 @@
+// clang-format off
+/*
+ *  Copyright 2017 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.
+ */
+
+/**
+ * @addtogroup Sync
+ * @{
+ */
+
+/**
+ * @file sync.h
+ */
+
+#ifndef ANDROID_SYNC_H
+#define ANDROID_SYNC_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+#include <linux/sync_file.h>
+
+__BEGIN_DECLS
+
+#if __ANDROID_API__ >= 26
+
+/* Fences indicate the status of an asynchronous task. They are initially
+ * in unsignaled state (0), and make a one-time transition to either signaled
+ * (1) or error (< 0) state. A sync file is a collection of one or more fences;
+ * the sync file's status is error if any of its fences are in error state,
+ * signaled if all of the child fences are signaled, or unsignaled otherwise.
+ *
+ * Sync files are created by various device APIs in response to submitting
+ * tasks to the device. Standard file descriptor lifetime syscalls like dup()
+ * and close() are used to manage sync file lifetime.
+ *
+ * The poll(), ppoll(), or select() syscalls can be used to wait for the sync
+ * file to change status, or (with a timeout of zero) to check its status.
+ *
+ * The functions below provide a few additional sync-specific operations.
+ */
+
+/**
+ * Merge two sync files.
+ *
+ * This produces a new sync file with the given name which has the union of the
+ * two original sync file's fences; redundant fences may be removed.
+ *
+ * If one of the input sync files is signaled or invalid, then this function
+ * may behave like dup(): the new file descriptor refers to the valid/unsignaled
+ * sync file with its original name, rather than a new sync file.
+ *
+ * The original fences remain valid, and the caller is responsible for closing
+ * them.
+ *
+ * Available since API level 26.
+ */
+int32_t sync_merge(const char* name, int32_t fd1, int32_t fd2) /* __INTRODUCED_IN(26) */;
+
+/**
+ * Retrieve detailed information about a sync file and its fences.
+ *
+ * The returned sync_file_info must be freed by calling sync_file_info_free().
+ *
+ * Available since API level 26.
+ */
+struct sync_file_info* sync_file_info(int32_t fd) /* __INTRODUCED_IN(26) */;
+
+/**
+ * Get the array of fence infos from the sync file's info.
+ *
+ * The returned array is owned by the parent sync file info, and has
+ * info->num_fences entries.
+ *
+ * Available since API level 26.
+ */
+static inline struct sync_fence_info* sync_get_fence_info(const struct sync_file_info* info) {
+// This header should compile in C, but some C++ projects enable
+// warnings-as-error for C-style casts.
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wold-style-cast"
+    return (struct sync_fence_info *)(uintptr_t)(info->sync_fence_info);
+#pragma GCC diagnostic pop
+}
+
+/**
+ * Free a struct sync_file_info structure
+ *
+ * Available since API level 26.
+ */
+void sync_file_info_free(struct sync_file_info* info) /* __INTRODUCED_IN(26) */;
+
+#endif /* __ANDROID_API__ >= 26 */
+
+__END_DECLS
+
+#endif /* ANDROID_SYNC_H */
+
+/** @} */
diff --git a/.ci/android_headers/sync/sync.h b/.ci/android_headers/sync/sync.h
new file mode 100644
index 0000000..4ec6d4c
--- /dev/null
+++ b/.ci/android_headers/sync/sync.h
@@ -0,0 +1,50 @@
+// clang-format off
+/*
+ *  sync.h
+ *
+ *   Copyright 2012 Google, Inc
+ *
+ *  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.
+ */
+
+#ifndef __SYS_CORE_SYNC_H
+#define __SYS_CORE_SYNC_H
+
+/* This file contains the legacy sync interface used by Android platform and
+ * device code. The direct contents will be removed over time as code
+ * transitions to using the updated interface in ndk/sync.h. When this file is
+ * empty other than the ndk/sync.h include, that file will be renamed to
+ * replace this one.
+ *
+ * New code should continue to include this file (#include <android/sync.h>)
+ * instead of ndk/sync.h so the eventual rename is seamless, but should only
+ * use the things declared in ndk/sync.h.
+ *
+ * This file used to be called sync/sync.h, but we renamed to that both the
+ * platform and NDK call it android/sync.h. A symlink from the old name to this
+ * one exists temporarily to avoid having to change all sync clients
+ * simultaneously. It will be removed when they've been updated, and probably
+ * after this change has been delivered to AOSP so that integrations don't
+ * break builds.
+ */
+
+#include "../ndk/sync.h"
+
+__BEGIN_DECLS
+
+/* timeout in msecs */
+int sync_wait(int fd, int timeout);
+
+__END_DECLS
+
+#endif /* __SYS_CORE_SYNC_H */
diff --git a/.ci/android_headers/system/graphics-base-v1.0.h b/.ci/android_headers/system/graphics-base-v1.0.h
new file mode 100644
index 0000000..20a80ed
--- /dev/null
+++ b/.ci/android_headers/system/graphics-base-v1.0.h
@@ -0,0 +1,141 @@
+// clang-format off
+// This file is autogenerated by hidl-gen. Do not edit manually.
+// Source: android.hardware.graphics.common@1.0
+// Location: hardware/interfaces/graphics/common/1.0/
+
+#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_
+#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    HAL_PIXEL_FORMAT_RGBA_8888 = 1,
+    HAL_PIXEL_FORMAT_RGBX_8888 = 2,
+    HAL_PIXEL_FORMAT_RGB_888 = 3,
+    HAL_PIXEL_FORMAT_RGB_565 = 4,
+    HAL_PIXEL_FORMAT_BGRA_8888 = 5,
+    HAL_PIXEL_FORMAT_YCBCR_422_SP = 16,
+    HAL_PIXEL_FORMAT_YCRCB_420_SP = 17,
+    HAL_PIXEL_FORMAT_YCBCR_422_I = 20,
+    HAL_PIXEL_FORMAT_RGBA_FP16 = 22,
+    HAL_PIXEL_FORMAT_RAW16 = 32,
+    HAL_PIXEL_FORMAT_BLOB = 33,
+    HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 34,
+    HAL_PIXEL_FORMAT_YCBCR_420_888 = 35,
+    HAL_PIXEL_FORMAT_RAW_OPAQUE = 36,
+    HAL_PIXEL_FORMAT_RAW10 = 37,
+    HAL_PIXEL_FORMAT_RAW12 = 38,
+    HAL_PIXEL_FORMAT_RGBA_1010102 = 43,
+    HAL_PIXEL_FORMAT_Y8 = 538982489,
+    HAL_PIXEL_FORMAT_Y16 = 540422489,
+    HAL_PIXEL_FORMAT_YV12 = 842094169,
+} android_pixel_format_t;
+
+typedef enum {
+    HAL_TRANSFORM_FLIP_H = 1,   // (1 << 0)
+    HAL_TRANSFORM_FLIP_V = 2,   // (1 << 1)
+    HAL_TRANSFORM_ROT_90 = 4,   // (1 << 2)
+    HAL_TRANSFORM_ROT_180 = 3,  // (FLIP_H | FLIP_V)
+    HAL_TRANSFORM_ROT_270 = 7,  // ((FLIP_H | FLIP_V) | ROT_90)
+} android_transform_t;
+
+typedef enum {
+    HAL_DATASPACE_UNKNOWN = 0,
+    HAL_DATASPACE_ARBITRARY = 1,
+    HAL_DATASPACE_STANDARD_SHIFT = 16,
+    HAL_DATASPACE_STANDARD_MASK = 4128768,                      // (63 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_UNSPECIFIED = 0,                     // (0 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT709 = 65536,                       // (1 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_625 = 131072,                  // (2 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED = 196608,       // (3 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_525 = 262144,                  // (4 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED = 327680,       // (5 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT2020 = 393216,                     // (6 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT2020_CONSTANT_LUMINANCE = 458752,  // (7 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_BT470M = 524288,                     // (8 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_FILM = 589824,                       // (9 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_DCI_P3 = 655360,                     // (10 << STANDARD_SHIFT)
+    HAL_DATASPACE_STANDARD_ADOBE_RGB = 720896,                  // (11 << STANDARD_SHIFT)
+    HAL_DATASPACE_TRANSFER_SHIFT = 22,
+    HAL_DATASPACE_TRANSFER_MASK = 130023424,       // (31 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_UNSPECIFIED = 0,        // (0 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_LINEAR = 4194304,       // (1 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_SRGB = 8388608,         // (2 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_SMPTE_170M = 12582912,  // (3 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_GAMMA2_2 = 16777216,    // (4 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_GAMMA2_6 = 20971520,    // (5 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_GAMMA2_8 = 25165824,    // (6 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_ST2084 = 29360128,      // (7 << TRANSFER_SHIFT)
+    HAL_DATASPACE_TRANSFER_HLG = 33554432,         // (8 << TRANSFER_SHIFT)
+    HAL_DATASPACE_RANGE_SHIFT = 27,
+    HAL_DATASPACE_RANGE_MASK = 939524096,      // (7 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_UNSPECIFIED = 0,       // (0 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_FULL = 134217728,      // (1 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_LIMITED = 268435456,   // (2 << RANGE_SHIFT)
+    HAL_DATASPACE_RANGE_EXTENDED = 402653184,  // (3 << RANGE_SHIFT)
+    HAL_DATASPACE_SRGB_LINEAR = 512,
+    HAL_DATASPACE_V0_SRGB_LINEAR = 138477568,  // ((STANDARD_BT709 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_V0_SCRGB_LINEAR =
+        406913024,  // ((STANDARD_BT709 | TRANSFER_LINEAR) | RANGE_EXTENDED)
+    HAL_DATASPACE_SRGB = 513,
+    HAL_DATASPACE_V0_SRGB = 142671872,   // ((STANDARD_BT709 | TRANSFER_SRGB) | RANGE_FULL)
+    HAL_DATASPACE_V0_SCRGB = 411107328,  // ((STANDARD_BT709 | TRANSFER_SRGB) | RANGE_EXTENDED)
+    HAL_DATASPACE_JFIF = 257,
+    HAL_DATASPACE_V0_JFIF = 146931712,  // ((STANDARD_BT601_625 | TRANSFER_SMPTE_170M) | RANGE_FULL)
+    HAL_DATASPACE_BT601_625 = 258,
+    HAL_DATASPACE_V0_BT601_625 =
+        281149440,  // ((STANDARD_BT601_625 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_BT601_525 = 259,
+    HAL_DATASPACE_V0_BT601_525 =
+        281280512,  // ((STANDARD_BT601_525 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_BT709 = 260,
+    HAL_DATASPACE_V0_BT709 = 281083904,  // ((STANDARD_BT709 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_DCI_P3_LINEAR = 139067392,  // ((STANDARD_DCI_P3 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_DCI_P3 = 155844608,  // ((STANDARD_DCI_P3 | TRANSFER_GAMMA2_6) | RANGE_FULL)
+    HAL_DATASPACE_DISPLAY_P3_LINEAR =
+        139067392,                         // ((STANDARD_DCI_P3 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_DISPLAY_P3 = 143261696,  // ((STANDARD_DCI_P3 | TRANSFER_SRGB) | RANGE_FULL)
+    HAL_DATASPACE_ADOBE_RGB = 151715840,  // ((STANDARD_ADOBE_RGB | TRANSFER_GAMMA2_2) | RANGE_FULL)
+    HAL_DATASPACE_BT2020_LINEAR = 138805248,  // ((STANDARD_BT2020 | TRANSFER_LINEAR) | RANGE_FULL)
+    HAL_DATASPACE_BT2020 = 147193856,     // ((STANDARD_BT2020 | TRANSFER_SMPTE_170M) | RANGE_FULL)
+    HAL_DATASPACE_BT2020_PQ = 163971072,  // ((STANDARD_BT2020 | TRANSFER_ST2084) | RANGE_FULL)
+    HAL_DATASPACE_DEPTH = 4096,
+    HAL_DATASPACE_SENSOR = 4097,
+} android_dataspace_t;
+
+typedef enum {
+    HAL_COLOR_MODE_NATIVE = 0,
+    HAL_COLOR_MODE_STANDARD_BT601_625 = 1,
+    HAL_COLOR_MODE_STANDARD_BT601_625_UNADJUSTED = 2,
+    HAL_COLOR_MODE_STANDARD_BT601_525 = 3,
+    HAL_COLOR_MODE_STANDARD_BT601_525_UNADJUSTED = 4,
+    HAL_COLOR_MODE_STANDARD_BT709 = 5,
+    HAL_COLOR_MODE_DCI_P3 = 6,
+    HAL_COLOR_MODE_SRGB = 7,
+    HAL_COLOR_MODE_ADOBE_RGB = 8,
+    HAL_COLOR_MODE_DISPLAY_P3 = 9,
+} android_color_mode_t;
+
+typedef enum {
+    HAL_COLOR_TRANSFORM_IDENTITY = 0,
+    HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX = 1,
+    HAL_COLOR_TRANSFORM_VALUE_INVERSE = 2,
+    HAL_COLOR_TRANSFORM_GRAYSCALE = 3,
+    HAL_COLOR_TRANSFORM_CORRECT_PROTANOPIA = 4,
+    HAL_COLOR_TRANSFORM_CORRECT_DEUTERANOPIA = 5,
+    HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA = 6,
+} android_color_transform_t;
+
+typedef enum {
+    HAL_HDR_DOLBY_VISION = 1,
+    HAL_HDR_HDR10 = 2,
+    HAL_HDR_HLG = 3,
+} android_hdr_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_0_EXPORTED_CONSTANTS_H_
diff --git a/.ci/android_headers/system/graphics-base-v1.1.h b/.ci/android_headers/system/graphics-base-v1.1.h
new file mode 100644
index 0000000..a90da62
--- /dev/null
+++ b/.ci/android_headers/system/graphics-base-v1.1.h
@@ -0,0 +1,49 @@
+// clang-format off
+// This file is autogenerated by hidl-gen. Do not edit manually.
+// Source: android.hardware.graphics.common@1.1
+// Location: hardware/interfaces/graphics/common/1.1/
+
+#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_1_EXPORTED_CONSTANTS_H_
+#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_1_EXPORTED_CONSTANTS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    HAL_PIXEL_FORMAT_DEPTH_16 = 48,
+    HAL_PIXEL_FORMAT_DEPTH_24 = 49,
+    HAL_PIXEL_FORMAT_DEPTH_24_STENCIL_8 = 50,
+    HAL_PIXEL_FORMAT_DEPTH_32F = 51,
+    HAL_PIXEL_FORMAT_DEPTH_32F_STENCIL_8 = 52,
+    HAL_PIXEL_FORMAT_STENCIL_8 = 53,
+    HAL_PIXEL_FORMAT_YCBCR_P010 = 54,
+} android_pixel_format_v1_1_t;
+
+typedef enum {
+    HAL_DATASPACE_BT2020_ITU =
+        281411584,  // ((STANDARD_BT2020 | TRANSFER_SMPTE_170M) | RANGE_LIMITED)
+    HAL_DATASPACE_BT2020_ITU_PQ =
+        298188800,  // ((STANDARD_BT2020 | TRANSFER_ST2084) | RANGE_LIMITED)
+    HAL_DATASPACE_BT2020_ITU_HLG = 302383104,  // ((STANDARD_BT2020 | TRANSFER_HLG) | RANGE_LIMITED)
+    HAL_DATASPACE_BT2020_HLG = 168165376,      // ((STANDARD_BT2020 | TRANSFER_HLG) | RANGE_FULL)
+} android_dataspace_v1_1_t;
+
+typedef enum {
+    HAL_COLOR_MODE_BT2020 = 10,
+    HAL_COLOR_MODE_BT2100_PQ = 11,
+    HAL_COLOR_MODE_BT2100_HLG = 12,
+} android_color_mode_v1_1_t;
+
+typedef enum {
+    HAL_RENDER_INTENT_COLORIMETRIC = 0,
+    HAL_RENDER_INTENT_ENHANCE = 1,
+    HAL_RENDER_INTENT_TONE_MAP_COLORIMETRIC = 2,
+    HAL_RENDER_INTENT_TONE_MAP_ENHANCE = 3,
+} android_render_intent_v1_1_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_1_EXPORTED_CONSTANTS_H_
diff --git a/.ci/android_headers/system/graphics-base-v1.2.h b/.ci/android_headers/system/graphics-base-v1.2.h
new file mode 100644
index 0000000..baddf79
--- /dev/null
+++ b/.ci/android_headers/system/graphics-base-v1.2.h
@@ -0,0 +1,32 @@
+// clang-format off
+// This file is autogenerated by hidl-gen. Do not edit manually.
+// Source: android.hardware.graphics.common@1.2
+// Location: hardware/interfaces/graphics/common/1.2/
+
+#ifndef HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_2_EXPORTED_CONSTANTS_H_
+#define HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_2_EXPORTED_CONSTANTS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+    HAL_HDR_HDR10_PLUS = 4,
+} android_hdr_v1_2_t;
+
+typedef enum {
+    HAL_DATASPACE_DISPLAY_BT2020 = 142999552 /* ((STANDARD_BT2020 | TRANSFER_SRGB) | RANGE_FULL) */,
+    HAL_DATASPACE_DYNAMIC_DEPTH = 4098 /* 0x1002 */,
+    HAL_DATASPACE_JPEG_APP_SEGMENTS = 4099 /* 0x1003 */,
+    HAL_DATASPACE_HEIF = 4100 /* 0x1004 */,
+} android_dataspace_v1_2_t;
+
+typedef enum {
+    HAL_PIXEL_FORMAT_HSV_888 = 55 /* 0x37 */,
+} android_pixel_format_v1_2_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  // HIDL_GENERATED_ANDROID_HARDWARE_GRAPHICS_COMMON_V1_2_EXPORTED_CONSTANTS_H_
diff --git a/.ci/android_headers/system/graphics-base.h b/.ci/android_headers/system/graphics-base.h
new file mode 100644
index 0000000..073b985
--- /dev/null
+++ b/.ci/android_headers/system/graphics-base.h
@@ -0,0 +1,9 @@
+// clang-format off
+#ifndef SYSTEM_CORE_GRAPHICS_BASE_H_
+#define SYSTEM_CORE_GRAPHICS_BASE_H_
+
+#include "graphics-base-v1.0.h"
+#include "graphics-base-v1.1.h"
+#include "graphics-base-v1.2.h"
+
+#endif  // SYSTEM_CORE_GRAPHICS_BASE_H_
diff --git a/.ci/android_headers/system/graphics-sw.h b/.ci/android_headers/system/graphics-sw.h
new file mode 100644
index 0000000..dd29e63
--- /dev/null
+++ b/.ci/android_headers/system/graphics-sw.h
@@ -0,0 +1,17 @@
+// clang-format off
+#ifndef SYSTEM_CORE_GRAPHICS_SW_H_
+#define SYSTEM_CORE_GRAPHICS_SW_H_
+
+/* Software formats not in the HAL definitions. */
+typedef enum {
+    HAL_PIXEL_FORMAT_YCBCR_422_888 = 39,   // 0x27
+    HAL_PIXEL_FORMAT_YCBCR_444_888 = 40,   // 0x28
+    HAL_PIXEL_FORMAT_FLEX_RGB_888 = 41,    // 0x29
+    HAL_PIXEL_FORMAT_FLEX_RGBA_8888 = 42,  // 0x2A
+} android_pixel_format_sw_t;
+
+/* for compatibility */
+#define HAL_PIXEL_FORMAT_YCbCr_422_888 HAL_PIXEL_FORMAT_YCBCR_422_888
+#define HAL_PIXEL_FORMAT_YCbCr_444_888 HAL_PIXEL_FORMAT_YCBCR_444_888
+
+#endif  // SYSTEM_CORE_GRAPHICS_SW_H_
diff --git a/.ci/android_headers/system/graphics.h b/.ci/android_headers/system/graphics.h
new file mode 100644
index 0000000..8693587
--- /dev/null
+++ b/.ci/android_headers/system/graphics.h
@@ -0,0 +1,269 @@
+// clang-format off
+/*
+ * Copyright (C) 2011 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.
+ */
+
+#ifndef SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H
+#define SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/*
+ * Some of the enums are now defined in HIDL in hardware/interfaces and are
+ * generated.
+ */
+#include "graphics-base.h"
+#include "graphics-sw.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* for compatibility */
+#define HAL_PIXEL_FORMAT_YCbCr_420_888 HAL_PIXEL_FORMAT_YCBCR_420_888
+#define HAL_PIXEL_FORMAT_YCbCr_422_SP HAL_PIXEL_FORMAT_YCBCR_422_SP
+#define HAL_PIXEL_FORMAT_YCrCb_420_SP HAL_PIXEL_FORMAT_YCRCB_420_SP
+#define HAL_PIXEL_FORMAT_YCbCr_422_I HAL_PIXEL_FORMAT_YCBCR_422_I
+typedef android_pixel_format_t android_pixel_format;
+typedef android_transform_t android_transform;
+typedef android_dataspace_t android_dataspace;
+typedef android_color_mode_t android_color_mode;
+typedef android_color_transform_t android_color_transform;
+typedef android_hdr_t android_hdr;
+
+/*
+ * If the HAL needs to create service threads to handle graphics related
+ * tasks, these threads need to run at HAL_PRIORITY_URGENT_DISPLAY priority
+ * if they can block the main rendering thread in any way.
+ *
+ * the priority of the current thread can be set with:
+ *
+ *      #include <sys/resource.h>
+ *      setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
+ *
+ */
+
+#define HAL_PRIORITY_URGENT_DISPLAY     (-8)
+
+/*
+ * Structure for describing YCbCr formats for consumption by applications.
+ * This is used with HAL_PIXEL_FORMAT_YCbCr_*_888.
+ *
+ * Buffer chroma subsampling is defined in the format.
+ * e.g. HAL_PIXEL_FORMAT_YCbCr_420_888 has subsampling 4:2:0.
+ *
+ * Buffers must have a 8 bit depth.
+ *
+ * y, cb, and cr point to the first byte of their respective planes.
+ *
+ * Stride describes the distance in bytes from the first value of one row of
+ * the image to the first value of the next row.  It includes the width of the
+ * image plus padding.
+ * ystride is the stride of the luma plane.
+ * cstride is the stride of the chroma planes.
+ *
+ * chroma_step is the distance in bytes from one chroma pixel value to the
+ * next.  This is 2 bytes for semiplanar (because chroma values are interleaved
+ * and each chroma value is one byte) and 1 for planar.
+ */
+
+struct android_ycbcr {
+    void *y;
+    void *cb;
+    void *cr;
+    size_t ystride;
+    size_t cstride;
+    size_t chroma_step;
+
+    /** reserved for future use, set to 0 by gralloc's (*lock_ycbcr)() */
+    uint32_t reserved[8];
+};
+
+/*
+ * Structures for describing flexible YUVA/RGBA formats for consumption by
+ * applications. Such flexible formats contain a plane for each component (e.g.
+ * red, green, blue), where each plane is laid out in a grid-like pattern
+ * occupying unique byte addresses and with consistent byte offsets between
+ * neighboring pixels.
+ *
+ * The android_flex_layout structure is used with any pixel format that can be
+ * represented by it, such as:
+ *  - HAL_PIXEL_FORMAT_YCbCr_*_888
+ *  - HAL_PIXEL_FORMAT_FLEX_RGB*_888
+ *  - HAL_PIXEL_FORMAT_RGB[AX]_888[8],BGRA_8888,RGB_888
+ *  - HAL_PIXEL_FORMAT_YV12,Y8,Y16,YCbCr_422_SP/I,YCrCb_420_SP
+ *  - even implementation defined formats that can be represented by
+ *    the structures
+ *
+ * Vertical increment (aka. row increment or stride) describes the distance in
+ * bytes from the first pixel of one row to the first pixel of the next row
+ * (below) for the component plane. This can be negative.
+ *
+ * Horizontal increment (aka. column or pixel increment) describes the distance
+ * in bytes from one pixel to the next pixel (to the right) on the same row for
+ * the component plane. This can be negative.
+ *
+ * Each plane can be subsampled either vertically or horizontally by
+ * a power-of-two factor.
+ *
+ * The bit-depth of each component can be arbitrary, as long as the pixels are
+ * laid out on whole bytes, in native byte-order, using the most significant
+ * bits of each unit.
+ */
+
+typedef enum android_flex_component {
+    /* luma */
+    FLEX_COMPONENT_Y = 1 << 0,
+    /* chroma blue */
+    FLEX_COMPONENT_Cb = 1 << 1,
+    /* chroma red */
+    FLEX_COMPONENT_Cr = 1 << 2,
+
+    /* red */
+    FLEX_COMPONENT_R = 1 << 10,
+    /* green */
+    FLEX_COMPONENT_G = 1 << 11,
+    /* blue */
+    FLEX_COMPONENT_B = 1 << 12,
+
+    /* alpha */
+    FLEX_COMPONENT_A = 1 << 30,
+} android_flex_component_t;
+
+typedef struct android_flex_plane {
+    /* pointer to the first byte of the top-left pixel of the plane. */
+    uint8_t *top_left;
+
+    android_flex_component_t component;
+
+    /* bits allocated for the component in each pixel. Must be a positive
+       multiple of 8. */
+    int32_t bits_per_component;
+    /* number of the most significant bits used in the format for this
+       component. Must be between 1 and bits_per_component, inclusive. */
+    int32_t bits_used;
+
+    /* horizontal increment */
+    int32_t h_increment;
+    /* vertical increment */
+    int32_t v_increment;
+    /* horizontal subsampling. Must be a positive power of 2. */
+    int32_t h_subsampling;
+    /* vertical subsampling. Must be a positive power of 2. */
+    int32_t v_subsampling;
+} android_flex_plane_t;
+
+typedef enum android_flex_format {
+    /* not a flexible format */
+    FLEX_FORMAT_INVALID = 0x0,
+    FLEX_FORMAT_Y = FLEX_COMPONENT_Y,
+    FLEX_FORMAT_YCbCr = FLEX_COMPONENT_Y | FLEX_COMPONENT_Cb | FLEX_COMPONENT_Cr,
+    FLEX_FORMAT_YCbCrA = FLEX_FORMAT_YCbCr | FLEX_COMPONENT_A,
+    FLEX_FORMAT_RGB = FLEX_COMPONENT_R | FLEX_COMPONENT_G | FLEX_COMPONENT_B,
+    FLEX_FORMAT_RGBA = FLEX_FORMAT_RGB | FLEX_COMPONENT_A,
+} android_flex_format_t;
+
+typedef struct android_flex_layout {
+    /* the kind of flexible format */
+    android_flex_format_t format;
+
+    /* number of planes; 0 for FLEX_FORMAT_INVALID */
+    uint32_t num_planes;
+    /* a plane for each component; ordered in increasing component value order.
+       E.g. FLEX_FORMAT_RGBA maps 0 -> R, 1 -> G, etc.
+       Can be NULL for FLEX_FORMAT_INVALID */
+    android_flex_plane_t *planes;
+} android_flex_layout_t;
+
+/**
+ * Structure used to define depth point clouds for format HAL_PIXEL_FORMAT_BLOB
+ * with dataSpace value of HAL_DATASPACE_DEPTH.
+ * When locking a native buffer of the above format and dataSpace value,
+ * the vaddr pointer can be cast to this structure.
+ *
+ * A variable-length list of (x,y,z, confidence) 3D points, as floats.  (x, y,
+ * z) represents a measured point's position, with the coordinate system defined
+ * by the data source.  Confidence represents the estimated likelihood that this
+ * measurement is correct. It is between 0.f and 1.f, inclusive, with 1.f ==
+ * 100% confidence.
+ *
+ * num_points is the number of points in the list
+ *
+ * xyz_points is the flexible array of floating-point values.
+ *   It contains (num_points) * 4 floats.
+ *
+ *   For example:
+ *     android_depth_points d = get_depth_buffer();
+ *     struct {
+ *       float x; float y; float z; float confidence;
+ *     } firstPoint, lastPoint;
+ *
+ *     firstPoint.x = d.xyzc_points[0];
+ *     firstPoint.y = d.xyzc_points[1];
+ *     firstPoint.z = d.xyzc_points[2];
+ *     firstPoint.confidence = d.xyzc_points[3];
+ *     lastPoint.x = d.xyzc_points[(d.num_points - 1) * 4 + 0];
+ *     lastPoint.y = d.xyzc_points[(d.num_points - 1) * 4 + 1];
+ *     lastPoint.z = d.xyzc_points[(d.num_points - 1) * 4 + 2];
+ *     lastPoint.confidence = d.xyzc_points[(d.num_points - 1) * 4 + 3];
+ */
+
+struct android_depth_points {
+    uint32_t num_points;
+
+    /** reserved for future use, set to 0 by gralloc's (*lock)() */
+    uint32_t reserved[8];
+
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wc99-extensions"
+#endif
+    float xyzc_points[];
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#endif
+};
+
+/**
+  * These structures are used to define the reference display's
+  * capabilities for HDR content. Display engine can use this
+  * to better tone map content to user's display.
+  * Color is defined in CIE XYZ coordinates
+  */
+struct android_xy_color {
+    float x;
+    float y;
+};
+
+struct android_smpte2086_metadata {
+    struct android_xy_color displayPrimaryRed;
+    struct android_xy_color displayPrimaryGreen;
+    struct android_xy_color displayPrimaryBlue;
+    struct android_xy_color whitePoint;
+    float maxLuminance;
+    float minLuminance;
+};
+
+struct android_cta861_3_metadata {
+    float maxContentLightLevel;
+    float maxFrameAverageLightLevel;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SYSTEM_CORE_INCLUDE_ANDROID_GRAPHICS_H */
diff --git a/.ci/android_headers/ui/GraphicBuffer.h b/.ci/android_headers/ui/GraphicBuffer.h
new file mode 100644
index 0000000..701340c
--- /dev/null
+++ b/.ci/android_headers/ui/GraphicBuffer.h
@@ -0,0 +1,286 @@
+// clang-format off
+/*
+ * Copyright (C) 2007 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.
+ */
+
+#ifndef ANDROID_GRAPHIC_BUFFER_H
+#define ANDROID_GRAPHIC_BUFFER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <android/hardware_buffer.h>
+#include <ui/ANativeObjectBase.h>
+#include <ui/GraphicBufferMapper.h>
+#include <ui/PixelFormat.h>
+#include <ui/Rect.h>
+#include <utils/Flattenable.h>
+#include <utils/RefBase.h>
+
+#include <nativebase/nativebase.h>
+
+#include <hardware/gralloc.h>
+
+namespace android {
+
+class GraphicBufferMapper;
+
+using GraphicBufferDeathCallback = std::function<void(void* /*context*/, uint64_t bufferId)>;
+
+// ===========================================================================
+// GraphicBuffer
+// ===========================================================================
+
+class GraphicBuffer
+    : public ANativeObjectBase<ANativeWindowBuffer, GraphicBuffer, RefBase>,
+      public Flattenable<GraphicBuffer>
+{
+    friend class Flattenable<GraphicBuffer>;
+public:
+
+    enum {
+        USAGE_SW_READ_NEVER     = GRALLOC_USAGE_SW_READ_NEVER,
+        USAGE_SW_READ_RARELY    = GRALLOC_USAGE_SW_READ_RARELY,
+        USAGE_SW_READ_OFTEN     = GRALLOC_USAGE_SW_READ_OFTEN,
+        USAGE_SW_READ_MASK      = GRALLOC_USAGE_SW_READ_MASK,
+
+        USAGE_SW_WRITE_NEVER    = GRALLOC_USAGE_SW_WRITE_NEVER,
+        USAGE_SW_WRITE_RARELY   = GRALLOC_USAGE_SW_WRITE_RARELY,
+        USAGE_SW_WRITE_OFTEN    = GRALLOC_USAGE_SW_WRITE_OFTEN,
+        USAGE_SW_WRITE_MASK     = GRALLOC_USAGE_SW_WRITE_MASK,
+
+        USAGE_SOFTWARE_MASK     = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK,
+
+        USAGE_PROTECTED         = GRALLOC_USAGE_PROTECTED,
+
+        USAGE_HW_TEXTURE        = GRALLOC_USAGE_HW_TEXTURE,
+        USAGE_HW_RENDER         = GRALLOC_USAGE_HW_RENDER,
+        USAGE_HW_2D             = GRALLOC_USAGE_HW_2D,
+        USAGE_HW_COMPOSER       = GRALLOC_USAGE_HW_COMPOSER,
+        USAGE_HW_VIDEO_ENCODER  = GRALLOC_USAGE_HW_VIDEO_ENCODER,
+        USAGE_HW_MASK           = GRALLOC_USAGE_HW_MASK,
+
+        USAGE_CURSOR            = GRALLOC_USAGE_CURSOR,
+    };
+
+    static sp<GraphicBuffer> from(ANativeWindowBuffer *);
+
+    static GraphicBuffer* fromAHardwareBuffer(AHardwareBuffer*);
+    static GraphicBuffer const* fromAHardwareBuffer(AHardwareBuffer const*);
+    AHardwareBuffer* toAHardwareBuffer();
+    AHardwareBuffer const* toAHardwareBuffer() const;
+
+    // Create a GraphicBuffer to be unflatten'ed into or be reallocated.
+    GraphicBuffer();
+
+    // Create a GraphicBuffer by allocating and managing a buffer internally.
+    // This function is privileged.  See reallocate for details.
+    GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+            uint32_t inLayerCount, uint64_t inUsage,
+            std::string requestorName = "<Unknown>");
+
+    // Create a GraphicBuffer from an existing handle.
+    enum HandleWrapMethod : uint8_t {
+        // Wrap and use the handle directly.  It assumes the handle has been
+        // registered and never fails.  The handle must have a longer lifetime
+        // than this wrapping GraphicBuffer.
+        //
+        // This can be used when, for example, you want to wrap a handle that
+        // is already managed by another GraphicBuffer.
+        WRAP_HANDLE,
+
+        // Take ownership of the handle and use it directly.  It assumes the
+        // handle has been registered and never fails.
+        //
+        // This can be used to manage an already registered handle with
+        // GraphicBuffer.
+        TAKE_HANDLE,
+
+        // Take onwership of an unregistered handle and use it directly.  It
+        // can fail when the buffer does not register.  There is no ownership
+        // transfer on failures.
+        //
+        // This can be used to, for example, create a GraphicBuffer from a
+        // handle returned by Parcel::readNativeHandle.
+        TAKE_UNREGISTERED_HANDLE,
+
+        // Make a clone of the handle and use the cloned handle.  It can fail
+        // when cloning fails or when the buffer does not register.  There is
+        // never ownership transfer.
+        //
+        // This can be used to create a GraphicBuffer from a handle that
+        // cannot be used directly, such as one from hidl_handle.
+        CLONE_HANDLE,
+    };
+    GraphicBuffer(const native_handle_t* inHandle, HandleWrapMethod method, uint32_t inWidth,
+                  uint32_t inHeight, PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage,
+                  uint32_t inStride);
+
+    // These functions are deprecated because they only take 32 bits of usage
+    GraphicBuffer(const native_handle_t* inHandle, HandleWrapMethod method, uint32_t inWidth,
+                  uint32_t inHeight, PixelFormat inFormat, uint32_t inLayerCount, uint32_t inUsage,
+                  uint32_t inStride)
+          : GraphicBuffer(inHandle, method, inWidth, inHeight, inFormat, inLayerCount,
+                          static_cast<uint64_t>(inUsage), inStride) {}
+    GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+            uint32_t inLayerCount, uint32_t inUsage, uint32_t inStride,
+            native_handle_t* inHandle, bool keepOwnership);
+    GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+            uint32_t inUsage, std::string requestorName = "<Unknown>");
+
+    // return status
+    status_t initCheck() const;
+
+    uint32_t getWidth() const           { return static_cast<uint32_t>(width); }
+    uint32_t getHeight() const          { return static_cast<uint32_t>(height); }
+    uint32_t getStride() const          { return static_cast<uint32_t>(stride); }
+    uint64_t getUsage() const           { return usage; }
+    PixelFormat getPixelFormat() const  { return format; }
+    uint32_t getLayerCount() const      { return static_cast<uint32_t>(layerCount); }
+    Rect getBounds() const              { return Rect(width, height); }
+    uint64_t getId() const              { return mId; }
+
+    uint32_t getGenerationNumber() const { return mGenerationNumber; }
+    void setGenerationNumber(uint32_t generation) {
+        mGenerationNumber = generation;
+    }
+
+    // This function is privileged.  It requires access to the allocator
+    // device or service, which usually involves adding suitable selinux
+    // rules.
+    status_t reallocate(uint32_t inWidth, uint32_t inHeight,
+            PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage);
+
+    bool needsReallocation(uint32_t inWidth, uint32_t inHeight,
+            PixelFormat inFormat, uint32_t inLayerCount, uint64_t inUsage);
+
+    // For the following two lock functions, if bytesPerStride or bytesPerPixel
+    // are unknown or variable, -1 will be returned
+    status_t lock(uint32_t inUsage, void** vaddr, int32_t* outBytesPerPixel = nullptr,
+                  int32_t* outBytesPerStride = nullptr);
+    status_t lock(uint32_t inUsage, const Rect& rect, void** vaddr,
+                  int32_t* outBytesPerPixel = nullptr, int32_t* outBytesPerStride = nullptr);
+    // For HAL_PIXEL_FORMAT_YCbCr_420_888
+    status_t lockYCbCr(uint32_t inUsage, android_ycbcr *ycbcr);
+    status_t lockYCbCr(uint32_t inUsage, const Rect& rect,
+            android_ycbcr *ycbcr);
+    status_t unlock();
+    // For the following three lockAsync functions, if bytesPerStride or bytesPerPixel
+    // are unknown or variable, -1 will be returned
+    status_t lockAsync(uint32_t inUsage, void** vaddr, int fenceFd,
+                       int32_t* outBytesPerPixel = nullptr, int32_t* outBytesPerStride = nullptr);
+    status_t lockAsync(uint32_t inUsage, const Rect& rect, void** vaddr, int fenceFd,
+                       int32_t* outBytesPerPixel = nullptr, int32_t* outBytesPerStride = nullptr);
+    status_t lockAsync(uint64_t inProducerUsage, uint64_t inConsumerUsage, const Rect& rect,
+                       void** vaddr, int fenceFd, int32_t* outBytesPerPixel = nullptr,
+                       int32_t* outBytesPerStride = nullptr);
+    status_t lockAsyncYCbCr(uint32_t inUsage, android_ycbcr *ycbcr,
+            int fenceFd);
+    status_t lockAsyncYCbCr(uint32_t inUsage, const Rect& rect,
+            android_ycbcr *ycbcr, int fenceFd);
+    status_t unlockAsync(int *fenceFd);
+
+    status_t isSupported(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+                         uint32_t inLayerCount, uint64_t inUsage, bool* outSupported) const;
+
+    ANativeWindowBuffer* getNativeBuffer() const;
+
+    // for debugging
+    static void dumpAllocationsToSystemLog();
+
+    // Flattenable protocol
+    size_t getFlattenedSize() const;
+    size_t getFdCount() const;
+    status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
+    status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
+
+    GraphicBufferMapper::Version getBufferMapperVersion() const {
+        return mBufferMapper.getMapperVersion();
+    }
+
+    void addDeathCallback(GraphicBufferDeathCallback deathCallback, void* context);
+
+private:
+    ~GraphicBuffer();
+
+    enum {
+        ownNone   = 0,
+        ownHandle = 1,
+        ownData   = 2,
+    };
+
+    inline const GraphicBufferMapper& getBufferMapper() const {
+        return mBufferMapper;
+    }
+    inline GraphicBufferMapper& getBufferMapper() {
+        return mBufferMapper;
+    }
+    uint8_t mOwner;
+
+private:
+    friend class Surface;
+    friend class BpSurface;
+    friend class BnSurface;
+    friend class LightRefBase<GraphicBuffer>;
+    GraphicBuffer(const GraphicBuffer& rhs);
+    GraphicBuffer& operator = (const GraphicBuffer& rhs);
+    const GraphicBuffer& operator = (const GraphicBuffer& rhs) const;
+
+    status_t initWithSize(uint32_t inWidth, uint32_t inHeight,
+            PixelFormat inFormat, uint32_t inLayerCount,
+            uint64_t inUsage, std::string requestorName);
+
+    status_t initWithHandle(const native_handle_t* inHandle, HandleWrapMethod method,
+                            uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+                            uint32_t inLayerCount, uint64_t inUsage, uint32_t inStride);
+
+    void free_handle();
+
+    GraphicBufferMapper& mBufferMapper;
+    ssize_t mInitCheck;
+
+    // numbers of fds/ints in native_handle_t to flatten
+    uint32_t mTransportNumFds;
+    uint32_t mTransportNumInts;
+
+    uint64_t mId;
+
+    // Stores the generation number of this buffer. If this number does not
+    // match the BufferQueue's internal generation number (set through
+    // IGBP::setGenerationNumber), attempts to attach the buffer will fail.
+    uint32_t mGenerationNumber;
+
+    // Send a callback when a GraphicBuffer dies.
+    //
+    // This is used for BufferStateLayer caching. GraphicBuffers are refcounted per process. When
+    // A GraphicBuffer doesn't have any more sp<> in a process, it is destroyed. This causes
+    // problems when trying to implicitcly cache across process boundaries. Ideally, both sides
+    // of the cache would hold onto wp<> references. When an app dropped its sp<>, the GraphicBuffer
+    // would be destroyed. Unfortunately, when SurfaceFlinger has only a wp<> reference to the
+    // GraphicBuffer, it immediately goes out of scope in the SurfaceFlinger process. SurfaceFlinger
+    // must hold onto a sp<> to the buffer. When the GraphicBuffer goes out of scope in the app's
+    // process, the client side cache will get this callback. It erases the buffer from its cache
+    // and informs SurfaceFlinger that it should drop its strong pointer reference to the buffer.
+    std::vector<std::pair<GraphicBufferDeathCallback, void* /*mDeathCallbackContext*/>>
+            mDeathCallbacks;
+};
+
+}; // namespace android
+
+#endif // ANDROID_GRAPHIC_BUFFER_H
diff --git a/.ci/android_headers/utils/Trace.h b/.ci/android_headers/utils/Trace.h
new file mode 100644
index 0000000..88c4db5
--- /dev/null
+++ b/.ci/android_headers/utils/Trace.h
@@ -0,0 +1,62 @@
+// clang-format off
+/*
+ * Copyright (C) 2012 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.
+ */
+
+#ifndef ANDROID_TRACE_H
+#define ANDROID_TRACE_H
+
+#if defined(_WIN32)
+
+#define ATRACE_NAME(...)
+#define ATRACE_CALL()
+
+#else  // !_WIN32
+
+#include <stdint.h>
+
+#include <cutils/trace.h>
+
+// See <cutils/trace.h> for more ATRACE_* macros.
+
+// ATRACE_NAME traces from its location until the end of its enclosing scope.
+#define _PASTE(x, y) x ## y
+#define PASTE(x, y) _PASTE(x,y)
+#define ATRACE_NAME(name) ::android::ScopedTrace PASTE(___tracer, __LINE__)(ATRACE_TAG, name)
+
+// ATRACE_CALL is an ATRACE_NAME that uses the current function name.
+#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
+
+namespace android {
+
+class ScopedTrace {
+public:
+    inline ScopedTrace(uint64_t tag, const char* name) : mTag(tag) {
+        atrace_begin(mTag, name);
+    }
+
+    inline ~ScopedTrace() {
+        atrace_end(mTag);
+    }
+
+private:
+    uint64_t mTag;
+};
+
+}  // namespace android
+
+#endif  // _WIN32
+
+#endif // ANDROID_TRACE_H
diff --git a/.clang-tidy b/.clang-tidy
new file mode 100644
index 0000000..0bb7bf0
--- /dev/null
+++ b/.clang-tidy
@@ -0,0 +1,42 @@
+# fuchsia: Conflicts with other checks
+# llvm-header-guard: Does not match drm_hwc header gusrd style 
+# Allow using ALOGE 
+
+Checks: >
+    *,
+    -fuchsia*,
+    -llvm*,
+    -cppcoreguidelines-pro-type-vararg, -hicpp-vararg,
+    -hicpp-signed-bitwise,
+
+# Turn all the warnings from the checks above into errors.
+WarningsAsErrors: "*"
+
+#HeaderFilterRegex: "^.*external/drm_hwcomposer/.*.h$"
+
+FormatStyle: google
+
+CheckOptions:
+  - { key: readability-identifier-naming.NamespaceCase,          value: lower_case }
+  - { key: readability-identifier-naming.ClassCase,              value: CamelCase  }
+  - { key: readability-identifier-naming.StructCase,             value: CamelCase  }
+  - { key: readability-identifier-naming.TemplateParameterCase,  value: CamelCase  }
+  - { key: readability-identifier-naming.FunctionCase,           value: aNy_CasE  }
+  - { key: readability-identifier-naming.VariableCase,           value: lower_case }
+  - { key: readability-identifier-naming.ClassMemberCase,        value: lower_case }
+  - { key: readability-identifier-naming.ClassMemberSuffix,      value: _          }
+  - { key: readability-identifier-naming.PrivateMemberSuffix,    value: _          }
+  - { key: readability-identifier-naming.ProtectedMemberSuffix,  value: _          }
+  - { key: readability-identifier-naming.EnumConstantCase,         value: CamelCase }
+  - { key: readability-identifier-naming.EnumConstantPrefix,       value: k         }
+  - { key: readability-identifier-naming.ConstexprVariableCase,    value: CamelCase }
+  - { key: readability-identifier-naming.ConstexprVariablePrefix,  value: k         }
+  - { key: readability-identifier-naming.GlobalConstantCase,       value: CamelCase }
+  - { key: readability-identifier-naming.GlobalConstantPrefix,     value: k         }
+  - { key: readability-identifier-naming.MemberConstantCase,       value: CamelCase }
+  - { key: readability-identifier-naming.MemberConstantPrefix,     value: k         }
+  - { key: readability-identifier-naming.StaticConstantCase,       value: CamelCase }
+  - { key: readability-identifier-naming.StaticConstantPrefix,     value: k         }
+  - { key: readability-implicit-bool-conversion.AllowIntegerConditions,  value: 1   }
+  - { key: readability-implicit-bool-conversion.AllowPointerConditions,  value: 1   }
+  - { key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic, value: 1 }
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index c97f4ff..04eb6c5 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,15 +1,37 @@
-image: ubuntu:16.04
+image: ubuntu:20.10
 
 before_script:
   - apt-get --quiet update --yes >/dev/null
-  - apt-get --quiet install --yes clang-format-5.0 git >/dev/null
+  - apt-get --quiet install --yes clang-11 clang-tidy-11 clang-format-11 git libdrm-dev blueprint-tools libgtest-dev >/dev/null
 
 stages:
+  - build
   - style
 
+build:
+  stage: build
+  script: "./.ci/.gitlab-ci-clang-build.sh"
+  artifacts:
+    when: on_failure
+    untracked: true
+
 checkstyle:
   stage: style
-  script: "./.gitlab-ci-checkcommit.sh"
+  script: "./.ci/.gitlab-ci-checkcommit.sh"
+  artifacts:
+    when: on_failure
+    untracked: true
+
+tidy-coarse:
+  stage: style
+  script: "./.ci/.gitlab-ci-clang-tidy-coarse.sh"
+  artifacts:
+    when: on_failure
+    untracked: true
+
+tidy-fine:
+  stage: style
+  script: "./.ci/.gitlab-ci-clang-tidy-fine.sh"
   artifacts:
     when: on_failure
     untracked: true
diff --git a/Android.bp b/Android.bp
index 7bb2bd6..d3c812d 100644
--- a/Android.bp
+++ b/Android.bp
@@ -38,8 +38,8 @@
     srcs: ["utils/Worker.cpp"],
 
     include_dirs: [
-        "external/drm_hwcomposer/include",
         "external/drm_hwcomposer",
+        "external/drm_hwcomposer/include",
     ],
 
     cflags: [
@@ -69,8 +69,8 @@
     ],
 
     include_dirs: [
-        "external/drm_hwcomposer/include",
         "external/drm_hwcomposer",
+        "external/drm_hwcomposer/include",
     ],
 
     static_libs: ["libdrmhwc_utils"],
@@ -81,8 +81,8 @@
     ],
 
     cppflags: [
-        "-DHWC2_USE_CPP11",
         "-DHWC2_INCLUDE_STRINGIFICATION",
+        "-DHWC2_USE_CPP11",
     ],
 
     product_variables: {
@@ -94,6 +94,7 @@
     relative_install_path: "hw",
     vendor: true,
 }
+
 cc_library_static {
     name: "drm_hwcomposer",
     defaults: ["hwcomposer.drm_defaults"],
@@ -122,9 +123,9 @@
         "utils/autolock.cpp",
         "utils/hwcutils.cpp",
 
-        "backend/BackendManager.cpp",
         "backend/Backend.cpp",
         "backend/BackendClient.cpp",
+        "backend/BackendManager.cpp",
         "backend/BackendRCarDu.cpp",
     ],
 }
diff --git a/DrmHwcTwo.cpp b/DrmHwcTwo.cpp
index 93b6fa7..8b2abfd 100644
--- a/DrmHwcTwo.cpp
+++ b/DrmHwcTwo.cpp
@@ -19,21 +19,24 @@
 
 #include "DrmHwcTwo.h"
 
-#include <cutils/properties.h>
 #include <hardware/hardware.h>
 #include <hardware/hwcomposer2.h>
-#include <inttypes.h>
-#include <log/log.h>
+#include <sync/sync.h>
 
+#include <cinttypes>
+#include <iostream>
+#include <sstream>
 #include <string>
 
 #include "backend/BackendManager.h"
 #include "bufferinfo/BufferInfoGetter.h"
 #include "compositor/DrmDisplayComposition.h"
+#include "utils/log.h"
+#include "utils/properties.h"
 
 namespace android {
 
-DrmHwcTwo::DrmHwcTwo() {
+DrmHwcTwo::DrmHwcTwo() : hwc2_device() {
   common.tag = HARDWARE_DEVICE_TAG;
   common.version = HWC_DEVICE_API_VERSION_2_0;
   common.close = HookDevClose;
@@ -58,8 +61,8 @@
     ALOGE("Failed to get crtc for display %d", static_cast<int>(displ));
     return HWC2::Error::BadDisplay;
   }
-  std::vector<DrmPlane *> display_planes;
-  for (auto &plane : drm->planes()) {
+  auto display_planes = std::vector<DrmPlane *>();
+  for (const auto &plane : drm->planes()) {
     if (plane->GetCrtcSupported(*crtc))
       display_planes.push_back(plane.get());
   }
@@ -83,8 +86,9 @@
     }
   }
 
-  auto &drmDevices = resource_manager_.getDrmDevices();
-  for (auto &device : drmDevices) {
+  const auto &drm_devices = resource_manager_.getDrmDevices();
+  for (const auto &device : drm_devices) {
+    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
     device->RegisterHotplugHandler(new DrmHotplugHandler(this, device.get()));
   }
   return ret;
@@ -103,12 +107,12 @@
 HWC2::Error DrmHwcTwo::CreateVirtualDisplay(uint32_t width, uint32_t height,
                                             int32_t *format,
                                             hwc2_display_t *display) {
-  // TODO: Implement virtual display
+  // TODO(nobody): Implement virtual display
   return unsupported(__func__, width, height, format, display);
 }
 
 HWC2::Error DrmHwcTwo::DestroyVirtualDisplay(hwc2_display_t display) {
-  // TODO: Implement virtual display
+  // TODO(nobody): Implement virtual display
   return unsupported(__func__, display);
 }
 
@@ -116,45 +120,43 @@
     DrmHwcTwo::HwcDisplay::Stats delta) {
   if (delta.total_pixops_ == 0)
     return "No stats yet";
-  double Ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_);
+  double ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_);
 
-  return (std::stringstream()
-          << " Total frames count: " << delta.total_frames_ << "\n"
-          << " Failed to test commit frames: " << delta.failed_kms_validate_
-          << "\n"
-          << " Failed to commit frames: " << delta.failed_kms_present_ << "\n"
-          << ((delta.failed_kms_present_ > 0)
-                  ? " !!! Internal failure, FIX it please\n"
-                  : "")
-          << " Flattened frames: " << delta.frames_flattened_ << "\n"
-          << " Pixel operations (free units)"
-          << " : [TOTAL: " << delta.total_pixops_
-          << " / GPU: " << delta.gpu_pixops_ << "]\n"
-          << " Composition efficiency: " << Ratio)
-      .str();
+  std::stringstream ss;
+  ss << " Total frames count: " << delta.total_frames_ << "\n"
+     << " Failed to test commit frames: " << delta.failed_kms_validate_ << "\n"
+     << " Failed to commit frames: " << delta.failed_kms_present_ << "\n"
+     << ((delta.failed_kms_present_ > 0)
+             ? " !!! Internal failure, FIX it please\n"
+             : "")
+     << " Flattened frames: " << delta.frames_flattened_ << "\n"
+     << " Pixel operations (free units)"
+     << " : [TOTAL: " << delta.total_pixops_ << " / GPU: " << delta.gpu_pixops_
+     << "]\n"
+     << " Composition efficiency: " << ratio;
+
+  return ss.str();
 }
 
 std::string DrmHwcTwo::HwcDisplay::Dump() {
-  auto out = (std::stringstream()
-              << "- Display on: " << connector_->name() << "\n"
-              << "  Flattening state: " << compositor_.GetFlatteningState()
-              << "\n"
-              << "Statistics since system boot:\n"
-              << DumpDelta(total_stats_) << "\n\n"
-              << "Statistics since last dumpsys request:\n"
-              << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n")
-                 .str();
+  std::stringstream ss;
+  ss << "- Display on: " << connector_->name() << "\n"
+     << "  Flattening state: " << compositor_.GetFlatteningState() << "\n"
+     << "Statistics since system boot:\n"
+     << DumpDelta(total_stats_) << "\n\n"
+     << "Statistics since last dumpsys request:\n"
+     << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n";
 
   memcpy(&prev_stats_, &total_stats_, sizeof(Stats));
-  return out;
+  return ss.str();
 }
 
 void DrmHwcTwo::Dump(uint32_t *outSize, char *outBuffer) {
   supported(__func__);
 
   if (outBuffer != nullptr) {
-    auto copiedBytes = mDumpString.copy(outBuffer, *outSize);
-    *outSize = static_cast<uint32_t>(copiedBytes);
+    auto copied_bytes = mDumpString.copy(outBuffer, *outSize);
+    *outSize = static_cast<uint32_t>(copied_bytes);
     return;
   }
 
@@ -170,7 +172,7 @@
 }
 
 uint32_t DrmHwcTwo::GetMaxVirtualDisplayCount() {
-  // TODO: Implement virtual display
+  // TODO(nobody): Implement virtual display
   unsupported(__func__);
   return 0;
 }
@@ -183,8 +185,8 @@
   switch (static_cast<HWC2::Callback>(descriptor)) {
     case HWC2::Callback::Hotplug: {
       SetHotplugCallback(data, function);
-      auto &drmDevices = resource_manager_.getDrmDevices();
-      for (auto &device : drmDevices)
+      const auto &drm_devices = resource_manager_.getDrmDevices();
+      for (const auto &device : drm_devices)
         HandleInitialHotplugState(device.get());
       break;
     }
@@ -212,7 +214,7 @@
                                   hwc2_display_t handle, HWC2::DisplayType type)
     : resource_manager_(resource_manager),
       drm_(drm),
-      importer_(importer),
+      importer_(std::move(importer)),
       handle_(handle),
       type_(type),
       color_transform_hint_(HAL_COLOR_TRANSFORM_IDENTITY) {
@@ -250,7 +252,7 @@
   char use_overlay_planes_prop[PROPERTY_VALUE_MAX];
   property_get("vendor.hwc.drm.use_overlay_planes", use_overlay_planes_prop,
                "1");
-  bool use_overlay_planes = atoi(use_overlay_planes_prop);
+  bool use_overlay_planes = strtol(use_overlay_planes_prop, nullptr, 10);
   for (auto &plane : *planes) {
     if (plane->type() == DRM_PLANE_TYPE_PRIMARY)
       primary_planes_.push_back(plane);
@@ -287,8 +289,8 @@
 
 HWC2::Error DrmHwcTwo::HwcDisplay::ChosePreferredConfig() {
   // Fetch the number of modes from the display
-  uint32_t num_configs;
-  HWC2::Error err = GetDisplayConfigs(&num_configs, NULL);
+  uint32_t num_configs = 0;
+  HWC2::Error err = GetDisplayConfigs(&num_configs, nullptr);
   if (err != HWC2::Error::None || !num_configs)
     return err;
 
@@ -373,11 +375,10 @@
   if (width > max.first || height > max.second)
     return HWC2::Error::Unsupported;
 
-  if (dataspace != HAL_DATASPACE_UNKNOWN &&
-      dataspace != HAL_DATASPACE_STANDARD_UNSPECIFIED)
+  if (dataspace != HAL_DATASPACE_UNKNOWN)
     return HWC2::Error::Unsupported;
 
-  // TODO: Validate format can be handled by either GL or planes
+  // TODO(nobody): Validate format can be handled by either GL or planes
   return HWC2::Error::None;
 }
 
@@ -420,7 +421,7 @@
       break;
     case HWC2::Attribute::VsyncPeriod:
       // in nanoseconds
-      *value = 1000 * 1000 * 1000 / mode->v_refresh();
+      *value = 1000.0 * 1000.0 * 1000.0 / mode->v_refresh();
       break;
     case HWC2::Attribute::DpiX:
       // Dots per 1000 inches
@@ -430,6 +431,11 @@
       // Dots per 1000 inches
       *value = mm_height ? (mode->v_display() * kUmPerInch) / mm_height : -1;
       break;
+#if PLATFORM_SDK_VERSION > 29
+    case HWC2::Attribute::ConfigGroup:
+      *value = 0; /* TODO: Add support for config groups */
+      break;
+#endif
     default:
       *value = -1;
       return HWC2::Error::BadConfig;
@@ -461,7 +467,8 @@
   // at least one non-interlaced alternative and only offer a single WxH@R
   // mode with at least the prefered mode from in DrmConnector::UpdateModes()
 
-  // TODO: Remove the following block of code until AOSP handles all modes
+  // TODO(nobody): Remove the following block of code until AOSP handles all
+  // modes
   std::vector<DrmMode> sel_modes;
 
   // Add the preferred mode first to be sure it's not dropped
@@ -480,11 +487,11 @@
   // Cycle over the modes and filter out "similar" modes, keeping only the
   // first ones in the order given by DRM (from CEA ids and timings order)
   for (const DrmMode &mode : connector_->modes()) {
-    // TODO: Remove this when 3D Attributes are in AOSP
+    // TODO(nobody): Remove this when 3D Attributes are in AOSP
     if (mode.flags() & DRM_MODE_FLAG_3D_MASK)
       continue;
 
-    // TODO: Remove this when the Interlaced attribute is in AOSP
+    // TODO(nobody): Remove this when the Interlaced attribute is in AOSP
     if (mode.flags() & DRM_MODE_FLAG_INTERLACE) {
       auto m = std::find_if(connector_->modes().begin(),
                             connector_->modes().end(),
@@ -501,7 +508,7 @@
 
     // Search for a similar WxH@R mode in the filtered list and drop it if
     // another mode with the same WxH@R has already been selected
-    // TODO: Remove this when AOSP handles duplicates modes
+    // TODO(nobody): Remove this when AOSP handles duplicates modes
     auto m = std::find_if(sel_modes.begin(), sel_modes.end(),
                           [&mode](DrmMode const &m) {
                             return m.h_display() == mode.h_display() &&
@@ -549,7 +556,7 @@
                                                       hwc2_layer_t *layers,
                                                       int32_t *layer_requests) {
   supported(__func__);
-  // TODO: I think virtual display should request
+  // TODO(nobody): I think virtual display should request
   //      HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here
   unsupported(__func__, display_requests, num_elements, layers, layer_requests);
   *num_elements = 0;
@@ -584,9 +591,10 @@
 
   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
     ++num_layers;
-    if (layers == NULL || fences == NULL) {
+    if (layers == nullptr || fences == nullptr)
       continue;
-    } else if (num_layers > *num_elements) {
+
+    if (num_layers > *num_elements) {
       ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements);
       return HWC2::Error::None;
     }
@@ -611,20 +619,7 @@
   }
 }
 
-bool DrmHwcTwo::HwcDisplay::HardwareSupportsLayerType(
-    HWC2::Composition comp_type) {
-  return comp_type == HWC2::Composition::Device ||
-         comp_type == HWC2::Composition::Cursor;
-}
-
 HWC2::Error DrmHwcTwo::HwcDisplay::CreateComposition(bool test) {
-  std::vector<DrmCompositionDisplayLayersMap> layers_map;
-  layers_map.emplace_back();
-  DrmCompositionDisplayLayersMap &map = layers_map.back();
-
-  map.display = static_cast<int>(handle_);
-  map.geometry_changed = true;  // TODO: Fix this
-
   // order the layers by z-order
   bool use_client_layer = false;
   uint32_t client_z_order = UINT32_MAX;
@@ -649,6 +644,8 @@
   if (z_map.empty())
     return HWC2::Error::BadLayer;
 
+  std::vector<DrmHwcLayer> composition_layers;
+
   // now that they're ordered by z, add them to the composition
   for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
     DrmHwcLayer layer;
@@ -658,15 +655,15 @@
       ALOGE("Failed to import layer, ret=%d", ret);
       return HWC2::Error::NoResources;
     }
-    map.layers.emplace_back(std::move(layer));
+    composition_layers.emplace_back(std::move(layer));
   }
 
-  std::unique_ptr<DrmDisplayComposition> composition = compositor_
-                                                           .CreateComposition();
-  composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
+  auto composition = std::make_unique<DrmDisplayComposition>(crtc_,
+                                                             planner_.get());
 
-  // TODO: Don't always assume geometry changed
-  int ret = composition->SetLayers(map.layers.data(), map.layers.size(), true);
+  // TODO(nobody): Don't always assume geometry changed
+  int ret = composition->SetLayers(composition_layers.data(),
+                                   composition_layers.size(), true);
   if (ret) {
     ALOGE("Failed to set layers in the composition ret=%d", ret);
     return HWC2::Error::BadLayer;
@@ -740,10 +737,12 @@
     return HWC2::Error::BadConfig;
   }
 
-  std::unique_ptr<DrmDisplayComposition> composition = compositor_
-                                                           .CreateComposition();
-  composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
+  auto composition = std::make_unique<DrmDisplayComposition>(crtc_,
+                                                             planner_.get());
   int ret = composition->SetDisplayMode(*mode);
+  if (ret) {
+    return HWC2::Error::BadConfig;
+  }
   ret = compositor_.ApplyComposition(std::move(composition));
   if (ret) {
     ALOGE("Failed to queue dpms composition on %d", ret);
@@ -778,10 +777,10 @@
   hwc_drm_bo bo{};
   BufferInfoGetter::GetInstance()->ConvertBoInfo(target, &bo);
 
-  hwc_frect_t source_crop = {.left = 0.0f,
-                             .top = 0.0f,
-                             .right = bo.width + 0.0f,
-                             .bottom = bo.height + 0.0f};
+  hwc_frect_t source_crop = {.left = 0.0F,
+                             .top = 0.0F,
+                             .right = bo.width + 0.0F,
+                             .bottom = bo.height + 0.0F};
   client_layer_.SetLayerSourceCrop(source_crop);
 
   return HWC2::Error::None;
@@ -820,7 +819,7 @@
 HWC2::Error DrmHwcTwo::HwcDisplay::SetOutputBuffer(buffer_handle_t buffer,
                                                    int32_t release_fence) {
   supported(__func__);
-  // TODO: Need virtual display support
+  // TODO(nobody): Need virtual display support
   return unsupported(__func__, buffer, release_fence);
 }
 
@@ -843,9 +842,8 @@
       return HWC2::Error::BadParameter;
   };
 
-  std::unique_ptr<DrmDisplayComposition> composition = compositor_
-                                                           .CreateComposition();
-  composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
+  auto composition = std::make_unique<DrmDisplayComposition>(crtc_,
+                                                             planner_.get());
   composition->SetDpmsMode(dpms_value);
   int ret = compositor_.ApplyComposition(std::move(composition));
   if (ret) {
@@ -861,30 +859,6 @@
   return HWC2::Error::None;
 }
 
-uint32_t DrmHwcTwo::HwcDisplay::CalcPixOps(
-    std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, size_t first_z,
-    size_t size) {
-  uint32_t pixops = 0;
-  for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
-    if (l.first >= first_z && l.first < first_z + size) {
-      hwc_rect_t df = l.second->display_frame();
-      pixops += (df.right - df.left) * (df.bottom - df.top);
-    }
-  }
-  return pixops;
-}
-
-void DrmHwcTwo::HwcDisplay::MarkValidated(
-    std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, size_t client_first_z,
-    size_t client_size) {
-  for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
-    if (l.first >= client_first_z && l.first < client_first_z + client_size)
-      l.second->set_validated_type(HWC2::Composition::Client);
-    else
-      l.second->set_validated_type(HWC2::Composition::Device);
-  }
-}
-
 HWC2::Error DrmHwcTwo::HwcDisplay::ValidateDisplay(uint32_t *num_types,
                                                    uint32_t *num_requests) {
   supported(__func__);
@@ -892,12 +866,92 @@
   return backend_->ValidateDisplay(this, num_types, num_requests);
 }
 
+std::vector<DrmHwcTwo::HwcLayer *>
+DrmHwcTwo::HwcDisplay::GetOrderLayersByZPos() {
+  std::vector<DrmHwcTwo::HwcLayer *> ordered_layers;
+  ordered_layers.reserve(layers_.size());
+
+  for (auto &[handle, layer] : layers_) {
+    ordered_layers.emplace_back(&layer);
+  }
+
+  std::sort(std::begin(ordered_layers), std::end(ordered_layers),
+            [](const DrmHwcTwo::HwcLayer *lhs, const DrmHwcTwo::HwcLayer *rhs) {
+              return lhs->z_order() < rhs->z_order();
+            });
+
+  return ordered_layers;
+}
+
+#if PLATFORM_SDK_VERSION > 29
+HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayConnectionType(uint32_t *outType) {
+  if (connector_->internal())
+    *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
+  else if (connector_->external())
+    *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::External);
+  else
+    return HWC2::Error::BadConfig;
+
+  return HWC2::Error::None;
+}
+
+HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayVsyncPeriod(
+    hwc2_vsync_period_t *outVsyncPeriod /* ns */) {
+  supported(__func__);
+  DrmMode const &mode = connector_->active_mode();
+  if (mode.id() == 0)
+    return HWC2::Error::BadConfig;
+
+  *outVsyncPeriod = 1E9 / mode.v_refresh();
+  return HWC2::Error::None;
+}
+
+HWC2::Error DrmHwcTwo::HwcDisplay::SetActiveConfigWithConstraints(
+    hwc2_config_t /*config*/,
+    hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints,
+    hwc_vsync_period_change_timeline_t *outTimeline) {
+  supported(__func__);
+
+  if (vsyncPeriodChangeConstraints == nullptr || outTimeline == nullptr) {
+    return HWC2::Error::BadParameter;
+  }
+
+  return HWC2::Error::BadConfig;
+}
+
+HWC2::Error DrmHwcTwo::HwcDisplay::SetAutoLowLatencyMode(bool /*on*/) {
+  return HWC2::Error::Unsupported;
+}
+
+HWC2::Error DrmHwcTwo::HwcDisplay::GetSupportedContentTypes(
+    uint32_t *outNumSupportedContentTypes,
+    const uint32_t *outSupportedContentTypes) {
+  if (outSupportedContentTypes == nullptr)
+    *outNumSupportedContentTypes = 0;
+
+  return HWC2::Error::None;
+}
+
+HWC2::Error DrmHwcTwo::HwcDisplay::SetContentType(int32_t contentType) {
+  supported(__func__);
+
+  if (contentType != HWC2_CONTENT_TYPE_NONE)
+    return HWC2::Error::Unsupported;
+
+  /* TODO: Map to the DRM Connector property:
+   * https://elixir.bootlin.com/linux/v5.4-rc5/source/drivers/gpu/drm/drm_connector.c#L809
+   */
+
+  return HWC2::Error::None;
+}
+#endif
+
 #if PLATFORM_SDK_VERSION > 28
 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayIdentificationData(
     uint8_t *outPort, uint32_t *outDataSize, uint8_t *outData) {
   supported(__func__);
 
-  drmModePropertyBlobPtr blob;
+  drmModePropertyBlobPtr blob = nullptr;
 
   if (connector_->GetEdidBlob(blob)) {
     ALOGE("Failed to get edid property value.");
@@ -919,7 +973,7 @@
     uint32_t *outNumCapabilities, uint32_t *outCapabilities) {
   unsupported(__func__, outCapabilities);
 
-  if (outNumCapabilities == NULL) {
+  if (outNumCapabilities == nullptr) {
     return HWC2::Error::BadParameter;
   }
 
@@ -1004,7 +1058,7 @@
 }
 
 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerColor(hwc_color_t color) {
-  // TODO: Put to client composition here?
+  // TODO(nobody): Put to client composition here?
   supported(__func__);
   layer_color_ = color;
   return HWC2::Error::None;
@@ -1036,7 +1090,7 @@
 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSidebandStream(
     const native_handle_t *stream) {
   supported(__func__);
-  // TODO: We don't support sideband
+  // TODO(nobody): We don't support sideband
   return unsupported(__func__, stream);
 }
 
@@ -1048,7 +1102,7 @@
 
 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSurfaceDamage(hwc_region_t damage) {
   supported(__func__);
-  // TODO: We don't use surface damage, marking as unsupported
+  // TODO(nobody): We don't use surface damage, marking as unsupported
   unsupported(__func__, damage);
   return HWC2::Error::None;
 }
@@ -1061,7 +1115,7 @@
 
 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerVisibleRegion(hwc_region_t visible) {
   supported(__func__);
-  // TODO: We don't use this information, marking as unsupported
+  // TODO(nobody): We don't use this information, marking as unsupported
   unsupported(__func__, visible);
   return HWC2::Error::None;
 }
@@ -1095,10 +1149,11 @@
   layer->sf_handle = buffer_;
   layer->acquire_fence = acquire_fence_.Release();
   layer->release_fence = std::move(release_fence);
-  layer->SetDisplayFrame(display_frame_);
-  layer->alpha = static_cast<uint16_t>(65535.0f * alpha_ + 0.5f);
-  layer->SetSourceCrop(source_crop_);
+  layer->display_frame = display_frame_;
+  layer->alpha = lround(65535.0F * alpha_);
+  layer->source_crop = source_crop_;
   layer->SetTransform(static_cast<int32_t>(transform_));
+  layer->dataspace = dataspace_;
 }
 
 void DrmHwcTwo::HandleDisplayHotplug(hwc2_display_t displayid, int state) {
@@ -1112,7 +1167,7 @@
 }
 
 void DrmHwcTwo::HandleInitialHotplugState(DrmDevice *drmDevice) {
-  for (auto &conn : drmDevice->connectors()) {
+  for (const auto &conn : drmDevice->connectors()) {
     if (conn->state() != DRM_MODE_CONNECTED)
       continue;
     HandleDisplayHotplug(conn->display(), conn->state());
@@ -1120,7 +1175,7 @@
 }
 
 void DrmHwcTwo::DrmHotplugHandler::HandleEvent(uint64_t timestamp_us) {
-  for (auto &conn : drm_->connectors()) {
+  for (const auto &conn : drm_->connectors()) {
     drmModeConnection old_state = conn->state();
     drmModeConnection cur_state = conn->UpdateModes()
                                       ? DRM_MODE_UNKNOWNCONNECTION
@@ -1326,6 +1381,36 @@
           DisplayHook<decltype(&HwcDisplay::SetDisplayBrightness),
                       &HwcDisplay::SetDisplayBrightness, float>);
 #endif /* PLATFORM_SDK_VERSION > 28 */
+#if PLATFORM_SDK_VERSION > 29
+    case HWC2::FunctionDescriptor::GetDisplayConnectionType:
+      return ToHook<HWC2_PFN_GET_DISPLAY_CONNECTION_TYPE>(
+          DisplayHook<decltype(&HwcDisplay::GetDisplayConnectionType),
+                      &HwcDisplay::GetDisplayConnectionType, uint32_t *>);
+    case HWC2::FunctionDescriptor::GetDisplayVsyncPeriod:
+      return ToHook<HWC2_PFN_GET_DISPLAY_VSYNC_PERIOD>(
+          DisplayHook<decltype(&HwcDisplay::GetDisplayVsyncPeriod),
+                      &HwcDisplay::GetDisplayVsyncPeriod,
+                      hwc2_vsync_period_t *>);
+    case HWC2::FunctionDescriptor::SetActiveConfigWithConstraints:
+      return ToHook<HWC2_PFN_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS>(
+          DisplayHook<decltype(&HwcDisplay::SetActiveConfigWithConstraints),
+                      &HwcDisplay::SetActiveConfigWithConstraints,
+                      hwc2_config_t, hwc_vsync_period_change_constraints_t *,
+                      hwc_vsync_period_change_timeline_t *>);
+    case HWC2::FunctionDescriptor::SetAutoLowLatencyMode:
+      return ToHook<HWC2_PFN_SET_AUTO_LOW_LATENCY_MODE>(
+          DisplayHook<decltype(&HwcDisplay::SetAutoLowLatencyMode),
+                      &HwcDisplay::SetAutoLowLatencyMode, bool>);
+    case HWC2::FunctionDescriptor::GetSupportedContentTypes:
+      return ToHook<HWC2_PFN_GET_SUPPORTED_CONTENT_TYPES>(
+          DisplayHook<decltype(&HwcDisplay::GetSupportedContentTypes),
+                      &HwcDisplay::GetSupportedContentTypes, uint32_t *,
+                      uint32_t *>);
+    case HWC2::FunctionDescriptor::SetContentType:
+      return ToHook<HWC2_PFN_SET_CONTENT_TYPE>(
+          DisplayHook<decltype(&HwcDisplay::SetContentType),
+                      &HwcDisplay::SetContentType, int32_t>);
+#endif
     // Layer functions
     case HWC2::FunctionDescriptor::SetCursorPosition:
       return ToHook<HWC2_PFN_SET_CURSOR_POSITION>(
@@ -1386,7 +1471,7 @@
                     &HwcLayer::SetLayerZOrder, uint32_t>);
     case HWC2::FunctionDescriptor::Invalid:
     default:
-      return NULL;
+      return nullptr;
   }
 }
 
@@ -1394,7 +1479,7 @@
 int DrmHwcTwo::HookDevOpen(const struct hw_module_t *module, const char *name,
                            struct hw_device_t **dev) {
   supported(__func__);
-  if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
+  if (strcmp(name, HWC_HARDWARE_COMPOSER) != 0) {
     ALOGE("Invalid module name- %s", name);
     return -EINVAL;
   }
@@ -1411,17 +1496,19 @@
     return -EINVAL;
   }
 
-  ctx->common.module = const_cast<hw_module_t *>(module);
+  ctx->common.module = (hw_module_t *)module;
   *dev = &ctx->common;
-  ctx.release();
+  ctx.release();  // NOLINT(bugprone-unused-return-value)
   return 0;
 }
 }  // namespace android
 
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
 static struct hw_module_methods_t hwc2_module_methods = {
     .open = android::DrmHwcTwo::HookDevOpen,
 };
 
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
 hw_module_t HAL_MODULE_INFO_SYM = {
     .tag = HARDWARE_MODULE_TAG,
     .module_api_version = HARDWARE_MODULE_API_VERSION(2, 0),
@@ -1429,6 +1516,6 @@
     .name = "DrmHwcTwo module",
     .author = "The Android Open Source Project",
     .methods = &hwc2_module_methods,
-    .dso = NULL,
+    .dso = nullptr,
     .reserved = {0},
 };
diff --git a/DrmHwcTwo.h b/DrmHwcTwo.h
index d489113..a0d8cdd 100644
--- a/DrmHwcTwo.h
+++ b/DrmHwcTwo.h
@@ -137,7 +137,7 @@
     HWC2::Error SetLayerSurfaceDamage(hwc_region_t damage);
     HWC2::Error SetLayerTransform(int32_t transform);
     HWC2::Error SetLayerVisibleRegion(hwc_region_t visible);
-    HWC2::Error SetLayerZOrder(uint32_t z);
+    HWC2::Error SetLayerZOrder(uint32_t order);
 
    private:
     // sf_type_ stores the initial type given to us by surfaceflinger,
@@ -174,11 +174,7 @@
     void RegisterRefreshCallback(hwc2_callback_data_t data,
                                  hwc2_function_pointer_t func);
     HWC2::Error CreateComposition(bool test);
-    bool HardwareSupportsLayerType(HWC2::Composition comp_type);
-    uint32_t CalcPixOps(std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map,
-                        size_t first_z, size_t size);
-    void MarkValidated(std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map,
-                       size_t client_first_z, size_t client_size);
+    std::vector<DrmHwcTwo::HwcLayer *> GetOrderLayersByZPos();
 
     void ClearDisplay();
 
@@ -218,6 +214,22 @@
     HWC2::Error GetDisplayBrightnessSupport(bool *supported);
     HWC2::Error SetDisplayBrightness(float);
 #endif
+#if PLATFORM_SDK_VERSION > 29
+    HWC2::Error GetDisplayConnectionType(uint32_t *outType);
+    HWC2::Error GetDisplayVsyncPeriod(hwc2_vsync_period_t *outVsyncPeriod);
+
+    HWC2::Error SetActiveConfigWithConstraints(
+        hwc2_config_t config,
+        hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints,
+        hwc_vsync_period_change_timeline_t *outTimeline);
+    HWC2::Error SetAutoLowLatencyMode(bool on);
+    HWC2::Error GetSupportedContentTypes(
+        uint32_t *outNumSupportedContentTypes,
+        const uint32_t *outSupportedContentTypes);
+
+    HWC2::Error SetContentType(int32_t contentType);
+#endif
+
     HWC2::Error GetDozeSupport(int32_t *support);
     HWC2::Error GetHdrCapabilities(uint32_t *num_types, int32_t *types,
                                    float *max_luminance,
@@ -334,8 +346,8 @@
     std::map<hwc2_layer_t, HwcLayer> layers_;
     HwcLayer client_layer_;
     UniqueFd present_fence_;
-    int32_t color_mode_;
-    std::array<float, MATRIX_SIZE> color_transform_matrix_;
+    int32_t color_mode_{};
+    std::array<float, MATRIX_SIZE> color_transform_matrix_{};
     android_color_transform_t color_transform_hint_;
 
     uint32_t frame_no_ = 0;
diff --git a/README.md b/README.md
index 05f1364..728bc76 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,29 @@
-drm_hwcomposer
+drm\_hwcomposer
 ======
 
-Patches to drm_hwcomposer are very much welcome, we really want this to be the
-universal HW composer implementation for Android and similar platforms
-So please bring on porting patches, bugfixes, improvements for documentation
-and new features.
+Patches to drm\_hwcomposer are very much welcome, we really want this to be the
+universal HW composer implementation for Android and similar platforms. So
+please bring on porting patches, bugfixes, improvements for documentation and
+new features.
 
 A short list of contribution guidelines:
-* Submit changes via gitlab merge requests on gitlab.freedesktop.org
-* drm_hwcomposer is Apache 2.0 Licensed and we require contributions to follow the developer's certificate of origin: http://developercertificate.org/
-* When submitting new code please follow the naming conventions documented in the generated documentation. Also please make full use of all the helpers and convenience macros provided by drm_hwcomposer. The below command can help you with formatting of your patches:
-  
-      `git diff | clang-format-diff-5.0 -p 1 -style=file`
-* Hardware specific changes should be tested on relevant platforms before committing.
+* Submit changes via gitlab merge requests on gitlab.freedesktop.org.
+* drm\_hwcomposer is Apache 2.0 Licensed and we require contributions to follow
+  the developer's certificate of origin: http://developercertificate.org/.
+* When submitting new code please follow the naming conventions documented in
+  the generated documentation. Also please make full use of all the helpers and
+  convenience macros provided by drm\_hwcomposer. The below command can help
+  you with formatting of your patches:
 
-If you need inspiration, please checkout our [TODO issues](https://gitlab.freedesktop.org/drm-hwcomposer/drm-hwcomposer/issues?label_name%5B%5D=TODO)
+    ```
+    git diff | clang-format-diff-11 -p 1 -style=file
+    ```
+
+* Hardware specific changes should be tested on relevant platforms before
+  committing.
+
+If you need inspiration, please checkout our [TODO issues][1].
 
 Happy hacking!
+
+[1]: https://gitlab.freedesktop.org/drm-hwcomposer/drm-hwcomposer/issues?label_name%5B%5D=TODO
diff --git a/backend/Backend.cpp b/backend/Backend.cpp
index 887eb0e..312faed 100644
--- a/backend/Backend.cpp
+++ b/backend/Backend.cpp
@@ -16,6 +16,8 @@
 
 #include "Backend.h"
 
+#include <climits>
+
 #include "BackendManager.h"
 #include "bufferinfo/BufferInfoGetter.h"
 
@@ -26,6 +28,100 @@
                                      uint32_t *num_requests) {
   *num_types = 0;
   *num_requests = 0;
+
+  auto layers = display->GetOrderLayersByZPos();
+
+  int client_start = -1;
+  size_t client_size = 0;
+
+  if (display->compositor().ShouldFlattenOnClient()) {
+    client_start = 0;
+    client_size = layers.size();
+    MarkValidated(layers, client_start, client_size);
+  } else {
+    std::tie(client_start, client_size) = GetClientLayers(display, layers);
+
+    MarkValidated(layers, client_start, client_size);
+
+    bool testing_needed = !(client_start == 0 && client_size == layers.size());
+
+    if (testing_needed &&
+        display->CreateComposition(true) != HWC2::Error::None) {
+      ++display->total_stats().failed_kms_validate_;
+      client_start = 0;
+      client_size = layers.size();
+      MarkValidated(layers, 0, client_size);
+    }
+  }
+
+  *num_types = client_size;
+
+  display->total_stats().frames_flattened_ = display->compositor()
+                                                 .GetFlattenedFramesCount();
+  display->total_stats().gpu_pixops_ += CalcPixOps(layers, client_start,
+                                                   client_size);
+  display->total_stats().total_pixops_ += CalcPixOps(layers, 0, layers.size());
+
+  return *num_types ? HWC2::Error::HasChanges : HWC2::Error::None;
+}
+
+std::tuple<int, size_t> Backend::GetClientLayers(
+    DrmHwcTwo::HwcDisplay *display,
+    const std::vector<DrmHwcTwo::HwcLayer *> &layers) {
+  int client_start = -1;
+  size_t client_size = 0;
+
+  for (int z_order = 0; z_order < layers.size(); ++z_order) {
+    if (IsClientLayer(display, layers[z_order])) {
+      if (client_start < 0)
+        client_start = (int)z_order;
+      client_size = (z_order - client_start) + 1;
+    }
+  }
+
+  return GetExtraClientRange(display, layers, client_start, client_size);
+}
+
+bool Backend::IsClientLayer(DrmHwcTwo::HwcDisplay *display,
+                            DrmHwcTwo::HwcLayer *layer) {
+  return !HardwareSupportsLayerType(layer->sf_type()) ||
+         !BufferInfoGetter::GetInstance()->IsHandleUsable(layer->buffer()) ||
+         display->color_transform_hint() != HAL_COLOR_TRANSFORM_IDENTITY ||
+         (layer->RequireScalingOrPhasing() &&
+          display->resource_manager()->ForcedScalingWithGpu());
+}
+
+bool Backend::HardwareSupportsLayerType(HWC2::Composition comp_type) {
+  return comp_type == HWC2::Composition::Device ||
+         comp_type == HWC2::Composition::Cursor;
+}
+
+uint32_t Backend::CalcPixOps(const std::vector<DrmHwcTwo::HwcLayer *> &layers,
+                             size_t first_z, size_t size) {
+  uint32_t pixops = 0;
+  for (int z_order = 0; z_order < layers.size(); ++z_order) {
+    if (z_order >= first_z && z_order < first_z + size) {
+      hwc_rect_t df = layers[z_order]->display_frame();
+      pixops += (df.right - df.left) * (df.bottom - df.top);
+    }
+  }
+  return pixops;
+}
+
+void Backend::MarkValidated(std::vector<DrmHwcTwo::HwcLayer *> &layers,
+                            size_t client_first_z, size_t client_size) {
+  for (int z_order = 0; z_order < layers.size(); ++z_order) {
+    if (z_order >= client_first_z && z_order < client_first_z + client_size)
+      layers[z_order]->set_validated_type(HWC2::Composition::Client);
+    else
+      layers[z_order]->set_validated_type(HWC2::Composition::Device);
+  }
+}
+
+std::tuple<int, int> Backend::GetExtraClientRange(
+    DrmHwcTwo::HwcDisplay *display,
+    const std::vector<DrmHwcTwo::HwcLayer *> &layers, int client_start,
+    size_t client_size) {
   size_t avail_planes = display->primary_planes().size() +
                         display->overlay_planes().size();
 
@@ -36,102 +132,41 @@
   if (avail_planes < display->layers().size())
     avail_planes--;
 
-  std::map<uint32_t, DrmHwcTwo::HwcLayer *> z_map, z_map_tmp;
-  uint32_t z_index = 0;
-  // First create a map of layers and z_order values
-  for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l :
-       display->layers())
-    z_map_tmp.emplace(std::make_pair(l.second.z_order(), &l.second));
-  // normalise the map so that the lowest z_order layer has key 0
-  for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map_tmp)
-    z_map.emplace(std::make_pair(z_index++, l.second));
+  int extra_client = int(layers.size() - client_size) - int(avail_planes);
 
-  uint32_t total_pixops = display->CalcPixOps(z_map, 0, z_map.size());
-  uint32_t gpu_pixops = 0;
-
-  int client_start = -1, client_size = 0;
-
-  if (display->compositor().ShouldFlattenOnClient()) {
-    client_start = 0;
-    client_size = z_map.size();
-    display->MarkValidated(z_map, client_start, client_size);
-  } else {
-    std::tie(client_start, client_size) = GetClientLayers(display, z_map);
-
-    int extra_client = (z_map.size() - client_size) - avail_planes;
-    if (extra_client > 0) {
-      int start = 0, steps;
-      if (client_size != 0) {
-        int prepend = std::min(client_start, extra_client);
-        int append = std::min(int(z_map.size() - (client_start + client_size)),
-                              extra_client);
-        start = client_start - prepend;
-        client_size += extra_client;
-        steps = 1 + std::min(std::min(append, prepend),
-                             int(z_map.size()) - (start + client_size));
-      } else {
-        client_size = extra_client;
-        steps = 1 + z_map.size() - extra_client;
-      }
-
-      gpu_pixops = INT_MAX;
-      for (int i = 0; i < steps; i++) {
-        uint32_t po = display->CalcPixOps(z_map, start + i, client_size);
-        if (po < gpu_pixops) {
-          gpu_pixops = po;
-          client_start = start + i;
-        }
-      }
+  if (extra_client > 0) {
+    int start = 0;
+    size_t steps = 0;
+    if (client_size != 0) {
+      int prepend = std::min(client_start, extra_client);
+      int append = std::min(int(layers.size()) -
+                                int(client_start + client_size),
+                            extra_client);
+      start = client_start - (int)prepend;
+      client_size += extra_client;
+      steps = 1 + std::min(std::min(append, prepend),
+                           int(layers.size()) - int(start + client_size));
+    } else {
+      client_size = extra_client;
+      steps = 1 + layers.size() - extra_client;
     }
 
-    display->MarkValidated(z_map, client_start, client_size);
-
-    bool testing_needed = !(client_start == 0 && client_size == z_map.size());
-
-    if (testing_needed &&
-        display->CreateComposition(true) != HWC2::Error::None) {
-      ++display->total_stats().failed_kms_validate_;
-      gpu_pixops = total_pixops;
-      client_size = z_map.size();
-      display->MarkValidated(z_map, 0, client_size);
-    }
-  }
-
-  *num_types = client_size;
-
-  display->total_stats().frames_flattened_ = display->compositor()
-                                                 .GetFlattenedFramesCount();
-  display->total_stats().gpu_pixops_ += gpu_pixops;
-  display->total_stats().total_pixops_ += total_pixops;
-
-  return *num_types ? HWC2::Error::HasChanges : HWC2::Error::None;
-}
-
-std::tuple<int, int> Backend::GetClientLayers(
-    DrmHwcTwo::HwcDisplay *display,
-    const std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map) {
-  int client_start = -1, client_size = 0;
-
-  for (auto & [ z_order, layer ] : z_map) {
-    if (IsClientLayer(display, layer)) {
-      if (client_start < 0)
-        client_start = z_order;
-      client_size = (z_order - client_start) + 1;
+    uint32_t gpu_pixops = INT_MAX;
+    for (int i = 0; i < steps; i++) {
+      uint32_t po = CalcPixOps(layers, start + i, client_size);
+      if (po < gpu_pixops) {
+        gpu_pixops = po;
+        client_start = start + i;
+      }
     }
   }
 
   return std::make_tuple(client_start, client_size);
 }
 
-bool Backend::IsClientLayer(DrmHwcTwo::HwcDisplay *display,
-                            DrmHwcTwo::HwcLayer *layer) {
-  return !display->HardwareSupportsLayerType(layer->sf_type()) ||
-         !BufferInfoGetter::GetInstance()->IsHandleUsable(layer->buffer()) ||
-         display->color_transform_hint() != HAL_COLOR_TRANSFORM_IDENTITY ||
-         (layer->RequireScalingOrPhasing() &&
-          display->resource_manager()->ForcedScalingWithGpu());
-}
-
+// clang-format off
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables, cert-err58-cpp)
 REGISTER_BACKEND("generic", Backend);
+// clang-format on
 
 }  // namespace android
diff --git a/backend/Backend.h b/backend/Backend.h
index 898fece..fc9a733 100644
--- a/backend/Backend.h
+++ b/backend/Backend.h
@@ -27,11 +27,22 @@
   virtual HWC2::Error ValidateDisplay(DrmHwcTwo::HwcDisplay *display,
                                       uint32_t *num_types,
                                       uint32_t *num_requests);
-  virtual std::tuple<int, int> GetClientLayers(
+  virtual std::tuple<int, size_t> GetClientLayers(
       DrmHwcTwo::HwcDisplay *display,
-      const std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map);
+      const std::vector<DrmHwcTwo::HwcLayer *> &layers);
   virtual bool IsClientLayer(DrmHwcTwo::HwcDisplay *display,
                              DrmHwcTwo::HwcLayer *layer);
+
+ protected:
+  bool HardwareSupportsLayerType(HWC2::Composition comp_type);
+  uint32_t CalcPixOps(const std::vector<DrmHwcTwo::HwcLayer *> &layers,
+                      size_t first_z, size_t size);
+  void MarkValidated(std::vector<DrmHwcTwo::HwcLayer *> &layers,
+                     size_t client_first_z, size_t client_size);
+  std::tuple<int, int> GetExtraClientRange(
+      DrmHwcTwo::HwcDisplay *display,
+      const std::vector<DrmHwcTwo::HwcLayer *> &layers, int client_start,
+      size_t client_size);
 };
 }  // namespace android
 
diff --git a/backend/BackendClient.cpp b/backend/BackendClient.cpp
index 033a35c..49963b8 100644
--- a/backend/BackendClient.cpp
+++ b/backend/BackendClient.cpp
@@ -30,6 +30,9 @@
   return HWC2::Error::HasChanges;
 }
 
+// clang-format off
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables, cert-err58-cpp)
 REGISTER_BACKEND("client", BackendClient);
+// clang-format on
 
 }  // namespace android
diff --git a/backend/BackendManager.cpp b/backend/BackendManager.cpp
index 0bacdcd..7b89761 100644
--- a/backend/BackendManager.cpp
+++ b/backend/BackendManager.cpp
@@ -18,12 +18,13 @@
 
 #include "BackendManager.h"
 
-#include <cutils/properties.h>
-#include <log/log.h>
+#include "utils/log.h"
+#include "utils/properties.h"
 
 namespace android {
 
-const std::vector<std::string> BackendManager::client_devices_ = {
+// NOLINTNEXTLINE(cert-err58-cpp)
+const std::vector<std::string> BackendManager::kClientDevices = {
     "kirin",
     "mediatek-drm",
 };
@@ -45,7 +46,7 @@
   char backend_override[PROPERTY_VALUE_MAX];
   property_get("vendor.hwc.backend_override", backend_override,
                driver_name.c_str());
-  std::string backend_name(std::move(backend_override));
+  std::string backend_name(backend_override);
 
   display->set_backend(GetBackendByName(backend_name));
   if (!display->backend()) {
@@ -63,15 +64,15 @@
 }
 
 std::unique_ptr<Backend> BackendManager::GetBackendByName(std::string &name) {
-  if (!available_backends_.size()) {
+  if (available_backends_.empty()) {
     ALOGE("No backends are specified");
     return nullptr;
   }
 
   auto it = available_backends_.find(name);
   if (it == available_backends_.end()) {
-    auto it = std::find(client_devices_.begin(), client_devices_.end(), name);
-    name = it == client_devices_.end() ? "generic" : "client";
+    auto it = std::find(kClientDevices.begin(), kClientDevices.end(), name);
+    name = it == kClientDevices.end() ? "generic" : "client";
   }
 
   return available_backends_[name]();
diff --git a/backend/BackendManager.h b/backend/BackendManager.h
index e86c098..9b314db 100644
--- a/backend/BackendManager.h
+++ b/backend/BackendManager.h
@@ -48,7 +48,7 @@
  private:
   BackendManager() = default;
 
-  static const std::vector<std::string> client_devices_;
+  static const std::vector<std::string> kClientDevices;
 
   std::map<std::string, backend_constructor_t> available_backends_;
 };
diff --git a/backend/BackendRCarDu.cpp b/backend/BackendRCarDu.cpp
index e85fa71..b012797 100644
--- a/backend/BackendRCarDu.cpp
+++ b/backend/BackendRCarDu.cpp
@@ -40,6 +40,9 @@
   return Backend::IsClientLayer(display, layer);
 }
 
+// clang-format off
+// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables, cert-err58-cpp)
 REGISTER_BACKEND("rcar-du", BackendRCarDu);
+// clang-format on
 
 }  // namespace android
\ No newline at end of file
diff --git a/bufferinfo/BufferInfoGetter.cpp b/bufferinfo/BufferInfoGetter.cpp
index afdc50e..7f7f8ae 100644
--- a/bufferinfo/BufferInfoGetter.cpp
+++ b/bufferinfo/BufferInfoGetter.cpp
@@ -22,13 +22,12 @@
 #include "BufferInfoMapperMetadata.h"
 #endif
 
-#include <cutils/properties.h>
-#include <gralloc_handle.h>
-#include <hardware/gralloc.h>
-#include <log/log.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
+#include "utils/log.h"
+#include "utils/properties.h"
+
 namespace android {
 
 BufferInfoGetter *BufferInfoGetter::GetInstance() {
@@ -40,7 +39,7 @@
       ALOGW(
           "Generic buffer getter is not available. Falling back to legacy...");
 #endif
-      inst.reset(LegacyBufferInfoGetter::CreateInstance());
+      inst = LegacyBufferInfoGetter::CreateInstance();
 #if PLATFORM_SDK_VERSION >= 30
     }
 #endif
@@ -53,12 +52,12 @@
   hwc_drm_bo_t bo;
   memset(&bo, 0, sizeof(hwc_drm_bo_t));
 
-  if (ConvertBoInfo(handle, &bo) != 0)
+  if (ConvertBoInfo(handle, &bo) != 0) {
     return false;
-
-  if (bo.prime_fds[0] == 0)
+  }
+  if (bo.prime_fds[0] == 0) {
     return false;
-
+  }
   return true;
 }
 
@@ -90,6 +89,8 @@
       return DRM_FORMAT_BGR565;
     case HAL_PIXEL_FORMAT_YV12:
       return DRM_FORMAT_YVU420;
+    case HAL_PIXEL_FORMAT_RGBA_1010102:
+      return DRM_FORMAT_ABGR2101010;
     default:
       ALOGE("Cannot convert hal format to drm format %u", hal_format);
       return DRM_FORMAT_INVALID;
@@ -103,13 +104,14 @@
     case DRM_FORMAT_ABGR8888:
     case DRM_FORMAT_BGR888:
     case DRM_FORMAT_BGR565:
+    case DRM_FORMAT_ABGR2101010:
       return true;
     default:
       return false;
   }
 }
 
-__attribute__((weak)) LegacyBufferInfoGetter *
+__attribute__((weak)) std::unique_ptr<LegacyBufferInfoGetter>
 LegacyBufferInfoGetter::CreateInstance() {
   ALOGE("No legacy buffer info getters available");
   return nullptr;
diff --git a/bufferinfo/BufferInfoGetter.h b/bufferinfo/BufferInfoGetter.h
index fad3d16..60ca985 100644
--- a/bufferinfo/BufferInfoGetter.h
+++ b/bufferinfo/BufferInfoGetter.h
@@ -51,26 +51,29 @@
 
   int ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) override = 0;
 
-  static LegacyBufferInfoGetter *CreateInstance();
+  static std::unique_ptr<LegacyBufferInfoGetter> CreateInstance();
 
   static uint32_t ConvertHalFormatToDrm(uint32_t hal_format);
   const gralloc_module_t *gralloc_;
 };
 
-#define LEGACY_BUFFER_INFO_GETTER(getter_)                           \
-  LegacyBufferInfoGetter *LegacyBufferInfoGetter::CreateInstance() { \
-    auto *instance = new getter_();                                  \
-    if (!instance)                                                   \
-      return NULL;                                                   \
-                                                                     \
-    int ret = instance->Init();                                      \
-    if (ret) {                                                       \
-      ALOGE("Failed to initialize the " #getter_ " getter %d", ret); \
-      delete instance;                                               \
-      return NULL;                                                   \
-    }                                                                \
-    return instance;                                                 \
+#ifdef DISABLE_LEGACY_GETTERS
+#define LEGACY_BUFFER_INFO_GETTER(getter_)
+#else
+#define LEGACY_BUFFER_INFO_GETTER(getter_)                             \
+  std::unique_ptr<LegacyBufferInfoGetter>                              \
+  LegacyBufferInfoGetter::CreateInstance() {                           \
+    auto instance = std::make_unique<getter_>();                       \
+    if (instance) {                                                    \
+      int ret = instance->Init();                                      \
+      if (ret) {                                                       \
+        ALOGE("Failed to initialize the " #getter_ " getter %d", ret); \
+        instance.reset();                                              \
+      }                                                                \
+    }                                                                  \
+    return std::move(instance);                                        \
   }
+#endif
 
 }  // namespace android
 #endif
diff --git a/bufferinfo/BufferInfoMapperMetadata.cpp b/bufferinfo/BufferInfoMapperMetadata.cpp
index 3aabeb5..23a9072 100644
--- a/bufferinfo/BufferInfoMapperMetadata.cpp
+++ b/bufferinfo/BufferInfoMapperMetadata.cpp
@@ -21,13 +21,13 @@
 #include "BufferInfoMapperMetadata.h"
 
 #include <drm/drm_fourcc.h>
-#include <inttypes.h>
-#include <log/log.h>
 #include <ui/GraphicBufferMapper.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
-using android::hardware::graphics::common::V1_1::BufferUsage;
+#include <cinttypes>
+
+#include "utils/log.h"
 
 namespace android {
 
@@ -107,7 +107,6 @@
     ALOGE("Failed to get DRM Modifier err=%d", err);
     return err;
   }
-  bo->with_modifiers = true;
 
   uint64_t width = 0;
   err = mapper.getWidth(handle, &width);
diff --git a/bufferinfo/legacy/BufferInfoImagination.cpp b/bufferinfo/legacy/BufferInfoImagination.cpp
index 84c177e..d646072 100644
--- a/bufferinfo/legacy/BufferInfoImagination.cpp
+++ b/bufferinfo/legacy/BufferInfoImagination.cpp
@@ -18,10 +18,10 @@
 
 #include "BufferInfoImagination.h"
 
-#include <log/log.h>
 #include <xf86drm.h>
 
 #include "img_gralloc1_public.h"
+#include "utils/log.h"
 
 namespace android {
 
@@ -29,7 +29,7 @@
 
 int BufferInfoImagination::ConvertBoInfo(buffer_handle_t handle,
                                          hwc_drm_bo_t *bo) {
-  IMG_native_handle_t *hnd = (IMG_native_handle_t *)handle;
+  auto *hnd = (IMG_native_handle_t *)handle;
   if (!hnd)
     return -EINVAL;
 
diff --git a/bufferinfo/legacy/BufferInfoLibdrm.cpp b/bufferinfo/legacy/BufferInfoLibdrm.cpp
index 3f6a6fd..52f792f 100644
--- a/bufferinfo/legacy/BufferInfoLibdrm.cpp
+++ b/bufferinfo/legacy/BufferInfoLibdrm.cpp
@@ -18,23 +18,24 @@
 
 #include "BufferInfoLibdrm.h"
 
-#include <cutils/properties.h>
 #include <gralloc_handle.h>
 #include <hardware/gralloc.h>
-#include <log/log.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
+#include "utils/log.h"
+#include "utils/properties.h"
+
 namespace android {
 
 LEGACY_BUFFER_INFO_GETTER(BufferInfoLibdrm);
 
 enum chroma_order {
-  YCbCr,
-  YCrCb,
+  kYCbCr,
+  kYCrCb,
 };
 
-struct droid_yuv_format {
+struct DroidYuvFormat {
   /* Lookup keys */
   int native;                     /* HAL_PIXEL_FORMAT_ */
   enum chroma_order chroma_order; /* chroma order is {Cb, Cr} or {Cr, Cb} */
@@ -46,37 +47,37 @@
 
 /* The following table is used to look up a DRI image FourCC based
  * on native format and information contained in android_ycbcr struct. */
-static const struct droid_yuv_format droid_yuv_formats[] = {
+static const struct DroidYuvFormat kDroidYuvFormats[] = {
     /* Native format, YCrCb, Chroma step, DRI image FourCC */
-    {HAL_PIXEL_FORMAT_YCbCr_420_888, YCbCr, 2, DRM_FORMAT_NV12},
-    {HAL_PIXEL_FORMAT_YCbCr_420_888, YCbCr, 1, DRM_FORMAT_YUV420},
-    {HAL_PIXEL_FORMAT_YCbCr_420_888, YCrCb, 1, DRM_FORMAT_YVU420},
-    {HAL_PIXEL_FORMAT_YV12, YCrCb, 1, DRM_FORMAT_YVU420},
+    {HAL_PIXEL_FORMAT_YCbCr_420_888, kYCbCr, 2, DRM_FORMAT_NV12},
+    {HAL_PIXEL_FORMAT_YCbCr_420_888, kYCbCr, 1, DRM_FORMAT_YUV420},
+    {HAL_PIXEL_FORMAT_YCbCr_420_888, kYCrCb, 1, DRM_FORMAT_YVU420},
+    {HAL_PIXEL_FORMAT_YV12, kYCrCb, 1, DRM_FORMAT_YVU420},
     /* HACK: See droid_create_image_from_prime_fds() and
      * https://issuetracker.google.com/32077885. */
-    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCbCr, 2, DRM_FORMAT_NV12},
-    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCbCr, 1, DRM_FORMAT_YUV420},
-    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_YVU420},
-    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_AYUV},
-    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_XYUV8888},
+    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCbCr, 2, DRM_FORMAT_NV12},
+    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCbCr, 1, DRM_FORMAT_YUV420},
+    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCrCb, 1, DRM_FORMAT_YVU420},
+    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCrCb, 1, DRM_FORMAT_AYUV},
+    {HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, kYCrCb, 1, DRM_FORMAT_XYUV8888},
 };
 
 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
 
 static int get_fourcc_yuv(int native, enum chroma_order chroma_order,
                           int chroma_step) {
-  for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i)
-    if (droid_yuv_formats[i].native == native &&
-        droid_yuv_formats[i].chroma_order == chroma_order &&
-        droid_yuv_formats[i].chroma_step == chroma_step)
-      return droid_yuv_formats[i].fourcc;
+  for (auto droid_yuv_format : kDroidYuvFormats)
+    if (droid_yuv_format.native == native &&
+        droid_yuv_format.chroma_order == chroma_order &&
+        droid_yuv_format.chroma_step == chroma_step)
+      return droid_yuv_format.fourcc;
 
   return -1;
 }
 
 static bool is_yuv(int native) {
-  for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i)
-    if (droid_yuv_formats[i].native == native)
+  for (auto droid_yuv_format : kDroidYuvFormats)
+    if (droid_yuv_format.native == native)
       return true;
 
   return false;
@@ -84,9 +85,9 @@
 
 bool BufferInfoLibdrm::GetYuvPlaneInfo(int num_fds, buffer_handle_t handle,
                                        hwc_drm_bo_t *bo) {
-  struct android_ycbcr ycbcr;
-  enum chroma_order chroma_order;
-  int ret;
+  struct android_ycbcr ycbcr {};
+  enum chroma_order chroma_order {};
+  int ret = 0;
 
   if (!gralloc_->lock_ycbcr) {
     static std::once_flag once;
@@ -109,11 +110,11 @@
   bo->offsets[0] = (size_t)ycbcr.y;
   /* We assume here that all the planes are located in one DMA-buf. */
   if ((size_t)ycbcr.cr < (size_t)ycbcr.cb) {
-    chroma_order = YCrCb;
+    chroma_order = kYCrCb;
     bo->offsets[1] = (size_t)ycbcr.cr;
     bo->offsets[2] = (size_t)ycbcr.cb;
   } else {
-    chroma_order = YCbCr;
+    chroma_order = kYCbCr;
     bo->offsets[1] = (size_t)ycbcr.cb;
     bo->offsets[2] = (size_t)ycbcr.cr;
   }
@@ -132,7 +133,7 @@
     ALOGW(
         "unsupported YUV format, native = %x, chroma_order = %s, chroma_step = "
         "%d",
-        bo->hal_format, chroma_order == YCbCr ? "YCbCr" : "YCrCb",
+        bo->hal_format, chroma_order == kYCbCr ? "YCbCr" : "YCrCb",
         (int)ycbcr.chroma_step);
     return false;
   }
@@ -171,8 +172,6 @@
 #endif
 #if GRALLOC_HANDLE_VERSION == 4
   bo->modifiers[0] = gr_handle->modifier;
-  bo->with_modifiers = gr_handle->modifier != DRM_FORMAT_MOD_NONE &&
-                       gr_handle->modifier != DRM_FORMAT_MOD_INVALID;
 #endif
 
   bo->usage = gr_handle->usage;
@@ -184,7 +183,18 @@
   } else {
     bo->pitches[0] = gr_handle->stride;
     bo->offsets[0] = 0;
-    bo->format = ConvertHalFormatToDrm(gr_handle->format);
+
+    /* FOSS graphic components (gbm_gralloc, mesa3d) are translating
+     * HAL_PIXEL_FORMAT_RGB_565 to DRM_FORMAT_RGB565 without swapping
+     * the R and B components. Same must be done here. */
+    switch (bo->hal_format) {
+      case HAL_PIXEL_FORMAT_RGB_565:
+        bo->format = DRM_FORMAT_RGB565;
+        break;
+      default:
+        bo->format = ConvertHalFormatToDrm(gr_handle->format);
+    }
+
     if (bo->format == DRM_FORMAT_INVALID)
       return -EINVAL;
   }
diff --git a/bufferinfo/legacy/BufferInfoMaliHisi.cpp b/bufferinfo/legacy/BufferInfoMaliHisi.cpp
index ab5579c..5fc413a 100644
--- a/bufferinfo/legacy/BufferInfoMaliHisi.cpp
+++ b/bufferinfo/legacy/BufferInfoMaliHisi.cpp
@@ -18,13 +18,13 @@
 
 #include "BufferInfoMaliHisi.h"
 
-#include <log/log.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
 #include <cinttypes>
 
 #include "gralloc_priv.h"
+#include "utils/log.h"
 
 #define MALI_ALIGN(value, base) (((value) + ((base)-1)) & ~((base)-1))
 
@@ -68,10 +68,9 @@
 
 int BufferInfoMaliHisi::ConvertBoInfo(buffer_handle_t handle,
                                       hwc_drm_bo_t *bo) {
-  bool is_rgb;
+  bool is_rgb = false;
 
-  private_handle_t const *hnd = reinterpret_cast<private_handle_t const *>(
-      handle);
+  const auto *hnd = (private_handle_t const *)handle;
   if (!hnd)
     return -EINVAL;
 
@@ -120,8 +119,6 @@
       break;
   }
 
-  bo->with_modifiers = true;
-
   return 0;
 }
 
diff --git a/bufferinfo/legacy/BufferInfoMaliMediatek.cpp b/bufferinfo/legacy/BufferInfoMaliMediatek.cpp
index ce47343..7e6f3a8 100644
--- a/bufferinfo/legacy/BufferInfoMaliMediatek.cpp
+++ b/bufferinfo/legacy/BufferInfoMaliMediatek.cpp
@@ -19,7 +19,6 @@
 #include "BufferInfoMaliMediatek.h"
 
 #include <hardware/gralloc.h>
-#include <log/log.h>
 #include <stdatomic.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
@@ -27,6 +26,7 @@
 #include <cinttypes>
 
 #include "gralloc_priv.h"
+#include "utils/log.h"
 
 namespace android {
 
@@ -34,8 +34,7 @@
 
 int BufferInfoMaliMediatek::ConvertBoInfo(buffer_handle_t handle,
                                           hwc_drm_bo_t *bo) {
-  private_handle_t const *hnd = reinterpret_cast<private_handle_t const *>(
-      handle);
+  const auto *hnd = (private_handle_t const *)handle;
   if (!hnd)
     return -EINVAL;
 
diff --git a/bufferinfo/legacy/BufferInfoMaliMeson.cpp b/bufferinfo/legacy/BufferInfoMaliMeson.cpp
index b6896e1..9daf542 100644
--- a/bufferinfo/legacy/BufferInfoMaliMeson.cpp
+++ b/bufferinfo/legacy/BufferInfoMaliMeson.cpp
@@ -18,13 +18,13 @@
 
 #include "BufferInfoMaliMeson.h"
 
-#include <log/log.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
 #include <cinttypes>
 
 #include "gralloc_priv.h"
+#include "utils/log.h"
 
 namespace android {
 
@@ -63,8 +63,7 @@
 
 int BufferInfoMaliMeson::ConvertBoInfo(buffer_handle_t handle,
                                        hwc_drm_bo_t *bo) {
-  private_handle_t const *hnd = reinterpret_cast<private_handle_t const *>(
-      handle);
+  const auto *hnd = (private_handle_t const *)handle;
   if (!hnd)
     return -EINVAL;
 
@@ -87,8 +86,6 @@
   bo->pitches[0] = hnd->byte_stride;
   bo->offsets[0] = 0;
 
-  bo->with_modifiers = true;
-
   return 0;
 }
 
diff --git a/bufferinfo/legacy/BufferInfoMinigbm.cpp b/bufferinfo/legacy/BufferInfoMinigbm.cpp
index 860de08..d030dff 100644
--- a/bufferinfo/legacy/BufferInfoMinigbm.cpp
+++ b/bufferinfo/legacy/BufferInfoMinigbm.cpp
@@ -18,29 +18,39 @@
 
 #include "BufferInfoMinigbm.h"
 
-#include <log/log.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
 #include "cros_gralloc_handle.h"
+#include "utils/log.h"
+
+#define DRM_FORMAT_YVU420_ANDROID fourcc_code('9', '9', '9', '7')
 
 namespace android {
 
 LEGACY_BUFFER_INFO_GETTER(BufferInfoMinigbm);
 
 int BufferInfoMinigbm::ConvertBoInfo(buffer_handle_t handle, hwc_drm_bo_t *bo) {
-  cros_gralloc_handle *gr_handle = (cros_gralloc_handle *)handle;
+  auto *gr_handle = (cros_gralloc_handle *)handle;
   if (!gr_handle)
     return -EINVAL;
 
   bo->width = gr_handle->width;
   bo->height = gr_handle->height;
   bo->hal_format = gr_handle->droid_format;
+
   bo->format = gr_handle->format;
+  if (bo->format == DRM_FORMAT_YVU420_ANDROID)
+    bo->format = DRM_FORMAT_YVU420;
+
   bo->usage = gr_handle->usage;
-  bo->prime_fds[0] = gr_handle->fds[0];
-  bo->pitches[0] = gr_handle->strides[0];
-  bo->offsets[0] = gr_handle->offsets[0];
+
+  for (int i = 0; i < gr_handle->num_planes; i++) {
+    bo->modifiers[i] = gr_handle->format_modifier;
+    bo->prime_fds[i] = gr_handle->fds[i];
+    bo->pitches[i] = gr_handle->strides[i];
+    bo->offsets[i] = gr_handle->offsets[i];
+  }
 
   return 0;
 }
diff --git a/compositor/DrmDisplayComposition.cpp b/compositor/DrmDisplayComposition.cpp
index 4d2e19a..7008e9c 100644
--- a/compositor/DrmDisplayComposition.cpp
+++ b/compositor/DrmDisplayComposition.cpp
@@ -18,33 +18,23 @@
 
 #include "DrmDisplayComposition.h"
 
-#include <log/log.h>
-#include <stdlib.h>
 #include <sync/sync.h>
 #include <xf86drmMode.h>
 
 #include <algorithm>
+#include <cstdlib>
 #include <unordered_set>
 
 #include "DrmDisplayCompositor.h"
 #include "Planner.h"
 #include "drm/DrmDevice.h"
+#include "utils/log.h"
 
 namespace android {
 
-DrmDisplayComposition::~DrmDisplayComposition() {
-}
-
-int DrmDisplayComposition::Init(DrmDevice *drm, DrmCrtc *crtc,
-                                Importer *importer, Planner *planner,
-                                uint64_t frame_no) {
-  drm_ = drm;
-  crtc_ = crtc;  // Can be NULL if we haven't modeset yet
-  importer_ = importer;
-  planner_ = planner;
-  frame_no_ = frame_no;
-
-  return 0;
+DrmDisplayComposition::DrmDisplayComposition(DrmCrtc *crtc, Planner *planner)
+    : crtc_(crtc),  // Can be NULL if we haven't modeset yet
+      planner_(planner) {
 }
 
 bool DrmDisplayComposition::validate_composition_type(DrmCompositionType des) {
@@ -75,8 +65,10 @@
 }
 
 int DrmDisplayComposition::SetDisplayMode(const DrmMode &display_mode) {
-  if (!validate_composition_type(DRM_COMPOSITION_TYPE_MODESET))
+  if (!validate_composition_type(DRM_COMPOSITION_TYPE_MODESET)) {
+    ALOGE("SetDisplayMode() Failed to validate composition type");
     return -EINVAL;
+  }
   display_mode_ = display_mode;
   dpms_mode_ = DRM_MODE_DPMS_ON;
   type_ = DRM_COMPOSITION_TYPE_MODESET;
@@ -84,8 +76,7 @@
 }
 
 int DrmDisplayComposition::AddPlaneDisable(DrmPlane *plane) {
-  composition_planes_.emplace_back(DrmCompositionPlane::Type::kDisable, plane,
-                                   crtc_);
+  composition_planes_.emplace_back(DrmCompositionPlane::Type::kDisable, plane);
   return 0;
 }
 
@@ -104,7 +95,7 @@
   for (size_t i = 0; i < layers_.size(); ++i)
     to_composite.emplace(std::make_pair(i, &layers_[i]));
 
-  int ret;
+  int ret = 0;
   std::tie(ret,
            composition_planes_) = planner_->ProvisionPlanes(to_composite, crtc_,
                                                             primary_planes,
@@ -123,7 +114,7 @@
     // make sure that source layers are ordered based on zorder
     std::sort(i.source_layers().begin(), i.source_layers().end());
 
-    std::vector<DrmPlane *> *container;
+    std::vector<DrmPlane *> *container = nullptr;
     if (i.plane()->type() == DRM_PLANE_TYPE_PRIMARY)
       container = primary_planes;
     else
@@ -211,7 +202,7 @@
     separator = true;
   }
 
-  uint32_t valid_bits = DrmHwcTransform::kFlipH | DrmHwcTransform::kFlipH |
+  uint32_t valid_bits = DrmHwcTransform::kFlipH | DrmHwcTransform::kFlipV |
                         DrmHwcTransform::kRotate90 |
                         DrmHwcTransform::kRotate180 |
                         DrmHwcTransform::kRotate270;
diff --git a/compositor/DrmDisplayComposition.h b/compositor/DrmDisplayComposition.h
index 73a9024..27b34f2 100644
--- a/compositor/DrmDisplayComposition.h
+++ b/compositor/DrmDisplayComposition.h
@@ -31,7 +31,6 @@
 
 class Importer;
 class Planner;
-class SquashState;
 
 enum DrmCompositionType {
   DRM_COMPOSITION_TYPE_EMPTY,
@@ -40,20 +39,6 @@
   DRM_COMPOSITION_TYPE_MODESET,
 };
 
-struct DrmCompositionDisplayLayersMap {
-  int display;
-  bool geometry_changed = true;
-  std::vector<DrmHwcLayer> layers;
-
-  DrmCompositionDisplayLayersMap() = default;
-  DrmCompositionDisplayLayersMap(DrmCompositionDisplayLayersMap &&rhs) =
-      default;
-};
-
-struct DrmCompositionRegion {
-  std::vector<size_t> source_layers;
-};
-
 class DrmCompositionPlane {
  public:
   enum class Type : int32_t {
@@ -64,15 +49,10 @@
   DrmCompositionPlane() = default;
   DrmCompositionPlane(DrmCompositionPlane &&rhs) = default;
   DrmCompositionPlane &operator=(DrmCompositionPlane &&other) = default;
-  DrmCompositionPlane(Type type, DrmPlane *plane, DrmCrtc *crtc)
-      : type_(type), plane_(plane), crtc_(crtc) {
+  DrmCompositionPlane(Type type, DrmPlane *plane) : type_(type), plane_(plane) {
   }
-  DrmCompositionPlane(Type type, DrmPlane *plane, DrmCrtc *crtc,
-                      size_t source_layer)
-      : type_(type),
-        plane_(plane),
-        crtc_(crtc),
-        source_layers_(1, source_layer) {
+  DrmCompositionPlane(Type type, DrmPlane *plane, size_t source_layer)
+      : type_(type), plane_(plane), source_layers_(1, source_layer) {
   }
 
   Type type() const {
@@ -86,10 +66,6 @@
     plane_ = plane;
   }
 
-  DrmCrtc *crtc() const {
-    return crtc_;
-  }
-
   std::vector<size_t> &source_layers() {
     return source_layers_;
   }
@@ -101,18 +77,14 @@
  private:
   Type type_ = Type::kDisable;
   DrmPlane *plane_ = NULL;
-  DrmCrtc *crtc_ = NULL;
   std::vector<size_t> source_layers_;
 };
 
 class DrmDisplayComposition {
  public:
-  DrmDisplayComposition() = default;
   DrmDisplayComposition(const DrmDisplayComposition &) = delete;
-  ~DrmDisplayComposition();
-
-  int Init(DrmDevice *drm, DrmCrtc *crtc, Importer *importer, Planner *planner,
-           uint64_t frame_no);
+  DrmDisplayComposition(DrmCrtc *crtc, Planner *planner);
+  ~DrmDisplayComposition() = default;
 
   int SetLayers(DrmHwcLayer *layers, size_t num_layers, bool geometry_changed);
   int AddPlaneComposition(DrmCompositionPlane plane);
@@ -135,10 +107,6 @@
     return geometry_changed_;
   }
 
-  uint64_t frame_no() const {
-    return frame_no_;
-  }
-
   DrmCompositionType type() const {
     return type_;
   }
@@ -155,10 +123,6 @@
     return crtc_;
   }
 
-  Importer *importer() const {
-    return importer_;
-  }
-
   Planner *planner() const {
     return planner_;
   }
@@ -176,9 +140,7 @@
  private:
   bool validate_composition_type(DrmCompositionType desired);
 
-  DrmDevice *drm_ = NULL;
   DrmCrtc *crtc_ = NULL;
-  Importer *importer_ = NULL;
   Planner *planner_ = NULL;
 
   DrmCompositionType type_ = DRM_COMPOSITION_TYPE_EMPTY;
@@ -187,11 +149,9 @@
 
   UniqueFd out_fence_ = -1;
 
-  bool geometry_changed_;
+  bool geometry_changed_ = true;
   std::vector<DrmHwcLayer> layers_;
   std::vector<DrmCompositionPlane> composition_planes_;
-
-  uint64_t frame_no_ = 0;
 };
 }  // namespace android
 
diff --git a/compositor/DrmDisplayCompositor.cpp b/compositor/DrmDisplayCompositor.cpp
index ba0d56b..665446e 100644
--- a/compositor/DrmDisplayCompositor.cpp
+++ b/compositor/DrmDisplayCompositor.cpp
@@ -20,15 +20,14 @@
 #include "DrmDisplayCompositor.h"
 
 #include <drm/drm_mode.h>
-#include <log/log.h>
 #include <pthread.h>
 #include <sched.h>
-#include <stdlib.h>
 #include <sync/sync.h>
-#include <time.h>
 #include <utils/Trace.h>
 
 #include <array>
+#include <cstdlib>
+#include <ctime>
 #include <sstream>
 #include <vector>
 
@@ -36,8 +35,7 @@
 #include "drm/DrmDevice.h"
 #include "drm/DrmPlane.h"
 #include "utils/autolock.h"
-
-static const uint32_t kWaitWritebackFence = 100;  // ms
+#include "utils/log.h"
 
 namespace android {
 
@@ -52,11 +50,11 @@
 
 class CompositorVsyncCallback : public VsyncCallback {
  public:
-  CompositorVsyncCallback(DrmDisplayCompositor *compositor)
+  explicit CompositorVsyncCallback(DrmDisplayCompositor *compositor)
       : compositor_(compositor) {
   }
 
-  void Callback(int display, int64_t timestamp) {
+  void Callback(int display, int64_t timestamp) override {
     compositor_->Vsync(display, timestamp);
   }
 
@@ -65,7 +63,7 @@
 };
 
 DrmDisplayCompositor::DrmDisplayCompositor()
-    : resource_manager_(NULL),
+    : resource_manager_(nullptr),
       display_(-1),
       initialized_(false),
       active_(false),
@@ -73,10 +71,9 @@
       dump_frames_composited_(0),
       dump_last_timestamp_ns_(0),
       flatten_countdown_(FLATTEN_COUNTDOWN_INIT),
-      writeback_fence_(-1),
       flattening_state_(FlatteningState::kNone),
       frames_flattened_(0) {
-  struct timespec ts;
+  struct timespec ts {};
   if (clock_gettime(CLOCK_MONOTONIC, &ts))
     return;
   dump_last_timestamp_ns_ = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
@@ -113,7 +110,7 @@
     ALOGE("Could not find drmdevice for display");
     return -EINVAL;
   }
-  int ret = pthread_mutex_init(&lock_, NULL);
+  int ret = pthread_mutex_init(&lock_, nullptr);
   if (ret) {
     ALOGE("Failed to initialize drm compositor lock %d\n", ret);
     return ret;
@@ -128,11 +125,6 @@
   return 0;
 }
 
-std::unique_ptr<DrmDisplayComposition> DrmDisplayCompositor::CreateComposition()
-    const {
-  return std::unique_ptr<DrmDisplayComposition>(new DrmDisplayComposition());
-}
-
 std::unique_ptr<DrmDisplayComposition>
 DrmDisplayCompositor::CreateInitializedComposition() const {
   DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
@@ -141,18 +133,8 @@
     ALOGE("Failed to find crtc for display = %d", display_);
     return std::unique_ptr<DrmDisplayComposition>();
   }
-  std::unique_ptr<DrmDisplayComposition> comp = CreateComposition();
-  std::shared_ptr<Importer> importer = resource_manager_->GetImporter(display_);
-  if (!importer) {
-    ALOGE("Failed to find resources for display = %d", display_);
-    return std::unique_ptr<DrmDisplayComposition>();
-  }
-  int ret = comp->Init(drm, crtc, importer.get(), planner_.get(), 0);
-  if (ret) {
-    ALOGE("Failed to init composition for display = %d", display_);
-    return std::unique_ptr<DrmDisplayComposition>();
-  }
-  return comp;
+
+  return std::make_unique<DrmDisplayComposition>(crtc, planner_.get());
 }
 
 FlatteningState DrmDisplayCompositor::GetFlatteningState() const {
@@ -172,7 +154,7 @@
 DrmDisplayCompositor::GetActiveModeResolution() {
   DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
   DrmConnector *connector = drm->GetConnectorForDisplay(display_);
-  if (connector == NULL) {
+  if (connector == nullptr) {
     ALOGE("Failed to determine display mode: no connector for display %d",
           display_);
     return std::make_tuple(0, 0, -ENODEV);
@@ -189,7 +171,7 @@
     return -ENOMEM;
   }
 
-  int ret;
+  int ret = 0;
   std::vector<DrmCompositionPlane> &comp_planes = display_comp
                                                       ->composition_planes();
   for (DrmCompositionPlane &comp_plane : comp_planes) {
@@ -216,49 +198,8 @@
   return 0;
 }
 
-int DrmDisplayCompositor::SetupWritebackCommit(drmModeAtomicReqPtr pset,
-                                               uint32_t crtc_id,
-                                               DrmConnector *writeback_conn,
-                                               DrmHwcBuffer *writeback_buffer) {
-  int ret = 0;
-  if (writeback_conn->writeback_fb_id().id() == 0 ||
-      writeback_conn->writeback_out_fence().id() == 0) {
-    ALOGE("Writeback properties don't exit");
-    return -EINVAL;
-  }
-  if ((*writeback_buffer)->fb_id == 0) {
-    ALOGE("Invalid writeback buffer");
-    return -EINVAL;
-  }
-  ret = drmModeAtomicAddProperty(pset, writeback_conn->id(),
-                                 writeback_conn->writeback_fb_id().id(),
-                                 (*writeback_buffer)->fb_id);
-  if (ret < 0) {
-    ALOGE("Failed to add writeback_fb_id");
-    return ret;
-  }
-  ret = drmModeAtomicAddProperty(pset, writeback_conn->id(),
-                                 writeback_conn->writeback_out_fence().id(),
-                                 (uint64_t)&writeback_fence_);
-  if (ret < 0) {
-    ALOGE("Failed to add writeback_out_fence");
-    return ret;
-  }
-
-  ret = drmModeAtomicAddProperty(pset, writeback_conn->id(),
-                                 writeback_conn->crtc_id_property().id(),
-                                 crtc_id);
-  if (ret < 0) {
-    ALOGE("Failed to  attach writeback");
-    return ret;
-  }
-  return 0;
-}
-
 int DrmDisplayCompositor::CommitFrame(DrmDisplayComposition *display_comp,
-                                      bool test_only,
-                                      DrmConnector *writeback_conn,
-                                      DrmHwcBuffer *writeback_buffer) {
+                                      bool test_only) {
   ATRACE_CALL();
 
   int ret = 0;
@@ -286,18 +227,6 @@
     return -ENOMEM;
   }
 
-  if (writeback_buffer != NULL) {
-    if (writeback_conn == NULL) {
-      ALOGE("Invalid arguments requested writeback without writeback conn");
-      return -EINVAL;
-    }
-    ret = SetupWritebackCommit(pset, crtc->id(), writeback_conn,
-                               writeback_buffer);
-    if (ret < 0) {
-      ALOGE("Failed to Setup Writeback Commit ret = %d", ret);
-      return ret;
-    }
-  }
   if (crtc->out_fence_ptr_property().id() != 0) {
     ret = drmModeAtomicAddProperty(pset, crtc->id(),
                                    crtc->out_fence_ptr_property().id(),
@@ -332,7 +261,6 @@
 
   for (DrmCompositionPlane &comp_plane : comp_planes) {
     DrmPlane *plane = comp_plane.plane();
-    DrmCrtc *crtc = comp_plane.crtc();
     std::vector<size_t> &source_layers = comp_plane.source_layers();
 
     int fb_id = -1;
@@ -341,7 +269,9 @@
     hwc_frect_t source_crop;
     uint64_t rotation = 0;
     uint64_t alpha = 0xFFFF;
-    uint64_t blend;
+    uint64_t blend = UINT64_MAX;
+    uint64_t color_encoding = UINT64_MAX;
+    uint64_t color_range = UINT64_MAX;
 
     if (comp_plane.type() != DrmCompositionPlane::Type::kDisable) {
       if (source_layers.size() > 1) {
@@ -427,6 +357,45 @@
           break;
         }
       }
+
+      if (plane->color_encoding_propery().id()) {
+        switch (layer.dataspace & HAL_DATASPACE_STANDARD_MASK) {
+          case HAL_DATASPACE_STANDARD_BT709:
+            std::tie(color_encoding,
+                     ret) = plane->color_encoding_propery()
+                                .GetEnumValueWithName("ITU-R BT.709 YCbCr");
+            break;
+          case HAL_DATASPACE_STANDARD_BT601_625:
+          case HAL_DATASPACE_STANDARD_BT601_625_UNADJUSTED:
+          case HAL_DATASPACE_STANDARD_BT601_525:
+          case HAL_DATASPACE_STANDARD_BT601_525_UNADJUSTED:
+            std::tie(color_encoding,
+                     ret) = plane->color_encoding_propery()
+                                .GetEnumValueWithName("ITU-R BT.601 YCbCr");
+            break;
+          case HAL_DATASPACE_STANDARD_BT2020:
+          case HAL_DATASPACE_STANDARD_BT2020_CONSTANT_LUMINANCE:
+            std::tie(color_encoding,
+                     ret) = plane->color_encoding_propery()
+                                .GetEnumValueWithName("ITU-R BT.2020 YCbCr");
+            break;
+        }
+      }
+
+      if (plane->color_range_property().id()) {
+        switch (layer.dataspace & HAL_DATASPACE_RANGE_MASK) {
+          case HAL_DATASPACE_RANGE_FULL:
+            std::tie(color_range,
+                     ret) = plane->color_range_property()
+                                .GetEnumValueWithName("YCbCr full range");
+            break;
+          case HAL_DATASPACE_RANGE_LIMITED:
+            std::tie(color_range,
+                     ret) = plane->color_range_property()
+                                .GetEnumValueWithName("YCbCr limited range");
+            break;
+        }
+      }
     }
 
     // Disable the plane if there's no framebuffer
@@ -500,7 +469,7 @@
       }
     }
 
-    if (plane->blend_property().id()) {
+    if (plane->blend_property().id() && blend != UINT64_MAX) {
       ret = drmModeAtomicAddProperty(pset, plane->id(),
                                      plane->blend_property().id(), blend) < 0;
       if (ret) {
@@ -509,6 +478,28 @@
         break;
       }
     }
+
+    if (plane->color_encoding_propery().id() && color_encoding != UINT64_MAX) {
+      ret = drmModeAtomicAddProperty(pset, plane->id(),
+                                     plane->color_encoding_propery().id(),
+                                     color_encoding) < 0;
+      if (ret) {
+        ALOGE("Failed to add COLOR_ENCODING property %d to plane %d",
+              plane->color_encoding_propery().id(), plane->id());
+        break;
+      }
+    }
+
+    if (plane->color_range_property().id() && color_range != UINT64_MAX) {
+      ret = drmModeAtomicAddProperty(pset, plane->id(),
+                                     plane->color_range_property().id(),
+                                     color_range) < 0;
+      if (ret) {
+        ALOGE("Failed to add COLOR_RANGE property %d to plane %d",
+              plane->color_range_property().id(), plane->id());
+        break;
+      }
+    }
   }
 
   if (!ret) {
@@ -575,8 +566,7 @@
 
 std::tuple<int, uint32_t> DrmDisplayCompositor::CreateModeBlob(
     const DrmMode &mode) {
-  struct drm_mode_modeinfo drm_mode;
-  memset(&drm_mode, 0, sizeof(drm_mode));
+  struct drm_mode_modeinfo drm_mode {};
   mode.ToDrmModeModeInfo(&drm_mode);
 
   uint32_t id = 0;
@@ -598,23 +588,17 @@
   if (DisablePlanes(active_composition_.get()))
     return;
 
-  active_composition_.reset(NULL);
-  vsync_worker_.VSyncControl(false);
+  active_composition_.reset(nullptr);
 }
 
 void DrmDisplayCompositor::ApplyFrame(
-    std::unique_ptr<DrmDisplayComposition> composition, int status,
-    bool writeback) {
+    std::unique_ptr<DrmDisplayComposition> composition, int status) {
   AutoLock lock(&lock_, __func__);
   if (lock.Lock())
     return;
   int ret = status;
 
   if (!ret) {
-    if (writeback && !CountdownExpired()) {
-      ALOGE("Abort playing back scene");
-      return;
-    }
     ret = CommitFrame(composition.get(), false);
   }
 
@@ -635,7 +619,7 @@
   } else {
     SetFlattening(FlatteningState::kClientDone);
   }
-  vsync_worker_.VSyncControl(!writeback);
+  vsync_worker_.VSyncControl(true);
 }
 
 int DrmDisplayCompositor::ApplyComposition(
@@ -685,118 +669,10 @@
   return CommitFrame(composition, true);
 }
 
-// Flatten a scene on the display by using a writeback connector
-// and returns the composition result as a DrmHwcLayer.
-int DrmDisplayCompositor::FlattenOnDisplay(
-    std::unique_ptr<DrmDisplayComposition> &src, DrmConnector *writeback_conn,
-    DrmMode &src_mode, DrmHwcLayer *writeback_layer) {
-  int ret = 0;
-  DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
-  ret = writeback_conn->UpdateModes();
-  if (ret) {
-    ALOGE("Failed to update modes %d", ret);
-    return ret;
-  }
-  for (const DrmMode &mode : writeback_conn->modes()) {
-    if (mode.h_display() == src_mode.h_display() &&
-        mode.v_display() == src_mode.v_display()) {
-      mode_.mode = mode;
-      if (mode_.blob_id)
-        drm->DestroyPropertyBlob(mode_.blob_id);
-      std::tie(ret, mode_.blob_id) = CreateModeBlob(mode_.mode);
-      if (ret) {
-        ALOGE("Failed to create mode blob for display %d", display_);
-        return ret;
-      }
-      mode_.needs_modeset = true;
-      break;
-    }
-  }
-  if (mode_.blob_id <= 0) {
-    ALOGE("Failed to find similar mode");
-    return -EINVAL;
-  }
-
-  DrmCrtc *crtc = drm->GetCrtcForDisplay(display_);
-  if (!crtc) {
-    ALOGE("Failed to find crtc for display %d", display_);
-    return -EINVAL;
-  }
-  // TODO what happens if planes could go to both CRTCs, I don't think it's
-  // handled anywhere
-  std::vector<DrmPlane *> primary_planes;
-  std::vector<DrmPlane *> overlay_planes;
-  for (auto &plane : drm->planes()) {
-    if (!plane->GetCrtcSupported(*crtc))
-      continue;
-    if (plane->type() == DRM_PLANE_TYPE_PRIMARY)
-      primary_planes.push_back(plane.get());
-    else if (plane->type() == DRM_PLANE_TYPE_OVERLAY)
-      overlay_planes.push_back(plane.get());
-  }
-
-  ret = src->Plan(&primary_planes, &overlay_planes);
-  if (ret) {
-    ALOGE("Failed to plan the composition ret = %d", ret);
-    return ret;
-  }
-
-  // Disable the planes we're not using
-  for (auto i = primary_planes.begin(); i != primary_planes.end();) {
-    src->AddPlaneDisable(*i);
-    i = primary_planes.erase(i);
-  }
-  for (auto i = overlay_planes.begin(); i != overlay_planes.end();) {
-    src->AddPlaneDisable(*i);
-    i = overlay_planes.erase(i);
-  }
-
-  AutoLock lock(&lock_, __func__);
-  ret = lock.Lock();
-  if (ret)
-    return ret;
-  DrmFramebuffer *writeback_fb = &framebuffers_[framebuffer_index_];
-  framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
-  if (!writeback_fb->Allocate(mode_.mode.h_display(), mode_.mode.v_display())) {
-    ALOGE("Failed to allocate writeback buffer");
-    return -ENOMEM;
-  }
-  DrmHwcBuffer *writeback_buffer = &writeback_layer->buffer;
-  writeback_layer->sf_handle = writeback_fb->buffer()->handle;
-  ret = writeback_layer->ImportBuffer(
-      resource_manager_->GetImporter(display_).get());
-  if (ret) {
-    ALOGE("Failed to import writeback buffer");
-    return ret;
-  }
-
-  ret = CommitFrame(src.get(), true, writeback_conn, writeback_buffer);
-  if (ret) {
-    ALOGE("Atomic check failed");
-    return ret;
-  }
-  ret = CommitFrame(src.get(), false, writeback_conn, writeback_buffer);
-  if (ret) {
-    ALOGE("Atomic commit failed");
-    return ret;
-  }
-
-  ret = sync_wait(writeback_fence_, kWaitWritebackFence);
-  writeback_layer->acquire_fence.Set(writeback_fence_);
-  writeback_fence_ = -1;
-  if (ret) {
-    ALOGE("Failed to wait on writeback fence");
-    return ret;
-  }
-  return 0;
-}
-
 void DrmDisplayCompositor::SetFlattening(FlatteningState new_state) {
   if (flattening_state_ != new_state) {
     switch (flattening_state_) {
       case FlatteningState::kClientDone:
-      case FlatteningState::kConcurrent:
-      case FlatteningState::kSerial:
         ++frames_flattened_;
         break;
       case FlatteningState::kClientRequested:
@@ -833,222 +709,14 @@
     SetFlattening(FlatteningState::kClientRequested);
     refresh_callback_hook_(refresh_callback_data_, display_);
     return 0;
-  } else {
-    ALOGV("No writeback connector available");
-    return -EINVAL;
-  }
-}
-
-// Flatten a scene by enabling the writeback connector attached
-// to the same CRTC as the one driving the display.
-int DrmDisplayCompositor::FlattenSerial(DrmConnector *writeback_conn) {
-  ALOGV("FlattenSerial by enabling writeback connector to the same crtc");
-  // Flattened composition with only one layer that is obtained
-  // using the writeback connector
-  std::unique_ptr<DrmDisplayComposition>
-      writeback_comp = CreateInitializedComposition();
-  if (!writeback_comp)
-    return -EINVAL;
-
-  AutoLock lock(&lock_, __func__);
-  int ret = lock.Lock();
-  if (ret)
-    return ret;
-  if (!IsFlatteningNeeded()) {
-    ALOGV("Flattening is not needed");
-    SetFlattening(FlatteningState::kNotNeeded);
-    return -EALREADY;
   }
 
-  DrmFramebuffer *writeback_fb = &framebuffers_[framebuffer_index_];
-  framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
-  lock.Unlock();
-
-  if (!writeback_fb->Allocate(mode_.mode.h_display(), mode_.mode.v_display())) {
-    ALOGE("Failed to allocate writeback buffer");
-    return -ENOMEM;
-  }
-  writeback_comp->layers().emplace_back();
-
-  DrmHwcLayer &writeback_layer = writeback_comp->layers().back();
-  writeback_layer.sf_handle = writeback_fb->buffer()->handle;
-  writeback_layer.source_crop = {0, 0, (float)mode_.mode.h_display(),
-                                 (float)mode_.mode.v_display()};
-  writeback_layer.display_frame = {0, 0, (int)mode_.mode.h_display(),
-                                   (int)mode_.mode.v_display()};
-  ret = writeback_layer.ImportBuffer(
-      resource_manager_->GetImporter(display_).get());
-  if (ret || writeback_comp->layers().size() != 1) {
-    ALOGE("Failed to import writeback buffer");
-    return ret;
-  }
-
-  drmModeAtomicReqPtr pset = drmModeAtomicAlloc();
-  if (!pset) {
-    ALOGE("Failed to allocate property set");
-    return -ENOMEM;
-  }
-  DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
-  DrmCrtc *crtc = drm->GetCrtcForDisplay(display_);
-  if (!crtc) {
-    ALOGE("Failed to find crtc for display %d", display_);
-    return -EINVAL;
-  }
-  ret = SetupWritebackCommit(pset, crtc->id(), writeback_conn,
-                             &writeback_layer.buffer);
-  if (ret < 0) {
-    ALOGE("Failed to Setup Writeback Commit");
-    return ret;
-  }
-  ret = drmModeAtomicCommit(drm->fd(), pset, 0, drm);
-  if (ret) {
-    ALOGE("Failed to enable writeback %d", ret);
-    return ret;
-  }
-  ret = sync_wait(writeback_fence_, kWaitWritebackFence);
-  writeback_layer.acquire_fence.Set(writeback_fence_);
-  writeback_fence_ = -1;
-  if (ret) {
-    ALOGE("Failed to wait on writeback fence");
-    return ret;
-  }
-
-  DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kLayer, NULL,
-                                    crtc);
-  for (auto &drmplane : drm->planes()) {
-    if (!drmplane->GetCrtcSupported(*crtc))
-      continue;
-    if (!squashed_comp.plane() && drmplane->type() == DRM_PLANE_TYPE_PRIMARY)
-      squashed_comp.set_plane(drmplane.get());
-    else
-      writeback_comp->AddPlaneDisable(drmplane.get());
-  }
-  squashed_comp.source_layers().push_back(0);
-  ret = writeback_comp->AddPlaneComposition(std::move(squashed_comp));
-  if (ret) {
-    ALOGE("Failed to add flatten scene");
-    return ret;
-  }
-
-  ApplyFrame(std::move(writeback_comp), 0, true);
-  return 0;
-}
-
-// Flatten a scene by using a crtc which works concurrent with
-// the one driving the display.
-int DrmDisplayCompositor::FlattenConcurrent(DrmConnector *writeback_conn) {
-  ALOGV("FlattenConcurrent by using an unused crtc/display");
-  int ret = 0;
-  DrmDisplayCompositor drmdisplaycompositor;
-  ret = drmdisplaycompositor.Init(resource_manager_, writeback_conn->display());
-  if (ret) {
-    ALOGE("Failed to init  drmdisplaycompositor = %d", ret);
-    return ret;
-  }
-  // Copy of the active_composition, needed because of two things:
-  // 1) Not to hold the lock for the whole time we are accessing
-  //    active_composition
-  // 2) It will be committed on a crtc that might not be on the same
-  //     dri node, so buffers need to be imported on the right node.
-  std::unique_ptr<DrmDisplayComposition>
-      copy_comp = drmdisplaycompositor.CreateInitializedComposition();
-
-  // Writeback composition that will be committed to the display.
-  std::unique_ptr<DrmDisplayComposition>
-      writeback_comp = CreateInitializedComposition();
-
-  if (!copy_comp || !writeback_comp)
-    return -EINVAL;
-  AutoLock lock(&lock_, __func__);
-  ret = lock.Lock();
-  if (ret)
-    return ret;
-  if (!IsFlatteningNeeded()) {
-    ALOGV("Flattening is not needed");
-    SetFlattening(FlatteningState::kNotNeeded);
-    return -EALREADY;
-  }
-  DrmCrtc *crtc = active_composition_->crtc();
-
-  std::vector<DrmHwcLayer> copy_layers;
-  for (DrmHwcLayer &src_layer : active_composition_->layers()) {
-    DrmHwcLayer copy;
-    ret = copy.InitFromDrmHwcLayer(&src_layer,
-                                   resource_manager_
-                                       ->GetImporter(writeback_conn->display())
-                                       .get());
-    if (ret) {
-      ALOGE("Failed to import buffer ret = %d", ret);
-      return -EINVAL;
-    }
-    copy_layers.emplace_back(std::move(copy));
-  }
-  ret = copy_comp->SetLayers(copy_layers.data(), copy_layers.size(), true);
-  if (ret) {
-    ALOGE("Failed to set copy_comp layers");
-    return ret;
-  }
-
-  lock.Unlock();
-  DrmHwcLayer writeback_layer;
-  ret = drmdisplaycompositor.FlattenOnDisplay(copy_comp, writeback_conn,
-                                              mode_.mode, &writeback_layer);
-  if (ret) {
-    ALOGE("Failed to flatten on display ret = %d", ret);
-    return ret;
-  }
-
-  DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kLayer, NULL,
-                                    crtc);
-  for (auto &drmplane : resource_manager_->GetDrmDevice(display_)->planes()) {
-    if (!drmplane->GetCrtcSupported(*crtc))
-      continue;
-    if (drmplane->type() == DRM_PLANE_TYPE_PRIMARY)
-      squashed_comp.set_plane(drmplane.get());
-    else
-      writeback_comp->AddPlaneDisable(drmplane.get());
-  }
-  writeback_comp->layers().emplace_back();
-  DrmHwcLayer &next_layer = writeback_comp->layers().back();
-  next_layer.sf_handle = writeback_layer.get_usable_handle();
-  next_layer.blending = DrmHwcBlending::kPreMult;
-  next_layer.source_crop = {0, 0, (float)mode_.mode.h_display(),
-                            (float)mode_.mode.v_display()};
-  next_layer.display_frame = {0, 0, (int)mode_.mode.h_display(),
-                              (int)mode_.mode.v_display()};
-  ret = next_layer.ImportBuffer(resource_manager_->GetImporter(display_).get());
-  if (ret) {
-    ALOGE("Failed to import framebuffer for display %d", ret);
-    return ret;
-  }
-  squashed_comp.source_layers().push_back(0);
-  ret = writeback_comp->AddPlaneComposition(std::move(squashed_comp));
-  if (ret) {
-    ALOGE("Failed to add plane composition %d", ret);
-    return ret;
-  }
-  ApplyFrame(std::move(writeback_comp), 0, true);
-  return ret;
+  ALOGV("No writeback connector available");
+  return -EINVAL;
 }
 
 int DrmDisplayCompositor::FlattenActiveComposition() {
-  DrmConnector *writeback_conn = resource_manager_->AvailableWritebackConnector(
-      display_);
-  if (!active_composition_ || !writeback_conn) {
-    // Try to fallback to GPU composition on client, since it is more
-    // power-efficient than composition on device side
-    return FlattenOnClient();
-  }
-
-  if (writeback_conn->display() != display_) {
-    SetFlattening(FlatteningState::kConcurrent);
-    return FlattenConcurrent(writeback_conn);
-  } else {
-    SetFlattening(FlatteningState::kSerial);
-    return FlattenSerial(writeback_conn);
-  }
-
-  return 0;
+  return FlattenOnClient();
 }
 
 bool DrmDisplayCompositor::CountdownExpired() const {
@@ -1077,7 +745,7 @@
   uint64_t num_frames = dump_frames_composited_;
   dump_frames_composited_ = 0;
 
-  struct timespec ts;
+  struct timespec ts {};
   ret = clock_gettime(CLOCK_MONOTONIC, &ts);
   if (ret) {
     pthread_mutex_unlock(&lock_);
@@ -1086,7 +754,7 @@
 
   uint64_t cur_ts = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
   uint64_t num_ms = (cur_ts - dump_last_timestamp_ns_) / (1000 * 1000);
-  float fps = num_ms ? (num_frames * 1000.0f) / (num_ms) : 0.0f;
+  float fps = num_ms ? (num_frames * 1000.0F) / (num_ms) : 0.0F;
 
   *out << "--DrmDisplayCompositor[" << display_
        << "]: num_frames=" << num_frames << " num_ms=" << num_ms
diff --git a/compositor/DrmDisplayCompositor.h b/compositor/DrmDisplayCompositor.h
index ab3f867..aebb6ff 100644
--- a/compositor/DrmDisplayCompositor.h
+++ b/compositor/DrmDisplayCompositor.h
@@ -21,21 +21,17 @@
 #include <hardware/hwcomposer.h>
 #include <pthread.h>
 
+#include <functional>
 #include <memory>
 #include <sstream>
 #include <tuple>
 
 #include "DrmDisplayComposition.h"
-#include "DrmFramebuffer.h"
 #include "Planner.h"
 #include "drm/ResourceManager.h"
 #include "drm/VSyncWorker.h"
 #include "drmhwcomposer.h"
 
-// One for the front, one for the back, and one for cases where we need to
-// squash a frame that the hw can't display with hw overlays.
-#define DRM_DISPLAY_BUFFERS 3
-
 // If a scene is still for this number of vblanks flatten it to reduce power
 // consumption.
 #define FLATTEN_COUNTDOWN_INIT 60
@@ -47,8 +43,6 @@
   kNotNeeded,
   kClientRequested,
   kClientDone,
-  kSerial,
-  kConcurrent
 };
 
 std::ostream &operator<<(std::ostream &str, FlatteningState state);
@@ -71,7 +65,6 @@
     refresh_callback_hook_ = reinterpret_cast<HWC2_PFN_REFRESH>(hook);
   }
 
-  std::unique_ptr<DrmDisplayComposition> CreateComposition() const;
   std::unique_ptr<DrmDisplayComposition> CreateInitializedComposition() const;
   int ApplyComposition(std::unique_ptr<DrmDisplayComposition> composition);
   int TestComposition(DrmDisplayComposition *composition);
@@ -106,27 +99,17 @@
   static const int kAcquireWaitTries = 5;
   static const int kAcquireWaitTimeoutMs = 100;
 
-  int CommitFrame(DrmDisplayComposition *display_comp, bool test_only,
-                  DrmConnector *writeback_conn = NULL,
-                  DrmHwcBuffer *writeback_buffer = NULL);
-  int SetupWritebackCommit(drmModeAtomicReqPtr pset, uint32_t crtc_id,
-                           DrmConnector *writeback_conn,
-                           DrmHwcBuffer *writeback_buffer);
+  int CommitFrame(DrmDisplayComposition *display_comp, bool test_only);
   int ApplyDpms(DrmDisplayComposition *display_comp);
   int DisablePlanes(DrmDisplayComposition *display_comp);
 
   void ApplyFrame(std::unique_ptr<DrmDisplayComposition> composition,
-                  int status, bool writeback = false);
+                  int status);
 
   void SetFlattening(FlatteningState new_state);
   bool IsFlatteningNeeded() const;
   int FlattenActiveComposition();
   int FlattenOnClient();
-  int FlattenSerial(DrmConnector *writeback_conn);
-  int FlattenConcurrent(DrmConnector *writeback_conn);
-  int FlattenOnDisplay(std::unique_ptr<DrmDisplayComposition> &src,
-                       DrmConnector *writeback_conn, DrmMode &src_mode,
-                       DrmHwcLayer *writeback_layer);
 
   bool CountdownExpired() const;
 
@@ -143,11 +126,8 @@
 
   ModeState mode_;
 
-  int framebuffer_index_;
-  DrmFramebuffer framebuffers_[DRM_DISPLAY_BUFFERS];
-
   // mutable since we need to acquire in Dump()
-  mutable pthread_mutex_t lock_;
+  mutable pthread_mutex_t lock_{};
 
   // State tracking progress since our last Dump(). These are mutable since
   // we need to reset them on every Dump() call.
@@ -156,7 +136,6 @@
   VSyncWorker vsync_worker_;
   int64_t flatten_countdown_;
   std::unique_ptr<Planner> planner_;
-  int writeback_fence_;
 
   FlatteningState flattening_state_;
   uint32_t frames_flattened_;
diff --git a/compositor/Planner.cpp b/compositor/Planner.cpp
index f4b5c51..42259d1 100644
--- a/compositor/Planner.cpp
+++ b/compositor/Planner.cpp
@@ -18,13 +18,14 @@
 
 #include "Planner.h"
 
-#include <log/log.h>
+#include <algorithm>
 
 #include "drm/DrmDevice.h"
+#include "utils/log.h"
 
 namespace android {
 
-std::unique_ptr<Planner> Planner::CreateInstance(DrmDevice *) {
+std::unique_ptr<Planner> Planner::CreateInstance(DrmDevice * /*device*/) {
   std::unique_ptr<Planner> planner(new Planner);
   planner->AddStage<PlanStageGreedy>();
   return planner;
@@ -43,57 +44,6 @@
   return usable_planes;
 }
 
-int Planner::PlanStage::ValidatePlane(DrmPlane *plane, DrmHwcLayer *layer) {
-  int ret = 0;
-  uint64_t blend;
-
-  if ((plane->rotation_property().id() == 0) &&
-      layer->transform != DrmHwcTransform::kIdentity) {
-    ALOGE("Rotation is not supported on plane %d", plane->id());
-    return -EINVAL;
-  }
-
-  if (plane->alpha_property().id() == 0 && layer->alpha != 0xffff) {
-    ALOGE("Alpha is not supported on plane %d", plane->id());
-    return -EINVAL;
-  }
-
-  if (plane->blend_property().id() == 0) {
-    if ((layer->blending != DrmHwcBlending::kNone) &&
-        (layer->blending != DrmHwcBlending::kPreMult)) {
-      ALOGE("Blending is not supported on plane %d", plane->id());
-      return -EINVAL;
-    }
-  } else {
-    switch (layer->blending) {
-      case DrmHwcBlending::kPreMult:
-        std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName(
-            "Pre-multiplied");
-        break;
-      case DrmHwcBlending::kCoverage:
-        std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName(
-            "Coverage");
-        break;
-      case DrmHwcBlending::kNone:
-      default:
-        std::tie(blend,
-                 ret) = plane->blend_property().GetEnumValueWithName("None");
-        break;
-    }
-    if (ret)
-      ALOGE("Expected a valid blend mode on plane %d", plane->id());
-  }
-
-  uint32_t format = layer->buffer->format;
-  if (!plane->IsFormatSupported(format)) {
-    ALOGE("Plane %d does not supports %c%c%c%c format", plane->id(), format,
-          format >> 8, format >> 16, format >> 24);
-    return -EINVAL;
-  }
-
-  return ret;
-}
-
 std::tuple<int, std::vector<DrmCompositionPlane>> Planner::ProvisionPlanes(
     std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
     std::vector<DrmPlane *> *primary_planes,
@@ -108,7 +58,7 @@
 
   // Go through the provisioning stages and provision planes
   for (auto &i : stages_) {
-    int ret = i->ProvisionPlanes(&composition, layers, crtc, &planes);
+    int ret = i->ProvisionPlanes(&composition, layers, &planes);
     if (ret) {
       ALOGE("Failed provision stage with ret %d", ret);
       return std::make_tuple(ret, std::vector<DrmCompositionPlane>());
@@ -120,24 +70,22 @@
 
 int PlanStageProtected::ProvisionPlanes(
     std::vector<DrmCompositionPlane> *composition,
-    std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+    std::map<size_t, DrmHwcLayer *> &layers,
     std::vector<DrmPlane *> *planes) {
-  int ret;
-  int protected_zorder = -1;
+  int ret = 0;
   for (auto i = layers.begin(); i != layers.end();) {
     if (!i->second->protected_usage()) {
       ++i;
       continue;
     }
 
-    ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer, crtc,
+    ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer,
                   std::make_pair(i->first, i->second));
     if (ret) {
       ALOGE("Failed to dedicate protected layer! Dropping it.");
       return ret;
     }
 
-    protected_zorder = i->first;
     i = layers.erase(i);
   }
 
@@ -146,16 +94,17 @@
 
 int PlanStageGreedy::ProvisionPlanes(
     std::vector<DrmCompositionPlane> *composition,
-    std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+    std::map<size_t, DrmHwcLayer *> &layers,
     std::vector<DrmPlane *> *planes) {
   // Fill up the remaining planes
   for (auto i = layers.begin(); i != layers.end(); i = layers.erase(i)) {
     int ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer,
-                      crtc, std::make_pair(i->first, i->second));
+                      std::make_pair(i->first, i->second));
     // We don't have any planes left
     if (ret == -ENOENT)
       break;
-    else if (ret) {
+
+    if (ret) {
       ALOGE("Failed to emplace layer %zu, dropping it", i->first);
       return ret;
     }
diff --git a/compositor/Planner.h b/compositor/Planner.h
index 09034ff..3390acb 100644
--- a/compositor/Planner.h
+++ b/compositor/Planner.h
@@ -21,6 +21,7 @@
 #include <hardware/hwcomposer.h>
 
 #include <map>
+#include <memory>
 #include <vector>
 
 #include "compositor/DrmDisplayComposition.h"
@@ -39,7 +40,6 @@
 
     virtual int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
                                 std::map<size_t, DrmHwcLayer *> &layers,
-                                DrmCrtc *crtc,
                                 std::vector<DrmPlane *> *planes) = 0;
 
    protected:
@@ -52,18 +52,16 @@
       return plane;
     }
 
-    static int ValidatePlane(DrmPlane *plane, DrmHwcLayer *layer);
-
     // Inserts the given layer:plane in the composition at the back
     static int Emplace(std::vector<DrmCompositionPlane> *composition,
                        std::vector<DrmPlane *> *planes,
-                       DrmCompositionPlane::Type type, DrmCrtc *crtc,
+                       DrmCompositionPlane::Type type,
                        std::pair<size_t, DrmHwcLayer *> layer) {
       DrmPlane *plane = PopPlane(planes);
       std::vector<DrmPlane *> unused_planes;
       int ret = -ENOENT;
       while (plane) {
-        ret = ValidatePlane(plane, layer.second);
+        ret = plane->IsValidForLayer(layer.second) ? 0 : -EINVAL;
         if (!ret)
           break;
         if (!plane->zpos_property().is_immutable())
@@ -72,7 +70,7 @@
       }
 
       if (!ret) {
-        composition->emplace_back(type, plane, crtc, layer.first);
+        composition->emplace_back(type, plane, layer.first);
         planes->insert(planes->begin(), unused_planes.begin(),
                        unused_planes.end());
       }
@@ -99,7 +97,7 @@
       std::vector<DrmPlane *> *overlay_planes);
 
   template <typename T, typename... A>
-  void AddStage(A &&... args) {
+  void AddStage(A &&...args) {
     stages_.emplace_back(
         std::unique_ptr<PlanStage>(new T(std::forward(args)...)));
   }
@@ -117,7 +115,7 @@
 class PlanStageProtected : public Planner::PlanStage {
  public:
   int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
-                      std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+                      std::map<size_t, DrmHwcLayer *> &layers,
                       std::vector<DrmPlane *> *planes);
 };
 
@@ -127,7 +125,7 @@
 class PlanStageGreedy : public Planner::PlanStage {
  public:
   int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
-                      std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+                      std::map<size_t, DrmHwcLayer *> &layers,
                       std::vector<DrmPlane *> *planes);
 };
 }  // namespace android
diff --git a/drm/DrmConnector.cpp b/drm/DrmConnector.cpp
index f1b6c1b..0468527 100644
--- a/drm/DrmConnector.cpp
+++ b/drm/DrmConnector.cpp
@@ -18,19 +18,19 @@
 
 #include "DrmConnector.h"
 
-#include <errno.h>
-#include <log/log.h>
-#include <stdint.h>
 #include <xf86drmMode.h>
 
 #include <array>
+#include <cerrno>
+#include <cstdint>
 #include <sstream>
 
 #include "DrmDevice.h"
+#include "utils/log.h"
 
 namespace android {
 
-constexpr size_t TYPES_COUNT = 17;
+constexpr size_t kTypesCount = 17;
 
 DrmConnector::DrmConnector(DrmDevice *drm, drmModeConnectorPtr c,
                            DrmEncoder *current_encoder,
@@ -58,7 +58,7 @@
     ALOGE("Could not get CRTC_ID property\n");
     return ret;
   }
-  ret = UpdateEdidProperty();
+  UpdateEdidProperty();
   if (writeback()) {
     ret = drm_->GetConnectorProperty(*this, "WRITEBACK_PIXEL_FORMATS",
                                      &writeback_pixel_formats_);
@@ -91,7 +91,7 @@
 }
 
 int DrmConnector::GetEdidBlob(drmModePropertyBlobPtr &blob) {
-  uint64_t blob_id;
+  uint64_t blob_id = 0;
   int ret = UpdateEdidProperty();
   if (ret) {
     return ret;
@@ -144,19 +144,19 @@
 }
 
 std::string DrmConnector::name() const {
-  constexpr std::array<const char *, TYPES_COUNT> names =
+  constexpr std::array<const char *, kTypesCount> kNames =
       {"None",   "VGA",  "DVI-I",     "DVI-D",   "DVI-A", "Composite",
        "SVIDEO", "LVDS", "Component", "DIN",     "DP",    "HDMI-A",
        "HDMI-B", "TV",   "eDP",       "Virtual", "DSI"};
 
-  if (type_ < TYPES_COUNT) {
+  if (type_ < kTypesCount) {
     std::ostringstream name_buf;
-    name_buf << names[type_] << "-" << type_id_;
+    name_buf << kNames[type_] << "-" << type_id_;
     return name_buf.str();
-  } else {
-    ALOGE("Unknown type in connector %d, could not make his name", id_);
-    return "None";
   }
+
+  ALOGE("Unknown type in connector %d, could not make his name", id_);
+  return "None";
 }
 
 int DrmConnector::UpdateModes() {
@@ -194,7 +194,7 @@
     }
   }
   modes_.swap(new_modes);
-  if (!preferred_mode_found && modes_.size() != 0) {
+  if (!preferred_mode_found && !modes_.empty()) {
     preferred_mode_id_ = modes_[0].id();
   }
   return 0;
diff --git a/drm/DrmConnector.h b/drm/DrmConnector.h
index 8533af8..3bc18c8 100644
--- a/drm/DrmConnector.h
+++ b/drm/DrmConnector.h
@@ -111,7 +111,7 @@
 
   std::vector<DrmEncoder *> possible_encoders_;
 
-  uint32_t preferred_mode_id_;
+  uint32_t preferred_mode_id_{};
 };
 }  // namespace android
 
diff --git a/drm/DrmCrtc.cpp b/drm/DrmCrtc.cpp
index 4ce8cfc..4da08fe 100644
--- a/drm/DrmCrtc.cpp
+++ b/drm/DrmCrtc.cpp
@@ -18,10 +18,11 @@
 
 #include "DrmCrtc.h"
 
-#include <log/log.h>
-#include <stdint.h>
+#include <utils/log.h>
 #include <xf86drmMode.h>
 
+#include <cstdint>
+
 #include "DrmDevice.h"
 
 namespace android {
diff --git a/drm/DrmDevice.cpp b/drm/DrmDevice.cpp
index bf1a5e2..150aa01 100644
--- a/drm/DrmDevice.cpp
+++ b/drm/DrmDevice.cpp
@@ -18,34 +18,35 @@
 
 #include "DrmDevice.h"
 
-#include <cutils/properties.h>
-#include <errno.h>
 #include <fcntl.h>
-#include <log/log.h>
-#include <stdint.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
 #include <algorithm>
 #include <array>
+#include <cerrno>
 #include <cinttypes>
+#include <cstdint>
 #include <sstream>
 #include <string>
 
-static void trim_left(std::string &str) {
-  str.erase(std::begin(str),
-            std::find_if(std::begin(str), std::end(str),
-                         [](int ch) { return !std::isspace(ch); }));
+#include "utils/log.h"
+#include "utils/properties.h"
+
+static void trim_left(std::string *str) {
+  str->erase(std::begin(*str),
+             std::find_if(std::begin(*str), std::end(*str),
+                          [](int ch) { return std::isspace(ch) == 0; }));
 }
 
-static void trim_right(std::string &str) {
-  str.erase(std::find_if(std::rbegin(str), std::rend(str),
-                         [](int ch) { return !std::isspace(ch); })
-                .base(),
-            std::end(str));
+static void trim_right(std::string *str) {
+  str->erase(std::find_if(std::rbegin(*str), std::rend(*str),
+                          [](int ch) { return std::isspace(ch) == 0; })
+                 .base(),
+             std::end(*str));
 }
 
-static void trim(std::string &str) {
+static void trim(std::string *str) {
   trim_left(str);
   trim_right(str);
 }
@@ -53,25 +54,25 @@
 namespace android {
 
 static std::vector<std::string> read_primary_display_order_prop() {
-  std::array<char, PROPERTY_VALUE_MAX> display_order_buf;
+  std::array<char, PROPERTY_VALUE_MAX> display_order_buf{};
   property_get("vendor.hwc.drm.primary_display_order", display_order_buf.data(),
                "...");
 
   std::vector<std::string> display_order;
   std::istringstream str(display_order_buf.data());
-  for (std::string conn_name = ""; std::getline(str, conn_name, ',');) {
-    trim(conn_name);
+  for (std::string conn_name; std::getline(str, conn_name, ',');) {
+    trim(&conn_name);
     display_order.push_back(std::move(conn_name));
   }
   return display_order;
 }
 
 static std::vector<DrmConnector *> make_primary_display_candidates(
-    std::vector<std::unique_ptr<DrmConnector>> &connectors) {
+    const std::vector<std::unique_ptr<DrmConnector>> &connectors) {
   std::vector<DrmConnector *> primary_candidates;
   std::transform(std::begin(connectors), std::end(connectors),
                  std::back_inserter(primary_candidates),
-                 [](std::unique_ptr<DrmConnector> &conn) {
+                 [](const std::unique_ptr<DrmConnector> &conn) {
                    return conn.get();
                  });
   primary_candidates.erase(std::remove_if(std::begin(primary_candidates),
@@ -119,7 +120,7 @@
 
 std::tuple<int, int> DrmDevice::Init(const char *path, int num_displays) {
   /* TODO: Use drmOpenControl here instead */
-  fd_.Set(open(path, O_RDWR));
+  fd_.Set(open(path, O_RDWR | O_CLOEXEC));
   if (fd() < 0) {
     ALOGE("Failed to open dri %s: %s", path, strerror(errno));
     return std::make_tuple(-ENODEV, 0);
@@ -145,6 +146,12 @@
   }
 #endif
 
+  drmSetMaster(fd());
+  if (!drmIsMaster(fd())) {
+    ALOGE("DRM/KMS master access required");
+    return std::make_tuple(-EACCES, 0);
+  }
+
   drmModeResPtr res = drmModeGetResources(fd());
   if (!res) {
     ALOGE("Failed to get DrmDevice resources");
@@ -189,7 +196,7 @@
     }
 
     std::vector<DrmCrtc *> possible_crtcs;
-    DrmCrtc *current_crtc = NULL;
+    DrmCrtc *current_crtc = nullptr;
     for (auto &crtc : crtcs_) {
       if ((1 << crtc->pipe()) & e->possible_crtcs)
         possible_crtcs.push_back(crtc.get());
@@ -221,7 +228,7 @@
     }
 
     std::vector<DrmEncoder *> possible_encoders;
-    DrmEncoder *current_encoder = NULL;
+    DrmEncoder *current_encoder = nullptr;
     for (int j = 0; j < c->count_encoders; ++j) {
       for (auto &encoder : encoders_) {
         if (encoder->id() == c->encoders[j])
@@ -344,22 +351,22 @@
 }
 
 DrmConnector *DrmDevice::GetConnectorForDisplay(int display) const {
-  for (auto &conn : connectors_) {
+  for (const auto &conn : connectors_) {
     if (conn->display() == display)
       return conn.get();
   }
-  return NULL;
+  return nullptr;
 }
 
 DrmConnector *DrmDevice::GetWritebackConnectorForDisplay(int display) const {
-  for (auto &conn : writeback_connectors_) {
+  for (const auto &conn : writeback_connectors_) {
     if (conn->display() == display)
       return conn.get();
   }
-  return NULL;
+  return nullptr;
 }
 
-// TODO what happens when hotplugging
+// TODO(nobody): what happens when hotplugging
 DrmConnector *DrmDevice::AvailableWritebackConnector(int display) const {
   DrmConnector *writeback_conn = GetWritebackConnectorForDisplay(display);
   DrmConnector *display_conn = GetConnectorForDisplay(display);
@@ -370,7 +377,7 @@
     return writeback_conn;
 
   // Use another CRTC if available and doesn't have any connector
-  for (auto &crtc : crtcs_) {
+  for (const auto &crtc : crtcs_) {
     if (crtc->display() == display)
       continue;
     display_conn = GetConnectorForDisplay(crtc->display());
@@ -381,23 +388,23 @@
     if (writeback_conn)
       return writeback_conn;
   }
-  return NULL;
+  return nullptr;
 }
 
 DrmCrtc *DrmDevice::GetCrtcForDisplay(int display) const {
-  for (auto &crtc : crtcs_) {
+  for (const auto &crtc : crtcs_) {
     if (crtc->display() == display)
       return crtc.get();
   }
-  return NULL;
+  return nullptr;
 }
 
 DrmPlane *DrmDevice::GetPlane(uint32_t id) const {
-  for (auto &plane : planes_) {
+  for (const auto &plane : planes_) {
     if (plane->id() == id)
       return plane.get();
   }
-  return NULL;
+  return nullptr;
 }
 
 const std::vector<std::unique_ptr<DrmCrtc>> &DrmDevice::crtcs() const {
@@ -441,7 +448,9 @@
     int ret = TryEncoderForDisplay(display, connector->encoder());
     if (!ret) {
       return 0;
-    } else if (ret != -EAGAIN) {
+    }
+
+    if (ret != -EAGAIN) {
       ALOGE("Could not set mode %d/%d", display, ret);
       return ret;
     }
@@ -452,7 +461,9 @@
     if (!ret) {
       connector->set_encoder(enc);
       return 0;
-    } else if (ret != -EAGAIN) {
+    }
+
+    if (ret != -EAGAIN) {
       ALOGE("Could not set mode %d/%d", display, ret);
       return ret;
     }
@@ -465,7 +476,7 @@
 // Attach writeback connector to the CRTC linked to the display_conn
 int DrmDevice::AttachWriteback(DrmConnector *display_conn) {
   DrmCrtc *display_crtc = display_conn->encoder()->crtc();
-  if (GetWritebackConnectorForDisplay(display_crtc->display()) != NULL) {
+  if (GetWritebackConnectorForDisplay(display_crtc->display()) != nullptr) {
     ALOGE("Display already has writeback attach to it");
     return -EINVAL;
   }
@@ -491,9 +502,8 @@
 }
 
 int DrmDevice::CreatePropertyBlob(void *data, size_t length,
-                                  uint32_t *blob_id) {
-  struct drm_mode_create_blob create_blob;
-  memset(&create_blob, 0, sizeof(create_blob));
+                                  uint32_t *blob_id) const {
+  struct drm_mode_create_blob create_blob {};
   create_blob.length = length;
   create_blob.data = (__u64)data;
 
@@ -506,12 +516,11 @@
   return 0;
 }
 
-int DrmDevice::DestroyPropertyBlob(uint32_t blob_id) {
+int DrmDevice::DestroyPropertyBlob(uint32_t blob_id) const {
   if (!blob_id)
     return 0;
 
-  struct drm_mode_destroy_blob destroy_blob;
-  memset(&destroy_blob, 0, sizeof(destroy_blob));
+  struct drm_mode_destroy_blob destroy_blob {};
   destroy_blob.blob_id = (__u32)blob_id;
   int ret = drmIoctl(fd(), DRM_IOCTL_MODE_DESTROYPROPBLOB, &destroy_blob);
   if (ret) {
@@ -526,8 +535,8 @@
 }
 
 int DrmDevice::GetProperty(uint32_t obj_id, uint32_t obj_type,
-                           const char *prop_name, DrmProperty *property) {
-  drmModeObjectPropertiesPtr props;
+                           const char *prop_name, DrmProperty *property) const {
+  drmModeObjectPropertiesPtr props = nullptr;
 
   props = drmModeObjectGetProperties(fd(), obj_id, obj_type);
   if (!props) {
@@ -566,8 +575,8 @@
                      property);
 }
 
-const std::string DrmDevice::GetName() const {
-  auto ver = drmGetVersion(fd_.get());
+std::string DrmDevice::GetName() const {
+  auto *ver = drmGetVersion(fd_.get());
   if (!ver) {
     ALOGW("Failed to get drm version for fd=%d", fd_.get());
     return "generic";
diff --git a/drm/DrmDevice.h b/drm/DrmDevice.h
index be68aa6..d8f347f 100644
--- a/drm/DrmDevice.h
+++ b/drm/DrmDevice.h
@@ -71,13 +71,13 @@
   int GetConnectorProperty(const DrmConnector &connector, const char *prop_name,
                            DrmProperty *property);
 
-  const std::string GetName() const;
+  std::string GetName() const;
 
   const std::vector<std::unique_ptr<DrmCrtc>> &crtcs() const;
   uint32_t next_mode_id();
 
-  int CreatePropertyBlob(void *data, size_t length, uint32_t *blob_id);
-  int DestroyPropertyBlob(uint32_t blob_id);
+  int CreatePropertyBlob(void *data, size_t length, uint32_t *blob_id) const;
+  int DestroyPropertyBlob(uint32_t blob_id) const;
   bool HandlesDisplay(int display) const;
   void RegisterHotplugHandler(DrmEventHandler *handler) {
     event_listener_.RegisterHotplugHandler(handler);
@@ -86,7 +86,7 @@
  private:
   int TryEncoderForDisplay(int display, DrmEncoder *enc);
   int GetProperty(uint32_t obj_id, uint32_t obj_type, const char *prop_name,
-                  DrmProperty *property);
+                  DrmProperty *property) const;
 
   int CreateDisplayPipe(DrmConnector *connector);
   int AttachWriteback(DrmConnector *display_conn);
diff --git a/drm/DrmEncoder.cpp b/drm/DrmEncoder.cpp
index bcf0926..ad05f88 100644
--- a/drm/DrmEncoder.cpp
+++ b/drm/DrmEncoder.cpp
@@ -16,19 +16,20 @@
 
 #include "DrmEncoder.h"
 
-#include <stdint.h>
 #include <xf86drmMode.h>
 
+#include <cstdint>
+
 #include "DrmDevice.h"
 
 namespace android {
 
 DrmEncoder::DrmEncoder(drmModeEncoderPtr e, DrmCrtc *current_crtc,
-                       const std::vector<DrmCrtc *> &possible_crtcs)
+                       std::vector<DrmCrtc *> possible_crtcs)
     : id_(e->encoder_id),
       crtc_(current_crtc),
       display_(-1),
-      possible_crtcs_(possible_crtcs) {
+      possible_crtcs_(std::move(possible_crtcs)) {
 }
 
 uint32_t DrmEncoder::id() const {
@@ -39,8 +40,8 @@
   return crtc_;
 }
 
-bool DrmEncoder::CanClone(DrmEncoder *possible_clone) {
-  return possible_clones_.find(possible_clone) != possible_clones_.end();
+bool DrmEncoder::CanClone(DrmEncoder *encoder) {
+  return possible_clones_.find(encoder) != possible_clones_.end();
 }
 
 void DrmEncoder::AddPossibleClone(DrmEncoder *possible_clone) {
diff --git a/drm/DrmEncoder.h b/drm/DrmEncoder.h
index f4464d0..4c01bc1 100644
--- a/drm/DrmEncoder.h
+++ b/drm/DrmEncoder.h
@@ -30,7 +30,7 @@
 class DrmEncoder {
  public:
   DrmEncoder(drmModeEncoderPtr e, DrmCrtc *current_crtc,
-             const std::vector<DrmCrtc *> &possible_crtcs);
+             std::vector<DrmCrtc *> possible_crtcs);
   DrmEncoder(const DrmEncoder &) = delete;
   DrmEncoder &operator=(const DrmEncoder &) = delete;
 
diff --git a/drm/DrmEventListener.cpp b/drm/DrmEventListener.cpp
index 3d95e28..a6eee47 100644
--- a/drm/DrmEventListener.cpp
+++ b/drm/DrmEventListener.cpp
@@ -18,16 +18,19 @@
 
 #include "DrmEventListener.h"
 
-#include <assert.h>
-#include <errno.h>
-#include <hardware/hardware.h>
-#include <hardware/hwcomposer.h>
 #include <linux/netlink.h>
-#include <log/log.h>
 #include <sys/socket.h>
 #include <xf86drm.h>
 
+#include <cassert>
+#include <cerrno>
+#include <cstring>
+
 #include "DrmDevice.h"
+#include "utils/log.h"
+
+/* Originally defined in system/core/libsystem/include/system/graphics.h */
+#define HAL_PRIORITY_URGENT_DISPLAY (-8)
 
 namespace android {
 
@@ -36,14 +39,14 @@
 }
 
 int DrmEventListener::Init() {
-  uevent_fd_.Set(socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT));
+  uevent_fd_.Set(
+      socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT));
   if (uevent_fd_.get() < 0) {
     ALOGE("Failed to open uevent socket: %s", strerror(errno));
     return uevent_fd_.get();
   }
 
-  struct sockaddr_nl addr;
-  memset(&addr, 0, sizeof(addr));
+  struct sockaddr_nl addr {};
   addr.nl_family = AF_NETLINK;
   addr.nl_pid = 0;
   addr.nl_groups = 0xFFFFFFFF;
@@ -54,6 +57,7 @@
     return -errno;
   }
 
+  // NOLINTNEXTLINE(readability-isolate-declaration)
   FD_ZERO(&fds_);
   FD_SET(drm_->fd(), &fds_);
   FD_SET(uevent_fd_.get(), &fds_);
@@ -70,19 +74,20 @@
 void DrmEventListener::FlipHandler(int /* fd */, unsigned int /* sequence */,
                                    unsigned int tv_sec, unsigned int tv_usec,
                                    void *user_data) {
-  DrmEventHandler *handler = (DrmEventHandler *)user_data;
+  auto *handler = (DrmEventHandler *)user_data;
   if (!handler)
     return;
 
   handler->HandleEvent((uint64_t)tv_sec * 1000 * 1000 + tv_usec);
-  delete handler;
+  delete handler;  // NOLINT(cppcoreguidelines-owning-memory)
 }
 
 void DrmEventListener::UEventHandler() {
   char buffer[1024];
-  int ret;
+  int ret = 0;
 
-  struct timespec ts;
+  struct timespec ts {};
+
   uint64_t timestamp = 0;
   ret = clock_gettime(CLOCK_MONOTONIC, &ts);
   if (!ret)
@@ -92,9 +97,10 @@
 
   while (true) {
     ret = read(uevent_fd_.get(), &buffer, sizeof(buffer));
-    if (ret == 0) {
+    if (ret == 0)
       return;
-    } else if (ret < 0) {
+
+    if (ret < 0) {
       ALOGE("Got error reading uevent %d", ret);
       return;
     }
@@ -102,12 +108,13 @@
     if (!hotplug_handler_)
       continue;
 
-    bool drm_event = false, hotplug_event = false;
-    for (int i = 0; i < ret;) {
+    bool drm_event = false;
+    bool hotplug_event = false;
+    for (uint32_t i = 0; i < ret;) {
       char *event = buffer + i;
-      if (strcmp(event, "DEVTYPE=drm_minor"))
+      if (strcmp(event, "DEVTYPE=drm_minor") != 0)
         drm_event = true;
-      else if (strcmp(event, "HOTPLUG=1"))
+      else if (strcmp(event, "HOTPLUG=1") != 0)
         hotplug_event = true;
 
       i += strlen(event) + 1;
@@ -119,15 +126,15 @@
 }
 
 void DrmEventListener::Routine() {
-  int ret;
+  int ret = 0;
   do {
-    ret = select(max_fd_ + 1, &fds_, NULL, NULL, NULL);
+    ret = select(max_fd_ + 1, &fds_, nullptr, nullptr, nullptr);
   } while (ret == -1 && errno == EINTR);
 
   if (FD_ISSET(drm_->fd(), &fds_)) {
     drmEventContext event_context =
         {.version = 2,
-         .vblank_handler = NULL,
+         .vblank_handler = nullptr,
          .page_flip_handler = DrmEventListener::FlipHandler};
     drmHandleEvent(drm_->fd(), &event_context);
   }
diff --git a/drm/DrmEventListener.h b/drm/DrmEventListener.h
index 9f9a4ba..c880a8c 100644
--- a/drm/DrmEventListener.h
+++ b/drm/DrmEventListener.h
@@ -53,7 +53,7 @@
  private:
   void UEventHandler();
 
-  fd_set fds_;
+  fd_set fds_{};
   UniqueFd uevent_fd_;
   int max_fd_ = -1;
 
diff --git a/drm/DrmGenericImporter.cpp b/drm/DrmGenericImporter.cpp
index 8ab4fe5..0cbe601 100644
--- a/drm/DrmGenericImporter.cpp
+++ b/drm/DrmGenericImporter.cpp
@@ -18,14 +18,16 @@
 
 #include "DrmGenericImporter.h"
 
-#include <cutils/properties.h>
 #include <gralloc_handle.h>
 #include <hardware/gralloc.h>
-#include <inttypes.h>
-#include <log/log.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
+#include <cinttypes>
+
+#include "utils/log.h"
+#include "utils/properties.h"
+
 namespace android {
 
 DrmGenericImporter::DrmGenericImporter(DrmDevice *drm) : drm_(drm) {
@@ -34,38 +36,37 @@
     ALOGE("drmGetCap failed. Fallback to no modifier support.");
     cap_value = 0;
   }
-  has_modifier_support_ = cap_value;
-}
-
-DrmGenericImporter::~DrmGenericImporter() {
+  has_modifier_support_ = cap_value != 0;
 }
 
 int DrmGenericImporter::ImportBuffer(hwc_drm_bo_t *bo) {
-  int ret = drmPrimeFDToHandle(drm_->fd(), bo->prime_fds[0],
-                               &bo->gem_handles[0]);
-  if (ret) {
-    ALOGE("failed to import prime fd %d ret=%d", bo->prime_fds[0], ret);
-    return ret;
-  }
+  int ret = 0;
 
-  for (int i = 1; i < HWC_DRM_BO_MAX_PLANES; i++) {
-    int fd = bo->prime_fds[i];
-    if (fd != 0) {
-      if (fd != bo->prime_fds[0]) {
-        ALOGE("Multiplanar FBs are not supported by this version of composer");
-        return -ENOTSUP;
+  for (int i = 0; i < HWC_DRM_BO_MAX_PLANES; i++) {
+    if (bo->prime_fds[i] > 0) {
+      if (i == 0 || bo->prime_fds[i] != bo->prime_fds[0]) {
+        ret = drmPrimeFDToHandle(drm_->fd(), bo->prime_fds[i],
+                                 &bo->gem_handles[i]);
+        if (ret) {
+          ALOGE("failed to import prime fd %d ret=%d", bo->prime_fds[i], ret);
+          return ret;
+        }
+      } else {
+        bo->gem_handles[i] = bo->gem_handles[0];
       }
-      bo->gem_handles[i] = bo->gem_handles[0];
     }
   }
 
-  if (!has_modifier_support_ && bo->modifiers[0]) {
+  bool has_modifiers = bo->modifiers[0] != DRM_FORMAT_MOD_NONE &&
+                       bo->modifiers[0] != DRM_FORMAT_MOD_INVALID;
+
+  if (!has_modifier_support_ && has_modifiers) {
     ALOGE("No ADDFB2 with modifier support. Can't import modifier %" PRIu64,
           bo->modifiers[0]);
     return -EINVAL;
   }
 
-  if (!bo->with_modifiers)
+  if (!has_modifiers)
     ret = drmModeAddFB2(drm_->fd(), bo->width, bo->height, bo->format,
                         bo->gem_handles, bo->pitches, bo->offsets, &bo->fb_id,
                         0);
@@ -73,15 +74,19 @@
     ret = drmModeAddFB2WithModifiers(drm_->fd(), bo->width, bo->height,
                                      bo->format, bo->gem_handles, bo->pitches,
                                      bo->offsets, bo->modifiers, &bo->fb_id,
-                                     bo->modifiers[0] ? DRM_MODE_FB_MODIFIERS
-                                                      : 0);
+                                     DRM_MODE_FB_MODIFIERS);
 
   if (ret) {
     ALOGE("could not create drm fb %d", ret);
     return ret;
   }
 
-  ImportHandle(bo->gem_handles[0]);
+  for (unsigned int gem_handle : bo->gem_handles) {
+    if (!gem_handle)
+      continue;
+
+    ImportHandle(gem_handle);
+  }
 
   return ret;
 }
@@ -91,18 +96,14 @@
     if (drmModeRmFB(drm_->fd(), bo->fb_id))
       ALOGE("Failed to rm fb");
 
-  for (int i = 0; i < HWC_DRM_BO_MAX_PLANES; i++) {
-    if (!bo->gem_handles[i])
+  for (unsigned int &gem_handle : bo->gem_handles) {
+    if (!gem_handle)
       continue;
 
-    if (ReleaseHandle(bo->gem_handles[i])) {
-      ALOGE("Failed to release gem handle %d", bo->gem_handles[i]);
-    } else {
-      for (int j = i + 1; j < HWC_DRM_BO_MAX_PLANES; j++)
-        if (bo->gem_handles[j] == bo->gem_handles[i])
-          bo->gem_handles[j] = 0;
-      bo->gem_handles[i] = 0;
-    }
+    if (ReleaseHandle(gem_handle))
+      ALOGE("Failed to release gem handle %d", gem_handle);
+    else
+      gem_handle = 0;
   }
   return 0;
 }
@@ -123,10 +124,7 @@
 }
 
 int DrmGenericImporter::CloseHandle(uint32_t gem_handle) {
-  struct drm_gem_close gem_close;
-
-  memset(&gem_close, 0, sizeof(gem_close));
-
+  struct drm_gem_close gem_close {};
   gem_close.handle = gem_handle;
   int ret = drmIoctl(drm_->fd(), DRM_IOCTL_GEM_CLOSE, &gem_close);
   if (ret)
diff --git a/drm/DrmGenericImporter.h b/drm/DrmGenericImporter.h
index ca53762..27cfc3b 100644
--- a/drm/DrmGenericImporter.h
+++ b/drm/DrmGenericImporter.h
@@ -33,8 +33,7 @@
 
 class Importer {
  public:
-  virtual ~Importer() {
-  }
+  virtual ~Importer() = default;
 
   // Imports the buffer referred to by handle into bo.
   //
@@ -52,7 +51,7 @@
 class DrmGenericImporter : public Importer {
  public:
   DrmGenericImporter(DrmDevice *drm);
-  ~DrmGenericImporter() override;
+  ~DrmGenericImporter() override = default;
 
   int ImportBuffer(hwc_drm_bo_t *bo) override;
   int ReleaseBuffer(hwc_drm_bo_t *bo) override;
diff --git a/drm/DrmMode.cpp b/drm/DrmMode.cpp
index 6de671a..dd25758 100644
--- a/drm/DrmMode.cpp
+++ b/drm/DrmMode.cpp
@@ -16,13 +16,14 @@
 
 #include "DrmMode.h"
 
+#include <cstring>
+
 #include "DrmDevice.h"
 
 namespace android {
 
 DrmMode::DrmMode(drmModeModeInfoPtr m)
-    : id_(0),
-      clock_(m->clock),
+    : clock_(m->clock),
       h_display_(m->hdisplay),
       h_sync_start_(m->hsync_start),
       h_sync_end_(m->hsync_end),
@@ -120,7 +121,7 @@
 
 float DrmMode::v_refresh() const {
   // Always recalculate refresh to report correct float rate
-  return clock_ / (float)(v_total_ * h_total_) * 1000.0f;
+  return clock_ / (float)(v_total_ * h_total_) * 1000.0F;
 }
 
 uint32_t DrmMode::flags() const {
diff --git a/drm/DrmPlane.cpp b/drm/DrmPlane.cpp
index f994252..5443e7e 100644
--- a/drm/DrmPlane.cpp
+++ b/drm/DrmPlane.cpp
@@ -18,13 +18,14 @@
 
 #include "DrmPlane.h"
 
-#include <errno.h>
-#include <log/log.h>
-#include <stdint.h>
-
+#include <algorithm>
+#include <cerrno>
 #include <cinttypes>
+#include <cstdint>
 
 #include "DrmDevice.h"
+#include "bufferinfo/BufferInfoGetter.h"
+#include "utils/log.h"
 
 namespace android {
 
@@ -44,7 +45,7 @@
     return ret;
   }
 
-  uint64_t type;
+  uint64_t type = 0;
   std::tie(ret, type) = p.value();
   if (ret) {
     ALOGE("Failed to get plane type property value");
@@ -141,6 +142,17 @@
   if (ret)
     ALOGI("Could not get IN_FENCE_FD property");
 
+  if (HasNonRgbFormat()) {
+    ret = drm_->GetPlaneProperty(*this, "COLOR_ENCODING",
+                                 &color_encoding_propery_);
+    if (ret)
+      ALOGI("Could not get COLOR_ENCODING property");
+
+    ret = drm_->GetPlaneProperty(*this, "COLOR_RANGE", &color_range_property_);
+    if (ret)
+      ALOGI("Could not get COLOR_RANGE property");
+  }
+
   return 0;
 }
 
@@ -149,7 +161,84 @@
 }
 
 bool DrmPlane::GetCrtcSupported(const DrmCrtc &crtc) const {
-  return !!((1 << crtc.pipe()) & possible_crtc_mask_);
+  return ((1 << crtc.pipe()) & possible_crtc_mask_) != 0;
+}
+
+bool DrmPlane::IsValidForLayer(DrmHwcLayer *layer) {
+  if (rotation_property_.id() == 0) {
+    if (layer->transform != DrmHwcTransform::kIdentity) {
+      ALOGV("Rotation is not supported on plane %d", id_);
+      return false;
+    }
+  } else {
+    // For rotation checks, we assume the hardware reports its capabilities
+    // consistently (e.g. a 270 degree rotation is a 90 degree rotation + H
+    // flip + V flip; it wouldn't make sense to support all of the latter but
+    // not the former).
+    int ret = 0;
+    const std::pair<enum DrmHwcTransform, std::string> transforms[] =
+        {{kFlipH, "reflect-x"},
+         {kFlipV, "reflect-y"},
+         {kRotate90, "rotate-90"},
+         {kRotate180, "rotate-180"},
+         {kRotate270, "rotate-270"}};
+
+    for (const auto &[transform, name] : transforms) {
+      if (layer->transform & transform) {
+        std::tie(std::ignore,
+                 ret) = rotation_property_.GetEnumValueWithName(name);
+        if (ret) {
+          ALOGV("Rotation '%s' is not supported on plane %d", name.c_str(),
+                id_);
+          return false;
+        }
+      }
+    }
+  }
+
+  if (alpha_property_.id() == 0 && layer->alpha != 0xffff) {
+    ALOGV("Alpha is not supported on plane %d", id_);
+    return false;
+  }
+
+  if (blend_property_.id() == 0) {
+    if ((layer->blending != DrmHwcBlending::kNone) &&
+        (layer->blending != DrmHwcBlending::kPreMult)) {
+      ALOGV("Blending is not supported on plane %d", id_);
+      return false;
+    }
+  } else {
+    int ret = 0;
+
+    switch (layer->blending) {
+      case DrmHwcBlending::kPreMult:
+        std::tie(std::ignore,
+                 ret) = blend_property_.GetEnumValueWithName("Pre-multiplied");
+        break;
+      case DrmHwcBlending::kCoverage:
+        std::tie(std::ignore,
+                 ret) = blend_property_.GetEnumValueWithName("Coverage");
+        break;
+      case DrmHwcBlending::kNone:
+      default:
+        std::tie(std::ignore,
+                 ret) = blend_property_.GetEnumValueWithName("None");
+        break;
+    }
+    if (ret) {
+      ALOGV("Expected a valid blend mode on plane %d", id_);
+      return false;
+    }
+  }
+
+  uint32_t format = layer->buffer->format;
+  if (!IsFormatSupported(format)) {
+    ALOGV("Plane %d does not supports %c%c%c%c format", id_, format,
+          format >> 8, format >> 16, format >> 24);
+    return false;
+  }
+
+  return true;
 }
 
 uint32_t DrmPlane::type() const {
@@ -161,6 +250,13 @@
          std::end(formats_);
 }
 
+bool DrmPlane::HasNonRgbFormat() const {
+  return std::find_if_not(std::begin(formats_), std::end(formats_),
+                          [](uint32_t format) {
+                            return BufferInfoGetter::IsDrmFormatRgb(format);
+                          }) != std::end(formats_);
+}
+
 const DrmProperty &DrmPlane::crtc_property() const {
   return crtc_property_;
 }
@@ -220,4 +316,12 @@
 const DrmProperty &DrmPlane::in_fence_fd_property() const {
   return in_fence_fd_property_;
 }
+
+const DrmProperty &DrmPlane::color_encoding_propery() const {
+  return color_encoding_propery_;
+}
+
+const DrmProperty &DrmPlane::color_range_property() const {
+  return color_range_property_;
+}
 }  // namespace android
diff --git a/drm/DrmPlane.h b/drm/DrmPlane.h
index 16731a8..862a0f3 100644
--- a/drm/DrmPlane.h
+++ b/drm/DrmPlane.h
@@ -24,6 +24,7 @@
 
 #include "DrmCrtc.h"
 #include "DrmProperty.h"
+#include "drmhwcomposer.h"
 
 namespace android {
 
@@ -40,10 +41,12 @@
   uint32_t id() const;
 
   bool GetCrtcSupported(const DrmCrtc &crtc) const;
+  bool IsValidForLayer(DrmHwcLayer *layer);
 
   uint32_t type() const;
 
   bool IsFormatSupported(uint32_t format) const;
+  bool HasNonRgbFormat() const;
 
   const DrmProperty &crtc_property() const;
   const DrmProperty &fb_property() const;
@@ -60,6 +63,8 @@
   const DrmProperty &alpha_property() const;
   const DrmProperty &blend_property() const;
   const DrmProperty &in_fence_fd_property() const;
+  const DrmProperty &color_encoding_propery() const;
+  const DrmProperty &color_range_property() const;
 
  private:
   DrmDevice *drm_;
@@ -67,7 +72,7 @@
 
   uint32_t possible_crtc_mask_;
 
-  uint32_t type_;
+  uint32_t type_{};
 
   std::vector<uint32_t> formats_;
 
@@ -86,6 +91,8 @@
   DrmProperty alpha_property_;
   DrmProperty blend_property_;
   DrmProperty in_fence_fd_property_;
+  DrmProperty color_encoding_propery_;
+  DrmProperty color_range_property_;
 };
 }  // namespace android
 
diff --git a/drm/DrmProperty.cpp b/drm/DrmProperty.cpp
index b60a76e..8e6f7e5 100644
--- a/drm/DrmProperty.cpp
+++ b/drm/DrmProperty.cpp
@@ -16,10 +16,10 @@
 
 #include "DrmProperty.h"
 
-#include <errno.h>
-#include <stdint.h>
 #include <xf86drmMode.h>
 
+#include <cerrno>
+#include <cstdint>
 #include <string>
 
 #include "DrmDevice.h"
@@ -30,11 +30,7 @@
     : value_(e->value), name_(e->name) {
 }
 
-DrmProperty::DrmPropertyEnum::~DrmPropertyEnum() {
-}
-
-DrmProperty::DrmProperty(drmModePropertyPtr p, uint64_t value)
-    : id_(0), type_(DRM_PROPERTY_TYPE_INVALID), flags_(0), name_("") {
+DrmProperty::DrmProperty(drmModePropertyPtr p, uint64_t value) {
   Init(p, value);
 }
 
@@ -45,13 +41,13 @@
   value_ = value;
 
   for (int i = 0; i < p->count_values; ++i)
-    values_.push_back(p->values[i]);
+    values_.emplace_back(p->values[i]);
 
   for (int i = 0; i < p->count_enums; ++i)
-    enums_.push_back(DrmPropertyEnum(&p->enums[i]));
+    enums_.emplace_back(DrmPropertyEnum(&p->enums[i]));
 
   for (int i = 0; i < p->count_blobs; ++i)
-    blob_ids_.push_back(p->blob_ids[i]);
+    blob_ids_.emplace_back(p->blob_ids[i]);
 
   if (flags_ & DRM_MODE_PROP_RANGE)
     type_ = DRM_PROPERTY_TYPE_INT;
@@ -61,6 +57,8 @@
     type_ = DRM_PROPERTY_TYPE_OBJECT;
   else if (flags_ & DRM_MODE_PROP_BLOB)
     type_ = DRM_PROPERTY_TYPE_BLOB;
+  else if (flags_ & DRM_MODE_PROP_BITMASK)
+    type_ = DRM_PROPERTY_TYPE_BITMASK;
 }
 
 uint32_t DrmProperty::id() const {
@@ -75,7 +73,7 @@
   if (type_ == DRM_PROPERTY_TYPE_BLOB)
     return std::make_tuple(0, value_);
 
-  if (values_.size() == 0)
+  if (values_.empty())
     return std::make_tuple(-ENOENT, 0);
 
   switch (type_) {
@@ -91,6 +89,7 @@
     case DRM_PROPERTY_TYPE_OBJECT:
       return std::make_tuple(0, value_);
 
+    case DRM_PROPERTY_TYPE_BITMASK:
     default:
       return std::make_tuple(-EINVAL, 0);
   }
@@ -107,7 +106,7 @@
 std::tuple<int, uint64_t> DrmProperty::range_min() const {
   if (!is_range())
     return std::make_tuple(-EINVAL, 0);
-  if (values_.size() < 1)
+  if (values_.empty())
     return std::make_tuple(-ENOENT, 0);
 
   return std::make_tuple(0, values_[0]);
@@ -123,9 +122,9 @@
 }
 
 std::tuple<uint64_t, int> DrmProperty::GetEnumValueWithName(
-    std::string name) const {
-  for (auto it : enums_) {
-    if (it.name_.compare(name) == 0) {
+    const std::string &name) const {
+  for (const auto &it : enums_) {
+    if (it.name_ == name) {
       return std::make_tuple(it.value_, 0);
     }
   }
diff --git a/drm/DrmProperty.h b/drm/DrmProperty.h
index d293da3..70678fd 100644
--- a/drm/DrmProperty.h
+++ b/drm/DrmProperty.h
@@ -30,6 +30,7 @@
   DRM_PROPERTY_TYPE_ENUM,
   DRM_PROPERTY_TYPE_OBJECT,
   DRM_PROPERTY_TYPE_BLOB,
+  DRM_PROPERTY_TYPE_BITMASK,
   DRM_PROPERTY_TYPE_INVALID,
 };
 
@@ -41,7 +42,7 @@
   DrmProperty &operator=(const DrmProperty &) = delete;
 
   void Init(drmModePropertyPtr p, uint64_t value);
-  std::tuple<uint64_t, int> GetEnumValueWithName(std::string name) const;
+  std::tuple<uint64_t, int> GetEnumValueWithName(const std::string &name) const;
 
   uint32_t id() const;
   std::string name() const;
@@ -57,7 +58,7 @@
   class DrmPropertyEnum {
    public:
     DrmPropertyEnum(drm_mode_property_enum *e);
-    ~DrmPropertyEnum();
+    ~DrmPropertyEnum() = default;
 
     uint64_t value_;
     std::string name_;
diff --git a/drm/ResourceManager.cpp b/drm/ResourceManager.cpp
index fc24aea..f8e9cab 100644
--- a/drm/ResourceManager.cpp
+++ b/drm/ResourceManager.cpp
@@ -18,17 +18,18 @@
 
 #include "ResourceManager.h"
 
-#include <cutils/properties.h>
-#include <log/log.h>
+#include <fcntl.h>
 #include <sys/stat.h>
 
 #include <sstream>
 
 #include "bufferinfo/BufferInfoGetter.h"
+#include "utils/log.h"
+#include "utils/properties.h"
 
 namespace android {
 
-ResourceManager::ResourceManager() : num_displays_(0), gralloc_(NULL) {
+ResourceManager::ResourceManager() : num_displays_(0), gralloc_(nullptr) {
 }
 
 int ResourceManager::Init() {
@@ -46,12 +47,12 @@
       std::ostringstream path;
       path << path_pattern << idx;
 
-      struct stat buf;
-      if (stat(path.str().c_str(), &buf)) {
+      struct stat buf {};
+      if (stat(path.str().c_str(), &buf))
         break;
-      } else if (IsKMSDev(path.str().c_str())) {
+
+      if (IsKMSDev(path.str().c_str()))
         ret = AddDrmDevice(path.str());
-      }
     }
   }
 
@@ -73,14 +74,15 @@
                        (const hw_module_t **)&gralloc_);
 }
 
-int ResourceManager::AddDrmDevice(std::string path) {
+int ResourceManager::AddDrmDevice(std::string const &path) {
   std::unique_ptr<DrmDevice> drm = std::make_unique<DrmDevice>();
-  int displays_added, ret;
+  int displays_added = 0;
+  int ret = 0;
   std::tie(ret, displays_added) = drm->Init(path.c_str(), num_displays_);
   if (ret)
     return ret;
   std::shared_ptr<Importer> importer;
-  importer.reset(new DrmGenericImporter(drm.get()));
+  importer = std::make_shared<DrmGenericImporter>(drm.get());
   if (!importer) {
     ALOGE("Failed to create importer instance");
     return -ENODEV;
@@ -93,7 +95,7 @@
 
 DrmConnector *ResourceManager::AvailableWritebackConnector(int display) {
   DrmDevice *drm_device = GetDrmDevice(display);
-  DrmConnector *writeback_conn = NULL;
+  DrmConnector *writeback_conn = nullptr;
   if (drm_device) {
     writeback_conn = drm_device->AvailableWritebackConnector(display);
     if (writeback_conn)
@@ -114,7 +116,7 @@
   if (fd < 0)
     return false;
 
-  auto res = drmModeGetResources(fd);
+  auto *res = drmModeGetResources(fd);
   if (!res) {
     close(fd);
     return false;
@@ -134,7 +136,7 @@
     if (drm->HandlesDisplay(display))
       return drm.get();
   }
-  return NULL;
+  return nullptr;
 }
 
 std::shared_ptr<Importer> ResourceManager::GetImporter(int display) {
@@ -142,7 +144,7 @@
     if (drms_[i]->HandlesDisplay(display))
       return importers_[i];
   }
-  return NULL;
+  return nullptr;
 }
 
 const gralloc_module_t *ResourceManager::gralloc() {
diff --git a/drm/ResourceManager.h b/drm/ResourceManager.h
index 7102cea..fca6e1f 100644
--- a/drm/ResourceManager.h
+++ b/drm/ResourceManager.h
@@ -45,7 +45,7 @@
   }
 
  private:
-  int AddDrmDevice(std::string path);
+  int AddDrmDevice(std::string const &path);
   static bool IsKMSDev(const char *path);
 
   int num_displays_;
@@ -53,7 +53,7 @@
   std::vector<std::shared_ptr<Importer>> importers_;
   const gralloc_module_t *gralloc_;
 
-  bool scale_with_gpu_;
+  bool scale_with_gpu_{};
 };
 }  // namespace android
 
diff --git a/drm/VSyncWorker.cpp b/drm/VSyncWorker.cpp
index b2f7e5f..25eeeab 100644
--- a/drm/VSyncWorker.cpp
+++ b/drm/VSyncWorker.cpp
@@ -18,25 +18,25 @@
 
 #include "VSyncWorker.h"
 
-#include <log/log.h>
-#include <stdlib.h>
-#include <time.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
+
+#include "utils/log.h"
+
 namespace android {
 
 VSyncWorker::VSyncWorker()
     : Worker("vsync", HAL_PRIORITY_URGENT_DISPLAY),
-      drm_(NULL),
+      drm_(nullptr),
       display_(-1),
       enabled_(false),
       last_timestamp_(-1) {
 }
 
-VSyncWorker::~VSyncWorker() {
-}
-
 int VSyncWorker::Init(DrmDevice *drm, int display) {
   drm_ = drm;
   display_ = display;
@@ -46,7 +46,7 @@
 
 void VSyncWorker::RegisterCallback(std::shared_ptr<VsyncCallback> callback) {
   Lock();
-  callback_ = callback;
+  callback_ = std::move(callback);
   Unlock();
 }
 
@@ -54,7 +54,7 @@
                                          hwc2_function_pointer_t hook) {
   Lock();
   vsync_callback_data_ = data;
-  vsync_callback_hook_ = reinterpret_cast<HWC2_PFN_VSYNC>(hook);
+  vsync_callback_hook_ = (HWC2_PFN_VSYNC)hook;
   Unlock();
 }
 
@@ -80,7 +80,7 @@
  *  Thus, we must sleep until timestamp 687 to maintain phase with the last
  *  timestamp.
  */
-int64_t VSyncWorker::GetPhasedVSync(int64_t frame_ns, int64_t current) {
+int64_t VSyncWorker::GetPhasedVSync(int64_t frame_ns, int64_t current) const {
   if (last_timestamp_ < 0)
     return current + frame_ns;
 
@@ -91,24 +91,26 @@
 static const int64_t kOneSecondNs = 1 * 1000 * 1000 * 1000;
 
 int VSyncWorker::SyntheticWaitVBlank(int64_t *timestamp) {
-  struct timespec vsync;
+  struct timespec vsync {};
   int ret = clock_gettime(CLOCK_MONOTONIC, &vsync);
+  if (ret)
+    return ret;
 
-  float refresh = 60.0f;  // Default to 60Hz refresh rate
+  float refresh = 60.0F;  // Default to 60Hz refresh rate
   DrmConnector *conn = drm_->GetConnectorForDisplay(display_);
-  if (conn && conn->active_mode().v_refresh() != 0.0f)
+  if (conn && conn->active_mode().v_refresh() != 0.0F)
     refresh = conn->active_mode().v_refresh();
   else
     ALOGW("Vsync worker active with conn=%p refresh=%f\n", conn,
-          conn ? conn->active_mode().v_refresh() : 0.0f);
+          conn ? conn->active_mode().v_refresh() : 0.0F);
 
   int64_t phased_timestamp = GetPhasedVSync(kOneSecondNs / refresh,
                                             vsync.tv_sec * kOneSecondNs +
                                                 vsync.tv_nsec);
   vsync.tv_sec = phased_timestamp / kOneSecondNs;
-  vsync.tv_nsec = phased_timestamp - (vsync.tv_sec * kOneSecondNs);
+  vsync.tv_nsec = int(phased_timestamp - (vsync.tv_sec * kOneSecondNs));
   do {
-    ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &vsync, NULL);
+    ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &vsync, nullptr);
   } while (ret == -1 && errno == EINTR);
   if (ret)
     return ret;
@@ -118,7 +120,7 @@
 }
 
 void VSyncWorker::Routine() {
-  int ret;
+  int ret = 0;
 
   Lock();
   if (!enabled_) {
@@ -146,11 +148,12 @@
       DRM_VBLANK_RELATIVE | (high_crtc & DRM_VBLANK_HIGH_CRTC_MASK));
   vblank.request.sequence = 1;
 
-  int64_t timestamp;
+  int64_t timestamp = 0;
   ret = drmWaitVBlank(drm_->fd(), &vblank);
-  if (ret == -EINTR) {
+  if (ret == -EINTR)
     return;
-  } else if (ret) {
+
+  if (ret) {
     ret = SyntheticWaitVBlank(&timestamp);
     if (ret)
       return;
diff --git a/drm/VSyncWorker.h b/drm/VSyncWorker.h
index 7454b51..b43918c 100644
--- a/drm/VSyncWorker.h
+++ b/drm/VSyncWorker.h
@@ -22,6 +22,7 @@
 #include <hardware/hwcomposer2.h>
 #include <stdint.h>
 
+#include <atomic>
 #include <map>
 
 #include "DrmDevice.h"
@@ -31,15 +32,14 @@
 
 class VsyncCallback {
  public:
-  virtual ~VsyncCallback() {
-  }
+  virtual ~VsyncCallback() = default;
   virtual void Callback(int display, int64_t timestamp) = 0;
 };
 
 class VSyncWorker : public Worker {
  public:
   VSyncWorker();
-  ~VSyncWorker() override;
+  ~VSyncWorker() override = default;
 
   int Init(DrmDevice *drm, int display);
   void RegisterCallback(std::shared_ptr<VsyncCallback> callback);
@@ -52,7 +52,7 @@
   void Routine() override;
 
  private:
-  int64_t GetPhasedVSync(int64_t frame_ns, int64_t current);
+  int64_t GetPhasedVSync(int64_t frame_ns, int64_t current) const;
   int SyntheticWaitVBlank(int64_t *timestamp);
 
   DrmDevice *drm_;
diff --git a/include/DrmFramebuffer.h b/include/DrmFramebuffer.h
deleted file mode 100644
index 33ca0db..0000000
--- a/include/DrmFramebuffer.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2015 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.
- */
-
-#ifndef ANDROID_DRM_FRAMEBUFFER_
-#define ANDROID_DRM_FRAMEBUFFER_
-
-#include <stdint.h>
-#include <sync/sync.h>
-#include <ui/GraphicBuffer.h>
-
-namespace android {
-
-struct DrmFramebuffer {
-  DrmFramebuffer() : release_fence_fd_(-1) {
-  }
-
-  ~DrmFramebuffer() {
-    if (release_fence_fd() >= 0)
-      close(release_fence_fd());
-  }
-
-  bool is_valid() {
-    return buffer_ != NULL;
-  }
-
-  sp<GraphicBuffer> buffer() {
-    return buffer_;
-  }
-
-  int release_fence_fd() {
-    return release_fence_fd_;
-  }
-
-  void set_release_fence_fd(int fd) {
-    if (release_fence_fd_ >= 0)
-      close(release_fence_fd_);
-    release_fence_fd_ = fd;
-  }
-
-  bool Allocate(uint32_t w, uint32_t h) {
-    if (is_valid()) {
-      if (buffer_->getWidth() == w && buffer_->getHeight() == h)
-        return true;
-
-      if (release_fence_fd_ >= 0) {
-        if (sync_wait(release_fence_fd_, kReleaseWaitTimeoutMs) != 0) {
-          ALOGE("Wait for release fence failed\n");
-          return false;
-        }
-      }
-      Clear();
-    }
-    buffer_ = new GraphicBuffer(w, h, PIXEL_FORMAT_RGB_888,
-                                GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_HW_RENDER |
-                                    GRALLOC_USAGE_HW_COMPOSER);
-    release_fence_fd_ = -1;
-    return is_valid();
-  }
-
-  void Clear() {
-    if (!is_valid())
-      return;
-
-    if (release_fence_fd_ >= 0) {
-      close(release_fence_fd_);
-      release_fence_fd_ = -1;
-    }
-
-    buffer_.clear();
-  }
-
-  int WaitReleased(int timeout_milliseconds) {
-    if (!is_valid())
-      return 0;
-    if (release_fence_fd_ < 0)
-      return 0;
-
-    int ret = sync_wait(release_fence_fd_, timeout_milliseconds);
-    return ret;
-  }
-
-  // Somewhat arbitrarily chosen, but wanted to stay below 3000ms, which is the
-  // system timeout
-  static const int kReleaseWaitTimeoutMs = 1500;
-
- private:
-  sp<GraphicBuffer> buffer_;
-  int release_fence_fd_;
-};
-}  // namespace android
-
-#endif  // ANDROID_DRM_FRAMEBUFFER_
diff --git a/include/drmhwcgralloc.h b/include/drmhwcgralloc.h
index fc0af64..05b2cf0 100644
--- a/include/drmhwcgralloc.h
+++ b/include/drmhwcgralloc.h
@@ -32,7 +32,6 @@
   uint32_t gem_handles[HWC_DRM_BO_MAX_PLANES];
   uint64_t modifiers[HWC_DRM_BO_MAX_PLANES];
   uint32_t fb_id;
-  bool with_modifiers;
   int acquire_fence_fd;
   void *priv;
 } hwc_drm_bo_t;
diff --git a/include/drmhwcomposer.h b/include/drmhwcomposer.h
index 0706ae5..a04cc29 100644
--- a/include/drmhwcomposer.h
+++ b/include/drmhwcomposer.h
@@ -136,6 +136,7 @@
   uint16_t alpha = 0xffff;
   hwc_frect_t source_crop;
   hwc_rect_t display_frame;
+  android_dataspace_t dataspace;
 
   UniqueFd acquire_fence;
   OutputFd release_fence;
@@ -144,8 +145,6 @@
   int InitFromDrmHwcLayer(DrmHwcLayer *layer, Importer *importer);
 
   void SetTransform(int32_t sf_transform);
-  void SetSourceCrop(hwc_frect_t const &crop);
-  void SetDisplayFrame(hwc_rect_t const &frame);
 
   buffer_handle_t get_usable_handle() const {
     return handle.get() != NULL ? handle.get() : sf_handle;
diff --git a/presubmit.sh b/presubmit.sh
new file mode 100755
index 0000000..249aaf5
--- /dev/null
+++ b/presubmit.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+
+set -e
+
+echo "Run native build:"
+
+./.ci/.gitlab-ci-clang-build.sh
+
+echo "Run style check:"
+
+./.ci/.gitlab-ci-checkcommit.sh
+
+echo "Run coarse clang-tidy check:"
+
+./.ci/.gitlab-ci-clang-tidy-coarse.sh
+
+echo "Run fine clang-tidy check:"
+
+./.ci/.gitlab-ci-clang-tidy-fine.sh
+
+echo -e "\n\e[32m --- SUCCESS ---"
diff --git a/tests/Android.bp b/tests/Android.bp
index 6ffb364..473c944 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -1,4 +1,23 @@
+cc_library_shared {
+    name: "hwcomposer.filegroups_build_test",
+    defaults: ["hwcomposer.drm_defaults"],
+    whole_static_libs: ["drm_hwcomposer"],
 
+    srcs: [
+        ":drm_hwcomposer_platformhisi",
+        ":drm_hwcomposer_platformimagination",
+        ":drm_hwcomposer_platformmediatek",
+        ":drm_hwcomposer_platformmeson",
+    ],
+
+    local_include_dirs: [
+        "test_include",
+    ],
+
+    cppflags: [
+        "-DDISABLE_LEGACY_GETTERS",
+    ],
+}
 
 package {
     // See: http://go/android-license-faq
@@ -19,7 +38,7 @@
     static_libs: ["libdrmhwc_utils"],
     shared_libs: ["hwcomposer.drm"],
     include_dirs: [
-        "external/drm_hwcomposer/include",
         "external/drm_hwcomposer",
+        "external/drm_hwcomposer/include",
     ],
 }
diff --git a/tests/test_include/cros_gralloc_handle.h b/tests/test_include/cros_gralloc_handle.h
new file mode 100644
index 0000000..d77d777
--- /dev/null
+++ b/tests/test_include/cros_gralloc_handle.h
@@ -0,0 +1,53 @@
+// clang-format off
+/*
+ * Copyright 2016 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#ifndef CROS_GRALLOC_HANDLE_H
+#define CROS_GRALLOC_HANDLE_H
+
+#include <cstdint>
+#include <cutils/native_handle.h>
+
+#define DRV_MAX_PLANES 4
+#define DRV_MAX_FDS (DRV_MAX_PLANES + 1)
+
+struct cros_gralloc_handle : public native_handle_t {
+	/*
+	 * File descriptors must immediately follow the native_handle_t base and used file
+	 * descriptors must be packed at the beginning of this array to work with
+	 * native_handle_clone().
+	 *
+	 * This field contains 'num_planes' plane file descriptors followed by an optional metadata
+	 * reserved region file descriptor if 'reserved_region_size' is greater than zero.
+	 */
+	int32_t fds[DRV_MAX_FDS];
+	uint32_t strides[DRV_MAX_PLANES];
+	uint32_t offsets[DRV_MAX_PLANES];
+	uint32_t sizes[DRV_MAX_PLANES];
+	uint32_t id;
+	uint32_t width;
+	uint32_t height;
+	uint32_t format; /* DRM format */
+	uint32_t tiling;
+	uint64_t format_modifier;
+	uint64_t use_flags; /* Buffer creation flags */
+	uint32_t magic;
+	uint32_t pixel_stride;
+	int32_t droid_format;
+	int32_t usage; /* Android usage. */
+	uint32_t num_planes;
+	uint64_t reserved_region_size;
+	uint64_t total_size; /* Total allocation size */
+	/*
+	 * Name is a null terminated char array located at handle->base.data[handle->name_offset].
+	 */
+	uint32_t name_offset;
+} __attribute__((packed));
+
+typedef const struct cros_gralloc_handle *cros_gralloc_handle_t;
+
+#endif
+// clang-format on
diff --git a/tests/test_include/gralloc_helper.h b/tests/test_include/gralloc_helper.h
new file mode 100644
index 0000000..b6cd24d
--- /dev/null
+++ b/tests/test_include/gralloc_helper.h
@@ -0,0 +1,54 @@
+// clang-format off
+/*
+ * Copyright (C) 2010-2017 ARM Limited. All rights reserved.
+ *
+ * Copyright (C) 2008 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.
+ */
+
+#ifndef GRALLOC_HELPER_H_
+#define GRALLOC_HELPER_H_
+
+#include <sys/mman.h>
+#include <sys/user.h>
+#include "utils/log.h"
+
+#ifndef AWAR
+#define AWAR(fmt, args...) \
+	__android_log_print(ANDROID_LOG_WARN, "[Gralloc-Warning]", "%s:%d " fmt, __func__, __LINE__, ##args)
+#endif
+#ifndef AINF
+#define AINF(fmt, args...) __android_log_print(ANDROID_LOG_INFO, "[Gralloc]", fmt, ##args)
+#endif
+#ifndef AERR
+#define AERR(fmt, args...) \
+	__android_log_print(ANDROID_LOG_ERROR, "[Gralloc-ERROR]", "%s:%d " fmt, __func__, __LINE__, ##args)
+#endif
+#ifndef AERR_IF
+#define AERR_IF(eq, fmt, args...) \
+	if ((eq))                     \
+	AERR(fmt, args)
+#endif
+
+#define GRALLOC_ALIGN(value, base) (((value) + ((base)-1)) & ~((base)-1))
+
+#define GRALLOC_UNUSED(x) ((void)x)
+
+static inline size_t round_up_to_page_size(size_t x)
+{
+	return (x + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
+}
+
+#endif /* GRALLOC_HELPER_H_ */
+// clang-format on
diff --git a/tests/test_include/gralloc_priv.h b/tests/test_include/gralloc_priv.h
new file mode 100644
index 0000000..e771a69
--- /dev/null
+++ b/tests/test_include/gralloc_priv.h
@@ -0,0 +1,69 @@
+// clang-format off
+/*
+ * Copyright (C) 2017 ARM Limited. All rights reserved.
+ *
+ * Copyright (C) 2008 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.
+ */
+
+#ifndef GRALLOC_PRIV_H_
+#define GRALLOC_PRIV_H_
+
+#include <stdint.h>
+#include <pthread.h>
+#include <errno.h>
+#include <linux/fb.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <cutils/native_handle.h>
+#include "utils/log.h"
+
+#if GRALLOC_USE_GRALLOC1_API
+#include <hardware/gralloc1.h>
+#else
+#include <hardware/gralloc.h>
+#endif
+/**
+ * mali_gralloc_formats.h needs the define for GRALLOC_MODULE_API_VERSION_0_3 and
+ * GRALLOC_MODULE_API_VERSION_1_0, so include <gralloc1.h> or <gralloc.h> before
+ * including mali_gralloc_formats.h
+ **/
+#include "mali_gralloc_formats.h"
+#include "mali_gralloc_usages.h"
+#include "gralloc_helper.h"
+
+#if defined(GRALLOC_MODULE_API_VERSION_0_3) || \
+    (defined(GRALLOC_MODULE_API_VERSION_1_0) && !defined(GRALLOC_DISABLE_PRIVATE_BUFFER_DEF))
+
+/*
+ * This header file contains the private buffer definition. For gralloc 0.3 it will
+ * always be exposed, but for gralloc 1.0 it will be removed at some point in the future.
+ *
+ * GRALLOC_DISABLE_PRIVATE_BUFFER_DEF is intended for DDKs to test while implementing
+ * the new private API.
+ */
+#include "mali_gralloc_buffer.h"
+#endif
+
+#if defined(GRALLOC_MODULE_API_VERSION_1_0)
+
+/* gralloc 1.0 supports the new private interface that abstracts
+ * the private buffer definition to a set of defined APIs.
+ */
+#include "mali_gralloc_private_interface.h"
+#endif
+
+#endif /* GRALLOC_PRIV_H_ */
+// clang-format on
diff --git a/tests/test_include/img_gralloc1_public.h b/tests/test_include/img_gralloc1_public.h
new file mode 100644
index 0000000..aef435f
--- /dev/null
+++ b/tests/test_include/img_gralloc1_public.h
@@ -0,0 +1,253 @@
+// clang-format off
+/* Copyright (c) Imagination Technologies Ltd.
+ *
+ * The contents of this file are subject to the MIT license as set out below.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef HAL_PUBLIC_H
+#define HAL_PUBLIC_H
+
+/* Authors of third party hardware composer (HWC) modules will need to include
+ * this header to access functionality in the gralloc and framebuffer HALs.
+ */
+
+#include <hardware/gralloc.h>
+#if 0 /* Header below is not used by drm_hwcomposer */
+#include <hardware/memtrack.h>
+#endif
+
+#define ALIGN(x,a)	(((x) + (a) - 1L) & ~((a) - 1L))
+#define HW_ALIGN	16
+
+/* This can be tuned down as appropriate for the SOC.
+ *
+ * IMG formats are usually a single sub-alloc.
+ * Some OEM video formats are two sub-allocs (Y, UV planes).
+ * Future OEM video formats might be three sub-allocs (Y, U, V planes).
+ */
+#define MAX_SUB_ALLOCS 3
+
+/* Format is not YCbCr (e.g. a RGB format) - bIsYUVFormat should be false */
+#define YUV_CHROMA_ORDER_NONE 0
+/* Cb follows Y */
+#define YUV_CHROMA_ORDER_CBCR_UV 1
+/* Cr follows Y */
+#define YUV_CHROMA_ORDER_CRCB_VU 2
+
+typedef struct
+{
+	native_handle_t base;
+
+	/* These fields can be sent cross process. They are also valid
+	 * to duplicate within the same process.
+	 *
+	 * A table is stored within psPrivateData on gralloc_module_t (this
+	 * is obviously per-process) which maps stamps to a mapped
+	 * PVRSRV_CLIENT_MEM_INFO in that process. Each map entry has a lock
+	 * count associated with it, satisfying the requirements of the
+	 * Android API. This also prevents us from leaking maps/allocations.
+	 *
+	 * This table has entries inserted either by alloc()
+	 * (alloc_device_t) or map() (gralloc_module_t). Entries are removed
+	 * by free() (alloc_device_t) and unmap() (gralloc_module_t).
+	 *
+	 * As a special case for framebuffer_device_t, framebuffer_open()
+	 * will add and framebuffer_close() will remove from this table.
+	 */
+
+#define IMG_NATIVE_HANDLE_NUMFDS MAX_SUB_ALLOCS
+	/* The `fd' field is used to "export" a meminfo to another process.
+	 * Therefore, it is allocated by alloc_device_t, and consumed by
+	 * gralloc_module_t. The framebuffer_device_t does not need a handle,
+	 * and the special value IMG_FRAMEBUFFER_FD is used instead.
+	 */
+	int fd[MAX_SUB_ALLOCS];
+
+#define IMG_NATIVE_HANDLE_NUMINTS \
+	((sizeof(unsigned long long) / sizeof(int)) + 5 + MAX_SUB_ALLOCS + 1 + MAX_SUB_ALLOCS + MAX_SUB_ALLOCS)
+	/* A KERNEL unique identifier for any exported kernel meminfo. Each
+	 * exported kernel meminfo will have a unique stamp, but note that in
+	 * userspace, several meminfos across multiple processes could have
+	 * the same stamp. As the native_handle can be dup(2)'d, there could be
+	 * multiple handles with the same stamp but different file descriptors.
+	 */
+	unsigned long long ui64Stamp;
+
+	/* This is used for buffer usage validation when locking a buffer,
+	 * and also in WSEGL (for the composition bypass feature).
+	 */
+	int usage;
+
+	/* In order to do efficient cache flushes we need the buffer dimensions
+	 * and format. These are available on the ANativeWindowBuffer,
+	 * but the platform doesn't pass them down to the graphics HAL.
+	 */
+	int iWidth;
+	int iHeight;
+	int iFormat;
+	unsigned int uiBpp;
+
+	/* The ion allocation path doesn't allow for the allocation size and
+	 * mapping flags to be communicated cross-process automatically.
+	 * Cache these here so we can map buffers in client processes.
+	 */
+	unsigned int uiAllocSize[MAX_SUB_ALLOCS];
+	unsigned int uiFlags;
+	/* For multi-planar allocations, there will be multiple hstrides */
+	int aiStride[MAX_SUB_ALLOCS];
+
+	/* For multi-planar allocations, there will be multiple vstrides */
+	int aiVStride[MAX_SUB_ALLOCS];
+
+}
+__attribute__((aligned(sizeof(int)),packed)) IMG_native_handle_t;
+
+typedef struct
+{
+	int l, t, w, h;
+}
+IMG_write_lock_rect_t;
+
+typedef int (*IMG_buffer_format_compute_params_pfn)(
+	unsigned int uiPlane, int *piWidth, int *piHeight,
+	int *piStride, int *piVStride, unsigned long *pulPlaneOffset);
+
+typedef struct IMG_buffer_format_public_t
+{
+	/* Buffer formats are returned as a linked list */
+	struct IMG_buffer_format_public_t *psNext;
+
+	/* HAL_PIXEL_FORMAT_... enumerant */
+	int iHalPixelFormat;
+
+	/* WSEGL_PIXELFORMAT_... enumerant */
+	int iWSEGLPixelFormat;
+
+	/* Friendly name for format */
+	const char *const szName;
+
+	/* Bits (not bytes) per pixel */
+	unsigned int uiBpp;
+
+	/* Supported HW usage bits. If this is GRALLOC_USAGE_HW_MASK, all usages
+	 * are supported. Used for HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED.
+	 */
+	int iSupportedUsage;
+
+	/* YUV output format */
+	int bIsYUVFormat;
+
+	/* YCBCR_ORDERING_* defined the order of the Cb/Cr values */
+	int eYUVChromaOrder;
+
+	/* Utility function for adjusting YUV per-plane parameters */
+	IMG_buffer_format_compute_params_pfn pfnComputeParams;
+}
+IMG_buffer_format_public_t;
+
+#if 0 /* Not used by drm_hwcomposer but require additional dependencies */
+
+typedef struct
+{
+	/* Base memtrack record, copied to caller */
+	struct memtrack_record	base;
+
+	/* Record type, for filtering cached records */
+	enum memtrack_type		eType;
+
+	/* Process ID, for filtering cached records */
+	pid_t					pid;
+}
+IMG_memtrack_record_public_t;
+
+typedef struct IMG_gralloc_module_public_t
+{
+	gralloc_module_t base;
+
+	/* This function is deprecated and might be NULL. Do not use it. */
+	int (*GetPhyAddrs)(gralloc_module_t const* module,
+					   buffer_handle_t handle, void **ppvPhyAddr);
+
+	/* Obtain HAL's registered format list */
+	const IMG_buffer_format_public_t *(*GetBufferFormats)(void);
+
+	int (*GetImplementationFormat) (struct IMG_gralloc_module_public_t const *psGrallocModule, int usage);
+
+	int (*GetMemTrackRecords)(struct IMG_gralloc_module_public_t const *module,
+							  IMG_memtrack_record_public_t **ppsRecords,
+							  size_t *puNumRecords);
+
+	/* Custom-blit components in lieu of overlay hardware */
+	int (*Blit)(struct IMG_gralloc_module_public_t const *module,
+				buffer_handle_t src,
+				void *dest[MAX_SUB_ALLOCS], int format);
+
+	int (*Blit2)(struct IMG_gralloc_module_public_t const *module,
+				 buffer_handle_t src, buffer_handle_t dest,
+				 int w, int h, int x, int y);
+
+	int (*Blit3)(struct IMG_gralloc_module_public_t const *module,
+				 unsigned long long ui64SrcStamp, int iSrcWidth,
+				 int iSrcHeight, int iSrcFormat, int eSrcRotation,
+				 buffer_handle_t dest, int eDestRotation);
+}
+IMG_gralloc_module_public_t;
+
+#endif
+
+/**
+ * pixel format definitions
+ */
+
+enum {
+	/*
+	 * 0x100 = 0x1FF
+	 *
+	 * This range is reserved for pixel formats that are specific to the HAL
+	 * implementation. Implementations can use any value in this range to
+	 * communicate video pixel formats between their HAL modules. These
+	 * formats must not have an alpha channel. Additionally, an EGLimage
+	 * created from a gralloc buffer of one of these formats must be
+	 * supported for use with the GL_OES_EGL_image_external OpenGL ES
+	 * extension.
+	 */
+
+	/*
+	 * These are vendor specific pixel format, by (informal) convention
+	 * IMGTec formats start from the top of the range, TI formats start from
+	 * the bottom
+	 */
+	HAL_PIXEL_FORMAT_TI_NV12 = 0x100,
+	HAL_PIXEL_FORMAT_TI_UNUSED = 0x101,
+	HAL_PIXEL_FORMAT_TI_NV12_1D = 0x102,
+	HAL_PIXEL_FORMAT_TI_Y8 = 0x103,
+	HAL_PIXEL_FORMAT_TI_Y16 = 0x104,
+	HAL_PIXEL_FORMAT_TI_UYVY = 0x105,
+	HAL_PIXEL_FORMAT_BGRX_8888 = 0x1FF,
+
+	/* generic format missing from Android list, not specific to vendor
+	 * implementation
+	 */
+	HAL_PIXEL_FORMAT_NV12 = 0x3231564E, // FourCC for NV12
+};
+
+#endif /* HAL_PUBLIC_H */
+// clang-format on
diff --git a/tests/test_include/mali_gralloc_buffer.h b/tests/test_include/mali_gralloc_buffer.h
new file mode 100644
index 0000000..83f77c2
--- /dev/null
+++ b/tests/test_include/mali_gralloc_buffer.h
@@ -0,0 +1,271 @@
+// clang-format off
+/*
+ * Copyright (C) 2017 ARM Limited. All rights reserved.
+ *
+ * Copyright (C) 2008 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.
+ */
+#ifndef MALI_GRALLOC_BUFFER_H_
+#define MALI_GRALLOC_BUFFER_H_
+
+#include <errno.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <sys/mman.h>
+
+#include "mali_gralloc_private_interface_types.h"
+
+/* NOTE:
+ * If your framebuffer device driver is integrated with dma_buf, you will have to
+ * change this IOCTL definition to reflect your integration with the framebuffer
+ * device.
+ * Expected return value is a structure filled with a file descriptor
+ * backing your framebuffer device memory.
+ */
+struct fb_dmabuf_export
+{
+	__u32 fd;
+	__u32 flags;
+};
+#define FBIOGET_DMABUF _IOR('F', 0x21, struct fb_dmabuf_export)
+
+/* the max string size of GRALLOC_HARDWARE_GPU0 & GRALLOC_HARDWARE_FB0
+ * 8 is big enough for "gpu0" & "fb0" currently
+ */
+#define MALI_GRALLOC_HARDWARE_MAX_STR_LEN 8
+#define NUM_FB_BUFFERS 2
+
+/* Define number of shared file descriptors */
+#define GRALLOC_ARM_NUM_FDS 2
+
+#define NUM_INTS_IN_PRIVATE_HANDLE ((sizeof(struct private_handle_t) - sizeof(native_handle)) / sizeof(int) - sNumFds)
+
+#define SZ_4K 0x00001000
+#define SZ_2M 0x00200000
+
+struct private_handle_t;
+
+#ifndef __cplusplus
+/* C99 with pedantic don't allow anonymous unions which is used in below struct
+ * Disable pedantic for C for this struct only.
+ */
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wpedantic"
+#endif
+
+#ifdef __cplusplus
+struct private_handle_t : public native_handle
+{
+#else
+struct private_handle_t
+{
+	struct native_handle nativeHandle;
+#endif
+
+#ifdef __cplusplus
+	/* Never intended to be used from C code */
+	enum
+	{
+		PRIV_FLAGS_FRAMEBUFFER = 0x00000001,
+		PRIV_FLAGS_USES_ION_COMPOUND_HEAP = 0x00000002,
+		PRIV_FLAGS_USES_ION = 0x00000004,
+		PRIV_FLAGS_USES_ION_DMA_HEAP = 0x00000008
+	};
+
+	enum
+	{
+		LOCK_STATE_WRITE = 1 << 31,
+		LOCK_STATE_MAPPED = 1 << 30,
+		LOCK_STATE_READ_MASK = 0x3FFFFFFF
+	};
+#endif
+
+	/*
+	 * Shared file descriptor for dma_buf sharing. This must be the first element in the
+	 * structure so that binder knows where it is and can properly share it between
+	 * processes.
+	 * DO NOT MOVE THIS ELEMENT!
+	 */
+	int share_fd;
+	int share_attr_fd;
+
+	// ints
+	int magic;
+	int req_format;
+	uint64_t internal_format;
+	int byte_stride;
+	int flags;
+	int size;
+	int width;
+	int height;
+	int internalWidth;
+	int internalHeight;
+	int stride;
+	union
+	{
+		void *base;
+		uint64_t padding;
+	};
+	union {
+		uint64_t consumer_usage;
+		uint64_t usage;
+	};
+	uint64_t producer_usage;
+	uint64_t backing_store_id;
+	int backing_store_size;
+	int writeOwner;
+	int allocating_pid;
+	int remote_pid;
+	int ref_count;
+	// locally mapped shared attribute area
+	union
+	{
+		void *attr_base;
+		uint64_t padding3;
+	};
+
+	mali_gralloc_yuv_info yuv_info;
+
+	// Following members is for framebuffer only
+	int fd;
+	union
+	{
+		off_t offset;
+		uint64_t padding4;
+	};
+
+	/*
+	 * min_pgsz denotes minimum phys_page size used by this buffer.
+	 * if buffer memory is physical contiguous set min_pgsz to buff->size
+	 * if not sure buff's real phys_page size, you can use SZ_4K for safe.
+	 */
+	int min_pgsz;
+#ifdef __cplusplus
+	/*
+	 * We track the number of integers in the structure. There are 16 unconditional
+	 * integers (magic - pid, yuv_info, fd and offset). Note that the fd element is
+	 * considered an int not an fd because it is not intended to be used outside the
+	 * surface flinger process. The GRALLOC_ARM_NUM_INTS variable is used to track the
+	 * number of integers that are conditionally included. Similar considerations apply
+	 * to the number of fds.
+	 */
+	static const int sNumFds = GRALLOC_ARM_NUM_FDS;
+	static const int sMagic = 0x3141592;
+
+	private_handle_t(int _flags, int _size, void *_base, uint64_t _consumer_usage, uint64_t _producer_usage,
+	                 int fb_file, off_t fb_offset)
+	    : share_fd(-1)
+	    , share_attr_fd(-1)
+	    , magic(sMagic)
+	    , flags(_flags)
+	    , size(_size)
+	    , width(0)
+	    , height(0)
+	    , stride(0)
+	    , base(_base)
+	    , consumer_usage(_consumer_usage)
+	    , producer_usage(_producer_usage)
+	    , backing_store_id(0x0)
+	    , backing_store_size(0)
+	    , writeOwner(0)
+	    , allocating_pid(getpid())
+	    , remote_pid(-1)
+	    , ref_count(1)
+	    , attr_base(MAP_FAILED)
+	    , yuv_info(MALI_YUV_NO_INFO)
+	    , fd(fb_file)
+	    , offset(fb_offset)
+	{
+		version = sizeof(native_handle);
+		numFds = sNumFds;
+		numInts = NUM_INTS_IN_PRIVATE_HANDLE;
+	}
+
+	private_handle_t(int _flags, int _size, int _min_pgsz, uint64_t _consumer_usage, uint64_t _producer_usage,
+	                 int _shared_fd, int _req_format, uint64_t _internal_format, int _byte_stride, int _width,
+	                 int _height, int _stride, int _internalWidth, int _internalHeight, int _backing_store_size)
+	    : share_fd(_shared_fd)
+	    , share_attr_fd(-1)
+	    , magic(sMagic)
+	    , req_format(_req_format)
+	    , internal_format(_internal_format)
+	    , byte_stride(_byte_stride)
+	    , flags(_flags)
+	    , size(_size)
+	    , width(_width)
+	    , height(_height)
+	    , internalWidth(_internalWidth)
+	    , internalHeight(_internalHeight)
+	    , stride(_stride)
+	    , base(NULL)
+	    , consumer_usage(_consumer_usage)
+	    , producer_usage(_producer_usage)
+	    , backing_store_id(0x0)
+	    , backing_store_size(_backing_store_size)
+	    , writeOwner(0)
+	    , allocating_pid(getpid())
+	    , remote_pid(-1)
+	    , ref_count(1)
+	    , attr_base(MAP_FAILED)
+	    , yuv_info(MALI_YUV_NO_INFO)
+	    , fd(-1)
+	    , offset(0)
+	    , min_pgsz(_min_pgsz)
+	{
+		version = sizeof(native_handle);
+		numFds = sNumFds;
+		numInts = NUM_INTS_IN_PRIVATE_HANDLE;
+	}
+
+	~private_handle_t()
+	{
+		magic = 0;
+	}
+
+	bool usesPhysicallyContiguousMemory()
+	{
+		return (flags & PRIV_FLAGS_FRAMEBUFFER) ? true : false;
+	}
+
+	static int validate(const native_handle *h)
+	{
+		const private_handle_t *hnd = (const private_handle_t *)h;
+
+		if (!h || h->version != sizeof(native_handle) || h->numInts != NUM_INTS_IN_PRIVATE_HANDLE ||
+		    h->numFds != sNumFds || hnd->magic != sMagic)
+		{
+			return -EINVAL;
+		}
+
+		return 0;
+	}
+
+	static private_handle_t *dynamicCast(const native_handle *in)
+	{
+		if (validate(in) == 0)
+		{
+			return (private_handle_t *)in;
+		}
+
+		return NULL;
+	}
+#endif
+};
+#ifndef __cplusplus
+/* Restore previous diagnostic for pedantic */
+#pragma GCC diagnostic pop
+#endif
+
+#endif /* MALI_GRALLOC_BUFFER_H_ */
+// clang-format on
diff --git a/tests/test_include/mali_gralloc_formats.h b/tests/test_include/mali_gralloc_formats.h
new file mode 100644
index 0000000..e62ce5e
--- /dev/null
+++ b/tests/test_include/mali_gralloc_formats.h
@@ -0,0 +1,270 @@
+// clang-format off
+/*
+ * Copyright (C) 2016-2017 ARM Limited. All rights reserved.
+ *
+ * Copyright (C) 2008 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.
+ */
+
+#ifndef MALI_GRALLOC_FORMATS_H_
+#define MALI_GRALLOC_FORMATS_H_
+
+#include <system/graphics.h>
+
+/* Internal formats are represented in gralloc as a 64bit identifier
+ * where the 32 lower bits are a base format and the 32 upper bits are modifiers.
+ *
+ * Modifier bits are divided into mutually exclusive ones and those that are not.
+ */
+/* Internal format type */
+typedef uint64_t mali_gralloc_internal_format;
+
+/* Internal format masks */
+#define MALI_GRALLOC_INTFMT_FMT_MASK 0x00000000ffffffffULL
+#define MALI_GRALLOC_INTFMT_EXT_MASK 0xffffffff00000000ULL
+#define MALI_GRALLOC_INTFMT_ME_EXT_MASK 0x0000ffff00000000ULL
+#define MALI_GRALLOC_INTFMT_REG_EXT_MASK 0xffff000000000000ULL
+
+/* Internal base formats */
+
+/* Base formats that do not have an identical HAL match
+ * are defined starting at the Android private range
+ */
+#define MALI_GRALLOC_FORMAT_INTERNAL_RANGE_BASE 0x100
+
+typedef enum
+{
+	MALI_GRALLOC_FORMAT_TYPE_USAGE,
+	MALI_GRALLOC_FORMAT_TYPE_INTERNAL,
+} mali_gralloc_format_type;
+
+typedef enum
+{
+	/* Internal definitions for HAL formats. */
+	MALI_GRALLOC_FORMAT_INTERNAL_RGBA_8888 = HAL_PIXEL_FORMAT_RGBA_8888,
+	MALI_GRALLOC_FORMAT_INTERNAL_RGBX_8888 = HAL_PIXEL_FORMAT_RGBX_8888,
+	MALI_GRALLOC_FORMAT_INTERNAL_RGB_888 = HAL_PIXEL_FORMAT_RGB_888,
+	MALI_GRALLOC_FORMAT_INTERNAL_RGB_565 = HAL_PIXEL_FORMAT_RGB_565,
+	MALI_GRALLOC_FORMAT_INTERNAL_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888,
+	MALI_GRALLOC_FORMAT_INTERNAL_YV12 = HAL_PIXEL_FORMAT_YV12,
+	MALI_GRALLOC_FORMAT_INTERNAL_Y8 = HAL_PIXEL_FORMAT_Y8,
+	MALI_GRALLOC_FORMAT_INTERNAL_Y16 = HAL_PIXEL_FORMAT_Y16,
+	MALI_GRALLOC_FORMAT_INTERNAL_YUV420_888 = HAL_PIXEL_FORMAT_YCbCr_420_888,
+
+	/* Camera specific HAL formats */
+	MALI_GRALLOC_FORMAT_INTERNAL_RAW16 = HAL_PIXEL_FORMAT_RAW16,
+	MALI_GRALLOC_FORMAT_INTERNAL_RAW12 = HAL_PIXEL_FORMAT_RAW12,
+	MALI_GRALLOC_FORMAT_INTERNAL_RAW10 = HAL_PIXEL_FORMAT_RAW10,
+	MALI_GRALLOC_FORMAT_INTERNAL_BLOB = HAL_PIXEL_FORMAT_BLOB,
+
+	/* Flexible YUV formats would be parsed but not have any representation as
+     * internal format itself but one of the ones below
+     */
+
+	/* The internal private formats that have no HAL equivivalent are defined
+     * afterwards starting at a specific base range */
+	MALI_GRALLOC_FORMAT_INTERNAL_NV12 = MALI_GRALLOC_FORMAT_INTERNAL_RANGE_BASE,
+	MALI_GRALLOC_FORMAT_INTERNAL_NV21,
+	MALI_GRALLOC_FORMAT_INTERNAL_YUV422_8BIT,
+
+	/* Extended YUV formats
+     *
+     * NOTE: P010, P210, and Y410 are only supported uncompressed.
+     */
+	MALI_GRALLOC_FORMAT_INTERNAL_Y0L2,
+	MALI_GRALLOC_FORMAT_INTERNAL_P010,
+	MALI_GRALLOC_FORMAT_INTERNAL_P210,
+	MALI_GRALLOC_FORMAT_INTERNAL_Y210,
+	MALI_GRALLOC_FORMAT_INTERNAL_Y410,
+
+	/* Add more internal formats here. Make sure decode_internal_format() is updated. */
+
+	/* These are legacy 0.3 gralloc formats used only by the wrap/unwrap macros. */
+	MALI_GRALLOC_FORMAT_INTERNAL_YV12_WRAP,
+	MALI_GRALLOC_FORMAT_INTERNAL_Y8_WRAP,
+	MALI_GRALLOC_FORMAT_INTERNAL_Y16_WRAP,
+
+	MALI_GRALLOC_FORMAT_INTERNAL_RANGE_LAST,
+} mali_gralloc_pixel_format;
+
+/* Format Modifier Bits Locations */
+#define MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START 32
+#define MALI_GRALLOC_INTFMT_EXTENSION_BIT_START (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 16)
+
+/* Mutually Exclusive Modifier Bits */
+
+/* This format will use AFBC */
+#define MALI_GRALLOC_INTFMT_AFBC_BASIC (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 0))
+
+/* This format uses AFBC split block mode */
+#define MALI_GRALLOC_INTFMT_AFBC_SPLITBLK (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 1))
+
+#define MALI_GRALLOC_INTFMT_UNUSED (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 2))
+
+/* This format uses AFBC wide block mode */
+#define MALI_GRALLOC_INTFMT_AFBC_WIDEBLK (1ULL << (MALI_GRALLOC_INTFMT_ME_EXTENSION_BIT_START + 3))
+
+/* Regular Modifier Bits */
+#define MALI_GRALLOC_INTFMT_AFBC_TILED_HEADERS (1ULL << (MALI_GRALLOC_INTFMT_EXTENSION_BIT_START + 0))
+
+/* This mask should be used to check or clear support for AFBC for an internal format
+ * These bits are mutually exclusive so this mask should not be used to enable support
+ */
+#define MALI_GRALLOC_INTFMT_AFBCENABLE_MASK \
+	((uint64_t)(MALI_GRALLOC_INTFMT_AFBC_BASIC | MALI_GRALLOC_INTFMT_AFBC_SPLITBLK | MALI_GRALLOC_INTFMT_AFBC_WIDEBLK))
+
+/* These are legacy Gralloc 0.3 support macros for passing private formats through the 0.3 alloc interface.
+ * It packs modifier bits together with base format into a 32 bit format identifier.
+ * Gralloc 1.0 interface should use private functions to set private buffer format in the buffer descriptor.
+ *
+ * Packing:
+ *
+ * Bits 15-0:    mali_gralloc_pixel_format format
+ * Bits 23-16:   mutually exclusive modifier bits
+ * Bits 31-24:   regular modifier bits
+ */
+static inline int mali_gralloc_format_wrapper(int format, int modifiers)
+{
+	/* Internal formats that are identical to HAL formats
+	 * have the same definition. This is convenient for
+	 * client parsing code to not have to parse them separately.
+	 *
+	 * For 3 of the HAL YUV formats that have very large definitions
+	 * this causes problems for packing in modifier bits.
+	 * Because of this reason we redefine these three formats
+	 * while packing/unpacking them.
+	 */
+	if (format == MALI_GRALLOC_FORMAT_INTERNAL_YV12)
+	{
+		format = MALI_GRALLOC_FORMAT_INTERNAL_YV12_WRAP;
+	}
+	else if (format == MALI_GRALLOC_FORMAT_INTERNAL_Y8)
+	{
+		format = MALI_GRALLOC_FORMAT_INTERNAL_Y8_WRAP;
+	}
+	else if (format == MALI_GRALLOC_FORMAT_INTERNAL_Y16)
+	{
+		format = MALI_GRALLOC_FORMAT_INTERNAL_Y16_WRAP;
+	}
+
+	return (modifiers | format);
+}
+
+static inline uint64_t mali_gralloc_format_unwrap(int x)
+{
+	uint64_t internal_format = (uint64_t)(((((uint64_t)(x)) & 0xff000000) << 24) | // Regular modifier bits
+	                                      ((((uint64_t)(x)) & 0x00ff0000) << 16) | // Mutually exclusive modifier bits
+	                                      (((uint64_t)(x)) & 0x0000ffff)); // Private format
+
+	uint64_t base_format = internal_format & MALI_GRALLOC_INTFMT_FMT_MASK;
+	uint64_t modifiers = internal_format & MALI_GRALLOC_INTFMT_EXT_MASK;
+
+	if (base_format == MALI_GRALLOC_FORMAT_INTERNAL_YV12_WRAP)
+	{
+		base_format = MALI_GRALLOC_FORMAT_INTERNAL_YV12;
+	}
+	else if (base_format == MALI_GRALLOC_FORMAT_INTERNAL_Y8_WRAP)
+	{
+		base_format = MALI_GRALLOC_FORMAT_INTERNAL_Y8;
+	}
+	else if (base_format == MALI_GRALLOC_FORMAT_INTERNAL_Y16_WRAP)
+	{
+		base_format = MALI_GRALLOC_FORMAT_INTERNAL_Y16;
+	}
+
+	return (modifiers | base_format);
+}
+
+#define GRALLOC_PRIVATE_FORMAT_WRAPPER(x) (mali_gralloc_format_wrapper(x, 0))
+#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC(x) (mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_BASIC >> 16)))
+#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_SPLITBLK(x) \
+	(mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_SPLITBLK >> 16)))
+#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_WIDEBLK(x) \
+	(mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_WIDEBLK >> 16)))
+#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_TILED_HEADERS_BASIC(x)                   \
+	(mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_TILED_HEADERS >> 24) | \
+	                                    (MALI_GRALLOC_INTFMT_AFBC_BASIC >> 16)))
+#define GRALLOC_PRIVATE_FORMAT_WRAPPER_AFBC_TILED_HEADERS_WIDE(x)                    \
+	(mali_gralloc_format_wrapper(x, (MALI_GRALLOC_INTFMT_AFBC_TILED_HEADERS >> 24) | \
+	                                    (MALI_GRALLOC_INTFMT_AFBC_WIDEBLK >> 16)))
+#define GRALLOC_PRIVATE_FORMAT_UNWRAP(x) mali_gralloc_format_unwrap(x)
+
+/* IP block capability masks */
+#define MALI_GRALLOC_FORMAT_CAPABILITY_OPTIONS_PRESENT ((uint64_t)(1 << 0))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_BASIC ((uint64_t)(1 << 1))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_SPLITBLK ((uint64_t)(1 << 2))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_WIDEBLK ((uint64_t)(1 << 3))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_WIDEBLK_YUV_DISABLE ((uint64_t)(1 << 4))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_YUV_NOREAD ((uint64_t)(1 << 5))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_YUV_NOWRITE ((uint64_t)(1 << 6))
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_TILED_HEADERS ((uint64_t)(1 << 7))
+
+#define MALI_GRALLOC_FORMAT_CAPABILITY_AFBCENABLE_MASK                                                     \
+	((uint64_t)(MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_BASIC | MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_SPLITBLK | \
+	            MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_WIDEBLK | MALI_GRALLOC_FORMAT_CAPABILITY_AFBC_TILED_HEADERS))
+
+struct mali_gralloc_format_caps
+{
+	uint64_t caps_mask;
+};
+typedef struct mali_gralloc_format_caps mali_gralloc_format_caps;
+
+#define MALI_GRALLOC_FORMATCAPS_SYM_NAME mali_gralloc_format_capabilities
+#define MALI_GRALLOC_FORMATCAPS_SYM_NAME_STR "mali_gralloc_format_capabilities"
+
+/* Producer and Consumer definitions */
+typedef enum
+{
+	MALI_GRALLOC_PRODUCER_VIDEO_DECODER,
+	MALI_GRALLOC_PRODUCER_GPU,
+	MALI_GRALLOC_PRODUCER_CAMERA,
+} mali_gralloc_producer_type;
+
+typedef enum
+{
+
+	/* For surface composition in SurfaceFlinger a producer
+     * will not know what consumer will process a buffer.
+     *
+     * MALI_GRALLOC_CONSUMER_GPU_OR_DISPLAY means the GPU
+     * MUST support the given format but it should be allocated
+     * with preference to the DPU.
+     */
+	MALI_GRALLOC_CONSUMER_GPU_OR_DISPLAY,
+	MALI_GRALLOC_CONSUMER_VIDEO_ENCODER,
+
+	/* This is used when no known "premium" dpu is configured.
+     * For example, HDLCD/CLCD would be such a dpu.
+     */
+	MALI_GRALLOC_CONSUMER_GPU_EXCL,
+} mali_gralloc_consumer_type;
+
+/* Internal prototypes */
+#if defined(GRALLOC_LIBRARY_BUILD)
+uint64_t mali_gralloc_select_format(uint64_t req_format, mali_gralloc_format_type type, uint64_t usage,
+                                    int buffer_size);
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void mali_gralloc_get_gpu_caps(struct mali_gralloc_format_caps *gpu_caps);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MALI_GRALLOC_FORMATS_H_ */
+// clang-format on
diff --git a/tests/test_include/mali_gralloc_private_interface_types.h b/tests/test_include/mali_gralloc_private_interface_types.h
new file mode 100644
index 0000000..26b7744
--- /dev/null
+++ b/tests/test_include/mali_gralloc_private_interface_types.h
@@ -0,0 +1,88 @@
+// clang-format off
+/*
+ * Copyright (C) 2017 ARM Limited. All rights reserved.
+ *
+ * Copyright (C) 2008 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.
+ */
+
+#ifndef MALI_GRALLOC_PRIVATE_INTERFACE_TYPES_H_
+#define MALI_GRALLOC_PRIVATE_INTERFACE_TYPES_H_
+
+#define GRALLOC_ARM_BUFFER_ATTR_HDR_INFO_SUPPORT
+
+typedef enum
+{
+	MALI_HDR_NO_INFO,
+	MALI_HDR_ST2084,
+	MALI_HDR_HLG,
+	MALI_HDR_LAST
+} mali_transfer_function;
+
+typedef struct
+{
+	//values are in units of 0.00002
+	uint16_t x;
+	uint16_t y;
+} primaries;
+
+typedef struct
+{
+	primaries r;
+	primaries g;
+	primaries b;
+	primaries w;
+	uint16_t minDisplayLuminance; // in cd/m^2
+	uint16_t maxDisplayLuminance; // in 0.0001 cd/m^2
+	uint16_t maxContentLightLevel; // in cd/m^2
+	uint16_t maxFrameAverageLightLevel; // in cd/m^2
+	mali_transfer_function eotf;
+} mali_hdr_info;
+
+enum
+{
+	/* CROP_RECT and YUV_TRANS are intended to be
+	 * written by producers and read by consumers.
+	 * A producer should write these parameters before
+	 * it queues a buffer to the consumer.
+	 */
+
+	/* CROP RECT, defined as an int array of top, left, height, width. Origin in top-left corner */
+	GRALLOC_ARM_BUFFER_ATTR_CROP_RECT = 1,
+
+	/* Set if the AFBC format used a YUV transform before compressing */
+	GRALLOC_ARM_BUFFER_ATTR_AFBC_YUV_TRANS = 2,
+
+	/* Set if the AFBC format uses sparse allocation */
+	GRALLOC_ARM_BUFFER_ATTR_AFBC_SPARSE_ALLOC = 3,
+
+	/* HDR Informations*/
+	GRALLOC_ARM_BUFFER_ATTR_HDR_INFO = 4,
+
+	GRALLOC_ARM_BUFFER_ATTR_LAST
+};
+
+typedef uint32_t buf_attr;
+
+typedef enum
+{
+	MALI_YUV_NO_INFO,
+	MALI_YUV_BT601_NARROW,
+	MALI_YUV_BT601_WIDE,
+	MALI_YUV_BT709_NARROW,
+	MALI_YUV_BT709_WIDE
+} mali_gralloc_yuv_info;
+
+#endif /* MALI_GRALLOC_PRIVATE_INTERFACE_TYPES_H_ */
+// clang-format on
diff --git a/tests/test_include/mali_gralloc_usages.h b/tests/test_include/mali_gralloc_usages.h
new file mode 100644
index 0000000..55de5a0
--- /dev/null
+++ b/tests/test_include/mali_gralloc_usages.h
@@ -0,0 +1,94 @@
+// clang-format off
+/*
+ * (C) COPYRIGHT 2017 ARM Limited. All rights reserved.
+ * Copyright (C) 2008 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.
+ */
+
+#ifndef MALI_GRALLOC_USAGES_H_
+#define MALI_GRALLOC_USAGES_H_
+
+/*
+ * Below usage types overlap, this is intentional.
+ * The reason is that for Gralloc 0.3 there are very
+ * few usage flags we have at our disposal.
+ *
+ * The overlapping is handled by processing the definitions
+ * in a specific order.
+ *
+ * MALI_GRALLOC_USAGE_PRIVATE_FORMAT and MALI_GRALLOC_USAGE_NO_AFBC
+ * don't overlap and are processed first.
+ *
+ * MALI_GRALLOC_USAGE_YUV_CONF are only for YUV formats and clients
+ * using MALI_GRALLOC_USAGE_NO_AFBC must never allocate YUV formats.
+ * The latter is strictly enforced and allocations will fail.
+ *
+ * MALI_GRALLOC_USAGE_AFBC_PADDING is only valid if MALI_GRALLOC_USAGE_NO_AFBC
+ * is not present.
+ */
+
+/*
+ * Gralloc private usage 0-3 are the same in 0.3 and 1.0.
+ * We defined based our usages based on what is available.
+ */
+#if defined(GRALLOC_MODULE_API_VERSION_1_0)
+typedef enum
+{
+	/* The client has specified a private format in the format parameter */
+	MALI_GRALLOC_USAGE_PRIVATE_FORMAT = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_3,
+
+	/* Buffer won't be allocated as AFBC */
+	MALI_GRALLOC_USAGE_NO_AFBC = (int)(GRALLOC1_PRODUCER_USAGE_PRIVATE_1 | GRALLOC1_PRODUCER_USAGE_PRIVATE_2),
+
+	/* Valid only for YUV allocations */
+	MALI_GRALLOC_USAGE_YUV_CONF_0 = 0,
+	MALI_GRALLOC_USAGE_YUV_CONF_1 = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_1,
+	MALI_GRALLOC_USAGE_YUV_CONF_2 = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_0,
+	MALI_GRALLOC_USAGE_YUV_CONF_3 = (int)(GRALLOC1_PRODUCER_USAGE_PRIVATE_0 | GRALLOC1_PRODUCER_USAGE_PRIVATE_1),
+	MALI_GRALLOC_USAGE_YUV_CONF_MASK = MALI_GRALLOC_USAGE_YUV_CONF_3,
+
+	/* A very specific alignment is requested on some buffers */
+	MALI_GRALLOC_USAGE_AFBC_PADDING = (int)GRALLOC1_PRODUCER_USAGE_PRIVATE_2,
+
+} mali_gralloc_usage_type;
+#elif defined(GRALLOC_MODULE_API_VERSION_0_3)
+typedef enum
+{
+	/* The client has specified a private format in the format parameter */
+	MALI_GRALLOC_USAGE_PRIVATE_FORMAT = (int)GRALLOC_USAGE_PRIVATE_3,
+
+	/* Buffer won't be allocated as AFBC */
+	MALI_GRALLOC_USAGE_NO_AFBC = (int)(GRALLOC_USAGE_PRIVATE_1 | GRALLOC_USAGE_PRIVATE_2),
+
+	/* Valid only for YUV allocations */
+	MALI_GRALLOC_USAGE_YUV_CONF_0 = 0,
+	MALI_GRALLOC_USAGE_YUV_CONF_1 = (int)GRALLOC_USAGE_PRIVATE_1,
+	MALI_GRALLOC_USAGE_YUV_CONF_2 = (int)GRALLOC_USAGE_PRIVATE_0,
+	MALI_GRALLOC_USAGE_YUV_CONF_3 = (int)(GRALLOC_USAGE_PRIVATE_0 | GRALLOC_USAGE_PRIVATE_1),
+	MALI_GRALLOC_USAGE_YUV_CONF_MASK = MALI_GRALLOC_USAGE_YUV_CONF_3,
+
+	/* A very specific alignment is requested on some buffers */
+	MALI_GRALLOC_USAGE_AFBC_PADDING = GRALLOC_USAGE_PRIVATE_2,
+
+} mali_gralloc_usage_type;
+#else
+#if defined(GRALLOC_LIBRARY_BUILD)
+#error "Please include mali_gralloc_module.h before including other gralloc headers when building gralloc itself"
+#else
+#error "Please include either gralloc.h or gralloc1.h header before including gralloc_priv.h"
+#endif
+#endif
+
+#endif /*MALI_GRALLOC_USAGES_H_*/
+// clang-format on
diff --git a/tests/worker_test.cpp b/tests/worker_test.cpp
index cb6275e..d1eb2b3 100644
--- a/tests/worker_test.cpp
+++ b/tests/worker_test.cpp
@@ -8,17 +8,13 @@
 using android::Worker;
 
 struct TestWorker : public Worker {
-  TestWorker()
-      : Worker("test-worker", HAL_PRIORITY_URGENT_DISPLAY),
-        value(0),
-        enabled_(false) {
-  }
+  TestWorker() : Worker("test-worker", HAL_PRIORITY_URGENT_DISPLAY){};
 
   int Init() {
     return InitWorker();
   }
 
-  void Routine() {
+  void Routine() override {
     Lock();
     if (!enabled_) {
       int ret = WaitForSignalOrExitLocked();
@@ -47,16 +43,17 @@
       Signal();
   }
 
-  int value;
+  // NOLINTNEXTLINE: should not be public
+  int value{};
 
  private:
-  bool enabled_;
+  bool enabled_{};
 };
 
 struct WorkerTest : public testing::Test {
   TestWorker worker;
 
-  virtual void SetUp() {
+  void SetUp() override {
     worker.Init();
   }
 
@@ -65,7 +62,8 @@
   }
 };
 
-TEST_F(WorkerTest, test_worker) {
+// NOLINTNEXTLINE: required by gtest macros
+TEST_F(WorkerTest, TestWorker) {
   // already isInitialized so should succeed
   ASSERT_TRUE(worker.initialized());
 
@@ -102,7 +100,8 @@
   ASSERT_FALSE(worker.initialized());
 }
 
-TEST_F(WorkerTest, exit_while_running) {
+// NOLINTNEXTLINE: required by gtest macros
+TEST_F(WorkerTest, ExitWhileRunning) {
   worker.Control(true);
 
   std::this_thread::sleep_for(std::chrono::milliseconds(50));
diff --git a/utils/Worker.cpp b/utils/Worker.cpp
index 1f30588..d2b60c8 100644
--- a/utils/Worker.cpp
+++ b/utils/Worker.cpp
@@ -34,8 +34,7 @@
   if (initialized())
     return -EALREADY;
 
-  thread_ = std::unique_ptr<std::thread>(
-      new std::thread(&Worker::InternalRoutine, this));
+  thread_ = std::make_unique<std::thread>(&Worker::InternalRoutine, this);
   initialized_ = true;
   exit_ = false;
 
diff --git a/utils/autolock.cpp b/utils/autolock.cpp
index 4e9552a..3342e46 100644
--- a/utils/autolock.cpp
+++ b/utils/autolock.cpp
@@ -19,10 +19,11 @@
 
 #include "autolock.h"
 
-#include <errno.h>
 #include <pthread.h>
 
-#include <log/log.h>
+#include <cerrno>
+
+#include "utils/log.h"
 
 namespace android {
 
diff --git a/utils/hwcutils.cpp b/utils/hwcutils.cpp
index 322efce..81097ce 100644
--- a/utils/hwcutils.cpp
+++ b/utils/hwcutils.cpp
@@ -30,18 +30,18 @@
 namespace android {
 
 const hwc_drm_bo *DrmHwcBuffer::operator->() const {
-  if (importer_ == NULL) {
+  if (importer_ == nullptr) {
     ALOGE("Access of non-existent BO");
     exit(1);
-    return NULL;
+    return nullptr;
   }
   return &bo_;
 }
 
 void DrmHwcBuffer::Clear() {
-  if (importer_ != NULL) {
+  if (importer_ != nullptr) {
     importer_->ReleaseBuffer(&bo_);
-    importer_ = NULL;
+    importer_ = nullptr;
   }
 }
 
@@ -60,7 +60,7 @@
     return ret;
   }
 
-  if (importer_ != NULL) {
+  if (importer_ != nullptr) {
     importer_->ReleaseBuffer(&bo_);
   }
 
@@ -72,13 +72,12 @@
 }
 
 int DrmHwcNativeHandle::CopyBufferHandle(buffer_handle_t handle) {
-  native_handle_t *handle_copy;
+  native_handle_t *handle_copy = nullptr;
   GraphicBufferMapper &gm(GraphicBufferMapper::get());
-  int ret;
+  int ret = 0;
 
   ret = gm.getGrallocMapper().importBuffer(handle,
-                                           const_cast<buffer_handle_t *>(
-                                               &handle_copy));
+                                           (buffer_handle_t *)&handle_copy);
 
   if (ret) {
     ALOGE("Failed to import buffer handle %d", ret);
@@ -97,13 +96,13 @@
 }
 
 void DrmHwcNativeHandle::Clear() {
-  if (handle_ != NULL) {
+  if (handle_ != nullptr) {
     GraphicBufferMapper &gm(GraphicBufferMapper::get());
     int ret = gm.freeBuffer(handle_);
     if (ret) {
       ALOGE("Failed to free buffer handle %d", ret);
     }
-    handle_ = NULL;
+    handle_ = nullptr;
   }
 }
 
@@ -135,14 +134,6 @@
   return ImportBuffer(importer);
 }
 
-void DrmHwcLayer::SetSourceCrop(hwc_frect_t const &crop) {
-  source_crop = crop;
-}
-
-void DrmHwcLayer::SetDisplayFrame(hwc_rect_t const &frame) {
-  display_frame = frame;
-}
-
 void DrmHwcLayer::SetTransform(int32_t sf_transform) {
   transform = 0;
   // 270* and 180* cannot be combined with flips. More specifically, they
diff --git a/utils/log.h b/utils/log.h
new file mode 100644
index 0000000..a48d2e7
--- /dev/null
+++ b/utils/log.h
@@ -0,0 +1,26 @@
+#ifndef UTILS_LOG_H_
+#define UTILS_LOG_H_
+
+#ifdef ANDROID
+
+#include <log/log.h>
+
+#else
+
+#include <cinttypes>
+#include <cstdio>
+
+// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
+#define ALOGE(args...) printf("ERR: " args)
+// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
+#define ALOGW(args...) printf("WARN: " args)
+// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
+#define ALOGI(args...) printf("INFO: " args)
+// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
+#define ALOGD(args...) printf("DBG:" args)
+// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
+#define ALOGV(args...) printf("VERBOSE: " args)
+
+#endif
+
+#endif
\ No newline at end of file
diff --git a/utils/properties.h b/utils/properties.h
new file mode 100644
index 0000000..607cbc5
--- /dev/null
+++ b/utils/properties.h
@@ -0,0 +1,28 @@
+#ifndef UTILS_PROPERTIES_H_
+#define UTILS_PROPERTIES_H_
+
+#ifdef ANDROID
+
+#include <cutils/properties.h>
+
+#else
+
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+
+// NOLINTNEXTLINE(readability-identifier-naming)
+constexpr int PROPERTY_VALUE_MAX = 92;
+
+auto inline property_get(const char *name, char *value,
+                         const char *default_value) -> int {
+  char *prop = std::getenv(name);
+  if (prop == nullptr) {
+    snprintf(value, PROPERTY_VALUE_MAX, "%s", default_value);
+  }
+  return strlen(value);
+}
+
+#endif
+
+#endif
\ No newline at end of file