Merge "Make libstatspull_bindgen available to resolv apex."
diff --git a/bootstat/boot_reason_test.sh b/bootstat/boot_reason_test.sh
index 299b5d4..845b303 100755
--- a/bootstat/boot_reason_test.sh
+++ b/bootstat/boot_reason_test.sh
@@ -367,8 +367,6 @@
   adb logcat -b all ${timestamp} |
   grep bootstat[^e] |
   grep -v -F "bootstat: Service started: /system/bin/bootstat --record_boot_complete${match}
-bootstat: Failed to read /data/misc/bootstat/post_decrypt_time_elapsed: No such file or directory
-bootstat: Failed to parse boot time record: /data/misc/bootstat/post_decrypt_time_elapsed
 bootstat: Service started: /system/bin/bootstat --record_boot_reason
 bootstat: Service started: /system/bin/bootstat --set_system_boot_reason
 bootstat: Service started: /system/bin/bootstat --record_time_since_factory_reset
@@ -388,7 +386,6 @@
 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.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:
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index 589b99a..844357c 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -67,15 +67,9 @@
     {"boot_complete",
      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE}},
-    {"boot_decryption_complete",
-     {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
-      android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_ENCRYPTION}},
     {"boot_complete_no_encryption",
      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_NO_ENCRYPTION}},
-    {"boot_complete_post_decrypt",
-     {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
-      android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__BOOT_COMPLETE_POST_DECRYPT}},
     {"factory_reset_boot_complete",
      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE}},
@@ -83,22 +77,12 @@
      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
       android::util::
           BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE_NO_ENCRYPTION}},
-    {"factory_reset_boot_complete_post_decrypt",
-     {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
-      android::util::
-          BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FACTORY_RESET_BOOT_COMPLETE_POST_DECRYPT}},
     {"ota_boot_complete",
      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE}},
     {"ota_boot_complete_no_encryption",
      {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
       android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE_NO_ENCRYPTION}},
-    {"ota_boot_complete_post_decrypt",
-     {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
-      android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__OTA_BOOT_COMPLETE_POST_DECRYPT}},
-    {"post_decrypt_time_elapsed",
-     {android::util::BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
-      android::util::BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__POST_DECRYPT}},
     // DURATION
     {"absolute_boot_time",
      {android::util::BOOT_TIME_EVENT_DURATION_REPORTED,
@@ -1313,8 +1297,7 @@
   return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
 }
 
-// Records several metrics related to the time it takes to boot the device,
-// including disambiguating boot time on encrypted or non-encrypted devices.
+// Records several metrics related to the time it takes to boot the device.
 void RecordBootComplete() {
   BootEventRecordStore boot_event_store;
   BootEventRecordStore::BootEventRecord record;
@@ -1341,25 +1324,15 @@
     return;
   }
 
-  // post_decrypt_time_elapsed is only logged on encrypted devices.
-  if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
-    // Log the amount of time elapsed until the device is decrypted, which
-    // includes the variable amount of time the user takes to enter the
-    // decryption password.
-    boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
+  // The *_no_encryption events are emitted unconditionally, since they are left
+  // over from a time when encryption meant "full-disk encryption".  But Android
+  // now always uses file-based encryption instead of full-disk encryption.  At
+  // some point, these misleading and redundant events should be removed.
+  boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
+                                         uptime_s.count());
 
-    // Subtract the decryption time to normalize the boot cycle timing.
-    std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
-    boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
-                                           boot_complete.count());
-  } else {
-    boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
-                                           uptime_s.count());
-  }
-
-  // Record the total time from device startup to boot complete, regardless of
-  // encryption state.
-  // Note: we are recording seconds here even though the field in statsd atom specifies
+  // Record the total time from device startup to boot complete.  Note: we are
+  // recording seconds here even though the field in statsd atom specifies
   // milliseconds.
   boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
 
diff --git a/bootstat/bootstat.rc b/bootstat/bootstat.rc
index a350fe7..23f01d1 100644
--- a/bootstat/bootstat.rc
+++ b/bootstat/bootstat.rc
@@ -33,7 +33,6 @@
     chown system log /data/misc/bootstat/last_boot_time_utc
     chown system log /data/misc/bootstat/ota_boot_complete
     chown system log /data/misc/bootstat/ota_boot_complete_no_encryption
-    chown system log /data/misc/bootstat/post_decrypt_time_elapsed
     chown system log /data/misc/bootstat/ro.boottime.init
     chown system log /data/misc/bootstat/ro.boottime.init.cold_boot_wait
     chown system log /data/misc/bootstat/ro.boottime.init.selinux
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 55770f1..c64de0e 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -103,9 +103,15 @@
 static bool is_permissive_mte() {
   // Environment variable for testing or local use from shell.
   char* permissive_env = getenv("MTE_PERMISSIVE");
+  char process_sysprop_name[512];
+  async_safe_format_buffer(process_sysprop_name, sizeof(process_sysprop_name),
+                           "persist.device_config.memory_safety_native.permissive.process.%s",
+                           getprogname());
   // DO NOT REPLACE this with GetBoolProperty. That uses std::string which allocates, so it is
   // not async-safe (and this functiong gets used in a signal handler).
   return property_parse_bool("persist.sys.mte.permissive") ||
+         property_parse_bool("persist.device_config.memory_safety_native.permissive.default") ||
+         property_parse_bool(process_sysprop_name) ||
          (permissive_env && ParseBool(permissive_env) == ParseBoolResult::kTrue);
 }
 
diff --git a/fastboot/device/commands.cpp b/fastboot/device/commands.cpp
index 823783e..3799d1f 100644
--- a/fastboot/device/commands.cpp
+++ b/fastboot/device/commands.cpp
@@ -40,6 +40,8 @@
 #include <storage_literals/storage_literals.h>
 #include <uuid/uuid.h>
 
+#include <bootloader_message/bootloader_message.h>
+
 #include "BootControlClient.h"
 #include "constants.h"
 #include "fastboot_device.h"
@@ -154,6 +156,14 @@
     return true;
 }
 
+static void PostWipeData() {
+    std::string err;
+    // Reset mte state of device.
+    if (!WriteMiscMemtagMessage({}, &err)) {
+        LOG(ERROR) << "Failed to reset MTE state: " << err;
+    }
+}
+
 const std::unordered_map<std::string, std::function<bool(FastbootDevice*)>> kSpecialVars = {
         {"all", GetVarAll},
         {"dmesg", GetDmesg},
@@ -232,6 +242,7 @@
         //Perform oem PostWipeData if Android userdata partition has been erased
         bool support_oem_postwipedata = false;
         if (partition_name == "userdata") {
+            PostWipeData();
             support_oem_postwipedata = OemPostWipeData(device);
         }
 
@@ -610,6 +621,10 @@
     if (ret < 0) {
         return device->WriteStatus(FastbootResult::FAIL, strerror(-ret));
     }
+    if (partition_name == "userdata") {
+        PostWipeData();
+    }
+
     return device->WriteStatus(FastbootResult::OKAY, "Flashing succeeded");
 }
 
diff --git a/fs_mgr/Android.bp b/fs_mgr/Android.bp
index 49761ac..45cd3c0 100644
--- a/fs_mgr/Android.bp
+++ b/fs_mgr/Android.bp
@@ -254,3 +254,39 @@
         "clean_scratch_files",
     ],
 }
+
+cc_binary {
+    name: "set-verity-state",
+    srcs: ["set-verity-state.cpp"],
+    shared_libs: [
+        "libbase",
+        "libbinder",
+        "libcrypto",
+        "libcrypto_utils",
+        "libfs_mgr_binder",
+        "libutils",
+    ],
+    static_libs: [
+        "libavb_user",
+    ],
+    header_libs: [
+        "libcutils_headers",
+    ],
+
+    cflags: ["-Werror"],
+    cppflags: [
+        "-DALLOW_DISABLE_VERITY=0",
+    ],
+    product_variables: {
+        debuggable: {
+            cppflags: [
+                "-UALLOW_DISABLE_VERITY",
+                "-DALLOW_DISABLE_VERITY=1",
+            ],
+        },
+    },
+    symlinks: [
+        "enable-verity",
+        "disable-verity",
+    ],
+}
diff --git a/fs_mgr/OWNERS b/fs_mgr/OWNERS
index c6f9054..6f1059b 100644
--- a/fs_mgr/OWNERS
+++ b/fs_mgr/OWNERS
@@ -2,3 +2,4 @@
 bowgotsai@google.com
 dvander@google.com
 elsk@google.com
+yochiang@google.com
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 9fe8e18..27137a2 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -22,6 +22,7 @@
 #include <fcntl.h>
 #include <inttypes.h>
 #include <libgen.h>
+#include <selinux/selinux.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -30,6 +31,7 @@
 #include <sys/stat.h>
 #include <sys/swap.h>
 #include <sys/types.h>
+#include <sys/utsname.h>
 #include <sys/wait.h>
 #include <time.h>
 #include <unistd.h>
@@ -2359,3 +2361,49 @@
 
     return true;
 }
+
+bool fs_mgr_filesystem_available(const std::string& filesystem) {
+    std::string filesystems;
+    if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) return false;
+    return filesystems.find("\t" + filesystem + "\n") != std::string::npos;
+}
+
+std::string fs_mgr_get_context(const std::string& mount_point) {
+    char* ctx = nullptr;
+    if (getfilecon(mount_point.c_str(), &ctx) == -1) {
+        PERROR << "getfilecon " << mount_point;
+        return "";
+    }
+
+    std::string context(ctx);
+    free(ctx);
+    return context;
+}
+
+OverlayfsValidResult fs_mgr_overlayfs_valid() {
+    // Overlayfs available in the kernel, and patched for override_creds?
+    if (access("/sys/module/overlay/parameters/override_creds", F_OK) == 0) {
+        return OverlayfsValidResult::kOverrideCredsRequired;
+    }
+    if (!fs_mgr_filesystem_available("overlay")) {
+        return OverlayfsValidResult::kNotSupported;
+    }
+    struct utsname uts;
+    if (uname(&uts) == -1) {
+        return OverlayfsValidResult::kNotSupported;
+    }
+    int major, minor;
+    if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
+        return OverlayfsValidResult::kNotSupported;
+    }
+    if (major < 4) {
+        return OverlayfsValidResult::kOk;
+    }
+    if (major > 4) {
+        return OverlayfsValidResult::kNotSupported;
+    }
+    if (minor > 3) {
+        return OverlayfsValidResult::kNotSupported;
+    }
+    return OverlayfsValidResult::kOk;
+}
diff --git a/fs_mgr/fs_mgr_overlayfs.cpp b/fs_mgr/fs_mgr_overlayfs.cpp
index 1d5a04b..df26d85 100644
--- a/fs_mgr/fs_mgr_overlayfs.cpp
+++ b/fs_mgr/fs_mgr_overlayfs.cpp
@@ -56,6 +56,7 @@
 #include <storage_literals/storage_literals.h>
 
 #include "fs_mgr_priv.h"
+#include "fs_mgr_priv_overlayfs.h"
 #include "libfiemap/utility.h"
 
 using namespace std::literals;
@@ -71,62 +72,9 @@
     return access(path.c_str(), F_OK) == 0;
 }
 
-// determine if a filesystem is available
-bool fs_mgr_overlayfs_filesystem_available(const std::string& filesystem) {
-    std::string filesystems;
-    if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) return false;
-    return filesystems.find("\t" + filesystem + "\n") != std::string::npos;
-}
-
 const auto kLowerdirOption = "lowerdir="s;
 const auto kUpperdirOption = "upperdir="s;
 
-}  // namespace
-
-#if ALLOW_ADBD_DISABLE_VERITY == 0  // If we are a user build, provide stubs
-
-bool fs_mgr_wants_overlayfs(FstabEntry*) {
-    return false;
-}
-
-Fstab fs_mgr_overlayfs_candidate_list(const Fstab&) {
-    return {};
-}
-
-bool fs_mgr_overlayfs_mount_all(Fstab*) {
-    return false;
-}
-
-bool fs_mgr_overlayfs_setup(const char*, bool*, bool) {
-    LOG(ERROR) << "Overlayfs remounts can only be used in debuggable builds";
-    return false;
-}
-
-OverlayfsTeardownResult fs_mgr_overlayfs_teardown(const char*, bool*) {
-    return OverlayfsTeardownResult::Ok;
-}
-
-bool fs_mgr_overlayfs_is_setup() {
-    return false;
-}
-
-namespace android {
-namespace fs_mgr {
-
-void MapScratchPartitionIfNeeded(Fstab*, const std::function<bool(const std::set<std::string>&)>&) {
-}
-
-void CleanupOldScratchFiles() {}
-
-void TeardownAllOverlayForMountPoint(const std::string&) {}
-
-}  // namespace fs_mgr
-}  // namespace android
-
-#else  // ALLOW_ADBD_DISABLE_VERITY == 0
-
-namespace {
-
 bool fs_mgr_in_recovery() {
     // Check the existence of recovery binary instead of using the compile time
     // __ANDROID_RECOVERY__ macro.
@@ -234,6 +182,28 @@
     return true;
 }
 
+bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev) {
+    struct statfs fs;
+    if ((statfs((mount_point + "/lost+found").c_str(), &fs) == -1) ||
+        (fs.f_type != EXT4_SUPER_MAGIC)) {
+        return false;
+    }
+
+    android::base::unique_fd fd(open(dev.c_str(), O_RDONLY | O_CLOEXEC));
+    if (fd < 0) return false;
+
+    struct ext4_super_block sb;
+    if ((TEMP_FAILURE_RETRY(lseek64(fd, 1024, SEEK_SET)) < 0) ||
+        (TEMP_FAILURE_RETRY(read(fd, &sb, sizeof(sb))) < 0)) {
+        return false;
+    }
+
+    struct fs_info info;
+    if (ext4_parse_sb(&sb, &info) < 0) return false;
+
+    return (info.feat_ro_compat & EXT4_FEATURE_RO_COMPAT_SHARED_BLOCKS) != 0;
+}
+
 bool fs_mgr_overlayfs_enabled(FstabEntry* entry) {
     // readonly filesystem, can not be mount -o remount,rw
     // for squashfs, erofs or if free space is (near) zero making such a remount
@@ -886,10 +856,10 @@
 
 // Only a suggestion for _first_ try during mounting
 std::string fs_mgr_overlayfs_scratch_mount_type() {
-    if (!access(kMkF2fs.c_str(), X_OK) && fs_mgr_overlayfs_filesystem_available("f2fs")) {
+    if (!access(kMkF2fs.c_str(), X_OK) && fs_mgr_filesystem_available("f2fs")) {
         return "f2fs";
     }
-    if (!access(kMkExt4.c_str(), X_OK) && fs_mgr_overlayfs_filesystem_available("ext4")) {
+    if (!access(kMkExt4.c_str(), X_OK) && fs_mgr_filesystem_available("ext4")) {
         return "ext4";
     }
     return "auto";
@@ -1233,11 +1203,41 @@
     return fs_mgr_overlayfs_mount_scratch(scratch_device, mnt_type);
 }
 
-bool fs_mgr_overlayfs_invalid() {
-    if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) return true;
+#if ALLOW_ADBD_DISABLE_VERITY
+constexpr bool kAllowOverlayfs = true;
+#else
+constexpr bool kAllowOverlayfs = false;
+#endif
 
+// NOTE: OverlayfsSetupAllowed() must be "stricter" than OverlayfsTeardownAllowed().
+// Setup is allowed only if teardown is also allowed.
+bool OverlayfsSetupAllowed(bool verbose = false) {
+    if (!kAllowOverlayfs) {
+        if (verbose) {
+            LOG(ERROR) << "Overlayfs remounts can only be used in debuggable builds";
+        }
+        return false;
+    }
+    // Check mandatory kernel patches.
+    if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) {
+        if (verbose) {
+            LOG(ERROR) << "Kernel does not support overlayfs";
+        }
+        return false;
+    }
     // in recovery or fastbootd, not allowed!
-    return fs_mgr_in_recovery();
+    if (fs_mgr_in_recovery()) {
+        if (verbose) {
+            LOG(ERROR) << "Unsupported overlayfs setup from recovery";
+        }
+        return false;
+    }
+    return true;
+}
+
+constexpr bool OverlayfsTeardownAllowed() {
+    // Never allow on non-debuggable build.
+    return kAllowOverlayfs;
 }
 
 }  // namespace
@@ -1331,29 +1331,28 @@
 }
 
 bool fs_mgr_overlayfs_mount_all(Fstab* fstab) {
-    auto ret = false;
-    if (fs_mgr_overlayfs_invalid()) return ret;
-
+    if (!OverlayfsSetupAllowed()) {
+        return false;
+    }
+    auto ret = true;
     auto scratch_can_be_mounted = true;
     for (const auto& entry : fs_mgr_overlayfs_candidate_list(*fstab)) {
         if (fs_mgr_is_verity_enabled(entry)) continue;
         auto mount_point = fs_mgr_mount_point(entry.mount_point);
         if (fs_mgr_overlayfs_already_mounted(mount_point)) {
-            ret = true;
             continue;
         }
         if (scratch_can_be_mounted) {
             scratch_can_be_mounted = false;
             TryMountScratch();
         }
-        if (fs_mgr_overlayfs_mount(mount_point)) ret = true;
+        ret &= fs_mgr_overlayfs_mount(mount_point);
     }
     return ret;
 }
 
 bool fs_mgr_overlayfs_setup(const char* mount_point, bool* want_reboot, bool just_disabled_verity) {
-    if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) {
-        LOG(ERROR) << "Overlayfs is not supported";
+    if (!OverlayfsSetupAllowed(/*verbose=*/true)) {
         return false;
     }
 
@@ -1523,7 +1522,8 @@
     return true;
 }
 
-OverlayfsTeardownResult TeardownMountsAndScratch(const char* mount_point, bool* want_reboot) {
+static OverlayfsTeardownResult TeardownMountsAndScratch(const char* mount_point,
+                                                        bool* want_reboot) {
     bool should_destroy_scratch = false;
     auto rv = OverlayfsTeardownResult::Ok;
     for (const auto& overlay_mount_point : OverlayMountPoints()) {
@@ -1555,6 +1555,10 @@
 
 // Returns false if teardown not permitted. If something is altered, set *want_reboot.
 OverlayfsTeardownResult fs_mgr_overlayfs_teardown(const char* mount_point, bool* want_reboot) {
+    if (!OverlayfsTeardownAllowed()) {
+        // Nothing to teardown.
+        return OverlayfsTeardownResult::Ok;
+    }
     // If scratch exists, but is not mounted, lets gain access to clean
     // specific override entries.
     auto mount_scratch = false;
@@ -1577,12 +1581,14 @@
 }
 
 bool fs_mgr_overlayfs_is_setup() {
+    if (!OverlayfsSetupAllowed()) {
+        return false;
+    }
     if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) return true;
     Fstab fstab;
     if (!ReadDefaultFstab(&fstab)) {
         return false;
     }
-    if (fs_mgr_overlayfs_invalid()) return false;
     for (const auto& entry : fs_mgr_overlayfs_candidate_list(fstab)) {
         if (fs_mgr_is_verity_enabled(entry)) continue;
         if (fs_mgr_overlayfs_already_mounted(fs_mgr_mount_point(entry.mount_point))) return true;
@@ -1595,7 +1601,7 @@
 
 void MapScratchPartitionIfNeeded(Fstab* fstab,
                                  const std::function<bool(const std::set<std::string>&)>& init) {
-    if (fs_mgr_overlayfs_invalid()) {
+    if (!OverlayfsSetupAllowed()) {
         return;
     }
     if (GetEntryForMountPoint(fstab, kScratchMountPoint) != nullptr) {
@@ -1632,6 +1638,9 @@
 }
 
 void CleanupOldScratchFiles() {
+    if (!OverlayfsTeardownAllowed()) {
+        return;
+    }
     if (!ScratchIsOnData()) {
         return;
     }
@@ -1641,6 +1650,9 @@
 }
 
 void TeardownAllOverlayForMountPoint(const std::string& mount_point) {
+    if (!OverlayfsTeardownAllowed()) {
+        return;
+    }
     if (!fs_mgr_in_recovery()) {
         LERROR << __FUNCTION__ << "(): must be called within recovery.";
         return;
@@ -1701,8 +1713,6 @@
 }  // namespace fs_mgr
 }  // namespace android
 
-#endif  // ALLOW_ADBD_DISABLE_VERITY != 0
-
 bool fs_mgr_overlayfs_already_mounted(const std::string& mount_point, bool overlay_only) {
     Fstab fstab;
     if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
@@ -1722,65 +1732,3 @@
     }
     return false;
 }
-
-bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev) {
-    struct statfs fs;
-    if ((statfs((mount_point + "/lost+found").c_str(), &fs) == -1) ||
-        (fs.f_type != EXT4_SUPER_MAGIC)) {
-        return false;
-    }
-
-    android::base::unique_fd fd(open(dev.c_str(), O_RDONLY | O_CLOEXEC));
-    if (fd < 0) return false;
-
-    struct ext4_super_block sb;
-    if ((TEMP_FAILURE_RETRY(lseek64(fd, 1024, SEEK_SET)) < 0) ||
-        (TEMP_FAILURE_RETRY(read(fd, &sb, sizeof(sb))) < 0)) {
-        return false;
-    }
-
-    struct fs_info info;
-    if (ext4_parse_sb(&sb, &info) < 0) return false;
-
-    return (info.feat_ro_compat & EXT4_FEATURE_RO_COMPAT_SHARED_BLOCKS) != 0;
-}
-
-std::string fs_mgr_get_context(const std::string& mount_point) {
-    char* ctx = nullptr;
-    if (getfilecon(mount_point.c_str(), &ctx) == -1) {
-        PLOG(ERROR) << "getfilecon " << mount_point;
-        return "";
-    }
-
-    std::string context(ctx);
-    free(ctx);
-    return context;
-}
-
-OverlayfsValidResult fs_mgr_overlayfs_valid() {
-    // Overlayfs available in the kernel, and patched for override_creds?
-    if (fs_mgr_access("/sys/module/overlay/parameters/override_creds")) {
-        return OverlayfsValidResult::kOverrideCredsRequired;
-    }
-    if (!fs_mgr_overlayfs_filesystem_available("overlay")) {
-        return OverlayfsValidResult::kNotSupported;
-    }
-    struct utsname uts;
-    if (uname(&uts) == -1) {
-        return OverlayfsValidResult::kNotSupported;
-    }
-    int major, minor;
-    if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
-        return OverlayfsValidResult::kNotSupported;
-    }
-    if (major < 4) {
-        return OverlayfsValidResult::kOk;
-    }
-    if (major > 4) {
-        return OverlayfsValidResult::kNotSupported;
-    }
-    if (minor > 3) {
-        return OverlayfsValidResult::kNotSupported;
-    }
-    return OverlayfsValidResult::kOk;
-}
diff --git a/fs_mgr/fs_mgr_priv.h b/fs_mgr/fs_mgr_priv.h
index c5e477c..46f54cc 100644
--- a/fs_mgr/fs_mgr_priv.h
+++ b/fs_mgr/fs_mgr_priv.h
@@ -99,6 +99,16 @@
 
 bool fs_mgr_teardown_verity(android::fs_mgr::FstabEntry* fstab);
 
+bool fs_mgr_filesystem_available(const std::string& filesystem);
+std::string fs_mgr_get_context(const std::string& mount_point);
+
+enum class OverlayfsValidResult {
+    kNotSupported = 0,
+    kOk,
+    kOverrideCredsRequired,
+};
+OverlayfsValidResult fs_mgr_overlayfs_valid();
+
 namespace android {
 namespace fs_mgr {
 bool UnmapDevice(const std::string& name);
diff --git a/fs_mgr/fs_mgr_priv_overlayfs.h b/fs_mgr/fs_mgr_priv_overlayfs.h
new file mode 100644
index 0000000..45b954d
--- /dev/null
+++ b/fs_mgr/fs_mgr_priv_overlayfs.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <string>
+
+#include <fstab/fstab.h>
+
+bool fs_mgr_overlayfs_already_mounted(const std::string& mount_point, bool overlay_only = true);
+bool fs_mgr_wants_overlayfs(android::fs_mgr::FstabEntry* entry);
+android::fs_mgr::Fstab fs_mgr_overlayfs_candidate_list(const android::fs_mgr::Fstab& fstab);
+
+// If "mount_point" is non-null, set up exactly one overlay.
+// If "mount_point" is null, setup any overlays.
+//
+// If |want_reboot| is non-null, and a reboot is needed to apply overlays, then
+// it will be true on return. The caller is responsible for initializing it.
+bool fs_mgr_overlayfs_setup(const char* mount_point = nullptr, bool* want_reboot = nullptr,
+                            bool just_disabled_verity = true);
+
+enum class OverlayfsTeardownResult {
+    Ok,
+    Busy,  // Indicates that overlays are still in use.
+    Error
+};
+OverlayfsTeardownResult fs_mgr_overlayfs_teardown(const char* mount_point = nullptr,
+                                                  bool* want_reboot = nullptr);
+
+namespace android {
+namespace fs_mgr {
+
+void CleanupOldScratchFiles();
+
+}  // namespace fs_mgr
+}  // namespace android
diff --git a/fs_mgr/fs_mgr_remount.cpp b/fs_mgr/fs_mgr_remount.cpp
index 2202fda..54c1c2c 100644
--- a/fs_mgr/fs_mgr_remount.cpp
+++ b/fs_mgr/fs_mgr_remount.cpp
@@ -42,6 +42,8 @@
 #include <libavb_user/libavb_user.h>
 #include <libgsi/libgsid.h>
 
+#include "fs_mgr_priv_overlayfs.h"
+
 using namespace std::literals;
 using android::fs_mgr::Fstab;
 using android::fs_mgr::FstabEntry;
@@ -451,10 +453,9 @@
     }
 
     // Mount overlayfs.
-    errno = 0;
-    if (!fs_mgr_overlayfs_mount_all(&partitions) && errno) {
-        PLOG(ERROR) << "Can not mount overlayfs for partitions";
-        return BAD_OVERLAY;
+    if (!fs_mgr_overlayfs_mount_all(&partitions)) {
+        LOG(WARNING) << "Cannot mount overlayfs for some partitions";
+        // Continue regardless to handle raw remount case.
     }
 
     // Get actual mounts _after_ overlayfs has been added.
diff --git a/fs_mgr/fs_mgr_vendor_overlay.cpp b/fs_mgr/fs_mgr_vendor_overlay.cpp
index 1372511..6b32b4d 100644
--- a/fs_mgr/fs_mgr_vendor_overlay.cpp
+++ b/fs_mgr/fs_mgr_vendor_overlay.cpp
@@ -25,7 +25,6 @@
 
 #include <android-base/logging.h>
 #include <android-base/properties.h>
-#include <fs_mgr_overlayfs.h>
 #include <fs_mgr_vendor_overlay.h>
 #include <fstab/fstab.h>
 
diff --git a/fs_mgr/include/fs_mgr_overlayfs.h b/fs_mgr/include/fs_mgr_overlayfs.h
index 4d9b13f..bdaabbf 100644
--- a/fs_mgr/include/fs_mgr_overlayfs.h
+++ b/fs_mgr/include/fs_mgr_overlayfs.h
@@ -17,51 +17,21 @@
 #pragma once
 
 #include <functional>
+#include <set>
+#include <string>
 
 #include <fstab/fstab.h>
 
-#include <set>
-#include <string>
-#include <vector>
+// Keep the list short and only add interfaces that must be exported public.
 
-android::fs_mgr::Fstab fs_mgr_overlayfs_candidate_list(const android::fs_mgr::Fstab& fstab);
-
-bool fs_mgr_wants_overlayfs(android::fs_mgr::FstabEntry* entry);
 bool fs_mgr_overlayfs_mount_all(android::fs_mgr::Fstab* fstab);
 bool fs_mgr_overlayfs_is_setup();
-bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev);
-bool fs_mgr_overlayfs_already_mounted(const std::string& mount_point, bool overlay_only = true);
-std::string fs_mgr_get_context(const std::string& mount_point);
-
-// If "mount_point" is non-null, set up exactly one overlay.
-// If "mount_point" is null, setup any overlays.
-//
-// If |want_reboot| is non-null, and a reboot is needed to apply overlays, then
-// it will be true on return. The caller is responsible for initializing it.
-bool fs_mgr_overlayfs_setup(const char* mount_point = nullptr, bool* want_reboot = nullptr,
-                            bool just_disabled_verity = true);
-
-enum class OverlayfsTeardownResult {
-    Ok,
-    Busy,  // Indicates that overlays are still in use.
-    Error
-};
-OverlayfsTeardownResult fs_mgr_overlayfs_teardown(const char* mount_point = nullptr,
-                                                  bool* want_reboot = nullptr);
-
-enum class OverlayfsValidResult {
-    kNotSupported = 0,
-    kOk,
-    kOverrideCredsRequired,
-};
-OverlayfsValidResult fs_mgr_overlayfs_valid();
 
 namespace android {
 namespace fs_mgr {
 
 void MapScratchPartitionIfNeeded(Fstab* fstab,
                                  const std::function<bool(const std::set<std::string>&)>& init);
-void CleanupOldScratchFiles();
 
 // Teardown overlays of all sources (cache dir, scratch device, DSU) for |mount_point|.
 // Teardown all overlays if |mount_point| is empty.
diff --git a/fs_mgr/set-verity-state.cpp b/fs_mgr/set-verity-state.cpp
new file mode 100644
index 0000000..84ee01f
--- /dev/null
+++ b/fs_mgr/set-verity-state.cpp
@@ -0,0 +1,258 @@
+/*
+ * Copyright (C) 2019 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 <getopt.h>
+#include <stdio.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+#include <binder/ProcessState.h>
+#include <cutils/android_reboot.h>
+#include <fs_mgr_overlayfs.h>
+#include <libavb_user/libavb_user.h>
+
+#include "fs_mgr_priv_overlayfs.h"
+
+using namespace std::string_literals;
+
+namespace {
+
+void print_usage() {
+    printf("Usage:\n"
+           "\tdisable-verity\n"
+           "\tenable-verity\n"
+           "\tset-verity-state [0|1]\n"
+           "Options:\n"
+           "\t-h --help\tthis help\n"
+           "\t-R --reboot\tautomatic reboot if needed for new settings to take effect\n"
+           "\t-v --verbose\tbe noisy\n");
+}
+
+#ifdef ALLOW_DISABLE_VERITY
+const bool kAllowDisableVerity = true;
+#else
+const bool kAllowDisableVerity = false;
+#endif
+
+static bool SetupOrTeardownOverlayfs(bool enable) {
+    bool want_reboot = false;
+    if (enable) {
+        if (!fs_mgr_overlayfs_setup(nullptr, &want_reboot)) {
+            LOG(ERROR) << "Overlayfs setup failed.";
+            return want_reboot;
+        }
+        if (want_reboot) {
+            printf("enabling overlayfs\n");
+        }
+    } else {
+        auto rv = fs_mgr_overlayfs_teardown(nullptr, &want_reboot);
+        if (rv == OverlayfsTeardownResult::Error) {
+            LOG(ERROR) << "Overlayfs teardown failed.";
+            return want_reboot;
+        }
+        if (rv == OverlayfsTeardownResult::Busy) {
+            LOG(ERROR) << "Overlayfs is still active until reboot.";
+            return true;
+        }
+        if (want_reboot) {
+            printf("disabling overlayfs\n");
+        }
+    }
+    return want_reboot;
+}
+
+/* Helper function to get A/B suffix, if any. If the device isn't
+ * using A/B the empty string is returned. Otherwise either "_a",
+ * "_b", ... is returned.
+ */
+std::string get_ab_suffix() {
+    return android::base::GetProperty("ro.boot.slot_suffix", "");
+}
+
+bool is_avb_device_locked() {
+    return android::base::GetProperty("ro.boot.vbmeta.device_state", "") == "locked";
+}
+
+bool is_debuggable() {
+    return android::base::GetBoolProperty("ro.debuggable", false);
+}
+
+bool is_using_avb() {
+    // Figure out if we're using VB1.0 or VB2.0 (aka AVB) - by
+    // contract, androidboot.vbmeta.digest is set by the bootloader
+    // when using AVB).
+    return !android::base::GetProperty("ro.boot.vbmeta.digest", "").empty();
+}
+
+[[noreturn]] void reboot(const std::string& name) {
+    LOG(INFO) << "Rebooting device for new settings to take effect";
+    ::sync();
+    android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot," + name);
+    ::sleep(60);
+    LOG(ERROR) << "Failed to reboot";
+    ::exit(1);
+}
+
+struct SetVerityStateResult {
+    bool success = false;
+    bool want_reboot = false;
+};
+
+/* Use AVB to turn verity on/off */
+SetVerityStateResult SetVerityState(bool enable_verity) {
+    std::string ab_suffix = get_ab_suffix();
+    bool verity_enabled = false;
+
+    if (is_avb_device_locked()) {
+        LOG(ERROR) << "Device must be bootloader unlocked to change verity state";
+        return {};
+    }
+
+    std::unique_ptr<AvbOps, decltype(&avb_ops_user_free)> ops(avb_ops_user_new(),
+                                                              &avb_ops_user_free);
+    if (!ops) {
+        LOG(ERROR) << "Error getting AVB ops";
+        return {};
+    }
+
+    if (!avb_user_verity_get(ops.get(), ab_suffix.c_str(), &verity_enabled)) {
+        LOG(ERROR) << "Error getting verity state";
+        return {};
+    }
+
+    if ((verity_enabled && enable_verity) || (!verity_enabled && !enable_verity)) {
+        LOG(INFO) << "Verity is already " << (verity_enabled ? "enabled" : "disabled");
+        return {.success = true, .want_reboot = false};
+    }
+
+    if (!avb_user_verity_set(ops.get(), ab_suffix.c_str(), enable_verity)) {
+        LOG(ERROR) << "Error setting verity state";
+        return {};
+    }
+
+    LOG(INFO) << "Successfully " << (enable_verity ? "enabled" : "disabled") << " verity";
+    return {.success = true, .want_reboot = true};
+}
+
+class MyLogger {
+  public:
+    explicit MyLogger(bool verbose) : verbose_(verbose) {}
+
+    void operator()(android::base::LogId id, android::base::LogSeverity severity, const char* tag,
+                    const char* file, unsigned int line, const char* message) {
+        // Hide log starting with '[fs_mgr]' unless it's an error.
+        if (verbose_ || severity >= android::base::ERROR || message[0] != '[') {
+            fprintf(stderr, "%s\n", message);
+        }
+        logd_(id, severity, tag, file, line, message);
+    }
+
+  private:
+    android::base::LogdLogger logd_;
+    bool verbose_;
+};
+
+}  // namespace
+
+int main(int argc, char* argv[]) {
+    bool auto_reboot = false;
+    bool verbose = false;
+
+    struct option longopts[] = {
+            {"help", no_argument, nullptr, 'h'},
+            {"reboot", no_argument, nullptr, 'R'},
+            {"verbose", no_argument, nullptr, 'v'},
+            {0, 0, nullptr, 0},
+    };
+    for (int opt; (opt = ::getopt_long(argc, argv, "hRv", longopts, nullptr)) != -1;) {
+        switch (opt) {
+            case 'h':
+                print_usage();
+                return 0;
+            case 'R':
+                auto_reboot = true;
+                break;
+            case 'v':
+                verbose = true;
+                break;
+            default:
+                print_usage();
+                return 1;
+        }
+    }
+
+    android::base::InitLogging(argv, MyLogger(verbose));
+
+    bool enable_verity = false;
+    const std::string progname = getprogname();
+    if (progname == "enable-verity") {
+        enable_verity = true;
+    } else if (progname == "disable-verity") {
+        enable_verity = false;
+    } else if (optind < argc && (argv[optind] == "1"s || argv[optind] == "0"s)) {
+        // progname "set-verity-state"
+        enable_verity = (argv[optind] == "1"s);
+    } else {
+        print_usage();
+        return 1;
+    }
+
+    if (!kAllowDisableVerity || !is_debuggable()) {
+        errno = EPERM;
+        PLOG(ERROR) << "Cannot disable/enable verity on user build";
+        return 1;
+    }
+
+    if (getuid() != 0) {
+        errno = EACCES;
+        PLOG(ERROR) << "Must be running as root (adb root)";
+        return 1;
+    }
+
+    if (!is_using_avb()) {
+        LOG(ERROR) << "Expected AVB device, VB1.0 is no longer supported";
+        return 1;
+    }
+
+    int exit_code = 0;
+    bool want_reboot = false;
+
+    auto ret = SetVerityState(enable_verity);
+    if (ret.success) {
+        want_reboot |= ret.want_reboot;
+    } else {
+        exit_code = 1;
+    }
+
+    // Disable any overlayfs unconditionally if we want verity enabled.
+    // Enable overlayfs only if verity is successfully disabled or is already disabled.
+    if (enable_verity || ret.success) {
+        // Start a threadpool to service waitForService() callbacks as
+        // fs_mgr_overlayfs_* might call waitForService() to get the image service.
+        android::ProcessState::self()->startThreadPool();
+        want_reboot |= SetupOrTeardownOverlayfs(!enable_verity);
+    }
+
+    if (want_reboot) {
+        if (auto_reboot) {
+            reboot(progname);
+        }
+        printf("Reboot the device for new settings to take effect\n");
+    }
+
+    return exit_code;
+}
diff --git a/init/Android.bp b/init/Android.bp
index 6255305..f0e362c 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -161,6 +161,7 @@
     },
     static_libs: [
         "libavb",
+        "libbootloader_message",
         "libc++fs",
         "libcgrouprc_format",
         "libfsverity_init",
@@ -181,7 +182,6 @@
     ],
     shared_libs: [
         "libbase",
-        "libbootloader_message",
         "libcrypto",
         "libcutils",
         "libdl",
diff --git a/init/service.cpp b/init/service.cpp
index 8334732..a633048 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -340,9 +340,18 @@
                               siginfo.si_status == BIONIC_SIGNAL_ART_PROFILER && !upgraded_mte_;
 
     if (should_upgrade_mte) {
-        LOG(INFO) << "Upgrading service " << name_ << " to sync MTE";
-        once_environment_vars_.emplace_back("BIONIC_MEMTAG_UPGRADE_SECS", "60");
-        upgraded_mte_ = true;
+        constexpr int kDefaultUpgradeSecs = 60;
+        int secs = GetIntProperty("persist.device_config.memory_safety_native.upgrade_secs.default",
+                                  kDefaultUpgradeSecs);
+        secs = GetIntProperty(
+                "persist.device_config.memory_safety_native.upgrade_secs.service." + name_, secs);
+        if (secs > 0) {
+            LOG(INFO) << "Upgrading service " << name_ << " to sync MTE for " << secs << " seconds";
+            once_environment_vars_.emplace_back("BIONIC_MEMTAG_UPGRADE_SECS", std::to_string(secs));
+            upgraded_mte_ = true;
+        } else {
+            LOG(INFO) << "Not upgrading service " << name_ << " to sync MTE due to device config";
+        }
     }
 #endif
 
diff --git a/libsparse/simg_dump.py b/libsparse/simg_dump.py
index 8811a52..47537ca 100755
--- a/libsparse/simg_dump.py
+++ b/libsparse/simg_dump.py
@@ -158,7 +158,7 @@
           curtype = format("Fill with 0x%08X" % (fill))
           if showhash:
             h = hashlib.sha1()
-            data = fill_bin * (blk_sz / 4);
+            data = fill_bin * (blk_sz // 4);
             for block in range(chunk_sz):
               h.update(data)
             curhash = h.hexdigest()
diff --git a/rootdir/init.zygote64.rc b/rootdir/init.zygote64.rc
index 5bde5f4..b6ca5c0 100644
--- a/rootdir/init.zygote64.rc
+++ b/rootdir/init.zygote64.rc
@@ -1,4 +1,4 @@
-service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
+service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
     class main
     priority -20
     user root
@@ -13,5 +13,5 @@
     onrestart restart media.tuner
     onrestart restart netd
     onrestart restart wificond
-    task_profiles ProcessCapacityHigh
+    task_profiles ProcessCapacityHigh MaxPerformance
     critical window=${zygote.critical_window.minute:-off} target=zygote-fatal
diff --git a/rootdir/init.zygote64_32.rc b/rootdir/init.zygote64_32.rc
index efb30d6..109bf6c 100644
--- a/rootdir/init.zygote64_32.rc
+++ b/rootdir/init.zygote64_32.rc
@@ -1,20 +1,4 @@
-service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
-    class main
-    priority -20
-    user root
-    group root readproc reserved_disk
-    socket zygote stream 660 root system
-    socket usap_pool_primary stream 660 root system
-    onrestart exec_background - system system -- /system/bin/vdc volume abort_fuse
-    onrestart write /sys/power/state on
-    onrestart restart audioserver
-    onrestart restart cameraserver
-    onrestart restart media
-    onrestart restart media.tuner
-    onrestart restart netd
-    onrestart restart wificond
-    task_profiles ProcessCapacityHigh MaxPerformance
-    critical window=${zygote.critical_window.minute:-off} target=zygote-fatal
+import /system/etc/init/hw/init.zygote64.rc
 
 service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload
     class main
diff --git a/set-verity-state/.clang-format b/set-verity-state/.clang-format
deleted file mode 120000
index fd0645f..0000000
--- a/set-verity-state/.clang-format
+++ /dev/null
@@ -1 +0,0 @@
-../.clang-format-2
\ No newline at end of file
diff --git a/set-verity-state/Android.bp b/set-verity-state/Android.bp
deleted file mode 100644
index f40118b..0000000
--- a/set-verity-state/Android.bp
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2019 The Android Open Source Project
-
-package {
-    default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-cc_binary {
-    name: "set-verity-state",
-    srcs: ["set-verity-state.cpp"],
-    shared_libs: [
-        "libbase",
-        "libbinder",
-        "libcrypto",
-        "libcrypto_utils",
-        "libfs_mgr_binder",
-        "libutils",
-    ],
-    static_libs: [
-        "libavb_user",
-    ],
-    header_libs: [
-        "libcutils_headers",
-    ],
-
-    cflags: ["-Werror"],
-    cppflags: [
-        "-DALLOW_DISABLE_VERITY=0",
-    ],
-    product_variables: {
-        debuggable: {
-            cppflags: [
-                "-UALLOW_DISABLE_VERITY",
-                "-DALLOW_DISABLE_VERITY=1",
-            ],
-        },
-    },
-    symlinks: [
-        "enable-verity",
-        "disable-verity",
-    ],
-}
diff --git a/set-verity-state/OWNERS b/set-verity-state/OWNERS
deleted file mode 100644
index e849450..0000000
--- a/set-verity-state/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-dvander@google.com
-yochiang@google.com
-bowgotsai@google.com
diff --git a/set-verity-state/set-verity-state.cpp b/set-verity-state/set-verity-state.cpp
deleted file mode 100644
index 2b9c0ca..0000000
--- a/set-verity-state/set-verity-state.cpp
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2019 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 <getopt.h>
-#include <stdio.h>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/properties.h>
-#include <binder/ProcessState.h>
-#include <cutils/android_reboot.h>
-#include <fs_mgr_overlayfs.h>
-#include <libavb_user/libavb_user.h>
-
-using namespace std::string_literals;
-
-namespace {
-
-void print_usage() {
-  printf(
-      "Usage:\n"
-      "\tdisable-verity\n"
-      "\tenable-verity\n"
-      "\tset-verity-state [0|1]\n"
-      "Options:\n"
-      "\t-h --help\tthis help\n"
-      "\t-R --reboot\tautomatic reboot if needed for new settings to take effect\n"
-      "\t-v --verbose\tbe noisy\n");
-}
-
-#ifdef ALLOW_DISABLE_VERITY
-const bool kAllowDisableVerity = true;
-#else
-const bool kAllowDisableVerity = false;
-#endif
-
-static bool SetupOrTeardownOverlayfs(bool enable) {
-  bool want_reboot = false;
-  if (enable) {
-    if (!fs_mgr_overlayfs_setup(nullptr, &want_reboot)) {
-      LOG(ERROR) << "Overlayfs setup failed.";
-      return want_reboot;
-    }
-    if (want_reboot) {
-      printf("enabling overlayfs\n");
-    }
-  } else {
-    auto rv = fs_mgr_overlayfs_teardown(nullptr, &want_reboot);
-    if (rv == OverlayfsTeardownResult::Error) {
-      LOG(ERROR) << "Overlayfs teardown failed.";
-      return want_reboot;
-    }
-    if (rv == OverlayfsTeardownResult::Busy) {
-      LOG(ERROR) << "Overlayfs is still active until reboot.";
-      return true;
-    }
-    if (want_reboot) {
-      printf("disabling overlayfs\n");
-    }
-  }
-  return want_reboot;
-}
-
-/* Helper function to get A/B suffix, if any. If the device isn't
- * using A/B the empty string is returned. Otherwise either "_a",
- * "_b", ... is returned.
- */
-std::string get_ab_suffix() {
-  return android::base::GetProperty("ro.boot.slot_suffix", "");
-}
-
-bool is_avb_device_locked() {
-  return android::base::GetProperty("ro.boot.vbmeta.device_state", "") == "locked";
-}
-
-bool is_debuggable() {
-  return android::base::GetBoolProperty("ro.debuggable", false);
-}
-
-bool is_using_avb() {
-  // Figure out if we're using VB1.0 or VB2.0 (aka AVB) - by
-  // contract, androidboot.vbmeta.digest is set by the bootloader
-  // when using AVB).
-  return !android::base::GetProperty("ro.boot.vbmeta.digest", "").empty();
-}
-
-[[noreturn]] void reboot(const std::string& name) {
-  LOG(INFO) << "Rebooting device for new settings to take effect";
-  ::sync();
-  android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot," + name);
-  ::sleep(60);
-  LOG(ERROR) << "Failed to reboot";
-  ::exit(1);
-}
-
-struct SetVerityStateResult {
-  bool success = false;
-  bool want_reboot = false;
-};
-
-/* Use AVB to turn verity on/off */
-SetVerityStateResult SetVerityState(bool enable_verity) {
-  std::string ab_suffix = get_ab_suffix();
-  bool verity_enabled = false;
-
-  if (is_avb_device_locked()) {
-    LOG(ERROR) << "Device must be bootloader unlocked to change verity state";
-    return {};
-  }
-
-  std::unique_ptr<AvbOps, decltype(&avb_ops_user_free)> ops(avb_ops_user_new(), &avb_ops_user_free);
-  if (!ops) {
-    LOG(ERROR) << "Error getting AVB ops";
-    return {};
-  }
-
-  if (!avb_user_verity_get(ops.get(), ab_suffix.c_str(), &verity_enabled)) {
-    LOG(ERROR) << "Error getting verity state";
-    return {};
-  }
-
-  if ((verity_enabled && enable_verity) || (!verity_enabled && !enable_verity)) {
-    LOG(INFO) << "Verity is already " << (verity_enabled ? "enabled" : "disabled");
-    return {.success = true, .want_reboot = false};
-  }
-
-  if (!avb_user_verity_set(ops.get(), ab_suffix.c_str(), enable_verity)) {
-    LOG(ERROR) << "Error setting verity state";
-    return {};
-  }
-
-  LOG(INFO) << "Successfully " << (enable_verity ? "enabled" : "disabled") << " verity";
-  return {.success = true, .want_reboot = true};
-}
-
-class MyLogger {
- public:
-  explicit MyLogger(bool verbose) : verbose_(verbose) {}
-
-  void operator()(android::base::LogId id, android::base::LogSeverity severity, const char* tag,
-                  const char* file, unsigned int line, const char* message) {
-    // Hide log starting with '[fs_mgr]' unless it's an error.
-    if (verbose_ || severity >= android::base::ERROR || message[0] != '[') {
-      fprintf(stderr, "%s\n", message);
-    }
-    logd_(id, severity, tag, file, line, message);
-  }
-
- private:
-  android::base::LogdLogger logd_;
-  bool verbose_;
-};
-
-}  // namespace
-
-int main(int argc, char* argv[]) {
-  bool auto_reboot = false;
-  bool verbose = false;
-
-  struct option longopts[] = {
-      {"help", no_argument, nullptr, 'h'},
-      {"reboot", no_argument, nullptr, 'R'},
-      {"verbose", no_argument, nullptr, 'v'},
-      {0, 0, nullptr, 0},
-  };
-  for (int opt; (opt = ::getopt_long(argc, argv, "hRv", longopts, nullptr)) != -1;) {
-    switch (opt) {
-      case 'h':
-        print_usage();
-        return 0;
-      case 'R':
-        auto_reboot = true;
-        break;
-      case 'v':
-        verbose = true;
-        break;
-      default:
-        print_usage();
-        return 1;
-    }
-  }
-
-  android::base::InitLogging(argv, MyLogger(verbose));
-
-  bool enable_verity = false;
-  const std::string progname = getprogname();
-  if (progname == "enable-verity") {
-    enable_verity = true;
-  } else if (progname == "disable-verity") {
-    enable_verity = false;
-  } else if (optind < argc && (argv[optind] == "1"s || argv[optind] == "0"s)) {
-    // progname "set-verity-state"
-    enable_verity = (argv[optind] == "1"s);
-  } else {
-    print_usage();
-    return 1;
-  }
-
-  if (!kAllowDisableVerity || !is_debuggable()) {
-    errno = EPERM;
-    PLOG(ERROR) << "Cannot disable/enable verity on user build";
-    return 1;
-  }
-
-  if (getuid() != 0) {
-    errno = EACCES;
-    PLOG(ERROR) << "Must be running as root (adb root)";
-    return 1;
-  }
-
-  if (!is_using_avb()) {
-    LOG(ERROR) << "Expected AVB device, VB1.0 is no longer supported";
-    return 1;
-  }
-
-  int exit_code = 0;
-  bool want_reboot = false;
-
-  auto ret = SetVerityState(enable_verity);
-  if (ret.success) {
-    want_reboot |= ret.want_reboot;
-  } else {
-    exit_code = 1;
-  }
-
-  // Disable any overlayfs unconditionally if we want verity enabled.
-  // Enable overlayfs only if verity is successfully disabled or is already disabled.
-  if (enable_verity || ret.success) {
-    // Start a threadpool to service waitForService() callbacks as
-    // fs_mgr_overlayfs_* might call waitForService() to get the image service.
-    android::ProcessState::self()->startThreadPool();
-    want_reboot |= SetupOrTeardownOverlayfs(!enable_verity);
-  }
-
-  if (want_reboot) {
-    if (auto_reboot) {
-      reboot(progname);
-    }
-    printf("Reboot the device for new settings to take effect\n");
-  }
-
-  return exit_code;
-}
diff --git a/storaged/storaged.cpp b/storaged/storaged.cpp
index cefef6e..ba79ff7 100644
--- a/storaged/storaged.cpp
+++ b/storaged/storaged.cpp
@@ -27,6 +27,7 @@
 #include <fstream>
 #include <sstream>
 #include <string>
+#include <utility>
 
 #include <aidl/android/hardware/health/BnHealthInfoCallback.h>
 #include <android-base/file.h>
@@ -62,7 +63,7 @@
 
 constexpr ssize_t benchmark_unit_size = 16 * 1024;  // 16KB
 
-constexpr ssize_t min_benchmark_size = 128 * 1024;  // 128KB
+constexpr size_t min_benchmark_size = 128 * 1024;  // 128KB
 
 }  // namespace
 
@@ -244,9 +245,10 @@
     proto.ParseFromString(ss.str());
 
     const UidIOUsage& uid_io_usage = proto.uid_io_usage();
-    uint32_t computed_crc = crc32(current_version,
-        reinterpret_cast<const Bytef*>(uid_io_usage.SerializeAsString().c_str()),
-        uid_io_usage.ByteSize());
+    uint32_t computed_crc =
+            crc32(current_version,
+                  reinterpret_cast<const Bytef*>(uid_io_usage.SerializeAsString().c_str()),
+                  uid_io_usage.ByteSizeLong());
     if (proto.crc() != computed_crc) {
         LOG(WARNING) << "CRC mismatch in " << proto_file;
         return;
@@ -264,31 +266,29 @@
 
     const UidIOUsage& uid_io_usage = proto->uid_io_usage();
     proto->set_crc(crc32(current_version,
-        reinterpret_cast<const Bytef*>(uid_io_usage.SerializeAsString().c_str()),
-        uid_io_usage.ByteSize()));
+                         reinterpret_cast<const Bytef*>(uid_io_usage.SerializeAsString().c_str()),
+                         uid_io_usage.ByteSizeLong()));
 
     uint32_t pagesize = sysconf(_SC_PAGESIZE);
     if (user_id == USER_SYSTEM) {
         proto->set_padding("", 1);
         vector<char> padding;
-        ssize_t size = ROUND_UP(MAX(min_benchmark_size, proto->ByteSize()),
-                                pagesize);
-        padding = vector<char>(size - proto->ByteSize(), 0xFD);
+        ssize_t size = ROUND_UP(std::max(min_benchmark_size, proto->ByteSizeLong()), pagesize);
+        padding = vector<char>(size - proto->ByteSizeLong(), 0xFD);
         proto->set_padding(padding.data(), padding.size());
-        while (!IS_ALIGNED(proto->ByteSize(), pagesize)) {
+        while (!IS_ALIGNED(proto->ByteSizeLong(), pagesize)) {
             padding.push_back(0xFD);
             proto->set_padding(padding.data(), padding.size());
         }
     }
 
     char* data = nullptr;
-    if (posix_memalign(reinterpret_cast<void**>(&data),
-                       pagesize, proto->ByteSize())) {
-        PLOG(ERROR) << "Faied to alloc aligned buffer (size: " << proto->ByteSize() << ")";
+    if (posix_memalign(reinterpret_cast<void**>(&data), pagesize, proto->ByteSizeLong())) {
+        PLOG(ERROR) << "Faied to alloc aligned buffer (size: " << proto->ByteSizeLong() << ")";
         return data;
     }
 
-    proto->SerializeToArray(data, proto->ByteSize());
+    proto->SerializeToArray(data, proto->ByteSizeLong());
     return data;
 }
 
@@ -314,7 +314,7 @@
 
         while (size > 0) {
             start = steady_clock::now();
-            ret = write(fd, data, MIN(benchmark_unit_size, size));
+            ret = write(fd, data, std::min(benchmark_unit_size, size));
             if (ret <= 0) {
                 PLOG(ERROR) << "Faied to write tmp file: " << tmp_file;
                 return;
@@ -352,7 +352,7 @@
     unique_ptr<char> proto_data(prepare_proto(user_id, proto));
     if (proto_data == nullptr) return;
 
-    flush_proto_data(user_id, proto_data.get(), proto->ByteSize());
+    flush_proto_data(user_id, proto_data.get(), proto->ByteSizeLong());
 }
 
 void storaged_t::flush_protos(unordered_map<int, StoragedProto>* protos) {