Merge RP1A.200204.001

Change-Id: I80a6f45bfa61ee0a8b3517de0e5e1d27aa8aa7aa
diff --git a/Android.bp b/Android.bp
index 518918c..5689ed2 100644
--- a/Android.bp
+++ b/Android.bp
@@ -84,7 +84,7 @@
         local_include_dirs: ["binder"],
         include_dirs: [
             "frameworks/native/aidl/binder",
-            "frameworks/base/core/java/android/os/incremental",
+            "frameworks/base/core/java",
         ],
         export_aidl_headers: true,
     },
diff --git a/FsCrypt.cpp b/FsCrypt.cpp
index a491206..5b01d5d 100644
--- a/FsCrypt.cpp
+++ b/FsCrypt.cpp
@@ -64,6 +64,7 @@
 
 using android::base::StringPrintf;
 using android::fs_mgr::GetEntryForMountPoint;
+using android::vold::BuildDataPath;
 using android::vold::kEmptyAuthentication;
 using android::vold::KeyBuffer;
 using android::vold::Keymaster;
@@ -89,9 +90,9 @@
 // Some users are ephemeral, don't try to wipe their keys from disk
 std::set<userid_t> s_ephemeral_users;
 
-// Map user ids to key references
-std::map<userid_t, std::string> s_de_key_raw_refs;
-std::map<userid_t, std::string> s_ce_key_raw_refs;
+// Map user ids to encryption policies
+std::map<userid_t, EncryptionPolicy> s_de_policies;
+std::map<userid_t, EncryptionPolicy> s_ce_policies;
 
 }  // namespace
 
@@ -198,65 +199,50 @@
 }
 
 // Retrieve the options to use for encryption policies on the /data filesystem.
-static void get_data_file_encryption_options(EncryptionOptions* options) {
+static bool get_data_file_encryption_options(EncryptionOptions* options) {
     auto entry = GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT);
     if (entry == nullptr) {
-        return;
+        LOG(ERROR) << "No mount point entry for " << DATA_MNT_POINT;
+        return false;
     }
     if (!ParseOptions(entry->encryption_options, options)) {
         LOG(ERROR) << "Unable to parse encryption options for " << DATA_MNT_POINT ": "
                    << entry->encryption_options;
-        return;
+        return false;
     }
-}
-
-// Retrieve the version to use for encryption policies on the /data filesystem.
-static int get_data_file_policy_version(void) {
-    EncryptionOptions options;
-    get_data_file_encryption_options(&options);
-    return options.version;
+    return true;
 }
 
 // Retrieve the options to use for encryption policies on adoptable storage.
-static bool get_volume_file_encryption_options(EncryptionOptions* options, int flags) {
+static bool get_volume_file_encryption_options(EncryptionOptions* options) {
     auto contents_mode =
             android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
     auto filenames_mode =
             android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
-    return ParseOptions(android::base::GetProperty("ro.crypto.volume.options",
-                                                   contents_mode + ":" + filenames_mode + ":v1"),
-                        options);
-}
-
-// Install a key for use by encrypted files on the /data filesystem.
-static bool install_data_key(const KeyBuffer& key, std::string* raw_ref) {
-    return android::vold::installKey(key, DATA_MNT_POINT, get_data_file_policy_version(), raw_ref);
-}
-
-// Evict a key for use by encrypted files on the /data filesystem.
-static bool evict_data_key(const std::string& raw_ref) {
-    return android::vold::evictKey(DATA_MNT_POINT, raw_ref, get_data_file_policy_version());
+    auto options_string = android::base::GetProperty("ro.crypto.volume.options",
+                                                     contents_mode + ":" + filenames_mode + ":v1");
+    if (!ParseOptions(options_string, options)) {
+        LOG(ERROR) << "Unable to parse volume encryption options: " << options_string;
+        return false;
+    }
+    return true;
 }
 
 bool is_wrapped_key_supported() {
     return GetEntryForMountPoint(&fstab_default, DATA_MNT_POINT)->fs_mgr_flags.wrapped_key;
 }
 
-static bool is_wrapped_key_supported_external() {
-    return false;
-}
-
 bool is_metadata_wrapped_key_supported() {
     return GetEntryForMountPoint(&fstab_default, METADATA_MNT_POINT)->fs_mgr_flags.wrapped_key;
 }
 
 static bool read_and_install_user_ce_key(userid_t user_id,
                                          const android::vold::KeyAuthentication& auth) {
-    if (s_ce_key_raw_refs.count(user_id) != 0) return true;
+    if (s_ce_policies.count(user_id) != 0) return true;
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
     KeyBuffer ce_key;
     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
-    std::string ce_raw_ref;
-
     if (is_wrapped_key_supported()) {
         KeyBuffer ephemeral_wrapped_key;
         if (!getEphemeralWrappedKey(KeyFormat::RAW, ce_key, &ephemeral_wrapped_key)) {
@@ -265,8 +251,9 @@
         }
         ce_key = std::move(ephemeral_wrapped_key);
     }
-    if (!install_data_key(ce_key, &ce_raw_ref)) return false;
-    s_ce_key_raw_refs[user_id] = ce_raw_ref;
+    EncryptionPolicy ce_policy;
+    if (!installKey(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
+    s_ce_policies[user_id] = ce_policy;
     LOG(DEBUG) << "Installed ce key for user " << user_id;
     return true;
 }
@@ -292,6 +279,8 @@
 // NB this assumes that there is only one thread listening for crypt commands, because
 // it creates keys in a fixed location.
 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
     KeyBuffer de_key, ce_key;
 
     if(is_wrapped_key_supported()) {
@@ -320,11 +309,6 @@
                                                kEmptyAuthentication, de_key))
             return false;
     }
-
-    /* Install the DE keys */
-    std::string de_raw_ref;
-    std::string ce_raw_ref;
-
     if (is_wrapped_key_supported()) {
         KeyBuffer ephemeral_wrapped_de_key;
         KeyBuffer ephemeral_wrapped_ce_key;
@@ -343,24 +327,24 @@
         de_key = std::move(ephemeral_wrapped_de_key);
         ce_key = std::move(ephemeral_wrapped_ce_key);
     }
-    if (!install_data_key(de_key, &de_raw_ref)) return false;
-    if (!install_data_key(ce_key, &ce_raw_ref)) return false;
-
-    s_de_key_raw_refs[user_id] = de_raw_ref;
-    s_ce_key_raw_refs[user_id] = ce_raw_ref;
-
+    EncryptionPolicy de_policy;
+    if (!installKey(DATA_MNT_POINT, options, de_key, &de_policy)) return false;
+    s_de_policies[user_id] = de_policy;
+    EncryptionPolicy ce_policy;
+    if (!installKey(DATA_MNT_POINT, options, ce_key, &ce_policy)) return false;
+    s_ce_policies[user_id] = ce_policy;
     LOG(DEBUG) << "Created keys for user " << user_id;
     return true;
 }
 
-static bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
-                           std::string* raw_ref) {
+static bool lookup_policy(const std::map<userid_t, EncryptionPolicy>& key_map, userid_t user_id,
+                          EncryptionPolicy* policy) {
     auto refi = key_map.find(user_id);
     if (refi == key_map.end()) {
         LOG(DEBUG) << "Cannot find key for " << user_id;
         return false;
     }
-    *raw_ref = refi->second;
+    *policy = refi->second;
     return true;
 }
 
@@ -372,6 +356,8 @@
 }
 
 static bool load_all_de_keys() {
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
     auto de_dir = user_key_dir + "/de";
     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(de_dir.c_str()), closedir);
     if (!dirp) {
@@ -393,21 +379,21 @@
             continue;
         }
         userid_t user_id = std::stoi(entry->d_name);
-        if (s_de_key_raw_refs.count(user_id) == 0) {
+        if (s_de_policies.count(user_id) == 0) {
             auto key_path = de_dir + "/" + entry->d_name;
-            KeyBuffer key;
-            if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
-            std::string raw_ref;
+            KeyBuffer de_key;
+            if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &de_key)) return false;
             if (is_wrapped_key_supported()) {
                 KeyBuffer ephemeral_wrapped_key;
-                if (!getEphemeralWrappedKey(KeyFormat::RAW, key, &ephemeral_wrapped_key)) {
+                if (!getEphemeralWrappedKey(KeyFormat::RAW, de_key, &ephemeral_wrapped_key)) {
                    LOG(ERROR) << "Failed to export de_key in create_and_install_user_keys";
                    return false;
                 }
-                key = std::move(ephemeral_wrapped_key);
+                de_key = std::move(ephemeral_wrapped_key);
             }
-            if (!install_data_key(key, &raw_ref)) return false;
-            s_de_key_raw_refs[user_id] = raw_ref;
+            EncryptionPolicy de_policy;
+            if (!installKey(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;
         }
     }
@@ -424,14 +410,16 @@
         LOG(INFO) << "Already initialized";
         return true;
     }
+    EncryptionOptions options;
+    if (!get_data_file_encryption_options(&options)) return false;
+
+    KeyBuffer device_key;
+    if (!android::vold::retrieveKey(true, kEmptyAuthentication, device_key_path, device_key_temp,
+                                    is_wrapped_key_supported(), &device_key))
+        return false;
 
     EncryptionPolicy device_policy;
-    get_data_file_encryption_options(&device_policy.options);
-    wrapped_key_supported = is_wrapped_key_supported();
-
-    if (!android::vold::retrieveAndInstallKey(true, kEmptyAuthentication, device_key_path,
-                                              device_key_temp, "", device_policy.options.version,
-                                              &device_policy.key_raw_ref, wrapped_key_supported))
+    if (!android::vold::installKey(DATA_MNT_POINT, options, device_key, &device_policy))
         return false;
 
     std::string options_string;
@@ -439,19 +427,21 @@
         LOG(ERROR) << "Unable to serialize options";
         return false;
     }
-    std::string options_filename = std::string("/data") + fscrypt_key_mode;
+    std::string options_filename = std::string(DATA_MNT_POINT) + fscrypt_key_mode;
     if (!android::vold::writeStringToFile(options_string, options_filename)) return false;
 
-    std::string ref_filename = std::string("/data") + fscrypt_key_ref;
+    std::string ref_filename = std::string(DATA_MNT_POINT) + fscrypt_key_ref;
     if (!android::vold::writeStringToFile(device_policy.key_raw_ref, ref_filename)) return false;
     LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
 
     KeyBuffer per_boot_key;
     if (!android::vold::randomKey(&per_boot_key)) return false;
-    std::string per_boot_raw_ref;
-    if (!install_data_key(per_boot_key, &per_boot_raw_ref)) return false;
+    EncryptionPolicy per_boot_policy;
+    if (!android::vold::installKey(DATA_MNT_POINT, options, per_boot_key, &per_boot_policy))
+        return false;
     std::string per_boot_ref_filename = std::string("/data") + fscrypt_key_per_boot_ref;
-    if (!android::vold::writeStringToFile(per_boot_raw_ref, per_boot_ref_filename)) return false;
+    if (!android::vold::writeStringToFile(per_boot_policy.key_raw_ref, per_boot_ref_filename))
+        return false;
     LOG(INFO) << "Wrote per boot key reference to:" << per_boot_ref_filename;
 
     if (!android::vold::FsyncDirectory(device_key_dir)) return false;
@@ -495,7 +485,7 @@
         return true;
     }
     // FIXME test for existence of key that is not loaded yet
-    if (s_ce_key_raw_refs.count(user_id) != 0) {
+    if (s_ce_policies.count(user_id) != 0) {
         LOG(ERROR) << "Already exists, can't fscrypt_vold_create_user_key for " << user_id
                    << " serial " << serial;
         // FIXME should we fail the command?
@@ -530,14 +520,13 @@
 
 static bool evict_ce_key(userid_t user_id) {
     bool success = true;
-    std::string raw_ref;
+    EncryptionPolicy policy;
     // If we haven't loaded the CE key, no need to evict it.
-    if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
-        success &= evict_data_key(raw_ref);
+    if (lookup_policy(s_ce_policies, user_id, &policy)) {
+        success &= android::vold::evictKey(DATA_MNT_POINT, policy);
         drop_caches_if_needed();
     }
-
-    s_ce_key_raw_refs.erase(user_id);
+    s_ce_policies.erase(user_id);
     return success;
 }
 
@@ -547,10 +536,11 @@
         return true;
     }
     bool success = true;
-    std::string raw_ref;
     success &= evict_ce_key(user_id);
-    success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref) && evict_data_key(raw_ref);
-    s_de_key_raw_refs.erase(user_id);
+    EncryptionPolicy de_policy;
+    success &= lookup_policy(s_de_policies, user_id, &de_policy) &&
+               android::vold::evictKey(DATA_MNT_POINT, de_policy);
+    s_de_policies.erase(user_id);
     auto it = s_ephemeral_users.find(user_id);
     if (it != s_ephemeral_users.end()) {
         s_ephemeral_users.erase(it);
@@ -653,12 +643,12 @@
     }
     android::vold::KeyAuthentication auth("", secdiscardable_hash);
 
-    if (!get_volume_file_encryption_options(&policy->options, flags)) return false;
-    wrapped_key_supported = is_wrapped_key_supported_external();
-
-    return android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
-                                                volume_uuid, policy->options.version,
-                                                &policy->key_raw_ref, wrapped_key_supported);
+    EncryptionOptions options;
+    if (!get_volume_file_encryption_options(&options)) return false;
+    KeyBuffer key;
+    if (!android::vold::retrieveKey(true, auth, key_path, key_path + "_tmp", false, &key)) return false;
+    if (!android::vold::installKey(BuildDataPath(volume_uuid), options, key, policy)) return false;
+    return true;
 }
 
 static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
@@ -735,7 +725,7 @@
     LOG(DEBUG) << "fscrypt_unlock_user_key " << user_id << " serial=" << serial
                << " token_present=" << (token_hex != "!");
     if (fscrypt_is_native()) {
-        if (s_ce_key_raw_refs.count(user_id) != 0) {
+        if (s_ce_policies.count(user_id) != 0) {
             LOG(WARNING) << "Tried to unlock already-unlocked key for user " << user_id;
             return true;
         }
@@ -825,9 +815,7 @@
         if (fscrypt_is_native()) {
             EncryptionPolicy de_policy;
             if (volume_uuid.empty()) {
-                if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_policy.key_raw_ref))
-                    return false;
-                get_data_file_encryption_options(&de_policy.options);
+                if (!lookup_policy(s_de_policies, user_id, &de_policy)) return false;
                 if (!EnsurePolicy(de_policy, system_de_path)) return false;
                 if (!EnsurePolicy(de_policy, misc_de_path)) return false;
                 if (!EnsurePolicy(de_policy, vendor_de_path)) return false;
@@ -857,13 +845,10 @@
         if (fscrypt_is_native()) {
             EncryptionPolicy ce_policy;
             if (volume_uuid.empty()) {
-                if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_policy.key_raw_ref))
-                    return false;
-                get_data_file_encryption_options(&ce_policy.options);
+                if (!lookup_policy(s_ce_policies, user_id, &ce_policy)) return false;
                 if (!EnsurePolicy(ce_policy, system_ce_path)) return false;
                 if (!EnsurePolicy(ce_policy, misc_ce_path)) return false;
                 if (!EnsurePolicy(ce_policy, vendor_ce_path)) return false;
-
             } else {
                 if (!read_or_create_volkey(misc_ce_path, volume_uuid, &ce_policy, flags)) return false;
             }
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 09d6ea3..50793ef 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -166,53 +166,42 @@
 }
 
 // Build a struct fscrypt_key_specifier for use in the key management ioctls.
-static bool buildKeySpecifier(fscrypt_key_specifier* spec, const std::string& raw_ref,
-                              int policy_version) {
-    switch (policy_version) {
+static bool buildKeySpecifier(fscrypt_key_specifier* spec, const EncryptionPolicy& policy) {
+    switch (policy.options.version) {
         case 1:
-            if (raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
+            if (policy.key_raw_ref.size() != FSCRYPT_KEY_DESCRIPTOR_SIZE) {
                 LOG(ERROR) << "Invalid key specifier size for v1 encryption policy: "
-                           << raw_ref.size();
+                           << policy.key_raw_ref.size();
                 return false;
             }
             spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
-            memcpy(spec->u.descriptor, raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
+            memcpy(spec->u.descriptor, policy.key_raw_ref.c_str(), FSCRYPT_KEY_DESCRIPTOR_SIZE);
             return true;
         case 2:
-            if (raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
+            if (policy.key_raw_ref.size() != FSCRYPT_KEY_IDENTIFIER_SIZE) {
                 LOG(ERROR) << "Invalid key specifier size for v2 encryption policy: "
-                           << raw_ref.size();
+                           << policy.key_raw_ref.size();
                 return false;
             }
             spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
-            memcpy(spec->u.identifier, raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
+            memcpy(spec->u.identifier, policy.key_raw_ref.c_str(), FSCRYPT_KEY_IDENTIFIER_SIZE);
             return true;
         default:
-            LOG(ERROR) << "Invalid encryption policy version: " << policy_version;
+            LOG(ERROR) << "Invalid encryption policy version: " << policy.options.version;
             return false;
     }
 }
 
-// Install a file-based encryption key to the kernel, for use by encrypted files
-// on the specified filesystem using the specified encryption policy version.
-//
-// For v1 policies, we use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it.
-// Otherwise we add the key to the legacy global session keyring.
-//
-// For v2 policies, we always use FS_IOC_ADD_ENCRYPTION_KEY; it's the only way
-// the kernel supports.
-//
-// Returns %true on success, %false on failure.  On success also sets *raw_ref
-// to the raw key reference for use in the encryption policy.
-bool installKey(const KeyBuffer& key, const std::string& mountpoint, int policy_version,
-                std::string* raw_ref) {
+bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
+                const KeyBuffer& key, EncryptionPolicy* policy) {
+    policy->options = options;
     // Put the fscrypt_add_key_arg in an automatically-zeroing buffer, since we
     // have to copy the raw key into it.
     KeyBuffer arg_buf(sizeof(struct fscrypt_add_key_arg) + key.size(), 0);
     struct fscrypt_add_key_arg* arg = (struct fscrypt_add_key_arg*)arg_buf.data();
 
     // Initialize the "key specifier", which is like a name for the key.
-    switch (policy_version) {
+    switch (options.version) {
         case 1:
             // A key for a v1 policy is specified by an arbitrary 8-byte
             // "descriptor", which must be provided by userspace.  We use the
@@ -221,14 +210,14 @@
                 /* When wrapped key is supported, only the first 32 bytes are
                    the same per boot. The second 32 bytes can change as the ephemeral
                    key is different. */
-                *raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size()/2);
+                policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size()/2);
             } else {
-                *raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
+                policy->key_raw_ref = generateKeyRef((const uint8_t*)key.data(), key.size());
             }
             if (!isFsKeyringSupported()) {
-                return installKeyLegacy(key, *raw_ref);
+                return installKeyLegacy(key, policy->key_raw_ref);
             }
-            if (!buildKeySpecifier(&arg->key_spec, *raw_ref, policy_version)) {
+            if (!buildKeySpecifier(&arg->key_spec, *policy)) {
                 return false;
             }
             break;
@@ -241,7 +230,7 @@
             arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
             break;
         default:
-            LOG(ERROR) << "Invalid encryption policy version: " << policy_version;
+            LOG(ERROR) << "Invalid encryption policy version: " << options.version;
             return false;
     }
 
@@ -262,9 +251,10 @@
 
     if (arg->key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
         // Retrieve the key identifier that the kernel computed.
-        *raw_ref = std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
+        policy->key_raw_ref =
+                std::string((char*)arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
     }
-    LOG(DEBUG) << "Installed fscrypt key with ref " << keyrefstring(*raw_ref) << " to "
+    LOG(DEBUG) << "Installed fscrypt key with ref " << keyrefstring(policy->key_raw_ref) << " to "
                << mountpoint;
     return true;
 }
@@ -292,15 +282,9 @@
     return success;
 }
 
-// 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.
-//
-// In the latter case, the caller is responsible for dropping caches.
-bool evictKey(const std::string& mountpoint, const std::string& raw_ref, int policy_version) {
-    if (policy_version == 1 && !isFsKeyringSupported()) {
-        return evictKeyLegacy(raw_ref);
+bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy) {
+    if (policy.options.version == 1 && !isFsKeyringSupported()) {
+        return evictKeyLegacy(policy.key_raw_ref);
     }
 
     android::base::unique_fd fd(open(mountpoint.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC));
@@ -312,11 +296,11 @@
     struct fscrypt_remove_key_arg arg;
     memset(&arg, 0, sizeof(arg));
 
-    if (!buildKeySpecifier(&arg.key_spec, raw_ref, policy_version)) {
+    if (!buildKeySpecifier(&arg.key_spec, policy)) {
         return false;
     }
 
-    std::string ref = keyrefstring(raw_ref);
+    std::string ref = keyrefstring(policy.key_raw_ref);
 
     if (ioctl(fd, FS_IOC_REMOVE_ENCRYPTION_KEY, &arg) != 0) {
         PLOG(ERROR) << "Failed to evict fscrypt key with ref " << ref << " from " << mountpoint;
@@ -334,14 +318,12 @@
     return true;
 }
 
-bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
-                           const std::string& key_path, const std::string& tmp_path,
-                           const std::string& volume_uuid, int policy_version,
-                           std::string* key_ref, bool wrapped_key_supported) {
-    KeyBuffer key;
+bool retrieveKey(bool create_if_absent, const KeyAuthentication& key_authentication,
+                 const std::string& key_path, const std::string& tmp_path,
+                 bool wrapped_key_supported, KeyBuffer* key, bool keepOld) {
     if (pathExists(key_path)) {
         LOG(DEBUG) << "Key exists, using: " << key_path;
-        if (!retrieveKey(key_path, key_authentication, &key)) return false;
+        if (!retrieveKey(key_path, key_authentication, key, keepOld)) return false;
     } else {
         if (!create_if_absent) {
             LOG(ERROR) << "No key found in " << key_path;
@@ -349,63 +331,19 @@
         }
         LOG(INFO) << "Creating new key in " << key_path;
         if (wrapped_key_supported) {
-            if(!generateWrappedKey(MAX_USER_ID, KeyType::DE_SYS, &key)) return false;
-        } else {
-            if (!randomKey(&key)) return false;
-        }
-        if (!storeKeyAtomically(key_path, tmp_path, key_authentication, key)) return false;
-    }
-
-    if (wrapped_key_supported) {
-        KeyBuffer ephemeral_wrapped_key;
-        if (!getEphemeralWrappedKey(KeyFormat::RAW, key, &ephemeral_wrapped_key)) {
-            LOG(ERROR) << "Failed to export key in retrieveAndInstallKey";
-            return false;
-        }
-        key = std::move(ephemeral_wrapped_key);
-    }
-
-    if (!installKey(key, BuildDataPath(volume_uuid), policy_version, key_ref)) {
-        LOG(ERROR) << "Failed to install key in " << key_path;
-        return false;
-    }
-    return true;
-}
-
-bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
-                 KeyBuffer* key, bool keepOld) {
-    if (pathExists(key_path)) {
-        LOG(DEBUG) << "Key exists, using: " << key_path;
-        if (!retrieveKey(key_path, kEmptyAuthentication, key, keepOld)) return false;
-        if (is_metadata_wrapped_key_supported()) {
-            KeyBuffer ephemeral_wrapped_key;
-            if (!getEphemeralWrappedKey(KeyFormat::RAW, *key, &ephemeral_wrapped_key)) {
-                LOG(ERROR) << "Failed to export key for retrieved key";
-                return false;
-            }
-            *key = std::move(ephemeral_wrapped_key);
-        }
-    } else {
-        if (!create_if_absent) {
-            LOG(ERROR) << "No key found in " << key_path;
-            return false;
-        }
-        LOG(INFO) << "Creating new key in " << key_path;
-        if (is_metadata_wrapped_key_supported()) {
             if(!generateWrappedKey(MAX_USER_ID, KeyType::ME, key)) return false;
         } else {
             if (!randomKey(key)) return false;
         }
-        if (!storeKeyAtomically(key_path, tmp_path,
-                kEmptyAuthentication, *key)) return false;
-	if (is_metadata_wrapped_key_supported()) {
-            KeyBuffer ephemeral_wrapped_key;
-            if (!getEphemeralWrappedKey(KeyFormat::RAW, *key, &ephemeral_wrapped_key)) {
-                LOG(ERROR) << "Failed to export key for generated key";
-                return false;
-            }
-            *key = std::move(ephemeral_wrapped_key);
+        if (!storeKeyAtomically(key_path, tmp_path, key_authentication, *key)) return false;
+    }
+    if (wrapped_key_supported) {
+        KeyBuffer ephemeral_wrapped_key;
+        if (!getEphemeralWrappedKey(KeyFormat::RAW, *key, &ephemeral_wrapped_key)) {
+            LOG(ERROR) << "Failed to export key for generated key";
+            return false;
         }
+        *key = std::move(ephemeral_wrapped_key);
     }
     return true;
 }
diff --git a/KeyUtil.h b/KeyUtil.h
index 06e4239..a638b26 100644
--- a/KeyUtil.h
+++ b/KeyUtil.h
@@ -21,25 +21,45 @@
 #include "KeyStorage.h"
 #include "Keymaster.h"
 
+#include <fscrypt/fscrypt.h>
+
 #include <memory>
 #include <string>
 
 namespace android {
 namespace vold {
 
+using namespace android::fscrypt;
+
 bool randomKey(KeyBuffer* key);
 
 bool isFsKeyringSupported(void);
 
-bool installKey(const KeyBuffer& key, const std::string& mountpoint, int policy_version,
-                std::string* raw_ref);
-bool evictKey(const std::string& mountpoint, const std::string& raw_ref, int policy_version);
-bool retrieveAndInstallKey(bool create_if_absent, const KeyAuthentication& key_authentication,
-                           const std::string& key_path, const std::string& tmp_path,
-                           const std::string& volume_uuid, int policy_version,
-                           std::string* key_ref, bool wrapped_key_supported);
-bool retrieveKey(bool create_if_absent, const std::string& key_path, const std::string& tmp_path,
-                 KeyBuffer* key, bool keepOld = true);
+// Install a file-based encryption key to the kernel, for use by encrypted files
+// on the specified filesystem using the specified encryption policy version.
+//
+// For v1 policies, we use FS_IOC_ADD_ENCRYPTION_KEY if the kernel supports it.
+// Otherwise we add the key to the legacy global session keyring.
+//
+// For v2 policies, we always use FS_IOC_ADD_ENCRYPTION_KEY; it's the only way
+// the kernel supports.
+//
+// Returns %true on success, %false on failure.  On success also sets *policy
+// to the EncryptionPolicy used to refer to this key.
+bool installKey(const std::string& mountpoint, const EncryptionOptions& options,
+                const KeyBuffer& key, EncryptionPolicy* policy);
+
+// Evict a file-based encryption key from the kernel.
+//
+// We use FS_IOC_REMOVE_ENCRYPTION_KEY if the kernel supports it.  Otherwise we
+// remove the key from the legacy global session keyring.
+//
+// In the latter case, the caller is responsible for dropping caches.
+bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy);
+
+bool retrieveKey(bool create_if_absent, const KeyAuthentication& key_authentication,
+                 const std::string& key_path, const std::string& tmp_path,
+                 bool wrapped_key_supported, KeyBuffer* key, bool keepOld = true);
 
 }  // namespace vold
 }  // namespace android
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
index 3c2e0d5..d41662b 100644
--- a/MetadataCrypt.cpp
+++ b/MetadataCrypt.cpp
@@ -37,6 +37,7 @@
 
 #include "Checkpoint.h"
 #include "EncryptInplace.h"
+#include "FsCrypt.h"
 #include "KeyStorage.h"
 #include "KeyUtil.h"
 #include "Keymaster.h"
@@ -106,19 +107,19 @@
 }
 
 static bool read_key(const FstabEntry& data_rec, bool create_if_absent, KeyBuffer* key) {
-    if (data_rec.key_dir.empty()) {
-        LOG(ERROR) << "Failed to get key_dir";
+    if (data_rec.metadata_key_dir.empty()) {
+        LOG(ERROR) << "Failed to get metadata_key_dir";
         return false;
     }
-    std::string key_dir = data_rec.key_dir;
+    std::string metadata_key_dir = data_rec.metadata_key_dir;
     std::string sKey;
-    auto dir = key_dir + "/key";
-    LOG(DEBUG) << "key_dir/key: " << dir;
+    auto dir = metadata_key_dir + "/key";
+    LOG(DEBUG) << "metadata_key_dir/key: " << dir;
     if (fs_mkdirs(dir.c_str(), 0700)) {
         PLOG(ERROR) << "Creating directories: " << dir;
         return false;
     }
-    auto temp = key_dir + "/tmp";
+    auto temp = metadata_key_dir + "/tmp";
     auto newKeyPath = dir + "/" + kFn_keymaster_key_blob_upgraded;
     /* If we have a leftover upgraded key, delete it.
      * We either failed an update and must return to the old key,
@@ -135,7 +136,9 @@
             unlink(newKeyPath.c_str());
     }
     bool needs_cp = cp_needsCheckpoint();
-    if (!android::vold::retrieveKey(create_if_absent, dir, temp, key, needs_cp)) return false;
+    if (!android::vold::retrieveKey(create_if_absent, kEmptyAuthentication, dir, temp,
+                                    is_metadata_wrapped_key_supported(), key, needs_cp))
+        return false;
     if (needs_cp && pathExists(newKeyPath)) std::thread(commit_key, dir).detach();
     return true;
 }
@@ -151,10 +154,32 @@
     return true;
 }
 
-static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
-                                  const std::string& real_blkdev, const KeyBuffer& key,
-                                  std::string* crypto_blkdev, bool set_dun) {
-    auto& dm = DeviceMapper::Instance();
+static std::string lookup_cipher(const std::string& cipher_name, bool is_legacy) {
+    if (is_legacy) {
+        if (cipher_name.empty() || cipher_name == "aes-256-xts") {
+            return "AES-256-XTS";
+        }
+    } else {
+        if (cipher_name.empty() || cipher_name == "aes-256-xts") {
+            return "aes-xts-plain64";
+        } else if (cipher_name == "adiantum") {
+            return "xchacha12,aes-adiantum-plain64";
+        }
+    }
+    LOG(ERROR) << "No metadata cipher named " << cipher_name << " found, is_legacy=" << is_legacy;
+    return "";
+}
+
+static bool create_crypto_blk_dev(const std::string& dm_name, const FstabEntry* data_rec,
+                                  const KeyBuffer& key, std::string* crypto_blkdev) {
+    uint64_t nr_sec;
+    if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
+
+    bool is_legacy;
+    if (!DmTargetDefaultKey::IsLegacy(&is_legacy)) return false;
+
+    auto cipher = lookup_cipher(data_rec->metadata_cipher, is_legacy);
+    if (cipher.empty()) return false;
 
     KeyBuffer hex_key_buffer;
     if (android::vold::StrToHex(key, hex_key_buffer) != android::OK) {
@@ -163,15 +188,24 @@
     }
     std::string hex_key(hex_key_buffer.data(), hex_key_buffer.size());
 
-    DmTable table;
-    table.Emplace<DmTargetDefaultKey>(0, nr_sec, "AES-256-XTS", hex_key, real_blkdev, 0, set_dun);
+    // Non-legacy driver always sets DUN
+    bool set_dun = !is_legacy || android::base::GetBoolProperty("ro.crypto.set_dun", false);
+    if (!set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
+        LOG(ERROR) << "Block checkpoints and metadata encryption require ro.crypto.set_dun option";
+        return false;
+    }
 
+    DmTable table;
+    table.Emplace<DmTargetDefaultKey>(0, nr_sec, cipher, hex_key, data_rec->blk_device, 0,
+                                      is_legacy, set_dun);
+
+    auto& dm = DeviceMapper::Instance();
     for (int i = 0;; i++) {
         if (dm.CreateDevice(dm_name, table)) {
             break;
         }
         if (i + 1 >= TABLE_LOAD_RETRIES) {
-            LOG(ERROR) << "Could not create default-key device " << dm_name;
+            PLOG(ERROR) << "Could not create default-key device " << dm_name;
             return false;
         }
         PLOG(INFO) << "Could not create default-key device, retrying";
@@ -196,25 +230,24 @@
 
     auto data_rec = GetEntryForMountPoint(&fstab_default, mount_point);
     if (!data_rec) {
-        LOG(ERROR) << "Failed to get data_rec";
+        LOG(ERROR) << "Failed to get data_rec for " << mount_point;
+        return false;
+    }
+    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;
     }
     KeyBuffer key;
     if (!read_key(*data_rec, needs_encrypt, &key)) return false;
-    uint64_t nr_sec;
-    if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
-    bool set_dun = android::base::GetBoolProperty("ro.crypto.set_dun", false);
-    if (!set_dun && data_rec->fs_mgr_flags.checkpoint_blk) {
-        LOG(ERROR) << "Block checkpoints and metadata encryption require setdun option!";
-        return false;
-    }
 
     std::string crypto_blkdev;
-    if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, blk_device, key, &crypto_blkdev, set_dun))
-        return false;
+    if (!create_crypto_blk_dev(kDmNameUserdata, data_rec, key, &crypto_blkdev)) return false;
 
     // FIXME handle the corrupt case
     if (needs_encrypt) {
+        uint64_t nr_sec;
+        if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
         LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
         off64_t size_already_done = 0;
         auto rc = cryptfs_enable_inplace(crypto_blkdev.data(), blk_device.data(), nr_sec,
diff --git a/Utils.cpp b/Utils.cpp
index 202b98d..3915667 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -115,6 +115,25 @@
     }
 }
 
+int SetQuotaProjectId(std::string path, long projectId) {
+    struct fsxattr fsx;
+
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << path << " to set project id.";
+        return -1;
+    }
+
+    int ret = ioctl(fd, FS_IOC_FSGETXATTR, &fsx);
+    if (ret == -1) {
+        PLOG(ERROR) << "Failed to get extended attributes for " << path << " to get project id.";
+        return ret;
+    }
+
+    fsx.fsx_projid = projectId;
+    return ioctl(fd, FS_IOC_FSSETXATTR, &fsx);
+}
+
 int PrepareDirsFromRoot(std::string path, std::string root, mode_t mode, uid_t uid, gid_t gid) {
     int ret = 0;
     if (!StartsWith(path, root)) {
@@ -1019,7 +1038,7 @@
 
     // Ensure that /mnt/user is 0700. With FUSE, apps don't need access to /mnt/user paths directly.
     // Without FUSE however, apps need /mnt/user access so /mnt/user in init.rc is 0755 until here
-    auto result = PrepareDir("/mnt/user", 0700, AID_ROOT, AID_ROOT);
+    auto result = PrepareDir("/mnt/user", 0750, AID_ROOT, AID_MEDIA_RW);
     if (result != android::OK) {
         PLOG(ERROR) << "Failed to prepare directory /mnt/user";
         return -1;
@@ -1043,13 +1062,13 @@
         return -1;
     }
 
-    result = PrepareDir(pre_pass_through_path, 0755, AID_ROOT, AID_ROOT);
+    result = PrepareDir(pre_pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
     if (result != android::OK) {
         PLOG(ERROR) << "Failed to prepare directory " << pre_pass_through_path;
         return -1;
     }
 
-    result = PrepareDir(pass_through_path, 0755, AID_ROOT, AID_ROOT);
+    result = PrepareDir(pass_through_path, 0710, AID_ROOT, AID_MEDIA_RW);
     if (result != android::OK) {
         PLOG(ERROR) << "Failed to prepare directory " << pass_through_path;
         return -1;
@@ -1066,7 +1085,7 @@
         Symlink("/storage/emulated/" + std::to_string(user_id), linkpath);
 
         std::string pass_through_linkpath(StringPrintf("/mnt/pass_through/%d/self", user_id));
-        result = PrepareDir(pass_through_linkpath, 0755, AID_ROOT, AID_ROOT);
+        result = PrepareDir(pass_through_linkpath, 0710, AID_ROOT, AID_MEDIA_RW);
         if (result != android::OK) {
             PLOG(ERROR) << "Failed to prepare directory " << pass_through_linkpath;
             return -1;
diff --git a/Utils.h b/Utils.h
index 056a635..42e8b4e 100644
--- a/Utils.h
+++ b/Utils.h
@@ -48,6 +48,7 @@
 status_t CreateDeviceNode(const std::string& path, dev_t dev);
 status_t DestroyDeviceNode(const std::string& path);
 
+int SetQuotaProjectId(std::string path, long projectId);
 /*
  * Recursively calls fs_prepare_dir() on all components in 'path', starting at 'root'.
  * 'path' must start with 'root'
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index db8b265..2539f50 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -933,26 +933,26 @@
     return ok();
 }
 
-binder::Status VoldNativeService::incFsVersion(int32_t* _aidl_return) {
-    *_aidl_return = IncFs_Version();
+binder::Status VoldNativeService::incFsEnabled(bool* _aidl_return) {
+    *_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);
+    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);
     }
-    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 = std::make_unique<ParcelFileDescriptor>(unique_fd(result.cmdFd));
-    if (result.logFd >= 0) {
-        _aidl_return->log = std::make_unique<ParcelFileDescriptor>(unique_fd(result.logFd));
+    _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();
 }
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 8277524..4a6fbac 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -148,9 +148,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/VolumeManager.cpp b/VolumeManager.cpp
index d8b1e32..3de89ab 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -830,16 +830,47 @@
         return -EINVAL;
     }
 
+    // Find the volume it belongs to
+    auto filter_fn = [&](const VolumeBase& vol) {
+        if (vol.getState() != VolumeBase::State::kMounted) {
+            // The volume must be mounted
+            return false;
+        }
+        if ((vol.getMountFlags() & VolumeBase::MountFlags::kVisible) == 0) {
+            // and visible
+            return false;
+        }
+        if (vol.getInternalPath().empty()) {
+            return false;
+        }
+        if (vol.getMountUserId() != USER_UNKNOWN &&
+            vol.getMountUserId() != multiuser_get_user_id(appUid)) {
+            // The app dir must be created on a volume with the same user-id
+            return false;
+        }
+        if (!path.empty() && StartsWith(path, vol.getPath())) {
+            return true;
+        }
+
+        return false;
+    };
+    auto volume = findVolumeWithFilter(filter_fn);
+    if (volume == nullptr) {
+        LOG(ERROR) << "Failed to find mounted volume for " << path;
+        return -EINVAL;
+    }
     // Convert paths to lower filesystem paths to avoid making FUSE requests for these reasons:
     // 1. A FUSE request from vold puts vold at risk of hanging if the FUSE daemon is down
     // 2. The FUSE daemon prevents requests on /mnt/user/0/emulated/<userid != 0> and a request
     // on /storage/emulated/10 means /mnt/user/0/emulated/10
-    // TODO(b/146419093): Use lower filesystem paths that don't depend on sdcardfs
-    const std::string lowerPath = "/mnt/runtime/default/" + path.substr(9);
-    const std::string lowerAppDirRoot = "/mnt/runtime/default/" + appDirRoot.substr(9);
+    const std::string lowerPath =
+            volume->getInternalPath() + path.substr(volume->getPath().length());
+    const std::string lowerAppDirRoot =
+            volume->getInternalPath() + appDirRoot.substr(volume->getPath().length());
 
     // First create the root which holds app dirs, if needed.
-    int ret = PrepareDirsFromRoot(lowerAppDirRoot, "/mnt/runtime/default/", 0771, AID_MEDIA_RW, AID_MEDIA_RW);
+    int ret = PrepareDirsFromRoot(lowerAppDirRoot, volume->getInternalPath(), 0771, AID_MEDIA_RW,
+                                  AID_MEDIA_RW);
     if (ret != 0) {
         return ret;
     }
diff --git a/VolumeManager.h b/VolumeManager.h
index cacab85..eb48736 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -83,6 +83,24 @@
     std::shared_ptr<android::vold::Disk> findDisk(const std::string& id);
     std::shared_ptr<android::vold::VolumeBase> findVolume(const std::string& id);
 
+    template <typename Fn>
+    std::shared_ptr<android::vold::VolumeBase> findVolumeWithFilter(Fn fn) {
+        for (const auto& vol : mInternalEmulatedVolumes) {
+            if (fn(*vol)) {
+                return vol;
+            }
+        }
+        for (const auto& disk : mDisks) {
+            for (const auto& vol : disk->getVolumes()) {
+                if (fn(*vol)) {
+                    return vol;
+                }
+            }
+        }
+
+        return nullptr;
+    }
+
     void listVolumes(android::vold::VolumeBase::Type type, std::list<std::string>& list) const;
 
     const std::set<userid_t>& getStartedUsers() const { return mStartedUsers; }
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index 266709f..0a35d93 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -130,8 +130,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/fs/Ext4.cpp b/fs/Ext4.cpp
index 0059233..8bb930d 100644
--- a/fs/Ext4.cpp
+++ b/fs/Ext4.cpp
@@ -171,6 +171,14 @@
     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);
+
+    if (needs_projid) {
+        cmd.push_back("-I");
+        cmd.push_back("512");
+    }
+
     std::string options("has_journal");
     if (android::base::GetBoolProperty("vold.has_quota", false)) {
         options += ",quota";
@@ -178,10 +186,21 @@
     if (fscrypt_is_native()) {
         options += ",encrypt";
     }
+    if (needs_casefold) {
+        options += ",casefold";
+    }
 
     cmd.push_back("-O");
     cmd.push_back(options);
 
+    if (needs_casefold || needs_projid) {
+        cmd.push_back("-E");
+        std::string extopts = "";
+        if (needs_casefold) extopts += "encoding=utf8,";
+        if (needs_projid) extopts += "quotatype=prjquota,";
+        cmd.push_back(extopts);
+    }
+
     cmd.push_back(source);
 
     if (numSectors) {
diff --git a/model/Disk.cpp b/model/Disk.cpp
index b66c336..f8357a9 100644
--- a/model/Disk.cpp
+++ b/model/Disk.cpp
@@ -162,6 +162,17 @@
     }
 }
 
+std::vector<std::shared_ptr<VolumeBase>> Disk::getVolumes() const {
+    std::vector<std::shared_ptr<VolumeBase>> vols;
+    for (const auto& vol : mVolumes) {
+        vols.push_back(vol);
+        auto stackedVolumes = vol->getVolumes();
+        vols.insert(vols.end(), stackedVolumes.begin(), stackedVolumes.end());
+    }
+
+    return vols;
+}
+
 status_t Disk::create() {
     CHECK(!mCreated);
     mCreated = true;
diff --git a/model/Disk.h b/model/Disk.h
index 889e906..d82d141 100644
--- a/model/Disk.h
+++ b/model/Disk.h
@@ -67,6 +67,8 @@
 
     void listVolumes(VolumeBase::Type type, std::list<std::string>& list) const;
 
+    std::vector<std::shared_ptr<VolumeBase>> getVolumes() const;
+
     status_t create();
     status_t destroy();
 
diff --git a/model/PublicVolume.cpp b/model/PublicVolume.cpp
index b246c95..a0b3227 100644
--- a/model/PublicVolume.cpp
+++ b/model/PublicVolume.cpp
@@ -141,13 +141,14 @@
     }
 
     if (mFsType == "vfat") {
-        if (vfat::Mount(mDevPath, mRawPath, false, false, false, AID_MEDIA_RW, AID_MEDIA_RW, 0007,
-                        true)) {
+        if (vfat::Mount(mDevPath, mRawPath, false, false, false, AID_ROOT,
+                        (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007, true)) {
             PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
             return -EIO;
         }
     } else if (mFsType == "exfat") {
-        if (exfat::Mount(mDevPath, mRawPath, AID_MEDIA_RW, AID_MEDIA_RW, 0007)) {
+        if (exfat::Mount(mDevPath, mRawPath, AID_ROOT,
+                         (isVisible ? AID_MEDIA_RW : AID_EXTERNAL_STORAGE), 0007)) {
             PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
             return -EIO;
         }