Merge "Record use of metadata encryption in property" into rvc-dev
diff --git a/Android.bp b/Android.bp
index c2f8936..b033647 100644
--- a/Android.bp
+++ b/Android.bp
@@ -131,6 +131,7 @@
         "ScryptParameters.cpp",
         "Utils.cpp",
         "VoldNativeService.cpp",
+        "VoldNativeServiceValidation.cpp",
         "VoldUtil.cpp",
         "VolumeManager.cpp",
         "cryptfs.cpp",
@@ -150,12 +151,10 @@
     product_variables: {
         arc: {
             exclude_srcs: [
-                "AppFuseUtil.cpp",
                 "model/ObbVolume.cpp",
             ],
             static_libs: [
                 "arc_services_aidl",
-                "libarcappfuse",
                 "libarcobbvolume",
             ],
         },
@@ -185,7 +184,6 @@
         arc: {
             static_libs: [
                 "arc_services_aidl",
-                "libarcappfuse",
                 "libarcobbvolume",
             ],
         },
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 3359699..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
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 4a9ed02..d9ced91 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:
     sp<KmDevice> mDevice;
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index 8bc8beb..0a34007 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();
 
@@ -287,25 +283,30 @@
         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();
diff --git a/Utils.cpp b/Utils.cpp
index 1e20d75..b129990 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -77,6 +77,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";
 
 static const char* kAndroidDir = "/Android/";
@@ -1103,8 +1104,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 5e6ff1b..e04dcaa 100644
--- a/Utils.h
+++ b/Utils.h
@@ -155,8 +155,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 57cee23..1020526 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -18,23 +18,6 @@
 
 #include "VoldNativeService.h"
 
-#include "Benchmark.h"
-#include "CheckEncryption.h"
-#include "Checkpoint.h"
-#include "FsCrypt.h"
-#include "IdleMaint.h"
-#include "MetadataCrypt.h"
-#include "MoveStorage.h"
-#include "Process.h"
-#include "VoldUtil.h"
-#include "VolumeManager.h"
-#include "cryptfs.h"
-
-#include "incfs_ndk.h"
-
-#include <fstream>
-#include <thread>
-
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
@@ -43,8 +26,26 @@
 #include <private/android_filesystem_config.h>
 #include <utils/Trace.h>
 
+#include <fstream>
+#include <thread>
+
+#include "Benchmark.h"
+#include "CheckEncryption.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.h"
+
 using android::base::StringPrintf;
 using std::endl;
+using namespace std::literals;
 
 namespace android {
 namespace vold {
@@ -53,14 +54,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 +75,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 != ',' && 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 +85,7 @@
 
 #define CHECK_ARGUMENT_ID(id)                          \
     {                                                  \
-        binder::Status status = checkArgumentId((id)); \
+        binder::Status status = CheckArgumentId((id)); \
         if (!status.isOk()) {                          \
             return status;                             \
         }                                              \
@@ -168,7 +93,7 @@
 
 #define CHECK_ARGUMENT_PATH(path)                          \
     {                                                      \
-        binder::Status status = checkArgumentPath((path)); \
+        binder::Status status = CheckArgumentPath((path)); \
         if (!status.isOk()) {                              \
             return status;                                 \
         }                                                  \
@@ -176,7 +101,7 @@
 
 #define CHECK_ARGUMENT_HEX(hex)                          \
     {                                                    \
-        binder::Status status = checkArgumentHex((hex)); \
+        binder::Status status = CheckArgumentHex((hex)); \
         if (!status.isOk()) {                            \
             return status;                               \
         }                                                \
@@ -206,7 +131,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,17 +139,16 @@
 
     ACQUIRE_LOCK;
     out << "vold is happy!" << endl;
-    out.flush();
     return NO_ERROR;
 }
 
 binder::Status VoldNativeService::setListener(
-    const android::sp<android::os::IVoldListener>& listener) {
+        const android::sp<android::os::IVoldListener>& listener) {
     ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_LOCK;
 
     VolumeManager::Instance()->setListener(listener);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::monitor() {
@@ -234,7 +158,7 @@
     { ACQUIRE_LOCK; }
     { ACQUIRE_CRYPT_LOCK; }
 
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::reset() {
@@ -281,12 +205,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) {
@@ -403,11 +327,11 @@
             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) {
+        const std::string& volId, const android::sp<android::os::IVoldTaskListener>& listener) {
     ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(volId);
     ACQUIRE_LOCK;
@@ -417,7 +341,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) {
@@ -432,8 +356,8 @@
 }
 
 binder::Status VoldNativeService::moveStorage(
-    const std::string& fromVolId, const std::string& toVolId,
-    const android::sp<android::os::IVoldTaskListener>& listener) {
+        const std::string& fromVolId, const std::string& toVolId,
+        const android::sp<android::os::IVoldTaskListener>& listener) {
     ENFORCE_SYSTEM_OR_ROOT;
     CHECK_ARGUMENT_ID(fromVolId);
     CHECK_ARGUMENT_ID(toVolId);
@@ -448,7 +372,7 @@
     }
 
     std::thread([=]() { android::vold::MoveStorage(fromVol, toVol, listener); }).detach();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::remountUid(int32_t uid, int32_t remountMode) {
@@ -491,7 +415,7 @@
     ACQUIRE_LOCK;
 
     return translate(
-        VolumeManager::Instance()->createObb(sourcePath, sourceKey, ownerGid, _aidl_return));
+            VolumeManager::Instance()->createObb(sourcePath, sourceKey, ownerGid, _aidl_return));
 }
 
 binder::Status VoldNativeService::destroyObb(const std::string& volId) {
@@ -529,30 +453,30 @@
 }
 
 binder::Status VoldNativeService::fstrim(
-    int32_t fstrimFlags, const android::sp<android::os::IVoldTaskListener>& listener) {
+        int32_t fstrimFlags, const android::sp<android::os::IVoldTaskListener>& listener) {
     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) {
+        const android::sp<android::os::IVoldTaskListener>& listener) {
     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) {
+        const android::sp<android::os::IVoldTaskListener>& listener) {
     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,
@@ -584,7 +508,7 @@
     }
 
     *_aidl_return = android::base::unique_fd(fd);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeCheckPassword(const std::string& password) {
@@ -601,7 +525,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) {
@@ -609,7 +533,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_crypto_complete();
-    return ok();
+    return Ok();
 }
 
 static int fdeEnableInternal(int32_t passwordType, const std::string& password,
@@ -649,7 +573,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,
@@ -676,7 +600,7 @@
         return error(StringPrintf("Failed to read field %s", key.c_str()));
     } else {
         *_aidl_return = buf;
-        return ok();
+        return Ok();
     }
 }
 
@@ -692,7 +616,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_get_password_type();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeGetPassword(std::string* _aidl_return) {
@@ -703,7 +627,7 @@
     if (res != nullptr) {
         *_aidl_return = res;
     }
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fdeClearPassword() {
@@ -711,7 +635,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     cryptfs_clear_password();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::fbeEnable() {
@@ -730,7 +654,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() {
@@ -745,7 +669,7 @@
     ACQUIRE_CRYPT_LOCK;
 
     *_aidl_return = cryptfs_isConvertibleToFBE() != 0;
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::mountFstab(const std::string& blkDevice,
@@ -764,7 +688,8 @@
     return translateBool(fscrypt_mount_metadata_encrypted(blkDevice, mountPoint, true));
 }
 
-binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial, bool ephemeral) {
+binder::Status VoldNativeService::createUserKey(int32_t userId, int32_t userSerial,
+                                                bool ephemeral) {
     ENFORCE_SYSTEM_OR_ROOT;
     ACQUIRE_CRYPT_LOCK;
 
@@ -845,13 +770,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) {
@@ -866,7 +791,7 @@
     ACQUIRE_LOCK;
 
     *_aidl_return = cp_needsRollback();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::needsCheckpoint(bool* _aidl_return) {
@@ -874,7 +799,7 @@
     ACQUIRE_LOCK;
 
     *_aidl_return = cp_needsCheckpoint();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::commitChanges() {
@@ -919,7 +844,7 @@
     ACQUIRE_LOCK;
 
     cp_abortChanges(message, retry);
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::supportsCheckpoint(bool* _aidl_return) {
@@ -948,40 +873,78 @@
     ACQUIRE_LOCK;
 
     cp_resetCheckpoint();
-    return ok();
+    return Ok();
 }
 
 binder::Status VoldNativeService::incFsEnabled(bool* _aidl_return) {
-    *_aidl_return = IncFs_IsEnabled();
-    return ok();
+    ENFORCE_SYSTEM_OR_ROOT;
+
+    *_aidl_return = incfs::enabled();
+    return Ok();
 }
 
 binder::Status VoldNativeService::mountIncFs(
         const std::string& backingPath, const std::string& targetDir, int32_t flags,
         ::android::os::incremental::IncrementalFileSystemControlParcel* _aidl_return) {
-    auto result = IncFs_Mount(backingPath.c_str(), targetDir.c_str(),
-                              {.flags = IncFsMountFlags(flags),
-                               .defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
-                               .readLogBufferPages = 4});
-    if (result.cmd < 0) {
-        return translate(result.cmd);
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(backingPath);
+    CHECK_ARGUMENT_PATH(targetDir);
+
+    auto control = incfs::mount(backingPath, targetDir,
+                                {.flags = IncFsMountFlags(flags),
+                                 .defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
+                                 // Mount with read logs disabled.
+                                 .readLogBufferPages = 0});
+    if (!control) {
+        return translate(-errno);
     }
-    using unique_fd = ::android::base::unique_fd;
-    _aidl_return->cmd.reset(unique_fd(result.cmd));
-    _aidl_return->pendingReads.reset(unique_fd(result.pendingReads));
-    if (result.logs >= 0) {
-        _aidl_return->log.reset(unique_fd(result.logs));
-    }
-    return ok();
+    auto fds = control.releaseFds();
+    using android::base::unique_fd;
+    _aidl_return->cmd.reset(unique_fd(fds[CMD].release()));
+    _aidl_return->pendingReads.reset(unique_fd(fds[PENDING_READS].release()));
+    _aidl_return->log.reset(unique_fd(fds[LOGS].release()));
+    return Ok();
 }
 
 binder::Status VoldNativeService::unmountIncFs(const std::string& dir) {
-    return translate(IncFs_Unmount(dir.c_str()));
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(dir);
+
+    return translate(incfs::unmount(dir));
+}
+
+binder::Status VoldNativeService::setIncFsMountOptions(
+        const ::android::os::incremental::IncrementalFileSystemControlParcel& control,
+        bool enableReadLogs) {
+    ENFORCE_SYSTEM_OR_ROOT;
+
+    auto incfsControl =
+            incfs::createControl(control.cmd.get(), control.pendingReads.get(), control.log.get());
+    auto cleanupFunc = [](auto incfsControl) {
+        for (auto& fd : incfsControl->releaseFds()) {
+            (void)fd.release();
+        }
+    };
+    auto cleanup =
+            std::unique_ptr<incfs::Control, decltype(cleanupFunc)>(&incfsControl, cleanupFunc);
+    if (auto error = incfs::setOptions(
+                incfsControl,
+                {.defaultReadTimeoutMs = INCFS_DEFAULT_READ_TIMEOUT_MS,
+                 .readLogBufferPages = enableReadLogs ? INCFS_DEFAULT_PAGE_READ_BUFFER_PAGES : 0});
+        error < 0) {
+        return binder::Status::fromServiceSpecificError(error);
+    }
+
+    return Ok();
 }
 
 binder::Status VoldNativeService::bindMount(const std::string& sourceDir,
                                             const std::string& targetDir) {
-    return translate(IncFs_BindMount(sourceDir.c_str(), targetDir.c_str()));
+    ENFORCE_SYSTEM_OR_ROOT;
+    CHECK_ARGUMENT_PATH(sourceDir);
+    CHECK_ARGUMENT_PATH(targetDir);
+
+    return translate(incfs::bindMount(sourceDir, targetDir));
 }
 
 }  // namespace vold
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 2f4b6eb..060d704 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -154,6 +154,9 @@
             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 setIncFsMountOptions(
+            const ::android::os::incremental::IncrementalFileSystemControlParcel& control,
+            bool enableReadLogs) 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..ee1e65a
--- /dev/null
+++ b/VoldNativeServiceValidation.cpp
@@ -0,0 +1,108 @@
+/*
+ * 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) {
+    int32_t pid;
+    int32_t uid;
+
+    if (checkCallingPermission(String16(permission), &pid, &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 != ',' && 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 6a40a52..f64f5f6 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -19,6 +19,7 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <limits.h>
 #include <mntent.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -82,6 +83,7 @@
 using android::vold::DeleteDirContentsAndDir;
 using android::vold::EnsureDirExists;
 using android::vold::IsFilesystemSupported;
+using android::vold::IsVirtioBlkDevice;
 using android::vold::PrepareAndroidDirs;
 using android::vold::PrepareAppDirFromRoot;
 using android::vold::PrivateVolume;
@@ -102,8 +104,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;
 
 using ScanProcCallback = bool(*)(uid_t uid, pid_t pid, int nsFd, const char* name, void* params);
 
@@ -230,12 +230,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;
@@ -739,8 +737,10 @@
 }
 
 
-// Set the namespace the app process and remount its storage directories.
-static bool remountStorageDirs(int nsFd, const char* sources[], const char* targets[], int size) {
+// In each app's namespace, mount tmpfs on obb and data dir, and bind mount obb and data
+// package dirs.
+static bool remountStorageDirs(int nsFd, const char* android_data_dir, const char* android_obb_dir,
+        int uid, const char* sources[], const char* targets[], int size) {
     // This code is executed after a fork so it's very important that the set of
     // methods we call here is strictly limited.
     if (setns(nsFd, CLONE_NEWNS) != 0) {
@@ -748,7 +748,27 @@
         return false;
     }
 
+    // Mount tmpfs on Android/data and Android/obb
+    if (TEMP_FAILURE_RETRY(mount("tmpfs", android_data_dir, "tmpfs",
+            MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
+        async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
+                        android_data_dir, strerror(errno));
+        return false;
+    }
+    if (TEMP_FAILURE_RETRY(mount("tmpfs", android_obb_dir, "tmpfs",
+            MS_NOSUID | MS_NODEV | MS_NOEXEC, "uid=0,gid=0,mode=0751")) == -1) {
+        async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount tmpfs to %s :%s",
+                android_obb_dir, strerror(errno));
+        return false;
+    }
+
     for (int i = 0; i < size; i++) {
+        // Create package dir and bind mount it to the actual one.
+        if (TEMP_FAILURE_RETRY(mkdir(targets[i], 0700)) == -1) {
+            async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mkdir %s %s",
+                    targets[i], strerror(errno));
+            return false;
+        }
         if (TEMP_FAILURE_RETRY(mount(sources[i], targets[i], NULL, MS_BIND | MS_REC, NULL)) == -1) {
             async_safe_format_log(ANDROID_LOG_ERROR, "vold", "Failed to mount %s to %s :%s",
                                   sources[i], targets[i], strerror(errno));
@@ -776,7 +796,8 @@
 }
 
 // Fork the process and remount storage
-static bool forkAndRemountStorage(int uid, int pid, const std::vector<std::string>& packageNames) {
+bool VolumeManager::forkAndRemountStorage(int uid, int pid,
+                                          const std::vector<std::string>& packageNames) {
     userid_t userId = multiuser_get_user_id(uid);
     std::string mnt_path = StringPrintf("/proc/%d/ns/mnt", pid);
     android::base::unique_fd nsFd(
@@ -814,18 +835,25 @@
             PLOG(ERROR) << "Failed to create dir: " << sources_cstr[i];
             return false;
         }
-        status = EnsureDirExists(targets_cstr[i], 0771, AID_MEDIA_RW, AID_MEDIA_RW);
+        // Make sure /storage/emulated/... paths are setup correctly
+        status = setupAppDir(targets_cstr[i], uid, false /* fixupExistingOnly */);
         if (status != OK) {
             PLOG(ERROR) << "Failed to create dir: " << targets_cstr[i];
             return false;
         }
     }
 
+    char android_data_dir[PATH_MAX];
+    char android_obb_dir[PATH_MAX];
+    snprintf(android_data_dir, PATH_MAX, "/storage/emulated/%d/Android/data", userId);
+    snprintf(android_obb_dir, PATH_MAX, "/storage/emulated/%d/Android/obb", userId);
+
     pid_t child;
     // Fork a child to mount Android/obb android Android/data dirs, as we don't want it to affect
     // original vold process mount namespace.
     if (!(child = fork())) {
-        if (remountStorageDirs(nsFd, sources_cstr, targets_cstr, size)) {
+        if (remountStorageDirs(nsFd, android_data_dir, android_obb_dir, uid,
+                sources_cstr, targets_cstr, size)) {
             _exit(0);
         } else {
             _exit(1);
@@ -945,7 +973,7 @@
              !StartsWith(test, "/mnt/scratch") &&
 #endif
              !StartsWith(test, "/mnt/vendor") && !StartsWith(test, "/mnt/product") &&
-             !StartsWith(test, "/mnt/installer")) ||
+             !StartsWith(test, "/mnt/installer") && !StartsWith(test, "/mnt/androidwritable")) ||
             StartsWith(test, "/storage/")) {
             toUnmount.push_front(test);
         }
@@ -1010,6 +1038,12 @@
         return OK;
     }
 
+    if (volume->getType() == VolumeBase::Type::kPublic) {
+        // On public volumes, we don't need to setup permissions, as everything goes through
+        // FUSE; just create the dirs and be done with it.
+        return fs_mkdirs(lowerPath.c_str(), 0700);
+    }
+
     // Create the app paths we need from the root
     return PrepareAppDirFromRoot(lowerPath, volumeRoot, appUid, fixupExistingOnly);
 }
diff --git a/VolumeManager.h b/VolumeManager.h
index b83871e..a9087fd 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -130,6 +130,8 @@
     int updateVirtualDisk();
     int setDebug(bool enable);
 
+    bool forkAndRemountStorage(int uid, int pid, const std::vector<std::string>& packageNames);
+
     static VolumeManager* Instance();
 
     /*
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index 1d5657f..68e2ba9 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -135,6 +135,7 @@
     boolean incFsEnabled();
     IncrementalFileSystemControlParcel mountIncFs(@utf8InCpp String backingPath, @utf8InCpp String targetDir, int flags);
     void unmountIncFs(@utf8InCpp String dir);
+    void setIncFsMountOptions(in IncrementalFileSystemControlParcel control, boolean enableReadLogs);
     void bindMount(@utf8InCpp String sourceDir, @utf8InCpp String targetDir);
 
     const int ENCRYPTION_FLAG_NO_UI = 4;
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 ee39f2b..9b8d2c4 100644
--- a/fs/F2fs.cpp
+++ b/fs/F2fs.cpp
@@ -90,8 +90,9 @@
     cmd.push_back("verity");
 
     const bool needs_casefold =
-            android::base::GetBoolProperty("ro.emulated_storage.casefold", false);
-    const bool needs_projid = android::base::GetBoolProperty("ro.emulated_storage.projid", false);
+            android::base::GetBoolProperty("external_storage.casefold.enabled", false);
+    const bool needs_projid =
+            android::base::GetBoolProperty("external_storage.projid.enabled", false);
     if (needs_projid) {
         cmd.push_back("-O");
         cmd.push_back("project_quota,extra_attr");
diff --git a/model/Disk.cpp b/model/Disk.cpp
index a4324db..4df4e9d 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;
@@ -322,7 +293,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";
@@ -627,7 +598,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/EmulatedVolume.cpp b/model/EmulatedVolume.cpp
index b212c0e..e7cd36e 100644
--- a/model/EmulatedVolume.cpp
+++ b/model/EmulatedVolume.cpp
@@ -22,6 +22,7 @@
 
 #include <android-base/logging.h>
 #include <android-base/properties.h>
+#include <android-base/scopeguard.h>
 #include <android-base/stringprintf.h>
 #include <cutils/fs.h>
 #include <private/android_filesystem_config.h>
@@ -48,7 +49,6 @@
     mRawPath = rawPath;
     mLabel = "emulated";
     mFuseMounted = false;
-    mAndroidMounted = false;
     mUseSdcardFs = IsFilesystemSupported("sdcardfs");
     mAppDataIsolationEnabled = base::GetBoolProperty(kVoldAppDataIsolationEnabled, false);
 }
@@ -60,7 +60,6 @@
     mRawPath = rawPath;
     mLabel = fsUuid;
     mFuseMounted = false;
-    mAndroidMounted = false;
     mUseSdcardFs = IsFilesystemSupported("sdcardfs");
     mAppDataIsolationEnabled = base::GetBoolProperty(kVoldAppDataIsolationEnabled, false);
 }
@@ -78,22 +77,37 @@
 }
 
 // Creates a bind mount from source to target
-static status_t doFuseBindMount(const std::string& source, const std::string& target) {
+static status_t doFuseBindMount(const std::string& source, const std::string& target,
+                                std::list<std::string>& pathsToUnmount) {
     LOG(INFO) << "Bind mounting " << source << " on " << target;
     auto status = BindMount(source, target);
     if (status != OK) {
         return status;
     }
     LOG(INFO) << "Bind mounted " << source << " on " << target;
+    pathsToUnmount.push_front(target);
     return OK;
 }
 
 status_t EmulatedVolume::mountFuseBindMounts() {
-    CHECK(!mAndroidMounted);
-
     std::string androidSource;
     std::string label = getLabel();
     int userId = getMountUserId();
+    std::list<std::string> pathsToUnmount;
+
+    auto unmounter = [&]() {
+        LOG(INFO) << "mountFuseBindMounts() unmount scope_guard running";
+        for (const auto& path : pathsToUnmount) {
+            LOG(INFO) << "Unmounting " << path;
+            auto status = UnmountTree(path);
+            if (status != OK) {
+                LOG(INFO) << "Failed to unmount " << path;
+            } else {
+                LOG(INFO) << "Unmounted " << path;
+            }
+        }
+    };
+    auto unmount_guard = android::base::make_scope_guard(unmounter);
 
     if (mUseSdcardFs) {
         androidSource = StringPrintf("/mnt/runtime/default/%s/%d/Android", label.c_str(), userId);
@@ -105,42 +119,84 @@
     // When app data isolation is enabled, obb/ will be mounted per app, otherwise we should
     // bind mount the whole Android/ to speed up reading.
     if (!mAppDataIsolationEnabled) {
-        std::string androidTarget(
-            StringPrintf("/mnt/user/%d/%s/%d/Android", userId, label.c_str(), userId));
-        status = doFuseBindMount(androidSource, androidTarget);
-    }
+        std::string androidDataSource = StringPrintf("%s/data", androidSource.c_str());
+        std::string androidDataTarget(
+                StringPrintf("/mnt/user/%d/%s/%d/Android/data", userId, label.c_str(), userId));
+        status = doFuseBindMount(androidDataSource, androidDataTarget, pathsToUnmount);
+        if (status != OK) {
+            return status;
+        }
 
-    if (status != OK) {
-        return status;
+        std::string androidObbSource = StringPrintf("%s/obb", androidSource.c_str());
+        std::string androidObbTarget(
+                StringPrintf("/mnt/user/%d/%s/%d/Android/obb", userId, label.c_str(), userId));
+        status = doFuseBindMount(androidObbSource, androidObbTarget, pathsToUnmount);
+        if (status != OK) {
+            return status;
+        }
     }
-    mAndroidMounted = true;
 
     // Installers get the same view as all other apps, with the sole exception that the
     // OBB dirs (Android/obb) are writable to them. On sdcardfs devices, this requires
     // a special bind mount, since app-private and OBB dirs share the same GID, but we
     // only want to give access to the latter.
-    if (!mUseSdcardFs) {
-        return OK;
-    }
-    std::string installerSource(
-            StringPrintf("/mnt/runtime/write/%s/%d/Android/obb", label.c_str(), userId));
-    std::string installerTarget(
-            StringPrintf("/mnt/installer/%d/%s/%d/Android/obb", userId, label.c_str(), userId));
+    if (mUseSdcardFs) {
+        std::string obbSource(StringPrintf("/mnt/runtime/write/%s/%d/Android/obb",
+                label.c_str(), userId));
+        std::string obbInstallerTarget(StringPrintf("/mnt/installer/%d/%s/%d/Android/obb",
+                userId, label.c_str(), userId));
 
-    status = doFuseBindMount(installerSource, installerTarget);
-    if (status != OK) {
-        return status;
+        status = doFuseBindMount(obbSource, obbInstallerTarget, pathsToUnmount);
+        if (status != OK) {
+            return status;
+        }
+    } else if (mAppDataIsolationEnabled) {
+        std::string obbSource(StringPrintf("%s/obb", androidSource.c_str()));
+        std::string obbInstallerTarget(StringPrintf("/mnt/installer/%d/%s/%d/Android/obb",
+                userId, label.c_str(), userId));
+
+        status = doFuseBindMount(obbSource, obbInstallerTarget, pathsToUnmount);
+        if (status != OK) {
+            return status;
+        }
     }
+
+    // /mnt/androidwriteable is similar to /mnt/installer, but it's for
+    // MOUNT_EXTERNAL_ANDROID_WRITABLE apps and it can also access DATA (Android/data) dirs.
+    if (mAppDataIsolationEnabled) {
+        std::string obbSource = mUseSdcardFs ?
+            StringPrintf("/mnt/runtime/write/%s/%d/Android/obb", label.c_str(), userId)
+            : StringPrintf("%s/obb", androidSource.c_str());
+
+        std::string obbAndroidWritableTarget(
+                StringPrintf("/mnt/androidwritable/%d/%s/%d/Android/obb",
+                userId, label.c_str(), userId));
+
+        status = doFuseBindMount(obbSource, obbAndroidWritableTarget, pathsToUnmount);
+        if (status != OK) {
+            return status;
+        }
+
+        std::string dataSource = mUseSdcardFs ?
+                StringPrintf("/mnt/runtime/write/%s/%d/Android/data", label.c_str(), userId)
+                : StringPrintf("%s/data", androidSource.c_str());
+        std::string dataTarget(StringPrintf("/mnt/androidwritable/%d/%s/%d/Android/data",
+                userId, label.c_str(), userId));
+
+        status = doFuseBindMount(dataSource, dataTarget, pathsToUnmount);
+        if (status != OK) {
+            return status;
+        }
+    }
+    unmount_guard.Disable();
     return OK;
 }
 
 status_t EmulatedVolume::unmountFuseBindMounts() {
-    CHECK(mAndroidMounted);
-
     std::string label = getLabel();
     int userId = getMountUserId();
 
-    if (mUseSdcardFs) {
+    if (mUseSdcardFs || mAppDataIsolationEnabled) {
         std::string installerTarget(
                 StringPrintf("/mnt/installer/%d/%s/%d/Android/obb", userId, label.c_str(), userId));
         LOG(INFO) << "Unmounting " << installerTarget;
@@ -150,25 +206,79 @@
             // Intentional continue to try to unmount the other bind mount
         }
     }
+    if (mAppDataIsolationEnabled) {
+        std::string obbTarget( StringPrintf("/mnt/androidwritable/%d/%s/%d/Android/obb",
+                userId, label.c_str(), userId));
+        LOG(INFO) << "Unmounting " << obbTarget;
+        auto status = UnmountTree(obbTarget);
+        if (status != OK) {
+            LOG(ERROR) << "Failed to unmount " << obbTarget;
+            // Intentional continue to try to unmount the other bind mount
+        }
+        std::string dataTarget(StringPrintf("/mnt/androidwritable/%d/%s/%d/Android/data",
+                userId, label.c_str(), userId));
+        LOG(INFO) << "Unmounting " << dataTarget;
+        status = UnmountTree(dataTarget);
+        if (status != OK) {
+            LOG(ERROR) << "Failed to unmount " << dataTarget;
+            // Intentional continue to try to unmount the other bind mount
+        }
+    }
+
     // When app data isolation is enabled, kill all apps that obb/ is mounted, otherwise we should
     // umount the whole Android/ dir.
     if (mAppDataIsolationEnabled) {
         std::string appObbDir(StringPrintf("%s/%d/Android/obb", getPath().c_str(), userId));
         KillProcessesWithMountPrefix(appObbDir);
     } else {
-        std::string androidTarget(
-                StringPrintf("/mnt/user/%d/%s/%d/Android", userId, label.c_str(), userId));
+        std::string androidDataTarget(
+                StringPrintf("/mnt/user/%d/%s/%d/Android/data", userId, label.c_str(), userId));
 
-        LOG(INFO) << "Unmounting " << androidTarget;
-        auto status = UnmountTree(androidTarget);
+        LOG(INFO) << "Unmounting " << androidDataTarget;
+        auto status = UnmountTree(androidDataTarget);
         if (status != OK) {
             return status;
         }
-        LOG(INFO) << "Unmounted " << androidTarget;
+        LOG(INFO) << "Unmounted " << androidDataTarget;
+
+        std::string androidObbTarget(
+                StringPrintf("/mnt/user/%d/%s/%d/Android/obb", userId, label.c_str(), userId));
+
+        LOG(INFO) << "Unmounting " << androidObbTarget;
+        status = UnmountTree(androidObbTarget);
+        if (status != OK) {
+            return status;
+        }
+        LOG(INFO) << "Unmounted " << androidObbTarget;
     }
     return OK;
 }
 
+status_t EmulatedVolume::unmountSdcardFs() {
+    if (!mUseSdcardFs || getMountUserId() != 0) {
+        // For sdcardfs, only unmount for user 0, since user 0 will always be running
+        // and the paths don't change for different users.
+        return OK;
+    }
+
+    ForceUnmount(mSdcardFsDefault);
+    ForceUnmount(mSdcardFsRead);
+    ForceUnmount(mSdcardFsWrite);
+    ForceUnmount(mSdcardFsFull);
+
+    rmdir(mSdcardFsDefault.c_str());
+    rmdir(mSdcardFsRead.c_str());
+    rmdir(mSdcardFsWrite.c_str());
+    rmdir(mSdcardFsFull.c_str());
+
+    mSdcardFsDefault.clear();
+    mSdcardFsRead.clear();
+    mSdcardFsWrite.clear();
+    mSdcardFsFull.clear();
+
+    return OK;
+}
+
 status_t EmulatedVolume::doMount() {
     std::string label = getLabel();
     bool isVisible = getMountFlags() & MountFlags::kVisible;
@@ -239,7 +349,15 @@
         TEMP_FAILURE_RETRY(waitpid(sdcardFsPid, nullptr, 0));
         sdcardFsPid = 0;
     }
+
     if (isFuse && isVisible) {
+        // Make sure we unmount sdcardfs if we bail out with an error below
+        auto sdcardfs_unmounter = [&]() {
+            LOG(INFO) << "sdcardfs_unmounter scope_guard running";
+            unmountSdcardFs();
+        };
+        auto sdcardfs_guard = android::base::make_scope_guard(sdcardfs_unmounter);
+
         LOG(INFO) << "Mounting emulated fuse volume";
         android::base::unique_fd fd;
         int user_id = getMountUserId();
@@ -259,13 +377,21 @@
         }
 
         mFuseMounted = true;
+        auto fuse_unmounter = [&]() {
+            LOG(INFO) << "fuse_unmounter scope_guard running";
+            fd.reset();
+            if (UnmountUserFuse(user_id, getInternalPath(), label) != OK) {
+                PLOG(INFO) << "UnmountUserFuse failed on emulated fuse volume";
+            }
+            mFuseMounted = false;
+        };
+        auto fuse_guard = android::base::make_scope_guard(fuse_unmounter);
+
         auto callback = getMountCallback();
         if (callback) {
             bool is_ready = false;
             callback->onVolumeChecking(std::move(fd), getPath(), getInternalPath(), &is_ready);
             if (!is_ready) {
-                fd.reset();
-                doUnmount();
                 return -EIO;
             }
         }
@@ -273,10 +399,12 @@
         // Only do the bind-mounts when we know for sure the FUSE daemon can resolve the path.
         res = mountFuseBindMounts();
         if (res != OK) {
-            fd.reset();
-            doUnmount();
+            return res;
         }
-        return res;
+
+        // All mounts where successful, disable scope guards
+        sdcardfs_guard.Disable();
+        fuse_guard.Disable();
     }
 
     return OK;
@@ -304,10 +432,8 @@
 
         // Ignoring unmount return status because we do want to try to unmount
         // the rest cleanly.
-        if (mAndroidMounted) {
-            unmountFuseBindMounts();
-            mAndroidMounted = false;
-        }
+        unmountFuseBindMounts();
+
         if (UnmountUserFuse(userId, getInternalPath(), label) != OK) {
             PLOG(INFO) << "UnmountUserFuse failed on emulated fuse volume";
             return -errno;
@@ -315,28 +441,8 @@
 
         mFuseMounted = false;
     }
-    if (getMountUserId() != 0 || !mUseSdcardFs) {
-        // For sdcardfs, only unmount for user 0, since user 0 will always be running
-        // and the paths don't change for different users.
-        return OK;
-    }
 
-    ForceUnmount(mSdcardFsDefault);
-    ForceUnmount(mSdcardFsRead);
-    ForceUnmount(mSdcardFsWrite);
-    ForceUnmount(mSdcardFsFull);
-
-    rmdir(mSdcardFsDefault.c_str());
-    rmdir(mSdcardFsRead.c_str());
-    rmdir(mSdcardFsWrite.c_str());
-    rmdir(mSdcardFsFull.c_str());
-
-    mSdcardFsDefault.clear();
-    mSdcardFsRead.clear();
-    mSdcardFsWrite.clear();
-    mSdcardFsFull.clear();
-
-    return OK;
+    return unmountSdcardFs();
 }
 
 std::string EmulatedVolume::getRootPath() const {
diff --git a/model/EmulatedVolume.h b/model/EmulatedVolume.h
index 9bff0ca..1d2385d 100644
--- a/model/EmulatedVolume.h
+++ b/model/EmulatedVolume.h
@@ -48,6 +48,7 @@
     status_t doUnmount() override;
 
   private:
+    status_t unmountSdcardFs();
     status_t mountFuseBindMounts();
     status_t unmountFuseBindMounts();
 
@@ -63,9 +64,6 @@
     /* Whether we mounted FUSE for this volume */
     bool mFuseMounted;
 
-    /* Whether we mounted Android/ for this volume */
-    bool mAndroidMounted;
-
     /* Whether to use sdcardfs for this volume */
     bool mUseSdcardFs;
 
diff --git a/model/PrivateVolume.cpp b/model/PrivateVolume.cpp
index a54b05e..e146633 100644
--- a/model/PrivateVolume.cpp
+++ b/model/PrivateVolume.cpp
@@ -43,6 +43,7 @@
 namespace android {
 namespace vold {
 
+static const unsigned int kMajorBlockLoop = 7;
 static const unsigned int kMajorBlockMmc = 179;
 
 PrivateVolume::PrivateVolume(dev_t device, const KeyBuffer& keyRaw)
@@ -176,6 +177,10 @@
         return -EIO;
     }
 
+    return OK;
+}
+
+void PrivateVolume::doPostMount() {
     auto vol_manager = VolumeManager::Instance();
     std::string mediaPath(mPath + "/media");
 
@@ -188,8 +193,6 @@
         addVolume(vol);
         vol->create();
     }
-
-    return OK;
 }
 
 status_t PrivateVolume::doUnmount() {
@@ -207,7 +210,9 @@
     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()) {
+        // Additionally, prefer f2fs for loop-bases devices
+        if ((major(mRawDevice) == kMajorBlockMmc || major(mRawDevice) == kMajorBlockLoop) &&
+            f2fs::IsSupported()) {
             resolvedFsType = "f2fs";
         } else {
             resolvedFsType = "ext4";
diff --git a/model/PrivateVolume.h b/model/PrivateVolume.h
index 9780485..607c4d1 100644
--- a/model/PrivateVolume.h
+++ b/model/PrivateVolume.h
@@ -49,6 +49,7 @@
     status_t doCreate() override;
     status_t doDestroy() override;
     status_t doMount() override;
+    void doPostMount() override;
     status_t doUnmount() override;
     status_t doFormat(const std::string& fsType) override;
 
diff --git a/model/VolumeBase.cpp b/model/VolumeBase.cpp
index 687d4f7..27448da 100644
--- a/model/VolumeBase.cpp
+++ b/model/VolumeBase.cpp
@@ -232,9 +232,14 @@
     status_t res = doMount();
     setState(res == OK ? State::kMounted : State::kUnmountable);
 
+    if (res == OK) {
+        doPostMount();
+    }
     return res;
 }
 
+void VolumeBase::doPostMount() {}
+
 status_t VolumeBase::unmount() {
     if (mState != State::kMounted) {
         LOG(WARNING) << getId() << " unmount requires state mounted";
diff --git a/model/VolumeBase.h b/model/VolumeBase.h
index 078bb0c..689750d 100644
--- a/model/VolumeBase.h
+++ b/model/VolumeBase.h
@@ -120,6 +120,7 @@
     virtual status_t doCreate();
     virtual status_t doDestroy();
     virtual status_t doMount() = 0;
+    virtual void doPostMount();
     virtual status_t doUnmount() = 0;
     virtual status_t doFormat(const std::string& fsType);
 
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..0f87937
--- /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 VoldServiceValidationTest : public testing::Test {};
+
+TEST_F(VoldServiceValidationTest, 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