Merge "Attempt to make libavb test working in CI"
diff --git a/debuggerd/Android.bp b/debuggerd/Android.bp
index fd62392..2390d79 100644
--- a/debuggerd/Android.bp
+++ b/debuggerd/Android.bp
@@ -176,6 +176,8 @@
         "libdebuggerd/open_files_list.cpp",
         "libdebuggerd/scudo.cpp",
         "libdebuggerd/tombstone.cpp",
+        "libdebuggerd/tombstone_proto.cpp",
+        "libdebuggerd/tombstone_proto_to_text.cpp",
         "libdebuggerd/utility.cpp",
     ],
 
@@ -206,6 +208,8 @@
     whole_static_libs: [
         "gwp_asan_crash_handler",
         "libscudo",
+        "libtombstone_proto",
+        "libprotobuf-cpp-lite",
     ],
 
     target: {
@@ -228,6 +232,20 @@
     },
 }
 
+cc_binary {
+    name: "pbtombstone",
+    defaults: ["debuggerd_defaults"],
+    srcs: ["pbtombstone.cpp"],
+    static_libs: [
+        "libbase",
+        "libdebuggerd",
+        "liblog",
+        "libprotobuf-cpp-lite",
+        "libtombstone_proto",
+        "libunwindstack",
+    ],
+}
+
 cc_test {
     name: "debuggerd_test",
     defaults: ["debuggerd_defaults"],
@@ -332,6 +350,9 @@
         "libtombstoned_client_static",
         "libdebuggerd",
         "libcutils",
+
+        "libtombstone_proto",
+        "libprotobuf-cpp-lite",
     ],
 
     shared_libs: [
diff --git a/debuggerd/common/include/dump_type.h b/debuggerd/common/include/dump_type.h
index 203269e..a3e171b 100644
--- a/debuggerd/common/include/dump_type.h
+++ b/debuggerd/common/include/dump_type.h
@@ -24,7 +24,8 @@
   kDebuggerdNativeBacktrace,
   kDebuggerdTombstone,
   kDebuggerdJavaBacktrace,
-  kDebuggerdAnyIntercept
+  kDebuggerdAnyIntercept,
+  kDebuggerdTombstoneProto,
 };
 
 inline std::ostream& operator<<(std::ostream& stream, const DebuggerdDumpType& rhs) {
@@ -41,6 +42,9 @@
     case kDebuggerdAnyIntercept:
       stream << "kDebuggerdAnyIntercept";
       break;
+    case kDebuggerdTombstoneProto:
+      stream << "kDebuggerdTombstoneProto";
+      break;
     default:
       stream << "[unknown]";
   }
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index 4f60005..51afcc2 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -40,6 +40,7 @@
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
+#include <bionic/macros.h>
 #include <bionic/reserved_signals.h>
 #include <cutils/sockets.h>
 #include <log/log.h>
@@ -194,6 +195,7 @@
 static bool g_tombstoned_connected = false;
 static unique_fd g_tombstoned_socket;
 static unique_fd g_output_fd;
+static unique_fd g_proto_fd;
 
 static void DefuseSignalHandlers() {
   // Don't try to dump ourselves.
@@ -214,7 +216,7 @@
     // If we abort before we get an output fd, contact tombstoned to let any
     // potential listeners know that we failed.
     if (!g_tombstoned_connected) {
-      if (!tombstoned_connect(g_target_thread, &g_tombstoned_socket, &g_output_fd,
+      if (!tombstoned_connect(g_target_thread, &g_tombstoned_socket, &g_output_fd, &g_proto_fd,
                               kDebuggerdAnyIntercept)) {
         // We failed to connect, not much we can do.
         LOG(ERROR) << "failed to connected to tombstoned to report failure";
@@ -247,10 +249,20 @@
   }
 
   int dump_type_int;
-  if (!android::base::ParseInt(argv[3], &dump_type_int, 0, 1)) {
+  if (!android::base::ParseInt(argv[3], &dump_type_int, 0)) {
     LOG(FATAL) << "invalid requested dump type: " << argv[3];
   }
+
   *dump_type = static_cast<DebuggerdDumpType>(dump_type_int);
+  switch (*dump_type) {
+    case kDebuggerdNativeBacktrace:
+    case kDebuggerdTombstone:
+    case kDebuggerdTombstoneProto:
+      break;
+
+    default:
+      LOG(FATAL) << "invalid requested dump type: " << dump_type_int;
+  }
 }
 
 static void ReadCrashInfo(unique_fd& fd, siginfo_t* siginfo,
@@ -299,7 +311,9 @@
       *siginfo = crash_info->data.s.siginfo;
       if (signal_has_si_addr(siginfo)) {
         process_info->has_fault_address = true;
-        process_info->fault_address = reinterpret_cast<uintptr_t>(siginfo->si_addr);
+        process_info->maybe_tagged_fault_address = reinterpret_cast<uintptr_t>(siginfo->si_addr);
+        process_info->untagged_fault_address =
+            untag_address(reinterpret_cast<uintptr_t>(siginfo->si_addr));
       }
       regs->reset(unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(),
                                                         &crash_info->data.s.ucontext));
@@ -477,6 +491,11 @@
       info.process_name = process_name;
       info.thread_name = get_thread_name(thread);
 
+      unique_fd attr_fd(openat(target_proc_fd, "attr/current", O_RDONLY | O_CLOEXEC));
+      if (!android::base::ReadFdToString(attr_fd, &info.selinux_label)) {
+        PLOG(WARNING) << "failed to read selinux label";
+      }
+
       if (!ptrace_interrupt(thread, &info.signo)) {
         PLOG(WARNING) << "failed to ptrace interrupt thread " << thread;
         ptrace(PTRACE_DETACH, thread, 0, 0);
@@ -555,8 +574,8 @@
   {
     ATRACE_NAME("tombstoned_connect");
     LOG(INFO) << "obtaining output fd from tombstoned, type: " << dump_type;
-    g_tombstoned_connected =
-        tombstoned_connect(g_target_thread, &g_tombstoned_socket, &g_output_fd, dump_type);
+    g_tombstoned_connected = tombstoned_connect(g_target_thread, &g_tombstoned_socket, &g_output_fd,
+                                                &g_proto_fd, dump_type);
   }
 
   if (g_tombstoned_connected) {
@@ -609,8 +628,8 @@
 
     {
       ATRACE_NAME("engrave_tombstone");
-      engrave_tombstone(std::move(g_output_fd), &unwinder, thread_info, g_target_thread, process_info,
-                        &open_files, &amfd_data);
+      engrave_tombstone(std::move(g_output_fd), std::move(g_proto_fd), &unwinder, thread_info,
+                        g_target_thread, process_info, &open_files, &amfd_data);
     }
   }
 
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index 45e555f..b9d6606 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -1309,11 +1309,11 @@
   tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
   ASSERT_EQ(InterceptStatus::kRegistered, status);
 
-  // First connect to tombstoned requesting a native backtrace. This
+  // First connect to tombstoned requesting a native tombstone. This
   // should result in a "regular" FD and not the installed intercept.
   const char native[] = "native";
   unique_fd tombstoned_socket, input_fd;
-  ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
+  ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
   ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
   tombstoned_notify_completion(tombstoned_socket.get());
 
@@ -1425,3 +1425,70 @@
   ConsumeFd(std::move(output_fd), &result);
   ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
 }
+
+TEST(tombstoned, proto) {
+  const pid_t self = getpid();
+  unique_fd tombstoned_socket, text_fd, proto_fd;
+  ASSERT_TRUE(
+      tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
+
+  tombstoned_notify_completion(tombstoned_socket.get());
+
+  ASSERT_NE(-1, text_fd.get());
+  ASSERT_NE(-1, proto_fd.get());
+
+  struct stat text_st;
+  ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
+
+  // Give tombstoned some time to link the files into place.
+  std::this_thread::sleep_for(100ms);
+
+  // Find the tombstone.
+  std::optional<int> tombstone_index;
+  for (int i = 0; i < 50; ++i) {
+    std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
+
+    struct stat st;
+    if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
+      continue;
+    }
+
+    if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
+      tombstone_index = i;
+      break;
+    }
+  }
+
+  ASSERT_TRUE(tombstone_index);
+  std::string proto_path =
+      android::base::StringPrintf("/data/tombstones/tombstone_%02d.pb", *tombstone_index);
+
+  struct stat proto_fd_st;
+  struct stat proto_file_st;
+  ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
+  ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
+
+  ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
+  ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
+}
+
+TEST(tombstoned, proto_intercept) {
+  const pid_t self = getpid();
+  unique_fd intercept_fd, output_fd;
+  InterceptStatus status;
+
+  tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
+  ASSERT_EQ(InterceptStatus::kRegistered, status);
+
+  unique_fd tombstoned_socket, text_fd, proto_fd;
+  ASSERT_TRUE(
+      tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
+  ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
+  tombstoned_notify_completion(tombstoned_socket.get());
+
+  text_fd.reset();
+
+  std::string output;
+  ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
+  ASSERT_EQ("foo", output);
+}
diff --git a/debuggerd/handler/debuggerd_fallback.cpp b/debuggerd/handler/debuggerd_fallback.cpp
index e103c82..feafa73 100644
--- a/debuggerd/handler/debuggerd_fallback.cpp
+++ b/debuggerd/handler/debuggerd_fallback.cpp
@@ -92,15 +92,15 @@
   __linker_disable_fallback_allocator();
 }
 
-static void debuggerd_fallback_tombstone(int output_fd, ucontext_t* ucontext, siginfo_t* siginfo,
-                                         void* abort_message) {
+static void debuggerd_fallback_tombstone(int output_fd, int proto_fd, ucontext_t* ucontext,
+                                         siginfo_t* siginfo, void* abort_message) {
   if (!__linker_enable_fallback_allocator()) {
     async_safe_format_log(ANDROID_LOG_ERROR, "libc", "fallback allocator already in use");
     return;
   }
 
-  engrave_tombstone_ucontext(output_fd, reinterpret_cast<uintptr_t>(abort_message), siginfo,
-                             ucontext);
+  engrave_tombstone_ucontext(output_fd, proto_fd, reinterpret_cast<uintptr_t>(abort_message),
+                             siginfo, ucontext);
   __linker_disable_fallback_allocator();
 }
 
@@ -232,7 +232,8 @@
 
   // Fetch output fd from tombstoned.
   unique_fd tombstone_socket, output_fd;
-  if (!tombstoned_connect(getpid(), &tombstone_socket, &output_fd, kDebuggerdNativeBacktrace)) {
+  if (!tombstoned_connect(getpid(), &tombstone_socket, &output_fd, nullptr,
+                          kDebuggerdNativeBacktrace)) {
     async_safe_format_log(ANDROID_LOG_ERROR, "libc",
                           "missing crash_dump_fallback() in selinux policy?");
     goto exit;
@@ -325,10 +326,10 @@
     _exit(1);
   }
 
-  unique_fd tombstone_socket, output_fd;
-  bool tombstoned_connected =
-      tombstoned_connect(getpid(), &tombstone_socket, &output_fd, kDebuggerdTombstone);
-  debuggerd_fallback_tombstone(output_fd.get(), ucontext, info, abort_message);
+  unique_fd tombstone_socket, output_fd, proto_fd;
+  bool tombstoned_connected = tombstoned_connect(getpid(), &tombstone_socket, &output_fd, &proto_fd,
+                                                 kDebuggerdTombstoneProto);
+  debuggerd_fallback_tombstone(output_fd.get(), proto_fd.get(), ucontext, info, abort_message);
   if (tombstoned_connected) {
     tombstoned_notify_completion(tombstone_socket.get());
   }
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 1297c4d..ca809e4 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -312,7 +312,7 @@
     return kDebuggerdNativeBacktrace;
   }
 
-  return kDebuggerdTombstone;
+  return kDebuggerdTombstoneProto;
 }
 
 static int debuggerd_dispatch_pseudothread(void* arg) {
diff --git a/debuggerd/libdebuggerd/gwp_asan.cpp b/debuggerd/libdebuggerd/gwp_asan.cpp
index f271365..9750fc4 100644
--- a/debuggerd/libdebuggerd/gwp_asan.cpp
+++ b/debuggerd/libdebuggerd/gwp_asan.cpp
@@ -72,8 +72,8 @@
 
   // Get the external crash address from the thread info.
   crash_address_ = 0u;
-  if (signal_has_si_addr(thread_info.siginfo)) {
-    crash_address_ = reinterpret_cast<uintptr_t>(thread_info.siginfo->si_addr);
+  if (process_info.has_fault_address) {
+    crash_address_ = process_info.untagged_fault_address;
   }
 
   // Ensure the error belongs to GWP-ASan.
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
index 3ff7d62..bf2cbb3 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
@@ -21,6 +21,7 @@
 #include <stddef.h>
 #include <sys/types.h>
 
+#include <functional>
 #include <map>
 #include <string>
 
@@ -30,6 +31,8 @@
 #include "types.h"
 
 // Forward declarations
+class Tombstone;
+
 namespace unwindstack {
 class Unwinder;
 }
@@ -44,13 +47,21 @@
 int open_tombstone(std::string* path);
 
 /* Creates a tombstone file and writes the crash dump to it. */
-void engrave_tombstone(android::base::unique_fd output_fd, unwindstack::Unwinder* unwinder,
+void engrave_tombstone(android::base::unique_fd output_fd, android::base::unique_fd proto_fd,
+                       unwindstack::Unwinder* unwinder,
                        const std::map<pid_t, ThreadInfo>& thread_info, pid_t target_thread,
                        const ProcessInfo& process_info, OpenFilesList* open_files,
                        std::string* amfd_data);
 
-void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
-                                ucontext_t* ucontext);
+void engrave_tombstone_ucontext(int tombstone_fd, int proto_fd, uint64_t abort_msg_address,
+                                siginfo_t* siginfo, ucontext_t* ucontext);
 
+void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+                             const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
+                             const ProcessInfo& process_info, const OpenFilesList* open_files);
+
+bool tombstone_proto_to_text(
+    const Tombstone& tombstone,
+    std::function<void(const std::string& line, bool should_log)> callback);
 
 #endif  // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/types.h b/debuggerd/libdebuggerd/include/libdebuggerd/types.h
index 30e75e1..d5b0735 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/types.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/types.h
@@ -31,7 +31,9 @@
   std::string thread_name;
 
   pid_t pid;
+
   std::string process_name;
+  std::string selinux_label;
 
   int signo = 0;
   siginfo_t* siginfo = nullptr;
@@ -46,5 +48,6 @@
   uintptr_t scudo_region_info = 0;
 
   bool has_fault_address = false;
-  uintptr_t fault_address = 0;
+  uintptr_t untagged_fault_address = 0;
+  uintptr_t maybe_tagged_fault_address = 0;
 };
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
index 29fb9a4..d71b76f 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
@@ -81,6 +81,8 @@
 
 void log_backtrace(log_t* log, unwindstack::Unwinder* unwinder, const char* prefix);
 
+ssize_t dump_memory(void* out, size_t len, size_t* start_offset, uint64_t* addr,
+                    unwindstack::Memory* memory);
 void dump_memory(log_t* log, unwindstack::Memory* backtrace, uint64_t addr, const std::string&);
 
 void drop_capabilities();
diff --git a/debuggerd/libdebuggerd/scudo.cpp b/debuggerd/libdebuggerd/scudo.cpp
index f8bfe07..141c3bd 100644
--- a/debuggerd/libdebuggerd/scudo.cpp
+++ b/debuggerd/libdebuggerd/scudo.cpp
@@ -44,7 +44,7 @@
   auto region_info = AllocAndReadFully(process_memory, process_info.scudo_region_info,
                                        __scudo_get_region_info_size());
 
-  untagged_fault_addr_ = untag_address(process_info.fault_address);
+  untagged_fault_addr_ = process_info.untagged_fault_address;
   uintptr_t fault_page = untagged_fault_addr_ & ~(PAGE_SIZE - 1);
 
   uintptr_t memory_begin = fault_page - PAGE_SIZE * 16;
@@ -67,7 +67,7 @@
     memory_tags[(i - memory_begin) / kTagGranuleSize] = process_memory->ReadTag(i);
   }
 
-  __scudo_get_error_info(&error_info_, process_info.fault_address, stack_depot.get(),
+  __scudo_get_error_info(&error_info_, process_info.maybe_tagged_fault_address, stack_depot.get(),
                          region_info.get(), memory.get(), memory_tags.get(), memory_begin,
                          memory_end - memory_begin);
 }
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index d88c5a9..822b74a 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -63,6 +63,8 @@
 #include "gwp_asan/common.h"
 #include "gwp_asan/crash_handler.h"
 
+#include "tombstone.pb.h"
+
 using android::base::GetBoolProperty;
 using android::base::GetProperty;
 using android::base::StringPrintf;
@@ -151,7 +153,9 @@
                              const ProcessInfo& process_info, unwindstack::Memory* process_memory) {
   char addr_desc[64];  // ", fault addr 0x1234"
   if (process_info.has_fault_address) {
-    size_t addr = process_info.fault_address;
+    // SIGILL faults will never have tagged addresses, so okay to
+    // indiscriminately use the tagged address here.
+    size_t addr = process_info.maybe_tagged_fault_address;
     if (thread_info.siginfo->si_signo == SIGILL) {
       uint32_t instruction = {};
       process_memory->Read(addr, &instruction, sizeof(instruction));
@@ -188,8 +192,7 @@
 static std::string get_addr_string(uint64_t addr) {
   std::string addr_str;
 #if defined(__LP64__)
-  addr_str = StringPrintf("%08x'%08x",
-                          static_cast<uint32_t>(addr >> 32),
+  addr_str = StringPrintf("%08x'%08x", static_cast<uint32_t>(addr >> 32),
                           static_cast<uint32_t>(addr & 0xffffffff));
 #else
   addr_str = StringPrintf("%08x", static_cast<uint32_t>(addr));
@@ -392,8 +395,7 @@
   if (primary_thread && gwp_asan_crash_data->CrashIsMine()) {
     gwp_asan_crash_data->DumpCause(log);
   } else if (thread_info.siginfo && !(primary_thread && scudo_crash_data->CrashIsMine())) {
-    dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps(),
-                        thread_info.registers.get());
+    dump_probable_cause(log, thread_info.siginfo, unwinder->GetMaps(), thread_info.registers.get());
   }
 
   if (primary_thread) {
@@ -433,9 +435,8 @@
                          thread_info.registers.get());
     if (maps != nullptr) {
       uint64_t addr = 0;
-      siginfo_t* si = thread_info.siginfo;
-      if (signal_has_si_addr(si)) {
-        addr = reinterpret_cast<uint64_t>(si->si_addr);
+      if (process_info.has_fault_address) {
+        addr = process_info.untagged_fault_address;
       }
       dump_all_maps(log, unwinder, addr);
     }
@@ -491,8 +492,7 @@
     // the tombstone file.
 
     if (first) {
-      _LOG(log, logtype::LOGS, "--------- %slog %s\n",
-        tail ? "tail end of " : "", filename);
+      _LOG(log, logtype::LOGS, "--------- %slog %s\n", tail ? "tail end of " : "", filename);
       first = false;
     }
 
@@ -553,8 +553,8 @@
   dump_log_file(log, pid, "main", tail);
 }
 
-void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
-                                ucontext_t* ucontext) {
+void engrave_tombstone_ucontext(int tombstone_fd, int proto_fd, uint64_t abort_msg_address,
+                                siginfo_t* siginfo, ucontext_t* ucontext) {
   pid_t uid = getuid();
   pid_t pid = getpid();
   pid_t tid = gettid();
@@ -571,14 +571,18 @@
   std::unique_ptr<unwindstack::Regs> regs(
       unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), ucontext));
 
+  std::string selinux_label;
+  android::base::ReadFileToString("/proc/self/attr/current", &selinux_label);
+
   std::map<pid_t, ThreadInfo> threads;
   threads[tid] = ThreadInfo{
       .registers = std::move(regs),
       .uid = uid,
       .tid = tid,
-      .thread_name = thread_name.c_str(),
+      .thread_name = std::move(thread_name),
       .pid = pid,
-      .process_name = process_name.c_str(),
+      .process_name = std::move(process_name),
+      .selinux_label = std::move(selinux_label),
       .siginfo = siginfo,
   };
 
@@ -588,17 +592,23 @@
   }
 
   ProcessInfo process_info;
+  unique_fd attr_fd(open("/proc/self/attr/current", O_RDONLY | O_CLOEXEC));
   process_info.abort_msg_address = abort_msg_address;
-  engrave_tombstone(unique_fd(dup(tombstone_fd)), &unwinder, threads, tid, process_info, nullptr,
-                    nullptr);
+  engrave_tombstone(unique_fd(dup(tombstone_fd)), unique_fd(dup(proto_fd)), &unwinder, threads, tid,
+                    process_info, nullptr, nullptr);
 }
 
-void engrave_tombstone(unique_fd output_fd, unwindstack::Unwinder* unwinder,
+void engrave_tombstone(unique_fd output_fd, unique_fd proto_fd, unwindstack::Unwinder* unwinder,
                        const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
                        const ProcessInfo& process_info, OpenFilesList* open_files,
                        std::string* amfd_data) {
   // Don't copy log messages to tombstone unless this is a development device.
-  bool want_logs = GetBoolProperty("ro.debuggable", false);
+  Tombstone tombstone;
+  engrave_tombstone_proto(&tombstone, unwinder, threads, target_thread, process_info, open_files);
+
+  if (!tombstone.SerializeToFileDescriptor(proto_fd.get())) {
+    PLOG(ERROR) << "Failed to write proto tombstone";
+  }
 
   log_t log;
   log.current_tid = target_thread;
@@ -606,35 +616,45 @@
   log.tfd = output_fd.get();
   log.amfd_data = amfd_data;
 
-  _LOG(&log, logtype::HEADER, "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
-  dump_header_info(&log);
-  _LOG(&log, logtype::HEADER, "Timestamp: %s\n", get_timestamp().c_str());
+  bool translate_proto = GetBoolProperty("debug.debuggerd.translate_proto_to_text", false);
+  if (translate_proto) {
+    tombstone_proto_to_text(tombstone, [&log](const std::string& line, bool should_log) {
+      _LOG(&log, should_log ? logtype::HEADER : logtype::LOGS, "%s\n", line.c_str());
+    });
+  } else {
+    bool want_logs = GetBoolProperty("ro.debuggable", false);
 
-  auto it = threads.find(target_thread);
-  if (it == threads.end()) {
-    LOG(FATAL) << "failed to find target thread";
-  }
+    _LOG(&log, logtype::HEADER,
+         "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
+    dump_header_info(&log);
+    _LOG(&log, logtype::HEADER, "Timestamp: %s\n", get_timestamp().c_str());
 
-  dump_thread(&log, unwinder, it->second, process_info, true);
-
-  if (want_logs) {
-    dump_logs(&log, it->second.pid, 50);
-  }
-
-  for (auto& [tid, thread_info] : threads) {
-    if (tid == target_thread) {
-      continue;
+    auto it = threads.find(target_thread);
+    if (it == threads.end()) {
+      LOG(FATAL) << "failed to find target thread";
     }
 
-    dump_thread(&log, unwinder, thread_info, process_info, false);
-  }
+    dump_thread(&log, unwinder, it->second, process_info, true);
 
-  if (open_files) {
-    _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
-    dump_open_files_list(&log, *open_files, "    ");
-  }
+    if (want_logs) {
+      dump_logs(&log, it->second.pid, 50);
+    }
 
-  if (want_logs) {
-    dump_logs(&log, it->second.pid, 0);
+    for (auto& [tid, thread_info] : threads) {
+      if (tid == target_thread) {
+        continue;
+      }
+
+      dump_thread(&log, unwinder, thread_info, process_info, false);
+    }
+
+    if (open_files) {
+      _LOG(&log, logtype::OPEN_FILES, "\nopen files:\n");
+      dump_open_files_list(&log, *open_files, "    ");
+    }
+
+    if (want_logs) {
+      dump_logs(&log, it->second.pid, 0);
+    }
   }
 }
diff --git a/debuggerd/libdebuggerd/tombstone_proto.cpp b/debuggerd/libdebuggerd/tombstone_proto.cpp
new file mode 100644
index 0000000..801b112
--- /dev/null
+++ b/debuggerd/libdebuggerd/tombstone_proto.cpp
@@ -0,0 +1,478 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#define LOG_TAG "DEBUG"
+
+#include "libdebuggerd/tombstone.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <time.h>
+
+#include <memory>
+#include <string>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+
+#include <android/log.h>
+#include <log/log.h>
+#include <log/log_read.h>
+#include <log/logprint.h>
+#include <private/android_filesystem_config.h>
+
+#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
+#include <unwindstack/Regs.h>
+#include <unwindstack/Unwinder.h>
+
+#include "libdebuggerd/open_files_list.h"
+#include "libdebuggerd/utility.h"
+#include "util.h"
+
+#include "tombstone.pb.h"
+
+using android::base::StringPrintf;
+
+// Use the demangler from libc++.
+extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
+
+static Architecture get_arch() {
+#if defined(__arm__)
+  return Architecture::ARM32;
+#elif defined(__aarch64__)
+  return Architecture::ARM64;
+#elif defined(__i386__)
+  return Architecture::X86;
+#elif defined(__x86_64__)
+  return Architecture::X86_64;
+#else
+#error Unknown architecture!
+#endif
+}
+
+static std::optional<std::string> get_stack_overflow_cause(uint64_t fault_addr, uint64_t sp,
+                                                           unwindstack::Maps* maps) {
+  static constexpr uint64_t kMaxDifferenceBytes = 256;
+  uint64_t difference;
+  if (sp >= fault_addr) {
+    difference = sp - fault_addr;
+  } else {
+    difference = fault_addr - sp;
+  }
+  if (difference <= kMaxDifferenceBytes) {
+    // The faulting address is close to the current sp, check if the sp
+    // indicates a stack overflow.
+    // On arm, the sp does not get updated when the instruction faults.
+    // In this case, the sp will still be in a valid map, which is the
+    // last case below.
+    // On aarch64, the sp does get updated when the instruction faults.
+    // In this case, the sp will be in either an invalid map if triggered
+    // on the main thread, or in a guard map if in another thread, which
+    // will be the first case or second case from below.
+    unwindstack::MapInfo* map_info = maps->Find(sp);
+    if (map_info == nullptr) {
+      return "stack pointer is in a non-existent map; likely due to stack overflow.";
+    } else if ((map_info->flags & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)) {
+      return "stack pointer is not in a rw map; likely due to stack overflow.";
+    } else if ((sp - map_info->start) <= kMaxDifferenceBytes) {
+      return "stack pointer is close to top of stack; likely stack overflow.";
+    }
+  }
+  return {};
+}
+
+static void dump_probable_cause(Tombstone* tombstone, const siginfo_t* si, unwindstack::Maps* maps,
+                                unwindstack::Regs* regs) {
+  std::optional<std::string> cause;
+  if (si->si_signo == SIGSEGV && si->si_code == SEGV_MAPERR) {
+    if (si->si_addr < reinterpret_cast<void*>(4096)) {
+      cause = "null pointer dereference";
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0ffc)) {
+      cause = "call to kuser_helper_version";
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fe0)) {
+      cause = "call to kuser_get_tls";
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fc0)) {
+      cause = "call to kuser_cmpxchg";
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0fa0)) {
+      cause = "call to kuser_memory_barrier";
+    } else if (si->si_addr == reinterpret_cast<void*>(0xffff0f60)) {
+      cause = "call to kuser_cmpxchg64";
+    } else {
+      cause = get_stack_overflow_cause(reinterpret_cast<uint64_t>(si->si_addr), regs->sp(), maps);
+    }
+  } else if (si->si_signo == SIGSEGV && si->si_code == SEGV_ACCERR) {
+    uint64_t fault_addr = reinterpret_cast<uint64_t>(si->si_addr);
+    unwindstack::MapInfo* map_info = maps->Find(fault_addr);
+    if (map_info != nullptr && map_info->flags == PROT_EXEC) {
+      cause = "execute-only (no-read) memory access error; likely due to data in .text.";
+    } else {
+      cause = get_stack_overflow_cause(fault_addr, regs->sp(), maps);
+    }
+  } else if (si->si_signo == SIGSYS && si->si_code == SYS_SECCOMP) {
+    cause = StringPrintf("seccomp prevented call to disallowed %s system call %d", ABI_STRING,
+                         si->si_syscall);
+  }
+
+  if (cause) {
+    tombstone->mutable_cause()->set_human_readable(*cause);
+  }
+}
+
+static void dump_abort_message(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+                               const ProcessInfo& process_info) {
+  std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
+  uintptr_t address = process_info.abort_msg_address;
+  if (address == 0) {
+    return;
+  }
+
+  size_t length;
+  if (!process_memory->ReadFully(address, &length, sizeof(length))) {
+    PLOG(ERROR) << "Failed to read abort message header";
+    return;
+  }
+
+  // The length field includes the length of the length field itself.
+  if (length < sizeof(size_t)) {
+    LOG(ERROR) << "Abort message header malformed: claimed length = " << length;
+    return;
+  }
+
+  length -= sizeof(size_t);
+
+  // The abort message should be null terminated already, but reserve a spot for NUL just in case.
+  std::string msg;
+  msg.resize(length);
+
+  if (!process_memory->ReadFully(address + sizeof(length), &msg[0], length)) {
+    PLOG(ERROR) << "Failed to read abort message header";
+    return;
+  }
+
+  tombstone->set_abort_message(msg);
+}
+
+static void dump_open_fds(Tombstone* tombstone, const OpenFilesList* open_files) {
+  if (open_files) {
+    for (auto& [fd, entry] : *open_files) {
+      FD f;
+
+      f.set_fd(fd);
+
+      const std::optional<std::string>& path = entry.path;
+      if (path) {
+        f.set_path(*path);
+      }
+
+      const std::optional<uint64_t>& fdsan_owner = entry.fdsan_owner;
+      if (fdsan_owner) {
+        const char* type = android_fdsan_get_tag_type(*fdsan_owner);
+        uint64_t value = android_fdsan_get_tag_value(*fdsan_owner);
+        f.set_owner(type);
+        f.set_tag(value);
+      }
+
+      *tombstone->add_open_fds() = f;
+    }
+  }
+}
+
+static void dump_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+                        const ThreadInfo& thread_info, bool memory_dump = false) {
+  Thread thread;
+
+  thread.set_id(thread_info.tid);
+  thread.set_name(thread_info.thread_name);
+
+  unwindstack::Maps* maps = unwinder->GetMaps();
+  unwindstack::Memory* memory = unwinder->GetProcessMemory().get();
+
+  thread_info.registers->IterateRegisters(
+      [&thread, memory_dump, maps, memory](const char* name, uint64_t value) {
+        Register r;
+        r.set_name(name);
+        r.set_u64(value);
+        *thread.add_registers() = r;
+
+        if (memory_dump) {
+          MemoryDump dump;
+
+          char buf[256];
+          size_t start_offset = 0;
+          ssize_t bytes = dump_memory(buf, sizeof(buf), &start_offset, &value, memory);
+          if (bytes == -1) {
+            return;
+          }
+
+          dump.set_register_name(name);
+
+          unwindstack::MapInfo* map_info = maps->Find(value);
+          if (map_info) {
+            dump.set_mapping_name(map_info->name);
+          }
+
+          dump.set_begin_address(value);
+
+          CHECK(start_offset + bytes <= sizeof(buf));
+          dump.set_memory(buf, start_offset + bytes);
+
+          *thread.add_memory_dump() = std::move(dump);
+        }
+      });
+
+  std::unique_ptr<unwindstack::Regs> regs_copy(thread_info.registers->Clone());
+  unwinder->SetRegs(regs_copy.get());
+  unwinder->Unwind();
+  if (unwinder->NumFrames() == 0) {
+    LOG(ERROR) << "Failed to unwind";
+    if (unwinder->LastErrorCode() != unwindstack::ERROR_NONE) {
+      LOG(ERROR) << "  Error code: " << unwinder->LastErrorCodeString();
+      LOG(ERROR) << "  Error address: " << StringPrintf("0x%" PRIx64, unwinder->LastErrorAddress());
+    }
+  } else {
+    unwinder->SetDisplayBuildID(true);
+    for (const auto& frame : unwinder->frames()) {
+      BacktraceFrame* f = thread.add_current_backtrace();
+      f->set_rel_pc(frame.rel_pc);
+      f->set_pc(frame.pc);
+      f->set_sp(frame.sp);
+
+      if (!frame.function_name.empty()) {
+        // TODO: Should this happen here, or on the display side?
+        char* demangled_name =
+            __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
+        if (demangled_name) {
+          f->set_function_name(demangled_name);
+          free(demangled_name);
+        } else {
+          f->set_function_name(frame.function_name);
+        }
+      }
+
+      f->set_function_offset(frame.function_offset);
+
+      if (frame.map_start == frame.map_end) {
+        // No valid map associated with this frame.
+        f->set_file_name("<unknown>");
+      } else if (!frame.map_name.empty()) {
+        f->set_file_name(frame.map_name);
+      } else {
+        f->set_file_name(StringPrintf("<anonymous:%" PRIx64 ">", frame.map_start));
+      }
+
+      f->set_file_map_offset(frame.map_elf_start_offset);
+
+      unwindstack::MapInfo* map_info = maps->Find(frame.map_start);
+      if (map_info) {
+        f->set_build_id(map_info->GetPrintableBuildID());
+      }
+    }
+  }
+
+  auto& threads = *tombstone->mutable_threads();
+  threads[thread_info.tid] = thread;
+}
+
+static void dump_main_thread(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+                             const ThreadInfo& thread_info) {
+  dump_thread(tombstone, unwinder, thread_info, true);
+}
+
+static void dump_mappings(Tombstone* tombstone, unwindstack::Unwinder* unwinder) {
+  unwindstack::Maps* maps = unwinder->GetMaps();
+  std::shared_ptr<unwindstack::Memory> process_memory = unwinder->GetProcessMemory();
+
+  for (const auto& map_info : *maps) {
+    auto* map = tombstone->add_memory_mappings();
+    map->set_begin_address(map_info->start);
+    map->set_end_address(map_info->end);
+    map->set_offset(map_info->offset);
+
+    if (map_info->flags & PROT_READ) {
+      map->set_read(true);
+    }
+    if (map_info->flags & PROT_WRITE) {
+      map->set_write(true);
+    }
+    if (map_info->flags & PROT_EXEC) {
+      map->set_execute(true);
+    }
+
+    map->set_mapping_name(map_info->name);
+
+    std::string build_id = map_info->GetPrintableBuildID();
+    if (!build_id.empty()) {
+      map->set_build_id(build_id);
+    }
+
+    map->set_load_bias(map_info->GetLoadBias(process_memory));
+  }
+}
+
+static void dump_log_file(Tombstone* tombstone, const char* logger, pid_t pid) {
+  logger_list* logger_list =
+      android_logger_list_open(android_name_to_log_id(logger), ANDROID_LOG_NONBLOCK, 0, pid);
+
+  LogBuffer buffer;
+
+  while (true) {
+    log_msg log_entry;
+    ssize_t actual = android_logger_list_read(logger_list, &log_entry);
+
+    if (actual < 0) {
+      if (actual == -EINTR) {
+        // interrupted by signal, retry
+        continue;
+      }
+      if (actual == -EAGAIN) {
+        // non-blocking EOF; we're done
+        break;
+      } else {
+        ALOGE("Error while reading log: %s\n", strerror(-actual));
+        break;
+      }
+    } else if (actual == 0) {
+      ALOGE("Got zero bytes while reading log: %s\n", strerror(errno));
+      break;
+    }
+
+    char timestamp_secs[32];
+    time_t sec = static_cast<time_t>(log_entry.entry.sec);
+    tm tm;
+    localtime_r(&sec, &tm);
+    strftime(timestamp_secs, sizeof(timestamp_secs), "%m-%d %H:%M:%S", &tm);
+    std::string timestamp =
+        StringPrintf("%s.%03d", timestamp_secs, log_entry.entry.nsec / 1'000'000);
+
+    // Msg format is: <priority:1><tag:N>\0<message:N>\0
+    char* msg = log_entry.msg();
+    if (msg == nullptr) {
+      continue;
+    }
+
+    unsigned char prio = msg[0];
+    char* tag = msg + 1;
+    msg = tag + strlen(tag) + 1;
+
+    // consume any trailing newlines
+    char* nl = msg + strlen(msg) - 1;
+    while (nl >= msg && *nl == '\n') {
+      *nl-- = '\0';
+    }
+
+    // Look for line breaks ('\n') and display each text line
+    // on a separate line, prefixed with the header, like logcat does.
+    do {
+      nl = strchr(msg, '\n');
+      if (nl != nullptr) {
+        *nl = '\0';
+        ++nl;
+      }
+
+      LogMessage* log_msg = buffer.add_logs();
+      log_msg->set_timestamp(timestamp);
+      log_msg->set_pid(log_entry.entry.pid);
+      log_msg->set_tid(log_entry.entry.tid);
+      log_msg->set_priority(prio);
+      log_msg->set_tag(tag);
+      log_msg->set_message(msg);
+    } while ((msg = nl));
+  }
+  android_logger_list_free(logger_list);
+
+  if (!buffer.logs().empty()) {
+    buffer.set_name(logger);
+    *tombstone->add_log_buffers() = std::move(buffer);
+  }
+}
+
+static void dump_logcat(Tombstone* tombstone, pid_t pid) {
+  dump_log_file(tombstone, "system", pid);
+  dump_log_file(tombstone, "main", pid);
+}
+
+void engrave_tombstone_proto(Tombstone* tombstone, unwindstack::Unwinder* unwinder,
+                             const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
+                             const ProcessInfo& process_info, const OpenFilesList* open_files) {
+  Tombstone result;
+
+  result.set_arch(get_arch());
+  result.set_build_fingerprint(android::base::GetProperty("ro.build.fingerprint", "unknown"));
+  result.set_revision(android::base::GetProperty("ro.revision", "unknown"));
+  result.set_timestamp(get_timestamp());
+
+  const ThreadInfo& main_thread = threads.at(target_thread);
+  result.set_pid(main_thread.pid);
+  result.set_tid(main_thread.tid);
+  result.set_uid(main_thread.uid);
+  result.set_selinux_label(main_thread.selinux_label);
+
+  result.set_process_name(main_thread.process_name);
+  CHECK(main_thread.siginfo != nullptr);
+
+  Signal sig;
+  sig.set_number(main_thread.signo);
+  sig.set_name(get_signame(main_thread.siginfo));
+  sig.set_code(main_thread.siginfo->si_code);
+  sig.set_code_name(get_sigcode(main_thread.siginfo));
+
+  if (signal_has_sender(main_thread.siginfo, main_thread.pid)) {
+    sig.set_has_sender(true);
+    sig.set_sender_uid(main_thread.siginfo->si_uid);
+    sig.set_sender_pid(main_thread.siginfo->si_pid);
+  }
+
+  if (process_info.has_fault_address) {
+    sig.set_has_fault_address(true);
+    sig.set_fault_address(process_info.untagged_fault_address);
+  }
+
+  *result.mutable_signal_info() = sig;
+
+  dump_abort_message(&result, unwinder, process_info);
+
+  dump_main_thread(&result, unwinder, main_thread);
+
+  for (const auto& [tid, thread_info] : threads) {
+    if (tid != target_thread) {
+      dump_thread(&result, unwinder, thread_info);
+    }
+  }
+
+  dump_probable_cause(&result, main_thread.siginfo, unwinder->GetMaps(),
+                      main_thread.registers.get());
+
+  dump_mappings(&result, unwinder);
+
+  // Only dump logs on debuggable devices.
+  if (android::base::GetBoolProperty("ro.debuggable", false)) {
+    dump_logcat(&result, main_thread.pid);
+  }
+
+  dump_open_fds(&result, open_files);
+
+  *tombstone = std::move(result);
+}
diff --git a/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp b/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
new file mode 100644
index 0000000..5ba0ad6
--- /dev/null
+++ b/debuggerd/libdebuggerd/tombstone_proto_to_text.cpp
@@ -0,0 +1,361 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#include <libdebuggerd/tombstone.h>
+
+#include <inttypes.h>
+
+#include <functional>
+#include <set>
+#include <string>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+
+#include "tombstone.pb.h"
+
+using android::base::StringAppendF;
+using android::base::StringPrintf;
+
+#define CB(log, ...) callback(StringPrintf(__VA_ARGS__), log)
+#define CBL(...) CB(true, __VA_ARGS__)
+#define CBS(...) CB(false, __VA_ARGS__)
+using CallbackType = std::function<void(const std::string& line, bool should_log)>;
+
+static const char* abi_string(const Tombstone& tombstone) {
+  switch (tombstone.arch()) {
+    case Architecture::ARM32:
+      return "arm";
+    case Architecture::ARM64:
+      return "arm64";
+    case Architecture::X86:
+      return "x86";
+    case Architecture::X86_64:
+      return "x86_64";
+    default:
+      return "<unknown>";
+  }
+}
+
+static int pointer_width(const Tombstone& tombstone) {
+  switch (tombstone.arch()) {
+    case Architecture::ARM32:
+      return 4;
+    case Architecture::ARM64:
+      return 8;
+    case Architecture::X86:
+      return 4;
+    case Architecture::X86_64:
+      return 8;
+    default:
+      return 8;
+  }
+}
+
+static void print_thread_header(CallbackType callback, const Tombstone& tombstone,
+                                const Thread& thread, bool should_log) {
+  CB(should_log, "pid: %d, tid: %d, name: %s  >>> %s <<<", tombstone.pid(), thread.id(),
+     thread.name().c_str(), tombstone.process_name().c_str());
+  CB(should_log, "uid: %d", tombstone.uid());
+}
+
+static void print_register_row(CallbackType callback, int word_size,
+                               std::vector<std::pair<std::string, uint64_t>> row, bool should_log) {
+  std::string output = "  ";
+  for (const auto& [name, value] : row) {
+    output += android::base::StringPrintf("  %-3s %0*" PRIx64, name.c_str(), 2 * word_size,
+                                          static_cast<uint64_t>(value));
+  }
+  callback(output, should_log);
+}
+
+static void print_thread_registers(CallbackType callback, const Tombstone& tombstone,
+                                   const Thread& thread, bool should_log) {
+  static constexpr size_t column_count = 4;
+  std::vector<std::pair<std::string, uint64_t>> current_row;
+  std::vector<std::pair<std::string, uint64_t>> special_row;
+  std::unordered_set<std::string> special_registers;
+
+  int word_size = pointer_width(tombstone);
+
+  switch (tombstone.arch()) {
+    case Architecture::ARM32:
+      special_registers = {"ip", "lr", "sp", "pc", "pst"};
+      break;
+
+    case Architecture::ARM64:
+      special_registers = {"ip", "lr", "sp", "pc", "pst"};
+      break;
+
+    case Architecture::X86:
+      special_registers = {"ebp", "esp", "eip"};
+      break;
+
+    case Architecture::X86_64:
+      special_registers = {"rbp", "rsp", "rip"};
+      break;
+
+    default:
+      LOG(FATAL) << "unknown architecture";
+  }
+
+  for (const auto& reg : thread.registers()) {
+    auto row = &current_row;
+    if (special_registers.count(reg.name()) == 1) {
+      row = &special_row;
+    }
+
+    row->emplace_back(reg.name(), reg.u64());
+    if (current_row.size() == column_count) {
+      print_register_row(callback, word_size, current_row, should_log);
+      current_row.clear();
+    }
+  }
+
+  if (!current_row.empty()) {
+    print_register_row(callback, word_size, current_row, should_log);
+  }
+
+  print_register_row(callback, word_size, special_row, should_log);
+}
+
+static void print_thread_backtrace(CallbackType callback, const Tombstone& tombstone,
+                                   const Thread& thread, bool should_log) {
+  CBS("");
+  CB(should_log, "backtrace:");
+  int index = 0;
+  for (const auto& frame : thread.current_backtrace()) {
+    std::string function;
+
+    if (!frame.function_name().empty()) {
+      function =
+          StringPrintf(" (%s+%" PRId64 ")", frame.function_name().c_str(), frame.function_offset());
+    }
+
+    std::string build_id;
+    if (!frame.build_id().empty()) {
+      build_id = StringPrintf(" (BuildId: %s)", frame.build_id().c_str());
+    }
+
+    CB(should_log, "      #%02d pc %0*" PRIx64 "  %s%s%s", index++, pointer_width(tombstone) * 2,
+       frame.rel_pc(), frame.file_name().c_str(), function.c_str(), build_id.c_str());
+  }
+}
+
+static void print_thread_memory_dump(CallbackType callback, const Tombstone& tombstone,
+                                     const Thread& thread) {
+  static constexpr size_t bytes_per_line = 16;
+  int word_size = pointer_width(tombstone);
+  for (const auto& mem : thread.memory_dump()) {
+    CBS("");
+    CBS("memory near %s (%s):", mem.register_name().c_str(), mem.mapping_name().c_str());
+    uint64_t addr = mem.begin_address();
+    for (size_t offset = 0; offset < mem.memory().size(); offset += bytes_per_line) {
+      std::string line = StringPrintf("    %0*" PRIx64, word_size * 2, addr + offset);
+
+      size_t bytes = std::min(bytes_per_line, mem.memory().size() - offset);
+      for (size_t i = 0; i < bytes; i += word_size) {
+        uint64_t word = 0;
+
+        // Assumes little-endian, but what doesn't?
+        memcpy(&word, mem.memory().data() + offset + i, word_size);
+
+        StringAppendF(&line, " %0*" PRIx64, word_size * 2, word);
+      }
+
+      char ascii[bytes_per_line + 1];
+
+      memset(ascii, '.', sizeof(ascii));
+      ascii[bytes_per_line] = '\0';
+
+      for (size_t i = 0; i < bytes; ++i) {
+        uint8_t byte = mem.memory()[offset + i];
+        if (byte >= 0x20 && byte < 0x7f) {
+          ascii[i] = byte;
+        }
+      }
+
+      CBS("%s  %s", line.c_str(), ascii);
+    }
+  }
+}
+
+static void print_thread(CallbackType callback, const Tombstone& tombstone, const Thread& thread) {
+  print_thread_header(callback, tombstone, thread, false);
+  print_thread_registers(callback, tombstone, thread, false);
+  print_thread_backtrace(callback, tombstone, thread, false);
+  print_thread_memory_dump(callback, tombstone, thread);
+}
+
+static void print_main_thread(CallbackType callback, const Tombstone& tombstone,
+                              const Thread& thread) {
+  print_thread_header(callback, tombstone, thread, true);
+
+  const Signal& signal_info = tombstone.signal_info();
+  std::string sender_desc;
+
+  if (signal_info.has_sender()) {
+    sender_desc =
+        StringPrintf(" from pid %d, uid %d", signal_info.sender_pid(), signal_info.sender_uid());
+  }
+
+  if (!tombstone.has_signal_info()) {
+    LOG(ERROR) << "signal info missing in tombstone";
+    CBL("signal information missing");
+  } else {
+    std::string fault_addr_desc;
+    if (signal_info.has_fault_address()) {
+      fault_addr_desc = StringPrintf("0x%" PRIx64, signal_info.fault_address());
+    } else {
+      fault_addr_desc = "--------";
+    }
+
+    CBL("signal %d (%s), code %d (%s%s), fault addr %s", signal_info.number(),
+        signal_info.name().c_str(), signal_info.code(), signal_info.code_name().c_str(),
+        sender_desc.c_str(), fault_addr_desc.c_str());
+  }
+
+  if (tombstone.has_cause()) {
+    const Cause& cause = tombstone.cause();
+    CBL("Cause: %s", cause.human_readable().c_str());
+  }
+
+  if (!tombstone.abort_message().empty()) {
+    CBL("Abort message: '%s'", tombstone.abort_message().c_str());
+  }
+
+  print_thread_registers(callback, tombstone, thread, true);
+  print_thread_backtrace(callback, tombstone, thread, true);
+  print_thread_memory_dump(callback, tombstone, thread);
+
+  CBS("");
+  CBS("memory map (%d %s):", tombstone.memory_mappings().size(),
+      tombstone.memory_mappings().size() == 1 ? "entry" : "entries");
+  int word_size = pointer_width(tombstone);
+  const auto format_pointer = [word_size](uint64_t ptr) -> std::string {
+    if (word_size == 8) {
+      uint64_t top = ptr >> 32;
+      uint64_t bottom = ptr & 0xFFFFFFFF;
+      return StringPrintf("%08" PRIx64 "'%08" PRIx64, top, bottom);
+    }
+
+    return StringPrintf("%0*" PRIx64, word_size * 2, ptr);
+  };
+
+  for (const auto& map : tombstone.memory_mappings()) {
+    std::string line = "    ";
+    StringAppendF(&line, "%s-%s", format_pointer(map.begin_address()).c_str(),
+                  format_pointer(map.end_address() - 1).c_str());
+    StringAppendF(&line, " %s%s%s", map.read() ? "r" : "-", map.write() ? "w" : "-",
+                  map.execute() ? "x" : "-");
+    StringAppendF(&line, "  %8" PRIx64 "  %8" PRIx64, map.offset(),
+                  map.end_address() - map.begin_address());
+
+    if (!map.mapping_name().empty()) {
+      StringAppendF(&line, "  %s", map.mapping_name().c_str());
+
+      if (!map.build_id().empty()) {
+        StringAppendF(&line, " (BuildId: %s)", map.build_id().c_str());
+      }
+
+      if (map.load_bias() != 0) {
+        StringAppendF(&line, " (load bias 0x%" PRIx64 ")", map.load_bias());
+      }
+    }
+
+    CBS("%s", line.c_str());
+  }
+}
+
+void print_logs(CallbackType callback, const Tombstone& tombstone, int tail) {
+  for (const auto& buffer : tombstone.log_buffers()) {
+    if (tail) {
+      CBS("--------- tail end of log %s", buffer.name().c_str());
+    } else {
+      CBS("--------- log %s", buffer.name().c_str());
+    }
+
+    int begin = 0;
+    if (tail != 0) {
+      begin = std::max(0, buffer.logs().size() - tail);
+    }
+
+    for (int i = begin; i < buffer.logs().size(); ++i) {
+      const LogMessage& msg = buffer.logs(i);
+
+      static const char* kPrioChars = "!.VDIWEFS";
+      char priority = (msg.priority() < strlen(kPrioChars) ? kPrioChars[msg.priority()] : '?');
+      CBS("%s %5u %5u %c %-8s: %s", msg.timestamp().c_str(), msg.pid(), msg.tid(), priority,
+          msg.tag().c_str(), msg.message().c_str());
+    }
+  }
+}
+
+bool tombstone_proto_to_text(const Tombstone& tombstone, CallbackType callback) {
+  CBL("*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***");
+  CBL("Build fingerprint: '%s'", tombstone.build_fingerprint().c_str());
+  CBL("Revision: '%s'", tombstone.revision().c_str());
+  CBL("ABI: '%s'", abi_string(tombstone));
+  CBL("Timestamp: %s", tombstone.timestamp().c_str());
+
+  // Process header
+  const auto& threads = tombstone.threads();
+  auto main_thread_it = threads.find(tombstone.tid());
+  if (main_thread_it == threads.end()) {
+    LOG(ERROR) << "failed to find entry for main thread in tombstone";
+    return false;
+  }
+
+  const auto& main_thread = main_thread_it->second;
+
+  print_main_thread(callback, tombstone, main_thread);
+
+  print_logs(callback, tombstone, 50);
+
+  // protobuf's map is unordered, so sort the keys first.
+  std::set<int> thread_ids;
+  for (const auto& [tid, _] : threads) {
+    if (tid != tombstone.tid()) {
+      thread_ids.insert(tid);
+    }
+  }
+
+  for (const auto& tid : thread_ids) {
+    CBS("--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---");
+    print_thread(callback, tombstone, threads.find(tid)->second);
+  }
+
+  if (tombstone.open_fds().size() > 0) {
+    CBS("");
+    CBS("open files:");
+    for (const auto& fd : tombstone.open_fds()) {
+      std::optional<std::string> owner;
+      if (!fd.owner().empty()) {
+        owner = StringPrintf("owned by %s 0x%" PRIx64, fd.owner().c_str(), fd.tag());
+      }
+
+      CBS("    fd %d: %s (%s)", fd.fd(), fd.path().c_str(), owner ? owner->c_str() : "unowned");
+    }
+  }
+
+  print_logs(callback, tombstone, 0);
+
+  return true;
+}
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 7826efc..f406ad4 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -126,56 +126,56 @@
 #define MEMORY_BYTES_TO_DUMP 256
 #define MEMORY_BYTES_PER_LINE 16
 
-void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const std::string& label) {
+ssize_t dump_memory(void* out, size_t len, size_t* start_offset, uint64_t* addr,
+                    unwindstack::Memory* memory) {
   // Align the address to the number of bytes per line to avoid confusing memory tag output if
   // memory is tagged and we start from a misaligned address. Start 32 bytes before the address.
-  addr &= ~(MEMORY_BYTES_PER_LINE - 1);
-  if (addr >= 4128) {
-    addr -= 32;
+  *addr &= ~(MEMORY_BYTES_PER_LINE - 1);
+  if (*addr >= 4128) {
+    *addr -= 32;
   }
 
   // We don't want the address tag to appear in the addresses in the memory dump.
-  addr = untag_address(addr);
+  *addr = untag_address(*addr);
 
   // Don't bother if the address would overflow, taking tag bits into account. Note that
   // untag_address truncates to 32 bits on 32-bit platforms as a side effect of returning a
   // uintptr_t, so this also checks for 32-bit overflow.
-  if (untag_address(addr + MEMORY_BYTES_TO_DUMP - 1) < addr) {
-    return;
+  if (untag_address(*addr + MEMORY_BYTES_TO_DUMP - 1) < *addr) {
+    return -1;
   }
 
-  // Dump 256 bytes
-  uintptr_t data[MEMORY_BYTES_TO_DUMP/sizeof(uintptr_t)];
-  memset(data, 0, MEMORY_BYTES_TO_DUMP);
-  size_t bytes = memory->Read(addr, reinterpret_cast<uint8_t*>(data), sizeof(data));
+  memset(out, 0, len);
+
+  size_t bytes = memory->Read(*addr, reinterpret_cast<uint8_t*>(out), len);
   if (bytes % sizeof(uintptr_t) != 0) {
     // This should never happen, but just in case.
     ALOGE("Bytes read %zu, is not a multiple of %zu", bytes, sizeof(uintptr_t));
     bytes &= ~(sizeof(uintptr_t) - 1);
   }
 
-  uint64_t start = 0;
+  *start_offset = 0;
   bool skip_2nd_read = false;
   if (bytes == 0) {
     // In this case, we might want to try another read at the beginning of
     // the next page only if it's within the amount of memory we would have
     // read.
     size_t page_size = sysconf(_SC_PAGE_SIZE);
-    start = ((addr + (page_size - 1)) & ~(page_size - 1)) - addr;
-    if (start == 0 || start >= MEMORY_BYTES_TO_DUMP) {
+    *start_offset = ((*addr + (page_size - 1)) & ~(page_size - 1)) - *addr;
+    if (*start_offset == 0 || *start_offset >= len) {
       skip_2nd_read = true;
     }
   }
 
-  if (bytes < MEMORY_BYTES_TO_DUMP && !skip_2nd_read) {
+  if (bytes < len && !skip_2nd_read) {
     // Try to do one more read. This could happen if a read crosses a map,
     // but the maps do not have any break between them. Or it could happen
     // if reading from an unreadable map, but the read would cross back
     // into a readable map. Only requires one extra read because a map has
     // to contain at least one page, and the total number of bytes to dump
     // is smaller than a page.
-    size_t bytes2 = memory->Read(addr + start + bytes, reinterpret_cast<uint8_t*>(data) + bytes,
-                                 sizeof(data) - bytes - start);
+    size_t bytes2 = memory->Read(*addr + *start_offset + bytes, static_cast<uint8_t*>(out) + bytes,
+                                 len - bytes - *start_offset);
     bytes += bytes2;
     if (bytes2 > 0 && bytes % sizeof(uintptr_t) != 0) {
       // This should never happen, but we'll try and continue any way.
@@ -185,9 +185,21 @@
   }
 
   // If we were unable to read anything, it probably means that the register doesn't contain a
-  // valid pointer. In that case, skip the output for this register entirely rather than emitting 16
-  // lines of dashes.
+  // valid pointer.
   if (bytes == 0) {
+    return -1;
+  }
+
+  return bytes;
+}
+
+void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const std::string& label) {
+  // Dump 256 bytes
+  uintptr_t data[MEMORY_BYTES_TO_DUMP / sizeof(uintptr_t)];
+  size_t start_offset = 0;
+
+  ssize_t bytes = dump_memory(data, sizeof(data), &start_offset, &addr, memory);
+  if (bytes == -1) {
     return;
   }
 
@@ -201,7 +213,7 @@
   // words are of course presented differently.
   uintptr_t* data_ptr = data;
   size_t current = 0;
-  size_t total_bytes = start + bytes;
+  size_t total_bytes = start_offset + bytes;
   for (size_t line = 0; line < MEMORY_BYTES_TO_DUMP / MEMORY_BYTES_PER_LINE; line++) {
     uint64_t tagged_addr = addr;
     long tag = memory->ReadTag(addr);
@@ -214,7 +226,7 @@
     addr += MEMORY_BYTES_PER_LINE;
     std::string ascii;
     for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
-      if (current >= start && current + sizeof(uintptr_t) <= total_bytes) {
+      if (current >= start_offset && current + sizeof(uintptr_t) <= total_bytes) {
         android::base::StringAppendF(&logline, " %" PRIPTR, static_cast<uint64_t>(*data_ptr));
 
         // Fill out the ascii string from the data.
diff --git a/debuggerd/pbtombstone.cpp b/debuggerd/pbtombstone.cpp
new file mode 100644
index 0000000..7527e31
--- /dev/null
+++ b/debuggerd/pbtombstone.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#include <err.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <unistd.h>
+
+#include <android-base/unique_fd.h>
+#include <libdebuggerd/tombstone.h>
+
+#include "tombstone.pb.h"
+
+using android::base::unique_fd;
+
+[[noreturn]] void usage(bool error) {
+  fprintf(stderr, "usage: pbtombstone TOMBSTONE.PB\n");
+  fprintf(stderr, "Convert a protobuf tombstone to text.\n");
+  exit(error);
+}
+
+int main(int argc, const char* argv[]) {
+  if (argc != 2) {
+    usage(true);
+  }
+
+  if (strcmp("-h", argv[1]) == 0 || strcmp("--help", argv[1]) == 0) {
+    usage(false);
+  }
+
+  unique_fd fd(open(argv[1], O_RDONLY | O_CLOEXEC));
+  if (fd == -1) {
+    err(1, "failed to open tombstone '%s'", argv[1]);
+  }
+
+  Tombstone tombstone;
+  if (!tombstone.ParseFromFileDescriptor(fd.get())) {
+    err(1, "failed to parse tombstone");
+  }
+
+  bool result = tombstone_proto_to_text(
+      tombstone, [](const std::string& line, bool) { printf("%s\n", line.c_str()); });
+
+  if (!result) {
+    errx(1, "tombstone was malformed");
+  }
+
+  return 0;
+}
diff --git a/debuggerd/proto/Android.bp b/debuggerd/proto/Android.bp
new file mode 100644
index 0000000..5307d50
--- /dev/null
+++ b/debuggerd/proto/Android.bp
@@ -0,0 +1,28 @@
+cc_library {
+    name: "libtombstone_proto",
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Wthread-safety",
+        "-Werror",
+    ],
+
+    compile_multilib: "both",
+
+    proto: {
+        export_proto_headers: true,
+        type: "lite",
+    },
+
+    srcs: [
+        "tombstone.proto",
+    ],
+
+    stl: "libc++_static",
+    apex_available: [
+        "com.android.runtime",
+    ],
+
+    recovery_available: true,
+    vendor_ramdisk_available: true,
+}
diff --git a/debuggerd/proto/tombstone.proto b/debuggerd/proto/tombstone.proto
new file mode 100644
index 0000000..aff50bd
--- /dev/null
+++ b/debuggerd/proto/tombstone.proto
@@ -0,0 +1,118 @@
+syntax = "proto3";
+
+message Tombstone {
+  Architecture arch = 1;
+  string build_fingerprint = 2;
+  string revision = 3;
+  string timestamp = 4;
+
+  uint32 pid = 5;
+  uint32 tid = 6;
+  uint32 uid = 7;
+  string selinux_label = 8;
+
+  string process_name = 9;
+
+  Signal signal_info = 10;
+  string abort_message = 14;
+  Cause cause = 15;
+
+  map<uint32, Thread> threads = 16;
+  repeated MemoryMapping memory_mappings = 17;
+  repeated LogBuffer log_buffers = 18;
+  repeated FD open_fds = 19;
+}
+
+enum Architecture {
+  ARM32 = 0;
+  ARM64 = 1;
+  X86 = 2;
+  X86_64 = 3;
+}
+
+message Signal {
+  int32 number = 1;
+  string name = 2;
+
+  int32 code = 3;
+  string code_name = 4;
+
+  bool has_sender = 5;
+  int32 sender_uid = 6;
+  int32 sender_pid = 7;
+
+  bool has_fault_address = 8;
+  uint64 fault_address = 9;
+}
+
+message Cause {
+  string human_readable = 1;
+}
+
+message Register {
+  string name = 1;
+  uint64 u64 = 2;
+}
+
+message Thread {
+  int32 id = 1;
+  string name = 2;
+  repeated Register registers = 3;
+  repeated BacktraceFrame current_backtrace = 4;
+  repeated MemoryDump memory_dump = 5;
+}
+
+message BacktraceFrame {
+  uint64 rel_pc = 1;
+  uint64 pc = 2;
+  uint64 sp = 3;
+
+  string function_name = 4;
+  uint64 function_offset = 5;
+
+  string file_name = 6;
+  uint64 file_map_offset = 7;
+  string build_id = 8;
+}
+
+message MemoryDump {
+  string register_name = 1;
+  string mapping_name = 2;
+  uint64 begin_address = 3;
+  bytes memory = 4;
+}
+
+message MemoryMapping {
+  uint64 begin_address = 1;
+  uint64 end_address = 2;
+  uint64 offset = 3;
+
+  bool read = 4;
+  bool write = 5;
+  bool execute = 6;
+
+  string mapping_name = 7;
+  string build_id = 8;
+  uint64 load_bias = 9;
+}
+
+message FD {
+  int32 fd = 1;
+  string path = 2;
+  string owner = 3;
+  uint64 tag = 4;
+}
+
+message LogBuffer {
+  string name = 1;
+  repeated LogMessage logs = 2;
+}
+
+message LogMessage {
+  string timestamp = 1;
+  uint32 pid = 2;
+  uint32 tid = 3;
+  uint32 priority = 4;
+  string tag = 5;
+  string message = 6;
+}
diff --git a/debuggerd/seccomp_policy/crash_dump.arm.policy b/debuggerd/seccomp_policy/crash_dump.arm.policy
index 254330d..4eac0e9 100644
--- a/debuggerd/seccomp_policy/crash_dump.arm.policy
+++ b/debuggerd/seccomp_policy/crash_dump.arm.policy
@@ -19,6 +19,7 @@
 getdents64: 1
 faccessat: 1
 recvmsg: 1
+recvfrom: 1
 process_vm_readv: 1
 tgkill: 1
 rt_sigprocmask: 1
diff --git a/debuggerd/seccomp_policy/crash_dump.arm64.policy b/debuggerd/seccomp_policy/crash_dump.arm64.policy
index 9b3ef09..1585cc6 100644
--- a/debuggerd/seccomp_policy/crash_dump.arm64.policy
+++ b/debuggerd/seccomp_policy/crash_dump.arm64.policy
@@ -18,6 +18,7 @@
 getdents64: 1
 faccessat: 1
 recvmsg: 1
+recvfrom: 1
 process_vm_readv: 1
 tgkill: 1
 rt_sigprocmask: 1
diff --git a/debuggerd/seccomp_policy/crash_dump.policy.def b/debuggerd/seccomp_policy/crash_dump.policy.def
index 2ef31b0..cd5aad4 100644
--- a/debuggerd/seccomp_policy/crash_dump.policy.def
+++ b/debuggerd/seccomp_policy/crash_dump.policy.def
@@ -24,6 +24,7 @@
 getdents64: 1
 faccessat: 1
 recvmsg: 1
+recvfrom: 1
 
 process_vm_readv: 1
 
diff --git a/debuggerd/seccomp_policy/crash_dump.x86.policy b/debuggerd/seccomp_policy/crash_dump.x86.policy
index 254330d..4eac0e9 100644
--- a/debuggerd/seccomp_policy/crash_dump.x86.policy
+++ b/debuggerd/seccomp_policy/crash_dump.x86.policy
@@ -19,6 +19,7 @@
 getdents64: 1
 faccessat: 1
 recvmsg: 1
+recvfrom: 1
 process_vm_readv: 1
 tgkill: 1
 rt_sigprocmask: 1
diff --git a/debuggerd/seccomp_policy/crash_dump.x86_64.policy b/debuggerd/seccomp_policy/crash_dump.x86_64.policy
index 9b3ef09..1585cc6 100644
--- a/debuggerd/seccomp_policy/crash_dump.x86_64.policy
+++ b/debuggerd/seccomp_policy/crash_dump.x86_64.policy
@@ -18,6 +18,7 @@
 getdents64: 1
 faccessat: 1
 recvmsg: 1
+recvfrom: 1
 process_vm_readv: 1
 tgkill: 1
 rt_sigprocmask: 1
diff --git a/debuggerd/tombstoned/include/tombstoned/tombstoned.h b/debuggerd/tombstoned/include/tombstoned/tombstoned.h
index 6403dbe..bff216c 100644
--- a/debuggerd/tombstoned/include/tombstoned/tombstoned.h
+++ b/debuggerd/tombstoned/include/tombstoned/tombstoned.h
@@ -23,6 +23,10 @@
 #include "dump_type.h"
 
 bool tombstoned_connect(pid_t pid, android::base::unique_fd* tombstoned_socket,
-                        android::base::unique_fd* output_fd, DebuggerdDumpType dump_type);
+                        android::base::unique_fd* text_output_fd,
+                        android::base::unique_fd* proto_output_fd, DebuggerdDumpType dump_type);
+
+bool tombstoned_connect(pid_t pid, android::base::unique_fd* tombstoned_socket,
+                        android::base::unique_fd* text_output_fd, DebuggerdDumpType dump_type);
 
 bool tombstoned_notify_completion(int tombstoned_socket);
diff --git a/debuggerd/tombstoned/intercept_manager.cpp b/debuggerd/tombstoned/intercept_manager.cpp
index 6cbf12c..437639e 100644
--- a/debuggerd/tombstoned/intercept_manager.cpp
+++ b/debuggerd/tombstoned/intercept_manager.cpp
@@ -191,6 +191,18 @@
                                       /* backlog */ -1, intercept_socket);
 }
 
+bool dump_types_compatible(DebuggerdDumpType interceptor, DebuggerdDumpType dump) {
+  if (interceptor == dump) {
+    return true;
+  }
+
+  if (interceptor == kDebuggerdTombstone && dump == kDebuggerdTombstoneProto) {
+    return true;
+  }
+
+  return false;
+}
+
 bool InterceptManager::GetIntercept(pid_t pid, DebuggerdDumpType dump_type,
                                     android::base::unique_fd* out_fd) {
   auto it = this->intercepts.find(pid);
@@ -201,7 +213,7 @@
   if (dump_type == kDebuggerdAnyIntercept) {
     LOG(INFO) << "found registered intercept of type " << it->second->dump_type
               << " for requested type kDebuggerdAnyIntercept";
-  } else if (it->second->dump_type != dump_type) {
+  } else if (!dump_types_compatible(it->second->dump_type, dump_type)) {
     LOG(WARNING) << "found non-matching intercept of type " << it->second->dump_type
                  << " for requested type: " << dump_type;
     return false;
diff --git a/debuggerd/tombstoned/tombstoned.cpp b/debuggerd/tombstoned/tombstoned.cpp
index d09b8e8..f057260 100644
--- a/debuggerd/tombstoned/tombstoned.cpp
+++ b/debuggerd/tombstoned/tombstoned.cpp
@@ -48,6 +48,8 @@
 using android::base::GetIntProperty;
 using android::base::SendFileDescriptors;
 using android::base::StringPrintf;
+
+using android::base::borrowed_fd;
 using android::base::unique_fd;
 
 static InterceptManager* intercept_manager;
@@ -57,14 +59,34 @@
   kCrashStatusQueued,
 };
 
+struct CrashArtifact {
+  unique_fd fd;
+  std::optional<std::string> temporary_path;
+
+  static CrashArtifact devnull() {
+    CrashArtifact result;
+    result.fd.reset(open("/dev/null", O_WRONLY | O_CLOEXEC));
+    return result;
+  }
+};
+
+struct CrashArtifactPaths {
+  std::string text;
+  std::optional<std::string> proto;
+};
+
+struct CrashOutput {
+  CrashArtifact text;
+  std::optional<CrashArtifact> proto;
+};
+
 // Ownership of Crash is a bit messy.
 // It's either owned by an active event that must have a timeout, or owned by
 // queued_requests, in the case that multiple crashes come in at the same time.
 struct Crash {
   ~Crash() { event_free(crash_event); }
 
-  std::string crash_tombstone_path;
-  unique_fd crash_tombstone_fd;
+  CrashOutput output;
   unique_fd crash_socket_fd;
   pid_t crash_pid;
   event* crash_event = nullptr;
@@ -75,14 +97,15 @@
 class CrashQueue {
  public:
   CrashQueue(const std::string& dir_path, const std::string& file_name_prefix, size_t max_artifacts,
-             size_t max_concurrent_dumps)
+             size_t max_concurrent_dumps, bool supports_proto)
       : file_name_prefix_(file_name_prefix),
         dir_path_(dir_path),
         dir_fd_(open(dir_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC)),
         max_artifacts_(max_artifacts),
         next_artifact_(0),
         max_concurrent_dumps_(max_concurrent_dumps),
-        num_concurrent_dumps_(0) {
+        num_concurrent_dumps_(0),
+        supports_proto_(supports_proto) {
     if (dir_fd_ == -1) {
       PLOG(FATAL) << "failed to open directory: " << dir_path;
     }
@@ -98,59 +121,104 @@
     return (crash->crash_type == kDebuggerdJavaBacktrace) ? for_anrs() : for_tombstones();
   }
 
+  static CrashQueue* for_crash(const std::unique_ptr<Crash>& crash) {
+    return for_crash(crash.get());
+  }
+
   static CrashQueue* for_tombstones() {
     static CrashQueue queue("/data/tombstones", "tombstone_" /* file_name_prefix */,
                             GetIntProperty("tombstoned.max_tombstone_count", 32),
-                            1 /* max_concurrent_dumps */);
+                            1 /* max_concurrent_dumps */, true /* supports_proto */);
     return &queue;
   }
 
   static CrashQueue* for_anrs() {
     static CrashQueue queue("/data/anr", "trace_" /* file_name_prefix */,
                             GetIntProperty("tombstoned.max_anr_count", 64),
-                            4 /* max_concurrent_dumps */);
+                            4 /* max_concurrent_dumps */, false /* supports_proto */);
     return &queue;
   }
 
-  std::pair<std::string, unique_fd> get_output() {
-    std::string path;
-    unique_fd result(openat(dir_fd_, ".", O_WRONLY | O_APPEND | O_TMPFILE | O_CLOEXEC, 0640));
-    if (result == -1) {
+  CrashArtifact create_temporary_file() const {
+    CrashArtifact result;
+
+    std::optional<std::string> path;
+    result.fd.reset(openat(dir_fd_, ".", O_WRONLY | O_APPEND | O_TMPFILE | O_CLOEXEC, 0640));
+    if (result.fd == -1) {
       // We might not have O_TMPFILE. Try creating with an arbitrary filename instead.
       static size_t counter = 0;
       std::string tmp_filename = StringPrintf(".temporary%zu", counter++);
-      result.reset(openat(dir_fd_, tmp_filename.c_str(),
-                          O_WRONLY | O_APPEND | O_CREAT | O_TRUNC | O_CLOEXEC, 0640));
-      if (result == -1) {
+      result.fd.reset(openat(dir_fd_, tmp_filename.c_str(),
+                             O_WRONLY | O_APPEND | O_CREAT | O_TRUNC | O_CLOEXEC, 0640));
+      if (result.fd == -1) {
         PLOG(FATAL) << "failed to create temporary tombstone in " << dir_path_;
       }
 
-      path = StringPrintf("%s/%s", dir_path_.c_str(), tmp_filename.c_str());
+      result.temporary_path = std::move(tmp_filename);
     }
-    return std::make_pair(std::move(path), std::move(result));
+
+    return std::move(result);
   }
 
-  std::string get_next_artifact_path() {
-    std::string file_name =
-        StringPrintf("%s/%s%02d", dir_path_.c_str(), file_name_prefix_.c_str(), next_artifact_);
+  std::optional<CrashOutput> get_output(DebuggerdDumpType dump_type) {
+    CrashOutput result;
+
+    switch (dump_type) {
+      case kDebuggerdNativeBacktrace:
+      case kDebuggerdJavaBacktrace:
+        // Don't generate tombstones for backtrace requests.
+        return {};
+
+      case kDebuggerdTombstoneProto:
+        if (!supports_proto_) {
+          LOG(ERROR) << "received kDebuggerdTombstoneProto on a queue that doesn't support proto";
+          return {};
+        }
+        result.proto = create_temporary_file();
+        result.text = create_temporary_file();
+        break;
+
+      case kDebuggerdTombstone:
+        result.text = create_temporary_file();
+        break;
+
+      default:
+        LOG(ERROR) << "unexpected dump type: " << dump_type;
+        return {};
+    }
+
+    return result;
+  }
+
+  borrowed_fd dir_fd() { return dir_fd_; }
+
+  CrashArtifactPaths get_next_artifact_paths() {
+    CrashArtifactPaths result;
+    result.text = StringPrintf("%s%02d", file_name_prefix_.c_str(), next_artifact_);
+
+    if (supports_proto_) {
+      result.proto = StringPrintf("%s%02d.pb", file_name_prefix_.c_str(), next_artifact_);
+    }
+
     next_artifact_ = (next_artifact_ + 1) % max_artifacts_;
-    return file_name;
+    return result;
   }
 
-  bool maybe_enqueue_crash(Crash* crash) {
+  // Consumes crash if it returns true, otherwise leaves it untouched.
+  bool maybe_enqueue_crash(std::unique_ptr<Crash>&& crash) {
     if (num_concurrent_dumps_ == max_concurrent_dumps_) {
-      queued_requests_.push_back(crash);
+      queued_requests_.emplace_back(std::move(crash));
       return true;
     }
 
     return false;
   }
 
-  void maybe_dequeue_crashes(void (*handler)(Crash* crash)) {
+  void maybe_dequeue_crashes(void (*handler)(std::unique_ptr<Crash> crash)) {
     while (!queued_requests_.empty() && num_concurrent_dumps_ < max_concurrent_dumps_) {
-      Crash* next_crash = queued_requests_.front();
+      std::unique_ptr<Crash> next_crash = std::move(queued_requests_.front());
       queued_requests_.pop_front();
-      handler(next_crash);
+      handler(std::move(next_crash));
     }
   }
 
@@ -164,7 +232,8 @@
     time_t oldest_time = std::numeric_limits<time_t>::max();
 
     for (size_t i = 0; i < max_artifacts_; ++i) {
-      std::string path = StringPrintf("%s/%s%02zu", dir_path_.c_str(), file_name_prefix_.c_str(), i);
+      std::string path =
+          StringPrintf("%s/%s%02zu", dir_path_.c_str(), file_name_prefix_.c_str(), i);
       struct stat st;
       if (stat(path.c_str(), &st) != 0) {
         if (errno == ENOENT) {
@@ -196,7 +265,9 @@
   const size_t max_concurrent_dumps_;
   size_t num_concurrent_dumps_;
 
-  std::deque<Crash*> queued_requests_;
+  bool supports_proto_;
+
+  std::deque<std::unique_ptr<Crash>> queued_requests_;
 
   DISALLOW_COPY_AND_ASSIGN(CrashQueue);
 };
@@ -205,52 +276,61 @@
 static constexpr bool kJavaTraceDumpsEnabled = true;
 
 // Forward declare the callbacks so they can be placed in a sensible order.
-static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int, void*);
+static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int,
+                            void*);
 static void crash_request_cb(evutil_socket_t sockfd, short ev, void* arg);
 static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg);
 
-static void perform_request(Crash* crash) {
+static void perform_request(std::unique_ptr<Crash> crash) {
   unique_fd output_fd;
   bool intercepted =
       intercept_manager->GetIntercept(crash->crash_pid, crash->crash_type, &output_fd);
-  if (!intercepted) {
-    if (crash->crash_type == kDebuggerdNativeBacktrace) {
-      // Don't generate tombstones for native backtrace requests.
-      output_fd.reset(open("/dev/null", O_WRONLY | O_CLOEXEC));
+  if (intercepted) {
+    if (crash->crash_type == kDebuggerdTombstoneProto) {
+      crash->output.proto = CrashArtifact::devnull();
+    }
+  } else {
+    if (auto o = CrashQueue::for_crash(crash.get())->get_output(crash->crash_type); o) {
+      crash->output = std::move(*o);
+      output_fd.reset(dup(crash->output.text.fd));
     } else {
-      std::tie(crash->crash_tombstone_path, output_fd) = CrashQueue::for_crash(crash)->get_output();
-      crash->crash_tombstone_fd.reset(dup(output_fd.get()));
+      LOG(ERROR) << "failed to get crash output for type " << crash->crash_type;
+      return;
     }
   }
 
-  TombstonedCrashPacket response = {
-    .packet_type = CrashPacketType::kPerformDump
-  };
-  ssize_t rc =
-      SendFileDescriptors(crash->crash_socket_fd, &response, sizeof(response), output_fd.get());
+  TombstonedCrashPacket response = {.packet_type = CrashPacketType::kPerformDump};
+
+  ssize_t rc = -1;
+  if (crash->output.proto) {
+    rc = SendFileDescriptors(crash->crash_socket_fd, &response, sizeof(response), output_fd.get(),
+                             crash->output.proto->fd.get());
+  } else {
+    rc = SendFileDescriptors(crash->crash_socket_fd, &response, sizeof(response), output_fd.get());
+  }
+
   output_fd.reset();
 
   if (rc == -1) {
     PLOG(WARNING) << "failed to send response to CrashRequest";
-    goto fail;
+    return;
   } else if (rc != sizeof(response)) {
     PLOG(WARNING) << "crash socket write returned short";
-    goto fail;
-  } else {
-    // TODO: Make this configurable by the interceptor?
-    struct timeval timeout = { 10, 0 };
-
-    event_base* base = event_get_base(crash->crash_event);
-    event_assign(crash->crash_event, base, crash->crash_socket_fd, EV_TIMEOUT | EV_READ,
-                 crash_completed_cb, crash);
-    event_add(crash->crash_event, &timeout);
+    return;
   }
 
-  CrashQueue::for_crash(crash)->on_crash_started();
-  return;
+  // TODO: Make this configurable by the interceptor?
+  struct timeval timeout = {10, 0};
 
-fail:
-  delete crash;
+  event_base* base = event_get_base(crash->crash_event);
+
+  event_assign(crash->crash_event, base, crash->crash_socket_fd, EV_TIMEOUT | EV_READ,
+               crash_completed_cb, crash.get());
+  event_add(crash->crash_event, &timeout);
+  CrashQueue::for_crash(crash)->on_crash_started();
+
+  // The crash is now owned by the event loop.
+  crash.release();
 }
 
 static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int,
@@ -268,39 +348,37 @@
 }
 
 static void crash_request_cb(evutil_socket_t sockfd, short ev, void* arg) {
-  ssize_t rc;
-  Crash* crash = static_cast<Crash*>(arg);
-
+  std::unique_ptr<Crash> crash(static_cast<Crash*>(arg));
   TombstonedCrashPacket request = {};
 
   if ((ev & EV_TIMEOUT) != 0) {
     LOG(WARNING) << "crash request timed out";
-    goto fail;
+    return;
   } else if ((ev & EV_READ) == 0) {
     LOG(WARNING) << "tombstoned received unexpected event from crash socket";
-    goto fail;
+    return;
   }
 
-  rc = TEMP_FAILURE_RETRY(read(sockfd, &request, sizeof(request)));
+  ssize_t rc = TEMP_FAILURE_RETRY(read(sockfd, &request, sizeof(request)));
   if (rc == -1) {
     PLOG(WARNING) << "failed to read from crash socket";
-    goto fail;
+    return;
   } else if (rc != sizeof(request)) {
     LOG(WARNING) << "crash socket received short read of length " << rc << " (expected "
                  << sizeof(request) << ")";
-    goto fail;
+    return;
   }
 
   if (request.packet_type != CrashPacketType::kDumpRequest) {
     LOG(WARNING) << "unexpected crash packet type, expected kDumpRequest, received  "
                  << StringPrintf("%#2hhX", request.packet_type);
-    goto fail;
+    return;
   }
 
   crash->crash_type = request.packet.dump_request.dump_type;
-  if (crash->crash_type < 0 || crash->crash_type > kDebuggerdAnyIntercept) {
+  if (crash->crash_type < 0 || crash->crash_type > kDebuggerdTombstoneProto) {
     LOG(WARNING) << "unexpected crash dump type: " << crash->crash_type;
-    goto fail;
+    return;
   }
 
   if (crash->crash_type != kDebuggerdJavaBacktrace) {
@@ -314,90 +392,117 @@
     int ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
     if (ret != 0) {
       PLOG(ERROR) << "Failed to getsockopt(..SO_PEERCRED)";
-      goto fail;
+      return;
     }
 
     crash->crash_pid = cr.pid;
   }
 
-  LOG(INFO) << "received crash request for pid " << crash->crash_pid;
+  pid_t crash_pid = crash->crash_pid;
+  LOG(INFO) << "received crash request for pid " << crash_pid;
 
-  if (CrashQueue::for_crash(crash)->maybe_enqueue_crash(crash)) {
-    LOG(INFO) << "enqueueing crash request for pid " << crash->crash_pid;
+  if (CrashQueue::for_crash(crash)->maybe_enqueue_crash(std::move(crash))) {
+    LOG(INFO) << "enqueueing crash request for pid " << crash_pid;
   } else {
-    perform_request(crash);
+    perform_request(std::move(crash));
   }
-
-  return;
-
-fail:
-  delete crash;
 }
 
-static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg) {
-  ssize_t rc;
-  Crash* crash = static_cast<Crash*>(arg);
-  TombstonedCrashPacket request = {};
+static bool link_fd(borrowed_fd fd, borrowed_fd dirfd, const std::string& path) {
+  std::string fd_path = StringPrintf("/proc/self/fd/%d", fd.get());
 
-  CrashQueue::for_crash(crash)->on_crash_completed();
-
-  if ((ev & EV_READ) == 0) {
-    goto fail;
+  int rc = linkat(AT_FDCWD, fd_path.c_str(), dirfd.get(), path.c_str(), AT_SYMLINK_FOLLOW);
+  if (rc != 0) {
+    PLOG(ERROR) << "failed to link file descriptor";
+    return false;
   }
+  return true;
+}
 
-  rc = TEMP_FAILURE_RETRY(read(sockfd, &request, sizeof(request)));
+static void crash_completed(borrowed_fd sockfd, std::unique_ptr<Crash> crash) {
+  TombstonedCrashPacket request = {};
+  CrashQueue* queue = CrashQueue::for_crash(crash);
+
+  ssize_t rc = TEMP_FAILURE_RETRY(read(sockfd.get(), &request, sizeof(request)));
   if (rc == -1) {
     PLOG(WARNING) << "failed to read from crash socket";
-    goto fail;
+    return;
   } else if (rc != sizeof(request)) {
     LOG(WARNING) << "crash socket received short read of length " << rc << " (expected "
                  << sizeof(request) << ")";
-    goto fail;
+    return;
   }
 
   if (request.packet_type != CrashPacketType::kCompletedDump) {
     LOG(WARNING) << "unexpected crash packet type, expected kCompletedDump, received "
                  << uint32_t(request.packet_type);
-    goto fail;
+    return;
   }
 
-  if (crash->crash_tombstone_fd != -1) {
-    std::string fd_path = StringPrintf("/proc/self/fd/%d", crash->crash_tombstone_fd.get());
-    std::string tombstone_path = CrashQueue::for_crash(crash)->get_next_artifact_path();
+  if (crash->output.text.fd == -1) {
+    LOG(WARNING) << "missing output fd";
+    return;
+  }
 
-    // linkat doesn't let us replace a file, so we need to unlink first.
-    int rc = unlink(tombstone_path.c_str());
-    if (rc != 0 && errno != ENOENT) {
-      PLOG(ERROR) << "failed to unlink tombstone at " << tombstone_path;
-      goto fail;
-    }
+  CrashArtifactPaths paths = queue->get_next_artifact_paths();
 
-    rc = linkat(AT_FDCWD, fd_path.c_str(), AT_FDCWD, tombstone_path.c_str(), AT_SYMLINK_FOLLOW);
-    if (rc != 0) {
-      PLOG(ERROR) << "failed to link tombstone";
+  // Always try to unlink the tombstone file.
+  // linkat doesn't let us replace a file, so we need to unlink before linking
+  // our results onto disk, and if we fail for some reason, we should delete
+  // stale tombstones to avoid confusing inconsistency.
+  rc = unlinkat(queue->dir_fd().get(), paths.text.c_str(), 0);
+  if (rc != 0 && errno != ENOENT) {
+    PLOG(ERROR) << "failed to unlink tombstone at " << paths.text;
+    return;
+  }
+
+  if (crash->output.text.fd != -1) {
+    if (!link_fd(crash->output.text.fd, queue->dir_fd(), paths.text)) {
+      LOG(ERROR) << "failed to link tombstone";
     } else {
       if (crash->crash_type == kDebuggerdJavaBacktrace) {
-        LOG(ERROR) << "Traces for pid " << crash->crash_pid << " written to: " << tombstone_path;
+        LOG(ERROR) << "Traces for pid " << crash->crash_pid << " written to: " << paths.text;
       } else {
         // NOTE: Several tools parse this log message to figure out where the
         // tombstone associated with a given native crash was written. Any changes
         // to this message must be carefully considered.
-        LOG(ERROR) << "Tombstone written to: " << tombstone_path;
-      }
-    }
-
-    // If we don't have O_TMPFILE, we need to clean up after ourselves.
-    if (!crash->crash_tombstone_path.empty()) {
-      rc = unlink(crash->crash_tombstone_path.c_str());
-      if (rc != 0) {
-        PLOG(ERROR) << "failed to unlink temporary tombstone at " << crash->crash_tombstone_path;
+        LOG(ERROR) << "Tombstone written to: " << paths.text;
       }
     }
   }
 
-fail:
+  if (crash->output.proto && crash->output.proto->fd != -1) {
+    if (!paths.proto) {
+      LOG(ERROR) << "missing path for proto tombstone";
+    } else if (!link_fd(crash->output.proto->fd, queue->dir_fd(), *paths.proto)) {
+      LOG(ERROR) << "failed to link proto tombstone";
+    }
+  }
+
+  // If we don't have O_TMPFILE, we need to clean up after ourselves.
+  if (crash->output.text.temporary_path) {
+    rc = unlinkat(queue->dir_fd().get(), crash->output.text.temporary_path->c_str(), 0);
+    if (rc != 0) {
+      PLOG(ERROR) << "failed to unlink temporary tombstone at " << paths.text;
+    }
+  }
+  if (crash->output.proto && crash->output.proto->temporary_path) {
+    rc = unlinkat(queue->dir_fd().get(), crash->output.proto->temporary_path->c_str(), 0);
+    if (rc != 0) {
+      PLOG(ERROR) << "failed to unlink temporary proto tombstone";
+    }
+  }
+}
+
+static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg) {
+  std::unique_ptr<Crash> crash(static_cast<Crash*>(arg));
   CrashQueue* queue = CrashQueue::for_crash(crash);
-  delete crash;
+
+  queue->on_crash_completed();
+
+  if ((ev & EV_READ) == EV_READ) {
+    crash_completed(sockfd, std::move(crash));
+  }
 
   // If there's something queued up, let them proceed.
   queue->maybe_dequeue_crashes(perform_request);
diff --git a/debuggerd/tombstoned/tombstoned_client.cpp b/debuggerd/tombstoned/tombstoned_client.cpp
index 2c23c98..abfafb1 100644
--- a/debuggerd/tombstoned/tombstoned_client.cpp
+++ b/debuggerd/tombstoned/tombstoned_client.cpp
@@ -32,8 +32,13 @@
 using android::base::ReceiveFileDescriptors;
 using android::base::unique_fd;
 
-bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd,
+bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* text_output_fd,
                         DebuggerdDumpType dump_type) {
+  return tombstoned_connect(pid, tombstoned_socket, text_output_fd, nullptr, dump_type);
+}
+
+bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* text_output_fd,
+                        unique_fd* proto_output_fd, DebuggerdDumpType dump_type) {
   unique_fd sockfd(
       socket_local_client((dump_type != kDebuggerdJavaBacktrace ? kTombstonedCrashSocketName
                                                                 : kTombstonedJavaTraceSocketName),
@@ -54,8 +59,15 @@
     return false;
   }
 
-  unique_fd tmp_output_fd;
-  ssize_t rc = ReceiveFileDescriptors(sockfd, &packet, sizeof(packet), &tmp_output_fd);
+  unique_fd tmp_output_fd, tmp_proto_fd;
+  ssize_t rc = -1;
+
+  if (dump_type == kDebuggerdTombstoneProto) {
+    rc = ReceiveFileDescriptors(sockfd, &packet, sizeof(packet), &tmp_output_fd, &tmp_proto_fd);
+  } else {
+    rc = ReceiveFileDescriptors(sockfd, &packet, sizeof(packet), &tmp_output_fd);
+  }
+
   if (rc == -1) {
     async_safe_format_log(ANDROID_LOG_ERROR, "libc",
                           "failed to read response to DumpRequest packet: %s", strerror(errno));
@@ -78,7 +90,10 @@
   }
 
   *tombstoned_socket = std::move(sockfd);
-  *output_fd = std::move(tmp_output_fd);
+  *text_output_fd = std::move(tmp_output_fd);
+  if (proto_output_fd) {
+    *proto_output_fd = std::move(tmp_proto_fd);
+  }
   return true;
 }
 
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 0addba3..7fa23db 100644
--- a/fs_mgr/libsnapshot/cow_snapuserd_test.cpp
+++ b/fs_mgr/libsnapshot/cow_snapuserd_test.cpp
@@ -98,6 +98,7 @@
     void ValidateMerge();
     void ReadSnapshotDeviceAndValidate();
     void Shutdown();
+    void MergeInterrupt();
 
     std::string snapshot_dev() const { return snapshot_dev_->path(); }
 
@@ -105,7 +106,11 @@
 
   private:
     void SetupImpl();
+
     void MergeImpl();
+    void SimulateDaemonRestart();
+    void StartMerge();
+
     void CreateCowDevice();
     void CreateBaseDevice();
     void InitCowDevice();
@@ -130,7 +135,7 @@
     std::unique_ptr<uint8_t[]> merged_buffer_;
     bool setup_ok_ = false;
     bool merge_ok_ = false;
-    size_t size_ = 1_MiB;
+    size_t size_ = 50_MiB;
     int cow_num_sectors_;
     int total_base_size_;
 };
@@ -154,9 +159,13 @@
 }
 
 void CowSnapuserdTest::Shutdown() {
-    ASSERT_TRUE(client_->StopSnapuserd());
     ASSERT_TRUE(snapshot_dev_->Destroy());
     ASSERT_TRUE(dmuser_dev_->Destroy());
+
+    auto misc_device = "/dev/dm-user/" + system_device_ctrl_name_;
+    ASSERT_TRUE(client_->WaitForDeviceDelete(system_device_ctrl_name_));
+    ASSERT_TRUE(android::fs_mgr::WaitForFileDeleted(misc_device, 10s));
+    ASSERT_TRUE(client_->DetachSnapuserd());
 }
 
 bool CowSnapuserdTest::Setup() {
@@ -367,7 +376,7 @@
     return merge_ok_;
 }
 
-void CowSnapuserdTest::MergeImpl() {
+void CowSnapuserdTest::StartMerge() {
     DmTable merge_table;
     ASSERT_TRUE(merge_table.AddTarget(std::make_unique<DmTargetSnapshot>(
             0, total_base_size_ / kSectorSize, base_loop_->device(), dmuser_dev_->path(),
@@ -377,6 +386,11 @@
 
     DeviceMapper& dm = DeviceMapper::Instance();
     ASSERT_TRUE(dm.LoadTableAndActivate("cowsnapuserd-test-dm-snapshot", merge_table));
+}
+
+void CowSnapuserdTest::MergeImpl() {
+    StartMerge();
+    DeviceMapper& dm = DeviceMapper::Instance();
 
     while (true) {
         vector<DeviceMapper::TargetInfo> status;
@@ -405,6 +419,44 @@
     ASSERT_EQ(memcmp(merged_buffer_.get(), orig_buffer_.get(), total_base_size_), 0);
 }
 
+void CowSnapuserdTest::SimulateDaemonRestart() {
+    Shutdown();
+    SetDeviceControlName();
+    StartSnapuserdDaemon();
+    InitCowDevice();
+    CreateDmUserDevice();
+    InitDaemon();
+    CreateSnapshotDevice();
+}
+
+void CowSnapuserdTest::MergeInterrupt() {
+    StartMerge();
+    std::this_thread::sleep_for(4s);
+    SimulateDaemonRestart();
+
+    StartMerge();
+    std::this_thread::sleep_for(3s);
+    SimulateDaemonRestart();
+
+    StartMerge();
+    std::this_thread::sleep_for(3s);
+    SimulateDaemonRestart();
+
+    StartMerge();
+    std::this_thread::sleep_for(1s);
+    SimulateDaemonRestart();
+
+    ASSERT_TRUE(Merge());
+}
+
+TEST(Snapuserd_Test, Snapshot_Merge_Resume) {
+    CowSnapuserdTest harness;
+    ASSERT_TRUE(harness.Setup());
+    harness.MergeInterrupt();
+    harness.ValidateMerge();
+    harness.Shutdown();
+}
+
 TEST(Snapuserd_Test, Snapshot) {
     CowSnapuserdTest harness;
     ASSERT_TRUE(harness.Setup());
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 397ff2e..d2ffaa7 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -441,7 +441,7 @@
     //
     // All sizes are specified in bytes, and the device, snapshot, COW partition and COW file sizes
     // must be a multiple of the sector size (512 bytes).
-    bool CreateSnapshot(LockedFile* lock, SnapshotStatus* status);
+    bool CreateSnapshot(LockedFile* lock, PartitionCowCreator* cow_creator, SnapshotStatus* status);
 
     // |name| should be the base partition name (e.g. "system_a"). Create the
     // backing COW image using the size previously passed to CreateSnapshot().
@@ -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..9329725 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);
@@ -308,7 +312,8 @@
     return WriteUpdateState(lock.get(), UpdateState::Unverified);
 }
 
-bool SnapshotManager::CreateSnapshot(LockedFile* lock, SnapshotStatus* status) {
+bool SnapshotManager::CreateSnapshot(LockedFile* lock, PartitionCowCreator* cow_creator,
+                                     SnapshotStatus* status) {
     CHECK(lock);
     CHECK(lock->lock_mode() == LOCK_EX);
     CHECK(status);
@@ -349,7 +354,7 @@
     status->set_state(SnapshotState::CREATED);
     status->set_sectors_allocated(0);
     status->set_metadata_sectors(0);
-    status->set_compression_enabled(IsCompressionEnabled());
+    status->set_compression_enabled(cow_creator->compression_enabled);
 
     if (!WriteSnapshotStatus(lock, *status)) {
         PLOG(ERROR) << "Could not write snapshot status: " << status->name();
@@ -465,8 +470,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 +484,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 +495,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 +540,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 +578,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 +684,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 +704,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 +720,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 +772,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 +790,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 +930,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 +953,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 +968,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 +986,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 +1008,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 +1031,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 +1054,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 +1062,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 +1072,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 +1116,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 +1160,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 +1199,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 +1233,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 +1258,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 +1272,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 +1281,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 +1394,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 +1422,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 +1433,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 +1578,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 +1612,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 +1626,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 +1942,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 +2014,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;
@@ -2093,10 +2130,6 @@
 bool SnapshotManager::UnmapDmUserDevice(const std::string& snapshot_name) {
     auto& dm = DeviceMapper::Instance();
 
-    if (!EnsureSnapuserdConnected()) {
-        return false;
-    }
-
     auto dm_user_name = GetDmUserCowName(snapshot_name);
     if (dm.GetState(dm_user_name) == DmDeviceState::INVALID) {
         return true;
@@ -2107,6 +2140,9 @@
         return false;
     }
 
+    if (!EnsureSnapuserdConnected()) {
+        return false;
+    }
     if (!snapuserd_client_->WaitForDeviceDelete(dm_user_name)) {
         LOG(ERROR) << "Failed to wait for " << dm_user_name << " control device to delete";
         return false;
@@ -2136,12 +2172,44 @@
         return false;
     }
 
-    if (!UnmapAllSnapshots(lock.get())) {
+    std::vector<std::string> snapshots;
+    if (!ListSnapshots(lock.get(), &snapshots)) {
         return false;
     }
 
-    uint32_t slot = SlotNumberForSlotSuffix(device_->GetOtherSlotSuffix());
-    return MapAllPartitions(lock.get(), device_->GetSuperDevice(slot), slot, timeout_ms);
+    const auto& opener = device_->GetPartitionOpener();
+    auto slot_suffix = device_->GetOtherSlotSuffix();
+    auto slot_number = SlotNumberForSlotSuffix(slot_suffix);
+    auto super_device = device_->GetSuperDevice(slot_number);
+    auto metadata = android::fs_mgr::ReadMetadata(opener, super_device, slot_number);
+    if (!metadata) {
+        LOG(ERROR) << "MapAllSnapshots could not read dynamic partition metadata for device: "
+                   << super_device;
+        return false;
+    }
+
+    for (const auto& snapshot : snapshots) {
+        if (!UnmapPartitionWithSnapshot(lock.get(), snapshot)) {
+            LOG(ERROR) << "MapAllSnapshots could not unmap snapshot: " << snapshot;
+            return false;
+        }
+
+        CreateLogicalPartitionParams params = {
+                .block_device = super_device,
+                .metadata = metadata.get(),
+                .partition_name = snapshot,
+                .partition_opener = &opener,
+                .timeout_ms = timeout_ms,
+        };
+        if (!MapPartitionWithSnapshot(lock.get(), std::move(params), SnapshotContext::Mount,
+                                      nullptr)) {
+            LOG(ERROR) << "MapAllSnapshots failed to map: " << snapshot;
+            return false;
+        }
+    }
+
+    LOG(INFO) << "MapAllSnapshots succeeded.";
+    return true;
 }
 
 bool SnapshotManager::UnmapAllSnapshots() {
@@ -2409,14 +2477,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;
 
@@ -2556,6 +2616,10 @@
     // these devices.
     AutoDeviceList created_devices;
 
+    bool use_compression = IsCompressionEnabled() &&
+                           manifest.dynamic_partition_metadata().vabc_enabled() &&
+                           !device_->IsRecovery();
+
     PartitionCowCreator cow_creator{
             .target_metadata = target_metadata.get(),
             .target_suffix = target_suffix,
@@ -2564,7 +2628,7 @@
             .current_suffix = current_suffix,
             .update = nullptr,
             .extra_extents = {},
-            .compression_enabled = IsCompressionEnabled(),
+            .compression_enabled = use_compression,
     };
 
     auto ret = CreateUpdateSnapshotsInternal(lock.get(), manifest, &cow_creator, &created_devices,
@@ -2588,6 +2652,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,8 +2770,17 @@
             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)) {
+        if (!CreateSnapshot(lock, cow_creator, &cow_creator_ret->snapshot_status)) {
             return Return::Error();
         }
         created_devices->EmplaceBack<AutoDeleteSnapshot>(this, lock, target_partition->name());
@@ -2802,11 +2893,6 @@
 
 bool SnapshotManager::MapUpdateSnapshot(const CreateLogicalPartitionParams& params,
                                         std::string* snapshot_path) {
-    if (IsCompressionEnabled()) {
-        LOG(ERROR) << "MapUpdateSnapshot cannot be used in compression mode.";
-        return false;
-    }
-
     auto lock = LockShared();
     if (!lock) return false;
     if (!UnmapPartitionWithSnapshot(lock.get(), params.GetPartitionName())) {
@@ -2815,6 +2901,15 @@
         return false;
     }
 
+    SnapshotStatus status;
+    if (!ReadSnapshotStatus(lock.get(), params.GetPartitionName(), &status)) {
+        return false;
+    }
+    if (status.compression_enabled()) {
+        LOG(ERROR) << "Cannot use MapUpdateSnapshot with compressed snapshots";
+        return false;
+    }
+
     SnapshotPaths paths;
     if (!MapPartitionWithSnapshot(lock.get(), params, SnapshotContext::Update, &paths)) {
         return false;
@@ -3375,5 +3470,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..0b8a03a 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -41,6 +41,7 @@
 
 #include <android/snapshot/snapshot.pb.h>
 #include <libsnapshot/test_helpers.h>
+#include "partition_cow_creator.h"
 #include "utility.h"
 
 // Mock classes are not used. Header included to ensure mocked class definition aligns with the
@@ -234,7 +235,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;
         }
@@ -322,7 +324,10 @@
 
         DeltaArchiveManifest manifest;
 
-        auto group = manifest.mutable_dynamic_partition_metadata()->add_groups();
+        auto dynamic_partition_metadata = manifest.mutable_dynamic_partition_metadata();
+        dynamic_partition_metadata->set_vabc_enabled(IsCompressionEnabled());
+
+        auto group = dynamic_partition_metadata->add_groups();
         group->set_name("group");
         group->set_size(device_size * 2);
         group->add_partition_names("test_partition");
@@ -415,13 +420,16 @@
 TEST_F(SnapshotTest, CreateSnapshot) {
     ASSERT_TRUE(AcquireLock());
 
+    PartitionCowCreator cow_creator;
+    cow_creator.compression_enabled = IsCompressionEnabled();
+
     static const uint64_t kDeviceSize = 1024 * 1024;
     SnapshotStatus status;
     status.set_name("test-snapshot");
     status.set_device_size(kDeviceSize);
     status.set_snapshot_size(kDeviceSize);
     status.set_cow_file_size(kDeviceSize);
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &cow_creator, &status));
     ASSERT_TRUE(CreateCowImage("test-snapshot"));
 
     std::vector<std::string> snapshots;
@@ -436,6 +444,7 @@
         ASSERT_EQ(status.state(), SnapshotState::CREATED);
         ASSERT_EQ(status.device_size(), kDeviceSize);
         ASSERT_EQ(status.snapshot_size(), kDeviceSize);
+        ASSERT_EQ(status.compression_enabled(), cow_creator.compression_enabled);
     }
 
     ASSERT_TRUE(sm->UnmapSnapshot(lock_.get(), "test-snapshot"));
@@ -446,38 +455,16 @@
 TEST_F(SnapshotTest, MapSnapshot) {
     ASSERT_TRUE(AcquireLock());
 
+    PartitionCowCreator cow_creator;
+    cow_creator.compression_enabled = IsCompressionEnabled();
+
     static const uint64_t kDeviceSize = 1024 * 1024;
     SnapshotStatus status;
     status.set_name("test-snapshot");
     status.set_device_size(kDeviceSize);
     status.set_snapshot_size(kDeviceSize);
     status.set_cow_file_size(kDeviceSize);
-    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, 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(sm->CreateSnapshot(lock_.get(), &cow_creator, &status));
     ASSERT_TRUE(CreateCowImage("test-snapshot"));
 
     std::string base_device;
@@ -590,8 +577,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 +604,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 9ad4a1a..ceba8ab 100644
--- a/fs_mgr/libsnapshot/snapuserd.cpp
+++ b/fs_mgr/libsnapshot/snapuserd.cpp
@@ -96,7 +96,7 @@
 // it will be de-compressed.
 bool Snapuserd::ProcessReplaceOp(const CowOperation* cow_op) {
     if (!reader_->ReadData(*cow_op, &bufsink_)) {
-        SNAP_LOG(ERROR) << "ReadData failed for chunk: " << cow_op->new_block;
+        SNAP_LOG(ERROR) << "ProcessReplaceOp failed for block " << cow_op->new_block;
         return false;
     }
 
@@ -113,7 +113,8 @@
     // if the successive blocks are contiguous.
     if (!android::base::ReadFullyAtOffset(backing_store_fd_, buffer, BLOCK_SIZE,
                                           cow_op->source * BLOCK_SIZE)) {
-        SNAP_LOG(ERROR) << "Copy-op failed. Read from backing store at: " << cow_op->source;
+        SNAP_PLOG(ERROR) << "Copy-op failed. Read from backing store: " << backing_store_device_
+                         << "at block :" << cow_op->source;
         return false;
     }
 
@@ -160,7 +161,7 @@
                     << " Aligned sector: " << it->second;
 
     if (!ProcessCowOp(it->second)) {
-        SNAP_LOG(ERROR) << "ReadUnalignedSector: " << sector << " failed";
+        SNAP_LOG(ERROR) << "ReadUnalignedSector: " << sector << " failed of size: " << size;
         return -1;
     }
 
@@ -377,16 +378,21 @@
             CHECK(cow_de->new_chunk == 0);
             break;
         } else {
-            SNAP_LOG(ERROR) << "Error in merge operation. Found invalid metadata";
-            SNAP_LOG(ERROR) << "merged_de-old-chunk: " << merged_de->old_chunk;
-            SNAP_LOG(ERROR) << "merged_de-new-chunk: " << merged_de->new_chunk;
-            SNAP_LOG(ERROR) << "cow_de-old-chunk: " << cow_de->old_chunk;
-            SNAP_LOG(ERROR) << "cow_de-new-chunk: " << cow_de->new_chunk;
+            SNAP_LOG(ERROR) << "Error in merge operation. Found invalid metadata: "
+                            << " merged_de-old-chunk: " << merged_de->old_chunk
+                            << " merged_de-new-chunk: " << merged_de->new_chunk
+                            << " cow_de-old-chunk: " << cow_de->old_chunk
+                            << " cow_de-new-chunk: " << cow_de->new_chunk
+                            << " unmerged_exceptions: " << unmerged_exceptions
+                            << " merged_ops_cur_iter: " << merged_ops_cur_iter
+                            << " offset: " << offset;
             return -1;
         }
     }
 
     if (*copy_op) {
+        SNAP_LOG(ERROR) << "Invalid batch merge of copy ops: merged_ops_cur_iter: "
+                        << merged_ops_cur_iter;
         CHECK(merged_ops_cur_iter == 1);
     }
     return merged_ops_cur_iter;
@@ -446,7 +452,7 @@
     header.num_merge_ops += merged_ops_cur_iter;
     reader_->UpdateMergeProgress(merged_ops_cur_iter);
     if (!writer_->CommitMerge(merged_ops_cur_iter, copy_op)) {
-        SNAP_LOG(ERROR) << "CommitMerge failed...";
+        SNAP_LOG(ERROR) << "CommitMerge failed... merged_ops_cur_iter: " << merged_ops_cur_iter;
         return false;
     }
 
@@ -661,7 +667,7 @@
 bool Snapuserd::WriteDmUserPayload(size_t size) {
     if (!android::base::WriteFully(ctrl_fd_, bufsink_.GetBufPtr(),
                                    sizeof(struct dm_user_header) + size)) {
-        SNAP_PLOG(ERROR) << "Write to dm-user failed";
+        SNAP_PLOG(ERROR) << "Write to dm-user failed size: " << size;
         return false;
     }
 
@@ -670,7 +676,7 @@
 
 bool Snapuserd::ReadDmUserPayload(void* buffer, size_t size) {
     if (!android::base::ReadFully(ctrl_fd_, buffer, size)) {
-        SNAP_PLOG(ERROR) << "ReadDmUserPayload failed";
+        SNAP_PLOG(ERROR) << "ReadDmUserPayload failed size: " << size;
         return false;
     }
 
@@ -808,7 +814,8 @@
                 ret = ReadData(sector + num_sectors_read, read_size);
                 if (ret < 0) {
                     SNAP_LOG(ERROR) << "ReadData failed for chunk id: " << chunk
-                                    << "Sector: " << header->sector;
+                                    << " Sector: " << (sector + num_sectors_read)
+                                    << " size: " << read_size << " header-len: " << header->len;
                     header->type = DM_USER_RESP_ERROR;
                 } else {
                     SNAP_LOG(DEBUG) << "ReadData success for chunk id: " << chunk
diff --git a/fs_mgr/libsnapshot/update_engine/update_metadata.proto b/fs_mgr/libsnapshot/update_engine/update_metadata.proto
index dda214e..4a97f81 100644
--- a/fs_mgr/libsnapshot/update_engine/update_metadata.proto
+++ b/fs_mgr/libsnapshot/update_engine/update_metadata.proto
@@ -73,6 +73,7 @@
 
 message DynamicPartitionMetadata {
     repeated DynamicPartitionGroup groups = 1;
+    optional bool vabc_enabled = 3;
 }
 
 message DeltaArchiveManifest {
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 c882e51..a299b6e 100644
--- a/fs_mgr/libvbmeta/Android.bp
+++ b/fs_mgr/libvbmeta/Android.bp
@@ -53,4 +53,8 @@
     data: [
         "data/*",
     ],
-}
\ No newline at end of file
+    // 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/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/first_stage_init.cpp b/init/first_stage_init.cpp
index 6954c03..f01a6c0 100644
--- a/init/first_stage_init.cpp
+++ b/init/first_stage_init.cpp
@@ -286,7 +286,11 @@
         }
     }
 
+
     if (want_console == FirstStageConsoleParam::CONSOLE_ON_FAILURE) {
+        if (!DoCreateDevices()) {
+            LOG(ERROR) << "Failed to create device nodes early";
+        }
         StartConsole(cmdline);
     }
 
@@ -327,7 +331,7 @@
         }
     }
 
-    if (!DoFirstStageMount()) {
+    if (!DoFirstStageMount(want_console != FirstStageConsoleParam::CONSOLE_ON_FAILURE)) {
         LOG(FATAL) << "Failed to mount required partitions early ...";
     }
 
diff --git a/init/first_stage_mount.cpp b/init/first_stage_mount.cpp
index 7c46281..de72f23 100644
--- a/init/first_stage_mount.cpp
+++ b/init/first_stage_mount.cpp
@@ -82,6 +82,7 @@
     // The factory method to create either FirstStageMountVBootV1 or FirstStageMountVBootV2
     // based on device tree configurations.
     static std::unique_ptr<FirstStageMount> Create();
+    bool DoCreateDevices();    // Creates devices and logical partitions from storage devices
     bool DoFirstStageMount();  // Mounts fstab entries read from device tree.
     bool InitDevices();
 
@@ -244,6 +245,28 @@
     }
 }
 
+bool FirstStageMount::DoCreateDevices() {
+    if (!InitDevices()) return false;
+
+    // Mount /metadata before creating logical partitions, since we need to
+    // know whether a snapshot merge is in progress.
+    auto metadata_partition = std::find_if(fstab_.begin(), fstab_.end(), [](const auto& entry) {
+        return entry.mount_point == "/metadata";
+    });
+    if (metadata_partition != fstab_.end()) {
+        if (MountPartition(metadata_partition, true /* erase_same_mounts */)) {
+            // Copies DSU AVB keys from the ramdisk to /metadata.
+            // Must be done before the following TrySwitchSystemAsRoot().
+            // Otherwise, ramdisk will be inaccessible after switching root.
+            CopyDsuAvbKeys();
+        }
+    }
+
+    if (!CreateLogicalPartitions()) return false;
+
+    return true;
+}
+
 bool FirstStageMount::DoFirstStageMount() {
     if (!IsDmLinearEnabled() && fstab_.empty()) {
         // Nothing to mount.
@@ -251,8 +274,6 @@
         return true;
     }
 
-    if (!InitDevices()) return false;
-
     if (!MountPartitions()) return false;
 
     return true;
@@ -505,22 +526,6 @@
 }
 
 bool FirstStageMount::MountPartitions() {
-    // Mount /metadata before creating logical partitions, since we need to
-    // know whether a snapshot merge is in progress.
-    auto metadata_partition = std::find_if(fstab_.begin(), fstab_.end(), [](const auto& entry) {
-        return entry.mount_point == "/metadata";
-    });
-    if (metadata_partition != fstab_.end()) {
-        if (MountPartition(metadata_partition, true /* erase_same_mounts */)) {
-            // Copies DSU AVB keys from the ramdisk to /metadata.
-            // Must be done before the following TrySwitchSystemAsRoot().
-            // Otherwise, ramdisk will be inaccessible after switching root.
-            CopyDsuAvbKeys();
-        }
-    }
-
-    if (!CreateLogicalPartitions()) return false;
-
     if (!TrySwitchSystemAsRoot()) return false;
 
     if (!SkipMountingPartitions(&fstab_)) return false;
@@ -829,8 +834,18 @@
 
 // Public functions
 // ----------------
+// Creates devices and logical partitions from storage devices
+bool DoCreateDevices() {
+    std::unique_ptr<FirstStageMount> handle = FirstStageMount::Create();
+    if (!handle) {
+        LOG(ERROR) << "Failed to create FirstStageMount";
+        return false;
+    }
+    return handle->DoCreateDevices();
+}
+
 // Mounts partitions specified by fstab in device tree.
-bool DoFirstStageMount() {
+bool DoFirstStageMount(bool create_devices) {
     // Skips first stage mount if we're in recovery mode.
     if (IsRecoveryMode()) {
         LOG(INFO) << "First stage mount skipped (recovery mode)";
@@ -842,6 +857,11 @@
         LOG(ERROR) << "Failed to create FirstStageMount";
         return false;
     }
+
+    if (create_devices) {
+        if (!handle->DoCreateDevices()) return false;
+    }
+
     return handle->DoFirstStageMount();
 }
 
diff --git a/init/first_stage_mount.h b/init/first_stage_mount.h
index 21d87fd..2f4e663 100644
--- a/init/first_stage_mount.h
+++ b/init/first_stage_mount.h
@@ -19,7 +19,8 @@
 namespace android {
 namespace init {
 
-bool DoFirstStageMount();
+bool DoCreateDevices();
+bool DoFirstStageMount(bool create_devices);
 void SetInitAvbVersionInRecovery();
 
 }  // namespace init
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,
+};