Merge "[MTE] Cleanup tagged si_addr refs to fix mappings OOB bug."
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 85ffc98..1297c4d 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -53,7 +53,6 @@
 #include <android-base/unique_fd.h>
 #include <async_safe/log.h>
 #include <bionic/reserved_signals.h>
-#include <cutils/properties.h>
 
 #include <libdebuggerd/utility.h>
 
diff --git a/debuggerd/tombstoned/intercept_manager.cpp b/debuggerd/tombstoned/intercept_manager.cpp
index 7d25c50..6cbf12c 100644
--- a/debuggerd/tombstoned/intercept_manager.cpp
+++ b/debuggerd/tombstoned/intercept_manager.cpp
@@ -27,7 +27,6 @@
 #include <android-base/cmsg.h>
 #include <android-base/logging.h>
 #include <android-base/unique_fd.h>
-#include <cutils/sockets.h>
 
 #include "protocol.h"
 #include "util.h"
diff --git a/debuggerd/util.cpp b/debuggerd/util.cpp
index 9d09210..f3bff8c 100644
--- a/debuggerd/util.cpp
+++ b/debuggerd/util.cpp
@@ -16,7 +16,6 @@
 
 #include "util.h"
 
-#include <sys/socket.h>
 #include <time.h>
 
 #include <string>
@@ -25,7 +24,6 @@
 #include <android-base/file.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <cutils/sockets.h>
 #include "protocol.h"
 
 std::string get_process_name(pid_t pid) {
diff --git a/deprecated-adf/OWNERS b/deprecated-adf/OWNERS
deleted file mode 100644
index 72b8b5a..0000000
--- a/deprecated-adf/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-ghackmann@google.com
-marissaw@google.com
diff --git a/deprecated-adf/libadf/Android.bp b/deprecated-adf/libadf/Android.bp
deleted file mode 100644
index 70f0a3b..0000000
--- a/deprecated-adf/libadf/Android.bp
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (C) 2013 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.
-
-cc_library {
-    name: "libadf",
-    recovery_available: true,
-    vendor_available: true,
-    vndk: {
-        enabled: true,
-    },
-    srcs: ["adf.cpp"],
-    cflags: ["-Werror"],
-    local_include_dirs: ["include"],
-    export_include_dirs: ["include"],
-}
diff --git a/deprecated-adf/libadf/adf.cpp b/deprecated-adf/libadf/adf.cpp
deleted file mode 100644
index fd9c208..0000000
--- a/deprecated-adf/libadf/adf.cpp
+++ /dev/null
@@ -1,746 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <malloc.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <algorithm>
-#include <memory>
-#include <vector>
-
-#include <linux/limits.h>
-
-#include <sys/ioctl.h>
-
-#include <adf/adf.h>
-
-#define ADF_BASE_PATH "/dev/"
-
-static ssize_t adf_id_vector_to_array(const std::vector<adf_id_t> &in,
-        adf_id_t **out)
-{
-    auto size = sizeof(in[0]) * in.size();
-    // We can't use new[] since the existing API says the caller should free()
-    // the returned array
-    auto ret = static_cast<adf_id_t *>(malloc(size));
-    if (!ret)
-        return -ENOMEM;
-
-    std::copy(in.begin(), in.end(), ret);
-    *out = ret;
-    return in.size();
-}
-
-static ssize_t adf_find_nodes(const char *pattern, adf_id_t **ids_out)
-{
-    struct dirent *dirent;
-    std::unique_ptr<DIR, decltype(&closedir)>
-        dir{opendir(ADF_BASE_PATH), closedir};
-    if (!dir)
-        return -errno;
-
-    std::vector<adf_id_t> ids;
-    errno = 0;
-    while ((dirent = readdir(dir.get()))) {
-        adf_id_t id;
-        int matched = sscanf(dirent->d_name, pattern, &id);
-
-        if (matched < 0)
-            return -errno;
-        else if (matched == 1)
-            ids.push_back(id);
-    }
-    if (errno)
-        return -errno;
-
-    return adf_id_vector_to_array(ids, ids_out);
-}
-
-ssize_t adf_devices(adf_id_t **ids)
-{
-    return adf_find_nodes("adf%u", ids);
-}
-
-int adf_device_open(adf_id_t id, int flags, struct adf_device *dev)
-{
-    char filename[64];
-
-    dev->id = id;
-
-    snprintf(filename, sizeof(filename), ADF_BASE_PATH "adf%u", id);
-    dev->fd = open(filename, flags);
-    if (dev->fd < 0)
-        return -errno;
-
-    return 0;
-}
-
-void adf_device_close(struct adf_device *dev)
-{
-    if (dev->fd >= 0)
-        close(dev->fd);
-}
-
-int adf_get_device_data(struct adf_device *dev, struct adf_device_data *data)
-{
-    int err;
-    int ret = 0;
-
-    memset(data, 0, sizeof(*data));
-
-    err = ioctl(dev->fd, ADF_GET_DEVICE_DATA, data);
-    if (err < 0)
-        return -ENOMEM;
-
-    if (data->n_attachments)
-        data->attachments = new adf_attachment_config[data->n_attachments];
-
-    if (data->n_allowed_attachments)
-        data->allowed_attachments =
-                new adf_attachment_config[data->n_allowed_attachments];
-
-    if (data->custom_data_size)
-        data->custom_data = new char[data->custom_data_size];
-
-    err = ioctl(dev->fd, ADF_GET_DEVICE_DATA, data);
-    if (err < 0) {
-        ret = -errno;
-        adf_free_device_data(data);
-    }
-    return ret;
-}
-
-void adf_free_device_data(struct adf_device_data *data)
-{
-    delete [] data->attachments;
-    data->attachments = nullptr;
-    delete [] data->allowed_attachments;
-    data->allowed_attachments = nullptr;
-    delete [] static_cast<char *>(data->custom_data);
-    data->custom_data = nullptr;
-}
-
-int adf_device_post(struct adf_device *dev,
-        adf_id_t *interfaces, size_t n_interfaces,
-        struct adf_buffer_config *bufs, size_t n_bufs,
-        void *custom_data, size_t custom_data_size)
-{
-    int err;
-    struct adf_post_config data;
-
-    memset(&data, 0, sizeof(data));
-    data.interfaces = interfaces;
-    data.n_interfaces = n_interfaces;
-    data.bufs = bufs;
-    data.n_bufs = n_bufs;
-    data.custom_data = custom_data;
-    data.custom_data_size = custom_data_size;
-
-    err = ioctl(dev->fd, ADF_POST_CONFIG, &data);
-    if (err < 0)
-        return -errno;
-
-    return (int)data.complete_fence;
-}
-
-int adf_device_post_v2(struct adf_device *dev,
-        adf_id_t *interfaces, __u32 n_interfaces,
-        struct adf_buffer_config *bufs, __u32 n_bufs,
-        void *custom_data, __u64 custom_data_size,
-        enum adf_complete_fence_type complete_fence_type,
-        int *complete_fence)
-{
-    int err;
-    struct adf_post_config_v2 data;
-
-    memset(&data, 0, sizeof(data));
-    data.interfaces = (uintptr_t)interfaces;
-    data.n_interfaces = n_interfaces;
-    data.bufs = (uintptr_t)bufs;
-    data.n_bufs = n_bufs;
-    data.custom_data = (uintptr_t)custom_data;
-    data.custom_data_size = custom_data_size;
-    data.complete_fence_type = complete_fence_type;
-
-    err = ioctl(dev->fd, ADF_POST_CONFIG_V2, &data);
-    if (err < 0)
-        return -errno;
-
-    if (complete_fence)
-        *complete_fence = data.complete_fence;
-    else if (data.complete_fence >= 0)
-        close(data.complete_fence);
-
-    return 0;
-}
-
-static int adf_device_attachment(struct adf_device *dev,
-        adf_id_t overlay_engine, adf_id_t interface, bool attach)
-{
-    int err;
-    struct adf_attachment_config data;
-
-    memset(&data, 0, sizeof(data));
-    data.overlay_engine = overlay_engine;
-    data.interface = interface;
-
-    err = ioctl(dev->fd, attach ? ADF_ATTACH : ADF_DETACH, &data);
-    if (err < 0)
-        return -errno;
-
-    return 0;
-}
-
-int adf_device_attach(struct adf_device *dev, adf_id_t overlay_engine,
-                      adf_id_t interface)
-{
-   return adf_device_attachment(dev, overlay_engine, interface, true);
-}
-
-int adf_device_detach(struct adf_device *dev, adf_id_t overlay_engine,
-                      adf_id_t interface)
-{
-   return adf_device_attachment(dev, overlay_engine, interface, false);
-}
-
-ssize_t adf_interfaces(struct adf_device *dev, adf_id_t **interfaces)
-{
-    char pattern[64];
-
-    snprintf(pattern, sizeof(pattern), "adf-interface%u.%%u", dev->id);
-    return adf_find_nodes(pattern, interfaces);
-}
-
-ssize_t adf_interfaces_for_overlay_engine(struct adf_device *dev,
-        adf_id_t overlay_engine, adf_id_t **interfaces)
-{
-    struct adf_device_data data;
-    auto err = adf_get_device_data(dev, &data);
-    if (err < 0)
-        return err;
-
-    std::vector<adf_id_t> ids;
-    if (data.allowed_attachments != nullptr)
-        for (size_t i = 0; i < data.n_allowed_attachments; i++)
-            if (data.allowed_attachments[i].overlay_engine == overlay_engine)
-              ids.push_back(data.allowed_attachments[i].interface);
-
-    adf_free_device_data(&data);
-    return adf_id_vector_to_array(ids, interfaces);
-}
-
-static ssize_t adf_interfaces_filter(struct adf_device *dev,
-        adf_id_t *in, size_t n_in, adf_id_t **out,
-        bool (*filter)(struct adf_interface_data *data, __u32 match),
-        __u32 match)
-{
-    std::vector<adf_id_t> ids;
-    for (size_t i = 0; i < n_in; i++) {
-        int fd = adf_interface_open(dev, in[i], O_RDONLY);
-        if (fd < 0)
-            return fd;
-
-        struct adf_interface_data data;
-        auto ret = adf_get_interface_data(fd, &data);
-        close(fd);
-        if (ret < 0)
-            return ret;
-
-        if (filter(&data, match))
-            ids.push_back(in[i]);
-    }
-
-    return adf_id_vector_to_array(ids, out);
-}
-
-static bool adf_interface_type_filter(struct adf_interface_data *data,
-        __u32 type)
-{
-    return data->type == (enum adf_interface_type)type;
-}
-
-ssize_t adf_interfaces_filter_by_type(struct adf_device *dev,
-        enum adf_interface_type type,
-        adf_id_t *in, size_t n_in, adf_id_t **out)
-{
-    return adf_interfaces_filter(dev, in, n_in, out, adf_interface_type_filter,
-            type);
-}
-
-static bool adf_interface_flags_filter(struct adf_interface_data *data,
-        __u32 flag)
-{
-    return !!(data->flags & flag);
-}
-
-ssize_t adf_interfaces_filter_by_flag(struct adf_device *dev, __u32 flag,
-        adf_id_t *in, size_t n_in, adf_id_t **out)
-{
-    return adf_interfaces_filter(dev, in, n_in, out, adf_interface_flags_filter,
-            flag);
-}
-
-int adf_interface_open(struct adf_device *dev, adf_id_t id, int flags)
-{
-    char filename[64];
-
-    snprintf(filename, sizeof(filename), ADF_BASE_PATH "adf-interface%u.%u",
-            dev->id, id);
-
-    int fd = open(filename, flags);
-    if (fd < 0)
-        return -errno;
-    return fd;
-}
-
-int adf_get_interface_data(int fd, struct adf_interface_data *data)
-{
-    int err;
-    int ret = 0;
-
-    memset(data, 0, sizeof(*data));
-
-    err = ioctl(fd, ADF_GET_INTERFACE_DATA, data);
-    if (err < 0)
-        return -errno;
-
-    if (data->n_available_modes)
-        data->available_modes = new drm_mode_modeinfo[data->n_available_modes];
-
-    if (data->custom_data_size)
-        data->custom_data = new char[data->custom_data_size];
-
-    err = ioctl(fd, ADF_GET_INTERFACE_DATA, data);
-    if (err < 0) {
-        ret = -errno;
-        adf_free_interface_data(data);
-    }
-    return ret;
-}
-
-void adf_free_interface_data(struct adf_interface_data *data)
-{
-    delete [] data->available_modes;
-    delete [] static_cast<char *>(data->custom_data);
-}
-
-int adf_interface_blank(int fd, __u8 mode)
-{
-    int err = ioctl(fd, ADF_BLANK, mode);
-    if (err < 0)
-        return -errno;
-    return 0;
-}
-
-int adf_interface_set_mode(int fd, struct drm_mode_modeinfo *mode)
-{
-    int err = ioctl(fd, ADF_SET_MODE, mode);
-    if (err < 0)
-        return -errno;
-    return 0;
-}
-
-int adf_interface_simple_buffer_alloc(int fd, __u32 w, __u32 h,
-        __u32 format, __u32 *offset, __u32 *pitch)
-{
-    int err;
-    struct adf_simple_buffer_alloc data;
-
-    memset(&data, 0, sizeof(data));
-    data.w = w;
-    data.h = h;
-    data.format = format;
-
-    err = ioctl(fd, ADF_SIMPLE_BUFFER_ALLOC, &data);
-    if (err < 0)
-        return -errno;
-
-    *offset = data.offset;
-    *pitch = data.pitch;
-    return (int)data.fd;
-}
-
-static void adf_interface_simple_post_config_buf(struct adf_buffer_config *buf,
-        __u32 overlay_engine, __u32 w, __u32 h, __u32 format, int buf_fd,
-        __u32 offset, __u32 pitch, int acquire_fence)
-{
-    buf->overlay_engine = overlay_engine;
-    buf->w = w;
-    buf->h = h;
-    buf->format = format;
-    buf->fd[0] = buf_fd;
-    buf->offset[0] = offset;
-    buf->pitch[0] = pitch;
-    buf->n_planes = 1;
-    buf->acquire_fence = acquire_fence;
-}
-
-int adf_interface_simple_post(int fd, __u32 overlay_engine,
-        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
-        __u32 pitch, int acquire_fence)
-{
-    int ret;
-    struct adf_simple_post_config data;
-
-    memset(&data, 0, sizeof(data));
-    adf_interface_simple_post_config_buf(&data.buf, overlay_engine, w, h, format,
-            buf_fd, offset, pitch, acquire_fence);
-    ret = ioctl(fd, ADF_SIMPLE_POST_CONFIG, &data);
-    if (ret < 0)
-        return -errno;
-
-    return (int)data.complete_fence;
-}
-
-int adf_interface_simple_post_v2(int fd, adf_id_t overlay_engine,
-        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
-        __u32 pitch, int acquire_fence,
-        enum adf_complete_fence_type complete_fence_type,
-        int *complete_fence)
-{
-    int ret;
-    struct adf_simple_post_config_v2 data;
-
-    memset(&data, 0, sizeof(data));
-    adf_interface_simple_post_config_buf(&data.buf, overlay_engine, w, h, format,
-            buf_fd, offset, pitch, acquire_fence);
-    data.complete_fence_type = complete_fence_type;
-
-    ret = ioctl(fd, ADF_SIMPLE_POST_CONFIG_V2, &data);
-    if (ret < 0)
-        return -errno;
-
-    if (complete_fence)
-        *complete_fence = data.complete_fence;
-    else if (data.complete_fence >= 0)
-        close(data.complete_fence);
-
-    return 0;
-}
-
-ssize_t adf_overlay_engines(struct adf_device *dev, adf_id_t **overlay_engines)
-{
-    char pattern[64];
-
-    snprintf(pattern, sizeof(pattern), "adf-overlay-engine%u.%%u", dev->id);
-    return adf_find_nodes(pattern, overlay_engines);
-}
-
-ssize_t adf_overlay_engines_for_interface(struct adf_device *dev,
-        adf_id_t interface, adf_id_t **overlay_engines)
-{
-    struct adf_device_data data;
-    auto err = adf_get_device_data(dev, &data);
-    if (err < 0)
-        return err;
-
-    std::vector<adf_id_t> ids;
-    if (data.allowed_attachments != nullptr)
-        for (size_t i = 0; i < data.n_allowed_attachments; i++)
-            if (data.allowed_attachments[i].interface == interface)
-                ids.push_back(data.allowed_attachments[i].overlay_engine);
-
-    return adf_id_vector_to_array(ids, overlay_engines);
-}
-
-static ssize_t adf_overlay_engines_filter(struct adf_device *dev,
-        adf_id_t *in, size_t n_in, adf_id_t **out,
-        bool (*filter)(struct adf_overlay_engine_data *data, void *cookie),
-        void *cookie)
-{
-    std::vector<adf_id_t> ids;
-    size_t i;
-    for (i = 0; i < n_in; i++) {
-        int fd = adf_overlay_engine_open(dev, in[i], O_RDONLY);
-        if (fd < 0)
-            return fd;
-
-        struct adf_overlay_engine_data data;
-        auto ret = adf_get_overlay_engine_data(fd, &data);
-        close(fd);
-        if (ret < 0)
-            return ret;
-
-        if (filter(&data, cookie))
-            ids.push_back(in[i]);
-    }
-
-    return adf_id_vector_to_array(ids, out);
-}
-
-struct format_filter_cookie {
-    const __u32 *formats;
-    size_t n_formats;
-};
-
-static bool adf_overlay_engine_format_filter(
-        struct adf_overlay_engine_data *data, void *cookie)
-{
-    auto c = static_cast<format_filter_cookie *>(cookie);
-    size_t i;
-    for (i = 0; i < data->n_supported_formats; i++) {
-        size_t j;
-        for (j = 0; j < c->n_formats; j++)
-            if (data->supported_formats[i] == c->formats[j])
-                return true;
-    }
-    return false;
-}
-
-ssize_t adf_overlay_engines_filter_by_format(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats, adf_id_t *in, size_t n_in,
-        adf_id_t **out)
-{
-    struct format_filter_cookie cookie = { formats, n_formats };
-    return adf_overlay_engines_filter(dev, in, n_in, out,
-            adf_overlay_engine_format_filter, &cookie);
-}
-
-int adf_overlay_engine_open(struct adf_device *dev, adf_id_t id, int flags)
-{
-    char filename[64];
-
-    snprintf(filename, sizeof(filename),
-            ADF_BASE_PATH "adf-overlay-engine%u.%u", dev->id, id);
-
-    int fd = open(filename, flags);
-    if (fd < 0)
-        return -errno;
-    return fd;
-}
-
-int adf_get_overlay_engine_data(int fd, struct adf_overlay_engine_data *data)
-{
-    int err;
-    int ret = 0;
-
-    memset(data, 0, sizeof(*data));
-
-    err = ioctl(fd, ADF_GET_OVERLAY_ENGINE_DATA, data);
-    if (err < 0)
-        return -errno;
-
-    if (data->n_supported_formats)
-        data->supported_formats = new __u32[data->n_supported_formats];
-
-    if (data->custom_data_size)
-      data->custom_data = new char[data->custom_data_size];
-
-    err = ioctl(fd, ADF_GET_OVERLAY_ENGINE_DATA, data);
-    if (err < 0) {
-        ret = -errno;
-        adf_free_overlay_engine_data(data);
-    }
-    return ret;
-}
-
-void adf_free_overlay_engine_data(struct adf_overlay_engine_data *data)
-{
-    delete [] data->supported_formats;
-    data->supported_formats = nullptr;
-    delete [] static_cast<char *>(data->custom_data);
-    data->custom_data = nullptr;
-}
-
-bool adf_overlay_engine_supports_format(int fd, __u32 format)
-{
-    struct adf_overlay_engine_data data;
-    bool ret = false;
-    size_t i;
-
-    int err = adf_get_overlay_engine_data(fd, &data);
-    if (err < 0)
-        return false;
-
-    if (data.supported_formats != nullptr) {
-        for (i = 0; i < data.n_supported_formats; i++) {
-            if (data.supported_formats[i] == format) {
-                ret = true;
-                break;
-            }
-        }
-    }
-
-    adf_free_overlay_engine_data(&data);
-    return ret;
-}
-
-int adf_set_event(int fd, enum adf_event_type type, bool enabled)
-{
-    struct adf_set_event data;
-
-    data.type = type;
-    data.enabled = enabled;
-
-    int err = ioctl(fd, ADF_SET_EVENT, &data);
-    if (err < 0)
-        return -errno;
-    return 0;
-}
-
-int adf_read_event(int fd, struct adf_event **event)
-{
-    struct adf_event header;
-    struct event_with_data {
-        struct adf_event base;
-        uint8_t data[0];
-    };
-    using unique_event = std::unique_ptr<event_with_data, decltype(&free)>;
-    size_t data_size;
-
-    int err = read(fd, &header, sizeof(header));
-    if (err < 0)
-        return -errno;
-    if ((size_t)err < sizeof(header))
-        return -EIO;
-    if (header.length < sizeof(header))
-        return -EIO;
-
-    // Again, we can't use new[] since the existing API says the caller should
-    // free() the returned event
-    auto event_ptr = static_cast<event_with_data *>(malloc(header.length));
-    unique_event event_ret{event_ptr, free};
-    if (!event_ret)
-        return -ENOMEM;
-    data_size = header.length - sizeof(header);
-
-    memcpy(event_ret.get(), &header, sizeof(header));
-    ssize_t read_size = read(fd, &event_ret->data, data_size);
-    if (read_size < 0)
-        return -errno;
-    if ((size_t)read_size < data_size)
-        return -EIO;
-
-    *event = &event_ret.release()->base;
-    return 0;
-}
-
-void adf_format_str(__u32 format, char buf[ADF_FORMAT_STR_SIZE])
-{
-    buf[0] = format & 0xFF;
-    buf[1] = (format >> 8) & 0xFF;
-    buf[2] = (format >> 16) & 0xFF;
-    buf[3] = (format >> 24) & 0xFF;
-    buf[4] = '\0';
-}
-
-static bool adf_find_simple_post_overlay_engine(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats,
-        adf_id_t interface, adf_id_t *overlay_engine)
-{
-    adf_id_t *engs = nullptr;
-    ssize_t n_engs = adf_overlay_engines_for_interface(dev, interface, &engs);
-
-    if (engs == nullptr)
-        return false;
-
-    adf_id_t *filtered_engs = nullptr;
-    ssize_t n_filtered_engs = adf_overlay_engines_filter_by_format(dev,
-            formats, n_formats, engs, n_engs, &filtered_engs);
-    free(engs);
-
-    if (filtered_engs == nullptr)
-        return false;
-
-    *overlay_engine = filtered_engs[0];
-    free(filtered_engs);
-    return true;
-}
-
-static const __u32 any_rgb_format[] = {
-    DRM_FORMAT_C8,
-    DRM_FORMAT_RGB332,
-    DRM_FORMAT_BGR233,
-    DRM_FORMAT_XRGB1555,
-    DRM_FORMAT_XBGR1555,
-    DRM_FORMAT_RGBX5551,
-    DRM_FORMAT_BGRX5551,
-    DRM_FORMAT_ARGB1555,
-    DRM_FORMAT_ABGR1555,
-    DRM_FORMAT_RGBA5551,
-    DRM_FORMAT_BGRA5551,
-    DRM_FORMAT_RGB565,
-    DRM_FORMAT_BGR565,
-    DRM_FORMAT_RGB888,
-    DRM_FORMAT_BGR888,
-    DRM_FORMAT_XRGB8888,
-    DRM_FORMAT_XBGR8888,
-    DRM_FORMAT_RGBX8888,
-    DRM_FORMAT_BGRX8888,
-    DRM_FORMAT_XRGB2101010,
-    DRM_FORMAT_XBGR2101010,
-    DRM_FORMAT_RGBX1010102,
-    DRM_FORMAT_BGRX1010102,
-    DRM_FORMAT_ARGB2101010,
-    DRM_FORMAT_ABGR2101010,
-    DRM_FORMAT_RGBA1010102,
-    DRM_FORMAT_BGRA1010102,
-    DRM_FORMAT_ARGB8888,
-    DRM_FORMAT_ABGR8888,
-    DRM_FORMAT_RGBA8888,
-    DRM_FORMAT_BGRA8888,
-};
-
-int adf_find_simple_post_configuration(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats,
-        adf_id_t *interface, adf_id_t *overlay_engine)
-{
-    adf_id_t *intfs = NULL;
-    ssize_t n_intfs = adf_interfaces(dev, &intfs);
-
-    if (n_intfs < 0)
-        return n_intfs;
-    else if (!intfs)
-        return -ENODEV;
-
-    adf_id_t *primary_intfs = nullptr;
-    ssize_t n_primary_intfs = adf_interfaces_filter_by_flag(dev,
-            ADF_INTF_FLAG_PRIMARY, intfs, n_intfs, &primary_intfs);
-    free(intfs);
-
-    if (n_primary_intfs < 0)
-        return n_primary_intfs;
-    else if (!primary_intfs)
-        return -ENODEV;
-
-    if (!formats) {
-        formats = any_rgb_format;
-        n_formats = sizeof(any_rgb_format) / sizeof(any_rgb_format[0]);
-    }
-
-    bool found = false;
-    ssize_t i = 0;
-    for (i = 0; i < n_primary_intfs; i++) {
-        found = adf_find_simple_post_overlay_engine(dev, formats, n_formats,
-                primary_intfs[i], overlay_engine);
-        if (found) {
-            *interface = primary_intfs[i];
-            break;
-        }
-    }
-    free(primary_intfs);
-
-    if (!found)
-        return -ENODEV;
-
-    return 0;
-}
diff --git a/deprecated-adf/libadf/include/adf/adf.h b/deprecated-adf/libadf/include/adf/adf.h
deleted file mode 100644
index e4c7b28..0000000
--- a/deprecated-adf/libadf/include/adf/adf.h
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * Copyright (C) 2013 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 _LIBADF_ADF_H_
-#define _LIBADF_ADF_H_
-
-#include <stdint.h>
-#include <stdbool.h>
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <video/adf.h>
-
-typedef __u32 adf_id_t;
-
-struct adf_device {
-    adf_id_t id;
-    int fd;
-};
-
-__BEGIN_DECLS
-
-/**
- * Enumerates all ADF devices.
- *
- * Returns the number of ADF devices, and sets ids to a list of device IDs.
- * The caller must free() the returned list of device IDs.
- *
- * On error, returns -errno.
- */
-ssize_t adf_devices(adf_id_t **ids);
-
-/**
- * Opens an ADF device.
- *
- * On error, returns -errno.
- */
-int adf_device_open(adf_id_t id, int flags, struct adf_device *dev);
-/**
- * Closes an ADF device.
- */
-void adf_device_close(struct adf_device *dev);
-/**
- * Reads the ADF device data.
- *
- * adf_get_device_data() allocates buffers inside data, which the caller
- * must free by calling adf_free_device_data().  On error, returns -errno.
- */
-int adf_get_device_data(struct adf_device *dev, struct adf_device_data *data);
-/**
- * Frees the device data returned by adf_get_device_data().
- */
-void adf_free_device_data(struct adf_device_data *data);
-
-/**
- * Atomically posts a new display configuration to the specified interfaces.
- *
- * Returns a sync fence fd that will fire when the configuration is removed
- * from the screen.  On error, returns -errno.
- */
-int adf_device_post(struct adf_device *dev,
-        adf_id_t *interfaces, size_t n_interfaces,
-        struct adf_buffer_config *bufs, size_t n_bufs,
-        void *custom_data, size_t custom_data_size);
-/**
- * Atomically posts a new display configuration to the specified interfaces.
- *
- * Compared to adf_device_post(), adf_device_post_v2():
- *
- *  (*) allows the client to choose the kind of sync fence returned
- *      (through complete_fence_type)
- *
- *  (*) stores the returned sync fence fd in a provided buffer, so the client
- *      can distinguish between a permission error (ret = -1) and a successful
- *      call that returns no fence (*complete_fence = -1)
- *
- * On error, returns -errno.
- *
- * On devices without the corresponding kernel support, returns -ENOTTY.
- */
-int adf_device_post_v2(struct adf_device *dev,
-        adf_id_t *interfaces, __u32 n_interfaces,
-        struct adf_buffer_config *bufs, __u32 n_bufs,
-        void *custom_data, __u64 custom_data_size,
-        enum adf_complete_fence_type complete_fence_type,
-        int *complete_fence);
-
-/**
- * Attaches the specified interface and overlay engine.
- */
-int adf_device_attach(struct adf_device *dev, adf_id_t overlay_engine,
-                      adf_id_t interface);
-/**
- * Detaches the specified interface and overlay engine.
- */
-int adf_device_detach(struct adf_device *dev, adf_id_t overlay_engine,
-                      adf_id_t interface);
-
-/**
- * Enumerates all interfaces belonging to an ADF device.
- *
- * The caller must free() the returned list of interface IDs.
- */
-ssize_t adf_interfaces(struct adf_device *dev, adf_id_t **interfaces);
-
-/**
- * Enumerates all interfaces which can be attached to the specified overlay
- * engine.
- *
- * The caller must free() the returned list of interface IDs.
- */
-ssize_t adf_interfaces_for_overlay_engine(struct adf_device *dev,
-        adf_id_t overlay_engine, adf_id_t **interfaces);
-/**
- * Filters a list of interfaces by type.
- *
- * Returns the number of matching interfaces, and sets out to a list of matching
- * interface IDs.  The caller must free() the returned list of interface IDs.
- *
- * On error, returns -errno.
- */
-ssize_t adf_interfaces_filter_by_type(struct adf_device *dev,
-        enum adf_interface_type type,
-        adf_id_t *in, size_t n_in, adf_id_t **out);
-/**
- * Filters a list of interfaces by flag.
- *
- * The caller must free() the returned list of interface IDs.
- */
-ssize_t adf_interfaces_filter_by_flag(struct adf_device *dev, __u32 flag,
-        adf_id_t *in, size_t n_in, adf_id_t **out);
-
-/**
- * Opens an ADF interface.
- *
- * Returns a file descriptor.  The caller must close() the fd when done.
- * On error, returns -errno.
- */
-int adf_interface_open(struct adf_device *dev, adf_id_t id, int flags);
-/**
- * Reads the interface data.
- *
- * adf_get_interface_data() allocates buffers inside data, which the caller
- * must free by calling adf_free_interface_data().  On error, returns -errno.
- */
-int adf_get_interface_data(int fd, struct adf_interface_data *data);
-/**
- * Frees the interface data returned by adf_get_interface_data().
- */
-void adf_free_interface_data(struct adf_interface_data *data);
-
-/**
- * Sets the interface's DPMS mode.
- */
-int adf_interface_blank(int fd, __u8 mode);
-/**
- * Sets the interface's display mode.
- */
-int adf_interface_set_mode(int fd, struct drm_mode_modeinfo *mode);
-/**
- * Allocates a single-plane RGB buffer of the specified size and format.
- *
- * Returns a dma-buf fd.  On error, returns -errno.
- */
-int adf_interface_simple_buffer_alloc(int fd, __u32 w, __u32 h,
-        __u32 format, __u32 *offset, __u32 *pitch);
-/**
- * Posts a single-plane RGB buffer to the display using the specified
- * overlay engine.
- *
- * Returns a sync fence fd that will fire when the buffer is removed
- * from the screen.  On error, returns -errno.
- */
-int adf_interface_simple_post(int fd, adf_id_t overlay_engine,
-        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
-        __u32 pitch, int acquire_fence);
-/**
- * Posts a single-plane RGB buffer to the display using the specified
- * overlay engine.
- *
- * Compared to adf_interface_simple_post(), adf_interface_simple_post_v2():
- *
- *  (*) allows the client to choose the kind of sync fence returned
- *      (through complete_fence_type)
- *
- *  (*) stores the returned sync fence fd in a provided buffer, so the client
- *      can distinguish between a permission error (ret = -1) and a successful
- *      call that returns no fence (*complete_fence = -1)
- *
- * On error, returns -errno.
- *
- * On devices without the corresponding kernel support, returns -ENOTTY.
- */
-int adf_interface_simple_post_v2(int fd, adf_id_t overlay_engine,
-        __u32 w, __u32 h, __u32 format, int buf_fd, __u32 offset,
-        __u32 pitch, int acquire_fence,
-        enum adf_complete_fence_type complete_fence_type,
-        int *complete_fence);
-
-/**
- * Enumerates all overlay engines belonging to an ADF device.
- *
- * The caller must free() the returned list of overlay engine IDs.
- */
-ssize_t adf_overlay_engines(struct adf_device *dev, adf_id_t **overlay_engines);
-
-/**
- * Enumerates all overlay engines which can be attached to the specified
- * interface.
- *
- * The caller must free() the returned list of overlay engine IDs.
- */
-ssize_t adf_overlay_engines_for_interface(struct adf_device *dev,
-        adf_id_t interface, adf_id_t **overlay_engines);
-/**
- * Filters a list of overlay engines by supported buffer format.
- *
- * Returns the overlay engines which support at least one of the specified
- * formats.  The caller must free() the returned list of overlay engine IDs.
- */
-ssize_t adf_overlay_engines_filter_by_format(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats, adf_id_t *in, size_t n_in,
-        adf_id_t **out);
-
-/**
- * Opens an ADF overlay engine.
- *
- * Returns a file descriptor.  The caller must close() the fd when done.
- * On error, returns -errno.
- */
-int adf_overlay_engine_open(struct adf_device *dev, adf_id_t id, int flags);
-/**
- * Reads the overlay engine data.
- *
- * adf_get_overlay_engine_data() allocates buffers inside data, which the caller
- * must free by calling adf_free_overlay_engine_data().  On error, returns
- * -errno.
- */
-int adf_get_overlay_engine_data(int fd, struct adf_overlay_engine_data *data);
-/**
- * Frees the overlay engine data returned by adf_get_overlay_engine_data().
- */
-void adf_free_overlay_engine_data(struct adf_overlay_engine_data *data);
-
-/**
- * Returns whether the overlay engine supports the specified format.
- */
-bool adf_overlay_engine_supports_format(int fd, __u32 format);
-
-/**
- * Subscribes or unsubscribes from the specified hardware event.
- */
-int adf_set_event(int fd, enum adf_event_type type, bool enabled);
-/**
- * Reads one event from the fd, blocking if needed.
- *
- * The caller must free() the returned buffer.  On error, returns -errno.
- */
-int adf_read_event(int fd, struct adf_event **event);
-
-#define ADF_FORMAT_STR_SIZE 5
-/**
- * Converts an ADF/DRM fourcc format to its string representation.
- */
-void adf_format_str(__u32 format, char buf[ADF_FORMAT_STR_SIZE]);
-
-/**
- * Finds an appropriate interface and overlay engine for a simple post.
- *
- * Specifically, finds the primary interface, and an overlay engine
- * that can be attached to the primary interface and supports one of the
- * specified formats.  The caller may pass a NULL formats list, to indicate that
- * any RGB format is acceptable.
- *
- * On error, returns -errno.
- */
-int adf_find_simple_post_configuration(struct adf_device *dev,
-        const __u32 *formats, size_t n_formats,
-        adf_id_t *interface, adf_id_t *overlay_engine);
-
-__END_DECLS
-
-#endif /* _LIBADF_ADF_H_ */
diff --git a/deprecated-adf/libadf/include/video/adf.h b/deprecated-adf/libadf/include/video/adf.h
deleted file mode 100644
index 692a425..0000000
--- a/deprecated-adf/libadf/include/video/adf.h
+++ /dev/null
@@ -1,209 +0,0 @@
-/****************************************************************************
- ****************************************************************************
- ***
- ***   This header was automatically generated from a Linux kernel header
- ***   of the same name, to make information necessary for userspace to
- ***   call into the kernel available to libc.  It contains only constants,
- ***   structures, and macros generated from the original header, and thus,
- ***   contains no copyrightable information.
- ***
- ***   To edit the content of this header, modify the corresponding
- ***   source file (e.g. under external/kernel-headers/original/) then
- ***   run bionic/libc/kernel/tools/update_all.py
- ***
- ***   Any manual change here will be lost the next time this script will
- ***   be run. You've been warned!
- ***
- ****************************************************************************
- ****************************************************************************/
-#ifndef _UAPI_VIDEO_ADF_H_
-#define _UAPI_VIDEO_ADF_H_
-#include <linux/ioctl.h>
-#include <linux/types.h>
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#include <drm/drm_fourcc.h>
-#include <drm/drm_mode.h>
-#define ADF_NAME_LEN 32
-#define ADF_MAX_CUSTOM_DATA_SIZE 4096
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-enum adf_interface_type {
-  ADF_INTF_DSI = 0,
-  ADF_INTF_eDP = 1,
-  ADF_INTF_DPI = 2,
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  ADF_INTF_VGA = 3,
-  ADF_INTF_DVI = 4,
-  ADF_INTF_HDMI = 5,
-  ADF_INTF_MEMORY = 6,
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  ADF_INTF_TYPE_DEVICE_CUSTOM = 128,
-  ADF_INTF_TYPE_MAX = (~(__u32) 0),
-};
-#define ADF_INTF_FLAG_PRIMARY (1 << 0)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_INTF_FLAG_EXTERNAL (1 << 1)
-enum adf_event_type {
-  ADF_EVENT_VSYNC = 0,
-  ADF_EVENT_HOTPLUG = 1,
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  ADF_EVENT_DEVICE_CUSTOM = 128,
-  ADF_EVENT_TYPE_MAX = 255,
-};
-enum adf_complete_fence_type {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  ADF_COMPLETE_FENCE_NONE = 0,
-  ADF_COMPLETE_FENCE_PRESENT = 1,
-  ADF_COMPLETE_FENCE_RELEASE = 2,
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct adf_set_event {
-  __u8 type;
-  __u8 enabled;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct adf_event {
-  __u8 type;
-  __u32 length;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct adf_vsync_event {
-  struct adf_event base;
-  __aligned_u64 timestamp;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct adf_hotplug_event {
-  struct adf_event base;
-  __u8 connected;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_MAX_PLANES 4
-struct adf_buffer_config {
-  __u32 overlay_engine;
-  __u32 w;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u32 h;
-  __u32 format;
-  __s32 fd[ADF_MAX_PLANES];
-  __u32 offset[ADF_MAX_PLANES];
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u32 pitch[ADF_MAX_PLANES];
-  __u8 n_planes;
-  __s32 acquire_fence;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_MAX_BUFFERS (4096 / sizeof(struct adf_buffer_config))
-struct adf_post_config {
-  size_t n_interfaces;
-  __u32 __user * interfaces;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  size_t n_bufs;
-  struct adf_buffer_config __user * bufs;
-  size_t custom_data_size;
-  void __user * custom_data;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __s32 complete_fence;
-};
-struct adf_post_config_v2 {
-  __u32 n_interfaces;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u64 interfaces;
-  __u32 n_bufs;
-  __u64 bufs;
-  __u64 custom_data_size;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u64 custom_data;
-  __s32 complete_fence;
-  __u8 complete_fence_type;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_MAX_INTERFACES (4096 / sizeof(__u32))
-struct adf_simple_buffer_alloc {
-  __u16 w;
-  __u16 h;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u32 format;
-  __s32 fd;
-  __u32 offset;
-  __u32 pitch;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-};
-struct adf_simple_post_config {
-  struct adf_buffer_config buf;
-  __s32 complete_fence;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-};
-struct adf_simple_post_config_v2 {
-  struct adf_buffer_config buf;
-  __s32 complete_fence;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u8 complete_fence_type;
-};
-struct adf_attachment_config {
-  __u32 overlay_engine;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u32 interface;
-};
-struct adf_device_data {
-  char name[ADF_NAME_LEN];
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  size_t n_attachments;
-  struct adf_attachment_config __user * attachments;
-  size_t n_allowed_attachments;
-  struct adf_attachment_config __user * allowed_attachments;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  size_t custom_data_size;
-  void __user * custom_data;
-};
-#define ADF_MAX_ATTACHMENTS (4096 / sizeof(struct adf_attachment_config))
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct adf_interface_data {
-  char name[ADF_NAME_LEN];
-  __u32 type;
-  __u32 id;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u32 flags;
-  __u8 dpms_state;
-  __u8 hotplug_detect;
-  __u16 width_mm;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  __u16 height_mm;
-  struct drm_mode_modeinfo current_mode;
-  size_t n_available_modes;
-  struct drm_mode_modeinfo __user * available_modes;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  size_t custom_data_size;
-  void __user * custom_data;
-};
-#define ADF_MAX_MODES (4096 / sizeof(struct drm_mode_modeinfo))
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct adf_overlay_engine_data {
-  char name[ADF_NAME_LEN];
-  size_t n_supported_formats;
-  __u32 __user * supported_formats;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-  size_t custom_data_size;
-  void __user * custom_data;
-};
-#define ADF_MAX_SUPPORTED_FORMATS (4096 / sizeof(__u32))
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_IOCTL_TYPE 'D'
-#define ADF_IOCTL_NR_CUSTOM 128
-#define ADF_SET_EVENT _IOW(ADF_IOCTL_TYPE, 0, struct adf_set_event)
-#define ADF_BLANK _IOW(ADF_IOCTL_TYPE, 1, __u8)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_POST_CONFIG _IOW(ADF_IOCTL_TYPE, 2, struct adf_post_config)
-#define ADF_SET_MODE _IOW(ADF_IOCTL_TYPE, 3, struct drm_mode_modeinfo)
-#define ADF_GET_DEVICE_DATA _IOR(ADF_IOCTL_TYPE, 4, struct adf_device_data)
-#define ADF_GET_INTERFACE_DATA _IOR(ADF_IOCTL_TYPE, 5, struct adf_interface_data)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_GET_OVERLAY_ENGINE_DATA _IOR(ADF_IOCTL_TYPE, 6, struct adf_overlay_engine_data)
-#define ADF_SIMPLE_POST_CONFIG _IOW(ADF_IOCTL_TYPE, 7, struct adf_simple_post_config)
-#define ADF_SIMPLE_BUFFER_ALLOC _IOW(ADF_IOCTL_TYPE, 8, struct adf_simple_buffer_alloc)
-#define ADF_ATTACH _IOW(ADF_IOCTL_TYPE, 9, struct adf_attachment_config)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ADF_DETACH _IOW(ADF_IOCTL_TYPE, 10, struct adf_attachment_config)
-#define ADF_POST_CONFIG_V2 _IOW(ADF_IOCTL_TYPE, 11, struct adf_post_config_v2)
-#define ADF_SIMPLE_POST_CONFIG_V2 _IOW(ADF_IOCTL_TYPE, 12, struct adf_simple_post_config_v2)
-#endif
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-
diff --git a/deprecated-adf/libadf/original-kernel-headers/video/adf.h b/deprecated-adf/libadf/original-kernel-headers/video/adf.h
deleted file mode 100644
index 8293c1d..0000000
--- a/deprecated-adf/libadf/original-kernel-headers/video/adf.h
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc.
- *
- * This software is licensed under the terms of the GNU General Public
- * License version 2, as published by the Free Software Foundation, and
- * may be copied, distributed, and modified under those terms.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- */
-
-#ifndef _UAPI_VIDEO_ADF_H_
-#define _UAPI_VIDEO_ADF_H_
-
-#include <linux/ioctl.h>
-#include <linux/types.h>
-
-#include <drm/drm_fourcc.h>
-#include <drm/drm_mode.h>
-
-#define ADF_NAME_LEN 32
-#define ADF_MAX_CUSTOM_DATA_SIZE 4096
-
-enum adf_interface_type {
-	ADF_INTF_DSI = 0,
-	ADF_INTF_eDP = 1,
-	ADF_INTF_DPI = 2,
-	ADF_INTF_VGA = 3,
-	ADF_INTF_DVI = 4,
-	ADF_INTF_HDMI = 5,
-	ADF_INTF_MEMORY = 6,
-	ADF_INTF_TYPE_DEVICE_CUSTOM = 128,
-	ADF_INTF_TYPE_MAX = (~(__u32)0),
-};
-
-#define ADF_INTF_FLAG_PRIMARY (1 << 0)
-#define ADF_INTF_FLAG_EXTERNAL (1 << 1)
-
-enum adf_event_type {
-	ADF_EVENT_VSYNC = 0,
-	ADF_EVENT_HOTPLUG = 1,
-	ADF_EVENT_DEVICE_CUSTOM = 128,
-	ADF_EVENT_TYPE_MAX = 255,
-};
-
-enum adf_complete_fence_type {
-	/* no fence */
-	ADF_COMPLETE_FENCE_NONE = 0,
-	/* fence fires when the configuration appears on the screen */
-	ADF_COMPLETE_FENCE_PRESENT = 1,
-	/* fence fires when the configuration leaves the screen */
-	ADF_COMPLETE_FENCE_RELEASE = 2,
-};
-
-/**
- * struct adf_set_event - start or stop subscribing to ADF events
- *
- * @type: the type of event to (un)subscribe
- * @enabled: subscribe or unsubscribe
- *
- * After subscribing to an event, userspace may poll() the ADF object's fd
- * to wait for events or read() to consume the event's data.
- *
- * ADF reserves event types 0 to %ADF_EVENT_DEVICE_CUSTOM-1 for its own events.
- * Devices may use event types %ADF_EVENT_DEVICE_CUSTOM to %ADF_EVENT_TYPE_MAX-1
- * for driver-private events.
- */
-struct adf_set_event {
-	__u8 type;
-	__u8 enabled;
-};
-
-/**
- * struct adf_event - common header for ADF event data
- *
- * @type: event type
- * @length: total size of event data, header inclusive
- */
-struct adf_event {
-	__u8 type;
-	__u32 length;
-};
-
-/**
- * struct adf_vsync_event - ADF vsync event
- *
- * @base: event header (see &struct adf_event)
- * @timestamp: time of vsync event, in nanoseconds
- */
-struct adf_vsync_event {
-	struct adf_event base;
-	__aligned_u64 timestamp;
-};
-
-/**
- * struct adf_vsync_event - ADF display hotplug event
- *
- * @base: event header (see &struct adf_event)
- * @connected: whether a display is now connected to the interface
- */
-struct adf_hotplug_event {
-	struct adf_event base;
-	__u8 connected;
-};
-
-#define ADF_MAX_PLANES 4
-/**
- * struct adf_buffer_config - description of buffer displayed by adf_post_config
- *
- * @overlay_engine: id of the target overlay engine
- * @w: width of display region in pixels
- * @h: height of display region in pixels
- * @format: DRM-style fourcc, see drm_fourcc.h for standard formats
- * @fd: dma_buf fd for each plane
- * @offset: location of first pixel to scan out, in bytes
- * @pitch: stride (i.e. length of a scanline including padding) in bytes
- * @n_planes: number of planes in buffer
- * @acquire_fence: sync_fence fd which will clear when the buffer is
- *	ready for display, or <0 if the buffer is already ready
- */
-struct adf_buffer_config {
-	__u32 overlay_engine;
-
-	__u32 w;
-	__u32 h;
-	__u32 format;
-
-	__s32 fd[ADF_MAX_PLANES];
-	__u32 offset[ADF_MAX_PLANES];
-	__u32 pitch[ADF_MAX_PLANES];
-	__u8 n_planes;
-
-	__s32 acquire_fence;
-};
-#define ADF_MAX_BUFFERS (4096 / sizeof(struct adf_buffer_config))
-
-/**
- * struct adf_post_config - request to flip to a new set of buffers
- *
- * This request is equivalent to &struct adf_post_config_v2 with
- * @complete_fence_type = %ADF_COMPLETE_FENCE_RELEASE.
- *
- * @n_interfaces: number of interfaces targeted by the flip (input)
- * @interfaces: ids of interfaces targeted by the flip (input)
- * @n_bufs: number of buffers displayed (input)
- * @bufs: description of buffers displayed (input)
- * @custom_data_size: size of driver-private data (input)
- * @custom_data: driver-private data (input)
- * @complete_fence: sync_fence fd which will clear when this
- *	configuration has left the screen (output)
- */
-struct adf_post_config {
-	size_t n_interfaces;
-	__u32 __user *interfaces;
-
-	size_t n_bufs;
-	struct adf_buffer_config __user *bufs;
-
-	size_t custom_data_size;
-	void __user *custom_data;
-
-	__s32 complete_fence;
-};
-
-/**
- * struct adf_post_config_v2 - request to flip to a new set of buffers
- *
- * @n_interfaces: number of interfaces targeted by the flip (input)
- * @interfaces: ids of interfaces targeted by the flip (input)
- * @n_bufs: number of buffers displayed (input)
- * @bufs: description of buffers displayed (input)
- * @custom_data_size: size of driver-private data (input)
- * @custom_data: driver-private data (input)
- * @complete_fence_type: one of &enum adf_complete_fence_type describing what
- * 	fence to return (input)
- * @complete_fence: sync_fence fd which will fire at the time
- * 	requested by @complete_fence_type (output)
- */
-struct adf_post_config_v2 {
-	__u32 n_interfaces;
-	__u64 interfaces; /* __u32 * packed into __u64 */
-
-	__u32 n_bufs;
-	__u64 bufs; /* struct adf_buffer_config * packed into __u64 */
-
-	__u64 custom_data_size;
-	__u64 custom_data; /* void * packed into __u64 */
-
-	__s32 complete_fence;
-	__u8 complete_fence_type;
-};
-#define ADF_MAX_INTERFACES (4096 / sizeof(__u32))
-
-/**
- * struct adf_simple_buffer_allocate - request to allocate a "simple" buffer
- *
- * @w: width of buffer in pixels (input)
- * @h: height of buffer in pixels (input)
- * @format: DRM-style fourcc (input)
- *
- * @fd: dma_buf fd (output)
- * @offset: location of first pixel, in bytes (output)
- * @pitch: length of a scanline including padding, in bytes (output)
- *
- * Simple buffers are analogous to DRM's "dumb" buffers.  They have a single
- * plane of linear RGB data which can be allocated and scanned out without
- * any driver-private ioctls or data.
- *
- * @format must be a standard RGB format defined in drm_fourcc.h.
- *
- * ADF clients must NOT assume that an interface can scan out a simple buffer
- * allocated by a different ADF interface, even if the two interfaces belong to
- * the same ADF device.
- */
-struct adf_simple_buffer_alloc {
-	__u16 w;
-	__u16 h;
-	__u32 format;
-
-	__s32 fd;
-	__u32 offset;
-	__u32 pitch;
-};
-
-/**
- * struct adf_simple_post_config - request to flip to a single buffer without
- * driver-private data
- *
- * This request is equivalent to &struct adf_simple_post_config_v2 with
- * @complete_fence_type = %ADF_COMPLETE_FENCE_RELEASE.
- *
- * @buf: description of buffer displayed (input)
- * @complete_fence: sync_fence fd which will clear when this buffer has left the
- * screen (output)
- */
-struct adf_simple_post_config {
-	struct adf_buffer_config buf;
-	__s32 complete_fence;
-};
-
-/**
- * struct adf_simple_post_config_v2 - request to flip to a single buffer without
- * driver-private data
- *
- * @buf: description of buffer displayed (input)
- * @complete_fence_type: one of &enum adf_complete_fence_type describing what
- * 	fence to return (input)
- * @complete_fence: sync_fence fd which will fire at the time
- * 	requested by @complete_fence_type (output)
- */
-struct adf_simple_post_config_v2 {
-	struct adf_buffer_config buf;
-	__s32 complete_fence;
-	__u8 complete_fence_type;
-};
-
-/**
- * struct adf_attachment_config - description of attachment between an overlay
- * engine and an interface
- *
- * @overlay_engine: id of the overlay engine
- * @interface: id of the interface
- */
-struct adf_attachment_config {
-	__u32 overlay_engine;
-	__u32 interface;
-};
-
-/**
- * struct adf_device_data - describes a display device
- *
- * @name: display device's name
- * @n_attachments: the number of current attachments
- * @attachments: list of current attachments
- * @n_allowed_attachments: the number of allowed attachments
- * @allowed_attachments: list of allowed attachments
- * @custom_data_size: size of driver-private data
- * @custom_data: driver-private data
- */
-struct adf_device_data {
-	char name[ADF_NAME_LEN];
-
-	size_t n_attachments;
-	struct adf_attachment_config __user *attachments;
-
-	size_t n_allowed_attachments;
-	struct adf_attachment_config __user *allowed_attachments;
-
-	size_t custom_data_size;
-	void __user *custom_data;
-};
-#define ADF_MAX_ATTACHMENTS (4096 / sizeof(struct adf_attachment_config))
-
-/**
- * struct adf_device_data - describes a display interface
- *
- * @name: display interface's name
- * @type: interface type (see enum @adf_interface_type)
- * @id: which interface of type @type;
- *	e.g. interface DSI.1 -> @type=@ADF_INTF_TYPE_DSI, @id=1
- * @flags: informational flags (bitmask of %ADF_INTF_FLAG_* values)
- * @dpms_state: DPMS state (one of @DRM_MODE_DPMS_* defined in drm_mode.h)
- * @hotplug_detect: whether a display is plugged in
- * @width_mm: screen width in millimeters, or 0 if unknown
- * @height_mm: screen height in millimeters, or 0 if unknown
- * @current_mode: current display mode
- * @n_available_modes: the number of hardware display modes
- * @available_modes: list of hardware display modes
- * @custom_data_size: size of driver-private data
- * @custom_data: driver-private data
- */
-struct adf_interface_data {
-	char name[ADF_NAME_LEN];
-
-	__u32 type;
-	__u32 id;
-	/* e.g. type=ADF_INTF_TYPE_DSI, id=1 => DSI.1 */
-	__u32 flags;
-
-	__u8 dpms_state;
-	__u8 hotplug_detect;
-	__u16 width_mm;
-	__u16 height_mm;
-
-	struct drm_mode_modeinfo current_mode;
-	size_t n_available_modes;
-	struct drm_mode_modeinfo __user *available_modes;
-
-	size_t custom_data_size;
-	void __user *custom_data;
-};
-#define ADF_MAX_MODES (4096 / sizeof(struct drm_mode_modeinfo))
-
-/**
- * struct adf_overlay_engine_data - describes an overlay engine
- *
- * @name: overlay engine's name
- * @n_supported_formats: number of supported formats
- * @supported_formats: list of supported formats
- * @custom_data_size: size of driver-private data
- * @custom_data: driver-private data
- */
-struct adf_overlay_engine_data {
-	char name[ADF_NAME_LEN];
-
-	size_t n_supported_formats;
-	__u32 __user *supported_formats;
-
-	size_t custom_data_size;
-	void __user *custom_data;
-};
-#define ADF_MAX_SUPPORTED_FORMATS (4096 / sizeof(__u32))
-
-#define ADF_IOCTL_TYPE		'D'
-#define ADF_IOCTL_NR_CUSTOM	128
-
-#define ADF_SET_EVENT		_IOW(ADF_IOCTL_TYPE, 0, struct adf_set_event)
-#define ADF_BLANK		_IOW(ADF_IOCTL_TYPE, 1, __u8)
-#define ADF_POST_CONFIG		_IOW(ADF_IOCTL_TYPE, 2, struct adf_post_config)
-#define ADF_SET_MODE		_IOW(ADF_IOCTL_TYPE, 3, \
-					struct drm_mode_modeinfo)
-#define ADF_GET_DEVICE_DATA	_IOR(ADF_IOCTL_TYPE, 4, struct adf_device_data)
-#define ADF_GET_INTERFACE_DATA	_IOR(ADF_IOCTL_TYPE, 5, \
-					struct adf_interface_data)
-#define ADF_GET_OVERLAY_ENGINE_DATA \
-				_IOR(ADF_IOCTL_TYPE, 6, \
-					struct adf_overlay_engine_data)
-#define ADF_SIMPLE_POST_CONFIG	_IOW(ADF_IOCTL_TYPE, 7, \
-					struct adf_simple_post_config)
-#define ADF_SIMPLE_BUFFER_ALLOC	_IOW(ADF_IOCTL_TYPE, 8, \
-					struct adf_simple_buffer_alloc)
-#define ADF_ATTACH		_IOW(ADF_IOCTL_TYPE, 9, \
-					struct adf_attachment_config)
-#define ADF_DETACH		_IOW(ADF_IOCTL_TYPE, 10, \
-					struct adf_attachment_config)
-
-#define ADF_POST_CONFIG_V2	_IOW(ADF_IOCTL_TYPE, 11, \
-					struct adf_post_config_v2)
-#define ADF_SIMPLE_POST_CONFIG_V2 \
-				_IOW(ADF_IOCTL_TYPE, 12, \
-					struct adf_simple_post_config_v2)
-
-#endif /* _UAPI_VIDEO_ADF_H_ */
diff --git a/deprecated-adf/libadf/tests/adf_test.cpp b/deprecated-adf/libadf/tests/adf_test.cpp
deleted file mode 100644
index 82a91f4..0000000
--- a/deprecated-adf/libadf/tests/adf_test.cpp
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-
-#include <adf/adf.h>
-#include <gtest/gtest.h>
-#include <sys/mman.h>
-#include <sync/sync.h>
-
-class AdfTest : public testing::Test {
-public:
-    AdfTest() : intf_id(0), intf(-1), eng_id(0), eng(-1) { }
-
-    virtual void SetUp() {
-        int err = adf_device_open(dev_id, O_RDWR, &dev);
-        ASSERT_GE(err, 0) << "opening ADF device " << dev_id <<
-                " failed: " << strerror(-err);
-
-        err = adf_find_simple_post_configuration(&dev, fmt8888, n_fmt8888,
-                &intf_id, &eng_id);
-        ASSERT_GE(err, 0) << "finding ADF configuration failed: " <<
-                strerror(-err);
-
-        intf = adf_interface_open(&dev, intf_id, O_RDWR);
-        ASSERT_GE(intf, 0) << "opening ADF interface " << dev_id << "." <<
-                intf_id << " failed: " << strerror(-intf);
-
-        eng = adf_overlay_engine_open(&dev, eng_id, O_RDWR);
-        ASSERT_GE(eng, 0) << "opening ADF overlay engine " << dev_id << "." <<
-                eng_id << " failed: " << strerror(-eng);
-    }
-
-    virtual void TearDown() {
-        if (eng >= 0)
-            close(eng);
-        if (intf >= 0)
-            close(intf);
-        adf_device_close(&dev);
-    }
-
-    void get8888Format(uint32_t &fmt, char fmt_str[ADF_FORMAT_STR_SIZE]) {
-        adf_overlay_engine_data data;
-        int err = adf_get_overlay_engine_data(eng, &data);
-        ASSERT_GE(err, 0) << "getting ADF overlay engine data failed: " <<
-                strerror(-err);
-
-        for (size_t i = 0; i < data.n_supported_formats; i++) {
-            for (size_t j = 0; j < n_fmt8888; j++) {
-                if (data.supported_formats[i] == fmt8888[j]) {
-                    fmt = data.supported_formats[i];
-                    adf_format_str(fmt, fmt_str);
-                    adf_free_overlay_engine_data(&data);
-                    return;
-                }
-            }
-        }
-
-        adf_free_overlay_engine_data(&data);
-        FAIL(); /* this should never happen */
-    }
-
-    /* various helpers to call ADF and die on failure */
-
-    void getInterfaceData(adf_interface_data &data) {
-         int err = adf_get_interface_data(intf, &data);
-         ASSERT_GE(err, 0) << "getting ADF interface data failed: " <<
-                 strerror(-err);
-    }
-
-    void getCurrentMode(uint32_t &w, uint32_t &h) {
-        adf_interface_data data;
-        ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
-        w = data.current_mode.hdisplay;
-        h = data.current_mode.vdisplay;
-        adf_free_interface_data(&data);
-    }
-
-    void blank(uint8_t mode) {
-        int err = adf_interface_blank(intf, mode);
-        ASSERT_FALSE(err < 0 && err != -EBUSY) <<
-                "unblanking interface failed: " << strerror(-err);
-    }
-
-    void attach() {
-        int err = adf_device_attach(&dev, eng_id, intf_id);
-        ASSERT_FALSE(err < 0 && err != -EALREADY) <<
-                "attaching overlay engine " << eng_id << " to interface " <<
-                intf_id << " failed: " << strerror(-err);
-    }
-
-    void detach() {
-        int err = adf_device_detach(&dev, eng_id, intf_id);
-        ASSERT_FALSE(err < 0 && err != -EINVAL) <<
-                "detaching overlay engine " << eng_id << " from interface " <<
-                intf_id << " failed: " << strerror(-err);
-    }
-
-    void readVsyncTimestamp(uint64_t &timestamp) {
-        adf_event *event;
-        int err = adf_read_event(intf, &event);
-        ASSERT_GE(err, 0) << "reading ADF event failed: " << strerror(-err);
-
-        ASSERT_EQ(ADF_EVENT_VSYNC, event->type);
-        ASSERT_EQ(sizeof(adf_vsync_event), event->length);
-
-        adf_vsync_event *vsync_event =
-                reinterpret_cast<adf_vsync_event *>(event);
-        timestamp = vsync_event->timestamp;
-        free(event);
-    }
-
-    void drawCheckerboard(uint32_t &w, uint32_t &h, uint32_t &format,
-            char format_str[ADF_FORMAT_STR_SIZE], int &buf_fd, uint32_t &offset,
-            uint32_t &pitch) {
-        ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
-        ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
-
-        buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
-                &pitch);
-        ASSERT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
-                format_str << " buffer failed: " << strerror(-buf_fd);
-        EXPECT_GE(pitch, w * 4);
-
-        void *mapped = mmap(NULL, pitch * h, PROT_WRITE, MAP_SHARED, buf_fd,
-                offset);
-        ASSERT_NE(mapped, MAP_FAILED) << "mapping " << w << "x" << h << " " <<
-                format_str << " buffer failed: " << strerror(-errno);
-
-        uint8_t *buf8 = static_cast<uint8_t *>(mapped);
-        for (uint32_t y = 0; y < h / 2; y++) {
-            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
-            for (uint32_t x = 0; x < w / 2; x++)
-                scanline[x] = 0xFF0000FF;
-            for (uint32_t x = w / 2; x < w; x++)
-                scanline[x] = 0xFF00FFFF;
-        }
-        for (uint32_t y = h / 2; y < h; y++) {
-            uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch);
-            for (uint32_t x = 0; x < w / 2; x++)
-                scanline[x] = 0xFFFF00FF;
-            for (uint32_t x = w / 2; x < w; x++)
-                scanline[x] = 0xFFFFFFFF;
-        }
-
-        munmap(mapped, pitch * h);
-    }
-
-protected:
-    adf_device dev;
-    adf_id_t intf_id;
-    int intf;
-    adf_id_t eng_id;
-    int eng;
-
-private:
-    const static adf_id_t dev_id;
-    const static __u32 fmt8888[];
-    const static size_t n_fmt8888;
-};
-
-const adf_id_t AdfTest::dev_id = 0;
-
-const __u32 AdfTest::fmt8888[] = {
-   DRM_FORMAT_XRGB8888,
-   DRM_FORMAT_XBGR8888,
-   DRM_FORMAT_RGBX8888,
-   DRM_FORMAT_BGRX8888,
-   DRM_FORMAT_ARGB8888,
-   DRM_FORMAT_ABGR8888,
-   DRM_FORMAT_RGBA8888,
-   DRM_FORMAT_BGRA8888
-};
-const size_t AdfTest::n_fmt8888 = sizeof(fmt8888) / sizeof(fmt8888[0]);
-
-TEST(adf, devices) {
-    adf_id_t *devs = nullptr;
-    ssize_t n_devs = adf_devices(&devs);
-    free(devs);
-
-    ASSERT_GE(n_devs, 0) << "enumerating ADF devices failed: " <<
-            strerror(-n_devs);
-    ASSERT_TRUE(devs != NULL);
-}
-
-TEST_F(AdfTest, device_data) {
-    adf_device_data data;
-    int err = adf_get_device_data(&dev, &data);
-    ASSERT_GE(err, 0) << "getting ADF device data failed: " << strerror(-err);
-
-    EXPECT_LT(data.n_attachments, ADF_MAX_ATTACHMENTS);
-    EXPECT_GT(data.n_allowed_attachments, 0U);
-    EXPECT_LT(data.n_allowed_attachments, ADF_MAX_ATTACHMENTS);
-    EXPECT_LT(data.custom_data_size, (size_t)ADF_MAX_CUSTOM_DATA_SIZE);
-    adf_free_device_data(&data);
-}
-
-TEST_F(AdfTest, interface_data) {
-    adf_interface_data data;
-    ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
-
-    EXPECT_LT(data.type, ADF_INTF_TYPE_MAX);
-    EXPECT_LE(data.dpms_state, DRM_MODE_DPMS_OFF);
-    EXPECT_EQ(1, data.hotplug_detect);
-    EXPECT_GT(data.n_available_modes, 0U);
-    EXPECT_LT(data.custom_data_size, (size_t)ADF_MAX_CUSTOM_DATA_SIZE);
-    adf_free_interface_data(&data);
-}
-
-TEST_F(AdfTest, overlay_engine_data) {
-    adf_overlay_engine_data data;
-    int err = adf_get_overlay_engine_data(eng, &data);
-    ASSERT_GE(err, 0) << "getting ADF overlay engine failed: " <<
-            strerror(-err);
-
-    EXPECT_GT(data.n_supported_formats, 0U);
-    EXPECT_LT(data.n_supported_formats, ADF_MAX_SUPPORTED_FORMATS);
-    EXPECT_LT(data.custom_data_size, (size_t)ADF_MAX_CUSTOM_DATA_SIZE);
-    adf_free_overlay_engine_data(&data);
-}
-
-TEST_F(AdfTest, blank) {
-    int err = adf_interface_blank(intf, (uint8_t)-1);
-    EXPECT_EQ(-EINVAL, err) << "setting bogus DPMS mode should have failed";
-
-    err = adf_interface_blank(eng, DRM_MODE_DPMS_OFF);
-    EXPECT_EQ(-EINVAL, err) << "blanking overlay engine should have failed";
-
-    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_OFF));
-    err = adf_interface_blank(intf, DRM_MODE_DPMS_OFF);
-    EXPECT_EQ(-EBUSY, err) << "blanking interface twice should have failed";
-
-    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
-    err = adf_interface_blank(intf, DRM_MODE_DPMS_ON);
-    EXPECT_EQ(-EBUSY, err) << "unblanking interface twice should have failed";
-
-    adf_interface_data data;
-    ASSERT_NO_FATAL_FAILURE(getInterfaceData(data));
-    EXPECT_EQ(DRM_MODE_DPMS_ON, data.dpms_state);
-    adf_free_interface_data(&data);
-}
-
-TEST_F(AdfTest, event) {
-    int err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, true);
-    EXPECT_EQ(-EINVAL, err) << "enabling bogus ADF event should have failed";
-
-    err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, false);
-    EXPECT_EQ(-EINVAL, err) << "disabling bogus ADF event should have failed";
-
-    err = adf_set_event(intf, ADF_EVENT_VSYNC, true);
-    ASSERT_GE(err, 0) << "enabling vsync event failed: " << strerror(-err);
-
-    err = adf_set_event(intf, ADF_EVENT_VSYNC, true);
-    EXPECT_EQ(-EALREADY, err) <<
-            "enabling vsync event twice should have failed";
-
-    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
-
-    uint64_t timestamp1, timestamp2;
-    ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp1));
-    ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp2));
-    EXPECT_GT(timestamp2, timestamp1);
-
-    err = adf_set_event(intf, ADF_EVENT_VSYNC, false);
-    EXPECT_GE(err, 0) << "disabling vsync event failed: " << strerror(-err);
-
-    err = adf_set_event(intf, ADF_EVENT_VSYNC, false);
-    EXPECT_EQ(-EALREADY, err) <<
-            "disabling vsync event twice should have failed";
-}
-
-TEST_F(AdfTest, attach) {
-    ASSERT_NO_FATAL_FAILURE(attach());
-    int err = adf_device_attach(&dev, eng_id, intf_id);
-    EXPECT_EQ(-EALREADY, err) << "attaching overlay engine " << eng_id <<
-            " to interface " << intf_id << " twice should have failed";
-
-    ASSERT_NO_FATAL_FAILURE(detach());
-    err = adf_device_detach(&dev, eng_id, intf_id);
-    EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id <<
-            " from interface " << intf_id << " twice should have failed";
-
-    err = adf_device_attach(&dev, eng_id, ADF_MAX_INTERFACES);
-    EXPECT_EQ(-EINVAL, err) << "attaching overlay engine " << eng_id <<
-            " to bogus interface should have failed";
-
-    err = adf_device_detach(&dev, eng_id, ADF_MAX_INTERFACES);
-    EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id <<
-            " from bogus interface should have failed";
-}
-
-TEST_F(AdfTest, simple_buffer_alloc) {
-    uint32_t w = 0, h = 0;
-    ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h));
-
-    uint32_t format;
-    char format_str[ADF_FORMAT_STR_SIZE];
-    ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str));
-
-    uint32_t offset;
-    uint32_t pitch;
-    int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset,
-            &pitch);
-    EXPECT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-buf_fd);
-    EXPECT_GE(pitch, w * 4);
-    close(buf_fd);
-
-    buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, 0xDEADBEEF, &offset,
-            &pitch);
-    /* n.b.: ADF only allows simple buffers with built-in RGB formats,
-       so this should fail even if a driver supports custom format 0xDEADBEEF */
-    EXPECT_EQ(-EINVAL, buf_fd) <<
-            "allocating buffer with bogus format should have failed";
-}
-
-TEST_F(AdfTest, simple_buffer) {
-    int buf_fd;
-    uint32_t w, h, format, offset, pitch;
-    char format_str[ADF_FORMAT_STR_SIZE];
-    ASSERT_NO_FATAL_FAILURE(drawCheckerboard(w, h, format, format_str,
-            buf_fd, offset, pitch));
-
-    ASSERT_NO_FATAL_FAILURE(attach());
-    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
-
-    int release_fence = adf_interface_simple_post(intf, eng_id, w, h, format,
-            buf_fd, offset, pitch, -1);
-    close(buf_fd);
-    ASSERT_GE(release_fence, 0) << "posting " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-release_fence);
-    close(release_fence);
-}
-
-TEST_F(AdfTest, simple_buffer_v2) {
-    int buf_fd;
-    uint32_t w, h, format, offset, pitch;
-    char format_str[ADF_FORMAT_STR_SIZE];
-    ASSERT_NO_FATAL_FAILURE(drawCheckerboard(w, h, format, format_str,
-            buf_fd, offset, pitch));
-
-    ASSERT_NO_FATAL_FAILURE(attach());
-    ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON));
-
-    int config_1_release;
-    int err = adf_interface_simple_post_v2(intf, eng_id, w, h,
-            format, buf_fd, offset, pitch, -1, ADF_COMPLETE_FENCE_RELEASE,
-            &config_1_release);
-    if (err == -ENOTTY) {
-        GTEST_LOG_(INFO) << "ADF_SIMPLE_POST_CONFIG_V2 not supported on this kernel";
-        return;
-    }
-    ASSERT_GE(err, 0) << "posting " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-err);
-
-    err = sync_wait(config_1_release, 1000);
-    ASSERT_EQ(-1, err) <<
-            "waiting for config 1's release fence should not have suceeded";
-    ASSERT_EQ(ETIME, errno) <<
-            "config 1's release fence should have timed out, but failed instead: " <<
-            strerror(errno);
-
-    int config_2_present;
-    err = adf_interface_simple_post_v2(intf, eng_id, w, h,
-            format, buf_fd, offset, pitch, -1, ADF_COMPLETE_FENCE_PRESENT,
-            &config_2_present);
-    ASSERT_GE(err, 0) << "posting " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-err);
-
-    err = sync_wait(config_2_present, 1000);
-    ASSERT_EQ(0, err) <<
-            "waiting for config 2's present fence failed: " << strerror(errno);
-    err = sync_wait(config_1_release, 0);
-    ASSERT_EQ(0, err) <<
-            "waiting for config 1's release fence failed: " << strerror(errno);
-    close(config_1_release);
-    close(config_2_present);
-
-    int config_3_no_fence;
-    err = adf_interface_simple_post_v2(intf, eng_id, w, h,
-            format, buf_fd, offset, pitch, -1, ADF_COMPLETE_FENCE_NONE,
-            &config_3_no_fence);
-    ASSERT_GE(err, 0) << "posting " << w << "x" << h << " " <<
-            format_str << " buffer failed: " << strerror(-err);
-    ASSERT_EQ(-1, config_3_no_fence) <<
-            "fence returned even though the fence type was ADF_COMPLETE_FENCE_NONE";
-
-    close(buf_fd);
-}
diff --git a/deprecated-adf/libadfhwc/Android.bp b/deprecated-adf/libadfhwc/Android.bp
deleted file mode 100644
index 57a8d76..0000000
--- a/deprecated-adf/libadfhwc/Android.bp
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (C) 2013 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.
-
-cc_library_static {
-    name: "libadfhwc",
-    srcs: ["adfhwc.cpp"],
-    static_libs: [
-        "libadf",
-        "liblog",
-        "libutils",
-    ],
-    cflags: [
-        "-DLOG_TAG=\"adfhwc\"",
-        "-Werror",
-    ],
-    local_include_dirs: ["include"],
-    export_include_dirs: ["include"],
-}
diff --git a/deprecated-adf/libadfhwc/adfhwc.cpp b/deprecated-adf/libadfhwc/adfhwc.cpp
deleted file mode 100644
index 63c0f75..0000000
--- a/deprecated-adf/libadfhwc/adfhwc.cpp
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <fcntl.h>
-#include <malloc.h>
-#include <poll.h>
-#include <pthread.h>
-#include <sys/resource.h>
-
-#include <log/log.h>
-#include <utils/Vector.h>
-
-#include <adf/adf.h>
-#include <adfhwc/adfhwc.h>
-
-struct adf_hwc_helper {
-    adf_hwc_event_callbacks const *event_cb;
-    void *event_cb_data;
-
-    pthread_t event_thread;
-
-    android::Vector<int> intf_fds;
-    android::Vector<drm_mode_modeinfo> display_configs;
-};
-
-template<typename T> inline T min(T a, T b) { return (a < b) ? a : b; }
-
-int adf_eventControl(struct adf_hwc_helper *dev, int disp, int event,
-        int enabled)
-{
-    if (enabled != !!enabled)
-        return -EINVAL;
-
-    if ((size_t)disp >= dev->intf_fds.size())
-        return -EINVAL;
-
-    switch (event) {
-    case HWC_EVENT_VSYNC:
-        return adf_set_event(dev->intf_fds[disp], ADF_EVENT_VSYNC, enabled);
-    }
-
-    return -EINVAL;
-}
-
-static inline int32_t dpi(uint16_t res, uint16_t size_mm)
-{
-    if (size_mm)
-        return 1000 * (res * 25.4f) / size_mm;
-    return 0;
-}
-
-int adf_blank(struct adf_hwc_helper *dev, int disp, int blank)
-{
-    if ((size_t)disp >= dev->intf_fds.size())
-        return -EINVAL;
-
-    uint8_t dpms_mode = blank ? DRM_MODE_DPMS_OFF : DRM_MODE_DPMS_ON;
-    return adf_interface_blank(dev->intf_fds[disp], dpms_mode);
-}
-
-int adf_query_display_types_supported(struct adf_hwc_helper *dev, int *value)
-{
-    *value = 0;
-    if (dev->intf_fds.size() > 0)
-        *value |= HWC_DISPLAY_PRIMARY_BIT;
-    if (dev->intf_fds.size() > 1)
-        *value |= HWC_DISPLAY_EXTERNAL_BIT;
-
-    return 0;
-}
-
-int adf_getDisplayConfigs(struct adf_hwc_helper *dev, int disp,
-        uint32_t *configs, size_t *numConfigs)
-{
-    if ((size_t)disp >= dev->intf_fds.size())
-        return -EINVAL;
-
-    adf_interface_data data;
-    int err = adf_get_interface_data(dev->intf_fds[disp], &data);
-    if (err < 0) {
-        ALOGE("failed to get ADF interface data: %s", strerror(err));
-        return err;
-    }
-
-    if (!data.hotplug_detect)
-        return -ENODEV;
-
-    android::Vector<drm_mode_modeinfo *> unique_configs;
-    unique_configs.push_back(&data.current_mode);
-    for (size_t i = 0; i < data.n_available_modes; i++)
-        if (memcmp(&data.available_modes[i], &data.current_mode,
-                sizeof(data.current_mode)))
-            unique_configs.push_back(&data.available_modes[i]);
-
-    for (size_t i = 0; i < min(*numConfigs, unique_configs.size()); i++) {
-        configs[i] = dev->display_configs.size();
-        dev->display_configs.push_back(*unique_configs[i]);
-    }
-    *numConfigs = unique_configs.size();
-
-    adf_free_interface_data(&data);
-    return 0;
-}
-
-static int32_t adf_display_attribute(const adf_interface_data &data,
-        const drm_mode_modeinfo &mode, const uint32_t attribute)
-{
-    switch (attribute) {
-    case HWC_DISPLAY_VSYNC_PERIOD:
-        if (mode.vrefresh)
-            return 1000000000 / mode.vrefresh;
-        return 0;
-
-    case HWC_DISPLAY_WIDTH:
-        return mode.hdisplay;
-
-    case HWC_DISPLAY_HEIGHT:
-        return mode.vdisplay;
-
-    case HWC_DISPLAY_DPI_X:
-        return dpi(mode.hdisplay, data.width_mm);
-
-    case HWC_DISPLAY_DPI_Y:
-        return dpi(mode.vdisplay, data.height_mm);
-
-    default:
-        ALOGE("unknown display attribute %u", attribute);
-        return -EINVAL;
-    }
-}
-
-int adf_getDisplayAttributes(struct adf_hwc_helper *dev, int disp,
-        uint32_t config, const uint32_t *attributes, int32_t *values)
-{
-    if ((size_t)disp >= dev->intf_fds.size())
-        return -EINVAL;
-
-    if (config >= dev->display_configs.size())
-        return -EINVAL;
-
-    adf_interface_data data;
-    int err = adf_get_interface_data(dev->intf_fds[disp], &data);
-    if (err < 0) {
-        ALOGE("failed to get ADF interface data: %s", strerror(err));
-        return err;
-    }
-
-    for (int i = 0; attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; i++)
-        values[i] = adf_display_attribute(data, dev->display_configs[config],
-                attributes[i]);
-
-    adf_free_interface_data(&data);
-    return 0;
-}
-
-static int32_t adf_display_attribute_hwc2(const adf_interface_data &data,
-        const drm_mode_modeinfo &mode, const uint32_t attribute)
-{
-    switch (attribute) {
-    case HWC2_ATTRIBUTE_VSYNC_PERIOD:
-        if (mode.vrefresh)
-            return 1000000000 / mode.vrefresh;
-        return 0;
-
-    case HWC2_ATTRIBUTE_WIDTH:
-        return mode.hdisplay;
-
-    case HWC2_ATTRIBUTE_HEIGHT:
-        return mode.vdisplay;
-
-    case HWC2_ATTRIBUTE_DPI_X:
-        return dpi(mode.hdisplay, data.width_mm);
-
-    case HWC2_ATTRIBUTE_DPI_Y:
-        return dpi(mode.vdisplay, data.height_mm);
-
-    default:
-        ALOGE("unknown display attribute %u", attribute);
-        return -EINVAL;
-    }
-}
-
-int adf_getDisplayAttributes_hwc2(struct adf_hwc_helper *dev, int disp,
-        uint32_t config, const uint32_t *attributes, int32_t *values)
-{
-    if ((size_t)disp >= dev->intf_fds.size())
-        return -EINVAL;
-
-    if (config >= dev->display_configs.size())
-        return -EINVAL;
-
-    adf_interface_data data;
-    int err = adf_get_interface_data(dev->intf_fds[disp], &data);
-    if (err < 0) {
-        ALOGE("failed to get ADF interface data: %s", strerror(err));
-        return err;
-    }
-
-    for (int i = 0; attributes[i] != HWC2_ATTRIBUTE_INVALID; i++)
-        values[i] = adf_display_attribute_hwc2(data,
-                dev->display_configs[config], attributes[i]);
-
-    adf_free_interface_data(&data);
-    return 0;
-}
-
-int adf_set_active_config_hwc2(struct adf_hwc_helper *dev, int disp,
-        uint32_t config)
-{
-    if ((size_t)disp >= dev->intf_fds.size())
-        return -EINVAL;
-
-    if (config >= dev->display_configs.size())
-        return -EINVAL;
-
-    struct drm_mode_modeinfo mode = dev->display_configs[config];
-
-    return adf_interface_set_mode(dev->intf_fds[disp], &mode);
-}
-
-static void handle_adf_event(struct adf_hwc_helper *dev, int disp)
-{
-    adf_event *event;
-    int err = adf_read_event(dev->intf_fds[disp], &event);
-    if (err < 0) {
-        ALOGE("error reading event from display %d: %s", disp, strerror(err));
-        return;
-    }
-
-    void *vsync_temp;
-    adf_vsync_event *vsync;
-    adf_hotplug_event *hotplug;
-
-    switch (event->type) {
-    case ADF_EVENT_VSYNC:
-        vsync_temp = event;
-        vsync = static_cast<adf_vsync_event *>(vsync_temp);
-        // casting directly to adf_vsync_event * makes g++ warn about
-        // potential alignment issues that don't apply here
-        dev->event_cb->vsync(dev->event_cb_data, disp, vsync->timestamp);
-        break;
-    case ADF_EVENT_HOTPLUG:
-        hotplug = reinterpret_cast<adf_hotplug_event *>(event);
-        dev->event_cb->hotplug(dev->event_cb_data, disp, hotplug->connected);
-        break;
-    default:
-        if (event->type < ADF_EVENT_DEVICE_CUSTOM)
-            ALOGW("unrecognized event type %u", event->type);
-        else if (!dev->event_cb || !dev->event_cb->custom_event)
-            ALOGW("unhandled event type %u", event->type);
-        else
-            dev->event_cb->custom_event(dev->event_cb_data, disp, event);
-    }
-    free(event);
-}
-
-static void *adf_event_thread(void *data)
-{
-    adf_hwc_helper *dev = static_cast<adf_hwc_helper *>(data);
-
-    setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
-
-    struct sigaction action = { };
-    sigemptyset(&action.sa_mask);
-    action.sa_flags = 0;
-    action.sa_handler = [](int) { pthread_exit(0); };
-
-    if (sigaction(SIGUSR2, &action, NULL) < 0) {
-        ALOGE("failed to set thread exit action %s", strerror(errno));
-        return NULL;
-    }
-
-    sigset_t signal_set;
-    sigemptyset(&signal_set);
-    sigaddset(&signal_set, SIGUSR2);
-
-    pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
-
-    pollfd fds[dev->intf_fds.size()];
-    for (size_t i = 0; i < dev->intf_fds.size(); i++) {
-        fds[i].fd = dev->intf_fds[i];
-        fds[i].events = POLLIN | POLLPRI;
-    }
-
-    while (true) {
-        if (TEMP_FAILURE_RETRY(poll(fds, dev->intf_fds.size(), -1)) < 0) {
-            ALOGE("error in event thread: %s", strerror(errno));
-            break;
-        }
-
-        for (size_t i = 0; i < dev->intf_fds.size(); i++)
-            if (fds[i].revents & (POLLIN | POLLPRI))
-                handle_adf_event(dev, i);
-    }
-
-    return NULL;
-}
-
-int adf_hwc_open(int *intf_fds, size_t n_intfs,
-        const struct adf_hwc_event_callbacks *event_cb, void *event_cb_data,
-        struct adf_hwc_helper **dev)
-{
-    if (!n_intfs)
-        return -EINVAL;
-
-    adf_hwc_helper *dev_ret = new adf_hwc_helper;
-    dev_ret->event_cb = event_cb;
-    dev_ret->event_cb_data = event_cb_data;
-
-    int ret;
-
-    for (size_t i = 0; i < n_intfs; i++) {
-        int dup_intf_fd = dup(intf_fds[i]);
-        if (dup_intf_fd < 0) {
-            ALOGE("failed to dup interface fd: %s", strerror(errno));
-            ret = -errno;
-            goto err;
-        }
-
-        dev_ret->intf_fds.push_back(dup_intf_fd);
-
-        ret = adf_set_event(dup_intf_fd, ADF_EVENT_HOTPLUG, 1);
-        if (ret < 0 && ret != -EINVAL) {
-            ALOGE("failed to enable hotplug event on display %zu: %s",
-                    i, strerror(errno));
-            goto err;
-        }
-    }
-
-    sigset_t signal_set;
-    sigemptyset(&signal_set);
-    sigaddset(&signal_set, SIGUSR2);
-
-    pthread_sigmask(SIG_BLOCK, &signal_set, NULL);
-
-    ret = pthread_create(&dev_ret->event_thread, NULL, adf_event_thread,
-            dev_ret);
-    if (ret) {
-        ALOGE("failed to create event thread: %s", strerror(ret));
-        goto err;
-    }
-
-    *dev = dev_ret;
-    return 0;
-
-err:
-    for (size_t i = 0; i < dev_ret->intf_fds.size(); i++)
-        close(dev_ret->intf_fds[i]);
-
-    delete dev_ret;
-    return ret;
-}
-
-void adf_hwc_close(struct adf_hwc_helper *dev)
-{
-    pthread_kill(dev->event_thread, SIGUSR2);
-    pthread_join(dev->event_thread, NULL);
-
-    for (size_t i = 0; i < dev->intf_fds.size(); i++)
-        close(dev->intf_fds[i]);
-
-    delete dev;
-}
diff --git a/deprecated-adf/libadfhwc/include/adfhwc/adfhwc.h b/deprecated-adf/libadfhwc/include/adfhwc/adfhwc.h
deleted file mode 100644
index 4f70925..0000000
--- a/deprecated-adf/libadfhwc/include/adfhwc/adfhwc.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2013 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 _LIBADFHWC_ADFHWC_H_
-#define _LIBADFHWC_ADFHWC_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <sys/cdefs.h>
-#include <video/adf.h>
-
-#include <hardware/hwcomposer.h>
-#include <hardware/hwcomposer2.h>
-
-struct adf_hwc_helper;
-
-struct adf_hwc_event_callbacks {
-    /**
-     * Called on vsync (required)
-     */
-    void (*vsync)(void *data, int disp, uint64_t timestamp);
-    /**
-     * Called on hotplug (required)
-     */
-    void (*hotplug)(void *data, int disp, bool connected);
-    /**
-     * Called on hardware-custom ADF events (optional)
-     */
-    void (*custom_event)(void *data, int disp, struct adf_event *event);
-};
-
-/**
- * Converts HAL pixel formats to equivalent ADF/DRM format FourCCs.
- */
-static inline uint32_t adf_fourcc_for_hal_pixel_format(int format)
-{
-    switch (format) {
-    case HAL_PIXEL_FORMAT_RGBA_8888:
-        return DRM_FORMAT_RGBA8888;
-    case HAL_PIXEL_FORMAT_RGBX_8888:
-        return DRM_FORMAT_RGBX8888;
-    case HAL_PIXEL_FORMAT_RGB_888:
-        return DRM_FORMAT_RGB888;
-    case HAL_PIXEL_FORMAT_RGB_565:
-        return DRM_FORMAT_RGB565;
-    case HAL_PIXEL_FORMAT_BGRA_8888:
-        return DRM_FORMAT_BGRA8888;
-    case HAL_PIXEL_FORMAT_YV12:
-        return DRM_FORMAT_YVU420;
-    case HAL_PIXEL_FORMAT_YCbCr_422_SP:
-        return DRM_FORMAT_NV16;
-    case HAL_PIXEL_FORMAT_YCrCb_420_SP:
-        return DRM_FORMAT_NV21;
-    case HAL_PIXEL_FORMAT_YCbCr_422_I:
-        return DRM_FORMAT_YUYV;
-    default:
-        return 0;
-    }
-}
-
-/**
- * Converts HAL display types to equivalent ADF interface flags.
- */
-static inline uint32_t adf_hwc_interface_flag_for_disp(int disp)
-{
-    switch (disp) {
-    case HWC_DISPLAY_PRIMARY:
-        return ADF_INTF_FLAG_PRIMARY;
-    case HWC_DISPLAY_EXTERNAL:
-        return ADF_INTF_FLAG_EXTERNAL;
-    default:
-        return 0;
-    }
-}
-
-__BEGIN_DECLS
-
-/**
- * Create a HWC helper for the specified ADF interfaces.
- *
- * intf_fds must be indexed by HWC display type: e.g.,
- * intf_fds[HWC_DISPLAY_PRIMARY] is the fd for the primary display
- * interface.  n_intfs must be >= 1.
- *
- * The caller retains ownership of the fds in intf_fds and must close()
- * them when they are no longer needed.
- *
- * On error, returns -errno.
- */
-int adf_hwc_open(int *intf_fds, size_t n_intfs,
-        const struct adf_hwc_event_callbacks *event_cb, void *event_cb_data,
-        struct adf_hwc_helper **dev);
-
-/**
- * Destroys a HWC helper.
- */
-void adf_hwc_close(struct adf_hwc_helper *dev);
-
-/**
- * Generic implementations of common HWC ops.
- *
- * The HWC should not point its ops directly at these helpers.  Instead, the HWC
- * should provide stub ops which call these helpers after converting the
- * hwc_composer_device_1* to a struct adf_hwc_helper*.
- */
-int adf_eventControl(struct adf_hwc_helper *dev, int disp, int event,
-        int enabled);
-int adf_blank(struct adf_hwc_helper *dev, int disp, int blank);
-int adf_query_display_types_supported(struct adf_hwc_helper *dev, int *value);
-int adf_getDisplayConfigs(struct adf_hwc_helper *dev, int disp,
-        uint32_t *configs, size_t *numConfigs);
-int adf_getDisplayAttributes(struct adf_hwc_helper *dev, int disp,
-        uint32_t config, const uint32_t *attributes, int32_t *values);
-/**
- * Generic implementation of common HWC2 functions.
- *
- * The HWC2 should not return these functions directly through getFunction.
- * Instead, the HWC2 should return stub functions which call these helpers.
- */
-int adf_getDisplayAttributes_hwc2(struct adf_hwc_helper *dev, int disp,
-        uint32_t config, const uint32_t *attributes, int32_t *values);
-int adf_set_active_config_hwc2(struct adf_hwc_helper *dev, int disp,
-        uint32_t config);
-
-__END_DECLS
-
-#endif /* _LIBADFHWC_ADFHWC_H_ */
diff --git a/fs_mgr/Android.bp b/fs_mgr/Android.bp
index ac784b2..96cc5c8 100644
--- a/fs_mgr/Android.bp
+++ b/fs_mgr/Android.bp
@@ -170,6 +170,7 @@
     defaults: ["fs_mgr_defaults"],
     static_libs: [
         "libavb_user",
+        "libgsid",
         "libutils",
         "libvold_binder",
     ],
diff --git a/fs_mgr/fs_mgr_remount.cpp b/fs_mgr/fs_mgr_remount.cpp
index b8b074e..745dab2 100644
--- a/fs_mgr/fs_mgr_remount.cpp
+++ b/fs_mgr/fs_mgr_remount.cpp
@@ -16,7 +16,6 @@
 
 #include <errno.h>
 #include <getopt.h>
-#include <libavb_user/libavb_user.h>
 #include <stdio.h>
 #include <sys/mount.h>
 #include <sys/types.h>
@@ -40,6 +39,8 @@
 #include <fs_mgr_overlayfs.h>
 #include <fs_mgr_priv.h>
 #include <fstab/fstab.h>
+#include <libavb_user/libavb_user.h>
+#include <libgsi/libgsid.h>
 
 namespace {
 
@@ -52,7 +53,9 @@
                  "\tpartition\tspecific partition(s) (empty does all)\n"
                  "\n"
                  "Remount specified partition(s) read-write, by name or mount point.\n"
-                 "-R notwithstanding, verity must be disabled on partition(s).";
+                 "-R notwithstanding, verity must be disabled on partition(s).\n"
+                 "-R within a DSU guest system reboots into the DSU instead of the host system,\n"
+                 "this command would enable DSU (one-shot) if not already enabled.";
 
     ::exit(exit_status);
 }
@@ -137,7 +140,8 @@
     REMOUNT_FAILED,
     MUST_REBOOT,
     BINDER_ERROR,
-    CHECKPOINTING
+    CHECKPOINTING,
+    GSID_ERROR,
 };
 
 static int do_remount(int argc, char* argv[]) {
@@ -340,6 +344,41 @@
         ++it;
     }
 
+    // If (1) remount requires a reboot to take effect, (2) system is currently
+    // running a DSU guest and (3) DSU is disabled, then enable DSU so that the
+    // next reboot would not take us back to the host system but stay within
+    // the guest system.
+    if (reboot_later) {
+        if (auto gsid = android::gsi::GetGsiService()) {
+            auto dsu_running = false;
+            if (auto status = gsid->isGsiRunning(&dsu_running); !status.isOk()) {
+                LOG(ERROR) << "Failed to get DSU running state: " << status;
+                return BINDER_ERROR;
+            }
+            auto dsu_enabled = false;
+            if (auto status = gsid->isGsiEnabled(&dsu_enabled); !status.isOk()) {
+                LOG(ERROR) << "Failed to get DSU enabled state: " << status;
+                return BINDER_ERROR;
+            }
+            if (dsu_running && !dsu_enabled) {
+                std::string dsu_slot;
+                if (auto status = gsid->getActiveDsuSlot(&dsu_slot); !status.isOk()) {
+                    LOG(ERROR) << "Failed to get active DSU slot: " << status;
+                    return BINDER_ERROR;
+                }
+                LOG(INFO) << "DSU is running but disabled, enable DSU so that we stay within the "
+                             "DSU guest system after reboot";
+                int error = 0;
+                if (auto status = gsid->enableGsi(/* oneShot = */ true, dsu_slot, &error);
+                    !status.isOk() || error != android::gsi::IGsiService::INSTALL_OK) {
+                    LOG(ERROR) << "Failed to enable DSU: " << status << ", error code: " << error;
+                    return !status.isOk() ? BINDER_ERROR : GSID_ERROR;
+                }
+                LOG(INFO) << "Successfully enabled DSU (one-shot mode)";
+            }
+        }
+    }
+
     if (partitions.empty() || just_disabled_verity) {
         if (reboot_later) reboot(setup_overlayfs);
         if (user_please_reboot_later) {
diff --git a/fs_mgr/libfs_avb/tests/avb_util_test.cpp b/fs_mgr/libfs_avb/tests/avb_util_test.cpp
index 784eb9c..1827566 100644
--- a/fs_mgr/libfs_avb/tests/avb_util_test.cpp
+++ b/fs_mgr/libfs_avb/tests/avb_util_test.cpp
@@ -216,9 +216,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     1088 bytes\n"
             "Auxiliary Block:          2304 bytes\n"
+            "Public key (sha1):        5227b569de003adc7f8ec3fc03e05dfbd969abad\n"
             "Algorithm:                SHA512_RSA8192\n"
             "Rollback Index:           20\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hashtree descriptor:\n"
@@ -346,9 +348,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     576 bytes\n"
             "Auxiliary Block:          1216 bytes\n"
+            "Public key (sha1):        2597c218aae470a130f61162feaae70afd97f011\n"
             "Algorithm:                SHA256_RSA4096\n"
             "Rollback Index:           10\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hash descriptor:\n"
@@ -639,9 +643,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     1088 bytes\n"
             "Auxiliary Block:          3840 bytes\n"
+            "Public key (sha1):        5227b569de003adc7f8ec3fc03e05dfbd969abad\n"
             "Algorithm:                SHA256_RSA8192\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Chain Partition descriptor:\n"
@@ -854,9 +860,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     1088 bytes\n"
             "Auxiliary Block:          3840 bytes\n"
+            "Public key (sha1):        5227b569de003adc7f8ec3fc03e05dfbd969abad\n"
             "Algorithm:                SHA256_RSA8192\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Chain Partition descriptor:\n"
@@ -886,9 +894,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     576 bytes\n"
             "Auxiliary Block:          2176 bytes\n"
+            "Public key (sha1):        2597c218aae470a130f61162feaae70afd97f011\n"
             "Algorithm:                SHA256_RSA4096\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Chain Partition descriptor:\n"
@@ -936,9 +946,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     320 bytes\n"
             "Auxiliary Block:          960 bytes\n"
+            "Public key (sha1):        cdbb77177f731920bbe0a0f94f84d9038ae0617d\n"
             "Algorithm:                SHA256_RSA2048\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hash descriptor:\n"
diff --git a/fs_mgr/libfs_avb/tests/basic_test.cpp b/fs_mgr/libfs_avb/tests/basic_test.cpp
index 5a1cd0d..1c47c07 100644
--- a/fs_mgr/libfs_avb/tests/basic_test.cpp
+++ b/fs_mgr/libfs_avb/tests/basic_test.cpp
@@ -59,9 +59,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     320 bytes\n"
             "Auxiliary Block:          576 bytes\n"
+            "Public key (sha1):        cdbb77177f731920bbe0a0f94f84d9038ae0617d\n"
             "Algorithm:                SHA256_RSA2048\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    (none)\n",
@@ -89,9 +91,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     576 bytes\n"
             "Auxiliary Block:          1216 bytes\n"
+            "Public key (sha1):        2597c218aae470a130f61162feaae70afd97f011\n"
             "Algorithm:                SHA256_RSA4096\n"
             "Rollback Index:           10\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hash descriptor:\n"
@@ -126,9 +130,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     1088 bytes\n"
             "Auxiliary Block:          2304 bytes\n"
+            "Public key (sha1):        5227b569de003adc7f8ec3fc03e05dfbd969abad\n"
             "Algorithm:                SHA512_RSA8192\n"
             "Rollback Index:           20\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hashtree descriptor:\n"
@@ -180,9 +186,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     320 bytes\n"
             "Auxiliary Block:          960 bytes\n"
+            "Public key (sha1):        cdbb77177f731920bbe0a0f94f84d9038ae0617d\n"
             "Algorithm:                SHA256_RSA2048\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hash descriptor:\n"
@@ -249,9 +257,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     1088 bytes\n"
             "Auxiliary Block:          3840 bytes\n"
+            "Public key (sha1):        5227b569de003adc7f8ec3fc03e05dfbd969abad\n"
             "Algorithm:                SHA256_RSA8192\n"
             "Rollback Index:           0\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Chain Partition descriptor:\n"
diff --git a/fs_mgr/libfs_avb/tests/fs_avb_util_test.cpp b/fs_mgr/libfs_avb/tests/fs_avb_util_test.cpp
index 7c34009..5ec1e90 100644
--- a/fs_mgr/libfs_avb/tests/fs_avb_util_test.cpp
+++ b/fs_mgr/libfs_avb/tests/fs_avb_util_test.cpp
@@ -57,9 +57,11 @@
             "Header Block:             256 bytes\n"
             "Authentication Block:     576 bytes\n"
             "Auxiliary Block:          1280 bytes\n"
+            "Public key (sha1):        2597c218aae470a130f61162feaae70afd97f011\n"
             "Algorithm:                SHA512_RSA4096\n"
             "Rollback Index:           20\n"
             "Flags:                    0\n"
+            "Rollback Index Location:  0\n"
             "Release String:           'unit test'\n"
             "Descriptors:\n"
             "    Hashtree descriptor:\n"
diff --git a/fs_mgr/libsnapshot/android/snapshot/snapshot.proto b/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
index 38c6bf8..36e1169 100644
--- a/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
+++ b/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
@@ -34,7 +34,19 @@
     MERGE_COMPLETED = 3;
 }
 
-// Next: 10
+// Next: 3
+enum MergePhase {
+    // No merge is in progress.
+    NO_MERGE = 0;
+
+    // Shrunk partitions can merge.
+    FIRST_PHASE = 1;
+
+    // Grown partitions can merge.
+    SECOND_PHASE = 2;
+}
+
+// Next: 11
 message SnapshotStatus {
     // Name of the snapshot. This is usually the name of the snapshotted
     // logical partition; for example, "system_b".
@@ -87,6 +99,9 @@
 
     // True if compression is enabled, false otherwise.
     bool compression_enabled = 9;
+
+    // The old partition size (if none existed, this will be zero).
+    uint64 old_partition_size = 10;
 }
 
 // Next: 8
@@ -118,7 +133,7 @@
     Cancelled = 7;
 };
 
-// Next: 6
+// Next: 7
 message SnapshotUpdateStatus {
     UpdateState state = 1;
 
@@ -136,6 +151,9 @@
 
     // Whether compression/dm-user was used for any snapshots.
     bool compression_enabled = 5;
+
+    // Merge phase (if state == MERGING).
+    MergePhase merge_phase = 6;
 }
 
 // Next: 4
diff --git a/fs_mgr/libsnapshot/cow_snapuserd_test.cpp b/fs_mgr/libsnapshot/cow_snapuserd_test.cpp
index 4cc0fd3..0addba3 100644
--- a/fs_mgr/libsnapshot/cow_snapuserd_test.cpp
+++ b/fs_mgr/libsnapshot/cow_snapuserd_test.cpp
@@ -255,17 +255,23 @@
     ASSERT_TRUE(writer.Initialize(cow_system_->fd));
 
     size_t num_blocks = size_ / options.block_size;
-    size_t blk_src_copy = num_blocks;
-    size_t blk_end_copy = blk_src_copy + num_blocks;
-    size_t source_blk = 0;
+    size_t blk_end_copy = num_blocks * 2;
+    size_t source_blk = num_blocks - 1;
+    size_t blk_src_copy = blk_end_copy - 1;
 
-    while (source_blk < num_blocks) {
+    size_t x = num_blocks;
+    while (1) {
         ASSERT_TRUE(writer.AddCopy(source_blk, blk_src_copy));
-        source_blk += 1;
-        blk_src_copy += 1;
+        x -= 1;
+        if (x == 0) {
+            break;
+        }
+        source_blk -= 1;
+        blk_src_copy -= 1;
     }
 
-    ASSERT_EQ(blk_src_copy, blk_end_copy);
+    source_blk = num_blocks;
+    blk_src_copy = blk_end_copy;
 
     ASSERT_TRUE(writer.AddRawBlocks(source_blk, random_buffer_1_.get(), size_));
 
@@ -280,11 +286,9 @@
 
     // Flush operations
     ASSERT_TRUE(writer.Finalize());
-
     // Construct the buffer required for validation
     orig_buffer_ = std::make_unique<uint8_t[]>(total_base_size_);
     std::string zero_buffer(size_, 0);
-
     ASSERT_EQ(android::base::ReadFullyAtOffset(base_fd_, orig_buffer_.get(), size_, size_), true);
     memcpy((char*)orig_buffer_.get() + size_, random_buffer_1_.get(), size_);
     memcpy((char*)orig_buffer_.get() + (size_ * 2), (void*)zero_buffer.c_str(), size_);
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 397ff2e..0a8567f 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -463,6 +463,10 @@
                       const std::string& base_device, const std::chrono::milliseconds& timeout_ms,
                       std::string* path);
 
+    // Map the source device used for dm-user.
+    bool MapSourceDevice(LockedFile* lock, const std::string& name,
+                         const std::chrono::milliseconds& timeout_ms, std::string* path);
+
     // Map a COW image that was previous created with CreateCowImage.
     std::optional<std::string> MapCowImage(const std::string& name,
                                            const std::chrono::milliseconds& timeout_ms);
@@ -521,11 +525,13 @@
     std::string GetMergeStateFilePath() const;
 
     // Helpers for merging.
+    bool MergeSecondPhaseSnapshots(LockedFile* lock);
     bool SwitchSnapshotToMerge(LockedFile* lock, const std::string& name);
     bool RewriteSnapshotDeviceTable(const std::string& dm_name);
     bool MarkSnapshotMergeCompleted(LockedFile* snapshot_lock, const std::string& snapshot_name);
     void AcknowledgeMergeSuccess(LockedFile* lock);
     void AcknowledgeMergeFailure();
+    MergePhase DecideMergePhase(const SnapshotStatus& status);
     std::unique_ptr<LpMetadata> ReadCurrentMetadata();
 
     enum class MetadataPartitionState {
@@ -558,7 +564,8 @@
     //   UpdateState::MergeNeedsReboot
     UpdateState CheckMergeState(const std::function<bool()>& before_cancel);
     UpdateState CheckMergeState(LockedFile* lock, const std::function<bool()>& before_cancel);
-    UpdateState CheckTargetMergeState(LockedFile* lock, const std::string& name);
+    UpdateState CheckTargetMergeState(LockedFile* lock, const std::string& name,
+                                      const SnapshotUpdateStatus& update_status);
 
     // Interact with status files under /metadata/ota/snapshots.
     bool WriteSnapshotStatus(LockedFile* lock, const SnapshotStatus& status);
@@ -568,12 +575,9 @@
     std::string GetSnapshotBootIndicatorPath();
     std::string GetRollbackIndicatorPath();
     std::string GetForwardMergeIndicatorPath();
+    std::string GetOldPartitionMetadataPath();
 
-    // Return the name of the device holding the "snapshot" or "snapshot-merge"
-    // target. This may not be the final device presented via MapSnapshot(), if
-    // for example there is a linear segment.
-    std::string GetSnapshotDeviceName(const std::string& snapshot_name,
-                                      const SnapshotStatus& status);
+    const LpMetadata* ReadOldPartitionMetadata(LockedFile* lock);
 
     bool MapAllPartitions(LockedFile* lock, const std::string& super_device, uint32_t slot,
                           const std::chrono::milliseconds& timeout_ms);
@@ -673,8 +677,8 @@
 
     // Helper for RemoveAllSnapshots.
     // Check whether |name| should be deleted as a snapshot name.
-    bool ShouldDeleteSnapshot(LockedFile* lock, const std::map<std::string, bool>& flashing_status,
-                              Slot current_slot, const std::string& name);
+    bool ShouldDeleteSnapshot(const std::map<std::string, bool>& flashing_status, Slot current_slot,
+                              const std::string& name);
 
     // Create or delete forward merge indicator given |wipe|. Iff wipe is scheduled,
     // allow forward merge on FDR.
@@ -722,6 +726,7 @@
     bool in_factory_data_reset_ = false;
     std::function<bool(const std::string&)> uevent_regen_callback_;
     std::unique_ptr<SnapuserdClient> snapuserd_client_;
+    std::unique_ptr<LpMetadata> old_partition_metadata_;
 };
 
 }  // namespace snapshot
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 21b720e..ebda430 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -132,8 +132,8 @@
     return partition_name + "-base";
 }
 
-static std::string GetSnapshotExtraDeviceName(const std::string& snapshot_name) {
-    return snapshot_name + "-inner";
+static std::string GetSourceDeviceName(const std::string& partition_name) {
+    return partition_name + "-src";
 }
 
 bool SnapshotManager::BeginUpdate() {
@@ -157,6 +157,9 @@
         images_->RemoveAllImages();
     }
 
+    // Clear any cached metadata (this allows re-using one manager across tests).
+    old_partition_metadata_ = nullptr;
+
     auto state = ReadUpdateState(file.get());
     if (state != UpdateState::None) {
         LOG(ERROR) << "An update is already in progress, cannot begin a new update";
@@ -255,6 +258,7 @@
             GetSnapshotBootIndicatorPath(),
             GetRollbackIndicatorPath(),
             GetForwardMergeIndicatorPath(),
+            GetOldPartitionMetadataPath(),
     };
     for (const auto& file : files) {
         RemoveFileIfExists(file);
@@ -465,8 +469,13 @@
         LOG(ERROR) << "Invalid snapshot size for " << base_device << ": " << status.snapshot_size();
         return false;
     }
+    if (status.device_size() != status.snapshot_size()) {
+        LOG(ERROR) << "Device size and snapshot size must be the same (device size = "
+                   << status.device_size() << ", snapshot size = " << status.snapshot_size();
+        return false;
+    }
+
     uint64_t snapshot_sectors = status.snapshot_size() / kSectorSize;
-    uint64_t linear_sectors = (status.device_size() - status.snapshot_size()) / kSectorSize;
 
     auto& dm = DeviceMapper::Instance();
 
@@ -474,7 +483,8 @@
     // have completed merging, but the start of the merge process is considered
     // atomic.
     SnapshotStorageMode mode;
-    switch (ReadUpdateState(lock)) {
+    SnapshotUpdateStatus update_status = ReadSnapshotUpdateStatus(lock);
+    switch (update_status.state()) {
         case UpdateState::MergeCompleted:
         case UpdateState::MergeNeedsReboot:
             LOG(ERROR) << "Should not create a snapshot device for " << name
@@ -484,52 +494,24 @@
         case UpdateState::MergeFailed:
             // Note: MergeFailed indicates that a merge is in progress, but
             // is possibly stalled. We still have to honor the merge.
-            mode = SnapshotStorageMode::Merge;
+            if (DecideMergePhase(status) == update_status.merge_phase()) {
+                mode = SnapshotStorageMode::Merge;
+            } else {
+                mode = SnapshotStorageMode::Persistent;
+            }
             break;
         default:
             mode = SnapshotStorageMode::Persistent;
             break;
     }
 
-    // The kernel (tested on 4.19) crashes horribly if a device has both a snapshot
-    // and a linear target in the same table. Instead, we stack them, and give the
-    // snapshot device a different name. It is not exposed to the caller in this
-    // case.
-    auto snap_name = (linear_sectors > 0) ? GetSnapshotExtraDeviceName(name) : name;
-
     DmTable table;
     table.Emplace<DmTargetSnapshot>(0, snapshot_sectors, base_device, cow_device, mode,
                                     kSnapshotChunkSize);
-    if (!dm.CreateDevice(snap_name, table, dev_path, timeout_ms)) {
-        LOG(ERROR) << "Could not create snapshot device: " << snap_name;
+    if (!dm.CreateDevice(name, table, dev_path, timeout_ms)) {
+        LOG(ERROR) << "Could not create snapshot device: " << name;
         return false;
     }
-
-    if (linear_sectors) {
-        std::string snap_dev;
-        if (!dm.GetDeviceString(snap_name, &snap_dev)) {
-            LOG(ERROR) << "Cannot determine major/minor for: " << snap_name;
-            return false;
-        }
-
-        // Our stacking will looks like this:
-        //     [linear, linear] ; to snapshot, and non-snapshot region of base device
-        //     [snapshot-inner]
-        //     [base device]   [cow]
-        DmTable table;
-        table.Emplace<DmTargetLinear>(0, snapshot_sectors, snap_dev, 0);
-        table.Emplace<DmTargetLinear>(snapshot_sectors, linear_sectors, base_device,
-                                      snapshot_sectors);
-        if (!dm.CreateDevice(name, table, dev_path, timeout_ms)) {
-            LOG(ERROR) << "Could not create outer snapshot device: " << name;
-            dm.DeleteDevice(snap_name);
-            return false;
-        }
-    }
-
-    // :TODO: when merging is implemented, we need to add an argument to the
-    // status indicating how much progress is left to merge. (device-mapper
-    // does not retain the initial values, so we can't derive them.)
     return true;
 }
 
@@ -557,6 +539,36 @@
     return std::nullopt;
 }
 
+bool SnapshotManager::MapSourceDevice(LockedFile* lock, const std::string& name,
+                                      const std::chrono::milliseconds& timeout_ms,
+                                      std::string* path) {
+    CHECK(lock);
+
+    auto metadata = ReadOldPartitionMetadata(lock);
+    if (!metadata) {
+        LOG(ERROR) << "Could not map source device due to missing or corrupt metadata";
+        return false;
+    }
+
+    auto old_name = GetOtherPartitionName(name);
+    auto slot_suffix = device_->GetSlotSuffix();
+    auto slot = SlotNumberForSlotSuffix(slot_suffix);
+
+    CreateLogicalPartitionParams params = {
+            .block_device = device_->GetSuperDevice(slot),
+            .metadata = metadata,
+            .partition_name = old_name,
+            .timeout_ms = timeout_ms,
+            .device_name = GetSourceDeviceName(name),
+            .partition_opener = &device_->GetPartitionOpener(),
+    };
+    if (!CreateLogicalPartition(std::move(params), path)) {
+        LOG(ERROR) << "Could not create source device for snapshot " << name;
+        return false;
+    }
+    return true;
+}
+
 bool SnapshotManager::UnmapSnapshot(LockedFile* lock, const std::string& name) {
     CHECK(lock);
 
@@ -565,13 +577,6 @@
         LOG(ERROR) << "Could not delete snapshot device: " << name;
         return false;
     }
-
-    auto snapshot_extra_device = GetSnapshotExtraDeviceName(name);
-    if (!dm.DeleteDeviceIfExists(snapshot_extra_device)) {
-        LOG(ERROR) << "Could not delete snapshot inner device: " << snapshot_extra_device;
-        return false;
-    }
-
     return true;
 }
 
@@ -678,6 +683,8 @@
 
     bool compression_enabled = false;
 
+    std::vector<std::string> first_merge_group;
+
     uint64_t total_cow_file_size = 0;
     DmTargetSnapshot::Status initial_target_values = {};
     for (const auto& snapshot : snapshots) {
@@ -696,6 +703,9 @@
         total_cow_file_size += snapshot_status.cow_file_size();
 
         compression_enabled |= snapshot_status.compression_enabled();
+        if (DecideMergePhase(snapshot_status) == MergePhase::FIRST_PHASE) {
+            first_merge_group.emplace_back(snapshot);
+        }
     }
 
     if (cow_file_size) {
@@ -709,14 +719,26 @@
     initial_status.set_metadata_sectors(initial_target_values.metadata_sectors);
     initial_status.set_compression_enabled(compression_enabled);
 
+    // If any partitions shrunk, we need to merge them before we merge any other
+    // partitions (see b/177935716). Otherwise, a merge from another partition
+    // may overwrite the source block of a copy operation.
+    const std::vector<std::string>* merge_group;
+    if (first_merge_group.empty()) {
+        merge_group = &snapshots;
+        initial_status.set_merge_phase(MergePhase::SECOND_PHASE);
+    } else {
+        merge_group = &first_merge_group;
+        initial_status.set_merge_phase(MergePhase::FIRST_PHASE);
+    }
+
     // Point of no return - mark that we're starting a merge. From now on every
-    // snapshot must be a merge target.
+    // eligible snapshot must be a merge target.
     if (!WriteSnapshotUpdateStatus(lock.get(), initial_status)) {
         return false;
     }
 
     bool rewrote_all = true;
-    for (const auto& snapshot : snapshots) {
+    for (const auto& snapshot : *merge_group) {
         // If this fails, we have no choice but to continue. Everything must
         // be merged. This is not an ideal state to be in, but it is safe,
         // because we the next boot will try again.
@@ -749,16 +771,15 @@
 
     // After this, we return true because we technically did switch to a merge
     // target. Everything else we do here is just informational.
-    auto dm_name = GetSnapshotDeviceName(name, status);
-    if (!RewriteSnapshotDeviceTable(dm_name)) {
+    if (!RewriteSnapshotDeviceTable(name)) {
         return false;
     }
 
     status.set_state(SnapshotState::MERGING);
 
     DmTargetSnapshot::Status dm_status;
-    if (!QuerySnapshotStatus(dm_name, nullptr, &dm_status)) {
-        LOG(ERROR) << "Could not query merge status for snapshot: " << dm_name;
+    if (!QuerySnapshotStatus(name, nullptr, &dm_status)) {
+        LOG(ERROR) << "Could not query merge status for snapshot: " << name;
     }
     status.set_sectors_allocated(dm_status.sectors_allocated);
     status.set_metadata_sectors(dm_status.metadata_sectors);
@@ -768,33 +789,33 @@
     return true;
 }
 
-bool SnapshotManager::RewriteSnapshotDeviceTable(const std::string& dm_name) {
+bool SnapshotManager::RewriteSnapshotDeviceTable(const std::string& name) {
     auto& dm = DeviceMapper::Instance();
 
     std::vector<DeviceMapper::TargetInfo> old_targets;
-    if (!dm.GetTableInfo(dm_name, &old_targets)) {
-        LOG(ERROR) << "Could not read snapshot device table: " << dm_name;
+    if (!dm.GetTableInfo(name, &old_targets)) {
+        LOG(ERROR) << "Could not read snapshot device table: " << name;
         return false;
     }
     if (old_targets.size() != 1 || DeviceMapper::GetTargetType(old_targets[0].spec) != "snapshot") {
-        LOG(ERROR) << "Unexpected device-mapper table for snapshot: " << dm_name;
+        LOG(ERROR) << "Unexpected device-mapper table for snapshot: " << name;
         return false;
     }
 
     std::string base_device, cow_device;
     if (!DmTargetSnapshot::GetDevicesFromParams(old_targets[0].data, &base_device, &cow_device)) {
-        LOG(ERROR) << "Could not derive underlying devices for snapshot: " << dm_name;
+        LOG(ERROR) << "Could not derive underlying devices for snapshot: " << name;
         return false;
     }
 
     DmTable table;
     table.Emplace<DmTargetSnapshot>(0, old_targets[0].spec.length, base_device, cow_device,
                                     SnapshotStorageMode::Merge, kSnapshotChunkSize);
-    if (!dm.LoadTableAndActivate(dm_name, table)) {
-        LOG(ERROR) << "Could not swap device-mapper tables on snapshot device " << dm_name;
+    if (!dm.LoadTableAndActivate(name, table)) {
+        LOG(ERROR) << "Could not swap device-mapper tables on snapshot device " << name;
         return false;
     }
-    LOG(INFO) << "Successfully switched snapshot device to a merge target: " << dm_name;
+    LOG(INFO) << "Successfully switched snapshot device to a merge target: " << name;
     return true;
 }
 
@@ -908,13 +929,13 @@
 
 UpdateState SnapshotManager::CheckMergeState(LockedFile* lock,
                                              const std::function<bool()>& before_cancel) {
-    UpdateState state = ReadUpdateState(lock);
-    switch (state) {
+    SnapshotUpdateStatus update_status = ReadSnapshotUpdateStatus(lock);
+    switch (update_status.state()) {
         case UpdateState::None:
         case UpdateState::MergeCompleted:
             // Harmless races are allowed between two callers of WaitForMerge,
             // so in both of these cases we just propagate the state.
-            return state;
+            return update_status.state();
 
         case UpdateState::Merging:
         case UpdateState::MergeNeedsReboot:
@@ -931,10 +952,10 @@
             if (HandleCancelledUpdate(lock, before_cancel)) {
                 return UpdateState::Cancelled;
             }
-            return state;
+            return update_status.state();
 
         default:
-            return state;
+            return update_status.state();
     }
 
     std::vector<std::string> snapshots;
@@ -946,8 +967,9 @@
     bool failed = false;
     bool merging = false;
     bool needs_reboot = false;
+    bool wrong_phase = false;
     for (const auto& snapshot : snapshots) {
-        UpdateState snapshot_state = CheckTargetMergeState(lock, snapshot);
+        UpdateState snapshot_state = CheckTargetMergeState(lock, snapshot, update_status);
         switch (snapshot_state) {
             case UpdateState::MergeFailed:
                 failed = true;
@@ -963,6 +985,9 @@
             case UpdateState::Cancelled:
                 cancelled = true;
                 break;
+            case UpdateState::None:
+                wrong_phase = true;
+                break;
             default:
                 LOG(ERROR) << "Unknown merge status for \"" << snapshot << "\": "
                            << "\"" << snapshot_state << "\"";
@@ -982,6 +1007,14 @@
         // it in WaitForMerge rather than here and elsewhere.
         return UpdateState::MergeFailed;
     }
+    if (wrong_phase) {
+        // If we got here, no other partitions are being merged, and nothing
+        // failed to merge. It's safe to move to the next merge phase.
+        if (!MergeSecondPhaseSnapshots(lock)) {
+            return UpdateState::MergeFailed;
+        }
+        return UpdateState::Merging;
+    }
     if (needs_reboot) {
         WriteUpdateState(lock, UpdateState::MergeNeedsReboot);
         return UpdateState::MergeNeedsReboot;
@@ -997,17 +1030,16 @@
     return UpdateState::MergeCompleted;
 }
 
-UpdateState SnapshotManager::CheckTargetMergeState(LockedFile* lock, const std::string& name) {
+UpdateState SnapshotManager::CheckTargetMergeState(LockedFile* lock, const std::string& name,
+                                                   const SnapshotUpdateStatus& update_status) {
     SnapshotStatus snapshot_status;
     if (!ReadSnapshotStatus(lock, name, &snapshot_status)) {
         return UpdateState::MergeFailed;
     }
 
-    std::string dm_name = GetSnapshotDeviceName(name, snapshot_status);
-
     std::unique_ptr<LpMetadata> current_metadata;
 
-    if (!IsSnapshotDevice(dm_name)) {
+    if (!IsSnapshotDevice(name)) {
         if (!current_metadata) {
             current_metadata = ReadCurrentMetadata();
         }
@@ -1021,7 +1053,7 @@
         // During a check, we decided the merge was complete, but we were unable to
         // collapse the device-mapper stack and perform COW cleanup. If we haven't
         // rebooted after this check, the device will still be a snapshot-merge
-        // target. If the have rebooted, the device will now be a linear target,
+        // target. If we have rebooted, the device will now be a linear target,
         // and we can try cleanup again.
         if (snapshot_status.state() == SnapshotState::MERGE_COMPLETED) {
             // NB: It's okay if this fails now, we gave cleanup our best effort.
@@ -1029,7 +1061,7 @@
             return UpdateState::MergeCompleted;
         }
 
-        LOG(ERROR) << "Expected snapshot or snapshot-merge for device: " << dm_name;
+        LOG(ERROR) << "Expected snapshot or snapshot-merge for device: " << name;
         return UpdateState::MergeFailed;
     }
 
@@ -1039,9 +1071,15 @@
 
     std::string target_type;
     DmTargetSnapshot::Status status;
-    if (!QuerySnapshotStatus(dm_name, &target_type, &status)) {
+    if (!QuerySnapshotStatus(name, &target_type, &status)) {
         return UpdateState::MergeFailed;
     }
+    if (target_type == "snapshot" &&
+        DecideMergePhase(snapshot_status) == MergePhase::SECOND_PHASE &&
+        update_status.merge_phase() == MergePhase::FIRST_PHASE) {
+        // The snapshot is not being merged because it's in the wrong phase.
+        return UpdateState::None;
+    }
     if (target_type != "snapshot-merge") {
         // We can get here if we failed to rewrite the target type in
         // InitiateMerge(). If we failed to create the target in first-stage
@@ -1077,6 +1115,38 @@
     return UpdateState::MergeCompleted;
 }
 
+bool SnapshotManager::MergeSecondPhaseSnapshots(LockedFile* lock) {
+    std::vector<std::string> snapshots;
+    if (!ListSnapshots(lock, &snapshots)) {
+        return UpdateState::MergeFailed;
+    }
+
+    SnapshotUpdateStatus update_status = ReadSnapshotUpdateStatus(lock);
+    CHECK(update_status.state() == UpdateState::Merging);
+    CHECK(update_status.merge_phase() == MergePhase::FIRST_PHASE);
+
+    update_status.set_merge_phase(MergePhase::SECOND_PHASE);
+    if (!WriteSnapshotUpdateStatus(lock, update_status)) {
+        return false;
+    }
+
+    bool rewrote_all = true;
+    for (const auto& snapshot : snapshots) {
+        SnapshotStatus snapshot_status;
+        if (!ReadSnapshotStatus(lock, snapshot, &snapshot_status)) {
+            return UpdateState::MergeFailed;
+        }
+        if (DecideMergePhase(snapshot_status) != MergePhase::SECOND_PHASE) {
+            continue;
+        }
+        if (!SwitchSnapshotToMerge(lock, snapshot)) {
+            LOG(ERROR) << "Failed to switch snapshot to a second-phase merge target: " << snapshot;
+            rewrote_all = false;
+        }
+    }
+    return rewrote_all;
+}
+
 std::string SnapshotManager::GetSnapshotBootIndicatorPath() {
     return metadata_dir_ + "/" + android::base::Basename(kBootIndicatorPath);
 }
@@ -1089,6 +1159,10 @@
     return metadata_dir_ + "/allow-forward-merge";
 }
 
+std::string SnapshotManager::GetOldPartitionMetadataPath() {
+    return metadata_dir_ + "/old-partition-metadata";
+}
+
 void SnapshotManager::AcknowledgeMergeSuccess(LockedFile* lock) {
     // It's not possible to remove update state in recovery, so write an
     // indicator that cleanup is needed on reboot. If a factory data reset
@@ -1124,21 +1198,20 @@
 
 bool SnapshotManager::OnSnapshotMergeComplete(LockedFile* lock, const std::string& name,
                                               const SnapshotStatus& status) {
-    auto dm_name = GetSnapshotDeviceName(name, status);
-    if (IsSnapshotDevice(dm_name)) {
+    if (IsSnapshotDevice(name)) {
         // We are extra-cautious here, to avoid deleting the wrong table.
         std::string target_type;
         DmTargetSnapshot::Status dm_status;
-        if (!QuerySnapshotStatus(dm_name, &target_type, &dm_status)) {
+        if (!QuerySnapshotStatus(name, &target_type, &dm_status)) {
             return false;
         }
         if (target_type != "snapshot-merge") {
             LOG(ERROR) << "Unexpected target type " << target_type
-                       << " for snapshot device: " << dm_name;
+                       << " for snapshot device: " << name;
             return false;
         }
         if (dm_status.sectors_allocated != dm_status.metadata_sectors) {
-            LOG(ERROR) << "Merge is unexpectedly incomplete for device " << dm_name;
+            LOG(ERROR) << "Merge is unexpectedly incomplete for device " << name;
             return false;
         }
         if (!CollapseSnapshotDevice(name, status)) {
@@ -1159,23 +1232,21 @@
 bool SnapshotManager::CollapseSnapshotDevice(const std::string& name,
                                              const SnapshotStatus& status) {
     auto& dm = DeviceMapper::Instance();
-    auto dm_name = GetSnapshotDeviceName(name, status);
 
     // Verify we have a snapshot-merge device.
     DeviceMapper::TargetInfo target;
-    if (!GetSingleTarget(dm_name, TableQuery::Table, &target)) {
+    if (!GetSingleTarget(name, TableQuery::Table, &target)) {
         return false;
     }
     if (DeviceMapper::GetTargetType(target.spec) != "snapshot-merge") {
         // This should be impossible, it was checked earlier.
-        LOG(ERROR) << "Snapshot device has invalid target type: " << dm_name;
+        LOG(ERROR) << "Snapshot device has invalid target type: " << name;
         return false;
     }
 
     std::string base_device, cow_device;
     if (!DmTargetSnapshot::GetDevicesFromParams(target.data, &base_device, &cow_device)) {
-        LOG(ERROR) << "Could not parse snapshot device " << dm_name
-                   << " parameters: " << target.data;
+        LOG(ERROR) << "Could not parse snapshot device " << name << " parameters: " << target.data;
         return false;
     }
 
@@ -1186,42 +1257,6 @@
         return false;
     }
 
-    if (dm_name != name) {
-        // We've derived the base device, but we actually need to replace the
-        // table of the outermost device. Do a quick verification that this
-        // device looks like we expect it to.
-        std::vector<DeviceMapper::TargetInfo> outer_table;
-        if (!dm.GetTableInfo(name, &outer_table)) {
-            LOG(ERROR) << "Could not validate outer snapshot table: " << name;
-            return false;
-        }
-        if (outer_table.size() != 2) {
-            LOG(ERROR) << "Expected 2 dm-linear targets for table " << name
-                       << ", got: " << outer_table.size();
-            return false;
-        }
-        for (const auto& target : outer_table) {
-            auto target_type = DeviceMapper::GetTargetType(target.spec);
-            if (target_type != "linear") {
-                LOG(ERROR) << "Outer snapshot table may only contain linear targets, but " << name
-                           << " has target: " << target_type;
-                return false;
-            }
-        }
-        if (outer_table[0].spec.length != snapshot_sectors) {
-            LOG(ERROR) << "dm-snapshot " << name << " should have " << snapshot_sectors
-                       << " sectors, got: " << outer_table[0].spec.length;
-            return false;
-        }
-        uint64_t expected_device_sectors = status.device_size() / kSectorSize;
-        uint64_t actual_device_sectors = outer_table[0].spec.length + outer_table[1].spec.length;
-        if (expected_device_sectors != actual_device_sectors) {
-            LOG(ERROR) << "Outer device " << name << " should have " << expected_device_sectors
-                       << " sectors, got: " << actual_device_sectors;
-            return false;
-        }
-    }
-
     uint32_t slot = SlotNumberForSlotSuffix(device_->GetSlotSuffix());
     // Create a DmTable that is identical to the base device.
     CreateLogicalPartitionParams base_device_params{
@@ -1236,7 +1271,6 @@
         return false;
     }
 
-    // Note: we are replacing the *outer* table here, so we do not use dm_name.
     if (!dm.LoadTableAndActivate(name, table)) {
         return false;
     }
@@ -1246,22 +1280,17 @@
     // flushed remaining I/O. We could in theory replace with dm-zero (or
     // re-use the table above), but for now it's better to know why this
     // would fail.
-    if (dm_name != name && !dm.DeleteDeviceIfExists(dm_name)) {
-        LOG(ERROR) << "Unable to delete snapshot device " << dm_name << ", COW cannot be "
-                   << "reclaimed until after reboot.";
-        return false;
-    }
-
     if (status.compression_enabled()) {
         UnmapDmUserDevice(name);
     }
-
-    // Cleanup the base device as well, since it is no longer used. This does
-    // not block cleanup.
     auto base_name = GetBaseDeviceName(name);
     if (!dm.DeleteDeviceIfExists(base_name)) {
         LOG(ERROR) << "Unable to delete base device for snapshot: " << base_name;
     }
+    auto source_name = GetSourceDeviceName(name);
+    if (!dm.DeleteDeviceIfExists(source_name)) {
+        LOG(ERROR) << "Unable to delete source device for snapshot: " << source_name;
+    }
     return true;
 }
 
@@ -1364,9 +1393,9 @@
             continue;
         }
 
-        std::string backing_device;
-        if (!dm.GetDmDevicePathByName(GetBaseDeviceName(snapshot), &backing_device)) {
-            LOG(ERROR) << "Could not get device path for " << GetBaseDeviceName(snapshot);
+        std::string source_device;
+        if (!dm.GetDmDevicePathByName(GetSourceDeviceName(snapshot), &source_device)) {
+            LOG(ERROR) << "Could not get device path for " << GetSourceDeviceName(snapshot);
             continue;
         }
 
@@ -1392,7 +1421,7 @@
         }
 
         if (transition == InitTransition::SELINUX_DETACH) {
-            auto message = misc_name + "," + cow_image_device + "," + backing_device;
+            auto message = misc_name + "," + cow_image_device + "," + source_device;
             snapuserd_argv->emplace_back(std::move(message));
 
             // Do not attempt to connect to the new snapuserd yet, it hasn't
@@ -1403,7 +1432,7 @@
         }
 
         uint64_t base_sectors =
-                snapuserd_client_->InitDmUserCow(misc_name, cow_image_device, backing_device);
+                snapuserd_client_->InitDmUserCow(misc_name, cow_image_device, source_device);
         if (base_sectors == 0) {
             // Unrecoverable as metadata reads from cow device failed
             LOG(FATAL) << "Failed to retrieve base_sectors from Snapuserd";
@@ -1548,7 +1577,7 @@
         //    Otherwise (UPDATED flag), only delete snapshots if they are not mapped
         //    as dm-snapshot (for example, after merge completes).
         bool should_unmap = current_slot != Slot::Target;
-        bool should_delete = ShouldDeleteSnapshot(lock, flashing_status, current_slot, name);
+        bool should_delete = ShouldDeleteSnapshot(flashing_status, current_slot, name);
 
         bool partition_ok = true;
         if (should_unmap && !UnmapPartitionWithSnapshot(lock, name)) {
@@ -1582,8 +1611,7 @@
 }
 
 // See comments in RemoveAllSnapshots().
-bool SnapshotManager::ShouldDeleteSnapshot(LockedFile* lock,
-                                           const std::map<std::string, bool>& flashing_status,
+bool SnapshotManager::ShouldDeleteSnapshot(const std::map<std::string, bool>& flashing_status,
                                            Slot current_slot, const std::string& name) {
     if (current_slot != Slot::Target) {
         return true;
@@ -1597,16 +1625,7 @@
         // partition flashed, okay to delete obsolete snapshots
         return true;
     }
-    // partition updated, only delete if not dm-snapshot
-    SnapshotStatus status;
-    if (!ReadSnapshotStatus(lock, name, &status)) {
-        LOG(WARNING) << "Unable to read snapshot status for " << name
-                     << ", guessing snapshot device name";
-        auto extra_name = GetSnapshotExtraDeviceName(name);
-        return !IsSnapshotDevice(name) && !IsSnapshotDevice(extra_name);
-    }
-    auto dm_name = GetSnapshotDeviceName(name, status);
-    return !IsSnapshotDevice(dm_name);
+    return !IsSnapshotDevice(name);
 }
 
 UpdateState SnapshotManager::GetUpdateState(double* progress) {
@@ -1922,24 +1941,35 @@
     }
 
     if (live_snapshot_status->compression_enabled()) {
-        auto name = GetDmUserCowName(params.GetPartitionName());
+        // Get the source device (eg the view of the partition from before it was resized).
+        std::string source_device_path;
+        if (!MapSourceDevice(lock, params.GetPartitionName(), remaining_time,
+                             &source_device_path)) {
+            LOG(ERROR) << "Could not map source device for: " << cow_name;
+            return false;
+        }
+
+        auto source_device = GetSourceDeviceName(params.GetPartitionName());
+        created_devices.EmplaceBack<AutoUnmapDevice>(&dm, source_device);
+
+        if (!WaitForDevice(source_device_path, remaining_time)) {
+            return false;
+        }
 
         std::string cow_path;
         if (!GetMappedImageDevicePath(cow_name, &cow_path)) {
             LOG(ERROR) << "Could not determine path for: " << cow_name;
             return false;
         }
-
-        // Ensure both |base_path| and |cow_path| are created, for snapuserd.
-        if (!WaitForDevice(base_path, remaining_time)) {
-            return false;
-        }
         if (!WaitForDevice(cow_path, remaining_time)) {
             return false;
         }
 
+        auto name = GetDmUserCowName(params.GetPartitionName());
+
         std::string new_cow_device;
-        if (!MapDmUserCow(lock, name, cow_path, base_path, remaining_time, &new_cow_device)) {
+        if (!MapDmUserCow(lock, name, cow_path, source_device_path, remaining_time,
+                          &new_cow_device)) {
             LOG(ERROR) << "Could not map dm-user device for partition "
                        << params.GetPartitionName();
             return false;
@@ -1983,12 +2013,18 @@
     }
 
     auto& dm = DeviceMapper::Instance();
-    std::string base_name = GetBaseDeviceName(target_partition_name);
+    auto base_name = GetBaseDeviceName(target_partition_name);
     if (!dm.DeleteDeviceIfExists(base_name)) {
         LOG(ERROR) << "Cannot delete base device: " << base_name;
         return false;
     }
 
+    auto source_name = GetSourceDeviceName(target_partition_name);
+    if (!dm.DeleteDeviceIfExists(source_name)) {
+        LOG(ERROR) << "Cannot delete source device: " << source_name;
+        return false;
+    }
+
     LOG(INFO) << "Successfully unmapped snapshot " << target_partition_name;
 
     return true;
@@ -2409,14 +2445,6 @@
     return true;
 }
 
-std::string SnapshotManager::GetSnapshotDeviceName(const std::string& snapshot_name,
-                                                   const SnapshotStatus& status) {
-    if (status.device_size() != status.snapshot_size()) {
-        return GetSnapshotExtraDeviceName(snapshot_name);
-    }
-    return snapshot_name;
-}
-
 bool SnapshotManager::EnsureImageManager() {
     if (images_) return true;
 
@@ -2588,6 +2616,24 @@
         return Return::Error();
     }
 
+    // If compression is enabled, we need to retain a copy of the old metadata
+    // so we can access original blocks in case they are moved around. We do
+    // not want to rely on the old super metadata slot because we don't
+    // guarantee its validity after the slot switch is successful.
+    if (cow_creator.compression_enabled) {
+        auto metadata = current_metadata->Export();
+        if (!metadata) {
+            LOG(ERROR) << "Could not export current metadata";
+            return Return::Error();
+        }
+
+        auto path = GetOldPartitionMetadataPath();
+        if (!android::fs_mgr::WriteToImageFile(path, *metadata.get())) {
+            LOG(ERROR) << "Cannot write old metadata to " << path;
+            return Return::Error();
+        }
+    }
+
     SnapshotUpdateStatus status = {};
     status.set_state(update_state);
     status.set_compression_enabled(cow_creator.compression_enabled);
@@ -2688,6 +2734,15 @@
             continue;
         }
 
+        // Find the original partition size.
+        auto name = target_partition->name();
+        auto old_partition_name =
+                name.substr(0, name.size() - target_suffix.size()) + cow_creator->current_suffix;
+        auto old_partition = cow_creator->current_metadata->FindPartition(old_partition_name);
+        if (old_partition) {
+            cow_creator_ret->snapshot_status.set_old_partition_size(old_partition->size());
+        }
+
         // Store these device sizes to snapshot status file.
         if (!CreateSnapshot(lock, &cow_creator_ret->snapshot_status)) {
             return Return::Error();
@@ -3375,5 +3430,26 @@
     return PerformInitTransition(InitTransition::SECOND_STAGE);
 }
 
+const LpMetadata* SnapshotManager::ReadOldPartitionMetadata(LockedFile* lock) {
+    CHECK(lock);
+
+    if (!old_partition_metadata_) {
+        auto path = GetOldPartitionMetadataPath();
+        old_partition_metadata_ = android::fs_mgr::ReadFromImageFile(path);
+        if (!old_partition_metadata_) {
+            LOG(ERROR) << "Could not read old partition metadata from " << path;
+            return nullptr;
+        }
+    }
+    return old_partition_metadata_.get();
+}
+
+MergePhase SnapshotManager::DecideMergePhase(const SnapshotStatus& status) {
+    if (status.compression_enabled() && status.device_size() < status.old_partition_size()) {
+        return MergePhase::FIRST_PHASE;
+    }
+    return MergePhase::SECOND_PHASE;
+}
+
 }  // namespace snapshot
 }  // namespace android
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index 80a6074..4c209ec 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -234,7 +234,8 @@
                 .partition_opener = &opener,
         };
 
-        auto result = sm->OpenSnapshotWriter(params, {});
+        auto old_partition = "/dev/block/mapper/" + GetOtherPartitionName(name);
+        auto result = sm->OpenSnapshotWriter(params, {old_partition});
         if (!result) {
             return AssertionFailure() << "Cannot open snapshot for writing: " << name;
         }
@@ -467,31 +468,6 @@
     ASSERT_TRUE(android::base::StartsWith(snap_device, "/dev/block/dm-"));
 }
 
-TEST_F(SnapshotTest, MapPartialSnapshot) {
-    ASSERT_TRUE(AcquireLock());
-
-    static const uint64_t kSnapshotSize = 1024 * 1024;
-    static const uint64_t kDeviceSize = 1024 * 1024 * 2;
-    SnapshotStatus status;
-    status.set_name("test-snapshot");
-    status.set_device_size(kDeviceSize);
-    status.set_snapshot_size(kSnapshotSize);
-    status.set_cow_file_size(kSnapshotSize);
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
-    ASSERT_TRUE(CreateCowImage("test-snapshot"));
-
-    std::string base_device;
-    ASSERT_TRUE(CreatePartition("base-device", kDeviceSize, &base_device));
-
-    std::string cow_device;
-    ASSERT_TRUE(MapCowImage("test-snapshot", 10s, &cow_device));
-
-    std::string snap_device;
-    ASSERT_TRUE(sm->MapSnapshot(lock_.get(), "test-snapshot", base_device, cow_device, 10s,
-                                &snap_device));
-    ASSERT_TRUE(android::base::StartsWith(snap_device, "/dev/block/dm-"));
-}
-
 TEST_F(SnapshotTest, NoMergeBeforeReboot) {
     ASSERT_TRUE(sm->FinishedSnapshotWrites(false));
 
@@ -590,8 +566,7 @@
     ASSERT_EQ(status.state(), SnapshotState::CREATED);
 
     DeviceMapper::TargetInfo target;
-    auto dm_name = init->GetSnapshotDeviceName("test_partition_b", status);
-    ASSERT_TRUE(init->IsSnapshotDevice(dm_name, &target));
+    ASSERT_TRUE(init->IsSnapshotDevice("test_partition_b", &target));
     ASSERT_EQ(DeviceMapper::GetTargetType(target.spec), "snapshot");
 }
 
@@ -618,8 +593,7 @@
 
     // We should not get a snapshot device now.
     DeviceMapper::TargetInfo target;
-    auto dm_name = init->GetSnapshotDeviceName("test_partition_b", status);
-    ASSERT_FALSE(init->IsSnapshotDevice(dm_name, &target));
+    ASSERT_FALSE(init->IsSnapshotDevice("test_partition_b", &target));
 
     // We should see a cancelled update as well.
     lock_ = nullptr;
diff --git a/fs_mgr/libsnapshot/snapuserd.cpp b/fs_mgr/libsnapshot/snapuserd.cpp
index 573b6a5..9ad4a1a 100644
--- a/fs_mgr/libsnapshot/snapuserd.cpp
+++ b/fs_mgr/libsnapshot/snapuserd.cpp
@@ -324,8 +324,7 @@
                 reinterpret_cast<struct disk_exception*>((char*)unmerged_buffer + offset);
 
         // Unmerged op by the kernel
-        if (merged_de->old_chunk != 0) {
-            CHECK(merged_de->new_chunk != 0);
+        if (merged_de->old_chunk != 0 || merged_de->new_chunk != 0) {
             CHECK(merged_de->old_chunk == cow_de->old_chunk);
             CHECK(merged_de->new_chunk == cow_de->new_chunk);
 
@@ -334,11 +333,6 @@
             continue;
         }
 
-        // Merge complete on this exception. However, we don't know how many
-        // merged in this cycle; hence break here.
-        CHECK(merged_de->new_chunk == 0);
-        CHECK(merged_de->old_chunk == 0);
-
         break;
     }
 
diff --git a/fs_mgr/libsnapshot/utility.cpp b/fs_mgr/libsnapshot/utility.cpp
index 7342fd4..4a2af1c 100644
--- a/fs_mgr/libsnapshot/utility.cpp
+++ b/fs_mgr/libsnapshot/utility.cpp
@@ -187,5 +187,13 @@
     return android::base::GetBoolProperty("ro.virtual_ab.compression.enabled", false);
 }
 
+std::string GetOtherPartitionName(const std::string& name) {
+    auto suffix = android::fs_mgr::GetPartitionSlotSuffix(name);
+    CHECK(suffix == "_a" || suffix == "_b");
+
+    auto other_suffix = (suffix == "_a") ? "_b" : "_a";
+    return name.substr(0, name.size() - suffix.size()) + other_suffix;
+}
+
 }  // namespace snapshot
 }  // namespace android
diff --git a/fs_mgr/libsnapshot/utility.h b/fs_mgr/libsnapshot/utility.h
index 3e6873b..671de9d 100644
--- a/fs_mgr/libsnapshot/utility.h
+++ b/fs_mgr/libsnapshot/utility.h
@@ -131,5 +131,8 @@
 
 bool IsCompressionEnabled();
 
+// Swap the suffix of a partition name.
+std::string GetOtherPartitionName(const std::string& name);
+
 }  // namespace snapshot
 }  // namespace android
diff --git a/fs_mgr/libvbmeta/Android.bp b/fs_mgr/libvbmeta/Android.bp
index bceabab..a299b6e 100644
--- a/fs_mgr/libvbmeta/Android.bp
+++ b/fs_mgr/libvbmeta/Android.bp
@@ -50,4 +50,11 @@
         "avbtool",
         "vbmake",
     ],
-}
\ No newline at end of file
+    data: [
+        "data/*",
+    ],
+    // Not unit tests due to several binary and lib dependencies currently hard to replicate in continuous execution
+    test_options: {
+        unit_test: false,
+    },
+}
diff --git a/fs_mgr/libvbmeta/data/testkey_rsa2048.pem b/fs_mgr/libvbmeta/data/testkey_rsa2048.pem
new file mode 100644
index 0000000..867dcff
--- /dev/null
+++ b/fs_mgr/libvbmeta/data/testkey_rsa2048.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEowIBAAKCAQEAxlVR3TIkouAOvH79vaJTgFhpfvVKQIeVkFRZPVXK/zY0Gvrh
+4JAqGjJoW/PfrQv5sdD36qtHH3a+G5hLZ6Ni+t/mtfjucxZfuLGC3kmJ1T3XqEKZ
+gXXI2IR7vVSoImREvDQGEDyJwtHzLANlkbGg0cghVhWZSCAndO8BenalC2v94/rt
+DfkPekH6dgU3Sf40T0sBSeSY94mOzTaqOR2pfV1rWlLRdWmo33zeHBv52Rlbt0dM
+uXAureXWiHztkm5GCBC1dgM+CaxNtizNEgC91KcD0xuRCCM2WxH+r1lpszyIJDct
+YbrFmVEYl/kjQpafhy7Nsk1fqSTyRdriZSYmTQIDAQABAoIBAQC+kJgaCuX8wYAn
+SXWQ0fmdZlXnMNRpcF0a0pD0SAzGb1RdYBXMaXiqtyhiwc53PPxsCDdNecjayIMd
+jJVXPTwLhTruOgMS/bp3gcgWwV34UHV4LJXGOGAE+jbS0hbDBMiudOYmj6RmVshp
+z9G1zZCSQNMXHaWsEYkX59XpzzoB384nRul2QgEtwzUNR9XlpzgtJBLk3SACkvsN
+mQ/DW8IWHXLg8vLn1LzVJ2e3B16H4MoE2TCHxqfMgr03IDRRJogkenQuQsFhevYT
+o/mJyHSWavVgzMHG9I5m+eepF4Wyhj1Y4WyKAuMI+9dHAX/h7Lt8XFCQCh5DbkVG
+zGr34sWBAoGBAOs7n7YZqNaaguovfIdRRsxxZr1yJAyDsr6w3yGImDZYju4c4WY9
+5esO2kP3FA4p0c7FhQF5oOb1rBuHEPp36cpL4aGeK87caqTfq63WZAujoTZpr9Lp
+BRbkL7w/xG7jpQ/clpA8sHzHGQs/nelxoOtC7E118FiRgvD/jdhlMyL9AoGBANfX
+vyoN1pplfT2xR8QOjSZ+Q35S/+SAtMuBnHx3l0qH2bbBjcvM1MNDWjnRDyaYhiRu
+i+KA7tqfib09+XpB3g5D6Ov7ls/Ldx0S/VcmVWtia2HK8y8iLGtokoBZKQ5AaFX2
+iQU8+tC4h69GnJYQKqNwgCUzh8+gHX5Y46oDiTmRAoGAYpOx8lX+czB8/Da6MNrW
+mIZNT8atZLEsDs2ANEVRxDSIcTCZJId7+m1W+nRoaycLTWNowZ1+2ErLvR10+AGY
+b7Ys79Wg9idYaY9yGn9lnZsMzAiuLeyIvXcSqgjvAKlVWrhOQFOughvNWvFl85Yy
+oWSCMlPiTLtt7CCsCKsgKuECgYBgdIp6GZsIfkgclKe0hqgvRoeU4TR3gcjJlM9A
+lBTo+pKhaBectplx9RxR8AnsPobbqwcaHnIfAuKDzjk5mEvKZjClnFXF4HAHbyAF
+nRzZEy9XkWFhc80T5rRpZO7C7qdxmu2aiKixM3V3L3/0U58qULEDbubHMw9bEhAT
+PudI8QKBgHEEiMm/hr9T41hbQi/LYanWnlFw1ue+osKuF8bXQuxnnHNuFT/c+9/A
+vWhgqG6bOEHu+p/IPrYm4tBMYlwsyh4nXCyGgDJLbLIfzKwKAWCtH9LwnyDVhOow
+GH9shdR+sW3Ew97xef02KAH4VlNANEmBV4sQNqWWvsYrcFm2rOdL
+-----END RSA PRIVATE KEY-----
diff --git a/fs_mgr/libvbmeta/super_vbmeta_test.cpp b/fs_mgr/libvbmeta/super_vbmeta_test.cpp
index daed0d1..7329a61 100644
--- a/fs_mgr/libvbmeta/super_vbmeta_test.cpp
+++ b/fs_mgr/libvbmeta/super_vbmeta_test.cpp
@@ -54,7 +54,7 @@
     cmd << "avbtool add_hashtree_footer"
         << " --image " << file_name << " --partition_name " << partition_name
         << " --partition_size " << FAKE_PARTITION_SIZE << " --algorithm SHA256_RSA2048"
-        << " --key external/avb/test/data/testkey_rsa2048.pem";
+        << " --key data/testkey_rsa2048.pem";
 
     int rc = system(cmd.str().c_str());
     EXPECT_TRUE(WIFEXITED(rc));
diff --git a/fs_mgr/tests/adb-remount-test.sh b/fs_mgr/tests/adb-remount-test.sh
index f5bbe35..2433833 100755
--- a/fs_mgr/tests/adb-remount-test.sh
+++ b/fs_mgr/tests/adb-remount-test.sh
@@ -740,7 +740,7 @@
   grep -v \
     -e "^\(overlay\|tmpfs\|none\|sysfs\|proc\|selinuxfs\|debugfs\|bpf\) " \
     -e "^\(binfmt_misc\|cg2_bpf\|pstore\|tracefs\|adb\|mtp\|ptp\|devpts\) " \
-    -e "^\(ramdumpfs\|binder\|/sys/kernel/debug\) " \
+    -e "^\(ramdumpfs\|binder\|/sys/kernel/debug\|securityfs\) " \
     -e " functionfs " \
     -e "^\(/data/media\|/dev/block/loop[0-9]*\) " \
     -e "^rootfs / rootfs rw," \
diff --git a/init/README.md b/init/README.md
index bcbbfbb..67d55e1 100644
--- a/init/README.md
+++ b/init/README.md
@@ -178,6 +178,8 @@
   will reboot into _fatal reboot target_.
   The default value of _fatal crash window mins_ is 4, and default value
   of _fatal reboot target_ is 'bootloader'.
+  For tests, the fatal reboot can be skipped by setting property
+  `init.svc_debug.no_fatal.<service-name>` to `true` for specified critical service.
 
 `disabled`
 > This service will not automatically start with its class.
diff --git a/init/service.cpp b/init/service.cpp
index d84dcd4..f6ce094 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -52,6 +52,7 @@
 #endif
 
 using android::base::boot_clock;
+using android::base::GetBoolProperty;
 using android::base::GetProperty;
 using android::base::Join;
 using android::base::make_scope_guard;
@@ -318,17 +319,19 @@
     // reboot into bootloader or set crashing property
     boot_clock::time_point now = boot_clock::now();
     if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {
-        bool boot_completed = android::base::GetBoolProperty("sys.boot_completed", false);
+        bool boot_completed = GetBoolProperty("sys.boot_completed", false);
         if (now < time_crashed_ + fatal_crash_window_ || !boot_completed) {
             if (++crash_count_ > 4) {
                 auto exit_reason = boot_completed ?
                     "in " + std::to_string(fatal_crash_window_.count()) + " minutes" :
                     "before boot completed";
                 if (flags_ & SVC_CRITICAL) {
-                    // Aborts into `fatal_reboot_target_'.
-                    SetFatalRebootTarget(fatal_reboot_target_);
-                    LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
-                               << exit_reason;
+                    if (!GetBoolProperty("init.svc_debug.no_fatal." + name_, false)) {
+                        // Aborts into `fatal_reboot_target_'.
+                        SetFatalRebootTarget(fatal_reboot_target_);
+                        LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
+                                   << exit_reason;
+                    }
                 } else {
                     LOG(ERROR) << "process with updatable components '" << name_
                                << "' exited 4 times " << exit_reason;
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 19c00f9..21a78c1 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -749,6 +749,11 @@
     mkdir /data/app 0771 system system encryption=Require
     mkdir /data/property 0700 root root encryption=Require
 
+    # create directory for updated font files.
+    mkdir /data/fonts/ 0771 root root encryption=Require
+    mkdir /data/fonts/files 0771 system system
+    mkdir /data/fonts/config 0770 system system
+
     # Create directories to push tests to for each linker namespace.
     # Create the subdirectories in case the first test is run as root
     # so it doesn't end up owned by root.
diff --git a/rootdir/ueventd.rc b/rootdir/ueventd.rc
index 64a64d2..aebcd5f 100644
--- a/rootdir/ueventd.rc
+++ b/rootdir/ueventd.rc
@@ -77,3 +77,5 @@
 /sys/devices/virtual/usb_composite/*   enable      0664  root   system
 /sys/devices/system/cpu/cpu*   cpufreq/scaling_max_freq   0664  system system
 /sys/devices/system/cpu/cpu*   cpufreq/scaling_min_freq   0664  system system
+/sys/devices/virtual/misc/uhid/*/leds/* brightness   0664  system system
+/sys/devices/virtual/misc/uhid/*/leds/* multi_intensity   0664  system system
diff --git a/trusty/keymaster/TrustyKeymaster.cpp b/trusty/keymaster/TrustyKeymaster.cpp
index 5690031..23e0433 100644
--- a/trusty/keymaster/TrustyKeymaster.cpp
+++ b/trusty/keymaster/TrustyKeymaster.cpp
@@ -37,6 +37,12 @@
     if (versionRsp.error != KM_ERROR_OK) {
         ALOGW("TA appears not to support GetVersion2, falling back (err = %d)", versionRsp.error);
 
+        err = trusty_keymaster_connect();
+        if (err) {
+            ALOGE("Failed to connect to trusty keymaster %d", err);
+            return err;
+        }
+
         GetVersionRequest versionReq;
         GetVersionResponse versionRsp;
         GetVersion(versionReq, &versionRsp);
diff --git a/deprecated-adf/libadf/tests/Android.bp b/trusty/secure_dpu/Android.bp
similarity index 72%
rename from deprecated-adf/libadf/tests/Android.bp
rename to trusty/secure_dpu/Android.bp
index 9b3430e..0d57cea 100644
--- a/deprecated-adf/libadf/tests/Android.bp
+++ b/trusty/secure_dpu/Android.bp
@@ -1,5 +1,4 @@
-//
-// Copyright (C) 2013 The Android Open Source Project
+// Copyright (C) 2021 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.
@@ -12,12 +11,10 @@
 // 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.
-//
 
-cc_test {
-    name: "adf-unit-tests",
-    srcs: ["adf_test.cpp"],
-    shared_libs: ["libsync"],
-    static_libs: ["libadf"],
-    cflags: ["-Werror"],
+cc_library_headers {
+    name: "secure_dpu_headers",
+    vendor: true,
+
+    export_include_dirs: ["include"],
 }
diff --git a/trusty/secure_dpu/include/trusty/secure_dpu/SecureDpu.h b/trusty/secure_dpu/include/trusty/secure_dpu/SecureDpu.h
new file mode 100644
index 0000000..b939d44
--- /dev/null
+++ b/trusty/secure_dpu/include/trusty/secure_dpu/SecureDpu.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2020, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+/**
+ * DOC: Secure DPU
+ *
+ * The Secure DPU works as the persistent channel between the non-secure and the
+ * secure world. The channel is established during the boot up stage of the
+ * non-secure world system. In general, the established channel allows the
+ * secure world applications initiate requests or notifications to the non-secure
+ * world.
+ *
+ * For particular devices, the secure world can only perform operations on the
+ * display when in the TUI session if device-specific setup is done by the
+ * non-secure world. Besides, the non-secure world could allocate framebuffer
+ * for the secure world application if the memory is limited in the secure world
+ * on specific devices.
+ *
+ * Currently, supported requests are to start / stop the secure display mode and
+ * to allocate framebuffer.
+ *
+ * This header file needs to be synced on both the Trusty and the Android
+ * codebase.
+ */
+
+#define SECURE_DPU_PORT_NAME "com.android.trusty.secure_dpu"
+#define SECURE_DPU_MAX_MSG_SIZE 64
+
+/**
+ * enum secure_dpu_cmd - command identifiers for secure_fb interface
+ * @SECURE_DPU_CMD_RESP_BIT:
+ *      Message is a response.
+ * @SECURE_DPU_CMD_REQ_SHIFT:
+ *      Number of bits used by @SECURE_DPU_CMD_RESP_BIT.
+ * @SECURE_DPU_CMD_START_SECURE_DISPLAY:
+ *      Notify the system to start secure display mode
+ * @SECURE_DPU_CMD_STOP_SECURE_DISPLAY:
+ *      Notify the system to stop secure display mode
+ * @SECURE_DPU_CMD_ALLOCATE_BUFFER:
+ *      Request non-secure world to allocate the buffer
+ */
+enum secure_dpu_cmd {
+    SECURE_DPU_CMD_RESP_BIT = 1,
+    SECURE_DPU_CMD_REQ_SHIFT = 1,
+    SECURE_DPU_CMD_START_SECURE_DISPLAY = (1 << SECURE_DPU_CMD_REQ_SHIFT),
+    SECURE_DPU_CMD_STOP_SECURE_DISPLAY = (2 << SECURE_DPU_CMD_REQ_SHIFT),
+    SECURE_DPU_CMD_ALLOCATE_BUFFER = (3 << SECURE_DPU_CMD_REQ_SHIFT),
+};
+
+/**
+ * struct secure_dpu_allocate_buffer_req - payload for
+ *                                         %SECURE_DPU_CMD_ALLOCATE_BUFFER
+ *                                         request
+ * @buffer_len: Requested length
+ */
+struct secure_dpu_allocate_buffer_req {
+    uint64_t buffer_len;
+};
+
+/**
+ * struct secure_dpu_allocate_buffer_resp - payload for
+ *                                          %SECURE_DPU_CMD_ALLOCATE_BUFFER
+ *                                          response
+ * @buffer_len: Allocated length
+ */
+struct secure_dpu_allocate_buffer_resp {
+    uint64_t buffer_len;
+};
+
+/**
+ * struct secure_fb_req - common structure for secure_fb requests.
+ * @cmd: Command identifier - one of &enum secure_dpu_cmd.
+ */
+struct secure_dpu_req {
+    uint32_t cmd;
+};
+
+/**
+ * struct secure_dpu_resp - common structure for secure_dpu responses.
+ * @cmd:    Command identifier - %SECURE_DPU_CMD_RESP_BIT or'ed with the
+ *                               command identifier of the corresponding
+ *                               request.
+ * @status: Status of requested operation. One of &enum secure_dpu_error.
+ */
+struct secure_dpu_resp {
+    uint32_t cmd;
+    int32_t status;
+};
+
+enum secure_dpu_error {
+    SECURE_DPU_ERROR_OK = 0,
+    SECURE_DPU_ERROR_FAIL = -1,
+    SECURE_DPU_ERROR_UNINITIALIZED = -2,
+    SECURE_DPU_ERROR_PARAMETERS = -3,
+    SECURE_DPU_ERROR_NO_MEMORY = -4,
+};