Merge "Don't call block checkpoint functions above dm-default-key"
diff --git a/Android.bp b/Android.bp
index 9d87f68..0ffc8f9 100644
--- a/Android.bp
+++ b/Android.bp
@@ -130,6 +130,7 @@
         "ScryptParameters.cpp",
         "Utils.cpp",
         "VoldNativeService.cpp",
+        "VoldNativeServiceValidation.cpp",
         "VoldUtil.cpp",
         "VolumeManager.cpp",
         "cryptfs.cpp",
@@ -149,12 +150,10 @@
     product_variables: {
         arc: {
             exclude_srcs: [
-                "AppFuseUtil.cpp",
                 "model/ObbVolume.cpp",
             ],
             static_libs: [
                 "arc_services_aidl",
-                "libarcappfuse",
                 "libarcobbvolume",
             ],
         },
@@ -183,7 +182,6 @@
         arc: {
             static_libs: [
                 "arc_services_aidl",
-                "libarcappfuse",
                 "libarcobbvolume",
             ],
         },
diff --git a/Checkpoint.cpp b/Checkpoint.cpp
index df5fc88..61035e5 100644
--- a/Checkpoint.cpp
+++ b/Checkpoint.cpp
@@ -294,6 +294,10 @@
     return false;
 }
 
+bool cp_isCheckpointing() {
+    return isCheckpointing;
+}
+
 namespace {
 const std::string kSleepTimeProp = "ro.sys.cp_msleeptime";
 const uint32_t msleeptime_default = 1000;  // 1 s
diff --git a/Checkpoint.h b/Checkpoint.h
index c1fb2b7..6f3acac 100644
--- a/Checkpoint.h
+++ b/Checkpoint.h
@@ -39,6 +39,8 @@
 
 bool cp_needsCheckpoint();
 
+bool cp_isCheckpointing();
+
 android::binder::Status cp_prepareCheckpoint();
 
 android::binder::Status cp_restoreCheckpoint(const std::string& mountPoint, int count = 0);
diff --git a/FsCrypt.cpp b/FsCrypt.cpp
index e31163f..aa66c01 100644
--- a/FsCrypt.cpp
+++ b/FsCrypt.cpp
@@ -83,8 +83,6 @@
 const std::string systemwide_volume_key_dir =
     std::string() + DATA_MNT_POINT + "/misc/vold/volume_keys";
 
-bool s_systemwide_keys_initialized = false;
-
 // Some users are ephemeral, don't try to wipe their keys from disk
 std::set<userid_t> s_ephemeral_users;
 
@@ -359,28 +357,37 @@
             continue;
         }
         userid_t user_id = std::stoi(entry->d_name);
-        if (s_de_policies.count(user_id) == 0) {
-            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;
-            s_de_policies[user_id] = de_policy;
-            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;
 }
 
+// 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;
+}
+
 bool fscrypt_initialize_systemwide_keys() {
     LOG(INFO) << "fscrypt_initialize_systemwide_keys";
 
-    if (s_systemwide_keys_initialized) {
-        LOG(INFO) << "Already initialized";
-        return true;
-    }
     EncryptionOptions options;
     if (!get_data_file_encryption_options(&options)) return false;
 
@@ -414,7 +421,6 @@
     LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
 
     if (!android::vold::FsyncDirectory(device_key_dir)) return false;
-    s_systemwide_keys_initialized = true;
     return true;
 }
 
@@ -445,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;
 }
 
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 6200c42..acc42db 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -27,6 +27,7 @@
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/properties.h>
 #include <keyutils.h>
 
 #include <fscrypt_uapi.h>
@@ -87,6 +88,7 @@
             }
             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
@@ -155,7 +157,7 @@
     return true;
 }
 
-// Add an encryption key to the legacy global session keyring.
+// 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));
@@ -178,6 +180,32 @@
     return true;
 }
 
+// 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) {
@@ -205,6 +233,34 @@
     }
 }
 
+// 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;
@@ -240,33 +296,24 @@
             return false;
     }
 
-    if (options.use_hw_wrapped_key) arg->flags |= FSCRYPT_ADD_KEY_FLAG_WRAPPED;
-    // Provide the raw key.
     arg->raw_size = key.size();
     memcpy(arg->raw, key.data(), key.size());
 
-    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;
-    }
+    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);
     }
-    LOG(DEBUG) << "Installed fscrypt key with ref " << keyrefstring(policy->key_raw_ref) << " to "
-               << mountpoint;
+    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 from the legacy global session keyring.
+// 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;
@@ -289,6 +336,26 @@
     return success;
 }
 
+static bool evictProvisioningKey(const std::string& ref) {
+    key_serial_t device_keyring;
+    if (!fscryptKeyring(&device_keyring)) {
+        return false;
+    }
+
+    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 evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
     if (policy.options.version == 1 && !isFsKeyringSupported()) {
         return evictKeyLegacy(policy.key_raw_ref);
@@ -322,6 +389,8 @@
         LOG(ERROR) << "Files still open after removing key with ref " << ref
                    << ".  These files were not locked!";
     }
+
+    if (!evictProvisioningKey(ref)) return false;
     return true;
 }
 
@@ -343,5 +412,31 @@
     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 dcb1dc7..23278c1 100644
--- a/KeyUtil.h
+++ b/KeyUtil.h
@@ -51,11 +51,16 @@
 // 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 legacy global session keyring.
+// 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,
@@ -63,16 +68,20 @@
 
 // Evict a file-based encryption key from the kernel.
 //
-// We use FS_IOC_REMOVE_ENCRYPTION_KEY if the kernel supports it.  Otherwise we
-// remove the key from the legacy global session keyring.
+// This undoes the effect of installKey().
 //
-// In the latter case, the caller is responsible for dropping caches.
+// 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 c3f2912..786cdb5 100644
--- a/Keymaster.cpp
+++ b/Keymaster.cpp
@@ -229,13 +229,19 @@
 }
 
 void Keymaster::earlyBootEnded() {
-    auto error = mDevice->earlyBootEnded();
-    if (!error.isOk()) {
-        LOG(ERROR) << "earlyBootEnded failed: " << error.description();
-    }
-    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: " << int32_t(km_error);
+    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;
+        }
     }
 }
 
diff --git a/Keymaster.h b/Keymaster.h
index ea102f5..4f2dd93 100644
--- a/Keymaster.h
+++ b/Keymaster.h
@@ -128,9 +128,9 @@
                              km::AuthorizationSet* outParams);
     bool isSecure();
 
-    // Tell Keymaster that early boot has ended and early boot-only keys can no longer be created or
-    // used.
-    void earlyBootEnded();
+    // 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;
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index bf0220e..ca2813d 100644
--- a/MetadataCrypt.cpp
+++ b/MetadataCrypt.cpp
@@ -58,7 +58,7 @@
 // Parsed from metadata options
 struct CryptoOptions {
     struct CryptoType cipher = invalid_crypto_type;
-    bool is_legacy = false;
+    bool use_legacy_options_format = false;
     bool set_dun = true;  // Non-legacy driver always sets DUN
     bool use_hw_wrapped_key = false;
 };
@@ -87,13 +87,9 @@
 }
 
 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 that early boot has
-    // ended.
-    //
-    // TODO(paulcrowley): Make a Keymaster singleton or something, so we don't have to repeatedly
-    // open and initialize the service.
-    ::android::vold::Keymaster keymaster;
-    keymaster.earlyBootEnded();
+    // 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.
@@ -211,7 +207,7 @@
 
     auto target = std::make_unique<DmTargetDefaultKey>(0, *nr_sec, options.cipher.get_kernel_name(),
                                                        hex_key, blk_device, 0);
-    if (options.is_legacy) target->SetIsLegacy();
+    if (options.use_legacy_options_format) target->SetUseLegacyOptionsFormat();
     if (options.set_dun) target->SetSetDun();
     if (options.use_hw_wrapped_key) target->SetWrappedKeyV0();
 
@@ -286,31 +282,31 @@
         LOG(ERROR) << "Failed to get data_rec for " << mount_point;
         return false;
     }
-    if (blk_device != data_rec->blk_device) {
-        LOG(ERROR) << "blk_device " << blk_device << " does not match fstab entry "
-                   << data_rec->blk_device << " for " << mount_point;
-        return false;
-    }
 
-    bool is_legacy;
-    if (!DmTargetDefaultKey::IsLegacy(&is_legacy)) return false;
+    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 (is_legacy) {
+    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.is_legacy = true;
+        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 {
+    } 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();
@@ -319,8 +315,7 @@
 
     std::string crypto_blkdev;
     uint64_t nr_sec;
-    if (!create_crypto_blk_dev(kDmNameUserdata, data_rec->blk_device, key, options, &crypto_blkdev,
-                               &nr_sec))
+    if (!create_crypto_blk_dev(kDmNameUserdata, blk_device, key, options, &crypto_blkdev, &nr_sec))
         return false;
 
     // FIXME handle the corrupt case
@@ -341,7 +336,12 @@
     }
 
     LOG(DEBUG) << "Mounting metadata-encrypted filesystem:" << mount_point;
-    mount_via_fs_mgr(data_rec->mount_point.c_str(), crypto_blkdev.c_str());
+    mount_via_fs_mgr(mount_point.c_str(), crypto_blkdev.c_str());
+
+    // Record that there's at least one fstab entry with metadata encryption
+    if (!android::base::SetProperty("ro.crypto.metadata.enabled", "true")) {
+        LOG(WARNING) << "failed to set ro.crypto.metadata.enabled";  // This isn't fatal
+    }
     return true;
 }
 
diff --git a/Utils.cpp b/Utils.cpp
index 1616d80..3e879f6 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -70,6 +70,7 @@
 static const char* kBlkidPath = "/system/bin/blkid";
 static const char* kKeyPath = "/data/misc/vold";
 
+static const char* kProcDevices = "/proc/devices";
 static const char* kProcFilesystems = "/proc/filesystems";
 
 // Lock used to protect process-level SELinux changes from racing with each
@@ -796,8 +797,39 @@
     }
 }
 
-bool IsRunningInEmulator() {
-    return android::base::GetBoolProperty("ro.kernel.qemu", false);
+static unsigned int GetMajorBlockVirtioBlk() {
+    std::string devices;
+    if (!ReadFileToString(kProcDevices, &devices)) {
+        PLOG(ERROR) << "Unable to open /proc/devices";
+        return 0;
+    }
+
+    bool blockSection = false;
+    for (auto line : android::base::Split(devices, "\n")) {
+        if (line == "Block devices:") {
+            blockSection = true;
+        } else if (line == "Character devices:") {
+            blockSection = false;
+        } else if (blockSection) {
+            auto tokens = android::base::Split(line, " ");
+            if (tokens.size() == 2 && tokens[1] == "virtblk") {
+                return std::stoul(tokens[0]);
+            }
+        }
+    }
+
+    return 0;
+}
+
+bool IsVirtioBlkDevice(unsigned int major) {
+    // Most virtualized platforms expose block devices with the virtio-blk
+    // block device driver. Unfortunately, this driver does not use a fixed
+    // major number, but relies on the kernel to assign one from a specific
+    // range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
+    // per Documentation/devices.txt. This is true even for the latest Linux
+    // kernel (4.4; see init() in drivers/block/virtio_blk.c).
+    static unsigned int kMajorBlockVirtioBlk = GetMajorBlockVirtioBlk();
+    return kMajorBlockVirtioBlk && major == kMajorBlockVirtioBlk;
 }
 
 static status_t findMountPointsWithPrefix(const std::string& prefix,
diff --git a/Utils.h b/Utils.h
index af4e401..661443b 100644
--- a/Utils.h
+++ b/Utils.h
@@ -133,8 +133,8 @@
 // TODO: promote to android::base
 bool Readlinkat(int dirfd, const std::string& path, std::string* result);
 
-/* Checks if Android is running in QEMU */
-bool IsRunningInEmulator();
+// Handles dynamic major assignment for virtio-block
+bool IsVirtioBlkDevice(unsigned int major);
 
 status_t UnmountTreeWithPrefix(const std::string& prefix);
 status_t UnmountTree(const std::string& mountPoint);
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index 800d602..be8e67c 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -26,6 +26,7 @@
 #include "MetadataCrypt.h"
 #include "MoveStorage.h"
 #include "Process.h"
+#include "VoldNativeServiceValidation.h"
 #include "VoldUtil.h"
 #include "VolumeManager.h"
 #include "cryptfs.h"
@@ -45,6 +46,7 @@
 
 using android::base::StringPrintf;
 using std::endl;
+using namespace std::literals;
 
 namespace android {
 namespace vold {
@@ -53,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()));
@@ -82,77 +76,9 @@
     }
 }
 
-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("/../") != 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_SYSTEM_OR_ROOT                              \
     {                                                       \
-        binder::Status status = checkUidOrRoot(AID_SYSTEM); \
+        binder::Status status = CheckUidOrRoot(AID_SYSTEM); \
         if (!status.isOk()) {                               \
             return status;                                  \
         }                                                   \
@@ -160,7 +86,7 @@
 
 #define CHECK_ARGUMENT_ID(id)                          \
     {                                                  \
-        binder::Status status = checkArgumentId((id)); \
+        binder::Status status = CheckArgumentId((id)); \
         if (!status.isOk()) {                          \
             return status;                             \
         }                                              \
@@ -168,7 +94,7 @@
 
 #define CHECK_ARGUMENT_PATH(path)                          \
     {                                                      \
-        binder::Status status = checkArgumentPath((path)); \
+        binder::Status status = CheckArgumentPath((path)); \
         if (!status.isOk()) {                              \
             return status;                                 \
         }                                                  \
@@ -176,7 +102,7 @@
 
 #define CHECK_ARGUMENT_HEX(hex)                          \
     {                                                    \
-        binder::Status status = checkArgumentHex((hex)); \
+        binder::Status status = CheckArgumentHex((hex)); \
         if (!status.isOk()) {                            \
             return status;                               \
         }                                                \
@@ -206,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;
@@ -214,7 +140,6 @@
 
     ACQUIRE_LOCK;
     out << "vold is happy!" << endl;
-    out.flush();
     return NO_ERROR;
 }
 
@@ -224,7 +149,7 @@
     ACQUIRE_LOCK;
 
     VolumeManager::Instance()->setListener(listener);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::monitor() {
@@ -234,7 +159,7 @@
     { ACQUIRE_LOCK; }
     { ACQUIRE_CRYPT_LOCK; }
 
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::reset() {
@@ -281,12 +206,12 @@
 
 binder::Status VoldNativeService::addAppIds(const std::vector<std::string>& packageNames,
                                             const std::vector<int32_t>& appIds) {
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::addSandboxIds(const std::vector<int32_t>& appIds,
                                                 const std::vector<std::string>& sandboxIds) {
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
@@ -398,7 +323,7 @@
             return error("Volume " + volId + " missing path");
         }
     }
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::benchmark(
@@ -412,7 +337,7 @@
     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) {
@@ -443,7 +368,7 @@
     }
 
     std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
@@ -510,7 +435,7 @@
     ACQUIRE_LOCK;
 
     std::thread([=]() { android::vold::Trim(listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::runIdleMaint(
@@ -519,7 +444,7 @@
     ACQUIRE_LOCK;
 
     std::thread([=]() { android::vold::RunIdleMaint(listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::abortIdleMaint(
@@ -528,7 +453,7 @@
     ACQUIRE_LOCK;
 
     std::thread([=]() { android::vold::AbortIdleMaint(listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::mountAppFuse(int32_t uid, int32_t mountId,
@@ -560,7 +485,7 @@
     }
 
     *_aidl_return = android::base::unique_fd(fd);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
@@ -577,7 +502,7 @@
     // 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) {
@@ -585,7 +510,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_crypto_complete();
-    return ok();
+    return Ok();
 }
 
 static int fdeEnableInternal(int32_t passwordType, const std::string& password,
@@ -625,7 +550,7 @@
     // 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,
@@ -652,7 +577,7 @@
         return error(StringPrintf("Failed to read field %s", key.c_str()));
     } else {
         *_aidl_return = buf;
-        return ok();
+        return Ok();
     }
 }
 
@@ -668,7 +593,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_get_password_type();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeGetPassword(std::string* _aidl_return) {
@@ -679,7 +604,7 @@
     if (res != nullptr) {
         *_aidl_return = res;
     }
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeClearPassword() {
@@ -687,7 +612,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     cryptfs_clear_password();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fbeEnable() {
@@ -706,7 +631,7 @@
         // 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() {
@@ -721,7 +646,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_isConvertibleToFBE() != 0;
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::mountFstab(const std::string& blkDevice,
@@ -821,13 +746,13 @@
 binder::Status VoldNativeService::prepareSandboxForApp(const std::string& packageName,
                                                        int32_t appId, const std::string& sandboxId,
                                                        int32_t userId) {
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::destroySandboxForApp(const std::string& packageName,
                                                        const std::string& sandboxId,
                                                        int32_t userId) {
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::startCheckpoint(int32_t retry) {
@@ -842,7 +767,7 @@
     ACQUIRE_LOCK;
 
     *_aidl_return = cp_needsRollback();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
@@ -850,7 +775,15 @@
     ACQUIRE_LOCK;
 
     *_aidl_return = cp_needsCheckpoint();
-    return ok();
+    return Ok();
+}
+
+binder::Status VoldNativeService::isCheckpointing(bool* _aidl_return) {
+    ENFORCE_SYSTEM_OR_ROOT;
+    ACQUIRE_LOCK;
+
+    *_aidl_return = cp_isCheckpointing();
+    return Ok();
 }
 
 binder::Status VoldNativeService::commitChanges() {
@@ -895,7 +828,7 @@
     ACQUIRE_LOCK;
 
     cp_abortChanges(message, retry);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
@@ -924,39 +857,54 @@
     ACQUIRE_LOCK;
 
     cp_resetCheckpoint();
-    return ok();
+    return Ok();
 }
 
-binder::Status VoldNativeService::incFsVersion(int32_t* _aidl_return) {
-    *_aidl_return = IncFs_Version();
-    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& imagePath, const std::string& targetDir, int32_t flags,
+        const std::string& backingPath, const std::string& targetDir, int32_t flags,
         ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) {
-    auto result = IncFs_Mount(imagePath.c_str(), targetDir.c_str(), flags,
-                              INCFS_DEFAULT_READ_TIMEOUT_MS, 0777);
-    if (result.cmdFd < 0) {
-        return translate(result.cmdFd);
+    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);
     }
-    LOG(INFO) << "VoldNativeService::mountIncFs: everything is fine! " << result.cmdFd << "/"
-              << result.logFd;
-    using ParcelFileDescriptor = ::android::os::ParcelFileDescriptor;
     using unique_fd = ::android::base::unique_fd;
-    _aidl_return->cmd = ParcelFileDescriptor(unique_fd(result.cmdFd));
-    if (result.logFd >= 0) {
-        _aidl_return->log = ParcelFileDescriptor(unique_fd(result.logFd));
+    _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)));
     }
-    return ok();
+    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()));
 }
 
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 213c48d..7065b04 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -133,6 +133,7 @@
     binder::Status startCheckpoint(int32_t retry);
     binder::Status needsCheckpoint(bool* _aidl_return);
     binder::Status needsRollback(bool* _aidl_return);
+    binder::Status isCheckpointing(bool* _aidl_return);
     binder::Status commitChanges();
     binder::Status prepareCheckpoint();
     binder::Status restoreCheckpoint(const std::string& mountPoint);
@@ -144,9 +145,9 @@
     binder::Status supportsFileCheckpoint(bool* _aidl_return);
     binder::Status resetCheckpoint();
 
-    binder::Status incFsVersion(int32_t* _aidl_return) override;
+    binder::Status incFsEnabled(bool* _aidl_return) override;
     binder::Status mountIncFs(
-            const std::string& imagePath, const std::string& targetDir, int32_t flags,
+            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;
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/VolumeManager.cpp b/VolumeManager.cpp
index f860eef..9f151ea 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -78,6 +78,7 @@
 using android::vold::CreateDir;
 using android::vold::DeleteDirContents;
 using android::vold::DeleteDirContentsAndDir;
+using android::vold::IsVirtioBlkDevice;
 using android::vold::Symlink;
 using android::vold::Unlink;
 using android::vold::UnmountTree;
@@ -94,8 +95,6 @@
 static const unsigned int kSizeVirtualDisk = 536870912;
 
 static const unsigned int kMajorBlockMmc = 179;
-static const unsigned int kMajorBlockExperimentalMin = 240;
-static const unsigned int kMajorBlockExperimentalMax = 254;
 
 VolumeManager* VolumeManager::sInstance = NULL;
 
@@ -214,12 +213,10 @@
             for (const auto& source : mDiskSources) {
                 if (source->matches(eventPath)) {
                     // For now, assume that MMC and virtio-blk (the latter is
-                    // emulator-specific; see Disk.cpp for details) devices are SD,
-                    // and that everything else is USB
+                    // specific to virtual platforms; see Utils.cpp for details)
+                    // devices are SD, and that everything else is USB
                     int flags = source->getFlags();
-                    if (major == kMajorBlockMmc || (android::vold::IsRunningInEmulator() &&
-                                                    major >= (int)kMajorBlockExperimentalMin &&
-                                                    major <= (int)kMajorBlockExperimentalMax)) {
+                    if (major == kMajorBlockMmc || IsVirtioBlkDevice(major)) {
                         flags |= android::vold::Disk::Flags::kSd;
                     } else {
                         flags |= android::vold::Disk::Flags::kUsb;
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index a454bd1..12c00e4 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -110,6 +110,7 @@
     void startCheckpoint(int retry);
     boolean needsCheckpoint();
     boolean needsRollback();
+    boolean isCheckpointing();
     void abortChanges(in @utf8InCpp String device, boolean retry);
     void commitChanges();
     void prepareCheckpoint();
@@ -128,8 +129,8 @@
 
     FileDescriptor openAppFuseFile(int uid, int mountId, int fileId, int flags);
 
-    int incFsVersion();
-    IncrementalFileSystemControlParcel mountIncFs(@utf8InCpp String imagePath, @utf8InCpp String targetDir, 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);
 
diff --git a/cryptfs.cpp b/cryptfs.cpp
index 7bcd835..c2c5936 100644
--- a/cryptfs.cpp
+++ b/cryptfs.cpp
@@ -32,6 +32,7 @@
 #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>
@@ -54,6 +55,7 @@
 #include <libgen.h>
 #include <linux/kdev_t.h>
 #include <math.h>
+#include <mntent.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -1380,8 +1382,46 @@
     return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
 }
 
+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 */
diff --git a/fs/Ext4.cpp b/fs/Ext4.cpp
index 8bb930d..6bc7ad2 100644
--- a/fs/Ext4.cpp
+++ b/fs/Ext4.cpp
@@ -171,8 +171,9 @@
     cmd.push_back("-M");
     cmd.push_back(target);
 
-    bool needs_casefold = android::base::GetBoolProperty("ro.emulated_storage.casefold", false);
-    bool needs_projid = android::base::GetBoolProperty("ro.emulated_storage.projid", false);
+    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");
diff --git a/fs/F2fs.cpp b/fs/F2fs.cpp
index 9517dc9..a615082 100644
--- a/fs/F2fs.cpp
+++ b/fs/F2fs.cpp
@@ -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/fscrypt_uapi.h b/fscrypt_uapi.h
index 08592e0..3cda96e 100644
--- a/fscrypt_uapi.h
+++ b/fscrypt_uapi.h
@@ -9,11 +9,19 @@
 struct sys_fscrypt_add_key_arg {
     struct fscrypt_key_specifier key_spec;
     __u32 raw_size;
-    __u32 __reserved[8];
+    __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/main.cpp b/main.cpp
index ebe5510..1f85fb5 100644
--- a/main.cpp
+++ b/main.cpp
@@ -41,8 +41,14 @@
 #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);
 
@@ -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
@@ -213,8 +217,7 @@
     }
 }
 
-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");
 
     if (!ReadDefaultFstab(&fstab_default)) {
@@ -223,19 +226,24 @@
     }
 
     /* Loop through entries looking for ones that vold manages */
-    *has_adoptable = false;
-    *has_quota = false;
-    *has_reserved = false;
+    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) {
-            *has_quota = true;
+            configs->has_quota = true;
         }
         if (entry.reserved_size > 0) {
-            *has_reserved = true;
+            configs->has_reserved = true;
+        }
+        if (entry.fs_mgr_flags.fs_compress) {
+            configs->has_compress = true;
         }
 
         /* Make sure logical partitions have an updated blk_device. */
-        if (entry.fs_mgr_flags.logical && !fs_mgr_update_logical_partition(&entry)) {
+        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;
         }
 
@@ -251,7 +259,7 @@
 
             if (entry.is_encryptable()) {
                 flags |= android::vold::Disk::Flags::kAdoptable;
-                *has_adoptable = true;
+                configs->has_adoptable = true;
             }
             if (entry.fs_mgr_flags.no_emulated_sd ||
                 android::base::GetBoolProperty("vold.debug.default_primary", false)) {
diff --git a/model/Disk.cpp b/model/Disk.cpp
index 6a6585e..09dc360 100644
--- a/model/Disk.cpp
+++ b/model/Disk.cpp
@@ -73,8 +73,6 @@
 static const unsigned int kMajorBlockScsiO = 134;
 static const unsigned int kMajorBlockScsiP = 135;
 static const unsigned int kMajorBlockMmc = 179;
-static const unsigned int kMajorBlockExperimentalMin = 240;
-static const unsigned int kMajorBlockExperimentalMax = 254;
 static const unsigned int kMajorBlockDynamicMin = 234;
 static const unsigned int kMajorBlockDynamicMax = 512;
 
@@ -88,33 +86,6 @@
     kGpt,
 };
 
-static bool isVirtioBlkDevice(unsigned int major) {
-    /*
-     * The new emulator's "ranchu" virtual board no longer includes a goldfish
-     * MMC-based SD card device; instead, it emulates SD cards with virtio-blk,
-     * which has been supported by upstream kernel and QEMU for quite a while.
-     * Unfortunately, the virtio-blk block device driver does not use a fixed
-     * major number, but relies on the kernel to assign one from a specific
-     * range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
-     * per Documentation/devices.txt. This is true even for the latest Linux
-     * kernel (4.4; see init() in drivers/block/virtio_blk.c).
-     *
-     * This makes it difficult for vold to detect a virtio-blk based SD card.
-     * The current solution checks two conditions (both must be met):
-     *
-     *  a) If the running environment is the emulator;
-     *  b) If the major number is an experimental block device major number (for
-     *     x86/x86_64 3.10 ranchu kernels, virtio-blk always gets major number
-     *     253, but it is safer to match the range than just one value).
-     *
-     * Other conditions could be used, too, e.g. the hardware name should be
-     * "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc.
-     * But just having a) and b) is enough for now.
-     */
-    return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin &&
-           major <= kMajorBlockExperimentalMax;
-}
-
 static bool isNvmeBlkDevice(unsigned int major, const std::string& sysPath) {
     return sysPath.find("nvme") != std::string::npos && major >= kMajorBlockDynamicMin &&
            major <= kMajorBlockDynamicMax;
@@ -298,7 +269,7 @@
             break;
         }
         default: {
-            if (isVirtioBlkDevice(majorId)) {
+            if (IsVirtioBlkDevice(majorId)) {
                 LOG(DEBUG) << "Recognized experimental block major ID " << majorId
                            << " as virtio-blk (emulator's virtual SD card device)";
                 mLabel = "Virtual";
@@ -597,7 +568,7 @@
             return std::stoi(tmp);
         }
         default: {
-            if (isVirtioBlkDevice(majorId)) {
+            if (IsVirtioBlkDevice(majorId)) {
                 // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is
                 // 2^4 - 1 = 15
                 return 15;
diff --git a/model/PrivateVolume.cpp b/model/PrivateVolume.cpp
index fd3daea..ba221a4 100644
--- a/model/PrivateVolume.cpp
+++ b/model/PrivateVolume.cpp
@@ -38,6 +38,7 @@
 #include <sys/wait.h>
 
 using android::base::StringPrintf;
+using android::vold::IsVirtioBlkDevice;
 
 namespace android {
 namespace vold {
@@ -178,7 +179,8 @@
     if (fsType == "auto") {
         // For now, assume that all MMC devices are flash-based SD cards, and
         // give everyone else ext4 because sysfs rotational isn't reliable.
-        if ((major(mRawDevice) == kMajorBlockMmc) && f2fs::IsSupported()) {
+        if ((major(mRawDevice) == kMajorBlockMmc ||
+             IsVirtioBlkDevice(major(mRawDevice))) && f2fs::IsSupported()) {
             resolvedFsType = "f2fs";
         } else {
             resolvedFsType = "ext4";
diff --git a/tests/Android.bp b/tests/Android.bp
index 4731d0a..b90de3a 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -7,7 +7,9 @@
 
     srcs: [
         "Utils_test.cpp",
+        "VoldNativeServiceValidation_test.cpp",
         "cryptfs_test.cpp",
     ],
     static_libs: ["libvold"],
+    shared_libs: ["libbinder"]
 }
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