Merge changes Id9263be8,Idd9a60b0 into main

* changes:
  snapuserd: Remove legacy dm-snapshot based snapshot and snapshot-merge
  libsnapshot: Prepare removal of legacy snapshot
diff --git a/debuggerd/crash_dump.cpp b/debuggerd/crash_dump.cpp
index a23a269..203b485 100644
--- a/debuggerd/crash_dump.cpp
+++ b/debuggerd/crash_dump.cpp
@@ -143,7 +143,7 @@
 }
 
 static bool activity_manager_notify(pid_t pid, int signal, const std::string& amfd_data,
-                                    bool recoverable_gwp_asan_crash) {
+                                    bool recoverable_crash) {
   ATRACE_CALL();
   android::base::unique_fd amfd(socket_local_client(
       "/data/system/ndebugsocket", ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM));
@@ -169,7 +169,7 @@
   // Activity Manager protocol:
   //  - 32-bit network-byte-order: pid
   //  - 32-bit network-byte-order: signal number
-  //  - byte: recoverable_gwp_asan_crash
+  //  - byte: recoverable_crash
   //  - bytes: raw text of the dump
   //  - null terminator
 
@@ -185,10 +185,9 @@
     return false;
   }
 
-  uint8_t recoverable_gwp_asan_crash_byte = recoverable_gwp_asan_crash ? 1 : 0;
-  if (!android::base::WriteFully(amfd, &recoverable_gwp_asan_crash_byte,
-                                 sizeof(recoverable_gwp_asan_crash_byte))) {
-    PLOG(ERROR) << "AM recoverable_gwp_asan_crash_byte write failed";
+  uint8_t recoverable_crash_byte = recoverable_crash ? 1 : 0;
+  if (!android::base::WriteFully(amfd, &recoverable_crash_byte, sizeof(recoverable_crash_byte))) {
+    PLOG(ERROR) << "AM recoverable_crash_byte write failed";
     return false;
   }
 
@@ -280,11 +279,11 @@
 
 static void ReadCrashInfo(unique_fd& fd, siginfo_t* siginfo,
                           std::unique_ptr<unwindstack::Regs>* regs, ProcessInfo* process_info,
-                          bool* recoverable_gwp_asan_crash) {
+                          bool* recoverable_crash) {
   std::aligned_storage<sizeof(CrashInfo) + 1, alignof(CrashInfo)>::type buf;
   CrashInfo* crash_info = reinterpret_cast<CrashInfo*>(&buf);
   ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &buf, sizeof(buf)));
-  *recoverable_gwp_asan_crash = false;
+  *recoverable_crash = false;
   if (rc == -1) {
     PLOG(FATAL) << "failed to read target ucontext";
   } else {
@@ -321,7 +320,7 @@
       process_info->scudo_region_info = crash_info->data.d.scudo_region_info;
       process_info->scudo_ring_buffer = crash_info->data.d.scudo_ring_buffer;
       process_info->scudo_ring_buffer_size = crash_info->data.d.scudo_ring_buffer_size;
-      *recoverable_gwp_asan_crash = crash_info->data.d.recoverable_gwp_asan_crash;
+      *recoverable_crash = crash_info->data.d.recoverable_crash;
       process_info->crash_detail_page = crash_info->data.d.crash_detail_page;
       FALLTHROUGH_INTENDED;
     case 1:
@@ -487,7 +486,7 @@
   std::map<pid_t, ThreadInfo> thread_info;
   siginfo_t siginfo;
   std::string error;
-  bool recoverable_gwp_asan_crash = false;
+  bool recoverable_crash = false;
 
   {
     ATRACE_NAME("ptrace");
@@ -539,8 +538,7 @@
 
       if (thread == g_target_thread) {
         // Read the thread's registers along with the rest of the crash info out of the pipe.
-        ReadCrashInfo(input_pipe, &siginfo, &info.registers, &process_info,
-                      &recoverable_gwp_asan_crash);
+        ReadCrashInfo(input_pipe, &siginfo, &info.registers, &process_info, &recoverable_crash);
         info.siginfo = &siginfo;
         info.signo = info.siginfo->si_signo;
 
@@ -670,7 +668,7 @@
   if (fatal_signal) {
     // Don't try to notify ActivityManager if it just crashed, or we might hang until timeout.
     if (thread_info[target_process].thread_name != "system_server") {
-      activity_manager_notify(target_process, signo, amfd_data, recoverable_gwp_asan_crash);
+      activity_manager_notify(target_process, signo, amfd_data, recoverable_crash);
     }
   }
 
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 141723b..25031bf 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -275,10 +275,6 @@
   }
 }
 
-static pid_t __fork() {
-  return clone(nullptr, nullptr, 0, nullptr);
-}
-
 // Double-clone, with CLONE_FILES to share the file descriptor table for kcmp validation.
 // Returns 0 in the orphaned child, the pid of the orphan in the original process, or -1 on failure.
 static void create_vm_process() {
@@ -396,7 +392,7 @@
     ASSERT_SAME_OFFSET(scudo_ring_buffer, scudo_ring_buffer);
     ASSERT_SAME_OFFSET(scudo_ring_buffer_size, scudo_ring_buffer_size);
     ASSERT_SAME_OFFSET(scudo_stack_depot_size, scudo_stack_depot_size);
-    ASSERT_SAME_OFFSET(recoverable_gwp_asan_crash, recoverable_gwp_asan_crash);
+    ASSERT_SAME_OFFSET(recoverable_crash, recoverable_crash);
     ASSERT_SAME_OFFSET(crash_detail_page, crash_detail_page);
 #undef ASSERT_SAME_OFFSET
 
@@ -426,7 +422,7 @@
   }
 
   // Don't use fork(2) to avoid calling pthread_atfork handlers.
-  pid_t crash_dump_pid = __fork();
+  pid_t crash_dump_pid = _Fork();
   if (crash_dump_pid == -1) {
     async_safe_format_log(ANDROID_LOG_FATAL, "libc",
                           "failed to fork in debuggerd signal handler: %s", strerror(errno));
@@ -573,6 +569,7 @@
   }
 
   gwp_asan_callbacks_t gwp_asan_callbacks = {};
+  bool recoverable_gwp_asan_crash = false;
   if (g_callbacks.get_gwp_asan_callbacks != nullptr) {
     // GWP-ASan catches use-after-free and heap-buffer-overflow by using PROT_NONE
     // guard pages, which lead to SEGV. Normally, debuggerd prints a bug report
@@ -587,10 +584,30 @@
         gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report &&
         gwp_asan_callbacks.debuggerd_needs_gwp_asan_recovery(info->si_addr)) {
       gwp_asan_callbacks.debuggerd_gwp_asan_pre_crash_report(info->si_addr);
-      process_info.recoverable_gwp_asan_crash = true;
+      recoverable_gwp_asan_crash = true;
+      process_info.recoverable_crash = true;
     }
   }
 
+  if (info->si_signo == SIGSEGV &&
+      (info->si_code == SEGV_MTESERR || info->si_code == SEGV_MTEAERR) && is_permissive_mte()) {
+    process_info.recoverable_crash = true;
+    // If we are in permissive MTE mode, we do not crash, but instead disable MTE on this thread,
+    // and then let the failing instruction be retried. The second time should work (except
+    // if there is another non-MTE fault).
+    int tagged_addr_ctrl = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
+    if (tagged_addr_ctrl < 0) {
+      fatal_errno("failed to PR_GET_TAGGED_ADDR_CTRL");
+    }
+    tagged_addr_ctrl = (tagged_addr_ctrl & ~PR_MTE_TCF_MASK) | PR_MTE_TCF_NONE;
+    if (prctl(PR_SET_TAGGED_ADDR_CTRL, tagged_addr_ctrl, 0, 0, 0) < 0) {
+      fatal_errno("failed to PR_SET_TAGGED_ADDR_CTRL");
+    }
+    async_safe_format_log(ANDROID_LOG_ERROR, "libc",
+                          "MTE ERROR DETECTED BUT RUNNING IN PERMISSIVE MODE. CONTINUING.");
+    pthread_mutex_unlock(&crash_mutex);
+  }
+
   // If sival_int is ~0, it means that the fallback handler has been called
   // once before and this function is being called again to dump the stack
   // of a specific thread. It is possible that the prctl call might return 1,
@@ -602,7 +619,7 @@
     // you can only set NO_NEW_PRIVS to 1, and the effect should be at worst a single missing
     // ANR trace.
     debuggerd_fallback_handler(info, ucontext, process_info.abort_msg);
-    if (no_new_privs && process_info.recoverable_gwp_asan_crash) {
+    if (no_new_privs && recoverable_gwp_asan_crash) {
       gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report(info->si_addr);
       return;
     }
@@ -679,29 +696,14 @@
     // If the signal is fatal, don't unlock the mutex to prevent other crashing threads from
     // starting to dump right before our death.
     pthread_mutex_unlock(&crash_mutex);
-  } else if (process_info.recoverable_gwp_asan_crash) {
-    gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report(info->si_addr);
+  } else if (process_info.recoverable_crash) {
+    if (recoverable_gwp_asan_crash) {
+      gwp_asan_callbacks.debuggerd_gwp_asan_post_crash_report(info->si_addr);
+    }
     pthread_mutex_unlock(&crash_mutex);
   }
 #ifdef __aarch64__
-  else if (info->si_signo == SIGSEGV &&
-           (info->si_code == SEGV_MTESERR || info->si_code == SEGV_MTEAERR) &&
-           is_permissive_mte()) {
-    // If we are in permissive MTE mode, we do not crash, but instead disable MTE on this thread,
-    // and then let the failing instruction be retried. The second time should work (except
-    // if there is another non-MTE fault).
-    int tagged_addr_ctrl = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
-    if (tagged_addr_ctrl < 0) {
-      fatal_errno("failed to PR_GET_TAGGED_ADDR_CTRL");
-    }
-    tagged_addr_ctrl = (tagged_addr_ctrl & ~PR_MTE_TCF_MASK) | PR_MTE_TCF_NONE;
-    if (prctl(PR_SET_TAGGED_ADDR_CTRL, tagged_addr_ctrl, 0, 0, 0) < 0) {
-      fatal_errno("failed to PR_SET_TAGGED_ADDR_CTRL");
-    }
-    async_safe_format_log(ANDROID_LOG_ERROR, "libc",
-                          "MTE ERROR DETECTED BUT RUNNING IN PERMISSIVE MODE. CONTINUING.");
-    pthread_mutex_unlock(&crash_mutex);
-  } else if (info->si_signo == SIGSEGV && info->si_code == SEGV_MTEAERR && getppid() == 1) {
+  else if (info->si_signo == SIGSEGV && info->si_code == SEGV_MTEAERR && getppid() == 1) {
     // Back channel to init (see system/core/init/service.cpp) to signal that
     // this process crashed due to an ASYNC MTE fault and should be considered
     // for upgrade to SYNC mode. We are re-using the ART profiler signal, which
@@ -761,18 +763,7 @@
   debuggerd_register_handlers(&action);
 }
 
-// When debuggerd's signal handler is the first handler called, it's great at
-// handling the recoverable GWP-ASan mode. For apps, sigchain (from libart) is
-// always the first signal handler, and so the following function is what
-// sigchain must call before processing the signal. This allows for processing
-// of a potentially recoverable GWP-ASan crash. If the signal requires GWP-ASan
-// recovery, then dump a report (via the regular debuggerd hanndler), and patch
-// up the allocator, and allow the process to continue (indicated by returning
-// 'true'). If the crash has nothing to do with GWP-ASan, or recovery isn't
-// possible, return 'false'.
-bool debuggerd_handle_signal(int signal_number, siginfo_t* info, void* context) {
-  if (signal_number != SIGSEGV || !signal_has_si_addr(info)) return false;
-
+bool debuggerd_handle_gwp_asan_signal(int signal_number, siginfo_t* info, void* context) {
   if (g_callbacks.get_gwp_asan_callbacks == nullptr) return false;
   gwp_asan_callbacks_t gwp_asan_callbacks = g_callbacks.get_gwp_asan_callbacks();
   if (gwp_asan_callbacks.debuggerd_needs_gwp_asan_recovery == nullptr ||
@@ -810,3 +801,33 @@
   pthread_mutex_unlock(&first_crash_mutex);
   return true;
 }
+
+// When debuggerd's signal handler is the first handler called, it's great at
+// handling the recoverable GWP-ASan and permissive MTE modes. For apps,
+// sigchain (from libart) is always the first signal handler, and so the
+// following function is what sigchain must call before processing the signal.
+// This allows for processing of a potentially recoverable GWP-ASan or MTE
+// crash. If the signal requires recovery, then dump a report (via the regular
+// debuggerd hanndler), and patch up the allocator (in the case of GWP-ASan) or
+// disable MTE on the thread, and allow the process to continue (indicated by
+// returning 'true'). If the crash has nothing to do with GWP-ASan/MTE, or
+// recovery isn't possible, return 'false'.
+bool debuggerd_handle_signal(int signal_number, siginfo_t* info, void* context) {
+  if (signal_number != SIGSEGV) return false;
+  if (info->si_code == SEGV_MTEAERR || info->si_code == SEGV_MTESERR) {
+    if (!is_permissive_mte()) return false;
+    // Because permissive MTE disables MTE for the entire thread, we're less
+    // worried about getting a whole bunch of crashes in a row. ActivityManager
+    // doesn't like multiple native crashes for an app in a short period of time
+    // (see the comment about recoverable GWP-ASan in
+    // `debuggerd_handle_gwp_asan_signal`), but that shouldn't happen if MTE is
+    // disabled for the entire thread. This might need to be changed if there's
+    // some low-hanging bug that happens across multiple threads in quick
+    // succession.
+    debuggerd_signal_handler(signal_number, info, context);
+    return true;
+  }
+
+  if (!signal_has_si_addr(info)) return false;
+  return debuggerd_handle_gwp_asan_signal(signal_number, info, context);
+}
diff --git a/debuggerd/include/debuggerd/handler.h b/debuggerd/include/debuggerd/handler.h
index c18cf6e..954f049 100644
--- a/debuggerd/include/debuggerd/handler.h
+++ b/debuggerd/include/debuggerd/handler.h
@@ -47,7 +47,7 @@
   const char* scudo_ring_buffer;
   size_t scudo_ring_buffer_size;
   size_t scudo_stack_depot_size;
-  bool recoverable_gwp_asan_crash;
+  bool recoverable_crash;
   struct crash_detail_page_t* crash_detail_page;
 };
 
diff --git a/debuggerd/protocol.h b/debuggerd/protocol.h
index d3fc15e..9af7377 100644
--- a/debuggerd/protocol.h
+++ b/debuggerd/protocol.h
@@ -100,7 +100,7 @@
   uintptr_t scudo_ring_buffer;
   size_t scudo_ring_buffer_size;
   size_t scudo_stack_depot_size;
-  bool recoverable_gwp_asan_crash;
+  bool recoverable_crash;
   uintptr_t crash_detail_page;
 };
 
diff --git a/debuggerd/tombstoned/tombstoned.cpp b/debuggerd/tombstoned/tombstoned.cpp
index e2a67a2..fa67d46 100644
--- a/debuggerd/tombstoned/tombstoned.cpp
+++ b/debuggerd/tombstoned/tombstoned.cpp
@@ -96,7 +96,7 @@
 class CrashQueue {
  public:
   CrashQueue(const std::string& dir_path, const std::string& file_name_prefix, size_t max_artifacts,
-             size_t max_concurrent_dumps, bool supports_proto)
+             size_t max_concurrent_dumps, bool supports_proto, bool world_readable)
       : file_name_prefix_(file_name_prefix),
         dir_path_(dir_path),
         dir_fd_(open(dir_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC)),
@@ -104,7 +104,8 @@
         next_artifact_(0),
         max_concurrent_dumps_(max_concurrent_dumps),
         num_concurrent_dumps_(0),
-        supports_proto_(supports_proto) {
+        supports_proto_(supports_proto),
+        world_readable_(world_readable) {
     if (dir_fd_ == -1) {
       PLOG(FATAL) << "failed to open directory: " << dir_path;
     }
@@ -127,14 +128,16 @@
   static CrashQueue* for_tombstones() {
     static CrashQueue queue("/data/tombstones", "tombstone_" /* file_name_prefix */,
                             GetIntProperty("tombstoned.max_tombstone_count", 32),
-                            1 /* max_concurrent_dumps */, true /* supports_proto */);
+                            1 /* max_concurrent_dumps */, true /* supports_proto */,
+                            true /* world_readable */);
     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 */, false /* supports_proto */);
+                            4 /* max_concurrent_dumps */, false /* supports_proto */,
+                            false /* world_readable */);
     return &queue;
   }
 
@@ -147,10 +150,12 @@
       PLOG(FATAL) << "failed to create temporary tombstone in " << dir_path_;
     }
 
-    // We need to fchmodat after creating to avoid getting the umask applied.
-    std::string fd_path = StringPrintf("/proc/self/fd/%d", result.fd.get());
-    if (fchmodat(dir_fd_, fd_path.c_str(), 0664, 0) != 0) {
-      PLOG(ERROR) << "Failed to make tombstone world-readable";
+    if (world_readable_) {
+      // We need to fchmodat after creating to avoid getting the umask applied.
+      std::string fd_path = StringPrintf("/proc/self/fd/%d", result.fd.get());
+      if (fchmodat(dir_fd_, fd_path.c_str(), 0664, 0) != 0) {
+        PLOG(ERROR) << "Failed to make tombstone world-readable";
+      }
     }
 
     return std::move(result);
@@ -262,6 +267,7 @@
   size_t num_concurrent_dumps_;
 
   bool supports_proto_;
+  bool world_readable_;
 
   std::deque<std::unique_ptr<Crash>> queued_requests_;
 
@@ -450,6 +456,14 @@
 
   CrashArtifactPaths paths = queue->get_next_artifact_paths();
 
+  if (crash->output.proto && crash->output.proto->fd != -1) {
+    if (!paths.proto) {
+      LOG(ERROR) << "missing path for proto tombstone";
+    } else {
+      rename_tombstone_fd(crash->output.proto->fd, queue->dir_fd(), *paths.proto);
+    }
+  }
+
   if (rename_tombstone_fd(crash->output.text.fd, queue->dir_fd(), paths.text)) {
     if (crash->crash_type == kDebuggerdJavaBacktrace) {
       LOG(ERROR) << "Traces for pid " << crash->crash_pid << " written to: " << paths.text;
@@ -460,14 +474,6 @@
       LOG(ERROR) << "Tombstone written to: " << paths.text;
     }
   }
-
-  if (crash->output.proto && crash->output.proto->fd != -1) {
-    if (!paths.proto) {
-      LOG(ERROR) << "missing path for proto tombstone";
-    } else {
-      rename_tombstone_fd(crash->output.proto->fd, queue->dir_fd(), *paths.proto);
-    }
-  }
 }
 
 static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg) {
diff --git a/fs_mgr/libdm/dm.cpp b/fs_mgr/libdm/dm.cpp
index e261aa3..fee67fdf 100644
--- a/fs_mgr/libdm/dm.cpp
+++ b/fs_mgr/libdm/dm.cpp
@@ -39,6 +39,9 @@
 #ifndef DM_DEFERRED_REMOVE
 #define DM_DEFERRED_REMOVE (1 << 17)
 #endif
+#ifndef DM_IMA_MEASUREMENT_FLAG
+#define DM_IMA_MEASUREMENT_FLAG (1 << 19)
+#endif
 
 namespace android {
 namespace dm {
@@ -540,6 +543,10 @@
     return GetTable(name, 0, table);
 }
 
+bool DeviceMapper::GetTableStatusIma(const std::string& name, std::vector<TargetInfo>* table) {
+    return GetTable(name, DM_IMA_MEASUREMENT_FLAG, table);
+}
+
 bool DeviceMapper::GetTableInfo(const std::string& name, std::vector<TargetInfo>* table) {
     return GetTable(name, DM_STATUS_TABLE_FLAG, table);
 }
diff --git a/fs_mgr/libdm/include/libdm/dm.h b/fs_mgr/libdm/include/libdm/dm.h
index 22c475f..fa97653 100644
--- a/fs_mgr/libdm/include/libdm/dm.h
+++ b/fs_mgr/libdm/include/libdm/dm.h
@@ -78,6 +78,7 @@
     virtual bool LoadTable(const std::string& name, const DmTable& table) = 0;
     virtual bool GetTableInfo(const std::string& name, std::vector<TargetInfo>* table) = 0;
     virtual bool GetTableStatus(const std::string& name, std::vector<TargetInfo>* table) = 0;
+    virtual bool GetTableStatusIma(const std::string& name, std::vector<TargetInfo>* table) = 0;
     virtual bool GetDmDevicePathByName(const std::string& name, std::string* path) = 0;
     virtual bool GetDeviceString(const std::string& name, std::string* dev) = 0;
     virtual bool DeleteDeviceIfExists(const std::string& name) = 0;
@@ -267,6 +268,12 @@
     // false.
     bool GetTableStatus(const std::string& name, std::vector<TargetInfo>* table) override;
 
+    // Query the status of a table, given a device name. The output vector will
+    // contain IMA TargetInfo for each target in the table. If the device does
+    // not exist, or there were too many targets, the call will fail and return
+    // false.
+    bool GetTableStatusIma(const std::string& name, std::vector<TargetInfo>* table) override;
+
     // Identical to GetTableStatus, except also retrives the active table for the device
     // mapper device from the kernel.
     bool GetTableInfo(const std::string& name, std::vector<TargetInfo>* table) override;
diff --git a/fs_mgr/liblp/fuzzer/liblp_builder_fuzzer.cpp b/fs_mgr/liblp/fuzzer/liblp_builder_fuzzer.cpp
index 7f09ac8..162c9fc 100644
--- a/fs_mgr/liblp/fuzzer/liblp_builder_fuzzer.cpp
+++ b/fs_mgr/liblp/fuzzer/liblp_builder_fuzzer.cpp
@@ -28,7 +28,7 @@
 static constexpr uint64_t kBlockDeviceInfoSize = 1024 * 1024;
 static constexpr uint64_t kValidBlockDeviceInfoSize = 8_GiB;
 static constexpr uint64_t kValidMaxGroupSize = 40960;
-static constexpr uint64_t kMinBlockDevValue = 0;
+static constexpr uint64_t kMinBlockDevValue = 1;
 static constexpr uint64_t kMaxBlockDevValue = 100000;
 static constexpr uint64_t kMinSectorValue = 1;
 static constexpr uint64_t kMaxSectorValue = 1000000;
@@ -149,12 +149,16 @@
 
 void BuilderFuzzer::setupBuilder(string superBlockDeviceName) {
     uint64_t blockDeviceInfoSize =
-            mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint64_t>() : kValidBlockDeviceInfoSize;
+            mFdp.ConsumeBool()
+                    ? mFdp.ConsumeIntegralInRange<uint64_t>(kMinBlockDevValue, kMaxBlockDevValue)
+                    : kValidBlockDeviceInfoSize;
     uint32_t alignment = mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint32_t>() : kValidAlignment;
     uint32_t alignmentOffset =
             mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint32_t>() : kValidAlignmentOffset;
-    uint32_t logicalBlockSize =
-            mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint32_t>() : kValidLogicalBlockSize;
+    uint32_t logicalBlockSize = mFdp.ConsumeBool() ? mFdp.ConsumeIntegralInRange<uint32_t>(
+                                                             kMinBlockDevValue, kMaxBlockDevValue)
+                                                   : kValidLogicalBlockSize;
+
     BlockDeviceInfo super(superBlockDeviceName, blockDeviceInfoSize, alignment, alignmentOffset,
                           logicalBlockSize);
     mBlockDevices.push_back(super);
@@ -176,13 +180,16 @@
             mFdp.ConsumeBool() ? kDeviceInfoName : mFdp.ConsumeRandomLengthString(kMaxBytes);
     BlockDeviceInfo changePartitionDeviceInfo(
             changePartitionDeviceInfoName,
-            mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint64_t>() : kBlockDeviceInfoSize /* size */,
+            mFdp.ConsumeBool()
+                    ? mFdp.ConsumeIntegralInRange<uint64_t>(kMinBlockDevValue, kMaxBlockDevValue)
+                    : kBlockDeviceInfoSize /* size */,
             mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint32_t>()
                                : kZeroAlignmentOffset /* alignment */,
             mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint32_t>()
                                : kZeroAlignmentOffset /* alignment_offset */,
-            mFdp.ConsumeBool() ? mFdp.ConsumeIntegral<uint32_t>()
-                               : kValidLogicalBlockSize /* logical_block_size */);
+            mFdp.ConsumeBool()
+                    ? mFdp.ConsumeIntegralInRange<uint32_t>(kMinBlockDevValue, kMaxBlockDevValue)
+                    : kValidLogicalBlockSize);
     mBlockDevices.push_back(changePartitionDeviceInfo);
 }
 
diff --git a/fs_mgr/libsnapshot/include_test/libsnapshot/test_helpers.h b/fs_mgr/libsnapshot/include_test/libsnapshot/test_helpers.h
index 5e9f049..90813fe 100644
--- a/fs_mgr/libsnapshot/include_test/libsnapshot/test_helpers.h
+++ b/fs_mgr/libsnapshot/include_test/libsnapshot/test_helpers.h
@@ -155,6 +155,9 @@
     virtual bool GetTableStatus(const std::string& name, std::vector<TargetInfo>* table) {
         return impl_.GetTableStatus(name, table);
     }
+    virtual bool GetTableStatusIma(const std::string& name, std::vector<TargetInfo>* table) {
+        return impl_.GetTableStatusIma(name, table);
+    }
     virtual bool GetDmDevicePathByName(const std::string& name, std::string* path) {
         return impl_.GetDmDevicePathByName(name, path);
     }
diff --git a/fs_mgr/libsnapshot/libsnapshot_cow/test_v3.cpp b/fs_mgr/libsnapshot/libsnapshot_cow/test_v3.cpp
index 2021348..4456b26 100644
--- a/fs_mgr/libsnapshot/libsnapshot_cow/test_v3.cpp
+++ b/fs_mgr/libsnapshot/libsnapshot_cow/test_v3.cpp
@@ -209,6 +209,48 @@
     ASSERT_EQ(sink, data);
 }
 
+TEST_F(CowTestV3, BigReplaceOp) {
+    CowOptions options;
+    options.op_count_max = 10000;
+    options.batch_write = true;
+    options.cluster_ops = 2048;
+
+    auto writer = CreateCowWriter(3, options, GetCowFd());
+    std::string data = "This is some data, believe it";
+    data.resize(options.block_size * 4096, '\0');
+    for (int i = 0; i < data.size(); i++) {
+        data[i] = static_cast<char>('A' + i / options.block_size);
+    }
+    ASSERT_TRUE(writer->AddRawBlocks(5, data.data(), data.size()));
+    ASSERT_TRUE(writer->Finalize());
+
+    CowReader reader;
+    ASSERT_TRUE(reader.Parse(cow_->fd));
+
+    const auto& header = reader.header_v3();
+    ASSERT_EQ(header.op_count, 4096);
+
+    auto iter = reader.GetOpIter();
+    ASSERT_NE(iter, nullptr);
+    ASSERT_FALSE(iter->AtEnd());
+
+    size_t i = 0;
+
+    while (!iter->AtEnd()) {
+        auto op = iter->Get();
+        std::string sink(options.block_size, '\0');
+        ASSERT_EQ(op->type(), kCowReplaceOp);
+        ASSERT_EQ(op->data_length, options.block_size);
+        ASSERT_EQ(op->new_block, 5 + i);
+        ASSERT_TRUE(ReadData(reader, op, sink.data(), options.block_size));
+        ASSERT_EQ(std::string_view(sink),
+                  std::string_view(data).substr(i * options.block_size, options.block_size))
+                << " readback data for " << i << "th block does not match";
+        iter->Next();
+        i++;
+    }
+}
+
 TEST_F(CowTestV3, ConsecutiveReplaceOp) {
     CowOptions options;
     options.op_count_max = 20;
diff --git a/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.cpp b/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.cpp
index de2e528..8cc9964 100644
--- a/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.cpp
+++ b/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.cpp
@@ -173,7 +173,7 @@
         batch_size_ = std::max<size_t>(options_.cluster_ops, 1);
         data_vec_.reserve(batch_size_);
         cached_data_.reserve(batch_size_);
-        cached_ops_.reserve(batch_size_);
+        cached_ops_.reserve(batch_size_ * kNonDataOpBufferSize);
     }
 
     if (batch_size_ > 1) {
@@ -342,7 +342,8 @@
     // Allow bigger batch sizes for ops without data. A single CowOperationV3
     // struct uses 14 bytes of memory, even if we cache 200 * 16 ops in memory,
     // it's only ~44K.
-    return cached_data_.size() >= batch_size_ || cached_ops_.size() >= batch_size_ * 16;
+    return cached_data_.size() >= batch_size_ ||
+           cached_ops_.size() >= batch_size_ * kNonDataOpBufferSize;
 }
 
 bool CowWriterV3::ConstructCowOpCompressedBuffers(uint64_t new_block_start, const void* data,
@@ -716,13 +717,27 @@
         return false;
     }
     if (!data.empty()) {
-        const auto ret = pwritev(fd_, data.data(), data.size(), next_data_pos_);
-        if (ret != total_data_size) {
+        int total_written = 0;
+        int i = 0;
+        while (i < data.size()) {
+            int chunk = std::min(static_cast<int>(data.size() - i), IOV_MAX);
+
+            const auto ret = pwritev(fd_, data.data() + i, chunk, next_data_pos_ + total_written);
+            if (ret < 0) {
+                PLOG(ERROR) << "write failed chunk size of: " << chunk
+                            << " at offset: " << next_data_pos_ + total_written << " " << errno;
+                return false;
+            }
+            total_written += ret;
+            i += chunk;
+        }
+        if (total_written != total_data_size) {
             PLOG(ERROR) << "write failed for data of size: " << data.size()
-                        << " at offset: " << next_data_pos_ << " " << ret;
+                        << " at offset: " << next_data_pos_ << " " << errno;
             return false;
         }
     }
+
     header_.op_count += ops.size();
     next_data_pos_ += total_data_size;
 
diff --git a/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h b/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h
index 48eb67b..e2dc698 100644
--- a/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h
+++ b/fs_mgr/libsnapshot/libsnapshot_cow/writer_v3.h
@@ -28,6 +28,9 @@
 namespace snapshot {
 
 using namespace android::storage_literals;
+// This is a multiple on top of the number of data ops that can be stored in our cache at once. This
+// is added so that we can cache more non-data ops as it takes up less space.
+static constexpr uint32_t kNonDataOpBufferSize = 16;
 
 class CowWriterV3 : public CowWriterBase {
   public:
diff --git a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_test.cpp b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_test.cpp
index 76b44b4..d05df82 100644
--- a/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_test.cpp
+++ b/fs_mgr/libsnapshot/snapuserd/user-space-merge/snapuserd_test.cpp
@@ -126,7 +126,8 @@
 }
 
 std::unique_ptr<ICowWriter> SnapuserdTestBase::CreateCowDeviceInternal() {
-    cow_system_ = std::make_unique<TemporaryFile>();
+    std::string path = android::base::GetExecutableDirectory();
+    cow_system_ = std::make_unique<TemporaryFile>(path);
 
     CowOptions options;
     options.compression = "gz";
@@ -147,7 +148,8 @@
     options.batch_write = true;
     options.compression_factor = params.block_size;
 
-    cow_system_ = std::make_unique<TemporaryFile>();
+    std::string path = android::base::GetExecutableDirectory();
+    cow_system_ = std::make_unique<TemporaryFile>(path);
 
     unique_fd fd(cow_system_->fd);
     cow_system_->fd = -1;
@@ -989,6 +991,7 @@
 void SnapuserdVariableBlockSizeTest::CreateV3CowDeviceForVariableBlockSize() {
     auto writer = CreateV3Cow();
 
+    ASSERT_NE(writer, nullptr);
     size_t total_data_to_write = size_;
 
     size_t total_blocks_to_write = total_data_to_write / BLOCK_SZ;
@@ -1337,6 +1340,7 @@
 void HandlerTestV3::SetUpV3Cow() {
     auto writer = CreateV3Cow();
 
+    ASSERT_NE(writer, nullptr);
     size_t total_data_to_write = size_;
 
     size_t total_blocks_to_write = total_data_to_write / BLOCK_SZ;
diff --git a/fs_mgr/tools/dmctl.cpp b/fs_mgr/tools/dmctl.cpp
index 9dc8c24..f843821 100644
--- a/fs_mgr/tools/dmctl.cpp
+++ b/fs_mgr/tools/dmctl.cpp
@@ -52,6 +52,7 @@
     std::cerr << "  list <devices | targets> [-v]" << std::endl;
     std::cerr << "  getpath <dm-name>" << std::endl;
     std::cerr << "  getuuid <dm-name>" << std::endl;
+    std::cerr << "  ima <dm-name>" << std::endl;
     std::cerr << "  info <dm-name>" << std::endl;
     std::cerr << "  replace <dm-name> <targets...>" << std::endl;
     std::cerr << "  status <dm-name>" << std::endl;
@@ -508,7 +509,14 @@
                       << std::endl;
             return -EINVAL;
         }
+    } else if (mode == "ima") {
+        if (!dm.GetTableStatusIma(argv[0], &table)) {
+            std::cerr << "Could not query table status of device \"" << argv[0] << "\"."
+                      << std::endl;
+            return -EINVAL;
+        }
     }
+
     std::cout << "Targets in the device-mapper table for " << argv[0] << ":" << std::endl;
     for (const auto& target : table) {
         std::cout << target.spec.sector_start << "-"
@@ -530,6 +538,10 @@
     return DumpTable("status", argc, argv);
 }
 
+static int ImaCmdHandler(int argc, char** argv) {
+    return DumpTable("ima", argc, argv);
+}
+
 static int ResumeCmdHandler(int argc, char** argv) {
     if (argc != 1) {
         std::cerr << "Invalid arguments, see \'dmctl help\'" << std::endl;
@@ -570,6 +582,7 @@
         {"info", InfoCmdHandler},
         {"table", TableCmdHandler},
         {"status", StatusCmdHandler},
+        {"ima", ImaCmdHandler},
         {"resume", ResumeCmdHandler},
         {"suspend", SuspendCmdHandler},
         // clang-format on
diff --git a/init/Android.bp b/init/Android.bp
index 12ca15a..d4b7fab 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -310,6 +310,7 @@
     name: "init_second_stage",
     defaults: ["init_second_stage_defaults"],
     static_libs: ["libinit"],
+    visibility: ["//visibility:any_system_partition"],
 }
 
 cc_binary {
diff --git a/libmodprobe/Android.bp b/libmodprobe/Android.bp
index 1d94a96..12906cc 100644
--- a/libmodprobe/Android.bp
+++ b/libmodprobe/Android.bp
@@ -10,6 +10,7 @@
     vendor_available: true,
     ramdisk_available: true,
     recovery_available: true,
+    vendor_ramdisk_available: true,
     host_supported: true,
     srcs: [
         "libmodprobe.cpp",
diff --git a/libvendorsupport/include_llndk/android/llndk-versioning.h b/libvendorsupport/include_llndk/android/llndk-versioning.h
index 8ae56d4..58cd18d 100644
--- a/libvendorsupport/include_llndk/android/llndk-versioning.h
+++ b/libvendorsupport/include_llndk/android/llndk-versioning.h
@@ -48,7 +48,9 @@
 
 // For non-vendor modules, API_LEVEL_AT_LEAST is replaced with __builtin_available(sdk_api_level) to
 // guard the API for __INTRODUCED_IN.
+#if !defined(API_LEVEL_AT_LEAST)
 #define API_LEVEL_AT_LEAST(sdk_api_level, vendor_api_level) \
     (__builtin_available(android sdk_api_level, *))
+#endif
 
 #endif  // __ANDROID_VENDOR__
diff --git a/rootdir/init.rc b/rootdir/init.rc
index ec203f9..d4cd4b8 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -648,6 +648,8 @@
     mkdir /metadata/aconfig 0775 root system
     mkdir /metadata/aconfig/flags 0770 root system
     mkdir /metadata/aconfig/boot 0775 root system
+    exec_start aconfigd-init
+    start aconfigd
 
 on late-fs
     # Ensure that tracefs has the correct permissions.
@@ -857,6 +859,8 @@
     mkdir /data/misc/odsign 0710 root system
     # directory used for odsign metrics
     mkdir /data/misc/odsign/metrics 0770 root system
+    # directory used for connectivity blob store.
+    mkdir /data/misc/connectivityblobdb 0770 system system
 
     # Directory for VirtualizationService temporary image files.
     # Delete any stale files owned by the old virtualizationservice uid (b/230056726).
diff --git a/toolbox/Android.bp b/toolbox/Android.bp
index 8594ec4..120cc6e 100644
--- a/toolbox/Android.bp
+++ b/toolbox/Android.bp
@@ -69,6 +69,7 @@
     name: "toolbox",
     defaults: ["toolbox_binary_defaults"],
     recovery_available: true,
+    vendor_ramdisk_available: true,
 }
 
 cc_binary {
diff --git a/trusty/utils/rpmb_dev/Android.bp b/trusty/utils/rpmb_dev/Android.bp
index a270087..5e9caaf 100644
--- a/trusty/utils/rpmb_dev/Android.bp
+++ b/trusty/utils/rpmb_dev/Android.bp
@@ -24,6 +24,7 @@
     ],
     shared_libs: [
         "libc",
+        "libcutils",
         "liblog",
         "libcrypto",
     ],
diff --git a/trusty/utils/rpmb_dev/rpmb_dev.c b/trusty/utils/rpmb_dev/rpmb_dev.c
index 0a9e6a1..cee3037 100644
--- a/trusty/utils/rpmb_dev/rpmb_dev.c
+++ b/trusty/utils/rpmb_dev/rpmb_dev.c
@@ -19,6 +19,7 @@
 #include "rpmb_protocol.h"
 
 #include <assert.h>
+#include <cutils/sockets.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <getopt.h>
@@ -613,20 +614,24 @@
         return EXIT_FAILURE;
     }
 
-    cmdres_sock = socket(AF_UNIX, SOCK_STREAM, 0);
+    cmdres_sock = android_get_control_socket(socket_path);
     if (cmdres_sock < 0) {
-        ALOGE("rpmb_dev: Failed to create command/response socket: %s\n", strerror(errno));
-        return EXIT_FAILURE;
-    }
+        ALOGW("android_get_control_socket(%s) failed, fall back to create it\n", socket_path);
+        cmdres_sock = socket(AF_UNIX, SOCK_STREAM, 0);
+        if (cmdres_sock < 0) {
+            ALOGE("rpmb_dev: Failed to create command/response socket: %s\n", strerror(errno));
+            return EXIT_FAILURE;
+        }
 
-    cmdres_sockaddr.sun_family = AF_UNIX;
-    strncpy(cmdres_sockaddr.sun_path, socket_path, sizeof(cmdres_sockaddr.sun_path));
+        cmdres_sockaddr.sun_family = AF_UNIX;
+        strncpy(cmdres_sockaddr.sun_path, socket_path, sizeof(cmdres_sockaddr.sun_path));
 
-    ret = bind(cmdres_sock, (struct sockaddr*)&cmdres_sockaddr, sizeof(struct sockaddr_un));
-    if (ret < 0) {
-        ALOGE("rpmb_dev: Failed to bind command/response socket: %s: %s\n", socket_path,
-              strerror(errno));
-        return EXIT_FAILURE;
+        ret = bind(cmdres_sock, (struct sockaddr*)&cmdres_sockaddr, sizeof(struct sockaddr_un));
+        if (ret < 0) {
+            ALOGE("rpmb_dev: Failed to bind command/response socket: %s: %s\n", socket_path,
+                  strerror(errno));
+            return EXIT_FAILURE;
+        }
     }
 
     ret = listen(cmdres_sock, 1);
diff --git a/trusty/utils/rpmb_dev/rpmb_dev.rc b/trusty/utils/rpmb_dev/rpmb_dev.rc
index 9e203b8..33ec0f2 100644
--- a/trusty/utils/rpmb_dev/rpmb_dev.rc
+++ b/trusty/utils/rpmb_dev/rpmb_dev.rc
@@ -1,29 +1,34 @@
 # RPMB Mock
-on post-fs-data
-    mkdir /data/vendor/ss
-    chown root system /data/vendor/ss
-    chmod 0770 /data/vendor/ss
-    rm /data/vendor/ss/rpmb_sock
-    start rpmb_mock_init
+on post-fs
+    mkdir /mnt/vendor/persist/ss 0770 root system
+    exec_start rpmb_mock_init
     start rpmb_mock
 
+on post-fs-data
+    mkdir /data/vendor/ss 0770 root system
+    symlink /mnt/vendor/persist/ss /data/vendor/ss/persist
+    chown root system /data/vendor/ss/persist
+    chmod 0770 /data/vendor/ss/persist
+
     # Storage proxy
-    start storageproxyd
+    restart storageproxyd
 
-service storageproxyd /vendor/bin/storageproxyd -d /dev/trusty-ipc-dev0 \
-        -r /data/vendor/ss/rpmb_sock -p /data/vendor/ss -t sock
-    class main
-    disabled
-    user root
+service storageproxyd /vendor/bin/storageproxyd -d ${ro.hardware.trusty_ipc_dev:-/dev/trusty-ipc-dev0} \
+        -r /dev/socket/rpmb_mock -p /data/vendor/ss -t sock
+    class early_hal
+    user system
+    group system
 
-service rpmb_mock_init /vendor/bin/rpmb_dev --dev /data/vendor/ss/RPMB_DATA --init --size 2048
+service rpmb_mock_init /vendor/bin/rpmb_dev --dev /mnt/vendor/persist/ss/RPMB_DATA --init --size 2048
     disabled
     user system
     group system
     oneshot
 
-service rpmb_mock /vendor/bin/rpmb_dev --dev /data/vendor/ss/RPMB_DATA --sock /data/vendor/ss/rpmb_sock
+service rpmb_mock /vendor/bin/rpmb_dev --dev /mnt/vendor/persist/ss/RPMB_DATA \
+                          --sock rpmb_mock
     class main
     disabled
     user system
     group system
+    socket rpmb_mock stream 660 system system