Merge "Add adbd_test to mts."
diff --git a/adb/Android.bp b/adb/Android.bp
index 2a56f0f..b3fe1ef 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -29,6 +29,7 @@
         "-DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION=1",
     ],
     cpp_std: "experimental",
+    stl: "libc++_static",
 
     use_version_lib: true,
     compile_multilib: "first",
@@ -160,6 +161,11 @@
     // libadbconnection_client doesn't need an embedded build number.
     use_version_lib: false,
 
+    target: {
+        linux: {
+            version_script: "adbconnection/libadbconnection_client.map.txt",
+        },
+    },
     stubs: {
         symbol_file: "adbconnection/libadbconnection_client.map.txt",
         versions: ["1"],
@@ -359,8 +365,6 @@
         "libz",
     ],
 
-    stl: "libc++_static",
-
     // Don't add anything here, we don't want additional shared dependencies
     // on the host adb tool, and shared libraries that link against libc++
     // will violate ODR
@@ -553,11 +557,9 @@
         keep_symbols: true,
     },
 
-    stl: "libc++_static",
     static_libs: [
         "libadbconnection_server",
         "libadbd",
-        "libadbd_auth",
         "libadbd_services",
         "libasyncio",
         "libbase",
@@ -572,6 +574,7 @@
     ],
 
     shared_libs: [
+        "libadbd_auth",
         "libcrypto",
     ],
 }
@@ -580,7 +583,6 @@
     name: "adbd_system_binaries",
     required: [
         "abb",
-        "libadbd_auth",
         "reboot",
         "set-verity-state",
     ]
@@ -734,7 +736,6 @@
         "libziparchive",
         "libz",
     ],
-    stl: "libc++_static",
     proto: {
         type: "lite",
         export_proto_headers: true,
diff --git a/adb/apex/ld.config.txt b/adb/apex/ld.config.txt
index d1858a4..ca297fe 100644
--- a/adb/apex/ld.config.txt
+++ b/adb/apex/ld.config.txt
@@ -5,16 +5,24 @@
 dir.adbd = /apex/com.android.adbd/bin/
 
 [adbd]
-additional.namespaces = platform,art
+additional.namespaces = apex,platform,art
 
 namespace.default.isolated = true
-namespace.default.search.paths = /apex/com.android.adbd/${LIB}
-namespace.default.asan.search.paths = /apex/com.android.adbd/${LIB}
 namespace.default.permitted.paths = /system/${LIB}
 namespace.default.asan.permitted.paths = /system/${LIB}
-namespace.default.links = art,platform
+namespace.default.links = apex,art,platform
+namespace.default.link.apex.shared_libs = libcrypto.so
 namespace.default.link.art.shared_libs = libadbconnection_server.so
-namespace.default.link.platform.shared_libs = libc.so:libdl.so:libm.so:libclang_rt.hwasan-aarch64-android.so
+
+# libcrypto.so in the APEX might be a symlink to /system, for APEXes bundled with the system image.
+# The dynamic linker works off of realpath, so we need to permit loading libcrypto.so from /system.
+namespace.default.link.platform.shared_libs = libc.so:libdl.so:libm.so:libclang_rt.hwasan-aarch64-android.so:liblog.so:libadbd_auth.so:libcrypto.so
+
+namespace.apex.isolated = true
+namespace.apex.search.paths = /apex/com.android.adbd/${LIB}
+namespace.apex.asan.search.paths = /apex/com.android.adbd/${LIB}
+namespace.apex.links = platform
+namespace.apex.link.platform.allow_all_shared_libs = true
 
 ###############################################################################
 # "art" APEX namespace: used for libadbdconnection_server
diff --git a/base/logging.cpp b/base/logging.cpp
index a868706..f42b996 100644
--- a/base/logging.cpp
+++ b/base/logging.cpp
@@ -340,18 +340,18 @@
 
   int lg_id = LogIdTolog_id_t(id);
 
-  char log_message[1024];
+  char log_message_with_file[4068];  // LOGGER_ENTRY_MAX_PAYLOAD, not available in the NDK.
   if (priority == ANDROID_LOG_FATAL && file != nullptr) {
-    snprintf(log_message, sizeof(log_message), "%s:%u] %s", file, line, message);
-  } else {
-    snprintf(log_message, sizeof(log_message), "%s", message);
+    snprintf(log_message_with_file, sizeof(log_message_with_file), "%s:%u] %s", file, line,
+             message);
+    message = log_message_with_file;
   }
 
   static auto& liblog_functions = GetLibLogFunctions();
   if (liblog_functions) {
     __android_logger_data logger_data = {sizeof(__android_logger_data),     lg_id, priority, tag,
                                          static_cast<const char*>(nullptr), 0};
-    liblog_functions->__android_log_logd_logger(&logger_data, log_message);
+    liblog_functions->__android_log_logd_logger(&logger_data, message);
   } else {
     __android_log_buf_print(lg_id, priority, tag, "%s", message);
   }
diff --git a/bootstat/Android.bp b/bootstat/Android.bp
index 5e2d171..edff26d 100644
--- a/bootstat/Android.bp
+++ b/bootstat/Android.bp
@@ -30,8 +30,8 @@
         "libbase",
         "libcutils",
         "liblog",
-        "libmetricslogger",
     ],
+    static_libs: ["libgtest_prod"],
 }
 
 // bootstat static library
diff --git a/bootstat/boot_reason_test.sh b/bootstat/boot_reason_test.sh
index f379d76..970ca94 100755
--- a/bootstat/boot_reason_test.sh
+++ b/bootstat/boot_reason_test.sh
@@ -7,7 +7,7 @@
 # - watch adb logcat -b all -d -s bootstat
 # - watch adb logcat -b all -d | audit2allow
 # - wait until screen is up, boot has completed, can mean wait for
-#   sys.boot_completed=1 and sys.logbootcomplete=1 to be true
+#   sys.boot_completed=1 and sys.bootstat.first_boot_completed=1 to be true
 #
 # All test frames, and nothing else, must be function names prefixed and
 # specifiged with the pattern 'test_<test>() {' as this is also how the
@@ -230,13 +230,13 @@
       if [ -n "`get_property sys.boot.reason`" ]
       then
         vals=`get_property |
-              sed -n 's/[[]sys[.]\(boot_completed\|logbootcomplete\)[]]: [[]\([01]\)[]]$/\1=\2/p'`
-        if [ "${vals}" = "`echo boot_completed=1 ; echo logbootcomplete=1`" ]
+              sed -n 's/[[]sys[.]\(boot_completed\|bootstat.first_boot_completed\)[]]: [[]\([01]\)[]]$/\1=\2/p'`
+        if [ "${vals}" = "`echo boot_completed=1 ; echo bootstat.first_boot_completed=1`" ]
         then
           sleep 1
           break
         fi
-        if [ "${vals}" = "`echo logbootcomplete=1 ; echo boot_completed=1`" ]
+        if [ "${vals}" = "`echo bootstat.first_boot_completed=1 ; echo boot_completed=1`" ]
         then
           sleep 1
           break
@@ -384,15 +384,15 @@
 init    : processing action (boot) from (/system/etc/init/bootstat.rc
 init    : processing action (ro.boot.bootreason=*) from (/system/etc/init/bootstat.rc
 init    : processing action (ro.boot.bootreason=* && post-fs) from (/system/etc/init/bootstat.rc
-init    : processing action (zygote-start) from (/system/etc/init/bootstat.rc
-init    : processing action (sys.boot_completed=1 && sys.logbootcomplete=1) from (/system/etc/init/bootstat.rc
+init    : processing action (sys.bootstat.first_zygote_start=0 && zygote-start) from (/system/etc/init/bootstat.rc
+init    : processing action (sys.boot_completed=1 && sys.bootstat.first_boot_completed=0) from (/system/etc/init/bootstat.rc
  (/system/bin/bootstat --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l)'
  (/system/bin/bootstat --set_system_boot_reason --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l)'
  (/system/bin/bootstat -r post_decrypt_time_elapsed)'
-init    : Command 'exec - system log -- /system/bin/bootstat --record_boot_complete' action=sys.boot_completed=1 && sys.logbootcomplete=1 (/system/etc/init/bootstat.rc:
-init    : Command 'exec - system log -- /system/bin/bootstat --record_boot_reason' action=sys.boot_completed=1 && sys.logbootcomplete=1 (/system/etc/init/bootstat.rc:
-init    : Command 'exec - system log -- /system/bin/bootstat --record_time_since_factory_reset' action=sys.boot_completed=1 && sys.logbootcomplete=1 (/system/etc/init/bootstat.rc:
-init    : Command 'exec_background - system log -- /system/bin/bootstat --set_system_boot_reason --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l' action=sys.boot_completed=1 && sys.logbootcomplete=1 (/system/etc/init/bootstat.rc
+init    : Command 'exec - system log -- /system/bin/bootstat --record_boot_complete' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc:
+init    : Command 'exec - system log -- /system/bin/bootstat --record_boot_reason' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc:
+init    : Command 'exec - system log -- /system/bin/bootstat --record_time_since_factory_reset' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc:
+init    : Command 'exec_background - system log -- /system/bin/bootstat --set_system_boot_reason --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l' action=sys.boot_completed=1 && sys.bootstat.first_boot_completed=0 (/system/etc/init/bootstat.rc
  (/system/bin/bootstat --record_boot_complete)'...
  (/system/bin/bootstat --record_boot_complete)' (pid${SPACE}
  (/system/bin/bootstat --record_boot_reason)'...
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index d08a59f..6b8a09a 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -44,7 +44,6 @@
 #include <android/log.h>
 #include <cutils/android_reboot.h>
 #include <cutils/properties.h>
-#include <metricslogger/metrics_logger.h>
 #include <statslog.h>
 
 #include "boot_event_record_store.h"
@@ -57,9 +56,10 @@
   BootEventRecordStore boot_event_store;
 
   auto events = boot_event_store.GetAllBootEvents();
-  for (auto i = events.cbegin(); i != events.cend(); ++i) {
-    android::metricslogger::LogHistogram(i->first, i->second);
-  }
+  // TODO(b/148575354): Replace with statsd.
+  // for (auto i = events.cbegin(); i != events.cend(); ++i) {
+  //   android::metricslogger::LogHistogram(i->first, i->second);
+  // }
 }
 
 // Records the named boot |event| to the record store. If |value| is non-empty
@@ -312,6 +312,11 @@
     {"reboot,unknown[0-9]*", 183},
     {"reboot,longkey,.*", 184},
     {"reboot,boringssl-self-check-failed", 185},
+    {"reboot,userspace_failed,shutdown_aborted", 186},
+    {"reboot,userspace_failed,watchdog_triggered", 187},
+    {"reboot,userspace_failed,watchdog_fork", 188},
+    {"reboot,userspace_failed,*", 189},
+    {"reboot,mount_userdata_failed", 190},
 };
 
 // Converts a string value representing the reason the system booted to an
@@ -1207,13 +1212,17 @@
   const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
 
   if (reason.empty()) {
+    // TODO(b/148575354): Replace with statsd.
     // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
     // (and not corruption anywhere else in the reporting pipeline).
-    android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
-                                           android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
+    // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
+    //                                        android::metricslogger::FIELD_PLATFORM_REASON,
+    //                                        "<EMPTY>");
   } else {
-    android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
-                                           android::metricslogger::FIELD_PLATFORM_REASON, reason);
+    // TODO(b/148575354): Replace with statsd.
+    // android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
+    //                                        android::metricslogger::FIELD_PLATFORM_REASON,
+    //                                        reason);
   }
 
   // Log the raw bootloader_boot_reason property value.
@@ -1241,9 +1250,10 @@
   time_t current_time_utc = time(nullptr);
 
   if (current_time_utc < 0) {
+    // TODO(b/148575354): Replace with statsd.
     // UMA does not display negative values in buckets, so convert to positive.
-    android::metricslogger::LogHistogram("factory_reset_current_time_failure",
-                                         std::abs(current_time_utc));
+    // android::metricslogger::LogHistogram("factory_reset_current_time_failure",
+    //                                      std::abs(current_time_utc));
 
     // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
     // is losing records somehow.
@@ -1251,7 +1261,8 @@
                                            std::abs(current_time_utc));
     return;
   } else {
-    android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
+    // TODO(b/148575354): Replace with statsd.
+    // android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
 
     // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
     // is losing records somehow.
@@ -1271,7 +1282,8 @@
   // Calculate and record the difference in time between now and the
   // factory_reset time.
   time_t factory_reset_utc = record.second;
-  android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
+  // TODO(b/148575354): Replace with statsd.
+  // android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
 
   // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
   // is losing records somehow.
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
index 85caf25..a350fe7 100644
--- a/bootstat/bootstat.rc
+++ b/bootstat/bootstat.rc
@@ -50,34 +50,34 @@
 on post-fs-data && property:init.svc.bootanim=running && property:ro.crypto.type=block
     exec_background - system log -- /system/bin/bootstat -r post_decrypt_time_elapsed
 
-# sys.logbootcomplete is a signal to enable the bootstat logging mechanism.
-# This signaling is necessary to prevent logging boot metrics after a runtime
-# restart (e.g., adb shell stop && adb shell start).  /proc/uptime is not reset
-# during a runtime restart, which leads to false boot time metrics being reported.
+# Initialize bootstat state machine.
 #
-# The 'on boot' event occurs once per hard boot (device power on), which
-# switches the flag on. If the device performs a runtime restart, the flag is
-# switched off and cannot be switched on until the device hard boots again.
-
-# Enable bootstat logging on boot.
-on boot
-    setprop sys.logbootcomplete 1
-
-# Disable further bootstat logging on a runtime restart. A runtime restart is
-# signaled by the zygote stopping.
-on property:init.svc.zygote=stopping
-    setprop sys.logbootcomplete 0
+# sys.bootstat.first_boot_completed: responsible for making sure that record_boot_complete happens
+# only once per device hard reboot. Possible values:
+#
+#   sys.bootstat.first_boot_completed=0 - first boot completed trigger wasn't processed yet.
+#   sys.bootstat.first_boot_completed=1 - first boot completed trigger was processed and
+#                                         record_boot_complete was called. Subsequent boot completed
+#                                         triggers (e.g. due to userspace reboot) won't retrigger
+#                                         record_boot_complete
+#
+# IMPORTANT, ro.persistent_properties.ready=1 trigger is used here to ensure that we initialize
+# state machine only once, which as result ensures that bootstat --set_system_boot_reason and
+# bootstat --record_boot_complete will be called only once per full reboot.
+on property:ro.persistent_properties.ready=true
+  setprop sys.bootstat.first_boot_completed 0
 
 # Set boot reason
-on zygote-start
+on property:ro.persistent_properties.ready=true
     # Converts bootloader boot reason and persist.sys.boot.reason to system boot reason
     # Need go after persist peroperties are loaded which is right before zygote-start trigger
     exec_background - system log -- /system/bin/bootstat --set_system_boot_reason
 
 # Record boot complete metrics.
-on property:sys.boot_completed=1 && property:sys.logbootcomplete=1
+on property:sys.boot_completed=1 && property:sys.bootstat.first_boot_completed=0
     # Record boot_complete and related stats (decryption, etc).
     # Record the boot reason.
     # Record time since factory reset.
     # Log all boot events.
     exec_background - system log -- /system/bin/bootstat --record_boot_complete --record_boot_reason --record_time_since_factory_reset -l
+    setprop sys.bootstat.first_boot_completed 1
diff --git a/fs_mgr/TEST_MAPPING b/fs_mgr/TEST_MAPPING
new file mode 100644
index 0000000..a947b4e
--- /dev/null
+++ b/fs_mgr/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "libdm_test"
+    }
+  ]
+}
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 9180a06..b27126b 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -887,7 +887,7 @@
 }
 
 static bool should_use_metadata_encryption(const FstabEntry& entry) {
-    return !entry.key_dir.empty() &&
+    return !entry.metadata_key_dir.empty() &&
            (entry.fs_mgr_flags.file_encryption || entry.fs_mgr_flags.force_fde_or_fbe);
 }
 
@@ -1159,7 +1159,7 @@
 static void WrapUserdataIfNeeded(FstabEntry* entry, const std::string& actual_block_device = {}) {
     const auto& block_device =
             actual_block_device.empty() ? entry->blk_device : actual_block_device;
-    if (entry->mount_point != "/data" || !entry->key_dir.empty() ||
+    if (entry->mount_point != "/data" || !entry->metadata_key_dir.empty() ||
         android::base::StartsWith(block_device, "/dev/block/dm-")) {
         return;
     }
diff --git a/fs_mgr/fs_mgr_format.cpp b/fs_mgr/fs_mgr_format.cpp
index acf4d7b..a8c2cc1 100644
--- a/fs_mgr/fs_mgr_format.cpp
+++ b/fs_mgr/fs_mgr_format.cpp
@@ -24,6 +24,7 @@
 #include <cutils/partition_utils.h>
 #include <sys/mount.h>
 
+#include <android-base/properties.h>
 #include <android-base/unique_fd.h>
 #include <ext4_utils/ext4.h>
 #include <ext4_utils/ext4_utils.h>
@@ -57,7 +58,7 @@
 }
 
 static int format_ext4(const std::string& fs_blkdev, const std::string& fs_mnt_point,
-                       bool crypt_footer) {
+                       bool crypt_footer, bool needs_projid) {
     uint64_t dev_sz;
     int rc = 0;
 
@@ -72,11 +73,20 @@
     }
 
     std::string size_str = std::to_string(dev_sz / 4096);
-    const char* const mke2fs_args[] = {
-            "/system/bin/mke2fs", "-t",   "ext4", "-b", "4096", fs_blkdev.c_str(),
-            size_str.c_str(),     nullptr};
 
-    rc = logwrap_fork_execvp(arraysize(mke2fs_args), mke2fs_args, nullptr, false, LOG_KLOG, true,
+    std::vector<const char*> mke2fs_args = {"/system/bin/mke2fs", "-t", "ext4", "-b", "4096"};
+
+    // Project ID's require wider inodes. The Quotas themselves are enabled by tune2fs during boot.
+    if (needs_projid) {
+        mke2fs_args.push_back("-I");
+        mke2fs_args.push_back("512");
+    }
+    // casefolding is enabled via tune2fs during boot.
+
+    mke2fs_args.push_back(fs_blkdev.c_str());
+    mke2fs_args.push_back(size_str.c_str());
+
+    rc = logwrap_fork_execvp(mke2fs_args.size(), mke2fs_args.data(), nullptr, false, LOG_KLOG, true,
                              nullptr);
     if (rc) {
         LERROR << "mke2fs returned " << rc;
@@ -95,7 +105,8 @@
     return rc;
 }
 
-static int format_f2fs(const std::string& fs_blkdev, uint64_t dev_sz, bool crypt_footer) {
+static int format_f2fs(const std::string& fs_blkdev, uint64_t dev_sz, bool crypt_footer,
+                       bool needs_projid, bool needs_casefold) {
     if (!dev_sz) {
         int rc = get_dev_sz(fs_blkdev, &dev_sz);
         if (rc) {
@@ -109,26 +120,40 @@
     }
 
     std::string size_str = std::to_string(dev_sz / 4096);
-    // clang-format off
-    const char* const args[] = {
-        "/system/bin/make_f2fs",
-        "-g", "android",
-        fs_blkdev.c_str(),
-        size_str.c_str(),
-        nullptr
-    };
-    // clang-format on
 
-    return logwrap_fork_execvp(arraysize(args), args, nullptr, false, LOG_KLOG, true, nullptr);
+    std::vector<const char*> args = {"/system/bin/make_f2fs", "-g", "android"};
+    if (needs_projid) {
+        args.push_back("-O");
+        args.push_back("project_quota,extra_attr");
+    }
+    if (needs_casefold) {
+        args.push_back("-O");
+        args.push_back("casefold");
+        args.push_back("-C");
+        args.push_back("utf8");
+    }
+    args.push_back(fs_blkdev.c_str());
+    args.push_back(size_str.c_str());
+
+    return logwrap_fork_execvp(args.size(), args.data(), nullptr, false, LOG_KLOG, true, nullptr);
 }
 
 int fs_mgr_do_format(const FstabEntry& entry, bool crypt_footer) {
     LERROR << __FUNCTION__ << ": Format " << entry.blk_device << " as '" << entry.fs_type << "'";
 
+    bool needs_casefold = false;
+    bool needs_projid = false;
+
+    if (entry.mount_point == "/data") {
+        needs_casefold = android::base::GetBoolProperty("ro.emulated_storage.casefold", false);
+        needs_projid = android::base::GetBoolProperty("ro.emulated_storage.projid", false);
+    }
+
     if (entry.fs_type == "f2fs") {
-        return format_f2fs(entry.blk_device, entry.length, crypt_footer);
+        return format_f2fs(entry.blk_device, entry.length, crypt_footer, needs_projid,
+                           needs_casefold);
     } else if (entry.fs_type == "ext4") {
-        return format_ext4(entry.blk_device, entry.mount_point, crypt_footer);
+        return format_ext4(entry.blk_device, entry.mount_point, crypt_footer, needs_projid);
     } else {
         LERROR << "File system type '" << entry.fs_type << "' is not supported";
         return -EINVAL;
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 9697a4c..561d994 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -276,7 +276,10 @@
             entry->vbmeta_partition = arg;
         } else if (StartsWith(flag, "keydirectory=")) {
             // The metadata flag is followed by an = and the directory for the keys.
-            entry->key_dir = arg;
+            entry->metadata_key_dir = arg;
+        } else if (StartsWith(flag, "metadata_cipher=")) {
+            // Specify the cipher to use for metadata encryption
+            entry->metadata_cipher = arg;
         } else if (StartsWith(flag, "sysfs_path=")) {
             // The path to trigger device gc by idle-maint of vold.
             entry->sysfs_path = arg;
@@ -591,8 +594,8 @@
         userdata.blk_device = "userdata_gsi";
         userdata.fs_mgr_flags.logical = true;
         userdata.fs_mgr_flags.formattable = true;
-        if (!userdata.key_dir.empty()) {
-            userdata.key_dir += "/gsi";
+        if (!userdata.metadata_key_dir.empty()) {
+            userdata.metadata_key_dir += "/gsi";
         }
     } else {
         userdata = BuildDsuUserdataFstabEntry();
diff --git a/fs_mgr/include_fstab/fstab/fstab.h b/fs_mgr/include_fstab/fstab/fstab.h
index 80deaef..4dc09c1 100644
--- a/fs_mgr/include_fstab/fstab/fstab.h
+++ b/fs_mgr/include_fstab/fstab/fstab.h
@@ -37,7 +37,8 @@
     unsigned long flags = 0;
     std::string fs_options;
     std::string key_loc;
-    std::string key_dir;
+    std::string metadata_key_dir;
+    std::string metadata_cipher;
     off64_t length = 0;
     std::string label;
     int partnum = -1;
diff --git a/fs_mgr/libdm/Android.bp b/fs_mgr/libdm/Android.bp
index 8a924d5..1c3427f 100644
--- a/fs_mgr/libdm/Android.bp
+++ b/fs_mgr/libdm/Android.bp
@@ -54,29 +54,32 @@
 }
 
 cc_defaults {
-    name: "libdm_defaults",
+    name: "libdm_test_defaults",
     defaults: ["fs_mgr_defaults"],
     static_libs: [
         "libdm",
+    ],
+    shared_libs: [
         "libbase",
         "libext2_uuid",
         "libfs_mgr",
         "liblog",
     ],
     srcs: [":libdm_test_srcs"],
+    auto_gen_config: true,
+    require_root: true,
 }
 
 cc_test {
     name: "libdm_test",
-    defaults: ["libdm_defaults"],
+    defaults: ["libdm_test_defaults"],
+    test_suites: ["device-tests"],
 }
 
 cc_test {
     name: "vts_libdm_test",
-    defaults: ["libdm_defaults"],
+    defaults: ["libdm_test_defaults"],
     test_suites: ["vts-core"],
-    auto_gen_config: true,
-    require_root: true,
     test_min_api_level: 29,
 }
 
diff --git a/fs_mgr/libdm/dm_target.cpp b/fs_mgr/libdm/dm_target.cpp
index 65f6e12..d7b689e 100644
--- a/fs_mgr/libdm/dm_target.cpp
+++ b/fs_mgr/libdm/dm_target.cpp
@@ -243,9 +243,49 @@
     return android::base::Join(argv, " ");
 }
 
+const std::string DmTargetDefaultKey::name_ = "default-key";
+
+bool DmTargetDefaultKey::IsLegacy(bool* result) {
+    DeviceMapper& dm = DeviceMapper::Instance();
+    DmTargetTypeInfo info;
+    if (!dm.GetTargetByName(name_, &info)) return false;
+    // dm-default-key was modified to be like dm-crypt with version 2
+    *result = !info.IsAtLeast(2, 0, 0);
+    return true;
+}
+
+bool DmTargetDefaultKey::Valid() const {
+    bool real_is_legacy;
+    if (!DmTargetDefaultKey::IsLegacy(&real_is_legacy)) return false;
+    if (real_is_legacy != is_legacy_) return false;
+    if (!is_legacy_ && !set_dun_) return false;
+    return true;
+}
+
 std::string DmTargetDefaultKey::GetParameterString() const {
-    return cipher_ + " " + key_ + " " + blockdev_ + " " + std::to_string(start_sector_) +
-           (set_dun_ ? " 1 set_dun" : "");
+    std::vector<std::string> argv;
+    argv.emplace_back(cipher_);
+    argv.emplace_back(key_);
+    if (!is_legacy_) {
+        argv.emplace_back("0");  // iv_offset
+    }
+    argv.emplace_back(blockdev_);
+    argv.push_back(std::to_string(start_sector_));
+    std::vector<std::string> extra_argv;
+    if (is_legacy_) {
+        if (set_dun_) {  // v2 always sets the DUN.
+            extra_argv.emplace_back("set_dun");
+        }
+    } else {
+        extra_argv.emplace_back("allow_discards");
+        extra_argv.emplace_back("sector_size:4096");
+        extra_argv.emplace_back("iv_large_sectors");
+    }
+    if (!extra_argv.empty()) {
+        argv.emplace_back(std::to_string(extra_argv.size()));
+        argv.insert(argv.end(), extra_argv.begin(), extra_argv.end());
+    }
+    return android::base::Join(argv, " ");
 }
 
 }  // namespace dm
diff --git a/fs_mgr/libdm/dm_test.cpp b/fs_mgr/libdm/dm_test.cpp
index b7f31bc..affdd29 100644
--- a/fs_mgr/libdm/dm_test.cpp
+++ b/fs_mgr/libdm/dm_test.cpp
@@ -516,10 +516,27 @@
 }
 
 TEST(libdm, DefaultKeyArgs) {
-    DmTargetDefaultKey target(0, 4096, "AES-256-XTS", "abcdef0123456789", "/dev/loop0", 0);
+    DmTargetTypeInfo info;
+
+    DeviceMapper& dm = DeviceMapper::Instance();
+    if (!dm.GetTargetByName("default-key", &info)) {
+        cout << "default-key module not enabled; skipping test" << std::endl;
+        return;
+    }
+    bool is_legacy;
+    ASSERT_TRUE(DmTargetDefaultKey::IsLegacy(&is_legacy));
+    // set_dun only in the non-is_legacy case
+    DmTargetDefaultKey target(0, 4096, "AES-256-XTS", "abcdef0123456789", "/dev/loop0", 0,
+                              is_legacy, !is_legacy);
     ASSERT_EQ(target.name(), "default-key");
     ASSERT_TRUE(target.Valid());
-    ASSERT_EQ(target.GetParameterString(), "AES-256-XTS abcdef0123456789 /dev/loop0 0");
+    if (is_legacy) {
+        ASSERT_EQ(target.GetParameterString(), "AES-256-XTS abcdef0123456789 /dev/loop0 0");
+    } else {
+        ASSERT_EQ(target.GetParameterString(),
+                  "AES-256-XTS abcdef0123456789 0 /dev/loop0 0 3 allow_discards sector_size:4096 "
+                  "iv_large_sectors");
+    }
 }
 
 TEST(libdm, DeleteDeviceWithTimeout) {
diff --git a/fs_mgr/libdm/include/libdm/dm_target.h b/fs_mgr/libdm/include/libdm/dm_target.h
index a78bc71..e3dd92b 100644
--- a/fs_mgr/libdm/include/libdm/dm_target.h
+++ b/fs_mgr/libdm/include/libdm/dm_target.h
@@ -281,23 +281,27 @@
   public:
     DmTargetDefaultKey(uint64_t start, uint64_t length, const std::string& cipher,
                        const std::string& key, const std::string& blockdev, uint64_t start_sector,
-                       bool set_dun = false)
+                       bool is_legacy, bool set_dun)
         : DmTarget(start, length),
           cipher_(cipher),
           key_(key),
           blockdev_(blockdev),
           start_sector_(start_sector),
+          is_legacy_(is_legacy),
           set_dun_(set_dun) {}
 
-    std::string name() const override { return "default-key"; }
-    bool Valid() const override { return true; }
+    std::string name() const override { return name_; }
+    bool Valid() const override;
     std::string GetParameterString() const override;
+    static bool IsLegacy(bool* result);
 
   private:
+    static const std::string name_;
     std::string cipher_;
     std::string key_;
     std::string blockdev_;
     uint64_t start_sector_;
+    bool is_legacy_;
     bool set_dun_;
 };
 
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 88731df..a6f07fc 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -1709,6 +1709,8 @@
         return UpdateState::MergeNeedsReboot;
     } else if (contents == "merge-failed") {
         return UpdateState::MergeFailed;
+    } else if (contents == "cancelled") {
+        return UpdateState::Cancelled;
     } else {
         LOG(ERROR) << "Unknown merge state in update state file: \"" << contents << "\"";
         return UpdateState::None;
@@ -1731,6 +1733,8 @@
             return os << "merge-needs-reboot";
         case UpdateState::MergeFailed:
             return os << "merge-failed";
+        case UpdateState::Cancelled:
+            return os << "cancelled";
         default:
             LOG(ERROR) << "Unknown update state: " << static_cast<uint32_t>(state);
             return os;
@@ -1957,8 +1961,17 @@
     auto current_super = device_->GetSuperDevice(current_slot);
 
     auto current_metadata = MetadataBuilder::New(opener, current_super, current_slot);
+    if (current_metadata == nullptr) {
+        LOG(ERROR) << "Cannot create metadata builder.";
+        return Return::Error();
+    }
+
     auto target_metadata =
             MetadataBuilder::NewForUpdate(opener, current_super, current_slot, target_slot);
+    if (target_metadata == nullptr) {
+        LOG(ERROR) << "Cannot create target metadata builder.";
+        return Return::Error();
+    }
 
     // Delete partitions with target suffix in |current_metadata|. Otherwise,
     // partition_cow_creator recognizes these left-over partitions as used space.
diff --git a/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp b/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
index 337be4f..5530e59 100644
--- a/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_metadata_updater_test.cpp
@@ -19,6 +19,7 @@
 #include <memory>
 #include <string>
 
+#include <android-base/properties.h>
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 #include <liblp/builder.h>
@@ -42,6 +43,10 @@
 
 class SnapshotMetadataUpdaterTest : public ::testing::TestWithParam<uint32_t> {
   public:
+    SnapshotMetadataUpdaterTest() {
+        is_virtual_ab_ = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
+    }
+
     void SetUp() override {
         target_slot_ = GetParam();
         target_suffix_ = SlotSuffixForSlotNumber(target_slot_);
@@ -122,6 +127,7 @@
                                   << ".";
     }
 
+    bool is_virtual_ab_;
     std::unique_ptr<MetadataBuilder> builder_;
     uint32_t target_slot_;
     std::string target_suffix_;
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index 7de37db..c49c49e 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -78,7 +78,9 @@
 
 class SnapshotTest : public ::testing::Test {
   public:
-    SnapshotTest() : dm_(DeviceMapper::Instance()) {}
+    SnapshotTest() : dm_(DeviceMapper::Instance()) {
+        is_virtual_ab_ = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
+    }
 
     // This is exposed for main.
     void Cleanup() {
@@ -88,6 +90,8 @@
 
   protected:
     void SetUp() override {
+        if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
         SnapshotTestPropertyFetcher::SetUp();
         InitializeState();
         CleanupTestArtifacts();
@@ -97,6 +101,8 @@
     }
 
     void TearDown() override {
+        if (!is_virtual_ab_) return;
+
         lock_ = nullptr;
 
         CleanupTestArtifacts();
@@ -329,6 +335,7 @@
         return AssertionSuccess();
     }
 
+    bool is_virtual_ab_;
     DeviceMapper& dm_;
     std::unique_ptr<SnapshotManager::LockedFile> lock_;
     android::fiemap::IImageManager* image_manager_ = nullptr;
@@ -754,6 +761,8 @@
 class SnapshotUpdateTest : public SnapshotTest {
   public:
     void SetUp() override {
+        if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
         SnapshotTest::SetUp();
         Cleanup();
 
@@ -784,6 +793,7 @@
 
         // Initialize source partition metadata using |manifest_|.
         src_ = MetadataBuilder::New(*opener_, "super", 0);
+        ASSERT_NE(src_, nullptr);
         ASSERT_TRUE(FillFakeMetadata(src_.get(), manifest_, "_a"));
         // Add sys_b which is like system_other.
         ASSERT_TRUE(src_->AddGroup("group_b", kGroupSize));
@@ -813,6 +823,8 @@
         }
     }
     void TearDown() override {
+        if (!is_virtual_ab_) return;
+
         Cleanup();
         SnapshotTest::TearDown();
     }
@@ -976,6 +988,7 @@
 
     // Test that partitions prioritize using space in super.
     auto tgt = MetadataBuilder::New(*opener_, "super", 1);
+    ASSERT_NE(tgt, nullptr);
     ASSERT_NE(nullptr, tgt->FindPartition("sys_b-cow"));
     ASSERT_NE(nullptr, tgt->FindPartition("vnd_b-cow"));
     ASSERT_EQ(nullptr, tgt->FindPartition("prd_b-cow"));
@@ -1189,7 +1202,9 @@
 
     // Check that the old COW space is reclaimed and does not occupy space of mapped partitions.
     auto src = MetadataBuilder::New(*opener_, "super", 1);
+    ASSERT_NE(src, nullptr);
     auto tgt = MetadataBuilder::New(*opener_, "super", 0);
+    ASSERT_NE(tgt, nullptr);
     for (const auto& cow_part_name : {"sys_a-cow", "vnd_a-cow", "prd_a-cow"}) {
         auto* cow_part = tgt->FindPartition(cow_part_name);
         ASSERT_NE(nullptr, cow_part) << cow_part_name << " does not exist in target metadata";
@@ -1280,6 +1295,7 @@
     SetSize(vnd_, 5_MiB);
     SetSize(prd_, 5_MiB);
     src_ = MetadataBuilder::New(*opener_, "super", 0);
+    ASSERT_NE(src_, nullptr);
     src_->RemoveGroupAndPartitions(group_->name() + "_a");
     src_->RemoveGroupAndPartitions(group_->name() + "_b");
     ASSERT_TRUE(FillFakeMetadata(src_.get(), manifest_, "_a"));
@@ -1625,6 +1641,8 @@
 };
 
 TEST_P(FlashAfterUpdateTest, FlashSlotAfterUpdate) {
+    if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
     // OTA client blindly unmaps all partitions that are possibly mapped.
     for (const auto& name : {"sys_b", "vnd_b", "prd_b"}) {
         ASSERT_TRUE(sm->UnmapUpdateSnapshot(name));
@@ -1651,6 +1669,7 @@
 
     // Simulate flashing |flashed_slot|. This clears the UPDATED flag.
     auto flashed_builder = MetadataBuilder::New(*opener_, "super", flashed_slot);
+    ASSERT_NE(flashed_builder, nullptr);
     flashed_builder->RemoveGroupAndPartitions(group_->name() + flashed_slot_suffix);
     flashed_builder->RemoveGroupAndPartitions(kCowGroupName);
     ASSERT_TRUE(FillFakeMetadata(flashed_builder.get(), manifest_, flashed_slot_suffix));
@@ -1718,13 +1737,17 @@
 // Test behavior of ImageManager::Create on low space scenario. These tests assumes image manager
 // uses /data as backup device.
 class ImageManagerTest : public SnapshotTest, public WithParamInterface<uint64_t> {
-  public:
+  protected:
     void SetUp() override {
+        if (!is_virtual_ab_) GTEST_SKIP() << "Test for Virtual A/B devices only";
+
         SnapshotTest::SetUp();
         userdata_ = std::make_unique<LowSpaceUserdata>();
         ASSERT_TRUE(userdata_->Init(GetParam()));
     }
     void TearDown() override {
+        if (!is_virtual_ab_) return;
+
         EXPECT_TRUE(!image_manager_->BackingImageExists(kImageName) ||
                     image_manager_->DeleteBackingImage(kImageName));
     }
diff --git a/fs_mgr/tests/fs_mgr_test.cpp b/fs_mgr/tests/fs_mgr_test.cpp
index c5adea6..800ad7e 100644
--- a/fs_mgr/tests/fs_mgr_test.cpp
+++ b/fs_mgr/tests/fs_mgr_test.cpp
@@ -413,7 +413,7 @@
         EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     }
     EXPECT_EQ("", entry->key_loc);
-    EXPECT_EQ("", entry->key_dir);
+    EXPECT_EQ("", entry->metadata_key_dir);
     EXPECT_EQ(0, entry->length);
     EXPECT_EQ("", entry->label);
     EXPECT_EQ(-1, entry->partnum);
@@ -440,7 +440,7 @@
         EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     }
     EXPECT_EQ("", entry->key_loc);
-    EXPECT_EQ("", entry->key_dir);
+    EXPECT_EQ("", entry->metadata_key_dir);
     EXPECT_EQ(0, entry->length);
     EXPECT_EQ("", entry->label);
     EXPECT_EQ(-1, entry->partnum);
@@ -892,7 +892,24 @@
     FstabEntry::FsMgrFlags flags = {};
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
 
-    EXPECT_EQ("/dir/key", entry->key_dir);
+    EXPECT_EQ("/dir/key", entry->metadata_key_dir);
+}
+
+TEST(fs_mgr, ReadFstabFromFile_FsMgrOptions_MetadataCipher) {
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    std::string fstab_contents = R"fs(
+source none0       swap   defaults      keydirectory=/dir/key,metadata_cipher=adiantum
+)fs";
+
+    ASSERT_TRUE(android::base::WriteStringToFile(fstab_contents, tf.path));
+
+    Fstab fstab;
+    EXPECT_TRUE(ReadFstabFromFile(tf.path, &fstab));
+    ASSERT_EQ(1U, fstab.size());
+
+    auto entry = fstab.begin();
+    EXPECT_EQ("adiantum", entry->metadata_cipher);
 }
 
 TEST(fs_mgr, ReadFstabFromFile_FsMgrOptions_SysfsPath) {
diff --git a/healthd/charger.cpp b/healthd/charger.cpp
index 58ed416..d03978d 100644
--- a/healthd/charger.cpp
+++ b/healthd/charger.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <android-base/logging.h>
+
 #include "charger.sysprop.h"
 #include "healthd_mode_charger.h"
 #include "healthd_mode_charger_nops.h"
@@ -23,6 +25,7 @@
 #endif
 
 int main(int argc, char** argv) {
+    android::base::InitLogging(argv, &android::base::KernelLogger);
     if (CHARGER_FORCE_NO_UI || android::sysprop::ChargerProperties::no_ui().value_or(false)) {
         return healthd_charger_nops(argc, argv);
     } else {
diff --git a/healthd/charger_utils.cpp b/healthd/charger_utils.cpp
index 0cf9df5..8bbfb4e 100644
--- a/healthd/charger_utils.cpp
+++ b/healthd/charger_utils.cpp
@@ -17,50 +17,28 @@
 #include "charger_utils.h"
 
 #include <android-base/logging.h>
-#include <android/hidl/manager/1.0/IServiceManager.h>
+#include <android/hardware/health/2.1/IHealth.h>
 #include <health/utils.h>
 #include <health2impl/Health.h>
-#include <hidl/ServiceManagement.h>
-
-using android::hardware::getPassthroughServiceManager;
-using android::hidl::base::V1_0::IBase;
-using android::hidl::manager::V1_0::IServiceManager;
 
 namespace android {
 namespace hardware {
 namespace health {
-sp<V2_1::IHealth> GetPassthroughHealthImpl() {
-    // Not using getService() because there is no hwservicemanager in charger mode.
-    sp<IServiceManager> pm = getPassthroughServiceManager();
-    if (pm == nullptr) {
-        LOG(WARNING) << "Cannot get passthrough service manager.";
-        return nullptr;
-    }
-    sp<IBase> base = pm->get(V2_0::IHealth::descriptor, "default");
-    if (base == nullptr) {
-        LOG(WARNING) << "Cannot find passthrough implementation of health 2.0 HAL for instance "
-                        "'default' on the device.";
-        return nullptr;
-    }
-    sp<V2_1::IHealth> service = V2_1::IHealth::castFrom(base);
-    if (service == nullptr) {
-        LOG(WARNING)
-                << "Cannot cast passthrough implementation of health 2.0 HAL to 2.1 for instance "
-                   "'default' on the device.";
-        return nullptr;
-    }
-    return service;
-}
 
-sp<V2_1::IHealth> GetPassthroughHealth() {
-    auto impl = GetPassthroughHealthImpl();
-    if (impl == nullptr) {
+sp<V2_1::IHealth> GetHealthServiceOrDefault() {
+    // No need to use get_health_service from libhealthhalutils that
+    // checks for "backup" instance provided by healthd, since
+    // V2_1::implementation::Health does the same thing.
+    sp<V2_1::IHealth> service = V2_1::IHealth::getService();
+    if (service != nullptr) {
+        LOG(INFO) << "Charger uses health HAL service.";
+    } else {
         LOG(WARNING) << "Charger uses system defaults.";
         auto config = std::make_unique<healthd_config>();
         InitHealthdConfig(config.get());
-        impl = new V2_1::implementation::Health(std::move(config));
+        service = new V2_1::implementation::Health(std::move(config));
     }
-    return impl;
+    return service;
 }
 
 }  // namespace health
diff --git a/healthd/charger_utils.h b/healthd/charger_utils.h
index f96e827..39d8aab 100644
--- a/healthd/charger_utils.h
+++ b/healthd/charger_utils.h
@@ -21,7 +21,9 @@
 namespace android {
 namespace hardware {
 namespace health {
-sp<V2_1::IHealth> GetPassthroughHealth();
+// Return health HAL service. If it is not supported on the device (with
+// VINTF checks), return a default passthrough implementation.
+sp<V2_1::IHealth> GetHealthServiceOrDefault();
 }  // namespace health
 }  // namespace hardware
 }  // namespace android
diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp
index 7d844c9..386ba1a 100644
--- a/healthd/healthd_mode_charger.cpp
+++ b/healthd/healthd_mode_charger.cpp
@@ -60,7 +60,7 @@
 
 using namespace android;
 using android::hardware::Return;
-using android::hardware::health::GetPassthroughHealth;
+using android::hardware::health::GetHealthServiceOrDefault;
 using android::hardware::health::HealthLoop;
 using android::hardware::health::V1_0::BatteryStatus;
 using android::hardware::health::V2_0::Result;
@@ -742,6 +742,6 @@
         }
     }
 
-    Charger charger(GetPassthroughHealth());
+    Charger charger(GetHealthServiceOrDefault());
     return charger.StartLoop();
 }
diff --git a/healthd/healthd_mode_charger_nops.cpp b/healthd/healthd_mode_charger_nops.cpp
index 13e7348..9fe381e 100644
--- a/healthd/healthd_mode_charger_nops.cpp
+++ b/healthd/healthd_mode_charger_nops.cpp
@@ -20,10 +20,10 @@
 
 #include "charger_utils.h"
 
-using android::hardware::health::GetPassthroughHealth;
+using android::hardware::health::GetHealthServiceOrDefault;
 using android::hardware::health::V2_1::implementation::HalHealthLoop;
 
 int healthd_charger_nops(int /* argc */, char** /* argv */) {
-    HalHealthLoop charger("charger", GetPassthroughHealth());
+    HalHealthLoop charger("charger", GetHealthServiceOrDefault());
     return charger.StartLoop();
 }
diff --git a/init/builtins.cpp b/init/builtins.cpp
index c877590..742e089 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -1123,6 +1123,7 @@
     auto reboot_reason = vdc_arg + "_failed";
     if (android::sysprop::InitProperties::userspace_reboot_in_progress().value_or(false)) {
         should_reboot_into_recovery = false;
+        reboot_reason = "userspace_failed," + vdc_arg;
     }
 
     auto reboot = [reboot_reason, should_reboot_into_recovery](const std::string& message) {
@@ -1159,7 +1160,7 @@
     }
     // TODO(b/135984674): check that fstab contains /data.
     if (auto rc = fs_mgr_remount_userdata_into_checkpointing(&fstab); rc < 0) {
-        trigger_shutdown("reboot,mount-userdata-failed");
+        trigger_shutdown("reboot,mount_userdata_failed");
     }
     if (auto result = queue_fs_event(initial_mount_fstab_return_code, true); !result) {
         return Error() << "queue_fs_event() failed: " << result.error();
diff --git a/init/init.cpp b/init/init.cpp
index a25bf6c..10701da 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -780,18 +780,18 @@
         if (!(waiting_for_prop || Service::is_exec_service_running())) {
             am.ExecuteOneCommand();
         }
-        if (!(waiting_for_prop || Service::is_exec_service_running())) {
-            if (!IsShuttingDown()) {
-                auto next_process_action_time = HandleProcessActions();
+        if (!IsShuttingDown()) {
+            auto next_process_action_time = HandleProcessActions();
 
-                // If there's a process that needs restarting, wake up in time for that.
-                if (next_process_action_time) {
-                    epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
-                            *next_process_action_time - boot_clock::now());
-                    if (*epoll_timeout < 0ms) epoll_timeout = 0ms;
-                }
+            // If there's a process that needs restarting, wake up in time for that.
+            if (next_process_action_time) {
+                epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
+                        *next_process_action_time - boot_clock::now());
+                if (*epoll_timeout < 0ms) epoll_timeout = 0ms;
             }
+        }
 
+        if (!(waiting_for_prop || Service::is_exec_service_running())) {
             // If there's more work to do, wake up again immediately.
             if (am.HasMoreCommands()) epoll_timeout = 0ms;
         }
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 8c90714..8b239fe 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -737,7 +737,7 @@
     auto guard = android::base::make_scope_guard([] {
         // Leave shutdown so that we can handle a full reboot.
         LeaveShutdown();
-        trigger_shutdown("reboot,abort-userspace-reboot");
+        trigger_shutdown("reboot,userspace_failed,shutdown_aborted");
     });
     // Triggering userspace-reboot-requested will result in a bunch of setprop
     // actions. We should make sure, that all of them are propagated before
@@ -831,7 +831,7 @@
     if (!WaitForProperty("sys.boot_completed", "1", timeout)) {
         LOG(ERROR) << "Failed to boot in " << timeout.count() << "ms. Switching to full reboot";
         // In this case device is in a boot loop. Only way to recover is to do dirty reboot.
-        RebootSystem(ANDROID_RB_RESTART2, "userspace-reboot-watchdog-triggered");
+        RebootSystem(ANDROID_RB_RESTART2, "userspace_failed,watchdog_triggered");
     }
     LOG(INFO) << "Device booted, stopping userspace reboot watchdog";
 }
@@ -847,7 +847,7 @@
     if (pid < 0) {
         PLOG(ERROR) << "Failed to fork process for userspace reboot watchdog. Switching to full "
                     << "reboot";
-        trigger_shutdown("reboot,userspace-reboot-failed-to-fork");
+        trigger_shutdown("reboot,userspace_failed,watchdog_fork");
         return;
     }
     if (pid == 0) {
diff --git a/libcutils/include/private/android_filesystem_config.h b/libcutils/include/private/android_filesystem_config.h
index ff6b036..a2d36ff 100644
--- a/libcutils/include/private/android_filesystem_config.h
+++ b/libcutils/include/private/android_filesystem_config.h
@@ -131,6 +131,8 @@
 #define AID_FSVERITY_CERT 1075   /* fs-verity key ownership in keystore */
 #define AID_CREDSTORE 1076       /* identity credential manager service */
 #define AID_EXTERNAL_STORAGE 1077 /* Full external storage access including USB OTG volumes */
+#define AID_EXT_DATA_RW 1078      /* GID for app-private data directories on external storage */
+#define AID_EXT_OBB_RW 1079       /* GID for OBB directories on external storage */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL 2000 /* adb and debug shell user */
diff --git a/libcutils/trace-dev.cpp b/libcutils/trace-dev.cpp
index 2ee39d3..9ca1729 100644
--- a/libcutils/trace-dev.cpp
+++ b/libcutils/trace-dev.cpp
@@ -32,6 +32,10 @@
 {
     atrace_marker_fd = open("/sys/kernel/debug/tracing/trace_marker", O_WRONLY | O_CLOEXEC);
     if (atrace_marker_fd == -1) {
+        atrace_marker_fd = open("/sys/kernel/tracing/trace_marker", O_WRONLY | O_CLOEXEC);
+    }
+
+    if (atrace_marker_fd == -1) {
         ALOGE("Error opening trace file: %s (%d)", strerror(errno), errno);
         atrace_enabled_tags = 0;
     } else {
diff --git a/liblog/include/log/log_main.h b/liblog/include/log/log_main.h
index 64791c2..1bd1c8a 100644
--- a/liblog/include/log/log_main.h
+++ b/liblog/include/log/log_main.h
@@ -56,7 +56,7 @@
 /*
  * Use __VA_ARGS__ if running a static analyzer,
  * to avoid warnings of unused variables in __VA_ARGS__.
- * Use contexpr function in C++ mode, so these macros can be used
+ * Use constexpr function in C++ mode, so these macros can be used
  * in other constexpr functions without warning.
  */
 #ifdef __clang_analyzer__
@@ -131,10 +131,10 @@
  * is -inverted- from the normal assert() semantics.
  */
 #ifndef LOG_ALWAYS_FATAL_IF
-#define LOG_ALWAYS_FATAL_IF(cond, ...)                              \
-  ((__predict_false(cond))                                          \
-       ? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
-       : __FAKE_USE_VA_ARGS(__VA_ARGS__))
+#define LOG_ALWAYS_FATAL_IF(cond, ...)                                                    \
+  ((__predict_false(cond)) ? (__FAKE_USE_VA_ARGS(__VA_ARGS__),                            \
+                              ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__))) \
+                           : ((void)0))
 #endif
 
 #ifndef LOG_ALWAYS_FATAL
@@ -213,9 +213,10 @@
 #if LOG_NDEBUG
 #define ALOGV_IF(cond, ...) __FAKE_USE_VA_ARGS(__VA_ARGS__)
 #else
-#define ALOGV_IF(cond, ...)                                                  \
-  ((__predict_false(cond)) ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
-                           : __FAKE_USE_VA_ARGS(__VA_ARGS__))
+#define ALOGV_IF(cond, ...)                                                               \
+  ((__predict_false(cond))                                                                \
+       ? (__FAKE_USE_VA_ARGS(__VA_ARGS__), (void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
+       : ((void)0))
 #endif
 #endif
 
@@ -227,9 +228,10 @@
 #endif
 
 #ifndef ALOGD_IF
-#define ALOGD_IF(cond, ...)                                                \
-  ((__predict_false(cond)) ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
-                           : __FAKE_USE_VA_ARGS(__VA_ARGS__))
+#define ALOGD_IF(cond, ...)                                                             \
+  ((__predict_false(cond))                                                              \
+       ? (__FAKE_USE_VA_ARGS(__VA_ARGS__), (void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
+       : ((void)0))
 #endif
 
 /*
@@ -240,9 +242,10 @@
 #endif
 
 #ifndef ALOGI_IF
-#define ALOGI_IF(cond, ...)                                               \
-  ((__predict_false(cond)) ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
-                           : __FAKE_USE_VA_ARGS(__VA_ARGS__))
+#define ALOGI_IF(cond, ...)                                                            \
+  ((__predict_false(cond))                                                             \
+       ? (__FAKE_USE_VA_ARGS(__VA_ARGS__), (void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
+       : ((void)0))
 #endif
 
 /*
@@ -253,9 +256,10 @@
 #endif
 
 #ifndef ALOGW_IF
-#define ALOGW_IF(cond, ...)                                               \
-  ((__predict_false(cond)) ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
-                           : __FAKE_USE_VA_ARGS(__VA_ARGS__))
+#define ALOGW_IF(cond, ...)                                                            \
+  ((__predict_false(cond))                                                             \
+       ? (__FAKE_USE_VA_ARGS(__VA_ARGS__), (void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
+       : ((void)0))
 #endif
 
 /*
@@ -266,9 +270,10 @@
 #endif
 
 #ifndef ALOGE_IF
-#define ALOGE_IF(cond, ...)                                                \
-  ((__predict_false(cond)) ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
-                           : __FAKE_USE_VA_ARGS(__VA_ARGS__))
+#define ALOGE_IF(cond, ...)                                                             \
+  ((__predict_false(cond))                                                              \
+       ? (__FAKE_USE_VA_ARGS(__VA_ARGS__), (void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
+       : ((void)0))
 #endif
 
 /* --------------------------------------------------------------------- */
diff --git a/libmetricslogger/Android.bp b/libmetricslogger/Android.bp
deleted file mode 100644
index 7d7554b..0000000
--- a/libmetricslogger/Android.bp
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2017 The Android Open Source Project
-
-metricslogger_lib_src_files = [
-    "metrics_logger.cpp",
-]
-
-cc_defaults {
-    name: "metricslogger_defaults",
-
-    host_supported: true,
-
-    export_include_dirs: ["include"],
-    local_include_dirs: ["include"],
-    shared_libs: [
-        "libbase",
-        "liblog",
-        "libstatssocket",
-    ],
-    whole_static_libs: ["libgtest_prod"],
-
-    cflags: [
-        "-Wall",
-        "-Wextra",
-        "-Werror",
-    ],
-}
-
-// metricslogger shared library
-// -----------------------------------------------------------------------------
-cc_library {
-    name: "libmetricslogger",
-    srcs: metricslogger_lib_src_files,
-    defaults: ["metricslogger_defaults"],
-    export_shared_lib_headers: ["libstatssocket"],
-}
-
-// metricslogger shared library, debug
-// -----------------------------------------------------------------------------
-cc_library_shared {
-    name: "libmetricslogger_debug",
-    srcs: metricslogger_lib_src_files,
-    defaults: ["metricslogger_defaults"],
-
-    target: {
-        host: {
-            cflags: ["-UNDEBUG"],
-        },
-    },
-}
-
-// Native tests
-// -----------------------------------------------------------------------------
-cc_test {
-    name: "metricslogger_tests",
-    isolated: true,
-    defaults: ["metricslogger_defaults"],
-    shared_libs: [
-        "libbase",
-        "libmetricslogger_debug",
-    ],
-    srcs: [
-        "metrics_logger_test.cpp",
-    ],
-}
diff --git a/libmetricslogger/OWNERS b/libmetricslogger/OWNERS
deleted file mode 100644
index 6a6fba2..0000000
--- a/libmetricslogger/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-cwren@google.com
-jhawkins@google.com
diff --git a/libmetricslogger/include/metricslogger/metrics_logger.h b/libmetricslogger/include/metricslogger/metrics_logger.h
deleted file mode 100644
index 71c04a6..0000000
--- a/libmetricslogger/include/metricslogger/metrics_logger.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <log/log_event_list.h>
-#include <stats_event_list.h>
-#include <cstdint>
-#include <string>
-
-namespace android {
-namespace metricslogger {
-
-// Logs a Tron histogram metric named |event| containing |data| to the Tron log
-// buffer.
-void LogHistogram(const std::string& event, int32_t data);
-
-// Logs a Tron counter metric named |name| containing |val| count to the Tron
-// log buffer.
-void LogCounter(const std::string& name, int32_t val);
-
-// Logs a Tron multi_action with category|category| containing the string
-// |value| in the field |field|.
-void LogMultiAction(int32_t category, int32_t field, const std::string& value);
-
-// Logs a Tron complex event.
-//
-// A complex event can include data in a structure not suppored by the other
-// log event types above.
-//
-// Note that instances of this class are single use. You must call Record()
-// to write the event to the event log.
-class ComplexEventLogger {
-  private:
-    android_log_event_list logger;
-    stats_event_list stats_logger;
-
-  public:
-    // Create a complex event with category|category|.
-    explicit ComplexEventLogger(int category);
-    // Set the package name that this event originates from.
-    void SetPackageName(const std::string& package_name);
-    // Add tagged data to the event, with the given tag and integer value.
-    void AddTaggedData(int tag, int32_t value);
-    // Add tagged data to the event, with the given tag and string value.
-    void AddTaggedData(int tag, const std::string& value);
-    // Add tagged data to the event, with the given tag and integer value.
-    void AddTaggedData(int tag, int64_t value);
-    // Add tagged data to the event, with the given tag and float value.
-    void AddTaggedData(int tag, float value);
-    // Record this event. This method can only be used once per instance
-    // of ComplexEventLogger. Do not made any subsequent calls to AddTaggedData
-    // after recording an event.
-    void Record();
-};
-
-// TODO: replace these with the metric_logger.proto definitions
-enum {
-    LOGBUILDER_CATEGORY = 757,
-    LOGBUILDER_TYPE = 758,
-    LOGBUILDER_NAME = 799,
-    LOGBUILDER_BUCKET = 801,
-    LOGBUILDER_VALUE = 802,
-    LOGBUILDER_COUNTER = 803,
-    LOGBUILDER_HISTOGRAM = 804,
-    LOGBUILDER_PACKAGENAME = 806,
-
-    ACTION_BOOT = 1098,
-    FIELD_PLATFORM_REASON = 1099,
-
-    FIELD_DURATION_MILLIS = 1304,
-
-    FIELD_END_BATTERY_PERCENT = 1308,
-
-    ACTION_HIDDEN_API_ACCESSED = 1391,
-    FIELD_HIDDEN_API_ACCESS_METHOD = 1392,
-    FIELD_HIDDEN_API_ACCESS_DENIED = 1393,
-    FIELD_HIDDEN_API_SIGNATURE = 1394,
-
-    ACTION_USB_CONNECTOR_CONNECTED = 1422,
-    ACTION_USB_CONNECTOR_DISCONNECTED = 1423,
-    ACTION_USB_AUDIO_CONNECTED = 1424,
-    FIELD_USB_AUDIO_VIDPID = 1425,
-    ACTION_USB_AUDIO_DISCONNECTED = 1426,
-    ACTION_HARDWARE_FAILED = 1427,
-    FIELD_HARDWARE_TYPE = 1428,
-    FIELD_HARDWARE_FAILURE_CODE = 1429,
-    ACTION_PHYSICAL_DROP = 1430,
-    FIELD_CONFIDENCE_PERCENT = 1431,
-    FIELD_ACCEL_MILLI_G = 1432,
-    ACTION_BATTERY_HEALTH = 1433,
-    FIELD_BATTERY_HEALTH_SNAPSHOT_TYPE = 1434,
-    FIELD_BATTERY_TEMPERATURE_DECI_C = 1435,
-    FIELD_BATTERY_VOLTAGE_UV = 1436,
-    FIELD_BATTERY_OPEN_CIRCUIT_VOLTAGE_UV = 1437,
-    ACTION_BATTERY_CHARGE_CYCLES = 1438,
-    FIELD_BATTERY_CHARGE_CYCLES = 1439,
-
-    ACTION_SLOW_IO = 1442,
-    FIELD_IO_OPERATION_TYPE = 1443,
-    FIELD_IO_OPERATION_COUNT = 1444,
-    ACTION_SPEAKER_IMPEDANCE = 1445,
-    FIELD_SPEAKER_IMPEDANCE_MILLIOHMS = 1446,
-    FIELD_SPEAKER_LOCATION = 1447,
-    FIELD_BATTERY_RESISTANCE_UOHMS = 1448,
-    FIELD_BATTERY_CURRENT_UA = 1449,
-    FIELD_HARDWARE_LOCATION = 1450,
-    ACTION_BATTERY_CAUSED_SHUTDOWN = 1451,
-};
-
-enum {
-    TYPE_ACTION = 4,
-};
-
-enum {
-    ACCESS_METHOD_NONE = 0,
-    ACCESS_METHOD_REFLECTION = 1,
-    ACCESS_METHOD_JNI = 2,
-    ACCESS_METHOD_LINKING = 3,
-};
-
-enum HardwareType {
-    HARDWARE_UNKNOWN = 0,
-    HARDWARE_MICROPHONE = 1,
-    HARDWARE_CODEC = 2,
-    HARDWARE_SPEAKER = 3,
-    HARDWARE_FINGERPRINT = 4,
-};
-
-enum HardwareFailureCode {
-    HARDWARE_FAILURE_UNKNOWN = 0,
-    HARDWARE_FAILURE_COMPLETE = 1,
-    HARDWARE_FAILURE_SPEAKER_HIGH_Z = 2,
-    HARDWARE_FAILURE_SPEAKER_SHORT = 3,
-    HARDWARE_FAILURE_FINGERPRINT_SENSOR_BROKEN = 4,
-    HARDWARE_FAILURE_FINGERPRINT_TOO_MANY_DEAD_PIXELS = 5,
-};
-
-enum IoOperation {
-    IOOP_UNKNOWN = 0,
-    IOOP_READ = 1,
-    IOOP_WRITE = 2,
-    IOOP_UNMAP = 3,
-    IOOP_SYNC = 4,
-};
-
-}  // namespace metricslogger
-}  // namespace android
diff --git a/libmetricslogger/metrics_logger.cpp b/libmetricslogger/metrics_logger.cpp
deleted file mode 100644
index 2a1b137..0000000
--- a/libmetricslogger/metrics_logger.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "metricslogger/metrics_logger.h"
-
-#include <cstdlib>
-
-#include <android-base/chrono_utils.h>
-#include <log/event_tag_map.h>
-
-using namespace android;
-
-namespace {
-
-const static int kStatsEventTag = 1937006964;
-const static int kKeyValuePairAtomId = 83;
-#ifdef __ANDROID__
-EventTagMap* kEventTagMap = android_openEventTagMap(nullptr);
-const int kSysuiMultiActionTag = android_lookupEventTagNum(
-    kEventTagMap, "sysui_multi_action", "(content|4)", ANDROID_LOG_UNKNOWN);
-#else
-// android_openEventTagMap does not work on host builds.
-const int kSysuiMultiActionTag = 0;
-#endif
-
-int64_t getElapsedTimeNanoSinceBoot() {
-    return std::chrono::duration_cast<std::chrono::nanoseconds>(
-                   android::base::boot_clock::now().time_since_epoch())
-            .count();
-}
-
-}  // namespace
-
-namespace android {
-namespace metricslogger {
-
-// Mirror com.android.internal.logging.MetricsLogger#histogram().
-void LogHistogram(const std::string& event, int32_t data) {
-    android_log_event_list log(kSysuiMultiActionTag);
-    log << LOGBUILDER_CATEGORY << LOGBUILDER_HISTOGRAM << LOGBUILDER_NAME << event
-        << LOGBUILDER_BUCKET << data << LOGBUILDER_VALUE << 1 << LOG_ID_EVENTS;
-
-    stats_event_list stats_log(kStatsEventTag);
-    stats_log << getElapsedTimeNanoSinceBoot() << kKeyValuePairAtomId << LOGBUILDER_CATEGORY
-              << LOGBUILDER_HISTOGRAM << LOGBUILDER_NAME << event << LOGBUILDER_BUCKET << data
-              << LOGBUILDER_VALUE << 1;
-    stats_log.write(LOG_ID_STATS);
-}
-
-// Mirror com.android.internal.logging.MetricsLogger#count().
-void LogCounter(const std::string& name, int32_t val) {
-    android_log_event_list log(kSysuiMultiActionTag);
-    log << LOGBUILDER_CATEGORY << LOGBUILDER_COUNTER << LOGBUILDER_NAME << name << LOGBUILDER_VALUE
-        << val << LOG_ID_EVENTS;
-
-    stats_event_list stats_log(kStatsEventTag);
-    stats_log << getElapsedTimeNanoSinceBoot() << kKeyValuePairAtomId << LOGBUILDER_CATEGORY
-              << LOGBUILDER_COUNTER << LOGBUILDER_NAME << name << LOGBUILDER_VALUE << val;
-    stats_log.write(LOG_ID_STATS);
-}
-
-// Mirror com.android.internal.logging.MetricsLogger#action().
-void LogMultiAction(int32_t category, int32_t field, const std::string& value) {
-    android_log_event_list log(kSysuiMultiActionTag);
-    log << LOGBUILDER_CATEGORY << category << LOGBUILDER_TYPE << TYPE_ACTION
-        << field << value << LOG_ID_EVENTS;
-
-    stats_event_list stats_log(kStatsEventTag);
-    stats_log << getElapsedTimeNanoSinceBoot() << kKeyValuePairAtomId << LOGBUILDER_CATEGORY
-              << category << LOGBUILDER_TYPE << TYPE_ACTION << field << value;
-    stats_log.write(LOG_ID_STATS);
-}
-
-ComplexEventLogger::ComplexEventLogger(int category)
-    : logger(kSysuiMultiActionTag), stats_logger(kStatsEventTag) {
-    logger << LOGBUILDER_CATEGORY << category;
-    stats_logger << getElapsedTimeNanoSinceBoot() << kKeyValuePairAtomId << LOGBUILDER_CATEGORY
-                 << category;
-}
-
-void ComplexEventLogger::SetPackageName(const std::string& package_name) {
-    logger << LOGBUILDER_PACKAGENAME << package_name;
-    stats_logger << LOGBUILDER_PACKAGENAME << package_name;
-}
-
-void ComplexEventLogger::AddTaggedData(int tag, int32_t value) {
-    logger << tag << value;
-    stats_logger << tag << value;
-}
-
-void ComplexEventLogger::AddTaggedData(int tag, const std::string& value) {
-    logger << tag << value;
-    stats_logger << tag << value;
-}
-
-void ComplexEventLogger::AddTaggedData(int tag, int64_t value) {
-    logger << tag << value;
-    stats_logger << tag << value;
-}
-
-void ComplexEventLogger::AddTaggedData(int tag, float value) {
-    logger << tag << value;
-    stats_logger << tag << value;
-}
-
-void ComplexEventLogger::Record() {
-    logger << LOG_ID_EVENTS;
-    stats_logger.write(LOG_ID_STATS);
-}
-
-}  // namespace metricslogger
-}  // namespace android
diff --git a/libmetricslogger/metrics_logger_test.cpp b/libmetricslogger/metrics_logger_test.cpp
deleted file mode 100644
index 440645c..0000000
--- a/libmetricslogger/metrics_logger_test.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2016 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 "metricslogger/metrics_logger.h"
-
-#include <gtest/gtest.h>
-
-TEST(MetricsLoggerTest, AddSingleBootEvent) {
-    android::metricslogger::LogHistogram("test_event", 42);
-    // TODO(jhawkins): Verify the EventLog is updated.
-}
-
-TEST(MetricsLoggerTest, AddCounterVal) {
-    android::metricslogger::LogCounter("test_count", 10);
-}
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 5f4b8c3..fc04b8f 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -32,6 +32,10 @@
     # cgroup for system_server and surfaceflinger
     mkdir /dev/memcg/system 0550 system system
 
+    # symlink the Android specific /dev/tun to Linux expected /dev/net/tun
+    mkdir /dev/net 0755 root root
+    symlink ../tun /dev/net/tun
+
     # set RLIMIT_NICE to allow priorities from 19 to -20
     setrlimit nice 40 40
 
@@ -174,10 +178,10 @@
 
     # Prepare directories for pass through processes
     mkdir /mnt/pass_through 0700 root root
-    mkdir /mnt/pass_through/0 0755 root root
-    mkdir /mnt/pass_through/0/self 0755 root root
-    mkdir /mnt/pass_through/0/emulated 0755 root root
-    mkdir /mnt/pass_through/0/emulated/0 0755 root root
+    mkdir /mnt/pass_through/0 0710 root media_rw
+    mkdir /mnt/pass_through/0/self 0710 root media_rw
+    mkdir /mnt/pass_through/0/emulated 0710 root media_rw
+    mkdir /mnt/pass_through/0/emulated/0 0710 root media_rw
 
     mkdir /mnt/expand 0771 system system
     mkdir /mnt/appfuse 0711 root root
@@ -721,6 +725,12 @@
 
     init_user0
 
+    # Allow apexd to snapshot and restore device encrypted apex data in the case
+    # of a rollback. This should be done immediately after DE_user data keys
+    # are loaded. APEXes should not access this data until this has been
+    # completed.
+    exec_start apexd-snapshotde
+
     # Set SELinux security contexts on upgrade or policy update.
     restorecon --recursive --skip-ce /data
 
diff --git a/rootdir/init.usb.rc b/rootdir/init.usb.rc
index 02d34ba..27b05ec 100644
--- a/rootdir/init.usb.rc
+++ b/rootdir/init.usb.rc
@@ -138,5 +138,4 @@
 
 on userspace-reboot-requested
   setprop sys.usb.config ""
-  setprop sys.usb.configfs ""
   setprop sys.usb.state ""