Merge "Revert "ARC++ swap for AppFuseUtil""
diff --git a/.clang-format b/.clang-format
deleted file mode 100644
index ae4a451..0000000
--- a/.clang-format
+++ /dev/null
@@ -1,11 +0,0 @@
-BasedOnStyle: Google
-AccessModifierOffset: -2
-AllowShortFunctionsOnASingleLine: Inline
-ColumnLimit: 100
-CommentPragmas: NOLINT:.*
-DerivePointerAlignment: false
-IndentWidth: 4
-PointerAlignment: Left
-TabWidth: 4
-UseTab: Never
-PenaltyExcessCharacter: 32
diff --git a/.clang-format b/.clang-format
new file mode 120000
index 0000000..ddcf5a2
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1 @@
+../../build/soong/scripts/system-clang-format
\ No newline at end of file
diff --git a/Android.bp b/Android.bp
index b192b42..0ffc8f9 100644
--- a/Android.bp
+++ b/Android.bp
@@ -17,6 +17,7 @@
         "-*",
         "cert-*",
         "clang-analyzer-security*",
+        "android-*",
     ],
     tidy_flags: [
         "-warnings-as-errors=clang-analyzer-security*,cert-*",
@@ -29,8 +30,11 @@
     static_libs: [
         "libavb",
         "libbootloader_message",
+        "libdm",
+        "libext2_uuid",
         "libfec",
         "libfec_rs",
+        "libfs_avb",
         "libfs_mgr",
         "libscrypt_static",
         "libsquashfs_utils",
@@ -39,6 +43,7 @@
     shared_libs: [
         "android.hardware.keymaster@3.0",
         "android.hardware.keymaster@4.0",
+        "android.hardware.keymaster@4.1",
         "android.hardware.boot@1.0",
         "libbase",
         "libbinder",
@@ -48,12 +53,12 @@
         "libdiskconfig",
         "libext4_utils",
         "libf2fs_sparseblock",
-        "libfscrypt",
         "libhardware",
         "libhardware_legacy",
+        "libincfs",
         "libhidlbase",
-        "libhwbinder",
         "libkeymaster4support",
+        "libkeymaster4_1support",
         "libkeyutils",
         "liblog",
         "liblogwrap",
@@ -76,13 +81,20 @@
     ],
     aidl: {
         local_include_dirs: ["binder"],
-        include_dirs: ["frameworks/native/aidl/binder"],
+        include_dirs: [
+            "frameworks/native/aidl/binder",
+            "frameworks/base/core/java",
+        ],
         export_aidl_headers: true,
     },
+    whole_static_libs: [
+        "libincremental_aidl-cpp",
+    ],
 }
 
 cc_library_headers {
     name: "libvold_headers",
+    recovery_available: true,
     export_include_dirs: ["."],
 }
 
@@ -99,6 +111,7 @@
         "Benchmark.cpp",
         "CheckEncryption.cpp",
         "Checkpoint.cpp",
+        "CryptoType.cpp",
         "Devmapper.cpp",
         "EncryptInplace.cpp",
         "FileDeviceUtils.cpp",
@@ -117,6 +130,7 @@
         "ScryptParameters.cpp",
         "Utils.cpp",
         "VoldNativeService.cpp",
+        "VoldNativeServiceValidation.cpp",
         "VoldUtil.cpp",
         "VolumeManager.cpp",
         "cryptfs.cpp",
@@ -129,9 +143,9 @@
         "model/ObbVolume.cpp",
         "model/PrivateVolume.cpp",
         "model/PublicVolume.cpp",
-        "model/VolumeBase.cpp",
         "model/StubVolume.cpp",
-        "secontext.cpp",
+        "model/VolumeBase.cpp",
+        "model/VolumeEncryption.cpp",
     ],
     product_variables: {
         arc: {
@@ -150,6 +164,9 @@
     shared_libs: [
         "android.hardware.health.storage@1.0",
     ],
+    whole_static_libs: [
+        "com.android.sysprop.apex",
+    ],
 }
 
 cc_binary {
@@ -182,7 +199,6 @@
 
     shared_libs: [
         "android.hardware.health.storage@1.0",
-        "libhidltransport",
     ],
 }
 
@@ -217,11 +233,12 @@
 
         "android.hardware.keymaster@3.0",
         "android.hardware.keymaster@4.0",
+        "android.hardware.keymaster@4.1",
         "libhardware",
         "libhardware_legacy",
         "libhidlbase",
-        "libhwbinder",
         "libkeymaster4support",
+        "libkeymaster4_1support",
     ],
 }
 
@@ -260,6 +277,5 @@
         "binder/android/os/IVoldListener.aidl",
         "binder/android/os/IVoldTaskListener.aidl",
     ],
+    path: "binder",
 }
-
-subdirs = ["tests"]
diff --git a/AppFuseUtil.cpp b/AppFuseUtil.cpp
index ba82ba5..711e70b 100644
--- a/AppFuseUtil.cpp
+++ b/AppFuseUtil.cpp
@@ -49,9 +49,6 @@
 }
 
 static android::status_t Mount(int device_fd, const std::string& path) {
-    // Remove existing mount.
-    android::vold::ForceUnmount(path);
-
     const auto opts = StringPrintf(
         "fd=%i,"
         "rootmode=40000,"
@@ -115,6 +112,11 @@
         return -1;
     }
 
+    // Forcibly remove the existing mount before we attempt to prepare the
+    // directory. If we have a dangling mount, then PrepareDir may fail if the
+    // indirection to FUSE doesn't work.
+    android::vold::ForceUnmount(path);
+
     // Create directories.
     const android::status_t result = android::vold::PrepareDir(path, 0700, 0, 0);
     if (result != android::OK) {
@@ -123,7 +125,8 @@
     }
 
     // Open device FD.
-    device_fd->reset(open("/dev/fuse", O_RDWR));  // not O_CLOEXEC
+    // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
+    device_fd->reset(open("/dev/fuse", O_RDWR));
     if (device_fd->get() == -1) {
         PLOG(ERROR) << "Failed to open /dev/fuse";
         return -1;
diff --git a/Benchmark.cpp b/Benchmark.cpp
index b0a3b85..0770da7 100644
--- a/Benchmark.cpp
+++ b/Benchmark.cpp
@@ -23,8 +23,8 @@
 #include <android-base/logging.h>
 
 #include <cutils/iosched_policy.h>
-#include <hardware_legacy/power.h>
 #include <private/android_filesystem_config.h>
+#include <wakelock/wakelock.h>
 
 #include <thread>
 
@@ -181,7 +181,7 @@
 void Benchmark(const std::string& path,
                const android::sp<android::os::IVoldTaskListener>& listener) {
     std::lock_guard<std::mutex> lock(kBenchmarkLock);
-    acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+    android::wakelock::WakeLock wl{kWakeLock};
 
     PerformanceBoost boost;
     android::os::PersistableBundle extras;
@@ -190,8 +190,6 @@
     if (listener) {
         listener->onFinished(res, extras);
     }
-
-    release_wake_lock(kWakeLock);
 }
 
 }  // namespace vold
diff --git a/Checkpoint.cpp b/Checkpoint.cpp
index 94a78eb..df5fc88 100644
--- a/Checkpoint.cpp
+++ b/Checkpoint.cpp
@@ -16,16 +16,20 @@
 
 #define LOG_TAG "Checkpoint"
 #include "Checkpoint.h"
+#include "VoldUtil.h"
+#include "VolumeManager.h"
 
 #include <fstream>
 #include <list>
 #include <memory>
 #include <string>
+#include <thread>
 #include <vector>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
+#include <android-base/properties.h>
 #include <android-base/unique_fd.h>
 #include <android/hardware/boot/1.0/IBootControl.h>
 #include <cutils/android_reboot.h>
@@ -35,10 +39,19 @@
 #include <mntent.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <unistd.h>
 
+using android::base::GetBoolProperty;
+using android::base::GetUintProperty;
+using android::base::SetProperty;
 using android::binder::Status;
+using android::fs_mgr::Fstab;
+using android::fs_mgr::ReadDefaultFstab;
+using android::fs_mgr::ReadFstabFromFile;
 using android::hardware::hidl_string;
 using android::hardware::boot::V1_0::BoolResult;
+using android::hardware::boot::V1_0::CommandResult;
 using android::hardware::boot::V1_0::IBootControl;
 using android::hardware::boot::V1_0::Slot;
 
@@ -48,15 +61,22 @@
 namespace {
 const std::string kMetadataCPFile = "/metadata/vold/checkpoint";
 
-bool setBowState(std::string const& block_device, std::string const& state) {
-    if (block_device.substr(0, 5) != "/dev/") {
-        LOG(ERROR) << "Expected block device, got " << block_device;
-        return false;
-    }
+binder::Status error(const std::string& msg) {
+    PLOG(ERROR) << msg;
+    return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
+}
 
-    std::string state_filename = std::string("/sys/") + block_device.substr(5) + "/bow/state";
-    if (!android::base::WriteStringToFile(state, state_filename)) {
-        PLOG(ERROR) << "Failed to write to file " << state_filename;
+binder::Status error(int error, const std::string& msg) {
+    LOG(ERROR) << msg;
+    return binder::Status::fromServiceSpecificError(error, String8(msg.c_str()));
+}
+
+bool setBowState(std::string const& block_device, std::string const& state) {
+    std::string bow_device = fs_mgr_find_bow_device(block_device);
+    if (bow_device.empty()) return false;
+
+    if (!android::base::WriteStringToFile(state, bow_device + "/bow/state")) {
+        PLOG(ERROR) << "Failed to write to file " << bow_device + "/bow/state";
         return false;
     }
 
@@ -65,8 +85,48 @@
 
 }  // namespace
 
+Status cp_supportsCheckpoint(bool& result) {
+    result = false;
+
+    for (const auto& entry : fstab_default) {
+        if (entry.fs_mgr_flags.checkpoint_blk || entry.fs_mgr_flags.checkpoint_fs) {
+            result = true;
+            return Status::ok();
+        }
+    }
+    return Status::ok();
+}
+
+Status cp_supportsBlockCheckpoint(bool& result) {
+    result = false;
+
+    for (const auto& entry : fstab_default) {
+        if (entry.fs_mgr_flags.checkpoint_blk) {
+            result = true;
+            return Status::ok();
+        }
+    }
+    return Status::ok();
+}
+
+Status cp_supportsFileCheckpoint(bool& result) {
+    result = false;
+
+    for (const auto& entry : fstab_default) {
+        if (entry.fs_mgr_flags.checkpoint_fs) {
+            result = true;
+            return Status::ok();
+        }
+    }
+    return Status::ok();
+}
+
 Status cp_startCheckpoint(int retry) {
-    if (retry < -1) return Status::fromExceptionCode(EINVAL, "Retry count must be more than -1");
+    bool result;
+    if (!cp_supportsCheckpoint(result).isOk() || !result)
+        return error(ENOTSUP, "Checkpoints not supported");
+
+    if (retry < -1) return error(EINVAL, "Retry count must be more than -1");
     std::string content = std::to_string(retry + 1);
     if (retry == -1) {
         sp<IBootControl> module = IBootControl::getService();
@@ -77,48 +137,113 @@
         }
     }
     if (!android::base::WriteStringToFile(content, kMetadataCPFile))
-        return Status::fromExceptionCode(errno, "Failed to write checkpoint file");
+        return error("Failed to write checkpoint file");
     return Status::ok();
 }
 
+namespace {
+
+volatile bool isCheckpointing = false;
+
+volatile bool needsCheckpointWasCalled = false;
+
+// Protects isCheckpointing, needsCheckpointWasCalled and code that makes decisions based on status
+// of isCheckpointing
+std::mutex isCheckpointingLock;
+}
+
 Status cp_commitChanges() {
+    std::lock_guard<std::mutex> lock(isCheckpointingLock);
+
+    if (!isCheckpointing) {
+        return Status::ok();
+    }
+    if (android::base::GetProperty("persist.vold.dont_commit_checkpoint", "0") == "1") {
+        LOG(WARNING)
+            << "NOT COMMITTING CHECKPOINT BECAUSE persist.vold.dont_commit_checkpoint IS 1";
+        return Status::ok();
+    }
+    sp<IBootControl> module = IBootControl::getService();
+    if (module) {
+        CommandResult cr;
+        module->markBootSuccessful([&cr](CommandResult result) { cr = result; });
+        if (!cr.success)
+            return error(EINVAL, "Error marking booted successfully: " + std::string(cr.errMsg));
+        LOG(INFO) << "Marked slot as booted successfully.";
+        // Clears the warm reset flag for next reboot.
+        if (!SetProperty("ota.warm_reset", "0")) {
+            LOG(WARNING) << "Failed to reset the warm reset flag";
+        }
+    }
     // Must take action for list of mounted checkpointed things here
     // To do this, we walk the list of mounted file systems.
     // But we also need to get the matching fstab entries to see
     // the original flags
     std::string err_str;
-    auto fstab_default = std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)>{
-        fs_mgr_read_fstab_default(), fs_mgr_free_fstab};
-    if (!fstab_default) return Status::fromExceptionCode(EINVAL, "Failed to get fstab");
 
-    auto mounts = std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)>{
-        fs_mgr_read_fstab("/proc/mounts"), fs_mgr_free_fstab};
-    if (!mounts) return Status::fromExceptionCode(EINVAL, "Failed to get /proc/mounts");
+    Fstab mounts;
+    if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
+        return error(EINVAL, "Failed to get /proc/mounts");
+    }
 
     // Walk mounted file systems
-    for (int i = 0; i < mounts->num_entries; ++i) {
-        const fstab_rec* mount_rec = &mounts->recs[i];
-        const fstab_rec* fstab_rec =
-            fs_mgr_get_entry_for_mount_point(fstab_default.get(), mount_rec->mount_point);
+    for (const auto& mount_rec : mounts) {
+        const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point);
         if (!fstab_rec) continue;
 
-        if (fs_mgr_is_checkpoint_fs(fstab_rec)) {
-            if (!strcmp(fstab_rec->fs_type, "f2fs")) {
-                mount(mount_rec->blk_device, mount_rec->mount_point, "none",
-                      MS_REMOUNT | fstab_rec->flags, "checkpoint=enable");
+        if (fstab_rec->fs_mgr_flags.checkpoint_fs) {
+            if (fstab_rec->fs_type == "f2fs") {
+                std::string options = mount_rec.fs_options + ",checkpoint=enable";
+                if (mount(mount_rec.blk_device.c_str(), mount_rec.mount_point.c_str(), "none",
+                          MS_REMOUNT | fstab_rec->flags, options.c_str())) {
+                    return error(EINVAL, "Failed to remount");
+                }
             }
-        } else if (fs_mgr_is_checkpoint_blk(fstab_rec)) {
-            setBowState(mount_rec->blk_device, "2");
+        } else if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
+            if (!setBowState(mount_rec.blk_device, "2"))
+                return error(EINVAL, "Failed to set bow state");
         }
     }
-    if (android::base::RemoveFileIfExists(kMetadataCPFile, &err_str))
-        return Status::fromExceptionCode(errno, err_str.c_str());
+    SetProperty("vold.checkpoint_committed", "1");
+    LOG(INFO) << "Checkpoint has been committed.";
+    isCheckpointing = false;
+    if (!android::base::RemoveFileIfExists(kMetadataCPFile, &err_str))
+        return error(err_str.c_str());
+
     return Status::ok();
 }
 
-Status cp_abortChanges() {
-    android_reboot(ANDROID_RB_RESTART2, 0, nullptr);
-    return Status::ok();
+namespace {
+void abort_metadata_file() {
+    std::string oldContent, newContent;
+    int retry = 0;
+    struct stat st;
+    int result = stat(kMetadataCPFile.c_str(), &st);
+
+    // If the file doesn't exist, we aren't managing a checkpoint retry counter
+    if (result != 0) return;
+    if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) {
+        PLOG(ERROR) << "Failed to read checkpoint file";
+        return;
+    }
+    std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
+
+    if (!android::base::ParseInt(retryContent, &retry)) {
+        PLOG(ERROR) << "Could not parse retry count";
+        return;
+    }
+    if (retry > 0) {
+        newContent = "0";
+        if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
+            PLOG(ERROR) << "Could not write checkpoint file";
+    }
+}
+}  // namespace
+
+void cp_abortChanges(const std::string& message, bool retry) {
+    if (!cp_needsCheckpoint()) return;
+    if (!retry) abort_metadata_file();
+    android_reboot(ANDROID_RB_RESTART2, 0, message.c_str());
 }
 
 bool cp_needsRollback() {
@@ -144,75 +269,158 @@
 }
 
 bool cp_needsCheckpoint() {
+    std::lock_guard<std::mutex> lock(isCheckpointingLock);
+
+    // Make sure we only return true during boot. See b/138952436 for discussion
+    if (needsCheckpointWasCalled) return isCheckpointing;
+    needsCheckpointWasCalled = true;
+
     bool ret;
     std::string content;
     sp<IBootControl> module = IBootControl::getService();
 
-    if (module && module->isSlotMarkedSuccessful(module->getCurrentSlot()) == BoolResult::FALSE)
+    if (isCheckpointing) return isCheckpointing;
+
+    if (module && module->isSlotMarkedSuccessful(module->getCurrentSlot()) == BoolResult::FALSE) {
+        isCheckpointing = true;
         return true;
+    }
     ret = android::base::ReadFileToString(kMetadataCPFile, &content);
-    if (ret) return content != "0";
+    if (ret) {
+        ret = content != "0";
+        isCheckpointing = ret;
+        return ret;
+    }
     return false;
 }
 
+namespace {
+const std::string kSleepTimeProp = "ro.sys.cp_msleeptime";
+const uint32_t msleeptime_default = 1000;  // 1 s
+const uint32_t max_msleeptime = 3600000;   // 1 h
+
+const std::string kMinFreeBytesProp = "ro.sys.cp_min_free_bytes";
+const uint64_t min_free_bytes_default = 100 * (1 << 20);  // 100 MiB
+
+const std::string kCommitOnFullProp = "ro.sys.cp_commit_on_full";
+const bool commit_on_full_default = true;
+
+static void cp_healthDaemon(std::string mnt_pnt, std::string blk_device, bool is_fs_cp) {
+    struct statvfs data;
+    uint32_t msleeptime = GetUintProperty(kSleepTimeProp, msleeptime_default, max_msleeptime);
+    uint64_t min_free_bytes =
+        GetUintProperty(kMinFreeBytesProp, min_free_bytes_default, (uint64_t)-1);
+    bool commit_on_full = GetBoolProperty(kCommitOnFullProp, commit_on_full_default);
+
+    struct timespec req;
+    req.tv_sec = msleeptime / 1000;
+    msleeptime %= 1000;
+    req.tv_nsec = msleeptime * 1000000;
+    while (isCheckpointing) {
+        uint64_t free_bytes = 0;
+        if (is_fs_cp) {
+            statvfs(mnt_pnt.c_str(), &data);
+            free_bytes = ((uint64_t) data.f_bavail) * data.f_frsize;
+        } else {
+            std::string bow_device = fs_mgr_find_bow_device(blk_device);
+            if (!bow_device.empty()) {
+                std::string content;
+                if (android::base::ReadFileToString(bow_device + "/bow/free", &content)) {
+                    free_bytes = std::strtoull(content.c_str(), NULL, 10);
+                }
+            }
+        }
+        if (free_bytes < min_free_bytes) {
+            if (commit_on_full) {
+                LOG(INFO) << "Low space for checkpointing. Commiting changes";
+                cp_commitChanges();
+                break;
+            } else {
+                LOG(INFO) << "Low space for checkpointing. Rebooting";
+                cp_abortChanges("checkpoint,low_space", false);
+                break;
+            }
+        }
+        nanosleep(&req, NULL);
+    }
+}
+
+}  // namespace
+
 Status cp_prepareCheckpoint() {
-    auto fstab_default = std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)>{
-        fs_mgr_read_fstab_default(), fs_mgr_free_fstab};
-    if (!fstab_default) return Status::fromExceptionCode(EINVAL, "Failed to get fstab");
+    // Log to notify CTS - see b/137924328 for context
+    LOG(INFO) << "cp_prepareCheckpoint called";
+    std::lock_guard<std::mutex> lock(isCheckpointingLock);
+    if (!isCheckpointing) {
+        return Status::ok();
+    }
 
-    auto mounts = std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)>{
-        fs_mgr_read_fstab("/proc/mounts"), fs_mgr_free_fstab};
-    if (!mounts) return Status::fromExceptionCode(EINVAL, "Failed to get /proc/mounts");
+    Fstab mounts;
+    if (!ReadFstabFromFile("/proc/mounts", &mounts)) {
+        return error(EINVAL, "Failed to get /proc/mounts");
+    }
 
-    for (int i = 0; i < mounts->num_entries; ++i) {
-        const fstab_rec* mount_rec = &mounts->recs[i];
-        const fstab_rec* fstab_rec =
-            fs_mgr_get_entry_for_mount_point(fstab_default.get(), mount_rec->mount_point);
+    for (const auto& mount_rec : mounts) {
+        const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point);
         if (!fstab_rec) continue;
 
-        if (fs_mgr_is_checkpoint_blk(fstab_rec)) {
+        if (fstab_rec->fs_mgr_flags.checkpoint_blk) {
             android::base::unique_fd fd(
-                TEMP_FAILURE_RETRY(open(mount_rec->mount_point, O_RDONLY | O_CLOEXEC)));
-            if (!fd) {
-                PLOG(ERROR) << "Failed to open mount point" << mount_rec->mount_point;
+                TEMP_FAILURE_RETRY(open(mount_rec.mount_point.c_str(), O_RDONLY | O_CLOEXEC)));
+            if (fd == -1) {
+                PLOG(ERROR) << "Failed to open mount point" << mount_rec.mount_point;
                 continue;
             }
 
             struct fstrim_range range = {};
             range.len = ULLONG_MAX;
+            nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
             if (ioctl(fd, FITRIM, &range)) {
-                PLOG(ERROR) << "Failed to trim " << mount_rec->mount_point;
+                PLOG(ERROR) << "Failed to trim " << mount_rec.mount_point;
                 continue;
             }
+            nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start;
+            LOG(INFO) << "Trimmed " << range.len << " bytes on " << mount_rec.mount_point << " in "
+                      << nanoseconds_to_milliseconds(time) << "ms for checkpoint";
 
-            setBowState(mount_rec->blk_device, "1");
+            setBowState(mount_rec.blk_device, "1");
+        }
+        if (fstab_rec->fs_mgr_flags.checkpoint_blk || fstab_rec->fs_mgr_flags.checkpoint_fs) {
+            std::thread(cp_healthDaemon, std::string(mount_rec.mount_point),
+                        std::string(mount_rec.blk_device),
+                        fstab_rec->fs_mgr_flags.checkpoint_fs == 1)
+                .detach();
         }
     }
     return Status::ok();
 }
 
 namespace {
-const int kBlockSize = 4096;
 const int kSectorSize = 512;
 
 typedef uint64_t sector_t;
 
 struct log_entry {
-    sector_t source;
-    sector_t dest;
-    uint32_t size;
+    sector_t source;  // in sectors of size kSectorSize
+    sector_t dest;    // in sectors of size kSectorSize
+    uint32_t size;    // in bytes
     uint32_t checksum;
 } __attribute__((packed));
 
-struct log_sector {
+struct log_sector_v1_0 {
     uint32_t magic;
+    uint16_t header_version;
+    uint16_t header_size;
+    uint32_t block_size;
     uint32_t count;
     uint32_t sequence;
-    struct log_entry entries[];
+    uint64_t sector0;
 } __attribute__((packed));
 
 // MAGIC is BOW in ascii
 const int kMagic = 0x00574f42;
+// Partially restored MAGIC is WOB in ascii
+const int kPartialRestoreMagic = 0x00424f57;
 
 void crc32(const void* data, size_t n_bytes, uint32_t* crc) {
     static uint32_t table[0x100] = {
@@ -266,65 +474,238 @@
     }
 }
 
+// A map of relocations.
+// The map must be initialized so that relocations[0] = 0
+// During restore, we replay the log records in reverse, copying from dest to
+// source
+// To validate, we must be able to read the 'dest' sectors as though they had
+// been copied but without actually copying. This map represents how the sectors
+// would have been moved. To read a sector s, find the index <= s and read
+// relocations[index] + s - index
+typedef std::map<sector_t, sector_t> Relocations;
+
+void relocate(Relocations& relocations, sector_t dest, sector_t source, int count) {
+    // Find first one we're equal to or greater than
+    auto s = --relocations.upper_bound(source);
+
+    // Take slice
+    Relocations slice;
+    slice[dest] = source - s->first + s->second;
+    ++s;
+
+    // Add rest of elements
+    for (; s != relocations.end() && s->first < source + count; ++s)
+        slice[dest - source + s->first] = s->second;
+
+    // Split range at end of dest
+    auto dest_end = --relocations.upper_bound(dest + count);
+    relocations[dest + count] = dest + count - dest_end->first + dest_end->second;
+
+    // Remove all elements in [dest, dest + count)
+    relocations.erase(relocations.lower_bound(dest), relocations.lower_bound(dest + count));
+
+    // Add new elements
+    relocations.insert(slice.begin(), slice.end());
+}
+
+// A map of sectors that have been written to.
+// The final entry must always be False.
+// When we restart the restore after an interruption, we must take care that
+// when we copy from dest to source, that the block we copy to was not
+// previously copied from.
+// i e. A->B C->A; If we replay this sequence, we end up copying C->B
+// We must save our partial result whenever we finish a page, or when we copy
+// to a location that was copied from earlier (our source is an earlier dest)
+typedef std::map<sector_t, bool> Used_Sectors;
+
+bool checkCollision(Used_Sectors& used_sectors, sector_t start, sector_t end) {
+    auto second_overlap = used_sectors.upper_bound(start);
+    auto first_overlap = --second_overlap;
+
+    if (first_overlap->second) {
+        return true;
+    } else if (second_overlap != used_sectors.end() && second_overlap->first < end) {
+        return true;
+    }
+    return false;
+}
+
+void markUsed(Used_Sectors& used_sectors, sector_t start, sector_t end) {
+    auto start_pos = used_sectors.insert_or_assign(start, true).first;
+    auto end_pos = used_sectors.insert_or_assign(end, false).first;
+
+    if (start_pos == used_sectors.begin() || !std::prev(start_pos)->second) {
+        start_pos++;
+    }
+    if (std::next(end_pos) != used_sectors.end() && !std::next(end_pos)->second) {
+        end_pos++;
+    }
+    if (start_pos->first < end_pos->first) {
+        used_sectors.erase(start_pos, end_pos);
+    }
+}
+
+// Restores the given log_entry's data from dest -> source
+// If that entry is a log sector, set the magic to kPartialRestoreMagic and flush.
+void restoreSector(int device_fd, Used_Sectors& used_sectors, std::vector<char>& ls_buffer,
+                   log_entry* le, std::vector<char>& buffer) {
+    log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]);
+    uint32_t index = le - ((log_entry*)&ls_buffer[ls.header_size]);
+    int count = (le->size - 1) / kSectorSize + 1;
+
+    if (checkCollision(used_sectors, le->source, le->source + count)) {
+        fsync(device_fd);
+        lseek64(device_fd, 0, SEEK_SET);
+        ls.count = index + 1;
+        ls.magic = kPartialRestoreMagic;
+        write(device_fd, &ls_buffer[0], ls.block_size);
+        fsync(device_fd);
+        used_sectors.clear();
+        used_sectors[0] = false;
+    }
+
+    markUsed(used_sectors, le->dest, le->dest + count);
+
+    if (index == 0 && ls.sequence != 0) {
+        log_sector_v1_0* next = reinterpret_cast<log_sector_v1_0*>(&buffer[0]);
+        if (next->magic == kMagic) {
+            next->magic = kPartialRestoreMagic;
+        }
+    }
+
+    lseek64(device_fd, le->source * kSectorSize, SEEK_SET);
+    write(device_fd, &buffer[0], le->size);
+
+    if (index == 0) {
+        fsync(device_fd);
+    }
+}
+
+// Read from the device
+// If we are validating, the read occurs as though the relocations had happened
+std::vector<char> relocatedRead(int device_fd, Relocations const& relocations, bool validating,
+                                sector_t sector, uint32_t size, uint32_t block_size) {
+    if (!validating) {
+        std::vector<char> buffer(size);
+        lseek64(device_fd, sector * kSectorSize, SEEK_SET);
+        read(device_fd, &buffer[0], size);
+        return buffer;
+    }
+
+    std::vector<char> buffer(size);
+    for (uint32_t i = 0; i < size; i += block_size, sector += block_size / kSectorSize) {
+        auto relocation = --relocations.upper_bound(sector);
+        lseek64(device_fd, (sector + relocation->second - relocation->first) * kSectorSize,
+                SEEK_SET);
+        read(device_fd, &buffer[i], block_size);
+    }
+
+    return buffer;
+}
+
 }  // namespace
 
-Status cp_restoreCheckpoint(const std::string& blockDevice) {
-    LOG(INFO) << "Restoring checkpoint on " << blockDevice;
-    std::fstream device(blockDevice, std::ios::binary | std::ios::in | std::ios::out);
-    if (!device) {
-        PLOG(ERROR) << "Cannot open " << blockDevice;
-        return Status::fromExceptionCode(errno, ("Cannot open " + blockDevice).c_str());
-    }
-    char buffer[kBlockSize];
-    device.read(buffer, kBlockSize);
-    log_sector& ls = *(log_sector*)buffer;
-    if (ls.magic != kMagic) {
-        LOG(ERROR) << "No magic";
-        return Status::fromExceptionCode(EINVAL, "No magic");
-    }
+Status cp_restoreCheckpoint(const std::string& blockDevice, int restore_limit) {
+    bool validating = true;
+    std::string action = "Validating";
+    int restore_count = 0;
 
-    LOG(INFO) << "Restoring " << ls.sequence << " log sectors";
+    for (;;) {
+        Relocations relocations;
+        relocations[0] = 0;
+        Status status = Status::ok();
 
-    for (int sequence = ls.sequence; sequence >= 0; sequence--) {
-        char buffer[kBlockSize];
-        device.seekg(0);
-        device.read(buffer, kBlockSize);
-        log_sector& ls = *(log_sector*)buffer;
-        if (ls.magic != kMagic) {
-            LOG(ERROR) << "No magic!";
-            return Status::fromExceptionCode(EINVAL, "No magic");
+        LOG(INFO) << action << " checkpoint on " << blockDevice;
+        base::unique_fd device_fd(open(blockDevice.c_str(), O_RDWR | O_CLOEXEC));
+        if (device_fd < 0) return error("Cannot open " + blockDevice);
+
+        log_sector_v1_0 original_ls;
+        read(device_fd, reinterpret_cast<char*>(&original_ls), sizeof(original_ls));
+        if (original_ls.magic == kPartialRestoreMagic) {
+            validating = false;
+            action = "Restoring";
+        } else if (original_ls.magic != kMagic) {
+            return error(EINVAL, "No magic");
         }
 
-        if ((int)ls.sequence != sequence) {
-            LOG(ERROR) << "Expecting log sector " << sequence << " but got " << ls.sequence;
-            return Status::fromExceptionCode(
-                EINVAL, ("Expecting log sector " + std::to_string(sequence) + " but got " +
-                         std::to_string(ls.sequence))
-                            .c_str());
-        }
+        LOG(INFO) << action << " " << original_ls.sequence << " log sectors";
 
-        LOG(INFO) << "Restoring from log sector " << ls.sequence;
+        for (int sequence = original_ls.sequence; sequence >= 0 && status.isOk(); sequence--) {
+            auto ls_buffer = relocatedRead(device_fd, relocations, validating, 0,
+                                           original_ls.block_size, original_ls.block_size);
+            log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]);
 
-        for (log_entry* le = &ls.entries[ls.count - 1]; le >= ls.entries; --le) {
-            LOG(INFO) << "Restoring " << le->size << " bytes from sector " << le->dest << " to "
-                      << le->source << " with checksum " << std::hex << le->checksum;
-            std::vector<char> buffer(le->size);
-            device.seekg(le->dest * kSectorSize);
-            device.read(&buffer[0], le->size);
+            Used_Sectors used_sectors;
+            used_sectors[0] = false;
 
-            uint32_t checksum = le->source / (kBlockSize / kSectorSize);
-            for (size_t i = 0; i < le->size; i += kBlockSize) {
-                crc32(&buffer[i], kBlockSize, &checksum);
+            if (ls.magic != kMagic && (ls.magic != kPartialRestoreMagic || validating)) {
+                status = error(EINVAL, "No magic");
+                break;
             }
 
-            if (le->checksum && checksum != le->checksum) {
-                LOG(ERROR) << "Checksums don't match " << std::hex << checksum;
-                return Status::fromExceptionCode(EINVAL, "Checksums don't match");
+            if (ls.block_size != original_ls.block_size) {
+                status = error(EINVAL, "Block size mismatch");
+                break;
             }
 
-            device.seekg(le->source * kSectorSize);
-            device.write(&buffer[0], le->size);
+            if ((int)ls.sequence != sequence) {
+                status = error(EINVAL, "Expecting log sector " + std::to_string(sequence) +
+                                           " but got " + std::to_string(ls.sequence));
+                break;
+            }
+
+            LOG(INFO) << action << " from log sector " << ls.sequence;
+            for (log_entry* le =
+                     reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]) + ls.count - 1;
+                 le >= reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]); --le) {
+                // This is very noisy - limit to DEBUG only
+                LOG(VERBOSE) << action << " " << le->size << " bytes from sector " << le->dest
+                             << " to " << le->source << " with checksum " << std::hex
+                             << le->checksum;
+
+                auto buffer = relocatedRead(device_fd, relocations, validating, le->dest, le->size,
+                                            ls.block_size);
+                uint32_t checksum = le->source / (ls.block_size / kSectorSize);
+                for (size_t i = 0; i < le->size; i += ls.block_size) {
+                    crc32(&buffer[i], ls.block_size, &checksum);
+                }
+
+                if (le->checksum && checksum != le->checksum) {
+                    status = error(EINVAL, "Checksums don't match");
+                    break;
+                }
+
+                if (validating) {
+                    relocate(relocations, le->source, le->dest, (le->size - 1) / kSectorSize + 1);
+                } else {
+                    restoreSector(device_fd, used_sectors, ls_buffer, le, buffer);
+                    restore_count++;
+                    if (restore_limit && restore_count >= restore_limit) {
+                        status = error(EAGAIN, "Hit the test limit");
+                        break;
+                    }
+                }
+            }
         }
+
+        if (!status.isOk()) {
+            if (!validating) {
+                LOG(ERROR) << "Checkpoint restore failed even though checkpoint validation passed";
+                return status;
+            }
+
+            LOG(WARNING) << "Checkpoint validation failed - attempting to roll forward";
+            auto buffer = relocatedRead(device_fd, relocations, false, original_ls.sector0,
+                                        original_ls.block_size, original_ls.block_size);
+            lseek64(device_fd, 0, SEEK_SET);
+            write(device_fd, &buffer[0], original_ls.block_size);
+            return Status::ok();
+        }
+
+        if (!validating) break;
+
+        validating = false;
+        action = "Restoring";
     }
 
     return Status::ok();
@@ -338,23 +719,26 @@
 
     // If the file doesn't exist, we aren't managing a checkpoint retry counter
     if (result != 0) return Status::ok();
-    if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) {
-        PLOG(ERROR) << "Failed to read checkpoint file";
-        return Status::fromExceptionCode(errno, "Failed to read checkpoint file");
-    }
+    if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent))
+        return error("Failed to read checkpoint file");
     std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" "));
 
     if (!android::base::ParseInt(retryContent, &retry))
-        return Status::fromExceptionCode(EINVAL, "Could not parse retry count");
+        return error(EINVAL, "Could not parse retry count");
     if (retry > 0) {
         retry--;
 
         newContent = std::to_string(retry);
         if (!android::base::WriteStringToFile(newContent, kMetadataCPFile))
-            return Status::fromExceptionCode(errno, "Could not write checkpoint file");
+            return error("Could not write checkpoint file");
     }
     return Status::ok();
 }
 
+void cp_resetCheckpoint() {
+    std::lock_guard<std::mutex> lock(isCheckpointingLock);
+    needsCheckpointWasCalled = false;
+}
+
 }  // namespace vold
 }  // namespace android
diff --git a/Checkpoint.h b/Checkpoint.h
index eac2f94..c1fb2b7 100644
--- a/Checkpoint.h
+++ b/Checkpoint.h
@@ -23,11 +23,17 @@
 namespace android {
 namespace vold {
 
+android::binder::Status cp_supportsCheckpoint(bool& result);
+
+android::binder::Status cp_supportsBlockCheckpoint(bool& result);
+
+android::binder::Status cp_supportsFileCheckpoint(bool& result);
+
 android::binder::Status cp_startCheckpoint(int retry);
 
 android::binder::Status cp_commitChanges();
 
-android::binder::Status cp_abortChanges();
+void cp_abortChanges(const std::string& message, bool retry);
 
 bool cp_needsRollback();
 
@@ -35,10 +41,11 @@
 
 android::binder::Status cp_prepareCheckpoint();
 
-android::binder::Status cp_restoreCheckpoint(const std::string& mountPoint);
+android::binder::Status cp_restoreCheckpoint(const std::string& mountPoint, int count = 0);
 
 android::binder::Status cp_markBootAttempt();
 
+void cp_resetCheckpoint();
 }  // namespace vold
 }  // namespace android
 
diff --git a/CryptoType.cpp b/CryptoType.cpp
new file mode 100644
index 0000000..155848e
--- /dev/null
+++ b/CryptoType.cpp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "CryptoType.h"
+
+#include <string.h>
+
+#include <android-base/logging.h>
+#include <cutils/properties.h>
+
+namespace android {
+namespace vold {
+
+const CryptoType& lookup_crypto_algorithm(const CryptoType table[], int table_len,
+                                          const CryptoType& default_alg, const char* property) {
+    char paramstr[PROPERTY_VALUE_MAX];
+
+    property_get(property, paramstr, default_alg.get_config_name());
+    for (int i = 0; i < table_len; i++) {
+        if (strcmp(paramstr, table[i].get_config_name()) == 0) {
+            return table[i];
+        }
+    }
+    LOG(ERROR) << "Invalid name (" << paramstr << ") for " << property << ".  Defaulting to "
+               << default_alg.get_config_name() << ".";
+    return default_alg;
+}
+
+}  // namespace vold
+}  // namespace android
diff --git a/CryptoType.h b/CryptoType.h
new file mode 100644
index 0000000..7ec419b
--- /dev/null
+++ b/CryptoType.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <stdlib.h>
+
+namespace android {
+namespace vold {
+
+// Struct representing an encryption algorithm supported by vold.
+// "config_name" represents the name we give the algorithm in
+// read-only properties and fstab files
+// "kernel_name" is the name we present to the Linux kernel
+// "keysize" is the size of the key in bytes.
+struct CryptoType {
+    // We should only be constructing CryptoTypes as part of
+    // supported_crypto_types[].  We do it via this pseudo-builder pattern,
+    // which isn't pure or fully protected as a concession to being able to
+    // do it all at compile time.  Add new CryptoTypes in
+    // supported_crypto_types[] below.
+    constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
+    constexpr CryptoType set_keysize(size_t size) const {
+        return CryptoType(this->config_name, this->kernel_name, size);
+    }
+    constexpr CryptoType set_config_name(const char* property) const {
+        return CryptoType(property, this->kernel_name, this->keysize);
+    }
+    constexpr CryptoType set_kernel_name(const char* crypto) const {
+        return CryptoType(this->config_name, crypto, this->keysize);
+    }
+
+    constexpr const char* get_config_name() const { return config_name; }
+    constexpr const char* get_kernel_name() const { return kernel_name; }
+    constexpr size_t get_keysize() const { return keysize; }
+
+  private:
+    const char* config_name;
+    const char* kernel_name;
+    size_t keysize;
+
+    constexpr CryptoType(const char* property, const char* crypto, size_t ksize)
+        : config_name(property), kernel_name(crypto), keysize(ksize) {}
+};
+
+// Use the named android property to look up a type from the table
+// If the property is not set or matches no table entry, return the default.
+const CryptoType& lookup_crypto_algorithm(const CryptoType table[], int table_len,
+                                          const CryptoType& default_alg, const char* property);
+
+// Some useful types
+
+constexpr CryptoType invalid_crypto_type = CryptoType();
+
+constexpr CryptoType aes_256_xts = CryptoType()
+                                           .set_config_name("aes-256-xts")
+                                           .set_kernel_name("aes-xts-plain64")
+                                           .set_keysize(64);
+
+constexpr CryptoType adiantum = CryptoType()
+                                        .set_config_name("adiantum")
+                                        .set_kernel_name("xchacha12,aes-adiantum-plain64")
+                                        .set_keysize(32);
+
+// Support compile-time validation of a crypto type table
+
+template <typename T, size_t N>
+constexpr size_t array_length(T (&)[N]) {
+    return N;
+}
+
+constexpr bool isValidCryptoType(size_t max_keylen, const CryptoType& crypto_type) {
+    return ((crypto_type.get_config_name() != nullptr) &&
+            (crypto_type.get_kernel_name() != nullptr) &&
+            (crypto_type.get_keysize() <= max_keylen));
+}
+
+// Confirms that all supported_crypto_types have a small enough keysize and
+// had both set_config_name() and set_kernel_name() called.
+// Note in C++11 that constexpr functions can only have a single line.
+// So our code is a bit convoluted (using recursion instead of a loop),
+// but it's asserting at compile time that all of our key lengths are valid.
+constexpr bool validateSupportedCryptoTypes(size_t max_keylen, const CryptoType types[],
+                                            size_t len) {
+    return len == 0 || (isValidCryptoType(max_keylen, types[len - 1]) &&
+                        validateSupportedCryptoTypes(max_keylen, types, len - 1));
+}
+
+}  // namespace vold
+}  // namespace android
diff --git a/Devmapper.cpp b/Devmapper.cpp
index b42467c..d55d92d 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -23,7 +23,6 @@
 #include <string.h>
 #include <unistd.h>
 
-#include <sys/ioctl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 
@@ -32,239 +31,72 @@
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
+#include <libdm/dm.h>
 #include <utils/Trace.h>
 
 #include "Devmapper.h"
 
-#define DEVMAPPER_BUFFER_SIZE 4096
-
 using android::base::StringPrintf;
+using namespace android::dm;
 
 static const char* kVoldPrefix = "vold:";
 
-void Devmapper::ioctlInit(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
-    memset(io, 0, dataSize);
-    io->data_size = dataSize;
-    io->data_start = sizeof(struct dm_ioctl);
-    io->version[0] = 4;
-    io->version[1] = 0;
-    io->version[2] = 0;
-    io->flags = flags;
-    if (name) {
-        size_t ret = strlcpy(io->name, name, sizeof(io->name));
-        if (ret >= sizeof(io->name)) abort();
-    }
-}
-
 int Devmapper::create(const char* name_raw, const char* loopFile, const char* key,
                       unsigned long numSectors, char* ubuffer, size_t len) {
+    auto& dm = DeviceMapper::Instance();
     auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw);
-    const char* name = name_string.c_str();
 
-    char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
-    if (!buffer) {
-        PLOG(ERROR) << "Failed malloc";
+    DmTable table;
+    table.Emplace<DmTargetCrypt>(0, numSectors, "twofish", key, 0, loopFile, 0);
+
+    if (!dm.CreateDevice(name_string, table)) {
+        LOG(ERROR) << "Failed to create device-mapper device " << name_string;
         return -1;
     }
 
-    int fd;
-    if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
-        PLOG(ERROR) << "Failed open";
-        free(buffer);
+    std::string path;
+    if (!dm.GetDmDevicePathByName(name_string, &path)) {
+        LOG(ERROR) << "Failed to get device-mapper device path for " << name_string;
         return -1;
     }
-
-    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
-
-    // Create the DM device
-    ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
-    if (ioctl(fd, DM_DEV_CREATE, io)) {
-        PLOG(ERROR) << "Failed DM_DEV_CREATE";
-        free(buffer);
-        close(fd);
-        return -1;
-    }
-
-    // Set the legacy geometry
-    ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
-    char* geoParams = buffer + sizeof(struct dm_ioctl);
-    // bps=512 spc=8 res=32 nft=2 sec=8190 mid=0xf0 spt=63 hds=64 hid=0 bspf=8 rdcl=2 infs=1 bkbs=2
-    strlcpy(geoParams, "0 64 63 0", DEVMAPPER_BUFFER_SIZE - sizeof(struct dm_ioctl));
-    geoParams += strlen(geoParams) + 1;
-    geoParams = (char*)_align(geoParams, 8);
-    if (ioctl(fd, DM_DEV_SET_GEOMETRY, io)) {
-        PLOG(ERROR) << "Failed DM_DEV_SET_GEOMETRY";
-        free(buffer);
-        close(fd);
-        return -1;
-    }
-
-    // Retrieve the device number we were allocated
-    ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-    if (ioctl(fd, DM_DEV_STATUS, io)) {
-        PLOG(ERROR) << "Failed DM_DEV_STATUS";
-        free(buffer);
-        close(fd);
-        return -1;
-    }
-
-    unsigned minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
-    snprintf(ubuffer, len, "/dev/block/dm-%u", minor);
-
-    // Load the table
-    struct dm_target_spec* tgt;
-    tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
-
-    ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, DM_STATUS_TABLE_FLAG);
-    io->target_count = 1;
-    tgt->status = 0;
-
-    tgt->sector_start = 0;
-    tgt->length = numSectors;
-
-    strlcpy(tgt->target_type, "crypt", sizeof(tgt->target_type));
-
-    char* cryptParams = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
-    snprintf(cryptParams,
-             DEVMAPPER_BUFFER_SIZE - (sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec)),
-             "twofish %s 0 %s 0", key, loopFile);
-    cryptParams += strlen(cryptParams) + 1;
-    cryptParams = (char*)_align(cryptParams, 8);
-    tgt->next = cryptParams - buffer;
-
-    if (ioctl(fd, DM_TABLE_LOAD, io)) {
-        PLOG(ERROR) << "Failed DM_TABLE_LOAD";
-        free(buffer);
-        close(fd);
-        return -1;
-    }
-
-    // Resume the new table
-    ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
-    if (ioctl(fd, DM_DEV_SUSPEND, io)) {
-        PLOG(ERROR) << "Failed DM_DEV_SUSPEND";
-        free(buffer);
-        close(fd);
-        return -1;
-    }
-
-    free(buffer);
-
-    close(fd);
+    snprintf(ubuffer, len, "%s", path.c_str());
     return 0;
 }
 
 int Devmapper::destroy(const char* name_raw) {
+    auto& dm = DeviceMapper::Instance();
+
     auto name_string = StringPrintf("%s%s", kVoldPrefix, name_raw);
-    const char* name = name_string.c_str();
-
-    char* buffer = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
-    if (!buffer) {
-        PLOG(ERROR) << "Failed malloc";
-        return -1;
-    }
-
-    int fd;
-    if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
-        PLOG(ERROR) << "Failed open";
-        free(buffer);
-        return -1;
-    }
-
-    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
-
-    // Create the DM device
-    ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
-
-    if (ioctl(fd, DM_DEV_REMOVE, io)) {
+    if (!dm.DeleteDevice(name_string)) {
         if (errno != ENXIO) {
             PLOG(ERROR) << "Failed DM_DEV_REMOVE";
         }
-        free(buffer);
-        close(fd);
         return -1;
     }
-
-    free(buffer);
-    close(fd);
     return 0;
 }
 
 int Devmapper::destroyAll() {
     ATRACE_NAME("Devmapper::destroyAll");
-    char* buffer = (char*)malloc(1024 * 64);
-    if (!buffer) {
-        PLOG(ERROR) << "Failed malloc";
-        return -1;
-    }
-    memset(buffer, 0, (1024 * 64));
 
-    char* buffer2 = (char*)malloc(DEVMAPPER_BUFFER_SIZE);
-    if (!buffer2) {
-        PLOG(ERROR) << "Failed malloc";
-        free(buffer);
+    auto& dm = DeviceMapper::Instance();
+    std::vector<DeviceMapper::DmBlockDevice> devices;
+    if (!dm.GetAvailableDevices(&devices)) {
+        LOG(ERROR) << "Failed to get dm devices";
         return -1;
     }
 
-    int fd;
-    if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
-        PLOG(ERROR) << "Failed open";
-        free(buffer);
-        free(buffer2);
-        return -1;
-    }
-
-    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
-    ioctlInit(io, (1024 * 64), NULL, 0);
-
-    if (ioctl(fd, DM_LIST_DEVICES, io)) {
-        PLOG(ERROR) << "Failed DM_LIST_DEVICES";
-        free(buffer);
-        free(buffer2);
-        close(fd);
-        return -1;
-    }
-
-    struct dm_name_list* n = (struct dm_name_list*)(((char*)buffer) + io->data_start);
-    if (!n->dev) {
-        free(buffer);
-        free(buffer2);
-        close(fd);
-        return 0;
-    }
-
-    unsigned nxt = 0;
-    do {
-        n = (struct dm_name_list*)(((char*)n) + nxt);
-        auto name = std::string(n->name);
-        if (android::base::StartsWith(name, kVoldPrefix)) {
-            LOG(DEBUG) << "Tearing down stale dm device named " << name;
-
-            memset(buffer2, 0, DEVMAPPER_BUFFER_SIZE);
-            struct dm_ioctl* io2 = (struct dm_ioctl*)buffer2;
-            ioctlInit(io2, DEVMAPPER_BUFFER_SIZE, n->name, 0);
-            if (ioctl(fd, DM_DEV_REMOVE, io2)) {
+    for (const auto& device : devices) {
+        if (android::base::StartsWith(device.name(), kVoldPrefix)) {
+            LOG(DEBUG) << "Tearing down stale dm device named " << device.name();
+            if (!dm.DeleteDevice(device.name())) {
                 if (errno != ENXIO) {
-                    PLOG(WARNING) << "Failed to destroy dm device named " << name;
+                    PLOG(WARNING) << "Failed to destroy dm device named " << device.name();
                 }
             }
         } else {
-            LOG(DEBUG) << "Found unmanaged dm device named " << name;
+            LOG(DEBUG) << "Found unmanaged dm device named " << device.name();
         }
-        nxt = n->next;
-    } while (nxt);
-
-    free(buffer);
-    free(buffer2);
-    close(fd);
+    }
     return 0;
 }
-
-void* Devmapper::_align(void* ptr, unsigned int a) {
-    unsigned long agn = --a;
-
-    return (void*)(((unsigned long)ptr + agn) & ~agn);
-}
diff --git a/Devmapper.h b/Devmapper.h
index b1f6dfa..9d4896e 100644
--- a/Devmapper.h
+++ b/Devmapper.h
@@ -26,10 +26,6 @@
                       unsigned long numSectors, char* buffer, size_t len);
     static int destroy(const char* name);
     static int destroyAll();
-
-  private:
-    static void* _align(void* ptr, unsigned int a);
-    static void ioctlInit(struct dm_ioctl* io, size_t data_size, const char* name, unsigned flags);
 };
 
 #endif
diff --git a/EncryptInplace.cpp b/EncryptInplace.cpp
index d559bff..9d304da 100644
--- a/EncryptInplace.cpp
+++ b/EncryptInplace.cpp
@@ -62,7 +62,8 @@
     off64_t one_pct, cur_pct, new_pct;
     off64_t blocks_already_done, tot_numblocks;
     off64_t used_blocks_already_done, tot_used_blocks;
-    char *real_blkdev, *crypto_blkdev;
+    const char* real_blkdev;
+    const char* crypto_blkdev;
     int count;
     off64_t offset;
     char* buffer;
@@ -244,8 +245,8 @@
     return rc;
 }
 
-static int cryptfs_enable_inplace_ext4(char* crypto_blkdev, char* real_blkdev, off64_t size,
-                                       off64_t* size_already_done, off64_t tot_size,
+static int cryptfs_enable_inplace_ext4(const char* crypto_blkdev, const char* real_blkdev,
+                                       off64_t size, off64_t* size_already_done, off64_t tot_size,
                                        off64_t previously_encrypted_upto,
                                        bool set_progress_properties) {
     u32 i;
@@ -383,13 +384,15 @@
     return 0;
 }
 
-static int cryptfs_enable_inplace_f2fs(char* crypto_blkdev, char* real_blkdev, off64_t size,
-                                       off64_t* size_already_done, off64_t tot_size,
+static int cryptfs_enable_inplace_f2fs(const char* crypto_blkdev, const char* real_blkdev,
+                                       off64_t size, off64_t* size_already_done, off64_t tot_size,
                                        off64_t previously_encrypted_upto,
                                        bool set_progress_properties) {
     struct encryptGroupsData data;
     struct f2fs_info* f2fs_info = NULL;
     int rc = ENABLE_INPLACE_ERR_OTHER;
+    struct timespec time_started = {0};
+
     if (previously_encrypted_upto > *size_already_done) {
         LOG(DEBUG) << "Not fast encrypting since resuming part way through";
         return ENABLE_INPLACE_ERR_OTHER;
@@ -422,9 +425,14 @@
 
     data.one_pct = data.tot_used_blocks / 100;
     data.cur_pct = 0;
-    data.time_started = time(NULL);
+    if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
+        LOG(WARNING) << "Error getting time at start";
+        // Note - continue anyway - we'll run with 0
+    }
+    data.time_started = time_started.tv_sec;
     data.remaining_time = -1;
 
+
     data.buffer = (char*)malloc(f2fs_info->block_size);
     if (!data.buffer) {
         LOG(ERROR) << "Failed to allocate crypto buffer";
@@ -457,8 +465,8 @@
     return rc;
 }
 
-static int cryptfs_enable_inplace_full(char* crypto_blkdev, char* real_blkdev, off64_t size,
-                                       off64_t* size_already_done, off64_t tot_size,
+static int cryptfs_enable_inplace_full(const char* crypto_blkdev, const char* real_blkdev,
+                                       off64_t size, off64_t* size_already_done, off64_t tot_size,
                                        off64_t previously_encrypted_upto,
                                        bool set_progress_properties) {
     int realfd, cryptofd;
@@ -524,11 +532,11 @@
     for (i /= CRYPT_SECTORS_PER_BUFSIZE; i < numblocks; i++) {
         new_pct = (i + blocks_already_done) / one_pct;
         if (set_progress_properties && new_pct > cur_pct) {
-            char buf[8];
+            char property_buf[8];
 
             cur_pct = new_pct;
-            snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
-            android::base::SetProperty("vold.encrypt_progress", buf);
+            snprintf(property_buf, sizeof(property_buf), "%" PRId64, cur_pct);
+            android::base::SetProperty("vold.encrypt_progress", property_buf);
         }
         if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
             PLOG(ERROR) << "Error reading real_blkdev " << real_blkdev << " for inplace encrypt";
@@ -570,7 +578,7 @@
 }
 
 /* returns on of the ENABLE_INPLACE_* return codes */
-int cryptfs_enable_inplace(char* crypto_blkdev, char* real_blkdev, off64_t size,
+int cryptfs_enable_inplace(const char* crypto_blkdev, const char* real_blkdev, off64_t size,
                            off64_t* size_already_done, off64_t tot_size,
                            off64_t previously_encrypted_upto, bool set_progress_properties) {
     int rc_ext4, rc_f2fs, rc_full;
diff --git a/EncryptInplace.h b/EncryptInplace.h
index 71644ac..a2b46cf 100644
--- a/EncryptInplace.h
+++ b/EncryptInplace.h
@@ -24,7 +24,12 @@
 #define RETRY_MOUNT_ATTEMPTS 10
 #define RETRY_MOUNT_DELAY_SECONDS 1
 
-int cryptfs_enable_inplace(char* crypto_blkdev, char* real_blkdev, off64_t size,
+/* Return values for cryptfs_enable_inplace() */
+#define ENABLE_INPLACE_OK 0
+#define ENABLE_INPLACE_ERR_OTHER (-1)
+#define ENABLE_INPLACE_ERR_DEV (-2) /* crypto_blkdev issue */
+
+int cryptfs_enable_inplace(const char* crypto_blkdev, const char* real_blkdev, off64_t size,
                            off64_t* size_already_done, off64_t tot_size,
                            off64_t previously_encrypted_upto, bool set_progress_properties);
 
diff --git a/FileDeviceUtils.cpp b/FileDeviceUtils.cpp
index ce938a9..c745b54 100644
--- a/FileDeviceUtils.cpp
+++ b/FileDeviceUtils.cpp
@@ -61,7 +61,6 @@
         LOG(ERROR) << "Didn't find a mountpoint to match path " << path;
         return "";
     }
-    LOG(DEBUG) << "For path " << path << " block device is " << result;
     return result;
 }
 
diff --git a/FsCrypt.cpp b/FsCrypt.cpp
index 087b916..aa66c01 100644
--- a/FsCrypt.cpp
+++ b/FsCrypt.cpp
@@ -23,6 +23,7 @@
 
 #include <algorithm>
 #include <map>
+#include <optional>
 #include <set>
 #include <sstream>
 #include <string>
@@ -42,8 +43,6 @@
 
 #include "android/os/IVold.h"
 
-#include "cryptfs.h"
-
 #define EMULATED_USES_SELINUX 0
 #define MANAGE_MISC_DIRS 0
 
@@ -57,20 +56,22 @@
 #include <android-base/logging.h>
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
 
 using android::base::StringPrintf;
-using android::base::WriteStringToFile;
+using android::fs_mgr::GetEntryForMountPoint;
+using android::vold::BuildDataPath;
 using android::vold::kEmptyAuthentication;
 using android::vold::KeyBuffer;
+using android::vold::KeyGeneration;
+using android::vold::retrieveKey;
+using android::vold::retrieveOrGenerateKey;
+using android::vold::writeStringToFile;
+using namespace android::fscrypt;
 
 namespace {
 
-struct PolicyKeyRef {
-    std::string contents_mode;
-    std::string filenames_mode;
-    std::string key_raw_ref;
-};
-
 const std::string device_key_dir = std::string() + DATA_MNT_POINT + fscrypt_unencrypted_folder;
 const std::string device_key_path = device_key_dir + "/key";
 const std::string device_key_temp = device_key_dir + "/temp";
@@ -82,19 +83,20 @@
 const std::string systemwide_volume_key_dir =
     std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
 
-bool s_global_de_initialized = false;
-
 // Some users are ephemeral, don't try to wipe their keys from disk
 std::set<userid_t> s_ephemeral_users;
 
-// Map user ids to key references
-std::map<userid_t, std::string> s_de_key_raw_refs;
-std::map<userid_t, std::string> s_ce_key_raw_refs;
-// TODO abolish this map, per b/26948053
-std::map<userid_t, KeyBuffer> s_ce_keys;
+// Map user ids to encryption policies
+std::map<userid_t, EncryptionPolicy> s_de_policies;
+std::map<userid_t, EncryptionPolicy> s_ce_policies;
 
 }  // namespace
 
+// Returns KeyGeneration suitable for key as described in EncryptionOptions
+static KeyGeneration makeGen(const EncryptionOptions& options) {
+    return KeyGeneration{FSCRYPT_MAX_KEY_SIZE, true, options.use_hw_wrapped_key};
+}
+
 static bool fscrypt_is_emulated() {
     return property_get_bool("persist.sys.emulate_fbe", false);
 }
@@ -174,8 +176,10 @@
         LOG(DEBUG) << "Renaming " << to_fix << " to " << current_path;
         if (rename(to_fix.c_str(), current_path.c_str()) != 0) {
             PLOG(WARNING) << "Unable to rename " << to_fix << " to " << current_path;
+            return;
         }
     }
+    android::vold::FsyncDirectory(directory_path);
 }
 
 static bool read_and_fixate_user_ce_key(userid_t user_id,
@@ -185,7 +189,7 @@
     auto const paths = get_ce_key_paths(directory_path);
     for (auto const ce_key_path : paths) {
         LOG(DEBUG) << "Trying user CE key " << ce_key_path;
-        if (android::vold::retrieveKey(ce_key_path, auth, ce_key)) {
+        if (retrieveKey(ce_key_path, auth, ce_key)) {
             LOG(DEBUG) << "Successfully retrieved key";
             fixate_user_ce_key(directory_path, ce_key_path, paths);
             return true;
@@ -195,15 +199,64 @@
     return false;
 }
 
+// Retrieve the options to use for encryption policies on the /data filesystem.
+static bool get_data_file_encryption_options(EncryptionOptions* options) {
+    auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+    if (entry == nullptr) {
+        LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
+        return false;
+    }
+    if (!ParseOptions(entry->encryption_options, options)) {
+        LOG(ERROR) << "Unable to parse encryption options for " << DATA_MNT_POINT ": "
+                   << entry->encryption_options;
+        return false;
+    }
+    return true;
+}
+
+static bool install_storage_key(const std::string& mountpoint, const EncryptionOptions& options,
+                                const KeyBuffer& key, EncryptionPolicy* policy) {
+    KeyBuffer ephemeral_wrapped_key;
+    if (options.use_hw_wrapped_key) {
+        if (!exportWrappedStorageKey(key, &ephemeral_wrapped_key)) {
+            LOG(ERROR) << "Failed to get ephemeral wrapped key";
+            return false;
+        }
+    }
+    return installKey(mountpoint, options, options.use_hw_wrapped_key ? ephemeral_wrapped_key : key,
+                      policy);
+}
+
+// Retrieve the options to use for encryption policies on adoptable storage.
+static bool get_volume_file_encryption_options(EncryptionOptions* options) {
+    // If we give the empty string, libfscrypt will use the default (currently XTS)
+    auto contents_mode = android::base::GetProperty("ro.crypto.volume.contents_mode", "");
+    // HEH as default was always a mistake. Use the libfscrypt default (CTS)
+    // for devices launching on versions above Android 10.
+    auto first_api_level = GetFirstApiLevel();
+    constexpr uint64_t pre_gki_level = 29;
+    auto filenames_mode =
+            android::base::GetProperty("ro.crypto.volume.filenames_mode",
+                                       first_api_level > pre_gki_level ? "" : "aes-256-heh");
+    auto options_string = android::base::GetProperty("ro.crypto.volume.options",
+                                                     contents_mode + ":" + filenames_mode);
+    if (!ParseOptionsForApiLevel(first_api_level, options_string, options)) {
+        LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
+        return false;
+    }
+    return true;
+}
+
 static bool read_and_install_user_ce_key(userid_t user_id,
                                          const android::vold::KeyAuthentication& auth) {
-    if (s_ce_key_raw_refs.count(user_id) != 0) return true;
+    if (s_ce_policies.count(user_id) != 0) return true;
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
     KeyBuffer ce_key;
     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
-    std::string ce_raw_ref;
-    if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
-    s_ce_keys[user_id] = std::move(ce_key);
-    s_ce_key_raw_refs[user_id] = ce_raw_ref;
+    EncryptionPolicy ce_policy;
+    if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
+    s_ce_policies[user_id] = ce_policy;
     LOG(DEBUG) << "Installed ce key for user " << user_id;
     return true;
 }
@@ -229,9 +282,11 @@
 // NB this assumes that there is only one thread listening for crypt commands, because
 // it creates keys in a fixed location.
 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
     KeyBuffer de_key, ce_key;
-    if (!android::vold::randomKey(&de_key)) return false;
-    if (!android::vold::randomKey(&ce_key)) return false;
+    if (!generateStorageKey(makeGen(options), &de_key)) return false;
+    if (!generateStorageKey(makeGen(options), &ce_key)) return false;
     if (create_ephemeral) {
         // If the key should be created as ephemeral, don't store it.
         s_ephemeral_users.insert(user_id);
@@ -250,43 +305,27 @@
                                                kEmptyAuthentication, de_key))
             return false;
     }
-    std::string de_raw_ref;
-    if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
-    s_de_key_raw_refs[user_id] = de_raw_ref;
-    std::string ce_raw_ref;
-    if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
-    s_ce_keys[user_id] = ce_key;
-    s_ce_key_raw_refs[user_id] = ce_raw_ref;
+    EncryptionPolicy de_policy;
+    if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
+    s_de_policies[user_id] = de_policy;
+    EncryptionPolicy ce_policy;
+    if (!install_storage_key(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
+    s_ce_policies[user_id] = ce_policy;
     LOG(DEBUG) << "Created keys for user " << user_id;
     return true;
 }
 
-static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
-                           std::string* raw_ref) {
+static bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
+                          EncryptionPolicy* policy) {
     auto refi = key_map.find(user_id);
     if (refi == key_map.end()) {
-        LOG(ERROR) << "Cannot find key for " << user_id;
+        LOG(DEBUG) << "Cannot find key for " << user_id;
         return false;
     }
-    *raw_ref = refi->second;
+    *policy = refi->second;
     return true;
 }
 
-static void get_data_file_encryption_modes(PolicyKeyRef* key_ref) {
-    struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
-    char const* contents_mode;
-    char const* filenames_mode;
-    fs_mgr_get_file_encryption_modes(rec, &contents_mode, &filenames_mode);
-    key_ref->contents_mode = contents_mode;
-    key_ref->filenames_mode = filenames_mode;
-}
-
-static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
-    return fscrypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
-                                 key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
-                                 key_ref.filenames_mode.c_str()) == 0;
-}
-
 static bool is_numeric(const char* name) {
     for (const char* p = name; *p != '\0'; p++) {
         if (!isdigit(*p)) return false;
@@ -295,6 +334,8 @@
 }
 
 static bool load_all_de_keys() {
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
     auto de_dir = user_key_dir + "/de";
     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
     if (!dirp) {
@@ -316,50 +357,70 @@
             continue;
         }
         userid_t user_id = std::stoi(entry->d_name);
-        if (s_de_key_raw_refs.count(user_id) == 0) {
-            auto key_path = de_dir + "/" + entry->d_name;
-            KeyBuffer key;
-            if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
-            std::string raw_ref;
-            if (!android::vold::installKey(key, &raw_ref)) return false;
-            s_de_key_raw_refs[user_id] = raw_ref;
-            LOG(DEBUG) << "Installed de key for user " << user_id;
+        auto key_path = de_dir + "/" + entry->d_name;
+        KeyBuffer de_key;
+        if (!retrieveKey(key_path, kEmptyAuthentication, &de_key)) return false;
+        EncryptionPolicy de_policy;
+        if (!install_storage_key(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
+        auto ret = s_de_policies.insert({user_id, de_policy});
+        if (!ret.second && ret.first->second != de_policy) {
+            LOG(ERROR) << "DE policy for user" << user_id << " changed";
+            return false;
         }
+        LOG(DEBUG) << "Installed de key for user " << user_id;
     }
     // fscrypt:TODO: go through all DE directories, ensure that all user dirs have the
     // correct policy set on them, and that no rogue ones exist.
     return true;
 }
 
-bool fscrypt_initialize_global_de() {
-    LOG(INFO) << "fscrypt_initialize_global_de";
-
-    if (s_global_de_initialized) {
-        LOG(INFO) << "Already initialized";
-        return true;
+// Attempt to reinstall CE keys for users that we think are unlocked.
+static bool try_reload_ce_keys() {
+    for (const auto& it : s_ce_policies) {
+        if (!android::vold::reloadKeyFromSessionKeyring(DATA_MNT_POINT, it.second)) {
+            LOG(ERROR) << "Failed to load CE key from session keyring for user " << it.first;
+            return false;
+        }
     }
+    return true;
+}
 
-    PolicyKeyRef device_ref;
-    if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
-                                              device_key_temp, &device_ref.key_raw_ref))
+bool fscrypt_initialize_systemwide_keys() {
+    LOG(INFO) << "fscrypt_initialize_systemwide_keys";
+
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
+
+    KeyBuffer device_key;
+    if (!retrieveOrGenerateKey(device_key_path, device_key_temp, kEmptyAuthentication,
+                               makeGen(options), &device_key))
         return false;
-    get_data_file_encryption_modes(&device_ref);
 
-    std::string modestring = device_ref.contents_mode + ":" + device_ref.filenames_mode;
-    std::string mode_filename = std::string("/data") + fscrypt_key_mode;
-    if (!android::base::WriteStringToFile(modestring, mode_filename)) {
-        PLOG(ERROR) << "Cannot save type";
+    EncryptionPolicy device_policy;
+    if (!install_storage_key(DATA_MNT_POINT, options, device_key, &device_policy)) return false;
+
+    std::string options_string;
+    if (!OptionsToString(device_policy.options, &options_string)) {
+        LOG(ERROR) << "Unable to serialize options";
         return false;
     }
+    std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
+    if (!android::vold::writeStringToFile(options_string, options_filename)) return false;
 
-    std::string ref_filename = std::string("/data") + fscrypt_key_ref;
-    if (!android::base::WriteStringToFile(device_ref.key_raw_ref, ref_filename)) {
-        PLOG(ERROR) << "Cannot save key reference to:" << ref_filename;
-        return false;
-    }
+    std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
+    if (!android::vold::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
     LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
 
-    s_global_de_initialized = true;
+    KeyBuffer per_boot_key;
+    if (!generateStorageKey(makeGen(options), &per_boot_key)) return false;
+    EncryptionPolicy per_boot_policy;
+    if (!install_storage_key(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy)) return false;
+    std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
+    if (!android::vold::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
+        return false;
+    LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
+
+    if (!android::vold::FsyncDirectory(device_key_dir)) return false;
     return true;
 }
 
@@ -390,6 +451,13 @@
         fscrypt_unlock_user_key(0, 0, "!", "!");
     }
 
+    // In some scenarios (e.g. userspace reboot) we might unmount userdata
+    // without doing a hard reboot. If CE keys were stored in fs keyring then
+    // they will be lost after unmount. Attempt to re-install them.
+    if (fscrypt_is_native() && android::vold::isFsKeyringSupported()) {
+        if (!try_reload_ce_keys()) return false;
+    }
+
     return true;
 }
 
@@ -399,7 +467,7 @@
         return true;
     }
     // FIXME test for existence of key that is not loaded yet
-    if (s_ce_key_raw_refs.count(user_id) != 0) {
+    if (s_ce_policies.count(user_id) != 0) {
         LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
                    << " serial " << serial;
         // FIXME should we fail the command?
@@ -411,25 +479,36 @@
     return true;
 }
 
-static void drop_caches() {
-    // Clean any dirty pages (otherwise they won't be dropped).
+// "Lock" all encrypted directories whose key has been removed.  This is needed
+// in the case where the keys are being put in the session keyring (rather in
+// the newer filesystem-level keyrings), because removing a key from the session
+// keyring doesn't affect inodes in the kernel's inode cache whose per-file key
+// was already set up.  So to remove the per-file keys and make the files
+// "appear encrypted", these inodes must be evicted.
+//
+// To do this, sync() to clean all dirty inodes, then drop all reclaimable slab
+// objects systemwide.  This is overkill, but it's the best available method
+// currently.  Don't use drop_caches mode "3" because that also evicts pagecache
+// for in-use files; all files relevant here are already closed and sync'ed.
+static void drop_caches_if_needed() {
+    if (android::vold::isFsKeyringSupported()) {
+        return;
+    }
     sync();
-    // Drop inode and page caches.
-    if (!WriteStringToFile("3", "/proc/sys/vm/drop_caches")) {
+    if (!writeStringToFile("2", "/proc/sys/vm/drop_caches")) {
         PLOG(ERROR) << "Failed to drop caches during key eviction";
     }
 }
 
 static bool evict_ce_key(userid_t user_id) {
-    s_ce_keys.erase(user_id);
     bool success = true;
-    std::string raw_ref;
+    EncryptionPolicy policy;
     // If we haven't loaded the CE key, no need to evict it.
-    if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
-        success &= android::vold::evictKey(raw_ref);
-        drop_caches();
+    if (lookup_policy(s_ce_policies, user_id, &policy)) {
+        success &= android::vold::evictKey(DATA_MNT_POINT, policy);
+        drop_caches_if_needed();
     }
-    s_ce_key_raw_refs.erase(user_id);
+    s_ce_policies.erase(user_id);
     return success;
 }
 
@@ -439,11 +518,11 @@
         return true;
     }
     bool success = true;
-    std::string raw_ref;
     success &= evict_ce_key(user_id);
-    success &=
-        lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && android::vold::evictKey(raw_ref);
-    s_de_key_raw_refs.erase(user_id);
+    EncryptionPolicy de_policy;
+    success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
+               android::vold::evictKey(DATA_MNT_POINT, de_policy);
+    s_de_policies.erase(user_id);
     auto it = s_ephemeral_users.find(user_id);
     if (it != s_ephemeral_users.end()) {
         s_ephemeral_users.erase(it);
@@ -503,6 +582,18 @@
     return true;
 }
 
+static std::optional<android::vold::KeyAuthentication> authentication_from_hex(
+        const std::string& token_hex, const std::string& secret_hex) {
+    std::string token, secret;
+    if (!parse_hex(token_hex, &token)) return std::optional<android::vold::KeyAuthentication>();
+    if (!parse_hex(secret_hex, &secret)) return std::optional<android::vold::KeyAuthentication>();
+    if (secret.empty()) {
+        return kEmptyAuthentication;
+    } else {
+        return android::vold::KeyAuthentication(token, secret);
+    }
+}
+
 static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
     return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
 }
@@ -512,7 +603,7 @@
 }
 
 static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
-                                  PolicyKeyRef* key_ref) {
+                                  EncryptionPolicy* policy) {
     auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
     std::string secdiscardable_hash;
     if (android::vold::pathExists(secdiscardable_path)) {
@@ -532,13 +623,13 @@
         return false;
     }
     android::vold::KeyAuthentication auth("", secdiscardable_hash);
-    if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
-                                              &key_ref->key_raw_ref))
+
+    EncryptionOptions options;
+    if (!get_volume_file_encryption_options(&options)) return false;
+    KeyBuffer key;
+    if (!retrieveOrGenerateKey(key_path, key_path + "_tmp", auth, makeGen(options), &key))
         return false;
-    key_ref->contents_mode =
-        android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
-    key_ref->filenames_mode =
-        android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
+    if (!install_storage_key(BuildDataPath(volume_uuid), options, key, policy)) return false;
     return true;
 }
 
@@ -548,29 +639,51 @@
     return android::vold::destroyKey(path);
 }
 
+static bool fscrypt_rewrap_user_key(userid_t user_id, int serial,
+                                    const android::vold::KeyAuthentication& retrieve_auth,
+                                    const android::vold::KeyAuthentication& store_auth) {
+    if (s_ephemeral_users.count(user_id) != 0) return true;
+    auto const directory_path = get_ce_key_directory_path(user_id);
+    KeyBuffer ce_key;
+    std::string ce_key_current_path = get_ce_key_current_path(directory_path);
+    if (retrieveKey(ce_key_current_path, retrieve_auth, &ce_key)) {
+        LOG(DEBUG) << "Successfully retrieved key";
+        // TODO(147732812): Remove this once Locksettingservice is fixed.
+        // Currently it calls fscrypt_clear_user_key_auth with a secret when lockscreen is
+        // changed from swipe to none or vice-versa
+    } else if (retrieveKey(ce_key_current_path, kEmptyAuthentication, &ce_key)) {
+        LOG(DEBUG) << "Successfully retrieved key with empty auth";
+    } else {
+        LOG(ERROR) << "Failed to retrieve key for user " << user_id;
+        return false;
+    }
+    auto const paths = get_ce_key_paths(directory_path);
+    std::string ce_key_path;
+    if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
+    if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, store_auth, ce_key))
+        return false;
+    if (!android::vold::FsyncDirectory(directory_path)) return false;
+    return true;
+}
+
 bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
                                const std::string& secret_hex) {
     LOG(DEBUG) << "fscrypt_add_user_key_auth " << user_id << " serial=" << serial
                << " token_present=" << (token_hex != "!");
     if (!fscrypt_is_native()) return true;
-    if (s_ephemeral_users.count(user_id) != 0) return true;
-    std::string token, secret;
-    if (!parse_hex(token_hex, &token)) return false;
-    if (!parse_hex(secret_hex, &secret)) return false;
-    auto auth =
-        secret.empty() ? kEmptyAuthentication : android::vold::KeyAuthentication(token, secret);
-    auto it = s_ce_keys.find(user_id);
-    if (it == s_ce_keys.end()) {
-        LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
-        return false;
-    }
-    const auto& ce_key = it->second;
-    auto const directory_path = get_ce_key_directory_path(user_id);
-    auto const paths = get_ce_key_paths(directory_path);
-    std::string ce_key_path;
-    if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
-    if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
-    return true;
+    auto auth = authentication_from_hex(token_hex, secret_hex);
+    if (!auth) return false;
+    return fscrypt_rewrap_user_key(user_id, serial, kEmptyAuthentication, *auth);
+}
+
+bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
+                                 const std::string& secret_hex) {
+    LOG(DEBUG) << "fscrypt_clear_user_key_auth " << user_id << " serial=" << serial
+               << " token_present=" << (token_hex != "!");
+    if (!fscrypt_is_native()) return true;
+    auto auth = authentication_from_hex(token_hex, secret_hex);
+    if (!auth) return false;
+    return fscrypt_rewrap_user_key(user_id, serial, *auth, kEmptyAuthentication);
 }
 
 bool fscrypt_fixate_newest_user_key_auth(userid_t user_id) {
@@ -593,15 +706,13 @@
     LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
                << " token_present=" << (token_hex != "!");
     if (fscrypt_is_native()) {
-        if (s_ce_key_raw_refs.count(user_id) != 0) {
+        if (s_ce_policies.count(user_id) != 0) {
             LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
             return true;
         }
-        std::string token, secret;
-        if (!parse_hex(token_hex, &token)) return false;
-        if (!parse_hex(secret_hex, &secret)) return false;
-        android::vold::KeyAuthentication auth(token, secret);
-        if (!read_and_install_user_ce_key(user_id, auth)) {
+        auto auth = authentication_from_hex(token_hex, secret_hex);
+        if (!auth) return false;
+        if (!read_and_install_user_ce_key(user_id, *auth)) {
             LOG(ERROR) << "Couldn't read key for " << user_id;
             return false;
         }
@@ -683,17 +794,16 @@
         if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
 
         if (fscrypt_is_native()) {
-            PolicyKeyRef de_ref;
+            EncryptionPolicy de_policy;
             if (volume_uuid.empty()) {
-                if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
-                get_data_file_encryption_modes(&de_ref);
-                if (!ensure_policy(de_ref, system_de_path)) return false;
-                if (!ensure_policy(de_ref, misc_de_path)) return false;
-                if (!ensure_policy(de_ref, vendor_de_path)) return false;
+                if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
+                if (!EnsurePolicy(de_policy, system_de_path)) return false;
+                if (!EnsurePolicy(de_policy, misc_de_path)) return false;
+                if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
             } else {
-                if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_ref)) return false;
+                if (!read_or_create_volkey(misc_de_path, volume_uuid, &de_policy)) return false;
             }
-            if (!ensure_policy(de_ref, user_de_path)) return false;
+            if (!EnsurePolicy(de_policy, user_de_path)) return false;
         }
     }
 
@@ -714,19 +824,17 @@
         if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
 
         if (fscrypt_is_native()) {
-            PolicyKeyRef ce_ref;
+            EncryptionPolicy ce_policy;
             if (volume_uuid.empty()) {
-                if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
-                get_data_file_encryption_modes(&ce_ref);
-                if (!ensure_policy(ce_ref, system_ce_path)) return false;
-                if (!ensure_policy(ce_ref, misc_ce_path)) return false;
-                if (!ensure_policy(ce_ref, vendor_ce_path)) return false;
-
+                if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
+                if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
+                if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
+                if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
             } else {
-                if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_ref)) return false;
+                if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_policy)) return false;
             }
-            if (!ensure_policy(ce_ref, media_ce_path)) return false;
-            if (!ensure_policy(ce_ref, user_ce_path)) return false;
+            if (!EnsurePolicy(ce_policy, media_ce_path)) return false;
+            if (!EnsurePolicy(ce_policy, user_ce_path)) return false;
         }
 
         if (volume_uuid.empty()) {
@@ -734,6 +842,7 @@
             // over these paths
             // NOTE: these paths need to be kept in sync with libselinux
             android::vold::RestoreconRecursive(system_ce_path);
+            android::vold::RestoreconRecursive(vendor_ce_path);
             android::vold::RestoreconRecursive(misc_ce_path);
         }
     }
diff --git a/FsCrypt.h b/FsCrypt.h
index 16e2f9a..641991a 100644
--- a/FsCrypt.h
+++ b/FsCrypt.h
@@ -18,13 +18,15 @@
 
 #include <cutils/multiuser.h>
 
-bool fscrypt_initialize_global_de();
+bool fscrypt_initialize_systemwide_keys();
 
 bool fscrypt_init_user0();
 bool fscrypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral);
 bool fscrypt_destroy_user_key(userid_t user_id);
 bool fscrypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token,
                                const std::string& secret);
+bool fscrypt_clear_user_key_auth(userid_t user_id, int serial, const std::string& token,
+                                 const std::string& secret);
 bool fscrypt_fixate_newest_user_key_auth(userid_t user_id);
 
 bool fscrypt_unlock_user_key(userid_t user_id, int serial, const std::string& token,
diff --git a/IdleMaint.cpp b/IdleMaint.cpp
index 79894fc..2b5a8f1 100644
--- a/IdleMaint.cpp
+++ b/IdleMaint.cpp
@@ -29,8 +29,8 @@
 #include <android-base/strings.h>
 #include <android/hardware/health/storage/1.0/IStorage.h>
 #include <fs_mgr.h>
-#include <hardware_legacy/power.h>
 #include <private/android_filesystem_config.h>
+#include <wakelock/wakelock.h>
 
 #include <dirent.h>
 #include <fcntl.h>
@@ -45,10 +45,12 @@
 using android::base::StringPrintf;
 using android::base::Timer;
 using android::base::WriteStringToFile;
+using android::fs_mgr::Fstab;
+using android::fs_mgr::ReadDefaultFstab;
 using android::hardware::Return;
 using android::hardware::Void;
-using android::hardware::health::storage::V1_0::IGarbageCollectCallback;
 using android::hardware::health::storage::V1_0::IStorage;
+using android::hardware::health::storage::V1_0::IGarbageCollectCallback;
 using android::hardware::health::storage::V1_0::Result;
 
 namespace android {
@@ -102,53 +104,48 @@
 }
 
 static void addFromFstab(std::list<std::string>* paths, PathTypes path_type) {
-    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
-                                                               fs_mgr_free_fstab);
-    struct fstab_rec* prev_rec = NULL;
+    Fstab fstab;
+    ReadDefaultFstab(&fstab);
 
-    for (int i = 0; i < fstab->num_entries; i++) {
-        auto fs_type = std::string(fstab->recs[i].fs_type);
-        /* Skip raw partitions */
-        if (fs_type == "emmc" || fs_type == "mtd") {
+    std::string previous_mount_point;
+    for (const auto& entry : fstab) {
+        // Skip raw partitions.
+        if (entry.fs_type == "emmc" || entry.fs_type == "mtd") {
             continue;
         }
-        /* Skip read-only filesystems */
-        if (fstab->recs[i].flags & MS_RDONLY) {
+        // Skip read-only filesystems
+        if (entry.flags & MS_RDONLY) {
             continue;
         }
-        if (fs_mgr_is_voldmanaged(&fstab->recs[i])) {
-            continue; /* Should we trim fat32 filesystems? */
+        if (entry.fs_mgr_flags.vold_managed) {
+            continue;  // Should we trim fat32 filesystems?
         }
-        if (fs_mgr_is_notrim(&fstab->recs[i])) {
+        if (entry.fs_mgr_flags.no_trim) {
             continue;
         }
 
-        /* Skip the multi-type partitions, which are required to be following each other.
-         * See fs_mgr.c's mount_with_alternatives().
-         */
-        if (prev_rec && !strcmp(prev_rec->mount_point, fstab->recs[i].mount_point)) {
+        // Skip the multi-type partitions, which are required to be following each other.
+        // See fs_mgr.c's mount_with_alternatives().
+        if (entry.mount_point == previous_mount_point) {
             continue;
         }
 
         if (path_type == PathTypes::kMountPoint) {
-            paths->push_back(fstab->recs[i].mount_point);
+            paths->push_back(entry.mount_point);
         } else if (path_type == PathTypes::kBlkDevice) {
             std::string gc_path;
-            if (std::string(fstab->recs[i].fs_type) == "f2fs" &&
-                Realpath(
-                    android::vold::BlockDeviceForPath(std::string(fstab->recs[i].mount_point) + "/"),
-                    &gc_path)) {
-                paths->push_back(std::string("/sys/fs/") + fstab->recs[i].fs_type + "/" +
-                                 Basename(gc_path));
+            if (entry.fs_type == "f2fs" &&
+                Realpath(android::vold::BlockDeviceForPath(entry.mount_point + "/"), &gc_path)) {
+                paths->push_back("/sys/fs/" + entry.fs_type + "/" + Basename(gc_path));
             }
         }
 
-        prev_rec = &fstab->recs[i];
+        previous_mount_point = entry.mount_point;
     }
 }
 
 void Trim(const android::sp<android::os::IVoldTaskListener>& listener) {
-    acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+    android::wakelock::WakeLock wl{kWakeLock};
 
     // Collect both fstab and vold volumes
     std::list<std::string> paths;
@@ -198,7 +195,6 @@
         listener->onFinished(0, extras);
     }
 
-    release_wake_lock(kWakeLock);
 }
 
 static bool waitForGc(const std::list<std::string>& paths) {
@@ -239,9 +235,6 @@
 static int startGc(const std::list<std::string>& paths) {
     for (const auto& path : paths) {
         LOG(DEBUG) << "Start GC on " << path;
-        if (!WriteStringToFile("1", path + "/discard_granularity")) {
-            PLOG(WARNING) << "Set discard gralunarity failed on" << path;
-        }
         if (!WriteStringToFile("1", path + "/gc_urgent")) {
             PLOG(WARNING) << "Start GC failed on " << path;
         }
@@ -255,30 +248,26 @@
         if (!WriteStringToFile("0", path + "/gc_urgent")) {
             PLOG(WARNING) << "Stop GC failed on " << path;
         }
-        if (!WriteStringToFile("16", path + "/discard_granularity")) {
-            PLOG(WARNING) << "Set discard gralunarity failed on" << path;
-        }
     }
     return android::OK;
 }
 
 static void runDevGcFstab(void) {
-    std::unique_ptr<fstab, decltype(&fs_mgr_free_fstab)> fstab(fs_mgr_read_fstab_default(),
-                                                               fs_mgr_free_fstab);
-    struct fstab_rec* rec = NULL;
+    Fstab fstab;
+    ReadDefaultFstab(&fstab);
 
-    for (int i = 0; i < fstab->num_entries; i++) {
-        if (fs_mgr_has_sysfs_path(&fstab->recs[i])) {
-            rec = &fstab->recs[i];
+    std::string path;
+    for (const auto& entry : fstab) {
+        if (!entry.sysfs_path.empty()) {
+            path = entry.sysfs_path;
             break;
         }
     }
-    if (!rec) {
+
+    if (path.empty()) {
         return;
     }
 
-    std::string path;
-    path.append(rec->sysfs_path);
     path = path + "/manual_gc";
     Timer timer;
 
@@ -380,7 +369,7 @@
 
     LOG(DEBUG) << "idle maintenance started";
 
-    acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+    android::wakelock::WakeLock wl{kWakeLock};
 
     std::list<std::string> paths;
     addFromFstab(&paths, PathTypes::kBlkDevice);
@@ -410,13 +399,11 @@
 
     LOG(DEBUG) << "idle maintenance completed";
 
-    release_wake_lock(kWakeLock);
-
     return android::OK;
 }
 
 int AbortIdleMaint(const android::sp<android::os::IVoldTaskListener>& listener) {
-    acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+    android::wakelock::WakeLock wl{kWakeLock};
 
     std::unique_lock<std::mutex> lk(cv_m);
     if (idle_maint_stat != IdleMaintStats::kStopped) {
@@ -434,8 +421,6 @@
         listener->onFinished(0, extras);
     }
 
-    release_wake_lock(kWakeLock);
-
     LOG(DEBUG) << "idle maintenance stopped";
 
     return android::OK;
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 035c7b7..951536b 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -16,10 +16,12 @@
 
 #include "KeyStorage.h"
 
+#include "Checkpoint.h"
 #include "Keymaster.h"
 #include "ScryptParameters.h"
 #include "Utils.h"
 
+#include <thread>
 #include <vector>
 
 #include <errno.h>
@@ -35,13 +37,14 @@
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <android-base/unique_fd.h>
 
 #include <cutils/properties.h>
 
 #include <hardware/hw_auth_token.h>
-#include <keymasterV4_0/authorization_set.h>
-#include <keymasterV4_0/keymaster_utils.h>
+#include <keymasterV4_1/authorization_set.h>
+#include <keymasterV4_1/keymaster_utils.h>
 
 extern "C" {
 
@@ -119,11 +122,42 @@
             return false;
         }
         const hw_auth_token_t* at = reinterpret_cast<const hw_auth_token_t*>(auth.token.data());
-        paramBuilder.Authorization(km::TAG_USER_SECURE_ID, at->user_id);
+        auto user_id = at->user_id;  // Make a copy because at->user_id is unaligned.
+        paramBuilder.Authorization(km::TAG_USER_SECURE_ID, user_id);
         paramBuilder.Authorization(km::TAG_USER_AUTH_TYPE, km::HardwareAuthenticatorType::PASSWORD);
         paramBuilder.Authorization(km::TAG_AUTH_TIMEOUT, AUTH_TIMEOUT);
     }
-    return keymaster.generateKey(paramBuilder, key);
+
+    auto paramsWithRollback = paramBuilder;
+    paramsWithRollback.Authorization(km::TAG_ROLLBACK_RESISTANCE);
+
+    // Generate rollback-resistant key if possible.
+    return keymaster.generateKey(paramsWithRollback, key) ||
+           keymaster.generateKey(paramBuilder, key);
+}
+
+bool generateWrappedStorageKey(KeyBuffer* key) {
+    Keymaster keymaster;
+    if (!keymaster) return false;
+    std::string key_temp;
+    auto paramBuilder = km::AuthorizationSetBuilder().AesEncryptionKey(AES_KEY_BYTES * 8);
+    paramBuilder.Authorization(km::TAG_ROLLBACK_RESISTANCE);
+    paramBuilder.Authorization(km::TAG_STORAGE_KEY);
+    if (!keymaster.generateKey(paramBuilder, &key_temp)) return false;
+    *key = KeyBuffer(key_temp.size());
+    memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
+    return true;
+}
+
+bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key) {
+    Keymaster keymaster;
+    if (!keymaster) return false;
+    std::string key_temp;
+
+    if (!keymaster.exportKey(kmKey, &key_temp)) return false;
+    *key = KeyBuffer(key_temp.size());
+    memcpy(reinterpret_cast<void*>(key->data()), key_temp.c_str(), key->size());
+    return true;
 }
 
 static std::pair<km::AuthorizationSet, km::HardwareAuthToken> beginParams(
@@ -147,33 +181,6 @@
     return true;
 }
 
-static bool writeStringToFile(const std::string& payload, const std::string& filename) {
-    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
-        open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
-    if (fd == -1) {
-        PLOG(ERROR) << "Failed to open " << filename;
-        return false;
-    }
-    if (!android::base::WriteStringToFd(payload, fd)) {
-        PLOG(ERROR) << "Failed to write to " << filename;
-        unlink(filename.c_str());
-        return false;
-    }
-    // fsync as close won't guarantee flush data
-    // see close(2), fsync(2) and b/68901441
-    if (fsync(fd) == -1) {
-        if (errno == EROFS || errno == EINVAL) {
-            PLOG(WARNING) << "Skip fsync " << filename
-                          << " on a file system does not support synchronization";
-        } else {
-            PLOG(ERROR) << "Failed to fsync " << filename;
-            unlink(filename.c_str());
-            return false;
-        }
-    }
-    return true;
-}
-
 static bool readRandomBytesOrLog(size_t count, std::string* out) {
     auto status = ReadRandomBytes(count, *out);
     if (status != OK) {
@@ -198,11 +205,33 @@
     return true;
 }
 
+static void deferedKmDeleteKey(const std::string& kmkey) {
+    while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
+        LOG(ERROR) << "Wait for boot timed out";
+    }
+    Keymaster keymaster;
+    if (!keymaster || !keymaster.deleteKey(kmkey)) {
+        LOG(ERROR) << "Defered Key deletion failed during upgrade";
+    }
+}
+
+bool kmDeleteKey(Keymaster& keymaster, const std::string& kmKey) {
+    bool needs_cp = cp_needsCheckpoint();
+
+    if (needs_cp) {
+        std::thread(deferedKmDeleteKey, kmKey).detach();
+        LOG(INFO) << "Deferring Key deletion during upgrade";
+        return true;
+    } else {
+        return keymaster.deleteKey(kmKey);
+    }
+}
+
 static KeymasterOperation begin(Keymaster& keymaster, const std::string& dir,
                                 km::KeyPurpose purpose, const km::AuthorizationSet& keyParams,
                                 const km::AuthorizationSet& opParams,
                                 const km::HardwareAuthToken& authToken,
-                                km::AuthorizationSet* outParams) {
+                                km::AuthorizationSet* outParams, bool keepOld) {
     auto kmKeyPath = dir + "/" + kFn_keymaster_key_blob;
     std::string kmKey;
     if (!readFileToString(kmKeyPath, &kmKey)) return KeymasterOperation();
@@ -219,12 +248,18 @@
         if (!keymaster.upgradeKey(kmKey, keyParams, &newKey)) return KeymasterOperation();
         auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
         if (!writeStringToFile(newKey, newKeyPath)) return KeymasterOperation();
-        if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
-            PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
-            return KeymasterOperation();
-        }
-        if (!keymaster.deleteKey(kmKey)) {
-            LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
+        if (!keepOld) {
+            if (rename(newKeyPath.c_str(), kmKeyPath.c_str()) != 0) {
+                PLOG(ERROR) << "Unable to move upgraded key to location: " << kmKeyPath;
+                return KeymasterOperation();
+            }
+            if (!android::vold::FsyncDirectory(dir)) {
+                LOG(ERROR) << "Key dir sync failed: " << dir;
+                return KeymasterOperation();
+            }
+            if (!kmDeleteKey(keymaster, kmKey)) {
+                LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
+            }
         }
         kmKey = newKey;
         LOG(INFO) << "Key upgraded: " << dir;
@@ -233,12 +268,12 @@
 
 static bool encryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
                                     const km::AuthorizationSet& keyParams,
-                                    const km::HardwareAuthToken& authToken,
-                                    const KeyBuffer& message, std::string* ciphertext) {
+                                    const km::HardwareAuthToken& authToken, const KeyBuffer& message,
+                                    std::string* ciphertext, bool keepOld) {
     km::AuthorizationSet opParams;
     km::AuthorizationSet outParams;
-    auto opHandle =
-        begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken, &outParams);
+    auto opHandle = begin(keymaster, dir, km::KeyPurpose::ENCRYPT, keyParams, opParams, authToken,
+                          &outParams, keepOld);
     if (!opHandle) return false;
     auto nonceBlob = outParams.GetTagValue(km::TAG_NONCE);
     if (!nonceBlob.isOk()) {
@@ -262,13 +297,14 @@
 static bool decryptWithKeymasterKey(Keymaster& keymaster, const std::string& dir,
                                     const km::AuthorizationSet& keyParams,
                                     const km::HardwareAuthToken& authToken,
-                                    const std::string& ciphertext, KeyBuffer* message) {
+                                    const std::string& ciphertext, KeyBuffer* message,
+                                    bool keepOld) {
     auto nonce = ciphertext.substr(0, GCM_NONCE_BYTES);
     auto bodyAndMac = ciphertext.substr(GCM_NONCE_BYTES);
     auto opParams = km::AuthorizationSetBuilder().Authorization(km::TAG_NONCE,
                                                                 km::support::blob2hidlVec(nonce));
-    auto opHandle =
-        begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken, nullptr);
+    auto opHandle = begin(keymaster, dir, km::KeyPurpose::DECRYPT, keyParams, opParams, authToken,
+                          nullptr, keepOld);
     if (!opHandle) return false;
     if (!opHandle.updateCompletely(bodyAndMac, message)) return false;
     if (!opHandle.finish(nullptr)) return false;
@@ -474,12 +510,14 @@
         km::AuthorizationSet keyParams;
         km::HardwareAuthToken authToken;
         std::tie(keyParams, authToken) = beginParams(auth, appId);
-        if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey))
+        if (!encryptWithKeymasterKey(keymaster, dir, keyParams, authToken, key, &encryptedKey,
+                                     false))
             return false;
     } else {
         if (!encryptWithoutKeymaster(appId, key, &encryptedKey)) return false;
     }
     if (!writeStringToFile(encryptedKey, dir + "/" + kFn_encrypted_key)) return false;
+    if (!FsyncDirectory(dir)) return false;
     return true;
 }
 
@@ -502,7 +540,8 @@
     return true;
 }
 
-bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key) {
+bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
+                 bool keepOld) {
     std::string version;
     if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
     if (version != kCurrentVersion) {
@@ -527,7 +566,8 @@
         km::AuthorizationSet keyParams;
         km::HardwareAuthToken authToken;
         std::tie(keyParams, authToken) = beginParams(auth, appId);
-        if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key))
+        if (!decryptWithKeymasterKey(keymaster, dir, keyParams, authToken, encryptedMessage, key,
+                                     keepOld))
             return false;
     } else {
         if (!decryptWithoutKeymaster(appId, encryptedMessage, key)) return false;
diff --git a/KeyStorage.h b/KeyStorage.h
index 786e5b4..f9d3ec6 100644
--- a/KeyStorage.h
+++ b/KeyStorage.h
@@ -31,7 +31,7 @@
 // If only "secret" is nonempty, it is used to decrypt in a non-Keymaster process.
 class KeyAuthentication {
   public:
-    KeyAuthentication(std::string t, std::string s) : token{t}, secret{s} {};
+    KeyAuthentication(const std::string& t, const std::string& s) : token{t}, secret{s} {};
 
     bool usesKeymaster() const { return !token.empty() || secret.empty(); };
 
@@ -61,12 +61,18 @@
                         const KeyAuthentication& auth, const KeyBuffer& key);
 
 // Retrieve the key from the named directory.
-bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key);
+bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, KeyBuffer* key,
+                 bool keepOld = false);
 
 // Securely destroy the key stored in the named directory and delete the directory.
 bool destroyKey(const std::string& dir);
 
 bool runSecdiscardSingle(const std::string& file);
+
+// Generate wrapped storage key using keymaster. Uses STORAGE_KEY tag in keymaster.
+bool generateWrappedStorageKey(KeyBuffer* key);
+// Export the per-boot boot wrapped storage key using keymaster.
+bool exportWrappedStorageKey(const KeyBuffer& kmKey, KeyBuffer* key);
 }  // namespace vold
 }  // namespace android
 
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index a17b8b2..acc42db 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -16,27 +16,33 @@
 
 #include "KeyUtil.h"
 
-#include <linux/fs.h>
 #include <iomanip>
 #include <sstream>
 #include <string>
 
+#include <fcntl.h>
+#include <linux/fscrypt.h>
 #include <openssl/sha.h>
+#include <sys/ioctl.h>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <keyutils.h>
 
+#include <fscrypt_uapi.h>
 #include "KeyStorage.h"
 #include "Utils.h"
 
 namespace android {
 namespace vold {
 
-constexpr int FS_AES_256_XTS_KEY_SIZE = 64;
+const KeyGeneration neverGen() {
+    return KeyGeneration{0, false, false};
+}
 
-bool randomKey(KeyBuffer* key) {
-    *key = KeyBuffer(FS_AES_256_XTS_KEY_SIZE);
+static bool randomKey(size_t size, KeyBuffer* key) {
+    *key = KeyBuffer(size);
     if (ReadRandomBytes(key->size(), key->data()) != 0) {
         // TODO status_t plays badly with PLOG, fix it.
         LOG(ERROR) << "Random read failed";
@@ -45,6 +51,56 @@
     return true;
 }
 
+bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key) {
+    if (!gen.allow_gen) return false;
+    if (gen.use_hw_wrapped_key) {
+        if (gen.keysize != FSCRYPT_MAX_KEY_SIZE) {
+            LOG(ERROR) << "Cannot generate a wrapped key " << gen.keysize << " bytes long";
+            return false;
+        }
+        return generateWrappedStorageKey(key);
+    } else {
+        return randomKey(gen.keysize, key);
+    }
+}
+
+// Return true if the kernel supports the ioctls to add/remove fscrypt keys
+// directly to/from the filesystem.
+bool isFsKeyringSupported(void) {
+    static bool initialized = false;
+    static bool supported;
+
+    if (!initialized) {
+        android::base::unique_fd fd(open("/data", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+
+        // FS_IOC_ADD_ENCRYPTION_KEY with a NULL argument will fail with ENOTTY
+        // if the ioctl isn't supported.  Otherwise it will fail with another
+        // error code such as EFAULT.
+        errno = 0;
+        (void)ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, NULL);
+        if (errno == ENOTTY) {
+            LOG(INFO) << "Kernel doesn't support FS_IOC_ADD_ENCRYPTION_KEY.  Falling back to "
+                         "session keyring";
+            supported = false;
+        } else {
+            if (errno != EFAULT) {
+                PLOG(WARNING) << "Unexpected error from FS_IOC_ADD_ENCRYPTION_KEY";
+            }
+            LOG(DEBUG) << "Detected support for FS_IOC_ADD_ENCRYPTION_KEY";
+            supported = true;
+            android::base::SetProperty("ro.crypto.uses_fs_ioc_add_encryption_key", "true");
+        }
+        // There's no need to check for FS_IOC_REMOVE_ENCRYPTION_KEY, since it's
+        // guaranteed to be available if FS_IOC_ADD_ENCRYPTION_KEY is.  There's
+        // also no need to check for support on external volumes separately from
+        // /data, since either the kernel supports the ioctls on all
+        // fscrypt-capable filesystems or it doesn't.
+
+        initialized = true;
+    }
+    return supported;
+}
+
 // Get raw keyref - used to make keyname and to pass to ioctl
 static std::string generateKeyRef(const uint8_t* key, int length) {
     SHA512_CTX c;
@@ -59,35 +115,39 @@
     unsigned char key_ref2[SHA512_DIGEST_LENGTH];
     SHA512_Final(key_ref2, &c);
 
-    static_assert(FS_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH, "Hash too short for descriptor");
-    return std::string((char*)key_ref2, FS_KEY_DESCRIPTOR_SIZE);
+    static_assert(FSCRYPT_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
+                  "Hash too short for descriptor");
+    return std::string((char*)key_ref2, FSCRYPT_KEY_DESCRIPTOR_SIZE);
 }
 
 static bool fillKey(const KeyBuffer& key, fscrypt_key* fs_key) {
-    if (key.size() != FS_AES_256_XTS_KEY_SIZE) {
+    if (key.size() != FSCRYPT_MAX_KEY_SIZE) {
         LOG(ERROR) << "Wrong size key " << key.size();
         return false;
     }
-    static_assert(FS_AES_256_XTS_KEY_SIZE <= sizeof(fs_key->raw), "Key too long!");
-    fs_key->mode = FS_ENCRYPTION_MODE_AES_256_XTS;
-    fs_key->size = key.size();
-    memset(fs_key->raw, 0, sizeof(fs_key->raw));
+    static_assert(FSCRYPT_MAX_KEY_SIZE == sizeof(fs_key->raw), "Mismatch of max key sizes");
+    fs_key->mode = 0;  // unused by kernel
     memcpy(fs_key->raw, key.data(), key.size());
+    fs_key->size = key.size();
     return true;
 }
 
 static char const* const NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt", nullptr};
 
-static std::string keyname(const std::string& prefix, const std::string& raw_ref) {
+static std::string keyrefstring(const std::string& raw_ref) {
     std::ostringstream o;
-    o << prefix << ":";
     for (unsigned char i : raw_ref) {
         o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
     }
     return o.str();
 }
 
-// Get the keyring we store all keys in
+static std::string buildLegacyKeyName(const std::string& prefix, const std::string& raw_ref) {
+    return prefix + ":" + keyrefstring(raw_ref);
+}
+
+// Get the ID of the keyring we store all fscrypt keys in when the kernel is too
+// old to support FS_IOC_ADD_ENCRYPTION_KEY and FS_IOC_REMOVE_ENCRYPTION_KEY.
 static bool fscryptKeyring(key_serial_t* device_keyring) {
     *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
     if (*device_keyring == -1) {
@@ -97,19 +157,17 @@
     return true;
 }
 
-// Install password into global keyring
-// Return raw key reference for use in policy
-bool installKey(const KeyBuffer& key, std::string* raw_ref) {
+// Add an encryption key of type "logon" to the global session keyring.
+static bool installKeyLegacy(const KeyBuffer& key, const std::string& raw_ref) {
     // Place fscrypt_key into automatically zeroing buffer.
     KeyBuffer fsKeyBuffer(sizeof(fscrypt_key));
     fscrypt_key& fs_key = *reinterpret_cast<fscrypt_key*>(fsKeyBuffer.data());
 
     if (!fillKey(key, &fs_key)) return false;
-    *raw_ref = generateKeyRef(fs_key.raw, fs_key.size);
     key_serial_t device_keyring;
     if (!fscryptKeyring(&device_keyring)) return false;
     for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
-        auto ref = keyname(*name_prefix, *raw_ref);
+        auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
         key_serial_t key_id =
             add_key("logon", ref.c_str(), (void*)&fs_key, sizeof(fs_key), device_keyring);
         if (key_id == -1) {
@@ -122,12 +180,146 @@
     return true;
 }
 
-bool evictKey(const std::string& raw_ref) {
+// Installs fscrypt-provisioning key into session level kernel keyring.
+// This allows for the given key to be installed back into filesystem keyring.
+// For more context see reloadKeyFromSessionKeyring.
+static bool installProvisioningKey(const KeyBuffer& key, const std::string& ref,
+                                   const fscrypt_key_specifier& key_spec) {
+    key_serial_t device_keyring;
+    if (!fscryptKeyring(&device_keyring)) return false;
+
+    // Place fscrypt_provisioning_key_payload into automatically zeroing buffer.
+    KeyBuffer buf(sizeof(fscrypt_provisioning_key_payload) + key.size(), 0);
+    fscrypt_provisioning_key_payload& provisioning_key =
+            *reinterpret_cast<fscrypt_provisioning_key_payload*>(buf.data());
+    memcpy(provisioning_key.raw, key.data(), key.size());
+    provisioning_key.type = key_spec.type;
+
+    key_serial_t key_id = add_key("fscrypt-provisioning", ref.c_str(), (void*)&provisioning_key,
+                                  buf.size(), device_keyring);
+    if (key_id == -1) {
+        PLOG(ERROR) << "Failed to insert fscrypt-provisioning key for " << ref
+                    << " into session keyring";
+        return false;
+    }
+    LOG(DEBUG) << "Added fscrypt-provisioning key for " << ref << " to session keyring";
+    return true;
+}
+
+// Build a struct fscrypt_key_specifier for use in the key management ioctls.
+static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
+    switch (policy.options.version) {
+        case 1:
+            if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
+                LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
+                           << policy.key_raw_ref.size();
+                return false;
+            }
+            spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
+            memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
+            return true;
+        case 2:
+            if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
+                LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
+                           << policy.key_raw_ref.size();
+                return false;
+            }
+            spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
+            memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
+            return true;
+        default:
+            LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
+            return false;
+    }
+}
+
+// Installs key into keyring of a filesystem mounted on |mountpoint|.
+//
+// It's callers responsibility to fill key specifier, and either arg->raw or arg->key_id.
+//
+// In case arg->key_spec.type equals to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER
+// arg->key_spec.u.identifier will be populated with raw key reference generated
+// by kernel.
+//
+// For documentation on difference between arg->raw and arg->key_id see
+// https://www.kernel.org/doc/html/latest/filesystems/fscrypt.html#fs-ioc-add-encryption-key
+static bool installFsKeyringKey(const std::string& mountpoint, const EncryptionOptions& options,
+                                fscrypt_add_key_arg* arg) {
+    if (options.use_hw_wrapped_key) arg->flags |= FSCRYPT_ADD_KEY_FLAG_WRAPPED;
+
+    android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << mountpoint << " to install key";
+        return false;
+    }
+
+    if (ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) != 0) {
+        PLOG(ERROR) << "Failed to install fscrypt key to " << mountpoint;
+        return false;
+    }
+
+    return true;
+}
+
+bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
+                const KeyBuffer& key, EncryptionPolicy* policy) {
+    policy->options = options;
+    // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
+    // have to copy the raw key into it.
+    KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
+    struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
+
+    // Initialize the "key specifier", which is like a name for the key.
+    switch (options.version) {
+        case 1:
+            // A key for a v1 policy is specified by an arbitrary 8-byte
+            // "descriptor", which must be provided by userspace.  We use the
+            // first 8 bytes from the double SHA-512 of the key itself.
+            policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
+            if (!isFsKeyringSupported()) {
+                return installKeyLegacy(key, policy->key_raw_ref);
+            }
+            if (!buildKeySpecifier(&arg->key_spec, *policy)) {
+                return false;
+            }
+            break;
+        case 2:
+            // A key for a v2 policy is specified by an 16-byte "identifier",
+            // which is a cryptographic hash of the key itself which the kernel
+            // computes and returns.  Any user-provided value is ignored; we
+            // just need to set the specifier type to indicate that we're adding
+            // this type of key.
+            arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
+            break;
+        default:
+            LOG(ERROR) << "Invalid encryption policy version: " << options.version;
+            return false;
+    }
+
+    arg->raw_size = key.size();
+    memcpy(arg->raw, key.data(), key.size());
+
+    if (!installFsKeyringKey(mountpoint, options, arg)) return false;
+
+    if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
+        // Retrieve the key identifier that the kernel computed.
+        policy->key_raw_ref =
+                std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
+    }
+    std::string ref = keyrefstring(policy->key_raw_ref);
+    LOG(DEBUG) << "Installed fscrypt key with ref " << ref << " to " << mountpoint;
+
+    if (!installProvisioningKey(key, ref, arg->key_spec)) return false;
+    return true;
+}
+
+// Remove an encryption key of type "logon" from the global session keyring.
+static bool evictKeyLegacy(const std::string& raw_ref) {
     key_serial_t device_keyring;
     if (!fscryptKeyring(&device_keyring)) return false;
     bool success = true;
     for (char const* const* name_prefix = NAME_PREFIXES; *name_prefix != nullptr; name_prefix++) {
-        auto ref = keyname(*name_prefix, raw_ref);
+        auto ref = buildLegacyKeyName(*name_prefix, raw_ref);
         auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
 
         // Unlink the key from the keyring.  Prefer unlinking to revoking or
@@ -144,46 +336,107 @@
     return success;
 }
 
-bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
-                           const std::string& key_path, const std::string& tmp_path,
-                           std::string* key_ref) {
-    KeyBuffer key;
-    if (pathExists(key_path)) {
-        LOG(DEBUG) << "Key exists, using: " << key_path;
-        if (!retrieveKey(key_path, key_authentication, &key)) return false;
-    } else {
-        if (!create_if_absent) {
-            LOG(ERROR) << "No key found in " << key_path;
-            return false;
-        }
-        LOG(INFO) << "Creating new key in " << key_path;
-        if (!randomKey(&key)) return false;
-        if (!storeKeyAtomically(key_path, tmp_path, key_authentication, key)) return false;
+static bool evictProvisioningKey(const std::string& ref) {
+    key_serial_t device_keyring;
+    if (!fscryptKeyring(&device_keyring)) {
+        return false;
     }
 
-    if (!installKey(key, key_ref)) {
-        LOG(ERROR) << "Failed to install key in " << key_path;
+    auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
+    if (key_serial == -1 && errno != ENOKEY) {
+        PLOG(ERROR) << "Error searching session keyring for fscrypt-provisioning key for " << ref;
+        return false;
+    }
+
+    if (key_serial != -1 && keyctl_unlink(key_serial, device_keyring) != 0) {
+        PLOG(ERROR) << "Failed to unlink fscrypt-provisioning key for " << ref
+                    << " from session keyring";
         return false;
     }
     return true;
 }
 
-bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
-                 KeyBuffer* key) {
+bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
+    if (policy.options.version == 1 && !isFsKeyringSupported()) {
+        return evictKeyLegacy(policy.key_raw_ref);
+    }
+
+    android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << mountpoint << " to evict key";
+        return false;
+    }
+
+    struct fscrypt_remove_key_arg arg;
+    memset(&arg, 0, sizeof(arg));
+
+    if (!buildKeySpecifier(&arg.key_spec, policy)) {
+        return false;
+    }
+
+    std::string ref = keyrefstring(policy.key_raw_ref);
+
+    if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
+        PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
+        return false;
+    }
+
+    LOG(DEBUG) << "Evicted fscrypt key with ref " << ref << " from " << mountpoint;
+    if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS) {
+        // Should never happen because keys are only added/removed as root.
+        LOG(ERROR) << "Unexpected case: key with ref " << ref << " is still added by other users!";
+    } else if (arg.removal_status_flags & FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY) {
+        LOG(ERROR) << "Files still open after removing key with ref " << ref
+                   << ".  These files were not locked!";
+    }
+
+    if (!evictProvisioningKey(ref)) return false;
+    return true;
+}
+
+bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
+                           const KeyAuthentication& key_authentication, const KeyGeneration& gen,
+                           KeyBuffer* key, bool keepOld) {
     if (pathExists(key_path)) {
         LOG(DEBUG) << "Key exists, using: " << key_path;
-        if (!retrieveKey(key_path, kEmptyAuthentication, key)) return false;
+        if (!retrieveKey(key_path, key_authentication, key, keepOld)) return false;
     } else {
-        if (!create_if_absent) {
+        if (!gen.allow_gen) {
             LOG(ERROR) << "No key found in " << key_path;
             return false;
         }
         LOG(INFO) << "Creating new key in " << key_path;
-        if (!randomKey(key)) return false;
-        if (!storeKeyAtomically(key_path, tmp_path, kEmptyAuthentication, *key)) return false;
+        if (!generateStorageKey(gen, key)) return false;
+        if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
     }
     return true;
 }
 
+bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy) {
+    key_serial_t device_keyring;
+    if (!fscryptKeyring(&device_keyring)) {
+        return false;
+    }
+
+    std::string ref = keyrefstring(policy.key_raw_ref);
+    auto key_serial = keyctl_search(device_keyring, "fscrypt-provisioning", ref.c_str(), 0);
+    if (key_serial == -1) {
+        PLOG(ERROR) << "Failed to find fscrypt-provisioning key for " << ref
+                    << " in session keyring";
+        return false;
+    }
+
+    LOG(DEBUG) << "Installing fscrypt-provisioning key for " << ref << " back into " << mountpoint
+               << " fs-keyring";
+
+    struct fscrypt_add_key_arg arg;
+    memset(&arg, 0, sizeof(arg));
+    if (!buildKeySpecifier(&arg.key_spec, policy)) return false;
+    arg.key_id = key_serial;
+    if (!installFsKeyringKey(mountpoint, policy.options, &arg)) return false;
+
+    return true;
+}
+
 }  // namespace vold
 }  // namespace android
diff --git a/KeyUtil.h b/KeyUtil.h
index b4115f4..23278c1 100644
--- a/KeyUtil.h
+++ b/KeyUtil.h
@@ -20,20 +20,67 @@
 #include "KeyBuffer.h"
 #include "KeyStorage.h"
 
+#include <fscrypt/fscrypt.h>
+
 #include <memory>
 #include <string>
 
 namespace android {
 namespace vold {
 
-bool randomKey(KeyBuffer* key);
-bool installKey(const KeyBuffer& key, std::string* raw_ref);
-bool evictKey(const std::string& raw_ref);
-bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
-                           const std::string& key_path, const std::string& tmp_path,
-                           std::string* key_ref);
-bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
-                 KeyBuffer* key);
+using namespace android::fscrypt;
+
+// Description of how to generate a key when needed.
+struct KeyGeneration {
+    size_t keysize;
+    bool allow_gen;
+    bool use_hw_wrapped_key;
+};
+
+// Generate a key as specified in KeyGeneration
+bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key);
+
+// Returns a key with allow_gen false so generateStorageKey returns false;
+// this is used to indicate to retrieveOrGenerateKey that a key should not
+// be generated.
+const KeyGeneration neverGen();
+
+bool isFsKeyringSupported(void);
+
+// Install a file-based encryption key to the kernel, for use by encrypted files
+// on the specified filesystem using the specified encryption policy version.
+//
+// For v1 policies, we use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it.
+// Otherwise we add the key to the global session keyring as a "logon" key.
+//
+// For v2 policies, we always use FS_IOC_ADD_ENCRYPTION_KEY; it's the only way
+// the kernel supports.
+//
+// If kernel supports FS_IOC_ADD_ENCRYPTION_KEY, also installs key of
+// fscrypt-provisioning type to the global session keyring. This makes it
+// possible to unmount and then remount mountpoint without losing the file-based
+// key.
+//
+// Returns %true on success, %false on failure.  On success also sets *policy
+// to the EncryptionPolicy used to refer to this key.
+bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
+                const KeyBuffer& key, EncryptionPolicy* policy);
+
+// Evict a file-based encryption key from the kernel.
+//
+// This undoes the effect of installKey().
+//
+// If the kernel doesn't support the filesystem-level keyring, the caller is
+// responsible for dropping caches.
+bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy);
+
+bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
+                           const KeyAuthentication& key_authentication, const KeyGeneration& gen,
+                           KeyBuffer* key, bool keepOld = true);
+
+// Re-installs a file-based encryption key of fscrypt-provisioning type from the
+// global session keyring back into fs keyring of the mountpoint.
+bool reloadKeyFromSessionKeyring(const std::string& mountpoint, const EncryptionPolicy& policy);
 
 }  // namespace vold
 }  // namespace android
diff --git a/Keymaster.cpp b/Keymaster.cpp
index aad4387..786cdb5 100644
--- a/Keymaster.cpp
+++ b/Keymaster.cpp
@@ -17,8 +17,8 @@
 #include "Keymaster.h"
 
 #include <android-base/logging.h>
-#include <keymasterV4_0/authorization_set.h>
-#include <keymasterV4_0/keymaster_utils.h>
+#include <keymasterV4_1/authorization_set.h>
+#include <keymasterV4_1/keymaster_utils.h>
 
 namespace android {
 namespace vold {
@@ -138,6 +138,27 @@
     return true;
 }
 
+bool Keymaster::exportKey(const KeyBuffer& kmKey, std::string* key) {
+    auto kmKeyBlob = km::support::blob2hidlVec(std::string(kmKey.data(), kmKey.size()));
+    km::ErrorCode km_error;
+    auto hidlCb = [&](km::ErrorCode ret, const hidl_vec<uint8_t>& exportedKeyBlob) {
+        km_error = ret;
+        if (km_error != km::ErrorCode::OK) return;
+        if (key)
+            key->assign(reinterpret_cast<const char*>(&exportedKeyBlob[0]), exportedKeyBlob.size());
+    };
+    auto error = mDevice->exportKey(km::KeyFormat::RAW, kmKeyBlob, {}, {}, hidlCb);
+    if (!error.isOk()) {
+        LOG(ERROR) << "export_key failed: " << error.description();
+        return false;
+    }
+    if (km_error != km::ErrorCode::OK) {
+        LOG(ERROR) << "export_key failed, code " << int32_t(km_error);
+        return false;
+    }
+    return true;
+}
+
 bool Keymaster::deleteKey(const std::string& key) {
     auto keyBlob = km::support::blob2hidlVec(key);
     auto error = mDevice->deleteKey(keyBlob);
@@ -207,6 +228,23 @@
     return mDevice->halVersion().securityLevel != km::SecurityLevel::SOFTWARE;
 }
 
+void Keymaster::earlyBootEnded() {
+    auto devices = KmDevice::enumerateAvailableDevices();
+    for (auto& dev : devices) {
+        auto error = dev->earlyBootEnded();
+        if (!error.isOk()) {
+            LOG(ERROR) << "earlyBootEnded call failed: " << error.description() << " for "
+                       << dev->halVersion().keymasterName;
+        }
+        km::V4_1_ErrorCode km_error = error;
+        if (km_error != km::V4_1_ErrorCode::OK && km_error != km::V4_1_ErrorCode::UNIMPLEMENTED) {
+            LOG(ERROR) << "Error reporting early boot ending to keymaster: "
+                       << static_cast<int32_t>(km_error) << " for "
+                       << dev->halVersion().keymasterName;
+        }
+    }
+}
+
 }  // namespace vold
 }  // namespace android
 
diff --git a/Keymaster.h b/Keymaster.h
index fabe0f4..4f2dd93 100644
--- a/Keymaster.h
+++ b/Keymaster.h
@@ -24,13 +24,25 @@
 #include <utility>
 
 #include <android-base/macros.h>
-#include <keymasterV4_0/Keymaster.h>
-#include <keymasterV4_0/authorization_set.h>
+#include <keymasterV4_1/Keymaster.h>
+#include <keymasterV4_1/authorization_set.h>
 
 namespace android {
 namespace vold {
 
-namespace km = ::android::hardware::keymaster::V4_0;
+namespace km {
+
+using namespace ::android::hardware::keymaster::V4_1;
+
+// Surprisingly -- to me, at least -- this is totally fine.  You can re-define symbols that were
+// brought in via a using directive (the "using namespace") above.  In general this seems like a
+// dangerous thing to rely on, but in this case its implications are simple and straightforward:
+// km::ErrorCode refers to the 4.0 ErrorCode, though we pull everything else from 4.1.
+using ErrorCode = ::android::hardware::keymaster::V4_0::ErrorCode;
+using V4_1_ErrorCode = ::android::hardware::keymaster::V4_1::ErrorCode;
+
+}  // namespace km
+
 using KmDevice = km::support::Keymaster;
 
 // C++ wrappers to the Keymaster hidl interface.
@@ -46,8 +58,8 @@
     ~KeymasterOperation();
     // Is this instance valid? This is false if creation fails, and becomes
     // false on finish or if an update fails.
-    explicit operator bool() { return mError == km::ErrorCode::OK; }
-    km::ErrorCode errorCode() { return mError; }
+    explicit operator bool() const { return mError == km::ErrorCode::OK; }
+    km::ErrorCode errorCode() const { return mError; }
     // Call "update" repeatedly until all of the input is consumed, and
     // concatenate the output. Return true on success.
     template <class TI, class TO>
@@ -102,6 +114,8 @@
     explicit operator bool() { return mDevice.get() != nullptr; }
     // Generate a key in the keymaster from the given params.
     bool generateKey(const km::AuthorizationSet& inParams, std::string* key);
+    // Exports a keymaster key with STORAGE_KEY tag wrapped with a per-boot ephemeral key
+    bool exportKey(const KeyBuffer& kmKey, std::string* key);
     // If the keymaster supports it, permanently delete a key.
     bool deleteKey(const std::string& key);
     // Replace stored key blob in response to KM_ERROR_KEY_REQUIRES_UPGRADE.
@@ -114,6 +128,10 @@
                              km::AuthorizationSet* outParams);
     bool isSecure();
 
+    // Tell all Keymaster instances that early boot has ended and early boot-only keys can no longer
+    // be created or used.
+    static void earlyBootEnded();
+
   private:
     std::unique_ptr<KmDevice> mDevice;
     DISALLOW_COPY_AND_ASSIGN(Keymaster);
diff --git a/Loop.cpp b/Loop.cpp
index 4926ea8..9fa876c 100644
--- a/Loop.cpp
+++ b/Loop.cpp
@@ -31,20 +31,25 @@
 
 #include <linux/kdev_t.h>
 
+#include <chrono>
+
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
+#include <fs_mgr/file_wait.h>
 #include <utils/Trace.h>
 
 #include "Loop.h"
 #include "VoldUtil.h"
 #include "sehandle.h"
 
+using namespace std::literals;
 using android::base::StringPrintf;
 using android::base::unique_fd;
 
 static const char* kVoldPrefix = "vold:";
+static constexpr size_t kLoopDeviceRetryAttempts = 3u;
 
 int Loop::create(const std::string& target, std::string& out_device) {
     unique_fd ctl_fd(open("/dev/loop-control", O_RDWR | O_CLOEXEC));
@@ -61,11 +66,22 @@
 
     out_device = StringPrintf("/dev/block/loop%d", num);
 
-    unique_fd target_fd(open(target.c_str(), O_RDWR | O_CLOEXEC));
+    unique_fd target_fd;
+    for (size_t i = 0; i != kLoopDeviceRetryAttempts; ++i) {
+        target_fd.reset(open(target.c_str(), O_RDWR | O_CLOEXEC));
+        if (target_fd.get() != -1) {
+            break;
+        }
+        usleep(50000);
+    }
     if (target_fd.get() == -1) {
         PLOG(ERROR) << "Failed to open " << target;
         return -errno;
     }
+    if (!android::fs_mgr::WaitForFile(out_device, 2s)) {
+        LOG(ERROR) << "Failed to find " << out_device;
+        return -ENOENT;
+    }
     unique_fd device_fd(open(out_device.c_str(), O_RDWR | O_CLOEXEC));
     if (device_fd.get() == -1) {
         PLOG(ERROR) << "Failed to open " << out_device;
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index e156424..b97be9d 100644
--- a/MetadataCrypt.cpp
+++ b/MetadataCrypt.cpp
@@ -23,43 +23,81 @@
 #include <vector>
 
 #include <fcntl.h>
-#include <sys/ioctl.h>
 #include <sys/param.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 
-#include <linux/dm-ioctl.h>
-
+#include <android-base/file.h>
 #include <android-base/logging.h>
 #include <android-base/properties.h>
+#include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <cutils/fs.h>
 #include <fs_mgr.h>
+#include <libdm/dm.h>
 
 #include "Checkpoint.h"
+#include "CryptoType.h"
 #include "EncryptInplace.h"
 #include "KeyStorage.h"
 #include "KeyUtil.h"
+#include "Keymaster.h"
 #include "Utils.h"
 #include "VoldUtil.h"
-#include "secontext.h"
 
-#define DM_CRYPT_BUF_SIZE 4096
 #define TABLE_LOAD_RETRIES 10
-#define DEFAULT_KEY_TARGET_TYPE "default-key"
 
+namespace android {
+namespace vold {
+
+using android::fs_mgr::FstabEntry;
+using android::fs_mgr::GetEntryForMountPoint;
 using android::vold::KeyBuffer;
+using namespace android::dm;
+
+// Parsed from metadata options
+struct CryptoOptions {
+    struct CryptoType cipher = invalid_crypto_type;
+    bool use_legacy_options_format = false;
+    bool set_dun = true;  // Non-legacy driver always sets DUN
+    bool use_hw_wrapped_key = false;
+};
 
 static const std::string kDmNameUserdata = "userdata";
 
+static const char* kFn_keymaster_key_blob = "keymaster_key_blob";
+static const char* kFn_keymaster_key_blob_upgraded = "keymaster_key_blob_upgraded";
+
+// The first entry in this table is the default crypto type.
+constexpr CryptoType supported_crypto_types[] = {aes_256_xts, adiantum};
+
+static_assert(validateSupportedCryptoTypes(64, supported_crypto_types,
+                                           array_length(supported_crypto_types)),
+              "We have a CryptoType which was incompletely constructed.");
+
+constexpr CryptoType legacy_aes_256_xts =
+        CryptoType().set_config_name("aes-256-xts").set_kernel_name("AES-256-XTS").set_keysize(64);
+
+static_assert(isValidCryptoType(64, legacy_aes_256_xts),
+              "We have a CryptoType which was incompletely constructed.");
+
+// Returns KeyGeneration suitable for key as described in CryptoOptions
+const KeyGeneration makeGen(const CryptoOptions& options) {
+    return KeyGeneration{options.cipher.get_keysize(), true, options.use_hw_wrapped_key};
+}
+
 static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
+    // We're about to mount data not verified by verified boot.  Tell Keymaster instances that early
+    // boot has ended.
+    ::android::vold::Keymaster::earlyBootEnded();
+
     // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
     // partitions in the fsck domain.
-    if (setexeccon(secontextFsck())) {
+    if (setexeccon(android::vold::sFsckContext)) {
         PLOG(ERROR) << "Failed to setexeccon";
         return false;
     }
-    auto mount_rc = fs_mgr_do_mount(fstab_default, const_cast<char*>(mount_point),
+    auto mount_rc = fs_mgr_do_mount(&fstab_default, const_cast<char*>(mount_point),
                                     const_cast<char*>(blk_device), nullptr,
                                     android::vold::cp_needsCheckpoint());
     if (setexeccon(nullptr)) {
@@ -74,31 +112,64 @@
     return true;
 }
 
-static bool read_key(struct fstab_rec const* data_rec, bool create_if_absent, KeyBuffer* key) {
-    if (!data_rec->key_dir) {
-        LOG(ERROR) << "Failed to get key_dir";
+// Note: It is possible to orphan a key if it is removed before deleting
+// Update this once keymaster APIs change, and we have a proper commit.
+static void commit_key(const std::string& dir) {
+    while (!android::base::WaitForProperty("vold.checkpoint_committed", "1")) {
+        LOG(ERROR) << "Wait for boot timed out";
+    }
+    Keymaster keymaster;
+    auto keyPath = dir + "/" + kFn_keymaster_key_blob;
+    auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
+    std::string key;
+
+    if (!android::base::ReadFileToString(keyPath, &key)) {
+        LOG(ERROR) << "Failed to read old key: " << dir;
+        return;
+    }
+    if (rename(newKeyPath.c_str(), keyPath.c_str()) != 0) {
+        PLOG(ERROR) << "Unable to move upgraded key to location: " << keyPath;
+        return;
+    }
+    if (!keymaster.deleteKey(key)) {
+        LOG(ERROR) << "Key deletion failed during upgrade, continuing anyway: " << dir;
+    }
+    LOG(INFO) << "Old Key deleted: " << dir;
+}
+
+static bool read_key(const std::string& metadata_key_dir, const KeyGeneration& gen,
+                     KeyBuffer* key) {
+    if (metadata_key_dir.empty()) {
+        LOG(ERROR) << "Failed to get metadata_key_dir";
         return false;
     }
-    std::string key_dir = data_rec->key_dir;
-    auto dir = key_dir + "/key";
-    LOG(DEBUG) << "key_dir/key: " << dir;
+    std::string sKey;
+    auto dir = metadata_key_dir + "/key";
+    LOG(DEBUG) << "metadata_key_dir/key: " << dir;
     if (fs_mkdirs(dir.c_str(), 0700)) {
         PLOG(ERROR) << "Creating directories: " << dir;
         return false;
     }
-    auto temp = key_dir + "/tmp";
-    if (!android::vold::retrieveKey(create_if_absent, dir, temp, key)) return false;
-    return true;
-}
-
-static KeyBuffer default_key_params(const std::string& real_blkdev, const KeyBuffer& key) {
-    KeyBuffer hex_key;
-    if (android::vold::StrToHex(key, hex_key) != android::OK) {
-        LOG(ERROR) << "Failed to turn key to hex";
-        return KeyBuffer();
+    auto temp = metadata_key_dir + "/tmp";
+    auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
+    /* If we have a leftover upgraded key, delete it.
+     * We either failed an update and must return to the old key,
+     * or we rebooted before commiting the keys in a freak accident.
+     * Either way, we can re-upgrade the key if we need to.
+     */
+    Keymaster keymaster;
+    if (pathExists(newKeyPath)) {
+        if (!android::base::ReadFileToString(newKeyPath, &sKey))
+            LOG(ERROR) << "Failed to read incomplete key: " << dir;
+        else if (!keymaster.deleteKey(sKey))
+            LOG(ERROR) << "Incomplete key deletion failed, continuing anyway: " << dir;
+        else
+            unlink(newKeyPath.c_str());
     }
-    auto res = KeyBuffer() + "AES-256-XTS " + hex_key + " " + real_blkdev.c_str() + " 0";
-    return res;
+    bool needs_cp = cp_needsCheckpoint();
+    if (!retrieveOrGenerateKey(dir, temp, kEmptyAuthentication, gen, key, needs_cp)) return false;
+    if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
+    return true;
 }
 
 static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t* nr_sec) {
@@ -109,118 +180,150 @@
     return true;
 }
 
-static struct dm_ioctl* dm_ioctl_init(char* buffer, size_t buffer_size, const std::string& dm_name) {
-    if (buffer_size < sizeof(dm_ioctl)) {
-        LOG(ERROR) << "dm_ioctl buffer too small";
-        return nullptr;
+static bool create_crypto_blk_dev(const std::string& dm_name, const std::string& blk_device,
+                                  const KeyBuffer& key, const CryptoOptions& options,
+                                  std::string* crypto_blkdev, uint64_t* nr_sec) {
+    if (!get_number_of_sectors(blk_device, nr_sec)) return false;
+    // TODO(paulcrowley): don't hardcode that DmTargetDefaultKey uses 4096-byte
+    // sectors
+    *nr_sec &= ~7;
+
+    KeyBuffer module_key;
+    if (options.use_hw_wrapped_key) {
+        if (!exportWrappedStorageKey(key, &module_key)) {
+            LOG(ERROR) << "Failed to get ephemeral wrapped key";
+            return false;
+        }
+    } else {
+        module_key = key;
     }
 
-    memset(buffer, 0, buffer_size);
-    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
-    io->data_size = buffer_size;
-    io->data_start = sizeof(struct dm_ioctl);
-    io->version[0] = 4;
-    io->version[1] = 0;
-    io->version[2] = 0;
-    io->flags = 0;
-    dm_name.copy(io->name, sizeof(io->name));
-    return io;
-}
-
-static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
-                                  const std::string& target_type, const KeyBuffer& crypt_params,
-                                  std::string* crypto_blkdev) {
-    android::base::unique_fd dm_fd(
-        TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC, 0)));
-    if (dm_fd == -1) {
-        PLOG(ERROR) << "Cannot open device-mapper";
+    KeyBuffer hex_key_buffer;
+    if (android::vold::StrToHex(module_key, hex_key_buffer) != android::OK) {
+        LOG(ERROR) << "Failed to turn key to hex";
         return false;
     }
-    alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
-    auto io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
-    if (!io || ioctl(dm_fd.get(), DM_DEV_CREATE, io) != 0) {
-        PLOG(ERROR) << "Cannot create dm-crypt device " << dm_name;
-        return false;
-    }
+    std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
 
-    // Get the device status, in particular, the name of its device file
-    io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
-    if (ioctl(dm_fd.get(), DM_DEV_STATUS, io) != 0) {
-        PLOG(ERROR) << "Cannot retrieve dm-crypt device status " << dm_name;
-        return false;
-    }
-    *crypto_blkdev = std::string() + "/dev/block/dm-" +
-                     std::to_string((io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
+    auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
+                                                       hex_key, blk_device, 0);
+    if (options.use_legacy_options_format) target->SetUseLegacyOptionsFormat();
+    if (options.set_dun) target->SetSetDun();
+    if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
 
-    io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
-    size_t paramix = io->data_start + sizeof(struct dm_target_spec);
-    size_t nullix = paramix + crypt_params.size();
-    size_t endix = (nullix + 1 + 7) & 8;  // Add room for \0 and align to 8 byte boundary
+    DmTable table;
+    table.AddTarget(std::move(target));
 
-    if (endix > sizeof(buffer)) {
-        LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE";
-        return false;
-    }
-
-    io->target_count = 1;
-    auto tgt = (struct dm_target_spec*)(buffer + io->data_start);
-    tgt->status = 0;
-    tgt->sector_start = 0;
-    tgt->length = nr_sec;
-    target_type.copy(tgt->target_type, sizeof(tgt->target_type));
-    memcpy(buffer + paramix, crypt_params.data(),
-           std::min(crypt_params.size(), sizeof(buffer) - paramix));
-    buffer[nullix] = '\0';
-    tgt->next = endix;
-
+    auto& dm = DeviceMapper::Instance();
     for (int i = 0;; i++) {
-        if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
+        if (dm.CreateDevice(dm_name, table)) {
             break;
         }
         if (i + 1 >= TABLE_LOAD_RETRIES) {
-            PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
+            PLOG(ERROR) << "Could not create default-key device " << dm_name;
             return false;
         }
-        PLOG(INFO) << "DM_TABLE_LOAD ioctl failed, retrying";
+        PLOG(INFO) << "Could not create default-key device, retrying";
         usleep(500000);
     }
 
-    // Resume this device to activate it
-    io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
-    if (ioctl(dm_fd.get(), DM_DEV_SUSPEND, io)) {
-        PLOG(ERROR) << "Cannot resume dm-crypt device " << dm_name;
+    if (!dm.GetDmDevicePathByName(dm_name, crypto_blkdev)) {
+        LOG(ERROR) << "Cannot retrieve default-key device status " << dm_name;
         return false;
     }
     return true;
 }
 
-bool fscrypt_mount_metadata_encrypted(const std::string& mount_point, bool needs_encrypt) {
+static const CryptoType& lookup_cipher(const std::string& cipher_name) {
+    if (cipher_name.empty()) return supported_crypto_types[0];
+    for (size_t i = 0; i < array_length(supported_crypto_types); i++) {
+        if (cipher_name == supported_crypto_types[i].get_config_name()) {
+            return supported_crypto_types[i];
+        }
+    }
+    return invalid_crypto_type;
+}
+
+static bool parse_options(const std::string& options_string, CryptoOptions* options) {
+    auto parts = android::base::Split(options_string, ":");
+    if (parts.size() < 1 || parts.size() > 2) {
+        LOG(ERROR) << "Invalid metadata encryption option: " << options_string;
+        return false;
+    }
+    std::string cipher_name = parts[0];
+    options->cipher = lookup_cipher(cipher_name);
+    if (options->cipher.get_kernel_name() == nullptr) {
+        LOG(ERROR) << "No metadata cipher named " << cipher_name << " found";
+        return false;
+    }
+
+    if (parts.size() == 2) {
+        if (parts[1] == "wrappedkey_v0") {
+            options->use_hw_wrapped_key = true;
+        } else {
+            LOG(ERROR) << "Invalid metadata encryption flag: " << parts[1];
+            return false;
+        }
+    }
+    return true;
+}
+
+bool fscrypt_mount_metadata_encrypted(const std::string& blk_device, const std::string& mount_point,
+                                      bool needs_encrypt) {
     LOG(DEBUG) << "fscrypt_mount_metadata_encrypted: " << mount_point << " " << needs_encrypt;
     auto encrypted_state = android::base::GetProperty("ro.crypto.state", "");
-    if (encrypted_state != "") {
+    if (encrypted_state != "" && encrypted_state != "encrypted") {
         LOG(DEBUG) << "fscrypt_enable_crypto got unexpected starting state: " << encrypted_state;
         return false;
     }
-    auto data_rec = fs_mgr_get_entry_for_mount_point(fstab_default, mount_point);
+
+    auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
     if (!data_rec) {
-        LOG(ERROR) << "Failed to get data_rec";
+        LOG(ERROR) << "Failed to get data_rec for " << mount_point;
         return false;
     }
-    KeyBuffer key;
-    if (!read_key(data_rec, needs_encrypt, &key)) return false;
-    uint64_t nr_sec;
-    if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
-    std::string crypto_blkdev;
-    if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
-                               default_key_params(data_rec->blk_device, key), &crypto_blkdev))
+
+    constexpr unsigned int pre_gki_level = 29;
+    unsigned int options_format_version = android::base::GetUintProperty<unsigned int>(
+            "ro.crypto.dm_default_key.options_format.version",
+            (GetFirstApiLevel() <= pre_gki_level ? 1 : 2));
+
+    CryptoOptions options;
+    if (options_format_version == 1) {
+        if (!data_rec->metadata_encryption.empty()) {
+            LOG(ERROR) << "metadata_encryption options cannot be set in legacy mode";
+            return false;
+        }
+        options.cipher = legacy_aes_256_xts;
+        options.use_legacy_options_format = true;
+        options.set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
+        if (!options.set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
+            LOG(ERROR)
+                    << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
+            return false;
+        }
+    } else if (options_format_version == 2) {
+        if (!parse_options(data_rec->metadata_encryption, &options)) return false;
+    } else {
+        LOG(ERROR) << "Unknown options_format_version: " << options_format_version;
         return false;
+    }
+
+    auto gen = needs_encrypt ? makeGen(options) : neverGen();
+    KeyBuffer key;
+    if (!read_key(data_rec->metadata_key_dir, gen, &key)) return false;
+
+    std::string crypto_blkdev;
+    uint64_t nr_sec;
+    if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec))
+        return false;
+
     // FIXME handle the corrupt case
     if (needs_encrypt) {
         LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
         off64_t size_already_done = 0;
-        auto rc =
-            cryptfs_enable_inplace(const_cast<char*>(crypto_blkdev.c_str()), data_rec->blk_device,
-                                   nr_sec, &size_already_done, nr_sec, 0, false);
+        auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), blk_device.data(), nr_sec,
+                                         &size_already_done, nr_sec, 0, false);
         if (rc != 0) {
             LOG(ERROR) << "Inplace crypto failed with code: " << rc;
             return false;
@@ -233,6 +336,31 @@
     }
 
     LOG(DEBUG) << "Mounting metadata-encrypted filesystem:" << mount_point;
-    mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
+    mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str());
     return true;
 }
+
+static bool get_volume_options(CryptoOptions* options) {
+    return parse_options(android::base::GetProperty("ro.crypto.volume.metadata.encryption", ""),
+                         options);
+}
+
+bool defaultkey_volume_keygen(KeyGeneration* gen) {
+    CryptoOptions options;
+    if (!get_volume_options(&options)) return false;
+    *gen = makeGen(options);
+    return true;
+}
+
+bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
+                                 const KeyBuffer& key, std::string* out_crypto_blkdev) {
+    LOG(DEBUG) << "defaultkey_setup_ext_volume: " << label << " " << blk_device;
+
+    CryptoOptions options;
+    if (!get_volume_options(&options)) return false;
+    uint64_t nr_sec;
+    return create_crypto_blk_dev(label, blk_device, key, options, out_crypto_blkdev, &nr_sec);
+}
+
+}  // namespace vold
+}  // namespace android
diff --git a/MetadataCrypt.h b/MetadataCrypt.h
index d82a43b..dc68e7c 100644
--- a/MetadataCrypt.h
+++ b/MetadataCrypt.h
@@ -19,6 +19,21 @@
 
 #include <string>
 
-bool fscrypt_mount_metadata_encrypted(const std::string& mount_point, bool needs_encrypt);
+#include "KeyBuffer.h"
+#include "KeyUtil.h"
 
+namespace android {
+namespace vold {
+
+bool fscrypt_mount_metadata_encrypted(const std::string& block_device,
+                                      const std::string& mount_point, bool needs_encrypt);
+
+bool defaultkey_volume_keygen(KeyGeneration* gen);
+
+bool defaultkey_setup_ext_volume(const std::string& label, const std::string& blk_device,
+                                 const android::vold::KeyBuffer& key,
+                                 std::string* out_crypto_blkdev);
+
+}  // namespace vold
+}  // namespace android
 #endif
diff --git a/MoveStorage.cpp b/MoveStorage.cpp
index 4653e01..2447cce 100644
--- a/MoveStorage.cpp
+++ b/MoveStorage.cpp
@@ -21,8 +21,8 @@
 #include <android-base/logging.h>
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
-#include <hardware_legacy/power.h>
 #include <private/android_filesystem_config.h>
+#include <wakelock/wakelock.h>
 
 #include <thread>
 
@@ -56,27 +56,27 @@
     }
 }
 
-static status_t pushBackContents(const std::string& path, std::vector<std::string>& cmd,
-                                 bool addWildcard) {
-    DIR* dir = opendir(path.c_str());
-    if (dir == NULL) {
-        return -1;
+static bool pushBackContents(const std::string& path, std::vector<std::string>& cmd,
+                             int searchLevels) {
+    if (searchLevels == 0) {
+        cmd.emplace_back(path);
+        return true;
+    }
+    auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(path.c_str()), closedir);
+    if (!dirp) {
+        PLOG(ERROR) << "Unable to open directory: " << path;
+        return false;
     }
     bool found = false;
     struct dirent* ent;
-    while ((ent = readdir(dir)) != NULL) {
+    while ((ent = readdir(dirp.get())) != NULL) {
         if ((!strcmp(ent->d_name, ".")) || (!strcmp(ent->d_name, ".."))) {
             continue;
         }
-        if (addWildcard) {
-            cmd.push_back(StringPrintf("%s/%s/*", path.c_str(), ent->d_name));
-        } else {
-            cmd.push_back(StringPrintf("%s/%s", path.c_str(), ent->d_name));
-        }
-        found = true;
+        auto subdir = path + "/" + ent->d_name;
+        found |= pushBackContents(subdir, cmd, searchLevels - 1);
     }
-    closedir(dir);
-    return found ? OK : -1;
+    return found;
 }
 
 static status_t execRm(const std::string& path, int startProgress, int stepProgress,
@@ -90,7 +90,7 @@
     cmd.push_back(kRmPath);
     cmd.push_back("-f"); /* force: remove without confirmation, no error if it doesn't exist */
     cmd.push_back("-R"); /* recursive: remove directory contents */
-    if (pushBackContents(path, cmd, true) != OK) {
+    if (!pushBackContents(path, cmd, 2)) {
         LOG(WARNING) << "No contents in " << path;
         return OK;
     }
@@ -143,7 +143,7 @@
     cmd.push_back("-R"); /* recurse into subdirectories (DEST must be a directory) */
     cmd.push_back("-P"); /* Do not follow symlinks [default] */
     cmd.push_back("-d"); /* don't dereference symlinks */
-    if (pushBackContents(fromPath, cmd, false) != OK) {
+    if (!pushBackContents(fromPath, cmd, 1)) {
         LOG(WARNING) << "No contents in " << fromPath;
         return OK;
     }
@@ -258,15 +258,13 @@
 
 void MoveStorage(const std::shared_ptr<VolumeBase>& from, const std::shared_ptr<VolumeBase>& to,
                  const android::sp<android::os::IVoldTaskListener>& listener) {
-    acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLock);
+    android::wakelock::WakeLock wl{kWakeLock};
 
     android::os::PersistableBundle extras;
     status_t res = moveStorageInternal(from, to, listener);
     if (listener) {
         listener->onFinished(res, extras);
     }
-
-    release_wake_lock(kWakeLock);
 }
 
 }  // namespace vold
diff --git a/OWNERS b/OWNERS
index 4e45284..bab0ef6 100644
--- a/OWNERS
+++ b/OWNERS
@@ -1,3 +1,6 @@
 jsharkey@android.com
 paulcrowley@google.com
 paullawrence@google.com
+ebiggers@google.com
+drosen@google.com
+zezeozue@google.com
diff --git a/Process.cpp b/Process.cpp
index a5028f2..3d8e3d7 100644
--- a/Process.cpp
+++ b/Process.cpp
@@ -46,18 +46,27 @@
 
 static bool checkMaps(const std::string& path, const std::string& prefix) {
     bool found = false;
-    std::ifstream infile(path);
-    std::string line;
-    while (std::getline(infile, line)) {
+    auto file = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
+    if (!file) {
+        return false;
+    }
+
+    char* buf = nullptr;
+    size_t len = 0;
+    while (getline(&buf, &len, file.get()) != -1) {
+        std::string line(buf);
         std::string::size_type pos = line.find('/');
         if (pos != std::string::npos) {
             line = line.substr(pos);
             if (android::base::StartsWith(line, prefix)) {
                 LOG(WARNING) << "Found map " << path << " referencing " << line;
                 found = true;
+                break;
             }
         }
     }
+    free(buf);
+
     return found;
 }
 
diff --git a/Utils.cpp b/Utils.cpp
index 04c3956..1616d80 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -25,6 +25,7 @@
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
+#include <android-base/unique_fd.h>
 #include <cutils/fs.h>
 #include <logwrap/logwrap.h>
 #include <private/android_filesystem_config.h>
@@ -35,12 +36,14 @@
 #include <mntent.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <unistd.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
 #include <sys/statvfs.h>
 #include <sys/sysmacros.h>
 #include <sys/types.h>
 #include <sys/wait.h>
+#include <unistd.h>
 
 #include <list>
 #include <mutex>
@@ -192,21 +195,66 @@
 }
 
 status_t BindMount(const std::string& source, const std::string& target) {
-    if (::mount(source.c_str(), target.c_str(), "", MS_BIND, NULL)) {
+    if (UnmountTree(target) < 0) {
+        return -errno;
+    }
+    if (TEMP_FAILURE_RETRY(mount(source.c_str(), target.c_str(), nullptr, MS_BIND, nullptr)) < 0) {
         PLOG(ERROR) << "Failed to bind mount " << source << " to " << target;
         return -errno;
     }
     return OK;
 }
 
+status_t Symlink(const std::string& target, const std::string& linkpath) {
+    if (Unlink(linkpath) < 0) {
+        return -errno;
+    }
+    if (TEMP_FAILURE_RETRY(symlink(target.c_str(), linkpath.c_str())) < 0) {
+        PLOG(ERROR) << "Failed to create symlink " << linkpath << " to " << target;
+        return -errno;
+    }
+    return OK;
+}
+
+status_t Unlink(const std::string& linkpath) {
+    if (TEMP_FAILURE_RETRY(unlink(linkpath.c_str())) < 0 && errno != EINVAL && errno != ENOENT) {
+        PLOG(ERROR) << "Failed to unlink " << linkpath;
+        return -errno;
+    }
+    return OK;
+}
+
+status_t CreateDir(const std::string& dir, mode_t mode) {
+    struct stat sb;
+    if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &sb)) == 0) {
+        if (S_ISDIR(sb.st_mode)) {
+            return OK;
+        } else if (TEMP_FAILURE_RETRY(unlink(dir.c_str())) == -1) {
+            PLOG(ERROR) << "Failed to unlink " << dir;
+            return -errno;
+        }
+    } else if (errno != ENOENT) {
+        PLOG(ERROR) << "Failed to stat " << dir;
+        return -errno;
+    }
+    if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), mode)) == -1 && errno != EEXIST) {
+        PLOG(ERROR) << "Failed to mkdir " << dir;
+        return -errno;
+    }
+    return OK;
+}
+
 bool FindValue(const std::string& raw, const std::string& key, std::string* value) {
     auto qual = key + "=\"";
-    auto start = raw.find(qual);
-    if (start > 0 && raw[start - 1] != ' ') {
-        start = raw.find(qual, start + 1);
+    size_t start = 0;
+    while (true) {
+        start = raw.find(qual, start);
+        if (start == std::string::npos) return false;
+        if (start == 0 || raw[start - 1] == ' ') {
+            break;
+        }
+        start += 1;
     }
-
-    if (start == std::string::npos) return false;
     start += qual.length();
 
     auto end = raw.find("\"", start);
@@ -235,7 +283,7 @@
     cmd.push_back(path);
 
     std::vector<std::string> output;
-    status_t res = ForkExecvp(cmd, output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
+    status_t res = ForkExecvp(cmd, &output, untrusted ? sBlkidUntrustedContext : sBlkidContext);
     if (res != OK) {
         LOG(WARNING) << "blkid failed to identify " << path;
         return res;
@@ -261,101 +309,92 @@
     return readMetadata(path, fsType, fsUuid, fsLabel, true);
 }
 
-status_t ForkExecvp(const std::vector<std::string>& args) {
-    return ForkExecvp(args, nullptr);
-}
-
-status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context) {
-    std::lock_guard<std::mutex> lock(kSecurityLock);
-    size_t argc = args.size();
-    char** argv = (char**)calloc(argc, sizeof(char*));
-    for (size_t i = 0; i < argc; i++) {
-        argv[i] = (char*)args[i].c_str();
-        if (i == 0) {
-            LOG(DEBUG) << args[i];
+static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
+    std::vector<const char*> argv;
+    argv.reserve(args.size() + 1);
+    for (const auto& arg : args) {
+        if (argv.empty()) {
+            LOG(DEBUG) << arg;
         } else {
-            LOG(DEBUG) << "    " << args[i];
+            LOG(DEBUG) << "    " << arg;
         }
+        argv.emplace_back(arg.data());
     }
-
-    if (context) {
-        if (setexeccon(context)) {
-            LOG(ERROR) << "Failed to setexeccon";
-            abort();
-        }
-    }
-    status_t res = android_fork_execvp(argc, argv, NULL, false, true);
-    if (context) {
-        if (setexeccon(nullptr)) {
-            LOG(ERROR) << "Failed to setexeccon";
-            abort();
-        }
-    }
-
-    free(argv);
-    return res;
+    argv.emplace_back(nullptr);
+    return argv;
 }
 
-status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output) {
-    return ForkExecvp(args, output, nullptr);
-}
-
-status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output,
-                    security_context_t context) {
-    std::lock_guard<std::mutex> lock(kSecurityLock);
-    std::string cmd;
-    for (size_t i = 0; i < args.size(); i++) {
-        cmd += args[i] + " ";
-        if (i == 0) {
-            LOG(DEBUG) << args[i];
-        } else {
-            LOG(DEBUG) << "    " << args[i];
-        }
-    }
-    output.clear();
-
-    if (context) {
-        if (setexeccon(context)) {
-            LOG(ERROR) << "Failed to setexeccon";
-            abort();
-        }
-    }
-    FILE* fp = popen(cmd.c_str(), "r");  // NOLINT
-    if (context) {
-        if (setexeccon(nullptr)) {
-            LOG(ERROR) << "Failed to setexeccon";
-            abort();
-        }
-    }
-
+static status_t ReadLinesFromFdAndLog(std::vector<std::string>* output,
+                                      android::base::unique_fd ufd) {
+    std::unique_ptr<FILE, int (*)(FILE*)> fp(android::base::Fdopen(std::move(ufd), "r"), fclose);
     if (!fp) {
-        PLOG(ERROR) << "Failed to popen " << cmd;
+        PLOG(ERROR) << "fdopen in ReadLinesFromFdAndLog";
         return -errno;
     }
+    if (output) output->clear();
     char line[1024];
-    while (fgets(line, sizeof(line), fp) != nullptr) {
+    while (fgets(line, sizeof(line), fp.get()) != nullptr) {
         LOG(DEBUG) << line;
-        output.push_back(std::string(line));
+        if (output) output->emplace_back(line);
     }
-    if (pclose(fp) != 0) {
-        PLOG(ERROR) << "Failed to pclose " << cmd;
+    return OK;
+}
+
+status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output,
+                    security_context_t context) {
+    auto argv = ConvertToArgv(args);
+
+    android::base::unique_fd pipe_read, pipe_write;
+    if (!android::base::Pipe(&pipe_read, &pipe_write)) {
+        PLOG(ERROR) << "Pipe in ForkExecvp";
         return -errno;
     }
 
+    pid_t pid = fork();
+    if (pid == 0) {
+        if (context) {
+            if (setexeccon(context)) {
+                LOG(ERROR) << "Failed to setexeccon in ForkExecvp";
+                abort();
+            }
+        }
+        pipe_read.reset();
+        if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
+            PLOG(ERROR) << "dup2 in ForkExecvp";
+            _exit(EXIT_FAILURE);
+        }
+        pipe_write.reset();
+        execvp(argv[0], const_cast<char**>(argv.data()));
+        PLOG(ERROR) << "exec in ForkExecvp";
+        _exit(EXIT_FAILURE);
+    }
+    if (pid == -1) {
+        PLOG(ERROR) << "fork in ForkExecvp";
+        return -errno;
+    }
+
+    pipe_write.reset();
+    auto st = ReadLinesFromFdAndLog(output, std::move(pipe_read));
+    if (st != 0) return st;
+
+    int status;
+    if (waitpid(pid, &status, 0) == -1) {
+        PLOG(ERROR) << "waitpid in ForkExecvp";
+        return -errno;
+    }
+    if (!WIFEXITED(status)) {
+        LOG(ERROR) << "Process did not exit normally, status: " << status;
+        return -ECHILD;
+    }
+    if (WEXITSTATUS(status)) {
+        LOG(ERROR) << "Process exited with code: " << WEXITSTATUS(status);
+        return WEXITSTATUS(status);
+    }
     return OK;
 }
 
 pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
-    size_t argc = args.size();
-    char** argv = (char**)calloc(argc + 1, sizeof(char*));
-    for (size_t i = 0; i < argc; i++) {
-        argv[i] = (char*)args[i].c_str();
-        if (i == 0) {
-            LOG(DEBUG) << args[i];
-        } else {
-            LOG(DEBUG) << "    " << args[i];
-        }
-    }
+    auto argv = ConvertToArgv(args);
 
     pid_t pid = fork();
     if (pid == 0) {
@@ -363,18 +402,14 @@
         close(STDOUT_FILENO);
         close(STDERR_FILENO);
 
-        if (execvp(argv[0], argv)) {
-            PLOG(ERROR) << "Failed to exec";
-        }
-
-        _exit(1);
+        execvp(argv[0], const_cast<char**>(argv.data()));
+        PLOG(ERROR) << "exec in ForkExecvpAsync";
+        _exit(EXIT_FAILURE);
     }
-
     if (pid == -1) {
-        PLOG(ERROR) << "Failed to exec";
+        PLOG(ERROR) << "fork in ForkExecvpAsync";
+        return -1;
     }
-
-    free(argv);
     return pid;
 }
 
@@ -389,7 +424,7 @@
         return -errno;
     }
 
-    size_t n;
+    ssize_t n;
     while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], bytes))) > 0) {
         bytes -= n;
         buf += n;
@@ -765,33 +800,131 @@
     return android::base::GetBoolProperty("ro.kernel.qemu", false);
 }
 
-status_t UnmountTree(const std::string& prefix) {
-    FILE* fp = setmntent("/proc/mounts", "r");
-    if (fp == NULL) {
-        PLOG(ERROR) << "Failed to open /proc/mounts";
+static status_t findMountPointsWithPrefix(const std::string& prefix,
+                                          std::list<std::string>& mountPoints) {
+    // Add a trailing slash if the client didn't provide one so that we don't match /foo/barbaz
+    // when the prefix is /foo/bar
+    std::string prefixWithSlash(prefix);
+    if (prefix.back() != '/') {
+        android::base::StringAppendF(&prefixWithSlash, "/");
+    }
+
+    std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
+    if (!mnts) {
+        PLOG(ERROR) << "Unable to open /proc/mounts";
         return -errno;
     }
 
     // Some volumes can be stacked on each other, so force unmount in
     // reverse order to give us the best chance of success.
-    std::list<std::string> toUnmount;
-    mntent* mentry;
-    while ((mentry = getmntent(fp)) != NULL) {
-        auto test = std::string(mentry->mnt_dir) + "/";
-        if (android::base::StartsWith(test, prefix)) {
-            toUnmount.push_front(test);
-        }
-    }
-    endmntent(fp);
-
-    for (const auto& path : toUnmount) {
-        if (umount2(path.c_str(), MNT_DETACH)) {
-            PLOG(ERROR) << "Failed to unmount " << path;
+    struct mntent* mnt;  // getmntent returns a thread local, so it's safe.
+    while ((mnt = getmntent(mnts.get())) != nullptr) {
+        auto mountPoint = std::string(mnt->mnt_dir) + "/";
+        if (android::base::StartsWith(mountPoint, prefixWithSlash)) {
+            mountPoints.push_front(mountPoint);
         }
     }
     return OK;
 }
 
+// Unmount all mountpoints that start with prefix. prefix itself doesn't need to be a mountpoint.
+status_t UnmountTreeWithPrefix(const std::string& prefix) {
+    std::list<std::string> toUnmount;
+    status_t result = findMountPointsWithPrefix(prefix, toUnmount);
+    if (result < 0) {
+        return result;
+    }
+    for (const auto& path : toUnmount) {
+        if (umount2(path.c_str(), MNT_DETACH)) {
+            PLOG(ERROR) << "Failed to unmount " << path;
+            result = -errno;
+        }
+    }
+    return result;
+}
+
+status_t UnmountTree(const std::string& mountPoint) {
+    if (TEMP_FAILURE_RETRY(umount2(mountPoint.c_str(), MNT_DETACH)) < 0 && errno != EINVAL &&
+        errno != ENOENT) {
+        PLOG(ERROR) << "Failed to unmount " << mountPoint;
+        return -errno;
+    }
+    return OK;
+}
+
+static status_t delete_dir_contents(DIR* dir) {
+    // Shamelessly borrowed from android::installd
+    int dfd = dirfd(dir);
+    if (dfd < 0) {
+        return -errno;
+    }
+
+    status_t result = OK;
+    struct dirent* de;
+    while ((de = readdir(dir))) {
+        const char* name = de->d_name;
+        if (de->d_type == DT_DIR) {
+            /* always skip "." and ".." */
+            if (name[0] == '.') {
+                if (name[1] == 0) continue;
+                if ((name[1] == '.') && (name[2] == 0)) continue;
+            }
+
+            android::base::unique_fd subfd(
+                openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
+            if (subfd.get() == -1) {
+                PLOG(ERROR) << "Couldn't openat " << name;
+                result = -errno;
+                continue;
+            }
+            std::unique_ptr<DIR, decltype(&closedir)> subdirp(
+                android::base::Fdopendir(std::move(subfd)), closedir);
+            if (!subdirp) {
+                PLOG(ERROR) << "Couldn't fdopendir " << name;
+                result = -errno;
+                continue;
+            }
+            result = delete_dir_contents(subdirp.get());
+            if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) {
+                PLOG(ERROR) << "Couldn't unlinkat " << name;
+                result = -errno;
+            }
+        } else {
+            if (unlinkat(dfd, name, 0) < 0) {
+                PLOG(ERROR) << "Couldn't unlinkat " << name;
+                result = -errno;
+            }
+        }
+    }
+    return result;
+}
+
+status_t DeleteDirContentsAndDir(const std::string& pathname) {
+    status_t res = DeleteDirContents(pathname);
+    if (res < 0) {
+        return res;
+    }
+    if (TEMP_FAILURE_RETRY(rmdir(pathname.c_str())) < 0 && errno != ENOENT) {
+        PLOG(ERROR) << "rmdir failed on " << pathname;
+        return -errno;
+    }
+    LOG(VERBOSE) << "Success: rmdir on " << pathname;
+    return OK;
+}
+
+status_t DeleteDirContents(const std::string& pathname) {
+    // Shamelessly borrowed from android::installd
+    std::unique_ptr<DIR, decltype(&closedir)> dirp(opendir(pathname.c_str()), closedir);
+    if (!dirp) {
+        if (errno == ENOENT) {
+            return OK;
+        }
+        PLOG(ERROR) << "Failed to opendir " << pathname;
+        return -errno;
+    }
+    return delete_dir_contents(dirp.get());
+}
+
 // TODO(118708649): fix duplication with init/util.h
 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout) {
     android::base::Timer t;
@@ -807,5 +940,50 @@
     return -1;
 }
 
+bool FsyncDirectory(const std::string& dirname) {
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_CLOEXEC)));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << dirname;
+        return false;
+    }
+    if (fsync(fd) == -1) {
+        if (errno == EROFS || errno == EINVAL) {
+            PLOG(WARNING) << "Skip fsync " << dirname
+                          << " on a file system does not support synchronization";
+        } else {
+            PLOG(ERROR) << "Failed to fsync " << dirname;
+            return false;
+        }
+    }
+    return true;
+}
+
+bool writeStringToFile(const std::string& payload, const std::string& filename) {
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
+        open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << filename;
+        return false;
+    }
+    if (!android::base::WriteStringToFd(payload, fd)) {
+        PLOG(ERROR) << "Failed to write to " << filename;
+        unlink(filename.c_str());
+        return false;
+    }
+    // fsync as close won't guarantee flush data
+    // see close(2), fsync(2) and b/68901441
+    if (fsync(fd) == -1) {
+        if (errno == EROFS || errno == EINVAL) {
+            PLOG(WARNING) << "Skip fsync " << filename
+                          << " on a file system does not support synchronization";
+        } else {
+            PLOG(ERROR) << "Failed to fsync " << filename;
+            unlink(filename.c_str());
+            return false;
+        }
+    }
+    return true;
+}
+
 }  // namespace vold
 }  // namespace android
diff --git a/Utils.h b/Utils.h
index 4d3522a..af4e401 100644
--- a/Utils.h
+++ b/Utils.h
@@ -57,6 +57,15 @@
 /* Creates bind mount from source to target */
 status_t BindMount(const std::string& source, const std::string& target);
 
+/** Creates a symbolic link to target */
+status_t Symlink(const std::string& target, const std::string& linkpath);
+
+/** Calls unlink(2) at linkpath */
+status_t Unlink(const std::string& linkpath);
+
+/** Creates the given directory if it is not already available */
+status_t CreateDir(const std::string& dir, mode_t mode);
+
 bool FindValue(const std::string& raw, const std::string& key, std::string* value);
 
 /* Reads filesystem metadata from device at path */
@@ -68,12 +77,8 @@
                                std::string* fsLabel);
 
 /* Returns either WEXITSTATUS() status, or a negative errno */
-status_t ForkExecvp(const std::vector<std::string>& args);
-status_t ForkExecvp(const std::vector<std::string>& args, security_context_t context);
-
-status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output);
-status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>& output,
-                    security_context_t context);
+status_t ForkExecvp(const std::vector<std::string>& args, std::vector<std::string>* output = nullptr,
+                    security_context_t context = nullptr);
 
 pid_t ForkExecvpAsync(const std::vector<std::string>& args);
 
@@ -131,10 +136,17 @@
 /* Checks if Android is running in QEMU */
 bool IsRunningInEmulator();
 
-status_t UnmountTree(const std::string& prefix);
+status_t UnmountTreeWithPrefix(const std::string& prefix);
+status_t UnmountTree(const std::string& mountPoint);
+
+status_t DeleteDirContentsAndDir(const std::string& pathname);
+status_t DeleteDirContents(const std::string& pathname);
 
 status_t WaitForFile(const char* filename, std::chrono::nanoseconds timeout);
 
+bool FsyncDirectory(const std::string& dirname);
+
+bool writeStringToFile(const std::string& payload, const std::string& filename);
 }  // namespace vold
 }  // namespace android
 
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index c58ff01..ee76518 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -17,18 +17,22 @@
 #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
 
 #include "VoldNativeService.h"
+
 #include "Benchmark.h"
 #include "CheckEncryption.h"
-#include "IdleMaint.h"
-#include "MoveStorage.h"
-#include "Process.h"
-#include "VolumeManager.h"
-
 #include "Checkpoint.h"
 #include "FsCrypt.h"
+#include "IdleMaint.h"
 #include "MetadataCrypt.h"
+#include "MoveStorage.h"
+#include "Process.h"
+#include "VoldNativeServiceValidation.h"
+#include "VoldUtil.h"
+#include "VolumeManager.h"
 #include "cryptfs.h"
 
+#include "incfs_ndk.h"
+
 #include <fstream>
 #include <thread>
 
@@ -42,6 +46,7 @@
 
 using android::base::StringPrintf;
 using std::endl;
+using namespace std::literals;
 
 namespace android {
 namespace vold {
@@ -50,14 +55,6 @@
 
 constexpr const char* kDump = "android.permission.DUMP";
 
-static binder::Status ok() {
-    return binder::Status::ok();
-}
-
-static binder::Status exception(uint32_t code, const std::string& msg) {
-    return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
-}
-
 static binder::Status error(const std::string& msg) {
     PLOG(ERROR) << msg;
     return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
@@ -79,85 +76,17 @@
     }
 }
 
-binder::Status checkPermission(const char* permission) {
-    pid_t pid;
-    uid_t uid;
-
-    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
-                               reinterpret_cast<int32_t*>(&uid))) {
-        return ok();
-    } else {
-        return exception(binder::Status::EX_SECURITY,
-                         StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
-    }
-}
-
-binder::Status checkUid(uid_t expectedUid) {
-    uid_t uid = IPCThreadState::self()->getCallingUid();
-    if (uid == expectedUid || uid == AID_ROOT) {
-        return ok();
-    } else {
-        return exception(binder::Status::EX_SECURITY,
-                         StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
-    }
-}
-
-binder::Status checkArgumentId(const std::string& id) {
-    if (id.empty()) {
-        return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing ID");
-    }
-    for (const char& c : id) {
-        if (!std::isalnum(c) && c != ':' && c != ',') {
-            return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
-                             StringPrintf("ID %s is malformed", id.c_str()));
-        }
-    }
-    return ok();
-}
-
-binder::Status checkArgumentPath(const std::string& path) {
-    if (path.empty()) {
-        return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
-    }
-    if (path[0] != '/') {
-        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
-                         StringPrintf("Path %s is relative", path.c_str()));
-    }
-    if ((path + '/').find("/../") != std::string::npos) {
-        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
-                         StringPrintf("Path %s is shady", path.c_str()));
-    }
-    for (const char& c : path) {
-        if (c == '\0' || c == '\n') {
-            return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
-                             StringPrintf("Path %s is malformed", path.c_str()));
-        }
-    }
-    return ok();
-}
-
-binder::Status checkArgumentHex(const std::string& hex) {
-    // Empty hex strings are allowed
-    for (const char& c : hex) {
-        if (!std::isxdigit(c) && c != ':' && c != '-') {
-            return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
-                             StringPrintf("Hex %s is malformed", hex.c_str()));
-        }
-    }
-    return ok();
-}
-
-#define ENFORCE_UID(uid)                         \
-    {                                            \
-        binder::Status status = checkUid((uid)); \
-        if (!status.isOk()) {                    \
-            return status;                       \
-        }                                        \
+#define ENFORCE_SYSTEM_OR_ROOT                              \
+    {                                                       \
+        binder::Status status = CheckUidOrRoot(AID_SYSTEM); \
+        if (!status.isOk()) {                               \
+            return status;                                  \
+        }                                                   \
     }
 
 #define CHECK_ARGUMENT_ID(id)                          \
     {                                                  \
-        binder::Status status = checkArgumentId((id)); \
+        binder::Status status = CheckArgumentId((id)); \
         if (!status.isOk()) {                          \
             return status;                             \
         }                                              \
@@ -165,7 +94,7 @@
 
 #define CHECK_ARGUMENT_PATH(path)                          \
     {                                                      \
-        binder::Status status = checkArgumentPath((path)); \
+        binder::Status status = CheckArgumentPath((path)); \
         if (!status.isOk()) {                              \
             return status;                                 \
         }                                                  \
@@ -173,7 +102,7 @@
 
 #define CHECK_ARGUMENT_HEX(hex)                          \
     {                                                    \
-        binder::Status status = checkArgumentHex((hex)); \
+        binder::Status status = CheckArgumentHex((hex)); \
         if (!status.isOk()) {                            \
             return status;                               \
         }                                                \
@@ -203,7 +132,7 @@
 
 status_t VoldNativeService::dump(int fd, const Vector<String16>& /* args */) {
     auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
-    const binder::Status dump_permission = checkPermission(kDump);
+    const binder::Status dump_permission = CheckPermission(kDump);
     if (!dump_permission.isOk()) {
         out << dump_permission.toString8() << endl;
         return PERMISSION_DENIED;
@@ -211,73 +140,82 @@
 
     ACQUIRE_LOCK;
     out << "vold is happy!" << endl;
-    out.flush();
     return NO_ERROR;
 }
 
 binder::Status VoldNativeService::setListener(
     const android::sp<android::os::IVoldListener>& listener) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     VolumeManager::Instance()->setListener(listener);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::monitor() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
 
     // Simply acquire/release each lock for watchdog
     { ACQUIRE_LOCK; }
     { ACQUIRE_CRYPT_LOCK; }
 
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::reset() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->reset());
 }
 
 binder::Status VoldNativeService::shutdown() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->shutdown());
 }
 
 binder::Status VoldNativeService::onUserAdded(int32_t userId, int32_t userSerial) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->onUserAdded(userId, userSerial));
 }
 
 binder::Status VoldNativeService::onUserRemoved(int32_t userId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->onUserRemoved(userId));
 }
 
 binder::Status VoldNativeService::onUserStarted(int32_t userId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->onUserStarted(userId));
 }
 
 binder::Status VoldNativeService::onUserStopped(int32_t userId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->onUserStopped(userId));
 }
 
+binder::Status VoldNativeService::addAppIds(const std::vector<std::string>& packageNames,
+                                            const std::vector<int32_t>& appIds) {
+    return Ok();
+}
+
+binder::Status VoldNativeService::addSandboxIds(const std::vector<int32_t>& appIds,
+                                                const std::vector<std::string>& sandboxIds) {
+    return Ok();
+}
+
 binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->onSecureKeyguardStateChanged(isShowing));
@@ -285,7 +223,7 @@
 
 binder::Status VoldNativeService::partition(const std::string& diskId, int32_t partitionType,
                                             int32_t ratio) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(diskId);
     ACQUIRE_LOCK;
 
@@ -307,7 +245,7 @@
 
 binder::Status VoldNativeService::forgetPartition(const std::string& partGuid,
                                                   const std::string& fsUuid) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_HEX(partGuid);
     CHECK_ARGUMENT_HEX(fsUuid);
     ACQUIRE_LOCK;
@@ -317,7 +255,7 @@
 
 binder::Status VoldNativeService::mount(const std::string& volId, int32_t mountFlags,
                                         int32_t mountUserId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -330,14 +268,20 @@
     vol->setMountUserId(mountUserId);
 
     int res = vol->mount();
-    if ((mountFlags & MOUNT_FLAG_PRIMARY) != 0) {
-        VolumeManager::Instance()->setPrimary(vol);
+    if (res != OK) {
+        return translate(res);
     }
-    return translate(res);
+    if ((mountFlags & MOUNT_FLAG_PRIMARY) != 0) {
+        res = VolumeManager::Instance()->setPrimary(vol);
+        if (res != OK) {
+            return translate(res);
+        }
+    }
+    return translate(OK);
 }
 
 binder::Status VoldNativeService::unmount(const std::string& volId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -349,7 +293,7 @@
 }
 
 binder::Status VoldNativeService::format(const std::string& volId, const std::string& fsType) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -379,12 +323,12 @@
             return error("Volume " + volId + " missing path");
         }
     }
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::benchmark(
     const std::string& volId, const android::sp<android::os::IVoldTaskListener>& listener) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -393,11 +337,11 @@
     if (!status.isOk()) return status;
 
     std::thread([=]() { android::vold::Benchmark(path, listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::checkEncryption(const std::string& volId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -410,7 +354,7 @@
 binder::Status VoldNativeService::moveStorage(
     const std::string& fromVolId, const std::string& toVolId,
     const android::sp<android::os::IVoldTaskListener>& listener) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(fromVolId);
     CHECK_ARGUMENT_ID(toVolId);
     ACQUIRE_LOCK;
@@ -424,35 +368,18 @@
     }
 
     std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
-    std::string tmp;
-    switch (remountMode) {
-        case REMOUNT_MODE_NONE:
-            tmp = "none";
-            break;
-        case REMOUNT_MODE_DEFAULT:
-            tmp = "default";
-            break;
-        case REMOUNT_MODE_READ:
-            tmp = "read";
-            break;
-        case REMOUNT_MODE_WRITE:
-            tmp = "write";
-            break;
-        default:
-            return error("Unknown mode " + std::to_string(remountMode));
-    }
-    return translate(VolumeManager::Instance()->remountUid(uid, tmp));
+    return translate(VolumeManager::Instance()->remountUid(uid, remountMode));
 }
 
 binder::Status VoldNativeService::mkdirs(const std::string& path) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_PATH(path);
     ACQUIRE_LOCK;
 
@@ -462,7 +389,7 @@
 binder::Status VoldNativeService::createObb(const std::string& sourcePath,
                                             const std::string& sourceKey, int32_t ownerGid,
                                             std::string* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_PATH(sourcePath);
     CHECK_ARGUMENT_HEX(sourceKey);
     ACQUIRE_LOCK;
@@ -472,7 +399,7 @@
 }
 
 binder::Status VoldNativeService::destroyObb(const std::string& volId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -482,7 +409,7 @@
 binder::Status VoldNativeService::createStubVolume(
     const std::string& sourcePath, const std::string& mountPath, const std::string& fsType,
     const std::string& fsUuid, const std::string& fsLabel, std::string* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_PATH(sourcePath);
     CHECK_ARGUMENT_PATH(mountPath);
     CHECK_ARGUMENT_HEX(fsUuid);
@@ -495,7 +422,7 @@
 }
 
 binder::Status VoldNativeService::destroyStubVolume(const std::string& volId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
 
@@ -504,41 +431,41 @@
 
 binder::Status VoldNativeService::fstrim(
     int32_t fstrimFlags, const android::sp<android::os::IVoldTaskListener>& listener) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     std::thread([=]() { android::vold::Trim(listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::runIdleMaint(
     const android::sp<android::os::IVoldTaskListener>& listener) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     std::thread([=]() { android::vold::RunIdleMaint(listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::abortIdleMaint(
     const android::sp<android::os::IVoldTaskListener>& listener) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     std::thread([=]() { android::vold::AbortIdleMaint(listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t mountId,
                                                android::base::unique_fd* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->mountAppFuse(uid, mountId, _aidl_return));
 }
 
 binder::Status VoldNativeService::unmountAppFuse(int32_t uid, int32_t mountId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return translate(VolumeManager::Instance()->unmountAppFuse(uid, mountId));
@@ -547,7 +474,7 @@
 binder::Status VoldNativeService::openAppFuseFile(int32_t uid, int32_t mountId, int32_t fileId,
                                                   int32_t flags,
                                                   android::base::unique_fd* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     int fd = VolumeManager::Instance()->openAppFuseFile(uid, mountId, fileId, flags);
@@ -558,32 +485,32 @@
     }
 
     *_aidl_return = android::base::unique_fd(fd);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translate(cryptfs_check_passwd(password.c_str()));
 }
 
 binder::Status VoldNativeService::fdeRestart() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     // Spawn as thread so init can issue commands back to vold without
     // causing deadlock, usually as a result of prep_data_fs.
     std::thread(&cryptfs_restart).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeComplete(int32_t* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_crypto_complete();
-    return ok();
+    return Ok();
 }
 
 static int fdeEnableInternal(int32_t passwordType, const std::string& password,
@@ -610,7 +537,7 @@
 
 binder::Status VoldNativeService::fdeEnable(int32_t passwordType, const std::string& password,
                                             int32_t encryptionFlags) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     LOG(DEBUG) << "fdeEnable(" << passwordType << ", *, " << encryptionFlags << ")";
@@ -623,26 +550,26 @@
     // Spawn as thread so init can issue commands back to vold without
     // causing deadlock, usually as a result of prep_data_fs.
     std::thread(&fdeEnableInternal, passwordType, password, encryptionFlags).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeChangePassword(int32_t passwordType,
                                                     const std::string& password) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translate(cryptfs_changepw(passwordType, password.c_str()));
 }
 
 binder::Status VoldNativeService::fdeVerifyPassword(const std::string& password) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translate(cryptfs_verify_passwd(password.c_str()));
 }
 
 binder::Status VoldNativeService::fdeGetField(const std::string& key, std::string* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     char buf[PROPERTY_VALUE_MAX];
@@ -650,53 +577,53 @@
         return error(StringPrintf("Failed to read field %s", key.c_str()));
     } else {
         *_aidl_return = buf;
-        return ok();
+        return Ok();
     }
 }
 
 binder::Status VoldNativeService::fdeSetField(const std::string& key, const std::string& value) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translate(cryptfs_setfield(key.c_str(), value.c_str()));
 }
 
 binder::Status VoldNativeService::fdeGetPasswordType(int32_t* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_get_password_type();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeGetPassword(std::string* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     const char* res = cryptfs_get_password();
     if (res != nullptr) {
         *_aidl_return = res;
     }
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeClearPassword() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     cryptfs_clear_password();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fbeEnable() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
-    return translateBool(fscrypt_initialize_global_de());
+    return translateBool(fscrypt_initialize_systemwide_keys());
 }
 
 binder::Status VoldNativeService::mountDefaultEncrypted() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     if (!fscrypt_is_native()) {
@@ -704,47 +631,49 @@
         // causing deadlock, usually as a result of prep_data_fs.
         std::thread(&cryptfs_mount_default_encrypted).detach();
     }
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::initUser0() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_init_user0());
 }
 
 binder::Status VoldNativeService::isConvertibleToFbe(bool* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_isConvertibleToFBE() != 0;
-    return ok();
+    return Ok();
 }
 
-binder::Status VoldNativeService::mountFstab(const std::string& mountPoint) {
-    ENFORCE_UID(AID_SYSTEM);
+binder::Status VoldNativeService::mountFstab(const std::string& blkDevice,
+                                             const std::string& mountPoint) {
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
-    return translateBool(fscrypt_mount_metadata_encrypted(mountPoint, false));
+    return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, false));
 }
 
-binder::Status VoldNativeService::encryptFstab(const std::string& mountPoint) {
-    ENFORCE_UID(AID_SYSTEM);
+binder::Status VoldNativeService::encryptFstab(const std::string& blkDevice,
+                                               const std::string& mountPoint) {
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
-    return translateBool(fscrypt_mount_metadata_encrypted(mountPoint, true));
+    return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, true));
 }
 
 binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial, bool ephemeral) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_vold_create_user_key(userId, userSerial, ephemeral));
 }
 
 binder::Status VoldNativeService::destroyUserKey(int32_t userId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_destroy_user_key(userId));
@@ -753,14 +682,23 @@
 binder::Status VoldNativeService::addUserKeyAuth(int32_t userId, int32_t userSerial,
                                                  const std::string& token,
                                                  const std::string& secret) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_add_user_key_auth(userId, userSerial, token, secret));
 }
 
+binder::Status VoldNativeService::clearUserKeyAuth(int32_t userId, int32_t userSerial,
+                                                   const std::string& token,
+                                                   const std::string& secret) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    ACQUIRE_CRYPT_LOCK;
+
+    return translateBool(fscrypt_clear_user_key_auth(userId, userSerial, token, secret));
+}
+
 binder::Status VoldNativeService::fixateNewestUserKeyAuth(int32_t userId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_fixate_newest_user_key_auth(userId));
@@ -769,23 +707,23 @@
 binder::Status VoldNativeService::unlockUserKey(int32_t userId, int32_t userSerial,
                                                 const std::string& token,
                                                 const std::string& secret) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_unlock_user_key(userId, userSerial, token, secret));
 }
 
 binder::Status VoldNativeService::lockUserKey(int32_t userId) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
     return translateBool(fscrypt_lock_user_key(userId));
 }
 
-binder::Status VoldNativeService::prepareUserStorage(const std::unique_ptr<std::string>& uuid,
+binder::Status VoldNativeService::prepareUserStorage(const std::optional<std::string>& uuid,
                                                      int32_t userId, int32_t userSerial,
                                                      int32_t flags) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     std::string empty_string = "";
     auto uuid_ = uuid ? *uuid : empty_string;
     CHECK_ARGUMENT_HEX(uuid_);
@@ -794,9 +732,9 @@
     return translateBool(fscrypt_prepare_user_storage(uuid_, userId, userSerial, flags));
 }
 
-binder::Status VoldNativeService::destroyUserStorage(const std::unique_ptr<std::string>& uuid,
+binder::Status VoldNativeService::destroyUserStorage(const std::optional<std::string>& uuid,
                                                      int32_t userId, int32_t flags) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     std::string empty_string = "";
     auto uuid_ = uuid ? *uuid : empty_string;
     CHECK_ARGUMENT_HEX(uuid_);
@@ -805,63 +743,161 @@
     return translateBool(fscrypt_destroy_user_storage(uuid_, userId, flags));
 }
 
+binder::Status VoldNativeService::prepareSandboxForApp(const std::string& packageName,
+                                                       int32_t appId, const std::string& sandboxId,
+                                                       int32_t userId) {
+    return Ok();
+}
+
+binder::Status VoldNativeService::destroySandboxForApp(const std::string& packageName,
+                                                       const std::string& sandboxId,
+                                                       int32_t userId) {
+    return Ok();
+}
+
 binder::Status VoldNativeService::startCheckpoint(int32_t retry) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return cp_startCheckpoint(retry);
 }
 
 binder::Status VoldNativeService::needsRollback(bool* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     *_aidl_return = cp_needsRollback();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     *_aidl_return = cp_needsCheckpoint();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::commitChanges() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return cp_commitChanges();
 }
 
 binder::Status VoldNativeService::prepareCheckpoint() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return cp_prepareCheckpoint();
 }
 
 binder::Status VoldNativeService::restoreCheckpoint(const std::string& mountPoint) {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_PATH(mountPoint);
     ACQUIRE_LOCK;
 
     return cp_restoreCheckpoint(mountPoint);
 }
 
+binder::Status VoldNativeService::restoreCheckpointPart(const std::string& mountPoint, int count) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(mountPoint);
+    ACQUIRE_LOCK;
+
+    return cp_restoreCheckpoint(mountPoint, count);
+}
+
 binder::Status VoldNativeService::markBootAttempt() {
-    ENFORCE_UID(AID_SYSTEM);
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     return cp_markBootAttempt();
 }
 
-binder::Status VoldNativeService::abortChanges() {
-    ENFORCE_UID(AID_SYSTEM);
+binder::Status VoldNativeService::abortChanges(const std::string& message, bool retry) {
+    ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
-    return cp_abortChanges();
+    cp_abortChanges(message, retry);
+    return Ok();
+}
+
+binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    ACQUIRE_LOCK;
+
+    return cp_supportsCheckpoint(*_aidl_return);
+}
+
+binder::Status VoldNativeService::supportsBlockCheckpoint(bool* _aidl_return) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    ACQUIRE_LOCK;
+
+    return cp_supportsBlockCheckpoint(*_aidl_return);
+}
+
+binder::Status VoldNativeService::supportsFileCheckpoint(bool* _aidl_return) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    ACQUIRE_LOCK;
+
+    return cp_supportsFileCheckpoint(*_aidl_return);
+}
+
+binder::Status VoldNativeService::resetCheckpoint() {
+    ENFORCE_SYSTEM_OR_ROOT;
+    ACQUIRE_LOCK;
+
+    cp_resetCheckpoint();
+    return Ok();
+}
+
+binder::Status VoldNativeService::incFsEnabled(bool* _aidl_return) {
+    ENFORCE_SYSTEM_OR_ROOT;
+
+    *_aidl_return = IncFs_IsEnabled();
+    return Ok();
+}
+
+binder::Status VoldNativeService::mountIncFs(
+        const std::string& backingPath, const std::string& targetDir, int32_t flags,
+        ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(backingPath);
+    CHECK_ARGUMENT_PATH(targetDir);
+
+    auto control = IncFs_Mount(backingPath.c_str(), targetDir.c_str(),
+                               {.flags = IncFsMountFlags(flags),
+                                .defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
+                                .readLogBufferPages = 4});
+    if (control == nullptr) {
+        return translate(-1);
+    }
+    using unique_fd = ::android::base::unique_fd;
+    _aidl_return->cmd.emplace(unique_fd(dup(IncFs_GetControlFd(control, CMD))));
+    _aidl_return->pendingReads.emplace(unique_fd(dup(IncFs_GetControlFd(control, PENDING_READS))));
+    auto logsFd = IncFs_GetControlFd(control, LOGS);
+    if (logsFd >= 0) {
+        _aidl_return->log.emplace(unique_fd(dup(logsFd)));
+    }
+    IncFs_DeleteControl(control);
+    return Ok();
+}
+
+binder::Status VoldNativeService::unmountIncFs(const std::string& dir) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(dir);
+
+    return translate(IncFs_Unmount(dir.c_str()));
+}
+
+binder::Status VoldNativeService::bindMount(const std::string& sourceDir,
+                                            const std::string& targetDir) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(sourceDir);
+    CHECK_ARGUMENT_PATH(targetDir);
+
+    return translate(IncFs_BindMount(sourceDir.c_str(), targetDir.c_str()));
 }
 
 }  // namespace vold
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 161acb8..4578dc0 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -42,6 +42,11 @@
     binder::Status onUserStarted(int32_t userId);
     binder::Status onUserStopped(int32_t userId);
 
+    binder::Status addAppIds(const std::vector<std::string>& packageNames,
+                             const std::vector<int32_t>& appIds);
+    binder::Status addSandboxIds(const std::vector<int32_t>& appIds,
+                                 const std::vector<std::string>& sandboxIds);
+
     binder::Status onSecureKeyguardStateChanged(bool isShowing);
 
     binder::Status partition(const std::string& diskId, int32_t partitionType, int32_t ratio);
@@ -99,27 +104,31 @@
     binder::Status mountDefaultEncrypted();
     binder::Status initUser0();
     binder::Status isConvertibleToFbe(bool* _aidl_return);
-    binder::Status mountFstab(const std::string& mountPoint);
-    binder::Status encryptFstab(const std::string& mountPoint);
+    binder::Status mountFstab(const std::string& blkDevice, const std::string& mountPoint);
+    binder::Status encryptFstab(const std::string& blkDevice, const std::string& mountPoint);
 
     binder::Status createUserKey(int32_t userId, int32_t userSerial, bool ephemeral);
     binder::Status destroyUserKey(int32_t userId);
 
     binder::Status addUserKeyAuth(int32_t userId, int32_t userSerial, const std::string& token,
                                   const std::string& secret);
+    binder::Status clearUserKeyAuth(int32_t userId, int32_t userSerial, const std::string& token,
+                                    const std::string& secret);
     binder::Status fixateNewestUserKeyAuth(int32_t userId);
 
     binder::Status unlockUserKey(int32_t userId, int32_t userSerial, const std::string& token,
                                  const std::string& secret);
     binder::Status lockUserKey(int32_t userId);
 
-    binder::Status prepareUserStorage(const std::unique_ptr<std::string>& uuid, int32_t userId,
+    binder::Status prepareUserStorage(const std::optional<std::string>& uuid, int32_t userId,
                                       int32_t userSerial, int32_t flags);
-    binder::Status destroyUserStorage(const std::unique_ptr<std::string>& uuid, int32_t userId,
+    binder::Status destroyUserStorage(const std::optional<std::string>& uuid, int32_t userId,
                                       int32_t flags);
 
-    binder::Status mountExternalStorageForApp(const std::string& packageName, int32_t appId,
-                                              const std::string& sandboxId, int32_t userId);
+    binder::Status prepareSandboxForApp(const std::string& packageName, int32_t appId,
+                                        const std::string& sandboxId, int32_t userId);
+    binder::Status destroySandboxForApp(const std::string& packageName,
+                                        const std::string& sandboxId, int32_t userId);
 
     binder::Status startCheckpoint(int32_t retry);
     binder::Status needsCheckpoint(bool* _aidl_return);
@@ -127,8 +136,20 @@
     binder::Status commitChanges();
     binder::Status prepareCheckpoint();
     binder::Status restoreCheckpoint(const std::string& mountPoint);
+    binder::Status restoreCheckpointPart(const std::string& mountPoint, int count);
     binder::Status markBootAttempt();
-    binder::Status abortChanges();
+    binder::Status abortChanges(const std::string& message, bool retry);
+    binder::Status supportsCheckpoint(bool* _aidl_return);
+    binder::Status supportsBlockCheckpoint(bool* _aidl_return);
+    binder::Status supportsFileCheckpoint(bool* _aidl_return);
+    binder::Status resetCheckpoint();
+
+    binder::Status incFsEnabled(bool* _aidl_return) override;
+    binder::Status mountIncFs(
+            const std::string& backingPath, const std::string& targetDir, int32_t flags,
+            ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) override;
+    binder::Status unmountIncFs(const std::string& dir) override;
+    binder::Status bindMount(const std::string& sourceDir, const std::string& targetDir) override;
 };
 
 }  // namespace vold
diff --git a/VoldNativeServiceValidation.cpp b/VoldNativeServiceValidation.cpp
new file mode 100644
index 0000000..61d8981
--- /dev/null
+++ b/VoldNativeServiceValidation.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "VoldNativeServiceValidation.h"
+
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <private/android_filesystem_config.h>
+
+#include <cctype>
+#include <string_view>
+
+using android::base::StringPrintf;
+using namespace std::literals;
+
+namespace android::vold {
+
+binder::Status Ok() {
+    return binder::Status::ok();
+}
+
+binder::Status Exception(uint32_t code, const std::string& msg) {
+    return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
+}
+
+binder::Status CheckPermission(const char* permission) {
+    pid_t pid;
+    uid_t uid;
+
+    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
+                               reinterpret_cast<int32_t*>(&uid))) {
+        return Ok();
+    } else {
+        return Exception(binder::Status::EX_SECURITY,
+                         StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
+    }
+}
+
+binder::Status CheckUidOrRoot(uid_t expectedUid) {
+    uid_t uid = IPCThreadState::self()->getCallingUid();
+    if (uid == expectedUid || uid == AID_ROOT) {
+        return Ok();
+    } else {
+        return Exception(binder::Status::EX_SECURITY,
+                         StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
+    }
+}
+
+binder::Status CheckArgumentId(const std::string& id) {
+    if (id.empty()) {
+        return Exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing ID");
+    }
+    for (const char& c : id) {
+        if (!std::isalnum(c) && c != ':' && c != ',') {
+            return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                             StringPrintf("ID %s is malformed", id.c_str()));
+        }
+    }
+    return Ok();
+}
+
+binder::Status CheckArgumentPath(const std::string& path) {
+    if (path.empty()) {
+        return Exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
+    }
+    if (path[0] != '/') {
+        return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                         StringPrintf("Path %s is relative", path.c_str()));
+    }
+    if (path.find("/../"sv) != path.npos || android::base::EndsWith(path, "/.."sv)) {
+        return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                         StringPrintf("Path %s is shady", path.c_str()));
+    }
+    for (const char& c : path) {
+        if (c == '\0' || c == '\n') {
+            return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                             StringPrintf("Path %s is malformed", path.c_str()));
+        }
+    }
+    return Ok();
+}
+
+binder::Status CheckArgumentHex(const std::string& hex) {
+    // Empty hex strings are allowed
+    for (const char& c : hex) {
+        if (!std::isxdigit(c) && c != ':' && c != '-') {
+            return Exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                             StringPrintf("Hex %s is malformed", hex.c_str()));
+        }
+    }
+    return Ok();
+}
+
+}  // namespace android::vold
diff --git a/VoldNativeServiceValidation.h b/VoldNativeServiceValidation.h
new file mode 100644
index 0000000..d2fc9e0
--- /dev/null
+++ b/VoldNativeServiceValidation.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <binder/Status.h>
+
+#include <string>
+
+#include <stdint.h>
+#include <sys/types.h>
+
+namespace android::vold {
+
+binder::Status Ok();
+binder::Status Exception(uint32_t code, const std::string& msg);
+
+binder::Status CheckPermission(const char* permission);
+binder::Status CheckUidOrRoot(uid_t expectedUid);
+binder::Status CheckArgumentId(const std::string& id);
+binder::Status CheckArgumentPath(const std::string& path);
+binder::Status CheckArgumentHex(const std::string& hex);
+
+}  // namespace android::vold
diff --git a/VoldUtil.cpp b/VoldUtil.cpp
index 4b980be..082f743 100644
--- a/VoldUtil.cpp
+++ b/VoldUtil.cpp
@@ -14,7 +14,6 @@
  * limitations under the License.
  */
 
-#include <linux/fs.h>
-#include <sys/ioctl.h>
+#include "VoldUtil.h"
 
-struct fstab* fstab_default;
+android::fs_mgr::Fstab fstab_default;
diff --git a/VoldUtil.h b/VoldUtil.h
index 782e36d..ce6b411 100644
--- a/VoldUtil.h
+++ b/VoldUtil.h
@@ -14,14 +14,10 @@
  * limitations under the License.
  */
 
-#ifndef _VOLDUTIL_H
-#define _VOLDUTIL_H
+#pragma once
 
 #include <fstab/fstab.h>
-#include <sys/cdefs.h>
 
-extern struct fstab* fstab_default;
+extern android::fs_mgr::Fstab fstab_default;
 
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
-
-#endif
+#define DATA_MNT_POINT "/data"
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index e08319b..f860eef 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -30,9 +30,11 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <unistd.h>
+#include <array>
 
 #include <linux/kdev_t.h>
 
+#include <ApexProperties.sysprop.h>
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
 #include <android-base/properties.h>
@@ -57,24 +59,37 @@
 #include "NetlinkManager.h"
 #include "Process.h"
 #include "Utils.h"
+#include "VoldNativeService.h"
 #include "VoldUtil.h"
 #include "VolumeManager.h"
-#include "cryptfs.h"
 #include "fs/Ext4.h"
 #include "fs/Vfat.h"
 #include "model/EmulatedVolume.h"
 #include "model/ObbVolume.h"
 #include "model/StubVolume.h"
 
+using android::OK;
+using android::base::GetBoolProperty;
 using android::base::StartsWith;
+using android::base::StringAppendF;
 using android::base::StringPrintf;
 using android::base::unique_fd;
+using android::vold::BindMount;
+using android::vold::CreateDir;
+using android::vold::DeleteDirContents;
+using android::vold::DeleteDirContentsAndDir;
+using android::vold::Symlink;
+using android::vold::Unlink;
+using android::vold::UnmountTree;
+using android::vold::VoldNativeService;
 
 static const char* kPathUserMount = "/mnt/user";
 static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
 
 static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
 
+static const std::string kEmptyString("");
+
 /* 512MiB is large enough for testing purposes */
 static const unsigned int kSizeVirtualDisk = 536870912;
 
@@ -102,7 +117,7 @@
 
 int VolumeManager::updateVirtualDisk() {
     ATRACE_NAME("VolumeManager::updateVirtualDisk");
-    if (android::base::GetBoolProperty(kPropVirtualDisk, false)) {
+    if (GetBoolProperty(kPropVirtualDisk, false)) {
         if (access(kPathVirtualDisk, F_OK) != 0) {
             Loop::createImageFile(kPathVirtualDisk, kSizeVirtualDisk / 512);
         }
@@ -319,7 +334,8 @@
     return nullptr;
 }
 
-void VolumeManager::listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) {
+void VolumeManager::listVolumes(android::vold::VolumeBase::Type type,
+                                std::list<std::string>& list) const {
     list.clear();
     for (const auto& disk : mDisks) {
         disk->listVolumes(type, list);
@@ -349,22 +365,14 @@
 
 int VolumeManager::linkPrimary(userid_t userId) {
     std::string source(mPrimary->getPath());
-    if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
+    if (mPrimary->isEmulated()) {
         source = StringPrintf("%s/%d", source.c_str(), userId);
         fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
     }
 
     std::string target(StringPrintf("/mnt/user/%d/primary", userId));
-    if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
-        if (errno != ENOENT) {
-            PLOG(WARNING) << "Failed to unlink " << target;
-        }
-    }
     LOG(DEBUG) << "Linking " << source << " to " << target;
-    if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
-        PLOG(WARNING) << "Failed to link";
-        return -errno;
-    }
+    Symlink(source, target);
     return 0;
 }
 
@@ -379,6 +387,7 @@
 }
 
 int VolumeManager::onUserStarted(userid_t userId) {
+    LOG(VERBOSE) << "onUserStarted: " << userId;
     // Note that sometimes the system will spin up processes from Zygote
     // before actually starting the user, so we're okay if Zygote
     // already created this directory.
@@ -393,6 +402,7 @@
 }
 
 int VolumeManager::onUserStopped(userid_t userId) {
+    LOG(VERBOSE) << "onUserStopped: " << userId;
     mStartedUsers.erase(userId);
     return 0;
 }
@@ -419,7 +429,30 @@
     return 0;
 }
 
-int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
+int VolumeManager::remountUid(uid_t uid, int32_t mountMode) {
+    std::string mode;
+    switch (mountMode) {
+        case VoldNativeService::REMOUNT_MODE_NONE:
+            mode = "none";
+            break;
+        case VoldNativeService::REMOUNT_MODE_DEFAULT:
+            mode = "default";
+            break;
+        case VoldNativeService::REMOUNT_MODE_READ:
+            mode = "read";
+            break;
+        case VoldNativeService::REMOUNT_MODE_WRITE:
+        case VoldNativeService::REMOUNT_MODE_LEGACY:
+        case VoldNativeService::REMOUNT_MODE_INSTALLER:
+            mode = "write";
+            break;
+        case VoldNativeService::REMOUNT_MODE_FULL:
+            mode = "full";
+            break;
+        default:
+            PLOG(ERROR) << "Unknown mode " << std::to_string(mountMode);
+            return -1;
+    }
     LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
 
     DIR* dir;
@@ -431,6 +464,8 @@
     struct stat sb;
     pid_t child;
 
+    static bool apexUpdatable = android::sysprop::ApexProperties::updatable().value_or(false);
+
     if (!(dir = opendir("/proc"))) {
         PLOG(ERROR) << "Failed to opendir";
         return -1;
@@ -475,8 +510,29 @@
             goto next;
         }
 
+        if (apexUpdatable) {
+            std::string exeName;
+            // When ro.apex.bionic_updatable is set to true,
+            // some early native processes have mount namespaces that are different
+            // from that of the init. Therefore, above check can't filter them out.
+            // Since the propagation type of / is 'shared', unmounting /storage
+            // for the early native processes affects other processes including
+            // init. Filter out such processes by skipping if a process is a
+            // non-Java process whose UID is < AID_APP_START. (The UID condition
+            // is required to not filter out child processes spawned by apps.)
+            if (!android::vold::Readlinkat(pidFd, "exe", &exeName)) {
+                PLOG(WARNING) << "Failed to read exe name for " << de->d_name;
+                goto next;
+            }
+            if (!StartsWith(exeName, "/system/bin/app_process") && sb.st_uid < AID_APP_START) {
+                LOG(WARNING) << "Skipping due to native system process";
+                goto next;
+            }
+        }
+
         // We purposefully leave the namespace open across the fork
-        nsFd = openat(pidFd, "ns/mnt", O_RDONLY);  // not O_CLOEXEC
+        // NOLINTNEXTLINE(android-cloexec-open): Deliberately not O_CLOEXEC
+        nsFd = openat(pidFd, "ns/mnt", O_RDONLY);
         if (nsFd < 0) {
             PLOG(WARNING) << "Failed to open namespace for " << de->d_name;
             goto next;
@@ -497,6 +553,8 @@
                 storageSource = "/mnt/runtime/read";
             } else if (mode == "write") {
                 storageSource = "/mnt/runtime/write";
+            } else if (mode == "full") {
+                storageSource = "/mnt/runtime/full";
             } else {
                 // Sane default of no storage visible
                 _exit(0);
@@ -590,7 +648,7 @@
 
     // Worst case we might have some stale mounts lurking around, so
     // force unmount those just to be safe.
-    FILE* fp = setmntent("/proc/mounts", "r");
+    FILE* fp = setmntent("/proc/mounts", "re");
     if (fp == NULL) {
         PLOG(ERROR) << "Failed to open /proc/mounts";
         return -errno;
diff --git a/VolumeManager.h b/VolumeManager.h
index 9227819..9bf7599 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -52,7 +52,7 @@
     std::mutex& getCryptLock() { return mCryptLock; }
 
     void setListener(android::sp<android::os::IVoldListener> listener) { mListener = listener; }
-    android::sp<android::os::IVoldListener> getListener() { return mListener; }
+    android::sp<android::os::IVoldListener> getListener() const { return mListener; }
 
     int start();
     int stop();
@@ -68,8 +68,8 @@
             return !fnmatch(mSysPattern.c_str(), sysPath.c_str(), 0);
         }
 
-        const std::string& getNickname() { return mNickname; }
-        int getFlags() { return mFlags; }
+        const std::string& getNickname() const { return mNickname; }
+        int getFlags() const { return mFlags; }
 
       private:
         std::string mSysPattern;
@@ -82,7 +82,7 @@
     std::shared_ptr<android::vold::Disk> findDisk(const std::string& id);
     std::shared_ptr<android::vold::VolumeBase> findVolume(const std::string& id);
 
-    void listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list);
+    void listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) const;
 
     int forgetPartition(const std::string& partGuid, const std::string& fsUuid);
 
@@ -95,7 +95,7 @@
 
     int setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol);
 
-    int remountUid(uid_t uid, const std::string& mode);
+    int remountUid(uid_t uid, int32_t remountMode);
 
     /* Reset all internal state, typically during framework boot */
     int reset();
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index 976eab1..63a30e4 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -16,6 +16,7 @@
 
 package android.os;
 
+import android.os.incremental.IncrementalFileSystemControlParcel;
 import android.os.IVoldListener;
 import android.os.IVoldTaskListener;
 
@@ -32,6 +33,9 @@
     void onUserStarted(int userId);
     void onUserStopped(int userId);
 
+    void addAppIds(in @utf8InCpp String[] packageNames, in int[] appIds);
+    void addSandboxIds(in int[] appIds, in @utf8InCpp String[] sandboxIds);
+
     void onSecureKeyguardStateChanged(boolean isShowing);
 
     void partition(@utf8InCpp String diskId, int partitionType, int ratio);
@@ -78,14 +82,16 @@
     void mountDefaultEncrypted();
     void initUser0();
     boolean isConvertibleToFbe();
-    void mountFstab(@utf8InCpp String mountPoint);
-    void encryptFstab(@utf8InCpp String mountPoint);
+    void mountFstab(@utf8InCpp String blkDevice, @utf8InCpp String mountPoint);
+    void encryptFstab(@utf8InCpp String blkDevice, @utf8InCpp String mountPoint);
 
     void createUserKey(int userId, int userSerial, boolean ephemeral);
     void destroyUserKey(int userId);
 
     void addUserKeyAuth(int userId, int userSerial, @utf8InCpp String token,
                         @utf8InCpp String secret);
+    void clearUserKeyAuth(int userId, int userSerial, @utf8InCpp String token,
+                        @utf8InCpp String secret);
     void fixateNewestUserKeyAuth(int userId);
 
     void unlockUserKey(int userId, int userSerial, @utf8InCpp String token,
@@ -96,14 +102,24 @@
                             int storageFlags);
     void destroyUserStorage(@nullable @utf8InCpp String uuid, int userId, int storageFlags);
 
+    void prepareSandboxForApp(in @utf8InCpp String packageName, int appId,
+                              in @utf8InCpp String sandboxId, int userId);
+    void destroySandboxForApp(in @utf8InCpp String packageName,
+                              in @utf8InCpp String sandboxId, int userId);
+
     void startCheckpoint(int retry);
     boolean needsCheckpoint();
     boolean needsRollback();
-    void abortChanges();
+    void abortChanges(in @utf8InCpp String device, boolean retry);
     void commitChanges();
     void prepareCheckpoint();
     void restoreCheckpoint(@utf8InCpp String device);
+    void restoreCheckpointPart(@utf8InCpp String device, int count);
     void markBootAttempt();
+    boolean supportsCheckpoint();
+    boolean supportsBlockCheckpoint();
+    boolean supportsFileCheckpoint();
+    void resetCheckpoint();
 
     @utf8InCpp String createStubVolume(@utf8InCpp String sourcePath,
             @utf8InCpp String mountPath, @utf8InCpp String fsType,
@@ -112,6 +128,11 @@
 
     FileDescriptor openAppFuseFile(int uid, int mountId, int fileId, int flags);
 
+    boolean incFsEnabled();
+    IncrementalFileSystemControlParcel mountIncFs(@utf8InCpp String backingPath, @utf8InCpp String targetDir, int flags);
+    void unmountIncFs(@utf8InCpp String dir);
+    void bindMount(@utf8InCpp String sourceDir, @utf8InCpp String targetDir);
+
     const int ENCRYPTION_FLAG_NO_UI = 4;
 
     const int ENCRYPTION_STATE_NONE = 1;
@@ -142,6 +163,9 @@
     const int REMOUNT_MODE_DEFAULT = 1;
     const int REMOUNT_MODE_READ = 2;
     const int REMOUNT_MODE_WRITE = 3;
+    const int REMOUNT_MODE_LEGACY = 4;
+    const int REMOUNT_MODE_INSTALLER = 5;
+    const int REMOUNT_MODE_FULL = 6;
 
     const int VOLUME_STATE_UNMOUNTED = 0;
     const int VOLUME_STATE_CHECKING = 1;
diff --git a/cryptfs.cpp b/cryptfs.cpp
index 5be29be..5c075ac 100644
--- a/cryptfs.cpp
+++ b/cryptfs.cpp
@@ -14,17 +14,12 @@
  * limitations under the License.
  */
 
-/* TO DO:
- *   1.  Perhaps keep several copies of the encrypted key, in case something
- *       goes horribly wrong?
- *
- */
-
 #define LOG_TAG "Cryptfs"
 
 #include "cryptfs.h"
 
 #include "Checkpoint.h"
+#include "CryptoType.h"
 #include "EncryptInplace.h"
 #include "FsCrypt.h"
 #include "Keymaster.h"
@@ -33,9 +28,11 @@
 #include "Utils.h"
 #include "VoldUtil.h"
 #include "VolumeManager.h"
-#include "secontext.h"
 
+#include <android-base/parseint.h>
 #include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <bootloader_message/bootloader_message.h>
 #include <cutils/android_reboot.h>
 #include <cutils/properties.h>
@@ -43,25 +40,25 @@
 #include <f2fs_sparseblock.h>
 #include <fs_mgr.h>
 #include <fscrypt/fscrypt.h>
-#include <hardware_legacy/power.h>
+#include <libdm/dm.h>
 #include <log/log.h>
 #include <logwrap/logwrap.h>
 #include <openssl/evp.h>
 #include <openssl/sha.h>
 #include <selinux/selinux.h>
+#include <wakelock/wakelock.h>
 
 #include <ctype.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <inttypes.h>
 #include <libgen.h>
-#include <linux/dm-ioctl.h>
 #include <linux/kdev_t.h>
 #include <math.h>
+#include <mntent.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <sys/ioctl.h>
 #include <sys/mount.h>
 #include <sys/param.h>
 #include <sys/stat.h>
@@ -74,11 +71,196 @@
 #include <crypto_scrypt.h>
 }
 
+using android::base::ParseUint;
+using android::base::StringPrintf;
+using android::fs_mgr::GetEntryForMountPoint;
+using android::vold::CryptoType;
+using android::vold::KeyBuffer;
+using android::vold::KeyGeneration;
+using namespace android::dm;
 using namespace std::chrono_literals;
 
-#define UNUSED __attribute__((unused))
+/* The current cryptfs version */
+#define CURRENT_MAJOR_VERSION 1
+#define CURRENT_MINOR_VERSION 3
 
-#define DM_CRYPT_BUF_SIZE 4096
+#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
+#define CRYPT_PERSIST_DATA_SIZE 0x1000
+
+#define MAX_CRYPTO_TYPE_NAME_LEN 64
+
+#define MAX_KEY_LEN 48
+#define SALT_LEN 16
+#define SCRYPT_LEN 32
+
+/* definitions of flags in the structure below */
+#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
+#define CRYPT_ENCRYPTION_IN_PROGRESS       \
+    0x2 /* Encryption partially completed, \
+           encrypted_upto valid*/
+#define CRYPT_INCONSISTENT_STATE                    \
+    0x4 /* Set when starting encryption, clear when \
+           exit cleanly, either through success or  \
+           correctly marked partial encryption */
+#define CRYPT_DATA_CORRUPT                      \
+    0x8 /* Set when encryption is fine, but the \
+           underlying volume is corrupt */
+#define CRYPT_FORCE_ENCRYPTION                        \
+    0x10 /* Set when it is time to encrypt this       \
+            volume on boot. Everything in this        \
+            structure is set up correctly as          \
+            though device is encrypted except         \
+            that the master key is encrypted with the \
+            default password. */
+#define CRYPT_FORCE_COMPLETE                           \
+    0x20 /* Set when the above encryption cycle is     \
+            complete. On next cryptkeeper entry, match \
+            the password. If it matches fix the master \
+            key and remove this flag. */
+
+/* Allowed values for type in the structure below */
+#define CRYPT_TYPE_PASSWORD                       \
+    0 /* master_key is encrypted with a password  \
+       * Must be zero to be compatible with pre-L \
+       * devices where type is always password.*/
+#define CRYPT_TYPE_DEFAULT                                            \
+    1                         /* master_key is encrypted with default \
+                               * password */
+#define CRYPT_TYPE_PATTERN 2  /* master_key is encrypted with a pattern */
+#define CRYPT_TYPE_PIN 3      /* master_key is encrypted with a pin */
+#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
+
+#define CRYPT_MNT_MAGIC 0xD0B5B1C4
+#define PERSIST_DATA_MAGIC 0xE950CD44
+
+/* Key Derivation Function algorithms */
+#define KDF_PBKDF2 1
+#define KDF_SCRYPT 2
+/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
+#define KDF_SCRYPT_KEYMASTER 5
+
+/* Maximum allowed keymaster blob size. */
+#define KEYMASTER_BLOB_SIZE 2048
+
+/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
+#define __le8 unsigned char
+
+#if !defined(SHA256_DIGEST_LENGTH)
+#define SHA256_DIGEST_LENGTH 32
+#endif
+
+/* This structure starts 16,384 bytes before the end of a hardware
+ * partition that is encrypted, or in a separate partition.  It's location
+ * is specified by a property set in init.<device>.rc.
+ * The structure allocates 48 bytes for a key, but the real key size is
+ * specified in the struct.  Currently, the code is hardcoded to use 128
+ * bit keys.
+ * The fields after salt are only valid in rev 1.1 and later stuctures.
+ * Obviously, the filesystem does not include the last 16 kbytes
+ * of the partition if the crypt_mnt_ftr lives at the end of the
+ * partition.
+ */
+
+struct crypt_mnt_ftr {
+    __le32 magic; /* See above */
+    __le16 major_version;
+    __le16 minor_version;
+    __le32 ftr_size;             /* in bytes, not including key following */
+    __le32 flags;                /* See above */
+    __le32 keysize;              /* in bytes */
+    __le32 crypt_type;           /* how master_key is encrypted. Must be a
+                                  * CRYPT_TYPE_XXX value */
+    __le64 fs_size;              /* Size of the encrypted fs, in 512 byte sectors */
+    __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
+                                    mount, set to 0 on successful mount */
+    unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
+                                                                 needed to decrypt this
+                                                                 partition, null terminated */
+    __le32 spare2;                                            /* ignored */
+    unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
+    unsigned char salt[SALT_LEN];          /* The salt used for this encryption */
+    __le64 persist_data_offset[2];         /* Absolute offset to both copies of crypt_persist_data
+                                            * on device with that info, either the footer of the
+                                            * real_blkdevice or the metadata partition. */
+
+    __le32 persist_data_size; /* The number of bytes allocated to each copy of the
+                               * persistent data table*/
+
+    __le8 kdf_type; /* The key derivation function used. */
+
+    /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
+    __le8 N_factor;        /* (1 << N) */
+    __le8 r_factor;        /* (1 << r) */
+    __le8 p_factor;        /* (1 << p) */
+    __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
+                              we have to stop (e.g. power low) this is the last
+                              encrypted 512 byte sector.*/
+    __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
+                                                     set, hash of first block, used
+                                                     to validate before continuing*/
+
+    /* key_master key, used to sign the derived key which is then used to generate
+     * the intermediate key
+     * This key should be used for no other purposes! We use this key to sign unpadded
+     * data, which is acceptable but only if the key is not reused elsewhere. */
+    __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
+    __le32 keymaster_blob_size;
+
+    /* Store scrypt of salted intermediate key. When decryption fails, we can
+       check if this matches, and if it does, we know that the problem is with the
+       drive, and there is no point in asking the user for more passwords.
+
+       Note that if any part of this structure is corrupt, this will not match and
+       we will continue to believe the user entered the wrong password. In that
+       case the only solution is for the user to enter a password enough times to
+       force a wipe.
+
+       Note also that there is no need to worry about migration. If this data is
+       wrong, we simply won't recognise a right password, and will continue to
+       prompt. On the first password change, this value will be populated and
+       then we will be OK.
+     */
+    unsigned char scrypted_intermediate_key[SCRYPT_LEN];
+
+    /* sha of this structure with this element set to zero
+       Used when encrypting on reboot to validate structure before doing something
+       fatal
+     */
+    unsigned char sha256[SHA256_DIGEST_LENGTH];
+};
+
+/* Persistant data that should be available before decryption.
+ * Things like airplane mode, locale and timezone are kept
+ * here and can be retrieved by the CryptKeeper UI to properly
+ * configure the phone before asking for the password
+ * This is only valid if the major and minor version above
+ * is set to 1.1 or higher.
+ *
+ * This is a 4K structure.  There are 2 copies, and the code alternates
+ * writing one and then clearing the previous one.  The reading
+ * code reads the first valid copy it finds, based on the magic number.
+ * The absolute offset to the first of the two copies is kept in rev 1.1
+ * and higher crypt_mnt_ftr structures.
+ */
+struct crypt_persist_entry {
+    char key[PROPERTY_KEY_MAX];
+    char val[PROPERTY_VALUE_MAX];
+};
+
+/* Should be exactly 4K in size */
+struct crypt_persist_data {
+    __le32 persist_magic;
+    __le32 persist_valid_entries;
+    __le32 persist_spare[30];
+    struct crypt_persist_entry persist_entry[0];
+};
+
+static int wait_and_unmount(const char* mountpoint, bool kill);
+
+typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
+                        void* params);
+
+#define UNUSED __attribute__((unused))
 
 #define HASH_COUNT 2000
 
@@ -119,6 +301,32 @@
 static int master_key_saved = 0;
 static struct crypt_persist_data* persist_data = NULL;
 
+constexpr CryptoType aes_128_cbc = CryptoType()
+                                           .set_config_name("AES-128-CBC")
+                                           .set_kernel_name("aes-cbc-essiv:sha256")
+                                           .set_keysize(16);
+
+constexpr CryptoType supported_crypto_types[] = {aes_128_cbc, android::vold::adiantum};
+
+static_assert(validateSupportedCryptoTypes(MAX_KEY_LEN, supported_crypto_types,
+                                           array_length(supported_crypto_types)),
+              "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
+              "incompletely constructed.");
+
+static const CryptoType& get_crypto_type() {
+    // We only want to parse this read-only property once.  But we need to wait
+    // until the system is initialized before we can read it.  So we use a static
+    // scoped within this function to get it only once.
+    static CryptoType crypto_type =
+            lookup_crypto_algorithm(supported_crypto_types, array_length(supported_crypto_types),
+                                    aes_128_cbc, "ro.crypto.fde_algorithm");
+    return crypto_type;
+}
+
+const KeyGeneration cryptfs_get_keygen() {
+    return KeyGeneration{get_crypto_type().get_keysize(), true, false};
+}
+
 /* Should we use keymaster? */
 static int keymaster_check_compatibility() {
     return keymaster_compatibility_cryptfs_scrypt();
@@ -249,127 +457,6 @@
     return;
 }
 
-static void ioctl_init(struct dm_ioctl* io, size_t dataSize, const char* name, unsigned flags) {
-    memset(io, 0, dataSize);
-    io->data_size = dataSize;
-    io->data_start = sizeof(struct dm_ioctl);
-    io->version[0] = 4;
-    io->version[1] = 0;
-    io->version[2] = 0;
-    io->flags = flags;
-    if (name) {
-        strlcpy(io->name, name, sizeof(io->name));
-    }
-}
-
-namespace {
-
-struct CryptoType;
-
-// Use to get the CryptoType in use on this device.
-const CryptoType& get_crypto_type();
-
-struct CryptoType {
-    // We should only be constructing CryptoTypes as part of
-    // supported_crypto_types[].  We do it via this pseudo-builder pattern,
-    // which isn't pure or fully protected as a concession to being able to
-    // do it all at compile time.  Add new CryptoTypes in
-    // supported_crypto_types[] below.
-    constexpr CryptoType() : CryptoType(nullptr, nullptr, 0xFFFFFFFF) {}
-    constexpr CryptoType set_keysize(uint32_t size) const {
-        return CryptoType(this->property_name, this->crypto_name, size);
-    }
-    constexpr CryptoType set_property_name(const char* property) const {
-        return CryptoType(property, this->crypto_name, this->keysize);
-    }
-    constexpr CryptoType set_crypto_name(const char* crypto) const {
-        return CryptoType(this->property_name, crypto, this->keysize);
-    }
-
-    constexpr const char* get_property_name() const { return property_name; }
-    constexpr const char* get_crypto_name() const { return crypto_name; }
-    constexpr uint32_t get_keysize() const { return keysize; }
-
-  private:
-    const char* property_name;
-    const char* crypto_name;
-    uint32_t keysize;
-
-    constexpr CryptoType(const char* property, const char* crypto, uint32_t ksize)
-        : property_name(property), crypto_name(crypto), keysize(ksize) {}
-    friend const CryptoType& get_crypto_type();
-    static const CryptoType& get_device_crypto_algorithm();
-};
-
-// We only want to parse this read-only property once.  But we need to wait
-// until the system is initialized before we can read it.  So we use a static
-// scoped within this function to get it only once.
-const CryptoType& get_crypto_type() {
-    static CryptoType crypto_type = CryptoType::get_device_crypto_algorithm();
-    return crypto_type;
-}
-
-constexpr CryptoType default_crypto_type = CryptoType()
-                                               .set_property_name("AES-128-CBC")
-                                               .set_crypto_name("aes-cbc-essiv:sha256")
-                                               .set_keysize(16);
-
-constexpr CryptoType supported_crypto_types[] = {
-    default_crypto_type,
-    // Add new CryptoTypes here.  Order is not important.
-};
-
-// ---------- START COMPILE-TIME SANITY CHECK BLOCK -------------------------
-// We confirm all supported_crypto_types have a small enough keysize and
-// had both set_property_name() and set_crypto_name() called.
-
-template <typename T, size_t N>
-constexpr size_t array_length(T (&)[N]) {
-    return N;
-}
-
-constexpr bool indexOutOfBoundsForCryptoTypes(size_t index) {
-    return (index >= array_length(supported_crypto_types));
-}
-
-constexpr bool isValidCryptoType(const CryptoType& crypto_type) {
-    return ((crypto_type.get_property_name() != nullptr) &&
-            (crypto_type.get_crypto_name() != nullptr) &&
-            (crypto_type.get_keysize() <= MAX_KEY_LEN));
-}
-
-// Note in C++11 that constexpr functions can only have a single line.
-// So our code is a bit convoluted (using recursion instead of a loop),
-// but it's asserting at compile time that all of our key lengths are valid.
-constexpr bool validateSupportedCryptoTypes(size_t index) {
-    return indexOutOfBoundsForCryptoTypes(index) ||
-           (isValidCryptoType(supported_crypto_types[index]) &&
-            validateSupportedCryptoTypes(index + 1));
-}
-
-static_assert(validateSupportedCryptoTypes(0),
-              "We have a CryptoType with keysize > MAX_KEY_LEN or which was "
-              "incompletely constructed.");
-//  ---------- END COMPILE-TIME SANITY CHECK BLOCK -------------------------
-
-// Don't call this directly, use get_crypto_type(), which caches this result.
-const CryptoType& CryptoType::get_device_crypto_algorithm() {
-    constexpr char CRYPT_ALGO_PROP[] = "ro.crypto.fde_algorithm";
-    char paramstr[PROPERTY_VALUE_MAX];
-
-    property_get(CRYPT_ALGO_PROP, paramstr, default_crypto_type.get_property_name());
-    for (auto const& ctype : supported_crypto_types) {
-        if (strcmp(paramstr, ctype.get_property_name()) == 0) {
-            return ctype;
-        }
-    }
-    ALOGE("Invalid name (%s) for %s.  Defaulting to %s\n", paramstr, CRYPT_ALGO_PROP,
-          default_crypto_type.get_property_name());
-    return default_crypto_type;
-}
-
-}  // namespace
-
 /**
  * Gets the default device scrypt parameters for key derivation time tuning.
  * The parameters should lead to about one second derivation time for the
@@ -389,15 +476,7 @@
     ftr->p_factor = pf;
 }
 
-uint32_t cryptfs_get_keysize() {
-    return get_crypto_type().get_keysize();
-}
-
-const char* cryptfs_get_crypto_name() {
-    return get_crypto_type().get_crypto_name();
-}
-
-static uint64_t get_fs_size(char* dev) {
+static uint64_t get_fs_size(const char* dev) {
     int fd, block_size;
     struct ext4_super_block sb;
     uint64_t len;
@@ -431,6 +510,22 @@
     return len / 512;
 }
 
+static void get_crypt_info(std::string* key_loc, std::string* real_blk_device) {
+    for (const auto& entry : fstab_default) {
+        if (!entry.fs_mgr_flags.vold_managed &&
+            (entry.fs_mgr_flags.crypt || entry.fs_mgr_flags.force_crypt ||
+             entry.fs_mgr_flags.force_fde_or_fbe || entry.fs_mgr_flags.file_encryption)) {
+            if (key_loc != nullptr) {
+                *key_loc = entry.key_loc;
+            }
+            if (real_blk_device != nullptr) {
+                *real_blk_device = entry.blk_device;
+            }
+            return;
+        }
+    }
+}
+
 static int get_crypt_ftr_info(char** metadata_fname, off64_t* off) {
     static int cached_data = 0;
     static uint64_t cached_off = 0;
@@ -440,22 +535,24 @@
     int rc = -1;
 
     if (!cached_data) {
-        fs_mgr_get_crypt_info(fstab_default, key_loc, real_blkdev, sizeof(key_loc));
+        std::string key_loc;
+        std::string real_blkdev;
+        get_crypt_info(&key_loc, &real_blkdev);
 
-        if (!strcmp(key_loc, KEY_IN_FOOTER)) {
+        if (key_loc == KEY_IN_FOOTER) {
             if (android::vold::GetBlockDevSize(real_blkdev, &cached_off) == android::OK) {
                 /* If it's an encrypted Android partition, the last 16 Kbytes contain the
                  * encryption info footer and key, and plenty of bytes to spare for future
                  * growth.
                  */
-                strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
+                strlcpy(cached_metadata_fname, real_blkdev.c_str(), sizeof(cached_metadata_fname));
                 cached_off -= CRYPT_FOOTER_OFFSET;
                 cached_data = 1;
             } else {
-                SLOGE("Cannot get size of block device %s\n", real_blkdev);
+                SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
             }
         } else {
-            strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
+            strlcpy(cached_metadata_fname, key_loc.c_str(), sizeof(cached_metadata_fname));
             cached_off = 0;
             cached_data = 1;
         }
@@ -947,202 +1044,99 @@
     master_key_ascii[a] = '\0';
 }
 
-static int load_crypto_mapping_table(struct crypt_mnt_ftr* crypt_ftr,
-                                     const unsigned char* master_key, const char* real_blk_name,
-                                     const char* name, int fd, const char* extra_params) {
-    alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
-    struct dm_ioctl* io;
-    struct dm_target_spec* tgt;
-    char* crypt_params;
-    // We need two ASCII characters to represent each byte, and need space for
-    // the '\0' terminator.
-    char master_key_ascii[MAX_KEY_LEN * 2 + 1];
-    size_t buff_offset;
-    int i;
+/*
+ * If the ro.crypto.fde_sector_size system property is set, append the
+ * parameters to make dm-crypt use the specified crypto sector size and round
+ * the crypto device size down to a crypto sector boundary.
+ */
+static int add_sector_size_param(DmTargetCrypt* target, struct crypt_mnt_ftr* ftr) {
+    constexpr char DM_CRYPT_SECTOR_SIZE[] = "ro.crypto.fde_sector_size";
+    char value[PROPERTY_VALUE_MAX];
 
-    io = (struct dm_ioctl*)buffer;
+    if (property_get(DM_CRYPT_SECTOR_SIZE, value, "") > 0) {
+        unsigned int sector_size;
 
-    /* Load the mapping table for this device */
-    tgt = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
-
-    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-    io->target_count = 1;
-    tgt->status = 0;
-    tgt->sector_start = 0;
-    tgt->length = crypt_ftr->fs_size;
-    strlcpy(tgt->target_type, "crypt", DM_MAX_TYPE_NAME);
-
-    crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
-    convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
-
-    buff_offset = crypt_params - buffer;
-    SLOGI("Extra parameters for dm_crypt: %s\n", extra_params);
-    snprintf(crypt_params, sizeof(buffer) - buff_offset, "%s %s 0 %s 0 %s",
-             crypt_ftr->crypto_type_name, master_key_ascii, real_blk_name, extra_params);
-    crypt_params += strlen(crypt_params) + 1;
-    crypt_params =
-        (char*)(((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
-    tgt->next = crypt_params - buffer;
-
-    for (i = 0; i < TABLE_LOAD_RETRIES; i++) {
-        if (!ioctl(fd, DM_TABLE_LOAD, io)) {
-            break;
+        if (!ParseUint(value, &sector_size) || sector_size < 512 || sector_size > 4096 ||
+            (sector_size & (sector_size - 1)) != 0) {
+            SLOGE("Invalid value for %s: %s.  Must be >= 512, <= 4096, and a power of 2\n",
+                  DM_CRYPT_SECTOR_SIZE, value);
+            return -1;
         }
-        usleep(500000);
+
+        target->SetSectorSize(sector_size);
+
+        // With this option, IVs will match the sector numbering, instead
+        // of being hard-coded to being based on 512-byte sectors.
+        target->SetIvLargeSectors();
+
+        // Round the crypto device size down to a crypto sector boundary.
+        ftr->fs_size &= ~((sector_size / 512) - 1);
     }
-
-    if (i == TABLE_LOAD_RETRIES) {
-        /* We failed to load the table, return an error */
-        return -1;
-    } else {
-        return i + 1;
-    }
-}
-
-static int get_dm_crypt_version(int fd, const char* name, int* version) {
-    char buffer[DM_CRYPT_BUF_SIZE];
-    struct dm_ioctl* io;
-    struct dm_target_versions* v;
-
-    io = (struct dm_ioctl*)buffer;
-
-    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-
-    if (ioctl(fd, DM_LIST_VERSIONS, io)) {
-        return -1;
-    }
-
-    /* Iterate over the returned versions, looking for name of "crypt".
-     * When found, get and return the version.
-     */
-    v = (struct dm_target_versions*)&buffer[sizeof(struct dm_ioctl)];
-    while (v->next) {
-        if (!strcmp(v->name, "crypt")) {
-            /* We found the crypt driver, return the version, and get out */
-            version[0] = v->version[0];
-            version[1] = v->version[1];
-            version[2] = v->version[2];
-            return 0;
-        }
-        v = (struct dm_target_versions*)(((char*)v) + v->next);
-    }
-
-    return -1;
-}
-
-static std::string extra_params_as_string(const std::vector<std::string>& extra_params_vec) {
-    if (extra_params_vec.empty()) return "";
-    std::string extra_params = std::to_string(extra_params_vec.size());
-    for (const auto& p : extra_params_vec) {
-        extra_params.append(" ");
-        extra_params.append(p);
-    }
-    return extra_params;
+    return 0;
 }
 
 static int create_crypto_blk_dev(struct crypt_mnt_ftr* crypt_ftr, const unsigned char* master_key,
-                                 const char* real_blk_name, char* crypto_blk_name, const char* name,
-                                 uint32_t flags) {
-    char buffer[DM_CRYPT_BUF_SIZE];
-    struct dm_ioctl* io;
-    unsigned int minor;
-    int fd = 0;
-    int err;
-    int retval = -1;
-    int version[3];
-    int load_count;
-    std::vector<std::string> extra_params_vec;
+                                 const char* real_blk_name, std::string* crypto_blk_name,
+                                 const char* name, uint32_t flags) {
+    auto& dm = DeviceMapper::Instance();
 
-    if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
-        SLOGE("Cannot open device-mapper\n");
-        goto errout;
-    }
+    // We need two ASCII characters to represent each byte, and need space for
+    // the '\0' terminator.
+    char master_key_ascii[MAX_KEY_LEN * 2 + 1];
+    convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
 
-    io = (struct dm_ioctl*)buffer;
+    auto target = std::make_unique<DmTargetCrypt>(0, crypt_ftr->fs_size,
+                                                  (const char*)crypt_ftr->crypto_type_name,
+                                                  master_key_ascii, 0, real_blk_name, 0);
+    target->AllowDiscards();
 
-    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-    err = ioctl(fd, DM_DEV_CREATE, io);
-    if (err) {
-        SLOGE("Cannot create dm-crypt device %s: %s\n", name, strerror(errno));
-        goto errout;
-    }
-
-    /* Get the device status, in particular, the name of it's device file */
-    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-    if (ioctl(fd, DM_DEV_STATUS, io)) {
-        SLOGE("Cannot retrieve dm-crypt device status\n");
-        goto errout;
-    }
-    minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
-    snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
-
-    if (!get_dm_crypt_version(fd, name, version)) {
-        /* Support for allow_discards was added in version 1.11.0 */
-        if ((version[0] >= 2) || ((version[0] == 1) && (version[1] >= 11))) {
-            extra_params_vec.emplace_back("allow_discards");
-        }
-    }
     if (flags & CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE) {
-        extra_params_vec.emplace_back("allow_encrypt_override");
+        target->AllowEncryptOverride();
     }
-    load_count = load_crypto_mapping_table(crypt_ftr, master_key, real_blk_name, name, fd,
-                                           extra_params_as_string(extra_params_vec).c_str());
-    if (load_count < 0) {
+    if (add_sector_size_param(target.get(), crypt_ftr)) {
+        SLOGE("Error processing dm-crypt sector size param\n");
+        return -1;
+    }
+
+    DmTable table;
+    table.AddTarget(std::move(target));
+
+    int load_count = 1;
+    while (load_count < TABLE_LOAD_RETRIES) {
+        if (dm.CreateDevice(name, table)) {
+            break;
+        }
+        load_count++;
+    }
+
+    if (load_count >= TABLE_LOAD_RETRIES) {
         SLOGE("Cannot load dm-crypt mapping table.\n");
-        goto errout;
-    } else if (load_count > 1) {
+        return -1;
+    }
+    if (load_count > 1) {
         SLOGI("Took %d tries to load dmcrypt table.\n", load_count);
     }
 
-    /* Resume this device to activate it */
-    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-
-    if (ioctl(fd, DM_DEV_SUSPEND, io)) {
-        SLOGE("Cannot resume the dm-crypt device\n");
-        goto errout;
+    if (!dm.GetDmDevicePathByName(name, crypto_blk_name)) {
+        SLOGE("Cannot determine dm-crypt path for %s.\n", name);
+        return -1;
     }
 
     /* Ensure the dm device has been created before returning. */
-    if (android::vold::WaitForFile(crypto_blk_name, 1s) < 0) {
+    if (android::vold::WaitForFile(crypto_blk_name->c_str(), 1s) < 0) {
         // WaitForFile generates a suitable log message
-        goto errout;
+        return -1;
     }
-
-    /* We made it here with no errors.  Woot! */
-    retval = 0;
-
-errout:
-    close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
-
-    return retval;
+    return 0;
 }
 
-static int delete_crypto_blk_dev(const char* name) {
-    int fd;
-    char buffer[DM_CRYPT_BUF_SIZE];
-    struct dm_ioctl* io;
-    int retval = -1;
-
-    if ((fd = open("/dev/device-mapper", O_RDWR | O_CLOEXEC)) < 0) {
-        SLOGE("Cannot open device-mapper\n");
-        goto errout;
+static int delete_crypto_blk_dev(const std::string& name) {
+    auto& dm = DeviceMapper::Instance();
+    if (!dm.DeleteDevice(name)) {
+        SLOGE("Cannot remove dm-crypt device %s: %s\n", name.c_str(), strerror(errno));
+        return -1;
     }
-
-    io = (struct dm_ioctl*)buffer;
-
-    ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
-    if (ioctl(fd, DM_DEV_REMOVE, io)) {
-        SLOGE("Cannot remove dm-crypt device\n");
-        goto errout;
-    }
-
-    /* We made it here with no errors.  Woot! */
-    retval = 0;
-
-errout:
-    close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
-
-    return retval;
+    return 0;
 }
 
 static int pbkdf2(const char* passwd, const unsigned char* salt, unsigned char* ikey,
@@ -1374,21 +1368,60 @@
 
 static int create_encrypted_random_key(const char* passwd, unsigned char* master_key,
                                        unsigned char* salt, struct crypt_mnt_ftr* crypt_ftr) {
-    int fd;
     unsigned char key_buf[MAX_KEY_LEN];
 
-    /* Get some random bits for a key */
-    fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
-    read(fd, key_buf, sizeof(key_buf));
-    read(fd, salt, SALT_LEN);
-    close(fd);
+    /* Get some random bits for a key and salt */
+    if (android::vold::ReadRandomBytes(sizeof(key_buf), reinterpret_cast<char*>(key_buf)) != 0) {
+        return -1;
+    }
+    if (android::vold::ReadRandomBytes(SALT_LEN, reinterpret_cast<char*>(salt)) != 0) {
+        return -1;
+    }
 
     /* Now encrypt it with the password */
     return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
 }
 
-int wait_and_unmount(const char* mountpoint, bool kill) {
+static void ensure_subdirectory_unmounted(const char *prefix) {
+    std::vector<std::string> umount_points;
+    std::unique_ptr<FILE, int (*)(FILE*)> mnts(setmntent("/proc/mounts", "r"), endmntent);
+    if (!mnts) {
+        SLOGW("could not read mount files");
+        return;
+    }
+
+    //Find sudirectory mount point
+    mntent* mentry;
+    std::string top_directory(prefix);
+    if (!android::base::EndsWith(prefix, "/")) {
+        top_directory = top_directory + "/";
+    }
+    while ((mentry = getmntent(mnts.get())) != nullptr) {
+        if (strcmp(mentry->mnt_dir, top_directory.c_str()) == 0) {
+            continue;
+        }
+
+        if (android::base::StartsWith(mentry->mnt_dir, top_directory)) {
+            SLOGW("found sub-directory mount %s - %s\n", prefix, mentry->mnt_dir);
+            umount_points.push_back(mentry->mnt_dir);
+        }
+    }
+
+    //Sort by path length to umount longest path first
+    std::sort(std::begin(umount_points), std::end(umount_points),
+        [](const std::string& s1, const std::string& s2) {return s1.length() > s2.length(); });
+
+    for (std::string& mount_point : umount_points) {
+        umount(mount_point.c_str());
+        SLOGW("umount sub-directory mount %s\n", mount_point.c_str());
+    }
+}
+
+static int wait_and_unmount(const char* mountpoint, bool kill) {
     int i, err, rc;
+
+    // Subdirectory mount will cause a failure of umount.
+    ensure_subdirectory_unmounted(mountpoint);
 #define WAIT_UNMOUNT_COUNT 20
 
     /*  Now umount the tmpfs filesystem */
@@ -1500,12 +1533,23 @@
 
     if (restart_main) {
         /* Here is where we shut down the framework.  The init scripts
-         * start all services in one of three classes: core, main or late_start.
-         * On boot, we start core and main.  Now, we stop main, but not core,
-         * as core includes vold and a few other really important things that
-         * we need to keep running.  Once main has stopped, we should be able
+         * start all services in one of these classes: core, early_hal, hal,
+         * main and late_start. To get to the minimal UI for PIN entry, we
+         * need to start core, early_hal, hal and main. When we want to
+         * shutdown the framework again, we need to stop most of the services in
+         * these classes, but only those services that were started after
+         * /data was mounted. This excludes critical services like vold and
+         * ueventd, which need to keep running. We could possible stop
+         * even fewer services, but because we want services to pick up APEX
+         * libraries from the real /data, restarting is better, as it makes
+         * these devices consistent with FBE devices and lets them use the
+         * most recent code.
+         *
+         * Once these services have stopped, we should be able
          * to umount the tmpfs /data, then mount the encrypted /data.
-         * We then restart the class main, and also the class late_start.
+         * We then restart the class core, hal, main, and also the class
+         * late_start.
+         *
          * At the moment, I've only put a few things in late_start that I know
          * are not needed to bring up the framework, and that also cause problems
          * with unmounting the tmpfs /data, but I hope to add add more services
@@ -1513,10 +1557,10 @@
          * till the user is asked for the password to the filesystem.
          */
 
-        /* The init files are setup to stop the class main when vold.decrypt is
-         * set to trigger_reset_main.
+        /* The init files are setup to stop the right set of services when
+         * vold.decrypt is set to trigger_shutdown_framework.
          */
-        property_set("vold.decrypt", "trigger_reset_main");
+        property_set("vold.decrypt", "trigger_shutdown_framework");
         SLOGD("Just asked init to shut down class main\n");
 
         /* Ugh, shutting down the framework is not synchronous, so until it
@@ -1545,9 +1589,9 @@
         char ro_prop[PROPERTY_VALUE_MAX];
         property_get("ro.crypto.readonly", ro_prop, "");
         if (strlen(ro_prop) > 0 && std::stoi(ro_prop)) {
-            struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
-            if (rec) {
-                rec->flags |= MS_RDONLY;
+            auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+            if (entry != nullptr) {
+                entry->flags |= MS_RDONLY;
             }
         }
 
@@ -1559,12 +1603,12 @@
          * fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
          * partitions in the fsck domain.
          */
-        if (setexeccon(secontextFsck())) {
+        if (setexeccon(android::vold::sFsckContext)) {
             SLOGE("Failed to setexeccon");
             return -1;
         }
         bool needs_cp = android::vold::cp_needsCheckpoint();
-        while ((mount_rc = fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
+        while ((mount_rc = fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT, crypto_blkdev, 0,
                                            needs_cp)) != 0) {
             if (mount_rc == FS_MGR_DOMNT_BUSY) {
                 /* TODO: invoke something similar to
@@ -1627,7 +1671,6 @@
 static int do_crypto_complete(const char* mount_point) {
     struct crypt_mnt_ftr crypt_ftr;
     char encrypted_state[PROPERTY_VALUE_MAX];
-    char key_loc[PROPERTY_VALUE_MAX];
 
     property_get("ro.crypto.state", encrypted_state, "");
     if (strcmp(encrypted_state, "encrypted")) {
@@ -1641,7 +1684,8 @@
     }
 
     if (get_crypt_ftr_and_key(&crypt_ftr)) {
-        fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
+        std::string key_loc;
+        get_crypt_info(&key_loc, nullptr);
 
         /*
          * Only report this error if key_loc is a file and it exists.
@@ -1650,7 +1694,7 @@
          * a "enter password" screen, or worse, a "press button to wipe the
          * device" screen.
          */
-        if ((key_loc[0] == '/') && (access("key_loc", F_OK) == -1)) {
+        if (!key_loc.empty() && key_loc[0] == '/' && (access("key_loc", F_OK) == -1)) {
             SLOGE("master key file does not exist, aborting");
             return CRYPTO_COMPLETE_NOT_ENCRYPTED;
         } else {
@@ -1682,8 +1726,8 @@
 static int test_mount_encrypted_fs(struct crypt_mnt_ftr* crypt_ftr, const char* passwd,
                                    const char* mount_point, const char* label) {
     unsigned char decrypted_master_key[MAX_KEY_LEN];
-    char crypto_blkdev[MAXPATHLEN];
-    char real_blkdev[MAXPATHLEN];
+    std::string crypto_blkdev;
+    std::string real_blkdev;
     char tmp_mount_point[64];
     unsigned int orig_failed_decrypt_count;
     int rc;
@@ -1707,12 +1751,12 @@
         }
     }
 
-    fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
+    get_crypt_info(nullptr, &real_blkdev);
 
     // Create crypto block device - all (non fatal) code paths
     // need it
-    if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev, label,
-                              0)) {
+    if (create_crypto_blk_dev(crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
+                              label, 0)) {
         SLOGE("Error creating decrypted block device\n");
         rc = -1;
         goto errout;
@@ -1735,7 +1779,8 @@
          * the footer, not the key. */
         snprintf(tmp_mount_point, sizeof(tmp_mount_point), "%s/tmp_mnt", mount_point);
         mkdir(tmp_mount_point, 0755);
-        if (fs_mgr_do_mount(fstab_default, DATA_MNT_POINT, crypto_blkdev, tmp_mount_point)) {
+        if (fs_mgr_do_mount(&fstab_default, DATA_MNT_POINT,
+                            const_cast<char*>(crypto_blkdev.c_str()), tmp_mount_point)) {
             SLOGE("Error temp mounting decrypted block device\n");
             delete_crypto_blk_dev(label);
 
@@ -1757,7 +1802,7 @@
 
         /* Save the name of the crypto block device
          * so we can mount it when restarting the framework. */
-        property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
+        property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev.c_str());
 
         /* Also save a the master key so we can reencrypted the key
          * the key when we want to change the password on it. */
@@ -1814,11 +1859,15 @@
  * storage volume. The incoming partition has no crypto header/footer,
  * as any metadata is been stored in a separate, small partition.  We
  * assume it must be using our same crypt type and keysize.
- *
- * out_crypto_blkdev must be MAXPATHLEN.
  */
-int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
-                             char* out_crypto_blkdev) {
+int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const KeyBuffer& key,
+                             std::string* out_crypto_blkdev) {
+    auto crypto_type = get_crypto_type();
+    if (key.size() != crypto_type.get_keysize()) {
+        SLOGE("Raw keysize %zu does not match crypt keysize %zu", key.size(),
+              crypto_type.get_keysize());
+        return -1;
+    }
     uint64_t nr_sec = 0;
     if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
         SLOGE("Failed to get size of %s: %s", real_blkdev, strerror(errno));
@@ -1828,23 +1877,16 @@
     struct crypt_mnt_ftr ext_crypt_ftr;
     memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
     ext_crypt_ftr.fs_size = nr_sec;
-    ext_crypt_ftr.keysize = cryptfs_get_keysize();
-    strlcpy((char*)ext_crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
+    ext_crypt_ftr.keysize = crypto_type.get_keysize();
+    strlcpy((char*)ext_crypt_ftr.crypto_type_name, crypto_type.get_kernel_name(),
             MAX_CRYPTO_TYPE_NAME_LEN);
     uint32_t flags = 0;
     if (fscrypt_is_native() &&
         android::base::GetBoolProperty("ro.crypto.allow_encrypt_override", false))
         flags |= CREATE_CRYPTO_BLK_DEV_FLAGS_ALLOW_ENCRYPT_OVERRIDE;
 
-    return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev, out_crypto_blkdev, label, flags);
-}
-
-/*
- * Called by vold when it's asked to unmount an encrypted external
- * storage volume.
- */
-int cryptfs_revert_ext_volume(const char* label) {
-    return delete_crypto_blk_dev((char*)label);
+    return create_crypto_blk_dev(&ext_crypt_ftr, reinterpret_cast<const unsigned char*>(key.data()),
+                                 real_blkdev, out_crypto_blkdev, label, flags);
 }
 
 int cryptfs_crypto_complete(void) {
@@ -1970,7 +2012,7 @@
 }
 
 /* Initialize a crypt_mnt_ftr structure.  The keysize is
- * defaulted to cryptfs_get_keysize() bytes, and the filesystem size to 0.
+ * defaulted to get_crypto_type().get_keysize() bytes, and the filesystem size to 0.
  * Presumably, at a minimum, the caller will update the
  * filesystem size and crypto_type_name after calling this function.
  */
@@ -1982,7 +2024,7 @@
     ftr->major_version = CURRENT_MAJOR_VERSION;
     ftr->minor_version = CURRENT_MINOR_VERSION;
     ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
-    ftr->keysize = cryptfs_get_keysize();
+    ftr->keysize = get_crypto_type().get_keysize();
 
     switch (keymaster_check_compatibility()) {
         case 1:
@@ -2036,8 +2078,8 @@
     return 0;
 }
 
-static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, char* crypto_blkdev,
-                                      char* real_blkdev, int previously_encrypted_upto) {
+static int cryptfs_enable_all_volumes(struct crypt_mnt_ftr* crypt_ftr, const char* crypto_blkdev,
+                                      const char* real_blkdev, int previously_encrypted_upto) {
     off64_t cur_encryption_done = 0, tot_encryption_size = 0;
     int rc = -1;
 
@@ -2072,18 +2114,20 @@
 }
 
 int cryptfs_enable_internal(int crypt_type, const char* passwd, int no_ui) {
-    char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN];
+    std::string crypto_blkdev;
+    std::string real_blkdev;
     unsigned char decrypted_master_key[MAX_KEY_LEN];
     int rc = -1, i;
     struct crypt_mnt_ftr crypt_ftr;
     struct crypt_persist_data* pdata;
     char encrypted_state[PROPERTY_VALUE_MAX];
     char lockid[32] = {0};
-    char key_loc[PROPERTY_VALUE_MAX];
+    std::string key_loc;
     int num_vols;
     off64_t previously_encrypted_upto = 0;
     bool rebootEncryption = false;
     bool onlyCreateHeader = false;
+    std::unique_ptr<android::wakelock::WakeLock> wakeLock = nullptr;
 
     if (get_crypt_ftr_and_key(&crypt_ftr) == 0) {
         if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
@@ -2122,22 +2166,20 @@
         goto error_unencrypted;
     }
 
-    // TODO refactor fs_mgr_get_crypt_info to get both in one call
-    fs_mgr_get_crypt_info(fstab_default, key_loc, 0, sizeof(key_loc));
-    fs_mgr_get_crypt_info(fstab_default, 0, real_blkdev, sizeof(real_blkdev));
+    get_crypt_info(&key_loc, &real_blkdev);
 
     /* Get the size of the real block device */
     uint64_t nr_sec;
     if (android::vold::GetBlockDev512Sectors(real_blkdev, &nr_sec) != android::OK) {
-        SLOGE("Cannot get size of block device %s\n", real_blkdev);
+        SLOGE("Cannot get size of block device %s\n", real_blkdev.c_str());
         goto error_unencrypted;
     }
 
     /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
-    if (!strcmp(key_loc, KEY_IN_FOOTER)) {
+    if (key_loc == KEY_IN_FOOTER) {
         uint64_t fs_size_sec, max_fs_size_sec;
-        fs_size_sec = get_fs_size(real_blkdev);
-        if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev);
+        fs_size_sec = get_fs_size(real_blkdev.c_str());
+        if (fs_size_sec == 0) fs_size_sec = get_f2fs_filesystem_size_sec(real_blkdev.data());
 
         max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
 
@@ -2152,7 +2194,7 @@
      * wants to keep the screen on, it can grab a full wakelock.
      */
     snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int)getpid());
-    acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
+    wakeLock = std::make_unique<android::wakelock::WakeLock>(lockid);
 
     /* The init files are setup to stop the class main and late start when
      * vold sets trigger_shutdown_framework.
@@ -2185,6 +2227,7 @@
          * /data, set a property saying we're doing inplace encryption,
          * and restart the framework.
          */
+        wait_and_unmount(DATA_MNT_POINT, true);
         if (fs_mgr_do_tmpfs_mount(DATA_MNT_POINT)) {
             goto error_shutting_down;
         }
@@ -2210,7 +2253,7 @@
             goto error_shutting_down;
         }
 
-        if (!strcmp(key_loc, KEY_IN_FOOTER)) {
+        if (key_loc == KEY_IN_FOOTER) {
             crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / CRYPT_SECTOR_SIZE);
         } else {
             crypt_ftr.fs_size = nr_sec;
@@ -2225,7 +2268,7 @@
             crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
         }
         crypt_ftr.crypt_type = crypt_type;
-        strlcpy((char*)crypt_ftr.crypto_type_name, cryptfs_get_crypto_name(),
+        strlcpy((char*)crypt_ftr.crypto_type_name, get_crypto_type().get_kernel_name(),
                 MAX_CRYPTO_TYPE_NAME_LEN);
 
         /* Make an encrypted master key */
@@ -2280,14 +2323,14 @@
     }
 
     decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
-    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
+    create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev.c_str(), &crypto_blkdev,
                           CRYPTO_BLOCK_DEVICE, 0);
 
     /* If we are continuing, check checksums match */
     rc = 0;
     if (previously_encrypted_upto) {
         __le8 hash_first_block[SHA256_DIGEST_LENGTH];
-        rc = cryptfs_SHA256_fileblock(crypto_blkdev, hash_first_block);
+        rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), hash_first_block);
 
         if (!rc &&
             memcmp(hash_first_block, crypt_ftr.hash_first_block, sizeof(hash_first_block)) != 0) {
@@ -2297,13 +2340,13 @@
     }
 
     if (!rc) {
-        rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev, real_blkdev,
+        rc = cryptfs_enable_all_volumes(&crypt_ftr, crypto_blkdev.c_str(), real_blkdev.data(),
                                         previously_encrypted_upto);
     }
 
     /* Calculate checksum if we are not finished */
     if (!rc && crypt_ftr.encrypted_upto != crypt_ftr.fs_size) {
-        rc = cryptfs_SHA256_fileblock(crypto_blkdev, crypt_ftr.hash_first_block);
+        rc = cryptfs_SHA256_fileblock(crypto_blkdev.c_str(), crypt_ftr.hash_first_block);
         if (rc) {
             SLOGE("Error calculating checksum for continuing encryption");
             rc = -1;
@@ -2332,7 +2375,7 @@
                 /* default encryption - continue first boot sequence */
                 property_set("ro.crypto.state", "encrypted");
                 property_set("ro.crypto.type", "block");
-                release_wake_lock(lockid);
+                wakeLock.reset(nullptr);
                 if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
                     // Bring up cryptkeeper that will check the password and set it
                     property_set("vold.decrypt", "trigger_shutdown_framework");
@@ -2369,7 +2412,6 @@
         } else {
             /* set property to trigger dialog */
             property_set("vold.encrypt_progress", "error_partially_encrypted");
-            release_wake_lock(lockid);
         }
         return -1;
     }
@@ -2379,14 +2421,10 @@
      * Set the property and return.  Hope the framework can deal with it.
      */
     property_set("vold.encrypt_progress", "error_reboot_failed");
-    release_wake_lock(lockid);
     return rc;
 
 error_unencrypted:
     property_set("vold.encrypt_progress", "error_not_encrypted");
-    if (lockid[0]) {
-        release_wake_lock(lockid);
-    }
     return -1;
 
 error_shutting_down:
@@ -2401,9 +2439,6 @@
 
     /* shouldn't get here */
     property_set("vold.encrypt_progress", "error_shutting_down");
-    if (lockid[0]) {
-        release_wake_lock(lockid);
-    }
     return -1;
 }
 
@@ -2458,24 +2493,25 @@
 static unsigned int persist_get_max_entries(int encrypted) {
     struct crypt_mnt_ftr crypt_ftr;
     unsigned int dsize;
-    unsigned int max_persistent_entries;
 
     /* If encrypted, use the values from the crypt_ftr, otherwise
      * use the values for the current spec.
      */
     if (encrypted) {
         if (get_crypt_ftr_and_key(&crypt_ftr)) {
-            return -1;
+            /* Something is wrong, assume no space for entries */
+            return 0;
         }
         dsize = crypt_ftr.persist_data_size;
     } else {
         dsize = CRYPT_PERSIST_DATA_SIZE;
     }
 
-    max_persistent_entries =
-        (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
-
-    return max_persistent_entries;
+    if (dsize > sizeof(struct crypt_persist_data)) {
+        return (dsize - sizeof(struct crypt_persist_data)) / sizeof(struct crypt_persist_entry);
+    } else {
+        return 0;
+    }
 }
 
 static int persist_get_key(const char* fieldname, char* value) {
@@ -2842,6 +2878,6 @@
 }
 
 int cryptfs_isConvertibleToFBE() {
-    struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab_default, DATA_MNT_POINT);
-    return (rec && fs_mgr_is_convertible_to_fbe(rec)) ? 1 : 0;
+    auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
+    return entry && entry->fs_mgr_flags.force_fde_or_fbe;
 }
diff --git a/cryptfs.h b/cryptfs.h
index 692d7ee..872806e 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -17,17 +17,7 @@
 #ifndef ANDROID_VOLD_CRYPTFS_H
 #define ANDROID_VOLD_CRYPTFS_H
 
-/* This structure starts 16,384 bytes before the end of a hardware
- * partition that is encrypted, or in a separate partition.  It's location
- * is specified by a property set in init.<device>.rc.
- * The structure allocates 48 bytes for a key, but the real key size is
- * specified in the struct.  Currently, the code is hardcoded to use 128
- * bit keys.
- * The fields after salt are only valid in rev 1.1 and later stuctures.
- * Obviously, the filesystem does not include the last 16 kbytes
- * of the partition if the crypt_mnt_ftr lives at the end of the
- * partition.
- */
+#include <string>
 
 #include <linux/types.h>
 #include <stdbool.h>
@@ -35,171 +25,10 @@
 
 #include <cutils/properties.h>
 
-/* The current cryptfs version */
-#define CURRENT_MAJOR_VERSION 1
-#define CURRENT_MINOR_VERSION 3
+#include "KeyBuffer.h"
+#include "KeyUtil.h"
 
 #define CRYPT_FOOTER_OFFSET 0x4000
-#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
-#define CRYPT_PERSIST_DATA_SIZE 0x1000
-
-#define MAX_CRYPTO_TYPE_NAME_LEN 64
-
-#define MAX_KEY_LEN 48
-#define SALT_LEN 16
-#define SCRYPT_LEN 32
-
-/* definitions of flags in the structure below */
-#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
-#define CRYPT_ENCRYPTION_IN_PROGRESS       \
-    0x2 /* Encryption partially completed, \
-           encrypted_upto valid*/
-#define CRYPT_INCONSISTENT_STATE                    \
-    0x4 /* Set when starting encryption, clear when \
-           exit cleanly, either through success or  \
-           correctly marked partial encryption */
-#define CRYPT_DATA_CORRUPT                      \
-    0x8 /* Set when encryption is fine, but the \
-           underlying volume is corrupt */
-#define CRYPT_FORCE_ENCRYPTION                        \
-    0x10 /* Set when it is time to encrypt this       \
-            volume on boot. Everything in this        \
-            structure is set up correctly as          \
-            though device is encrypted except         \
-            that the master key is encrypted with the \
-            default password. */
-#define CRYPT_FORCE_COMPLETE                           \
-    0x20 /* Set when the above encryption cycle is     \
-            complete. On next cryptkeeper entry, match \
-            the password. If it matches fix the master \
-            key and remove this flag. */
-
-/* Allowed values for type in the structure below */
-#define CRYPT_TYPE_PASSWORD                       \
-    0 /* master_key is encrypted with a password  \
-       * Must be zero to be compatible with pre-L \
-       * devices where type is always password.*/
-#define CRYPT_TYPE_DEFAULT                                           \
-    1                        /* master_key is encrypted with default \
-                              * password */
-#define CRYPT_TYPE_PATTERN 2 /* master_key is encrypted with a pattern */
-#define CRYPT_TYPE_PIN 3     /* master_key is encrypted with a pin */
-#define CRYPT_TYPE_MAX_TYPE 3 /* type cannot be larger than this value */
-
-#define CRYPT_MNT_MAGIC 0xD0B5B1C4
-#define PERSIST_DATA_MAGIC 0xE950CD44
-
-/* Key Derivation Function algorithms */
-#define KDF_PBKDF2 1
-#define KDF_SCRYPT 2
-/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
-#define KDF_SCRYPT_KEYMASTER 5
-
-/* Maximum allowed keymaster blob size. */
-#define KEYMASTER_BLOB_SIZE 2048
-
-/* __le32 and __le16 defined in system/extras/ext4_utils/ext4_utils.h */
-#define __le8 unsigned char
-
-#if !defined(SHA256_DIGEST_LENGTH)
-#define SHA256_DIGEST_LENGTH 32
-#endif
-
-struct crypt_mnt_ftr {
-    __le32 magic; /* See above */
-    __le16 major_version;
-    __le16 minor_version;
-    __le32 ftr_size;             /* in bytes, not including key following */
-    __le32 flags;                /* See above */
-    __le32 keysize;              /* in bytes */
-    __le32 crypt_type;           /* how master_key is encrypted. Must be a
-                                  * CRYPT_TYPE_XXX value */
-    __le64 fs_size;              /* Size of the encrypted fs, in 512 byte sectors */
-    __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
-                                    mount, set to 0 on successful mount */
-    unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
-                                                                 needed to decrypt this
-                                                                 partition, null terminated */
-    __le32 spare2;                                            /* ignored */
-    unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
-    unsigned char salt[SALT_LEN];          /* The salt used for this encryption */
-    __le64 persist_data_offset[2];         /* Absolute offset to both copies of crypt_persist_data
-                                            * on device with that info, either the footer of the
-                                            * real_blkdevice or the metadata partition. */
-
-    __le32 persist_data_size; /* The number of bytes allocated to each copy of the
-                               * persistent data table*/
-
-    __le8 kdf_type; /* The key derivation function used. */
-
-    /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
-    __le8 N_factor;        /* (1 << N) */
-    __le8 r_factor;        /* (1 << r) */
-    __le8 p_factor;        /* (1 << p) */
-    __le64 encrypted_upto; /* If we are in state CRYPT_ENCRYPTION_IN_PROGRESS and
-                              we have to stop (e.g. power low) this is the last
-                              encrypted 512 byte sector.*/
-    __le8 hash_first_block[SHA256_DIGEST_LENGTH]; /* When CRYPT_ENCRYPTION_IN_PROGRESS
-                                                     set, hash of first block, used
-                                                     to validate before continuing*/
-
-    /* key_master key, used to sign the derived key which is then used to generate
-     * the intermediate key
-     * This key should be used for no other purposes! We use this key to sign unpadded
-     * data, which is acceptable but only if the key is not reused elsewhere. */
-    __le8 keymaster_blob[KEYMASTER_BLOB_SIZE];
-    __le32 keymaster_blob_size;
-
-    /* Store scrypt of salted intermediate key. When decryption fails, we can
-       check if this matches, and if it does, we know that the problem is with the
-       drive, and there is no point in asking the user for more passwords.
-
-       Note that if any part of this structure is corrupt, this will not match and
-       we will continue to believe the user entered the wrong password. In that
-       case the only solution is for the user to enter a password enough times to
-       force a wipe.
-
-       Note also that there is no need to worry about migration. If this data is
-       wrong, we simply won't recognise a right password, and will continue to
-       prompt. On the first password change, this value will be populated and
-       then we will be OK.
-     */
-    unsigned char scrypted_intermediate_key[SCRYPT_LEN];
-
-    /* sha of this structure with this element set to zero
-       Used when encrypting on reboot to validate structure before doing something
-       fatal
-     */
-    unsigned char sha256[SHA256_DIGEST_LENGTH];
-};
-
-/* Persistant data that should be available before decryption.
- * Things like airplane mode, locale and timezone are kept
- * here and can be retrieved by the CryptKeeper UI to properly
- * configure the phone before asking for the password
- * This is only valid if the major and minor version above
- * is set to 1.1 or higher.
- *
- * This is a 4K structure.  There are 2 copies, and the code alternates
- * writing one and then clearing the previous one.  The reading
- * code reads the first valid copy it finds, based on the magic number.
- * The absolute offset to the first of the two copies is kept in rev 1.1
- * and higher crypt_mnt_ftr structures.
- */
-struct crypt_persist_entry {
-    char key[PROPERTY_KEY_MAX];
-    char val[PROPERTY_VALUE_MAX];
-};
-
-/* Should be exactly 4K in size */
-struct crypt_persist_data {
-    __le32 persist_magic;
-    __le32 persist_valid_entries;
-    __le32 persist_spare[30];
-    struct crypt_persist_entry persist_entry[0];
-};
-
-#define DATA_MNT_POINT "/data"
 
 /* Return values for cryptfs_crypto_complete */
 #define CRYPTO_COMPLETE_NOT_ENCRYPTED 1
@@ -209,11 +38,6 @@
 #define CRYPTO_COMPLETE_INCONSISTENT (-3)
 #define CRYPTO_COMPLETE_CORRUPT (-4)
 
-/* Return values for cryptfs_enable_inplace*() */
-#define ENABLE_INPLACE_OK 0
-#define ENABLE_INPLACE_ERR_OTHER (-1)
-#define ENABLE_INPLACE_ERR_DEV (-2) /* crypto_blkdev issue */
-
 /* Return values for cryptfs_getfield */
 #define CRYPTO_GETFIELD_OK 0
 #define CRYPTO_GETFIELD_ERROR_NO_FIELD (-1)
@@ -231,11 +55,8 @@
 #define PERSIST_DEL_KEY_ERROR_OTHER (-1)
 #define PERSIST_DEL_KEY_ERROR_NO_FIELD (-2)
 
+// Exposed for testing only
 int match_multi_entry(const char* key, const char* field, unsigned index);
-int wait_and_unmount(const char* mountpoint, bool kill);
-
-typedef int (*kdf_func)(const char* passwd, const unsigned char* salt, unsigned char* ikey,
-                        void* params);
 
 int cryptfs_crypto_complete(void);
 int cryptfs_check_passwd(const char* pw);
@@ -244,9 +65,8 @@
 int cryptfs_enable(int type, const char* passwd, int no_ui);
 int cryptfs_changepw(int type, const char* newpw);
 int cryptfs_enable_default(int no_ui);
-int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev, const unsigned char* key,
-                             char* out_crypto_blkdev);
-int cryptfs_revert_ext_volume(const char* label);
+int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
+                             const android::vold::KeyBuffer& key, std::string* out_crypto_blkdev);
 int cryptfs_getfield(const char* fieldname, char* value, int len);
 int cryptfs_setfield(const char* fieldname, const char* value);
 int cryptfs_mount_default_encrypted(void);
@@ -254,8 +74,6 @@
 const char* cryptfs_get_password(void);
 void cryptfs_clear_password(void);
 int cryptfs_isConvertibleToFBE(void);
-
-uint32_t cryptfs_get_keysize();
-const char* cryptfs_get_crypto_name();
+const android::vold::KeyGeneration cryptfs_get_keygen();
 
 #endif /* ANDROID_VOLD_CRYPTFS_H */
diff --git a/fs/Exfat.cpp b/fs/Exfat.cpp
index 5c15075..34f1024 100644
--- a/fs/Exfat.cpp
+++ b/fs/Exfat.cpp
@@ -41,9 +41,10 @@
 status_t Check(const std::string& source) {
     std::vector<std::string> cmd;
     cmd.push_back(kFsckPath);
+    cmd.push_back("-a");
     cmd.push_back(source);
 
-    int rc = ForkExecvp(cmd, sFsckUntrustedContext);
+    int rc = ForkExecvp(cmd, nullptr, sFsckUntrustedContext);
     if (rc == 0) {
         LOG(INFO) << "Check OK";
         return 0;
diff --git a/fs/Ext4.cpp b/fs/Ext4.cpp
index 806cfd1..6bc7ad2 100644
--- a/fs/Ext4.cpp
+++ b/fs/Ext4.cpp
@@ -117,7 +117,7 @@
         cmd.push_back(c_source);
 
         // ext4 devices are currently always trusted
-        return ForkExecvp(cmd, sFsckContext);
+        return ForkExecvp(cmd, nullptr, sFsckContext);
     }
 
     return 0;
@@ -171,6 +171,15 @@
     cmd.push_back("-M");
     cmd.push_back(target);
 
+    bool needs_casefold =
+            android::base::GetBoolProperty("external_storage.casefold.enabled", false);
+    bool needs_projid = android::base::GetBoolProperty("external_storage.projid.enabled", false);
+
+    if (needs_projid) {
+        cmd.push_back("-I");
+        cmd.push_back("512");
+    }
+
     std::string options("has_journal");
     if (android::base::GetBoolProperty("vold.has_quota", false)) {
         options += ",quota";
@@ -178,10 +187,21 @@
     if (fscrypt_is_native()) {
         options += ",encrypt";
     }
+    if (needs_casefold) {
+        options += ",casefold";
+    }
 
     cmd.push_back("-O");
     cmd.push_back(options);
 
+    if (needs_casefold || needs_projid) {
+        cmd.push_back("-E");
+        std::string extopts = "";
+        if (needs_casefold) extopts += "encoding=utf8,";
+        if (needs_projid) extopts += "quotatype=prjquota,";
+        cmd.push_back(extopts);
+    }
+
     cmd.push_back(source);
 
     if (numSectors) {
diff --git a/fs/F2fs.cpp b/fs/F2fs.cpp
index c6e0f52..a615082 100644
--- a/fs/F2fs.cpp
+++ b/fs/F2fs.cpp
@@ -48,7 +48,7 @@
     cmd.push_back(source);
 
     // f2fs devices are currently always trusted
-    return ForkExecvp(cmd, sFsckContext);
+    return ForkExecvp(cmd, nullptr, sFsckContext);
 }
 
 status_t Mount(const std::string& source, const std::string& target) {
@@ -85,7 +85,12 @@
         cmd.push_back("-O");
         cmd.push_back("encrypt");
     }
-
+    if (android::base::GetBoolProperty("vold.has_compress", false)) {
+        cmd.push_back("-O");
+        cmd.push_back("compression");
+        cmd.push_back("-O");
+        cmd.push_back("extra_attr");
+    }
     cmd.push_back("-O");
     cmd.push_back("verity");
 
diff --git a/fs/Vfat.cpp b/fs/Vfat.cpp
index 7b833d1..4f1e982 100644
--- a/fs/Vfat.cpp
+++ b/fs/Vfat.cpp
@@ -64,10 +64,11 @@
         cmd.push_back(kFsckPath);
         cmd.push_back("-p");
         cmd.push_back("-f");
+        cmd.push_back("-y");
         cmd.push_back(source);
 
         // Fat devices are currently always untrusted
-        rc = ForkExecvp(cmd, sFsckUntrustedContext);
+        rc = ForkExecvp(cmd, nullptr, sFsckUntrustedContext);
 
         if (rc < 0) {
             LOG(ERROR) << "Filesystem check failed due to logwrap error";
diff --git a/fscrypt_uapi.h b/fscrypt_uapi.h
new file mode 100644
index 0000000..3cda96e
--- /dev/null
+++ b/fscrypt_uapi.h
@@ -0,0 +1,27 @@
+#ifndef _UAPI_LINUX_FSCRYPT_VOLD_H
+#define _UAPI_LINUX_FSCRYPT_VOLD_H
+
+#include <linux/fscrypt.h>
+#include <linux/types.h>
+
+#define FSCRYPT_ADD_KEY_FLAG_WRAPPED 0x01
+
+struct sys_fscrypt_add_key_arg {
+    struct fscrypt_key_specifier key_spec;
+    __u32 raw_size;
+    __u32 key_id;
+    __u32 __reserved[7];
+    __u32 flags;
+    __u8 raw[];
+};
+
+struct sys_fscrypt_provisioning_key_payload {
+    __u32 type;
+    __u32 __reserved;
+    __u8 raw[];
+};
+
+#define fscrypt_add_key_arg sys_fscrypt_add_key_arg
+#define fscrypt_provisioning_key_payload sys_fscrypt_provisioning_key_payload
+
+#endif  //_UAPI_LINUX_FSCRYPT_VOLD_H
diff --git a/hash.h b/hash.h
deleted file mode 100644
index cd81805..0000000
--- a/hash.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 1999 Kungliga Tekniska Högskolan
- * (Royal Institute of Technology, Stockholm, Sweden).
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * 3. Neither the name of KTH nor the names of its contributors may be
- *    used to endorse or promote products derived from this software without
- *    specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY KTH AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KTH OR ITS CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
- * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
-
-/* $Heimdal: hash.h,v 1.1 1999/03/22 19:16:25 joda Exp $
-   $NetBSD: hash.h,v 1.1.1.3 2002/09/12 12:41:42 joda Exp $ */
-
-/* stuff in common between md4, md5, and sha1 */
-
-#ifndef __hash_h__
-#define __hash_h__
-
-#include <stdlib.h>
-#include <string.h>
-
-#ifndef min
-#define min(a, b) (((a) > (b)) ? (b) : (a))
-#endif
-
-/* Vector Crays doesn't have a good 32-bit type, or more precisely,
-   int32_t as defined by <bind/bitypes.h> isn't 32 bits, and we don't
-   want to depend in being able to redefine this type.  To cope with
-   this we have to clamp the result in some places to [0,2^32); no
-   need to do this on other machines.  Did I say this was a mess?
-   */
-
-#ifdef _CRAY
-#define CRAYFIX(X) ((X)&0xffffffff)
-#else
-#define CRAYFIX(X) (X)
-#endif
-
-static inline u_int32_t cshift(u_int32_t x, unsigned int n) {
-    x = CRAYFIX(x);
-    return CRAYFIX((x << n) | (x >> (32 - n)));
-}
-
-#endif /* __hash_h__ */
diff --git a/main.cpp b/main.cpp
index e1f8404..1f85fb5 100644
--- a/main.cpp
+++ b/main.cpp
@@ -20,7 +20,6 @@
 #include "VoldNativeService.h"
 #include "VoldUtil.h"
 #include "VolumeManager.h"
-#include "cryptfs.h"
 #include "model/Disk.h"
 #include "sehandle.h"
 
@@ -42,18 +41,25 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 
-static int process_config(VolumeManager* vm, bool* has_adoptable, bool* has_quota,
-                          bool* has_reserved);
+typedef struct vold_configs {
+    bool has_adoptable : 1;
+    bool has_quota : 1;
+    bool has_reserved : 1;
+    bool has_compress : 1;
+} VoldConfigs;
+
+static int process_config(VolumeManager* vm, VoldConfigs* configs);
 static void coldboot(const char* path);
 static void parse_args(int argc, char** argv);
 
 struct selabel_handle* sehandle;
 
 using android::base::StringPrintf;
+using android::fs_mgr::ReadDefaultFstab;
 
 int main(int argc, char** argv) {
     atrace_set_tracing_enabled(false);
-    setenv("ANDROID_LOG_TAGS", "*:d", 1);
+    setenv("ANDROID_LOG_TAGS", "*:d", 1);  // Do not submit with verbose logs enabled
     android::base::InitLogging(argv, android::base::LogdLogger(android::base::SYSTEM));
 
     LOG(INFO) << "Vold 3.0 (the awakening) firing up";
@@ -100,11 +106,8 @@
         exit(1);
     }
 
-    bool has_adoptable;
-    bool has_quota;
-    bool has_reserved;
-
-    if (process_config(vm, &has_adoptable, &has_quota, &has_reserved)) {
+    VoldConfigs configs = {};
+    if (process_config(vm, &configs)) {
         PLOG(ERROR) << "Error reading configuration... continuing anyways";
     }
 
@@ -128,9 +131,10 @@
 
     // This call should go after listeners are started to avoid
     // a deadlock between vold and init (see b/34278978 for details)
-    android::base::SetProperty("vold.has_adoptable", has_adoptable ? "1" : "0");
-    android::base::SetProperty("vold.has_quota", has_quota ? "1" : "0");
-    android::base::SetProperty("vold.has_reserved", has_reserved ? "1" : "0");
+    android::base::SetProperty("vold.has_adoptable", configs.has_adoptable ? "1" : "0");
+    android::base::SetProperty("vold.has_quota", configs.has_quota ? "1" : "0");
+    android::base::SetProperty("vold.has_reserved", configs.has_reserved ? "1" : "0");
+    android::base::SetProperty("vold.has_compress", configs.has_compress ? "1" : "0");
 
     // Do coldboot here so it won't block booting,
     // also the cold boot is needed in case we have flash drive
@@ -151,6 +155,7 @@
         {"blkid_untrusted_context", required_argument, 0, 'B'},
         {"fsck_context", required_argument, 0, 'f'},
         {"fsck_untrusted_context", required_argument, 0, 'F'},
+        {nullptr, 0, nullptr, 0},
     };
 
     int c;
@@ -212,44 +217,51 @@
     }
 }
 
-static int process_config(VolumeManager* vm, bool* has_adoptable, bool* has_quota,
-                          bool* has_reserved) {
+static int process_config(VolumeManager* vm, VoldConfigs* configs) {
     ATRACE_NAME("process_config");
 
-    fstab_default = fs_mgr_read_fstab_default();
-    if (!fstab_default) {
+    if (!ReadDefaultFstab(&fstab_default)) {
         PLOG(ERROR) << "Failed to open default fstab";
         return -1;
     }
 
     /* Loop through entries looking for ones that vold manages */
-    *has_adoptable = false;
-    *has_quota = false;
-    *has_reserved = false;
-    for (int i = 0; i < fstab_default->num_entries; i++) {
-        auto rec = &fstab_default->recs[i];
-        if (fs_mgr_is_quota(rec)) {
-            *has_quota = true;
+    configs->has_adoptable = false;
+    configs->has_quota = false;
+    configs->has_reserved = false;
+    configs->has_compress = false;
+    for (auto& entry : fstab_default) {
+        if (entry.fs_mgr_flags.quota) {
+            configs->has_quota = true;
         }
-        if (rec->reserved_size > 0) {
-            *has_reserved = true;
+        if (entry.reserved_size > 0) {
+            configs->has_reserved = true;
+        }
+        if (entry.fs_mgr_flags.fs_compress) {
+            configs->has_compress = true;
         }
 
-        if (fs_mgr_is_voldmanaged(rec)) {
-            if (fs_mgr_is_nonremovable(rec)) {
+        /* Make sure logical partitions have an updated blk_device. */
+        if (entry.fs_mgr_flags.logical && !fs_mgr_update_logical_partition(&entry) &&
+            !entry.fs_mgr_flags.no_fail) {
+            PLOG(FATAL) << "could not find logical partition " << entry.blk_device;
+        }
+
+        if (entry.fs_mgr_flags.vold_managed) {
+            if (entry.fs_mgr_flags.nonremovable) {
                 LOG(WARNING) << "nonremovable no longer supported; ignoring volume";
                 continue;
             }
 
-            std::string sysPattern(rec->blk_device);
-            std::string nickname(rec->label);
+            std::string sysPattern(entry.blk_device);
+            std::string nickname(entry.label);
             int flags = 0;
 
-            if (fs_mgr_is_encryptable(rec)) {
+            if (entry.is_encryptable()) {
                 flags |= android::vold::Disk::Flags::kAdoptable;
-                *has_adoptable = true;
+                configs->has_adoptable = true;
             }
-            if (fs_mgr_is_noemulatedsd(rec) ||
+            if (entry.fs_mgr_flags.no_emulated_sd ||
                 android::base::GetBoolProperty("vold.debug.default_primary", false)) {
                 flags |= android::vold::Disk::Flags::kDefaultPrimary;
             }
diff --git a/model/Disk.cpp b/model/Disk.cpp
index 3d25e4c..6a6585e 100644
--- a/model/Disk.cpp
+++ b/model/Disk.cpp
@@ -20,6 +20,7 @@
 #include "PublicVolume.h"
 #include "Utils.h"
 #include "VolumeBase.h"
+#include "VolumeEncryption.h"
 #include "VolumeManager.h"
 
 #include <android-base/file.h>
@@ -30,8 +31,6 @@
 #include <android-base/strings.h>
 #include <fscrypt/fscrypt.h>
 
-#include "cryptfs.h"
-
 #include <fcntl.h>
 #include <inttypes.h>
 #include <stdio.h>
@@ -153,7 +152,7 @@
     return nullptr;
 }
 
-void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) {
+void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) const {
     for (const auto& vol : mVolumes) {
         if (vol->getType() == type) {
             list.push_back(vol->getId());
@@ -216,7 +215,8 @@
 
     LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
 
-    auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
+    auto keyBuffer = KeyBuffer(keyRaw.begin(), keyRaw.end());
+    auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyBuffer));
     if (mJustPartitioned) {
         LOG(DEBUG) << "Device just partitioned; silently formatting";
         vol->setSilent(true);
@@ -341,7 +341,7 @@
     cmd.push_back(mDevPath);
 
     std::vector<std::string> output;
-    status_t res = ForkExecvp(cmd, output);
+    status_t res = ForkExecvp(cmd, &output);
     if (res != OK) {
         LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
 
@@ -504,11 +504,12 @@
         return -EIO;
     }
 
-    std::string keyRaw;
-    if (ReadRandomBytes(cryptfs_get_keysize(), keyRaw) != OK) {
+    KeyBuffer key;
+    if (!generate_volume_key(&key)) {
         LOG(ERROR) << "Failed to generate key";
         return -EIO;
     }
+    std::string keyRaw(key.begin(), key.end());
 
     std::string partGuid;
     StrToHex(partGuidRaw, partGuid);
diff --git a/model/Disk.h b/model/Disk.h
index 3140144..889e906 100644
--- a/model/Disk.h
+++ b/model/Disk.h
@@ -54,18 +54,18 @@
         kEmmc = 1 << 4,
     };
 
-    const std::string& getId() { return mId; }
-    const std::string& getEventPath() { return mEventPath; }
-    const std::string& getSysPath() { return mSysPath; }
-    const std::string& getDevPath() { return mDevPath; }
-    dev_t getDevice() { return mDevice; }
-    uint64_t getSize() { return mSize; }
-    const std::string& getLabel() { return mLabel; }
-    int getFlags() { return mFlags; }
+    const std::string& getId() const { return mId; }
+    const std::string& getEventPath() const { return mEventPath; }
+    const std::string& getSysPath() const { return mSysPath; }
+    const std::string& getDevPath() const { return mDevPath; }
+    dev_t getDevice() const { return mDevice; }
+    uint64_t getSize() const { return mSize; }
+    const std::string& getLabel() const { return mLabel; }
+    int getFlags() const { return mFlags; }
 
     std::shared_ptr<VolumeBase> findVolume(const std::string& id);
 
-    void listVolumes(VolumeBase::Type type, std::list<std::string>& list);
+    void listVolumes(VolumeBase::Type type, std::list<std::string>& list) const;
 
     status_t create();
     status_t destroy();
diff --git a/model/EmulatedVolume.cpp b/model/EmulatedVolume.cpp
index 8d9ac74..552fe2f 100644
--- a/model/EmulatedVolume.cpp
+++ b/model/EmulatedVolume.cpp
@@ -16,9 +16,10 @@
 
 #include "EmulatedVolume.h"
 #include "Utils.h"
+#include "VolumeManager.h"
 
-#include <android-base/stringprintf.h>
 #include <android-base/logging.h>
+#include <android-base/stringprintf.h>
 #include <cutils/fs.h>
 #include <private/android_filesystem_config.h>
 #include <utils/Timers.h>
@@ -65,18 +66,20 @@
     mFuseDefault = StringPrintf("/mnt/runtime/default/%s", label.c_str());
     mFuseRead = StringPrintf("/mnt/runtime/read/%s", label.c_str());
     mFuseWrite = StringPrintf("/mnt/runtime/write/%s", label.c_str());
+    mFuseFull = StringPrintf("/mnt/runtime/full/%s", label.c_str());
 
     setInternalPath(mRawPath);
     setPath(StringPrintf("/storage/%s", label.c_str()));
 
     if (fs_prepare_dir(mFuseDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
         fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
-        fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT)) {
+        fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT) ||
+        fs_prepare_dir(mFuseFull.c_str(), 0700, AID_ROOT, AID_ROOT)) {
         PLOG(ERROR) << getId() << " failed to create mount points";
         return -errno;
     }
 
-    dev_t before = GetDevice(mFuseWrite);
+    dev_t before = GetDevice(mFuseFull);
 
     if (!(mFusePid = fork())) {
         // clang-format off
@@ -87,6 +90,7 @@
                 "-w",
                 "-G",
                 "-i",
+                "-o",
                 mRawPath.c_str(),
                 label.c_str(),
                 NULL)) {
@@ -104,7 +108,7 @@
     }
 
     nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
-    while (before == GetDevice(mFuseWrite)) {
+    while (before == GetDevice(mFuseFull)) {
         LOG(DEBUG) << "Waiting for FUSE to spin up...";
         usleep(50000);  // 50ms
 
@@ -130,14 +134,17 @@
     ForceUnmount(mFuseDefault);
     ForceUnmount(mFuseRead);
     ForceUnmount(mFuseWrite);
+    ForceUnmount(mFuseFull);
 
     rmdir(mFuseDefault.c_str());
     rmdir(mFuseRead.c_str());
     rmdir(mFuseWrite.c_str());
+    rmdir(mFuseFull.c_str());
 
     mFuseDefault.clear();
     mFuseRead.clear();
     mFuseWrite.clear();
+    mFuseFull.clear();
 
     return OK;
 }
diff --git a/model/EmulatedVolume.h b/model/EmulatedVolume.h
index f618c55..fddfe4e 100644
--- a/model/EmulatedVolume.h
+++ b/model/EmulatedVolume.h
@@ -52,6 +52,7 @@
     std::string mFuseDefault;
     std::string mFuseRead;
     std::string mFuseWrite;
+    std::string mFuseFull;
 
     /* PID of FUSE wrapper */
     pid_t mFusePid;
diff --git a/model/PrivateVolume.cpp b/model/PrivateVolume.cpp
index de2a09f..fd3daea 100644
--- a/model/PrivateVolume.cpp
+++ b/model/PrivateVolume.cpp
@@ -17,14 +17,15 @@
 #include "PrivateVolume.h"
 #include "EmulatedVolume.h"
 #include "Utils.h"
+#include "VolumeEncryption.h"
 #include "VolumeManager.h"
-#include "cryptfs.h"
 #include "fs/Ext4.h"
 #include "fs/F2fs.h"
 
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <cutils/fs.h>
+#include <libdm/dm.h>
 #include <private/android_filesystem_config.h>
 
 #include <fcntl.h>
@@ -43,7 +44,7 @@
 
 static const unsigned int kMajorBlockMmc = 179;
 
-PrivateVolume::PrivateVolume(dev_t device, const std::string& keyRaw)
+PrivateVolume::PrivateVolume(dev_t device, const KeyBuffer& keyRaw)
     : VolumeBase(Type::kPrivate), mRawDevice(device), mKeyRaw(keyRaw) {
     setId(StringPrintf("private:%u,%u", major(device), minor(device)));
     mRawDevPath = StringPrintf("/dev/block/vold/%s", getId().c_str());
@@ -64,23 +65,18 @@
     if (CreateDeviceNode(mRawDevPath, mRawDevice)) {
         return -EIO;
     }
-    if (mKeyRaw.size() != cryptfs_get_keysize()) {
-        PLOG(ERROR) << getId() << " Raw keysize " << mKeyRaw.size()
-                    << " does not match crypt keysize " << cryptfs_get_keysize();
+
+    // Recover from stale vold by tearing down any old mappings
+    auto& dm = dm::DeviceMapper::Instance();
+    if (!dm.DeleteDeviceIfExists(getId())) {
+        PLOG(ERROR) << "Cannot remove dm device " << getId();
         return -EIO;
     }
 
-    // Recover from stale vold by tearing down any old mappings
-    cryptfs_revert_ext_volume(getId().c_str());
-
     // TODO: figure out better SELinux labels for private volumes
 
-    unsigned char* key = (unsigned char*)mKeyRaw.data();
-    char crypto_blkdev[MAXPATHLEN];
-    int res = cryptfs_setup_ext_volume(getId().c_str(), mRawDevPath.c_str(), key, crypto_blkdev);
-    mDmDevPath = crypto_blkdev;
-    if (res != 0) {
-        PLOG(ERROR) << getId() << " failed to setup cryptfs";
+    if (!setup_ext_volume(getId(), mRawDevPath, mKeyRaw, &mDmDevPath)) {
+        LOG(ERROR) << getId() << " failed to setup metadata encryption";
         return -EIO;
     }
 
@@ -88,8 +84,10 @@
 }
 
 status_t PrivateVolume::doDestroy() {
-    if (cryptfs_revert_ext_volume(getId().c_str())) {
-        LOG(ERROR) << getId() << " failed to revert cryptfs";
+    auto& dm = dm::DeviceMapper::Instance();
+    if (!dm.DeleteDevice(getId())) {
+        PLOG(ERROR) << "Cannot remove dm device " << getId();
+        return -EIO;
     }
     return DestroyDeviceNode(mRawDevPath);
 }
diff --git a/model/PrivateVolume.h b/model/PrivateVolume.h
index 85aa4dc..819632b 100644
--- a/model/PrivateVolume.h
+++ b/model/PrivateVolume.h
@@ -37,11 +37,11 @@
  */
 class PrivateVolume : public VolumeBase {
   public:
-    PrivateVolume(dev_t device, const std::string& keyRaw);
+    PrivateVolume(dev_t device, const KeyBuffer& keyRaw);
     virtual ~PrivateVolume();
-    const std::string& getFsType() { return mFsType; };
-    const std::string& getRawDevPath() { return mRawDevPath; };
-    const std::string& getRawDmDevPath() { return mDmDevPath; };
+    const std::string& getFsType() const { return mFsType; };
+    const std::string& getRawDevPath() const { return mRawDevPath; };
+    const std::string& getRawDmDevPath() const { return mDmDevPath; };
 
   protected:
     status_t doCreate() override;
@@ -63,7 +63,7 @@
     std::string mPath;
 
     /* Encryption key as raw bytes */
-    std::string mKeyRaw;
+    KeyBuffer mKeyRaw;
 
     /* Filesystem type */
     std::string mFsType;
diff --git a/model/PublicVolume.cpp b/model/PublicVolume.cpp
index 8ed4356..0a6b351 100644
--- a/model/PublicVolume.cpp
+++ b/model/PublicVolume.cpp
@@ -21,6 +21,7 @@
 #include "fs/Vfat.h"
 
 #include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <cutils/fs.h>
 #include <private/android_filesystem_config.h>
@@ -34,6 +35,7 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 
+using android::base::GetBoolProperty;
 using android::base::StringPrintf;
 
 namespace android {
@@ -119,6 +121,7 @@
     mFuseDefault = StringPrintf("/mnt/runtime/default/%s", stableName.c_str());
     mFuseRead = StringPrintf("/mnt/runtime/read/%s", stableName.c_str());
     mFuseWrite = StringPrintf("/mnt/runtime/write/%s", stableName.c_str());
+    mFuseFull = StringPrintf("/mnt/runtime/full/%s", stableName.c_str());
 
     setInternalPath(mRawPath);
     if (getMountFlags() & MountFlags::kVisible) {
@@ -156,12 +159,13 @@
 
     if (fs_prepare_dir(mFuseDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
         fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
-        fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT)) {
+        fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT) ||
+        fs_prepare_dir(mFuseFull.c_str(), 0700, AID_ROOT, AID_ROOT)) {
         PLOG(ERROR) << getId() << " failed to create FUSE mount points";
         return -errno;
     }
 
-    dev_t before = GetDevice(mFuseWrite);
+    dev_t before = GetDevice(mFuseFull);
 
     if (!(mFusePid = fork())) {
         if (getMountFlags() & MountFlags::kPrimary) {
@@ -201,7 +205,7 @@
     }
 
     nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME);
-    while (before == GetDevice(mFuseWrite)) {
+    while (before == GetDevice(mFuseFull)) {
         LOG(DEBUG) << "Waiting for FUSE to spin up...";
         usleep(50000);  // 50ms
 
@@ -230,16 +234,19 @@
     ForceUnmount(mFuseDefault);
     ForceUnmount(mFuseRead);
     ForceUnmount(mFuseWrite);
+    ForceUnmount(mFuseFull);
     ForceUnmount(mRawPath);
 
     rmdir(mFuseDefault.c_str());
     rmdir(mFuseRead.c_str());
     rmdir(mFuseWrite.c_str());
+    rmdir(mFuseFull.c_str());
     rmdir(mRawPath.c_str());
 
     mFuseDefault.clear();
     mFuseRead.clear();
     mFuseWrite.clear();
+    mFuseFull.clear();
     mRawPath.clear();
 
     return OK;
diff --git a/model/PublicVolume.h b/model/PublicVolume.h
index c918f52..2feccca 100644
--- a/model/PublicVolume.h
+++ b/model/PublicVolume.h
@@ -63,6 +63,7 @@
     std::string mFuseDefault;
     std::string mFuseRead;
     std::string mFuseWrite;
+    std::string mFuseFull;
 
     /* PID of FUSE wrapper */
     pid_t mFusePid;
diff --git a/model/VolumeBase.cpp b/model/VolumeBase.cpp
index 300add1..ffc7900 100644
--- a/model/VolumeBase.cpp
+++ b/model/VolumeBase.cpp
@@ -35,7 +35,7 @@
 VolumeBase::VolumeBase(Type type)
     : mType(type),
       mMountFlags(0),
-      mMountUserId(-1),
+      mMountUserId(USER_UNKNOWN),
       mCreated(false),
       mState(State::kUnmounted),
       mSilent(false) {}
@@ -143,7 +143,7 @@
     return OK;
 }
 
-android::sp<android::os::IVoldListener> VolumeBase::getListener() {
+android::sp<android::os::IVoldListener> VolumeBase::getListener() const {
     if (mSilent) {
         return nullptr;
     } else {
@@ -219,11 +219,7 @@
 
     setState(State::kChecking);
     status_t res = doMount();
-    if (res == OK) {
-        setState(State::kMounted);
-    } else {
-        setState(State::kUnmountable);
-    }
+    setState(res == OK ? State::kMounted : State::kUnmountable);
 
     return res;
 }
@@ -267,5 +263,10 @@
     return -ENOTSUP;
 }
 
+std::ostream& VolumeBase::operator<<(std::ostream& stream) const {
+    return stream << " VolumeBase{id=" << mId << ",mountFlags=" << mMountFlags
+                  << ",mountUserId=" << mMountUserId << "}";
+}
+
 }  // namespace vold
 }  // namespace android
diff --git a/model/VolumeBase.h b/model/VolumeBase.h
index 92a83f0..53eeb6f 100644
--- a/model/VolumeBase.h
+++ b/model/VolumeBase.h
@@ -27,6 +27,8 @@
 #include <list>
 #include <string>
 
+static constexpr userid_t USER_UNKNOWN = ((userid_t)-1);
+
 namespace android {
 namespace vold {
 
@@ -76,15 +78,15 @@
         kBadRemoval,
     };
 
-    const std::string& getId() { return mId; }
-    const std::string& getDiskId() { return mDiskId; }
-    const std::string& getPartGuid() { return mPartGuid; }
-    Type getType() { return mType; }
-    int getMountFlags() { return mMountFlags; }
-    userid_t getMountUserId() { return mMountUserId; }
-    State getState() { return mState; }
-    const std::string& getPath() { return mPath; }
-    const std::string& getInternalPath() { return mInternalPath; }
+    const std::string& getId() const { return mId; }
+    const std::string& getDiskId() const { return mDiskId; }
+    const std::string& getPartGuid() const { return mPartGuid; }
+    Type getType() const { return mType; }
+    int getMountFlags() const { return mMountFlags; }
+    userid_t getMountUserId() const { return mMountUserId; }
+    State getState() const { return mState; }
+    const std::string& getPath() const { return mPath; }
+    const std::string& getInternalPath() const { return mInternalPath; }
 
     status_t setDiskId(const std::string& diskId);
     status_t setPartGuid(const std::string& partGuid);
@@ -97,12 +99,16 @@
 
     std::shared_ptr<VolumeBase> findVolume(const std::string& id);
 
+    bool isEmulated() { return mType == Type::kEmulated; }
+
     status_t create();
     status_t destroy();
     status_t mount();
     status_t unmount();
     status_t format(const std::string& fsType);
 
+    std::ostream& operator<<(std::ostream& stream) const;
+
   protected:
     explicit VolumeBase(Type type);
 
@@ -116,7 +122,7 @@
     status_t setPath(const std::string& path);
     status_t setInternalPath(const std::string& internalPath);
 
-    android::sp<android::os::IVoldListener> getListener();
+    android::sp<android::os::IVoldListener> getListener() const;
 
   private:
     /* ID that uniquely references volume while alive */
diff --git a/model/VolumeEncryption.cpp b/model/VolumeEncryption.cpp
new file mode 100644
index 0000000..5b0e73d
--- /dev/null
+++ b/model/VolumeEncryption.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "VolumeEncryption.h"
+
+#include <string>
+
+#include <android-base/logging.h>
+#include <android-base/properties.h>
+
+#include "KeyBuffer.h"
+#include "KeyUtil.h"
+#include "MetadataCrypt.h"
+#include "cryptfs.h"
+
+namespace android {
+namespace vold {
+
+enum class VolumeMethod { kFailed, kCrypt, kDefaultKey };
+
+static VolumeMethod lookup_volume_method() {
+    constexpr uint64_t pre_gki_level = 29;
+    auto first_api_level =
+            android::base::GetUintProperty<uint64_t>("ro.product.first_api_level", 0);
+    auto method = android::base::GetProperty("ro.crypto.volume.metadata.method", "default");
+    if (method == "default") {
+        return first_api_level > pre_gki_level ? VolumeMethod::kDefaultKey : VolumeMethod::kCrypt;
+    } else if (method == "dm-default-key") {
+        return VolumeMethod::kDefaultKey;
+    } else if (method == "dm-crypt") {
+        if (first_api_level > pre_gki_level) {
+            LOG(ERROR) << "volume encryption method dm-crypt cannot be used, "
+                          "ro.product.first_api_level = "
+                       << first_api_level;
+            return VolumeMethod::kFailed;
+        }
+        return VolumeMethod::kCrypt;
+    } else {
+        LOG(ERROR) << "Unknown volume encryption method: " << method;
+        return VolumeMethod::kFailed;
+    }
+}
+
+static VolumeMethod volume_method() {
+    static VolumeMethod method = lookup_volume_method();
+    return method;
+}
+
+bool generate_volume_key(android::vold::KeyBuffer* key) {
+    KeyGeneration gen;
+    switch (volume_method()) {
+        case VolumeMethod::kFailed:
+            LOG(ERROR) << "Volume encryption setup failed";
+            return false;
+        case VolumeMethod::kCrypt:
+            gen = cryptfs_get_keygen();
+            break;
+        case VolumeMethod::kDefaultKey:
+            if (!defaultkey_volume_keygen(&gen)) return false;
+            break;
+    }
+    if (!generateStorageKey(gen, key)) return false;
+    return true;
+}
+
+bool setup_ext_volume(const std::string& label, const std::string& blk_device,
+                      const android::vold::KeyBuffer& key, std::string* out_crypto_blkdev) {
+    switch (volume_method()) {
+        case VolumeMethod::kFailed:
+            LOG(ERROR) << "Volume encryption setup failed";
+            return false;
+        case VolumeMethod::kCrypt:
+            return cryptfs_setup_ext_volume(label.c_str(), blk_device.c_str(), key,
+                                            out_crypto_blkdev) == 0;
+        case VolumeMethod::kDefaultKey:
+            return defaultkey_setup_ext_volume(label, blk_device, key, out_crypto_blkdev);
+    }
+}
+
+}  // namespace vold
+}  // namespace android
diff --git a/model/VolumeEncryption.h b/model/VolumeEncryption.h
new file mode 100644
index 0000000..d06c12b
--- /dev/null
+++ b/model/VolumeEncryption.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <string>
+
+#include "KeyBuffer.h"
+
+namespace android {
+namespace vold {
+
+bool generate_volume_key(android::vold::KeyBuffer* key);
+
+bool setup_ext_volume(const std::string& label, const std::string& blk_device,
+                      const android::vold::KeyBuffer& key, std::string* out_crypto_blkdev);
+
+}  // namespace vold
+}  // namespace android
diff --git a/secdiscard.cpp b/secdiscard.cpp
index 2d9dc35..4659eed 100644
--- a/secdiscard.cpp
+++ b/secdiscard.cpp
@@ -75,7 +75,8 @@
 #define F2FS_IOC_SET_PIN_FILE _IOW(F2FS_IOCTL_MAGIC, 13, __u32)
 #define F2FS_IOC_GET_PIN_FILE _IOR(F2FS_IOCTL_MAGIC, 14, __u32)
 #endif
-        android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(target.c_str(), O_WRONLY, 0)));
+        android::base::unique_fd fd(
+            TEMP_FAILURE_RETRY(open(target.c_str(), O_WRONLY | O_CLOEXEC, 0)));
         if (fd == -1) {
             LOG(ERROR) << "Secure discard open failed for: " << target;
             return 0;
@@ -94,7 +95,6 @@
         }
         set = 0;
         ioctl(fd, F2FS_IOC_SET_PIN_FILE, &set);
-        LOG(DEBUG) << "Discarded: " << target;
     }
     return 0;
 }
@@ -143,11 +143,14 @@
         range[0] = fiemap->fm_extents[i].fe_physical;
         range[1] = fiemap->fm_extents[i].fe_length;
         if (ioctl(fs_fd.get(), BLKSECDISCARD, range) == -1) {
-            PLOG(ERROR) << "Unable to BLKSECDISCARD " << path;
+            // Use zero overwrite as a fallback for BLKSECDISCARD
             if (!overwrite_with_zeros(fs_fd.get(), range[0], range[1])) return false;
-            LOG(DEBUG) << "Used zero overwrite";
         }
     }
+    // Should wait for overwrites completion. Otherwise after unlink(),
+    // filesystem can allocate these blocks and IO can be reordered, resulting
+    // in making zero blocks to filesystem blocks.
+    fsync(fs_fd.get());
     return true;
 }
 
diff --git a/secontext.cpp b/secontext.cpp
deleted file mode 100644
index bc21fc2..0000000
--- a/secontext.cpp
+++ /dev/null
@@ -1,21 +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 "secontext.h"
-#include <Utils.h>
-
-security_context_t secontextFsck() {
-    return android::vold::sFsckContext;
-}
diff --git a/secontext.h b/secontext.h
deleted file mode 100644
index f5339c8..0000000
--- a/secontext.h
+++ /dev/null
@@ -1,23 +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.
- */
-#ifndef _SECONTEXT_H_
-#define _SECONTEXT_H_
-
-#include <selinux/selinux.h>
-
-security_context_t secontextFsck();
-
-#endif
diff --git a/tests/Android.bp b/tests/Android.bp
index a070178..b90de3a 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -6,9 +6,10 @@
     ],
 
     srcs: [
-        "CryptfsScryptHidlizationEquivalence_test.cpp",
         "Utils_test.cpp",
+        "VoldNativeServiceValidation_test.cpp",
         "cryptfs_test.cpp",
     ],
     static_libs: ["libvold"],
+    shared_libs: ["libbinder"]
 }
diff --git a/tests/CryptfsScryptHidlizationEquivalence_test.cpp b/tests/CryptfsScryptHidlizationEquivalence_test.cpp
deleted file mode 100644
index 72170e3..0000000
--- a/tests/CryptfsScryptHidlizationEquivalence_test.cpp
+++ /dev/null
@@ -1,450 +0,0 @@
-/*
-**
-** Copyright 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.
-*/
-
-#define LOG_TAG "scrypt_test"
-#include <log/log.h>
-
-#include <gtest/gtest.h>
-#include <hardware/keymaster0.h>
-#include <hardware/keymaster1.h>
-#include <cstring>
-
-#include "../Keymaster.h"
-#include "../cryptfs.h"
-
-#ifdef CONFIG_HW_DISK_ENCRYPTION
-#include "cryptfs_hw.h"
-#endif
-
-#define min(a, b) ((a) < (b) ? (a) : (b))
-
-/* Maximum allowed keymaster blob size. */
-#define KEYMASTER_BLOB_SIZE 2048
-
-/* Key Derivation Function algorithms */
-#define KDF_PBKDF2 1
-#define KDF_SCRYPT 2
-/* Algorithms 3 & 4 deprecated before shipping outside of google, so removed */
-#define KDF_SCRYPT_KEYMASTER 5
-
-#define KEY_LEN_BYTES 16
-
-#define DEFAULT_PASSWORD "default_password"
-
-#define RSA_KEY_SIZE 2048
-#define RSA_KEY_SIZE_BYTES (RSA_KEY_SIZE / 8)
-#define RSA_EXPONENT 0x10001
-#define KEYMASTER_CRYPTFS_RATE_LIMIT 1  // Maximum one try per second
-
-static int keymaster_init(keymaster0_device_t** keymaster0_dev,
-                          keymaster1_device_t** keymaster1_dev) {
-    int rc;
-
-    const hw_module_t* mod;
-    rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
-    if (rc) {
-        ALOGE("could not find any keystore module");
-        goto err;
-    }
-
-    SLOGI("keymaster module name is %s", mod->name);
-    SLOGI("keymaster version is %d", mod->module_api_version);
-
-    *keymaster0_dev = NULL;
-    *keymaster1_dev = NULL;
-    if (mod->module_api_version == KEYMASTER_MODULE_API_VERSION_1_0) {
-        SLOGI("Found keymaster1 module, using keymaster1 API.");
-        rc = keymaster1_open(mod, keymaster1_dev);
-    } else {
-        SLOGI("Found keymaster0 module, using keymaster0 API.");
-        rc = keymaster0_open(mod, keymaster0_dev);
-    }
-
-    if (rc) {
-        ALOGE("could not open keymaster device in %s (%s)", KEYSTORE_HARDWARE_MODULE_ID,
-              strerror(-rc));
-        goto err;
-    }
-
-    return 0;
-
-err:
-    *keymaster0_dev = NULL;
-    *keymaster1_dev = NULL;
-    return rc;
-}
-
-/* Should we use keymaster? */
-static int keymaster_check_compatibility_old() {
-    keymaster0_device_t* keymaster0_dev = 0;
-    keymaster1_device_t* keymaster1_dev = 0;
-    int rc = 0;
-
-    if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
-        SLOGE("Failed to init keymaster");
-        rc = -1;
-        goto out;
-    }
-
-    if (keymaster1_dev) {
-        rc = 1;
-        goto out;
-    }
-
-    if (!keymaster0_dev || !keymaster0_dev->common.module) {
-        rc = -1;
-        goto out;
-    }
-
-    // TODO(swillden): Check to see if there's any reason to require v0.3.  I think v0.1 and v0.2
-    // should work.
-    if (keymaster0_dev->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_3) {
-        rc = 0;
-        goto out;
-    }
-
-    if (!(keymaster0_dev->flags & KEYMASTER_SOFTWARE_ONLY) &&
-        (keymaster0_dev->flags & KEYMASTER_BLOBS_ARE_STANDALONE)) {
-        rc = 1;
-    }
-
-out:
-    if (keymaster1_dev) {
-        keymaster1_close(keymaster1_dev);
-    }
-    if (keymaster0_dev) {
-        keymaster0_close(keymaster0_dev);
-    }
-    return rc;
-}
-
-/* Create a new keymaster key and store it in this footer */
-static int keymaster_create_key_old(struct crypt_mnt_ftr* ftr) {
-    uint8_t* key = 0;
-    keymaster0_device_t* keymaster0_dev = 0;
-    keymaster1_device_t* keymaster1_dev = 0;
-
-    if (ftr->keymaster_blob_size) {
-        SLOGI("Already have key");
-        return 0;
-    }
-
-    if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
-        SLOGE("Failed to init keymaster");
-        return -1;
-    }
-
-    int rc = 0;
-    size_t key_size = 0;
-    if (keymaster1_dev) {
-        keymaster_key_param_t params[] = {
-            /* Algorithm & size specifications.  Stick with RSA for now.  Switch to AES later. */
-            keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
-            keymaster_param_int(KM_TAG_KEY_SIZE, RSA_KEY_SIZE),
-            keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, RSA_EXPONENT),
-
-            /* The only allowed purpose for this key is signing. */
-            keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
-
-            /* Padding & digest specifications. */
-            keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
-            keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
-
-            /* Require that the key be usable in standalone mode.  File system isn't available. */
-            keymaster_param_enum(KM_TAG_BLOB_USAGE_REQUIREMENTS, KM_BLOB_STANDALONE),
-
-            /* No auth requirements, because cryptfs is not yet integrated with gatekeeper. */
-            keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
-
-            /* Rate-limit key usage attempts, to rate-limit brute force */
-            keymaster_param_int(KM_TAG_MIN_SECONDS_BETWEEN_OPS, KEYMASTER_CRYPTFS_RATE_LIMIT),
-        };
-        keymaster_key_param_set_t param_set = {params, sizeof(params) / sizeof(*params)};
-        keymaster_key_blob_t key_blob;
-        keymaster_error_t error = keymaster1_dev->generate_key(
-            keymaster1_dev, &param_set, &key_blob, NULL /* characteristics */);
-        if (error != KM_ERROR_OK) {
-            SLOGE("Failed to generate keymaster1 key, error %d", error);
-            rc = -1;
-            goto out;
-        }
-
-        key = (uint8_t*)key_blob.key_material;
-        key_size = key_blob.key_material_size;
-    } else if (keymaster0_dev) {
-        keymaster_rsa_keygen_params_t params;
-        memset(&params, '\0', sizeof(params));
-        params.public_exponent = RSA_EXPONENT;
-        params.modulus_size = RSA_KEY_SIZE;
-
-        if (keymaster0_dev->generate_keypair(keymaster0_dev, TYPE_RSA, &params, &key, &key_size)) {
-            SLOGE("Failed to generate keypair");
-            rc = -1;
-            goto out;
-        }
-    } else {
-        SLOGE("Cryptfs bug: keymaster_init succeeded but didn't initialize a device");
-        rc = -1;
-        goto out;
-    }
-
-    if (key_size > KEYMASTER_BLOB_SIZE) {
-        SLOGE("Keymaster key too large for crypto footer");
-        rc = -1;
-        goto out;
-    }
-
-    memcpy(ftr->keymaster_blob, key, key_size);
-    ftr->keymaster_blob_size = key_size;
-
-out:
-    if (keymaster0_dev) keymaster0_close(keymaster0_dev);
-    if (keymaster1_dev) keymaster1_close(keymaster1_dev);
-    free(key);
-    return rc;
-}
-
-/* This signs the given object using the keymaster key. */
-static int keymaster_sign_object_old(struct crypt_mnt_ftr* ftr, const unsigned char* object,
-                                     const size_t object_size, unsigned char** signature,
-                                     size_t* signature_size) {
-    int rc = 0;
-    keymaster0_device_t* keymaster0_dev = 0;
-    keymaster1_device_t* keymaster1_dev = 0;
-
-    unsigned char to_sign[RSA_KEY_SIZE_BYTES];
-    size_t to_sign_size = sizeof(to_sign);
-    memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
-
-    if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
-        SLOGE("Failed to init keymaster");
-        rc = -1;
-        goto out;
-    }
-
-    // To sign a message with RSA, the message must satisfy two
-    // constraints:
-    //
-    // 1. The message, when interpreted as a big-endian numeric value, must
-    //    be strictly less than the public modulus of the RSA key.  Note
-    //    that because the most significant bit of the public modulus is
-    //    guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
-    //    key), an n-bit message with most significant bit 0 always
-    //    satisfies this requirement.
-    //
-    // 2. The message must have the same length in bits as the public
-    //    modulus of the RSA key.  This requirement isn't mathematically
-    //    necessary, but is necessary to ensure consistency in
-    //    implementations.
-    switch (ftr->kdf_type) {
-        case KDF_SCRYPT_KEYMASTER:
-            // This ensures the most significant byte of the signed message
-            // is zero.  We could have zero-padded to the left instead, but
-            // this approach is slightly more robust against changes in
-            // object size.  However, it's still broken (but not unusably
-            // so) because we really should be using a proper deterministic
-            // RSA padding function, such as PKCS1.
-            memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
-            SLOGI("Signing safely-padded object");
-            break;
-        default:
-            SLOGE("Unknown KDF type %d", ftr->kdf_type);
-            rc = -1;
-            goto out;
-    }
-
-    if (keymaster0_dev) {
-        keymaster_rsa_sign_params_t params;
-        params.digest_type = DIGEST_NONE;
-        params.padding_type = PADDING_NONE;
-
-        rc = keymaster0_dev->sign_data(keymaster0_dev, &params, ftr->keymaster_blob,
-                                       ftr->keymaster_blob_size, to_sign, to_sign_size, signature,
-                                       signature_size);
-        goto out;
-    } else if (keymaster1_dev) {
-        keymaster_key_blob_t key = {ftr->keymaster_blob, ftr->keymaster_blob_size};
-        keymaster_key_param_t params[] = {
-            keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
-            keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
-        };
-        keymaster_key_param_set_t param_set = {params, sizeof(params) / sizeof(*params)};
-        keymaster_operation_handle_t op_handle;
-        keymaster_error_t error = keymaster1_dev->begin(
-            keymaster1_dev, KM_PURPOSE_SIGN, &key, &param_set, NULL /* out_params */, &op_handle);
-        if (error == KM_ERROR_KEY_RATE_LIMIT_EXCEEDED) {
-            // Key usage has been rate-limited.  Wait a bit and try again.
-            sleep(KEYMASTER_CRYPTFS_RATE_LIMIT);
-            error = keymaster1_dev->begin(keymaster1_dev, KM_PURPOSE_SIGN, &key, &param_set,
-                                          NULL /* out_params */, &op_handle);
-        }
-        if (error != KM_ERROR_OK) {
-            SLOGE("Error starting keymaster signature transaction: %d", error);
-            rc = -1;
-            goto out;
-        }
-
-        keymaster_blob_t input = {to_sign, to_sign_size};
-        size_t input_consumed;
-        error = keymaster1_dev->update(keymaster1_dev, op_handle, NULL /* in_params */, &input,
-                                       &input_consumed, NULL /* out_params */, NULL /* output */);
-        if (error != KM_ERROR_OK) {
-            SLOGE("Error sending data to keymaster signature transaction: %d", error);
-            rc = -1;
-            goto out;
-        }
-        if (input_consumed != to_sign_size) {
-            // This should never happen.  If it does, it's a bug in the keymaster implementation.
-            SLOGE("Keymaster update() did not consume all data.");
-            keymaster1_dev->abort(keymaster1_dev, op_handle);
-            rc = -1;
-            goto out;
-        }
-
-        keymaster_blob_t tmp_sig;
-        error = keymaster1_dev->finish(keymaster1_dev, op_handle, NULL /* in_params */,
-                                       NULL /* verify signature */, NULL /* out_params */, &tmp_sig);
-        if (error != KM_ERROR_OK) {
-            SLOGE("Error finishing keymaster signature transaction: %d", error);
-            rc = -1;
-            goto out;
-        }
-
-        *signature = (uint8_t*)tmp_sig.data;
-        *signature_size = tmp_sig.data_length;
-    } else {
-        SLOGE("Cryptfs bug: keymaster_init succeded but didn't initialize a device.");
-        rc = -1;
-        goto out;
-    }
-
-out:
-    if (keymaster1_dev) keymaster1_close(keymaster1_dev);
-    if (keymaster0_dev) keymaster0_close(keymaster0_dev);
-
-    return rc;
-}
-
-/* Should we use keymaster? */
-static int keymaster_check_compatibility_new() {
-    return keymaster_compatibility_cryptfs_scrypt();
-}
-
-#if 0
-/* Create a new keymaster key and store it in this footer */
-static int keymaster_create_key_new(struct crypt_mnt_ftr *ftr)
-{
-    if (ftr->keymaster_blob_size) {
-        SLOGI("Already have key");
-        return 0;
-    }
-
-    int rc = keymaster_create_key_for_cryptfs_scrypt(RSA_KEY_SIZE, RSA_EXPONENT,
-            KEYMASTER_CRYPTFS_RATE_LIMIT, ftr->keymaster_blob, KEYMASTER_BLOB_SIZE,
-            &ftr->keymaster_blob_size);
-    if (rc) {
-        if (ftr->keymaster_blob_size > KEYMASTER_BLOB_SIZE) {
-            SLOGE("Keymaster key blob to large)");
-            ftr->keymaster_blob_size = 0;
-        }
-        SLOGE("Failed to generate keypair");
-        return -1;
-    }
-    return 0;
-}
-#endif
-
-/* This signs the given object using the keymaster key. */
-static int keymaster_sign_object_new(struct crypt_mnt_ftr* ftr, const unsigned char* object,
-                                     const size_t object_size, unsigned char** signature,
-                                     size_t* signature_size) {
-    unsigned char to_sign[RSA_KEY_SIZE_BYTES];
-    size_t to_sign_size = sizeof(to_sign);
-    memset(to_sign, 0, RSA_KEY_SIZE_BYTES);
-
-    // To sign a message with RSA, the message must satisfy two
-    // constraints:
-    //
-    // 1. The message, when interpreted as a big-endian numeric value, must
-    //    be strictly less than the public modulus of the RSA key.  Note
-    //    that because the most significant bit of the public modulus is
-    //    guaranteed to be 1 (else it's an (n-1)-bit key, not an n-bit
-    //    key), an n-bit message with most significant bit 0 always
-    //    satisfies this requirement.
-    //
-    // 2. The message must have the same length in bits as the public
-    //    modulus of the RSA key.  This requirement isn't mathematically
-    //    necessary, but is necessary to ensure consistency in
-    //    implementations.
-    switch (ftr->kdf_type) {
-        case KDF_SCRYPT_KEYMASTER:
-            // This ensures the most significant byte of the signed message
-            // is zero.  We could have zero-padded to the left instead, but
-            // this approach is slightly more robust against changes in
-            // object size.  However, it's still broken (but not unusably
-            // so) because we really should be using a proper deterministic
-            // RSA padding function, such as PKCS1.
-            memcpy(to_sign + 1, object, min(RSA_KEY_SIZE_BYTES - 1, object_size));
-            SLOGI("Signing safely-padded object");
-            break;
-        default:
-            SLOGE("Unknown KDF type %d", ftr->kdf_type);
-            return -1;
-    }
-    if (keymaster_sign_object_for_cryptfs_scrypt(
-            ftr->keymaster_blob, ftr->keymaster_blob_size, KEYMASTER_CRYPTFS_RATE_LIMIT, to_sign,
-            to_sign_size, signature, signature_size) != KeymasterSignResult::ok)
-        return -1;
-    return 0;
-}
-
-namespace android {
-
-class CryptFsTest : public testing::Test {
-  protected:
-    virtual void SetUp() {}
-
-    virtual void TearDown() {}
-};
-
-TEST_F(CryptFsTest, ScryptHidlizationEquivalenceTest) {
-    crypt_mnt_ftr ftr;
-    ftr.kdf_type = KDF_SCRYPT_KEYMASTER;
-    ftr.keymaster_blob_size = 0;
-
-    ASSERT_EQ(0, keymaster_create_key_old(&ftr));
-
-    uint8_t* sig1 = nullptr;
-    uint8_t* sig2 = nullptr;
-    size_t sig_size1 = 123456789;
-    size_t sig_size2 = 123456789;
-    uint8_t object[] = "the object";
-
-    ASSERT_EQ(1, keymaster_check_compatibility_old());
-    ASSERT_EQ(1, keymaster_check_compatibility_new());
-    ASSERT_EQ(0, keymaster_sign_object_old(&ftr, object, 10, &sig1, &sig_size1));
-    ASSERT_EQ(0, keymaster_sign_object_new(&ftr, object, 10, &sig2, &sig_size2));
-
-    ASSERT_EQ(sig_size1, sig_size2);
-    ASSERT_NE(nullptr, sig1);
-    ASSERT_NE(nullptr, sig2);
-    EXPECT_EQ(0, memcmp(sig1, sig2, sig_size1));
-    free(sig1);
-    free(sig2);
-}
-
-}  // namespace android
diff --git a/tests/Utils_test.cpp b/tests/Utils_test.cpp
index e16cbac..d18dc67 100644
--- a/tests/Utils_test.cpp
+++ b/tests/Utils_test.cpp
@@ -27,6 +27,7 @@
     std::string tmp;
 
     ASSERT_FALSE(FindValue("", "KEY", &tmp));
+    ASSERT_FALSE(FindValue("NOTMATCH=\"VALUE\"", "KEY", &tmp));
     ASSERT_FALSE(FindValue("BADKEY=\"VALUE\"", "KEY", &tmp));
 
     ASSERT_TRUE(FindValue("KEY=\"VALUE\"", "KEY", &tmp));
@@ -37,6 +38,9 @@
 
     ASSERT_TRUE(FindValue("BADKEY=\"VALUE\" KEY=\"BAZ\"", "KEY", &tmp));
     ASSERT_EQ("BAZ", tmp);
+
+    ASSERT_TRUE(FindValue("BADKEY=\"VALUE\" NOTKEY=\"OTHER\" KEY=\"QUUX\"", "KEY", &tmp));
+    ASSERT_EQ("QUUX", tmp);
 }
 
 }  // namespace vold
diff --git a/tests/VoldNativeServiceValidation_test.cpp b/tests/VoldNativeServiceValidation_test.cpp
new file mode 100644
index 0000000..b057b82
--- /dev/null
+++ b/tests/VoldNativeServiceValidation_test.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "../VoldNativeServiceValidation.h"
+
+#include <gtest/gtest.h>
+
+#include <string_view>
+
+using namespace std::literals;
+
+namespace android::vold {
+
+class VoldNativeServiceValidationTest : public testing::Test {};
+
+TEST_F(VoldNativeServiceValidationTest, CheckArgumentPathTest) {
+    EXPECT_TRUE(CheckArgumentPath("/").isOk());
+    EXPECT_TRUE(CheckArgumentPath("/1/2").isOk());
+    EXPECT_TRUE(CheckArgumentPath("/1/2/").isOk());
+    EXPECT_TRUE(CheckArgumentPath("/1/2/./3").isOk());
+    EXPECT_TRUE(CheckArgumentPath("/1/2/./3/.").isOk());
+    EXPECT_TRUE(CheckArgumentPath(
+                        "/very long path with some/ spaces and quite/ uncommon names /in\1 it/")
+                        .isOk());
+
+    EXPECT_FALSE(CheckArgumentPath("").isOk());
+    EXPECT_FALSE(CheckArgumentPath("relative/path").isOk());
+    EXPECT_FALSE(CheckArgumentPath("../data/..").isOk());
+    EXPECT_FALSE(CheckArgumentPath("/../data/..").isOk());
+    EXPECT_FALSE(CheckArgumentPath("/data/../system").isOk());
+    EXPECT_FALSE(CheckArgumentPath("/data/..trick/../system").isOk());
+    EXPECT_FALSE(CheckArgumentPath("/data/..").isOk());
+    EXPECT_FALSE(CheckArgumentPath("/data/././../apex").isOk());
+    EXPECT_FALSE(CheckArgumentPath(std::string("/data/strange\0one"sv)).isOk());
+    EXPECT_FALSE(CheckArgumentPath(std::string("/data/strange\ntwo"sv)).isOk());
+}
+
+}  // namespace android::vold
diff --git a/vdc.cpp b/vdc.cpp
index e971d52..a6a3fb0 100644
--- a/vdc.cpp
+++ b/vdc.cpp
@@ -32,6 +32,7 @@
 
 #include <android-base/logging.h>
 #include <android-base/parseint.h>
+#include <android-base/strings.h>
 #include <android-base/stringprintf.h>
 #include <binder/IServiceManager.h>
 #include <binder/Status.h>
@@ -55,9 +56,10 @@
     return res;
 }
 
-static void checkStatus(android::binder::Status status) {
+static void checkStatus(std::vector<std::string>& cmd, android::binder::Status status) {
     if (status.isOk()) return;
-    LOG(ERROR) << "Failed: " << status.toString8().string();
+    std::string command = ::android::base::Join(cmd, " ");
+    LOG(ERROR) << "Command: " << command << " Failed: " << status.toString8().string();
     exit(ENOTTY);
 }
 
@@ -88,45 +90,68 @@
     auto vold = android::interface_cast<android::os::IVold>(binder);
 
     if (args[0] == "cryptfs" && args[1] == "enablefilecrypto") {
-        checkStatus(vold->fbeEnable());
+        checkStatus(args, vold->fbeEnable());
     } else if (args[0] == "cryptfs" && args[1] == "init_user0") {
-        checkStatus(vold->initUser0());
+        checkStatus(args, vold->initUser0());
     } else if (args[0] == "cryptfs" && args[1] == "enablecrypto") {
         int passwordType = android::os::IVold::PASSWORD_TYPE_DEFAULT;
         int encryptionFlags = android::os::IVold::ENCRYPTION_FLAG_NO_UI;
-        checkStatus(vold->fdeEnable(passwordType, "", encryptionFlags));
+        checkStatus(args, vold->fdeEnable(passwordType, "", encryptionFlags));
     } else if (args[0] == "cryptfs" && args[1] == "mountdefaultencrypted") {
-        checkStatus(vold->mountDefaultEncrypted());
+        checkStatus(args, vold->mountDefaultEncrypted());
     } else if (args[0] == "volume" && args[1] == "shutdown") {
-        checkStatus(vold->shutdown());
+        checkStatus(args, vold->shutdown());
+    } else if (args[0] == "volume" && args[1] == "reset") {
+        checkStatus(args, vold->reset());
     } else if (args[0] == "cryptfs" && args[1] == "checkEncryption" && args.size() == 3) {
-        checkStatus(vold->checkEncryption(args[2]));
-    } else if (args[0] == "cryptfs" && args[1] == "mountFstab" && args.size() == 3) {
-        checkStatus(vold->mountFstab(args[2]));
-    } else if (args[0] == "cryptfs" && args[1] == "encryptFstab" && args.size() == 3) {
-        checkStatus(vold->encryptFstab(args[2]));
+        checkStatus(args, vold->checkEncryption(args[2]));
+    } else if (args[0] == "cryptfs" && args[1] == "mountFstab" && args.size() == 4) {
+        checkStatus(args, vold->mountFstab(args[2], args[3]));
+    } else if (args[0] == "cryptfs" && args[1] == "encryptFstab" && args.size() == 4) {
+        checkStatus(args, vold->encryptFstab(args[2], args[3]));
+    } else if (args[0] == "checkpoint" && args[1] == "supportsCheckpoint" && args.size() == 2) {
+        bool supported = false;
+        checkStatus(args, vold->supportsCheckpoint(&supported));
+        return supported ? 1 : 0;
+    } else if (args[0] == "checkpoint" && args[1] == "supportsBlockCheckpoint" &&
+               args.size() == 2) {
+        bool supported = false;
+        checkStatus(args, vold->supportsBlockCheckpoint(&supported));
+        return supported ? 1 : 0;
+    } else if (args[0] == "checkpoint" && args[1] == "supportsFileCheckpoint" && args.size() == 2) {
+        bool supported = false;
+        checkStatus(args, vold->supportsFileCheckpoint(&supported));
+        return supported ? 1 : 0;
     } else if (args[0] == "checkpoint" && args[1] == "startCheckpoint" && args.size() == 3) {
         int retry;
         if (!android::base::ParseInt(args[2], &retry)) exit(EINVAL);
-        checkStatus(vold->startCheckpoint(retry));
+        checkStatus(args, vold->startCheckpoint(retry));
     } else if (args[0] == "checkpoint" && args[1] == "needsCheckpoint" && args.size() == 2) {
         bool enabled = false;
-        checkStatus(vold->needsCheckpoint(&enabled));
+        checkStatus(args, vold->needsCheckpoint(&enabled));
         return enabled ? 1 : 0;
     } else if (args[0] == "checkpoint" && args[1] == "needsRollback" && args.size() == 2) {
         bool enabled = false;
-        checkStatus(vold->needsRollback(&enabled));
+        checkStatus(args, vold->needsRollback(&enabled));
         return enabled ? 1 : 0;
     } else if (args[0] == "checkpoint" && args[1] == "commitChanges" && args.size() == 2) {
-        checkStatus(vold->commitChanges());
+        checkStatus(args, vold->commitChanges());
     } else if (args[0] == "checkpoint" && args[1] == "prepareCheckpoint" && args.size() == 2) {
-        checkStatus(vold->prepareCheckpoint());
+        checkStatus(args, vold->prepareCheckpoint());
     } else if (args[0] == "checkpoint" && args[1] == "restoreCheckpoint" && args.size() == 3) {
-        checkStatus(vold->restoreCheckpoint(args[2]));
+        checkStatus(args, vold->restoreCheckpoint(args[2]));
+    } else if (args[0] == "checkpoint" && args[1] == "restoreCheckpointPart" && args.size() == 4) {
+        int count;
+        if (!android::base::ParseInt(args[3], &count)) exit(EINVAL);
+        checkStatus(args, vold->restoreCheckpointPart(args[2], count));
     } else if (args[0] == "checkpoint" && args[1] == "markBootAttempt" && args.size() == 2) {
-        checkStatus(vold->markBootAttempt());
-    } else if (args[0] == "checkpoint" && args[1] == "abortChanges" && args.size() == 2) {
-        checkStatus(vold->abortChanges());
+        checkStatus(args, vold->markBootAttempt());
+    } else if (args[0] == "checkpoint" && args[1] == "abortChanges" && args.size() == 4) {
+        int retry;
+        if (!android::base::ParseInt(args[2], &retry)) exit(EINVAL);
+        checkStatus(args, vold->abortChanges(args[2], retry != 0));
+    } else if (args[0] == "checkpoint" && args[1] == "resetCheckpoint") {
+        checkStatus(args, vold->resetCheckpoint());
     } else {
         LOG(ERROR) << "Raw commands are no longer supported";
         exit(EINVAL);
diff --git a/vold_prepare_subdirs.cpp b/vold_prepare_subdirs.cpp
index 8c3df30..d624d73 100644
--- a/vold_prepare_subdirs.cpp
+++ b/vold_prepare_subdirs.cpp
@@ -120,6 +120,31 @@
     }
 }
 
+static bool prepare_apex_subdirs(struct selabel_handle* sehandle, const std::string& path) {
+    if (!prepare_dir(sehandle, 0711, 0, 0, path + "/apexdata")) return false;
+
+    auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir("/apex"), closedir);
+    if (!dirp) {
+        PLOG(ERROR) << "Unable to open apex directory";
+        return false;
+    }
+    struct dirent* entry;
+    while ((entry = readdir(dirp.get())) != nullptr) {
+        if (entry->d_type != DT_DIR) continue;
+
+        const char* name = entry->d_name;
+        // skip any starting with "."
+        if (name[0] == '.') continue;
+
+        if (strchr(name, '@') != NULL) continue;
+
+        if (!prepare_dir(sehandle, 0771, AID_ROOT, AID_SYSTEM, path + "/apexdata/" + name)) {
+            return false;
+        }
+    }
+    return true;
+}
+
 static bool prepare_subdirs(const std::string& volume_uuid, int user_id, int flags) {
     struct selabel_handle* sehandle = selinux_android_file_context_handle();
 
@@ -128,16 +153,42 @@
             auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
             if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/vold")) return false;
             if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/storaged")) return false;
+            if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/rollback")) return false;
+            // TODO: Return false if this returns false once sure this should succeed.
+            prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/apexrollback");
+            prepare_apex_subdirs(sehandle, misc_de_path);
 
             auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
             if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, vendor_de_path + "/fpdata")) {
                 return false;
             }
+            auto facedata_path = vendor_de_path + "/facedata";
+            if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) {
+                return false;
+            }
         }
         if (flags & android::os::IVold::STORAGE_FLAG_CE) {
             auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
             if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/vold")) return false;
             if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/storaged")) return false;
+            if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/rollback")) return false;
+            // TODO: Return false if this returns false once sure this should succeed.
+            prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/apexrollback");
+            prepare_apex_subdirs(sehandle, misc_ce_path);
+
+            auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
+            if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, system_ce_path + "/backup")) {
+                return false;
+            }
+            if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM,
+                             system_ce_path + "/backup_stage")) {
+                return false;
+            }
+            auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
+            auto facedata_path = vendor_ce_path + "/facedata";
+            if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) {
+                return false;
+            }
         }
     }
     return true;