Merge "clang-format many files." am: a676df01e2 am: 957b9544dd
am: 8b2b67bc1e

Change-Id: Iad04e9517cd01e2ea13281b31e7b13ae75414d7e
diff --git a/Android.bp b/Android.bp
index 080c5fe..8fd29f0 100644
--- a/Android.bp
+++ b/Android.bp
@@ -140,7 +140,7 @@
         },
     },
     shared_libs: [
-        "android.hardware.health.filesystem@1.0",
+        "android.hardware.health.storage@1.0",
     ],
 }
 
@@ -173,7 +173,7 @@
     ],
 
     shared_libs: [
-        "android.hardware.health.filesystem@1.0",
+        "android.hardware.health.storage@1.0",
         "libhidltransport",
     ],
 }
diff --git a/IdleMaint.cpp b/IdleMaint.cpp
index ff2ebc5..d73b6d2 100644
--- a/IdleMaint.cpp
+++ b/IdleMaint.cpp
@@ -27,7 +27,7 @@
 #include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
-#include <android/hardware/health/filesystem/1.0/IFileSystem.h>
+#include <android/hardware/health/storage/1.0/IStorage.h>
 #include <fs_mgr.h>
 #include <hardware_legacy/power.h>
 #include <private/android_filesystem_config.h>
@@ -47,9 +47,9 @@
 using android::base::WriteStringToFile;
 using android::hardware::Return;
 using android::hardware::Void;
-using android::hardware::health::filesystem::V1_0::IFileSystem;
-using android::hardware::health::filesystem::V1_0::IGarbageCollectCallback;
-using android::hardware::health::filesystem::V1_0::Result;
+using android::hardware::health::storage::V1_0::IStorage;
+using android::hardware::health::storage::V1_0::IGarbageCollectCallback;
+using android::hardware::health::storage::V1_0::Result;
 
 namespace android {
 namespace vold {
@@ -344,7 +344,7 @@
     Result mResult{Result::UNKNOWN_ERROR};
 };
 
-static void runDevGcOnHal(sp<IFileSystem> service) {
+static void runDevGcOnHal(sp<IStorage> service) {
     LOG(DEBUG) << "Start Dev GC on HAL";
     sp<GcCallback> cb = new GcCallback();
     auto ret = service->garbageCollect(DEVGC_TIMEOUT_SEC, cb);
@@ -356,7 +356,7 @@
 }
 
 static void runDevGc(void) {
-    auto service = IFileSystem::getService();
+    auto service = IStorage::getService();
     if (service != nullptr) {
         runDevGcOnHal(service);
     } else {
diff --git a/VoldNativeService.cpp b/VoldNativeService.cpp
index 81523c6..999df94 100644
--- a/VoldNativeService.cpp
+++ b/VoldNativeService.cpp
@@ -146,6 +146,69 @@
     return ok();
 }
 
+binder::Status checkArgumentPackageName(const std::string& packageName) {
+    // This logic is borrowed from PackageParser.java
+    bool hasSep = false;
+    bool front = true;
+
+    for (size_t i = 0; i < packageName.length(); ++i) {
+        char c = packageName[i];
+        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+            front = false;
+            continue;
+        }
+        if (!front) {
+            if ((c >= '0' && c <= '9') || c == '_') {
+                continue;
+            }
+        }
+        if (c == '.') {
+            hasSep = true;
+            front = true;
+            continue;
+        }
+        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                StringPrintf("Bad package character %c in %s", c, packageName.c_str()));
+    }
+
+    if (front) {
+        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
+                StringPrintf("Missing separator in %s", packageName.c_str()));
+    }
+
+    return ok();
+}
+
+binder::Status checkArgumentPackageNames(const std::vector<std::string>& packageNames) {
+    for (size_t i = 0; i < packageNames.size(); ++i) {
+        binder::Status status = checkArgumentPackageName(packageNames[i]);
+        if (!status.isOk()) {
+            return status;
+        }
+    }
+    return ok();
+}
+
+binder::Status checkArgumentSandboxId(const std::string& sandboxId) {
+    // sandboxId will be in either the format shared:<shared-user-id> or <package-name>
+    // and <shared-user-id> name has same requirements as <package-name>.
+    std::size_t nameStartIndex = 0;
+    if (android::base::StartsWith(sandboxId, "shared:")) {
+        nameStartIndex = 7;  // len("shared:")
+    }
+    return checkArgumentPackageName(sandboxId.substr(nameStartIndex));
+}
+
+binder::Status checkArgumentSandboxIds(const std::vector<std::string>& sandboxIds) {
+    for (size_t i = 0; i < sandboxIds.size(); ++i) {
+        binder::Status status = checkArgumentSandboxId(sandboxIds[i]);
+        if (!status.isOk()) {
+            return status;
+        }
+    }
+    return ok();
+}
+
 #define ENFORCE_UID(uid) {                                  \
     binder::Status status = checkUid((uid));                \
     if (!status.isOk()) {                                   \
@@ -174,6 +237,34 @@
     }                                                       \
 }
 
+#define CHECK_ARGUMENT_PACKAGE_NAMES(packageNames) {                        \
+    binder::Status status = checkArgumentPackageNames((packageNames));      \
+    if (!status.isOk()) {                                                   \
+        return status;                                                      \
+    }                                                                       \
+}
+
+#define CHECK_ARGUMENT_SANDBOX_IDS(sandboxIds) {                            \
+    binder::Status status = checkArgumentSandboxIds((sandboxIds));          \
+    if (!status.isOk()) {                                                   \
+        return status;                                                      \
+    }                                                                       \
+}
+
+#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {                          \
+    binder::Status status = checkArgumentPackageName((packageName));        \
+    if (!status.isOk()) {                                                   \
+        return status;                                                      \
+    }                                                                       \
+}
+
+#define CHECK_ARGUMENT_SANDBOX_ID(sandboxId) {                              \
+    binder::Status status = checkArgumentSandboxId((sandboxId));            \
+    if (!status.isOk()) {                                                   \
+        return status;                                                      \
+    }                                                                       \
+}
+
 #define ACQUIRE_LOCK \
     std::lock_guard<std::mutex> lock(VolumeManager::Instance()->getLock()); \
     ATRACE_CALL();
@@ -261,11 +352,13 @@
     return translate(VolumeManager::Instance()->onUserRemoved(userId));
 }
 
-binder::Status VoldNativeService::onUserStarted(int32_t userId) {
+binder::Status VoldNativeService::onUserStarted(int32_t userId,
+        const std::vector<std::string>& packageNames) {
     ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PACKAGE_NAMES(packageNames);
     ACQUIRE_LOCK;
 
-    return translate(VolumeManager::Instance()->onUserStarted(userId));
+    return translate(VolumeManager::Instance()->onUserStarted(userId, packageNames));
 }
 
 binder::Status VoldNativeService::onUserStopped(int32_t userId) {
@@ -275,6 +368,24 @@
     return translate(VolumeManager::Instance()->onUserStopped(userId));
 }
 
+binder::Status VoldNativeService::addAppIds(const std::vector<std::string>& packageNames,
+        const std::vector<int32_t>& appIds) {
+    ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PACKAGE_NAMES(packageNames);
+    ACQUIRE_LOCK;
+
+    return translate(VolumeManager::Instance()->addAppIds(packageNames, appIds));
+}
+
+binder::Status VoldNativeService::addSandboxIds(const std::vector<int32_t>& appIds,
+        const std::vector<std::string>& sandboxIds) {
+    ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_SANDBOX_IDS(sandboxIds);
+    ACQUIRE_LOCK;
+
+    return translate(VolumeManager::Instance()->addSandboxIds(appIds, sandboxIds));
+}
+
 binder::Status VoldNativeService::onSecureKeyguardStateChanged(bool isShowing) {
     ENFORCE_UID(AID_SYSTEM);
     ACQUIRE_LOCK;
@@ -759,5 +870,16 @@
     return translateBool(e4crypt_destroy_user_storage(uuid_, userId, flags));
 }
 
+binder::Status VoldNativeService::mountExternalStorageForApp(const std::string& packageName,
+        int32_t appId, const std::string& sandboxId, int32_t userId) {
+    ENFORCE_UID(AID_SYSTEM);
+    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
+    CHECK_ARGUMENT_SANDBOX_ID(sandboxId);
+    ACQUIRE_LOCK;
+
+    return translate(VolumeManager::Instance()->mountExternalStorageForApp(
+            packageName, appId, sandboxId, userId));
+}
+
 }  // namespace vold
 }  // namespace android
diff --git a/VoldNativeService.h b/VoldNativeService.h
index 2e90101..d5de707 100644
--- a/VoldNativeService.h
+++ b/VoldNativeService.h
@@ -39,9 +39,14 @@
 
     binder::Status onUserAdded(int32_t userId, int32_t userSerial);
     binder::Status onUserRemoved(int32_t userId);
-    binder::Status onUserStarted(int32_t userId);
+    binder::Status onUserStarted(int32_t userId, const std::vector<std::string>& packageNames);
     binder::Status onUserStopped(int32_t userId);
 
+    binder::Status addAppIds(const std::vector<std::string>& packageNames,
+            const std::vector<int32_t>& appIds);
+    binder::Status addSandboxIds(const std::vector<int32_t>& appIds,
+            const std::vector<std::string>& sandboxIds);
+
     binder::Status onSecureKeyguardStateChanged(bool isShowing);
 
     binder::Status partition(const std::string& diskId, int32_t partitionType, int32_t ratio);
@@ -113,6 +118,9 @@
             int32_t userId, int32_t userSerial, int32_t flags);
     binder::Status destroyUserStorage(const std::unique_ptr<std::string>& uuid,
             int32_t userId, int32_t flags);
+
+    binder::Status mountExternalStorageForApp(const std::string& packageName, int32_t appId,
+            const std::string& sandboxId, int32_t userId);
 };
 
 }  // namespace vold
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 21e132a..260c2f0 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -64,14 +64,19 @@
 #include "model/EmulatedVolume.h"
 #include "model/ObbVolume.h"
 
+using android::base::GetBoolProperty;
+using android::base::StringAppendF;
 using android::base::StringPrintf;
 using android::base::unique_fd;
 
 static const char* kPathUserMount = "/mnt/user";
 static const char* kPathVirtualDisk = "/data/misc/vold/virtual_disk";
 
+static const char* kIsolatedStorage = "persist.sys.isolated_storage";
 static const char* kPropVirtualDisk = "persist.sys.virtual_disk";
 
+static const std::string kEmptyString("");
+
 /* 512MiB is large enough for testing purposes */
 static const unsigned int kSizeVirtualDisk = 536870912;
 
@@ -93,6 +98,7 @@
     // For security reasons, assume that a secure keyguard is
     // showing until we hear otherwise
     mSecureKeyguardShowing = true;
+    mMntStorageCreated = false;
 }
 
 VolumeManager::~VolumeManager() {
@@ -341,27 +347,250 @@
     return success ? 0 : -1;
 }
 
-int VolumeManager::linkPrimary(userid_t userId) {
-    std::string source(mPrimary->getPath());
-    if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
-        source = StringPrintf("%s/%d", source.c_str(), userId);
-        fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
+static int prepareMntStorageDir() {
+    std::string mntTarget("/mnt/storage");
+    if (fs_prepare_dir(mntTarget.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
+        PLOG(ERROR) << "fs_prepare_dir failed on " << mntTarget;
+        return -errno;
     }
-
-    std::string target(StringPrintf("/mnt/user/%d/primary", userId));
-    if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
-        if (errno != ENOENT) {
-            PLOG(WARNING) << "Failed to unlink " << target;
-        }
+    if (TEMP_FAILURE_RETRY(mount("/mnt/runtime/write", mntTarget.c_str(),
+            nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
+        PLOG(ERROR) << "Failed to mount /mnt/runtime/write at " << mntTarget;
+        return -errno;
     }
-    LOG(DEBUG) << "Linking " << source << " to " << target;
-    if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
-        PLOG(WARNING) << "Failed to link";
+    if (TEMP_FAILURE_RETRY(mount(nullptr, mntTarget.c_str(),
+            nullptr, MS_REC | MS_SLAVE, nullptr)) == -1) {
+        PLOG(ERROR) << "Failed to set MS_SLAVE at " << mntTarget;
         return -errno;
     }
     return 0;
 }
 
+int VolumeManager::linkPrimary(userid_t userId, const std::vector<std::string>& packageNames) {
+    if (GetBoolProperty(kIsolatedStorage, false)) {
+        // This should ideally go into start() but it's possible that system properties are not
+        // loaded at that point.
+        if (!mMntStorageCreated) {
+            prepareMntStorageDir();
+            mMntStorageCreated = true;
+        }
+
+        if (mountSandboxesForPrimaryVol(userId, packageNames) != 0) {
+            return -errno;
+        }
+        // Keep /sdcard working for shell process
+        std::string primarySource(mPrimary->getPath());
+        if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
+            StringAppendF(&primarySource, "/%d", userId);
+        }
+        std::string target(StringPrintf("/mnt/user/%d/primary", userId));
+        if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
+            if (errno != ENOENT) {
+                PLOG(WARNING) << "Failed to unlink " << target;
+            }
+        }
+        if (TEMP_FAILURE_RETRY(symlink(primarySource.c_str(), target.c_str()))) {
+            PLOG(WARNING) << "Failed to link " << primarySource << " at " << target;
+            return -errno;
+        }
+    } else {
+        std::string source(mPrimary->getPath());
+        if (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated) {
+            source = StringPrintf("%s/%d", source.c_str(), userId);
+            fs_prepare_dir(source.c_str(), 0755, AID_ROOT, AID_ROOT);
+        }
+
+        std::string target(StringPrintf("/mnt/user/%d/primary", userId));
+        if (TEMP_FAILURE_RETRY(unlink(target.c_str()))) {
+            if (errno != ENOENT) {
+                PLOG(WARNING) << "Failed to unlink " << target;
+            }
+        }
+        LOG(DEBUG) << "Linking " << source << " to " << target;
+        if (TEMP_FAILURE_RETRY(symlink(source.c_str(), target.c_str()))) {
+            PLOG(WARNING) << "Failed to link";
+            return -errno;
+        }
+    }
+    return 0;
+}
+
+int VolumeManager::mountSandboxesForPrimaryVol(userid_t userId,
+        const std::vector<std::string>& packageNames) {
+    std::string primaryRoot(StringPrintf("/mnt/storage/%s", mPrimary->getLabel().c_str()));
+    bool isPrimaryEmulated =
+            (mPrimary->getType() == android::vold::VolumeBase::Type::kEmulated);
+    if (isPrimaryEmulated) {
+        StringAppendF(&primaryRoot, "/%d", userId);
+        if (fs_prepare_dir(primaryRoot.c_str(), 0755, AID_ROOT, AID_ROOT) != 0) {
+            PLOG(ERROR) << "fs_prepare_dir failed on " << primaryRoot;
+            return -errno;
+        }
+    }
+
+    std::string sandboxRoot = prepareSubDirs(primaryRoot, "Android/sandbox/",
+            0700, AID_ROOT, AID_ROOT);
+    if (sandboxRoot.empty()) {
+        return -errno;
+    }
+    std::string sharedSandboxRoot;
+    StringAppendF(&sharedSandboxRoot, "%s/shared", sandboxRoot.c_str());
+    // Create shared sandbox base dir for apps with sharedUserIds
+    if (fs_prepare_dir(sharedSandboxRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
+        PLOG(ERROR) << "fs_prepare_dir failed on " << sharedSandboxRoot;
+        return -errno;
+    }
+
+    std::string dataRoot = prepareSubDirs(primaryRoot, "Android/data/",
+            0700, AID_ROOT, AID_ROOT);
+    if (dataRoot.empty()) {
+        return -errno;
+    }
+
+    std::string mntTargetRoot = StringPrintf("/mnt/user/%d", userId);
+    if (fs_prepare_dir(mntTargetRoot.c_str(), 0751, AID_ROOT, AID_ROOT) != 0) {
+        PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
+        return -errno;
+    }
+    mntTargetRoot.append("/package");
+    if (fs_prepare_dir(mntTargetRoot.c_str(), 0700, AID_ROOT, AID_ROOT) != 0) {
+        PLOG(ERROR) << "fs_prepare_dir failed on " << mntTargetRoot;
+        return -errno;
+    }
+
+    for (auto& packageName : packageNames) {
+        const auto& it = mAppIds.find(packageName);
+        if (it == mAppIds.end()) {
+            PLOG(ERROR) << "appId is not available for " << packageName;
+            continue;
+        }
+        appid_t appId = it->second;
+        std::string sandboxId = mSandboxIds[appId];
+        uid_t uid = multiuser_get_uid(userId, appId);
+
+        // Create /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
+        std::string pkgSandboxSourceDir = prepareSandboxSource(uid, sandboxId, sandboxRoot);
+        if (pkgSandboxSourceDir.empty()) {
+            return -errno;
+        }
+
+        // Create [1] /mnt/storage/emulated/0/Android/data/<packageName>
+        // Create [2] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>/Android/data/<packageName>
+        // Mount [1] at [2]
+        std::string pkgDataSourceDir = preparePkgDataSource(packageName, uid, dataRoot);
+        if (pkgDataSourceDir.empty()) {
+            return -errno;
+        }
+        std::string pkgDataTargetDir = preparePkgDataTarget(packageName, uid,
+                pkgSandboxSourceDir);
+        if (pkgDataTargetDir.empty()) {
+            return -errno;
+        }
+        if (TEMP_FAILURE_RETRY(mount(pkgDataSourceDir.c_str(), pkgDataTargetDir.c_str(),
+                nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
+            PLOG(ERROR) << "Failed to mount " << pkgDataSourceDir << " at "
+                        << pkgDataTargetDir;
+            return -errno;
+        }
+
+        // Already created [1] /mnt/storage/emulated/0/Android/sandbox/<sandboxId>
+        // Create [2] /mnt/user/0/package/<packageName>/emulated/0
+        // Mount [1] at [2]
+        std::string pkgSandboxTargetDir = prepareSandboxTarget(packageName, uid,
+                mPrimary->getLabel(), mntTargetRoot, isPrimaryEmulated);
+        if (pkgSandboxTargetDir.empty()) {
+            return -errno;
+        }
+
+        if (TEMP_FAILURE_RETRY(mount(pkgSandboxSourceDir.c_str(), pkgSandboxTargetDir.c_str(),
+                nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
+            PLOG(ERROR) << "Failed to mount " << pkgSandboxSourceDir << " at "
+                        << pkgSandboxTargetDir;
+            return -errno;
+        }
+
+        // Create [1] /mnt/user/0/package/<packageName>/self/primary
+        // Already created [2] /mnt/user/0/package/<packageName>/emulated/0
+        // Mount [2] at [1]
+        std::string pkgPrimaryTargetDir = prepareSubDirs(
+                StringPrintf("%s/%s", mntTargetRoot.c_str(), packageName.c_str()),
+                "self/primary/", 0755, uid, uid);
+        if (pkgPrimaryTargetDir.empty()) {
+            return -errno;
+        }
+        if (TEMP_FAILURE_RETRY(mount(pkgSandboxTargetDir.c_str(), pkgPrimaryTargetDir.c_str(),
+                nullptr, MS_BIND | MS_REC, nullptr)) == -1) {
+            PLOG(ERROR) << "Failed to mount " << pkgSandboxTargetDir << " at "
+                        << pkgPrimaryTargetDir;
+            return -errno;
+        }
+    }
+    return 0;
+}
+
+std::string VolumeManager::prepareSubDirs(const std::string& pathPrefix,
+        const std::string& subDirs, mode_t mode, uid_t uid, gid_t gid) {
+    std::string path(pathPrefix);
+    std::vector<std::string> subDirList = android::base::Split(subDirs, "/");
+    for (size_t i = 0; i < subDirList.size(); ++i) {
+        std::string subDir = subDirList[i];
+        if (subDir.empty()) {
+            continue;
+        }
+        StringAppendF(&path, "/%s", subDir.c_str());
+        if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
+            PLOG(ERROR) << "fs_prepare_dir failed on " << path;
+            return kEmptyString;
+        }
+    }
+    return path;
+}
+
+std::string VolumeManager::prepareSandboxSource(uid_t uid, const std::string& sandboxId,
+        const std::string& sandboxRootDir) {
+    std::string sandboxSourceDir(sandboxRootDir);
+    if (android::base::StartsWith(sandboxId, "shared:")) {
+        StringAppendF(&sandboxSourceDir, "/shared/%s", sandboxId.substr(7).c_str());
+    } else {
+        StringAppendF(&sandboxSourceDir, "/%s", sandboxId.c_str());
+    }
+    if (fs_prepare_dir(sandboxSourceDir.c_str(), 0755, uid, uid) != 0) {
+        PLOG(ERROR) << "fs_prepare_dir failed on " << sandboxSourceDir;
+        return kEmptyString;
+    }
+    return sandboxSourceDir;
+}
+
+std::string VolumeManager::prepareSandboxTarget(const std::string& packageName, uid_t uid,
+        const std::string& volumeLabel, const std::string& mntTargetRootDir,
+        bool isUserDependent) {
+    std::string segment;
+    if (isUserDependent) {
+        segment = StringPrintf("%s/%s/%d/",
+                packageName.c_str(), volumeLabel.c_str(), multiuser_get_user_id(uid));
+    } else {
+        segment = StringPrintf("%s/%s/",
+                packageName.c_str(), volumeLabel.c_str());
+    }
+    return prepareSubDirs(mntTargetRootDir, segment.c_str(), 0755, uid, uid);
+}
+
+std::string VolumeManager::preparePkgDataSource(const std::string& packageName, uid_t uid,
+        const std::string& dataRootDir) {
+    std::string dataSourceDir = StringPrintf("%s/%s", dataRootDir.c_str(), packageName.c_str());
+    if (fs_prepare_dir(dataSourceDir.c_str(), 0755, uid, uid) != 0) {
+        PLOG(ERROR) << "fs_prepare_dir failed on " << dataSourceDir;
+        return kEmptyString;
+    }
+    return dataSourceDir;
+}
+
+std::string VolumeManager::preparePkgDataTarget(const std::string& packageName, uid_t uid,
+        const std::string& pkgSandboxDir) {
+    std::string segment = StringPrintf("Android/data/%s/", packageName.c_str());
+    return prepareSubDirs(pkgSandboxDir, segment.c_str(), 0755, uid, uid);
+}
+
 int VolumeManager::onUserAdded(userid_t userId, int userSerialNumber) {
     mAddedUsers[userId] = userSerialNumber;
     return 0;
@@ -372,7 +601,7 @@
     return 0;
 }
 
-int VolumeManager::onUserStarted(userid_t userId) {
+int VolumeManager::onUserStarted(userid_t userId, const std::vector<std::string>& packageNames) {
     // Note that sometimes the system will spin up processes from Zygote
     // before actually starting the user, so we're okay if Zygote
     // already created this directory.
@@ -380,8 +609,9 @@
     fs_prepare_dir(path.c_str(), 0755, AID_ROOT, AID_ROOT);
 
     mStartedUsers.insert(userId);
+    mUserPackages[userId] = packageNames;
     if (mPrimary) {
-        linkPrimary(userId);
+        linkPrimary(userId, packageNames);
     }
     return 0;
 }
@@ -391,6 +621,40 @@
     return 0;
 }
 
+int VolumeManager::addAppIds(const std::vector<std::string>& packageNames,
+        const std::vector<int32_t>& appIds) {
+    for (size_t i = 0; i < packageNames.size(); ++i) {
+        mAppIds[packageNames[i]] = appIds[i];
+    }
+    return 0;
+}
+
+int VolumeManager::addSandboxIds(const std::vector<int32_t>& appIds,
+        const std::vector<std::string>& sandboxIds) {
+    for (size_t i = 0; i < appIds.size(); ++i) {
+        mSandboxIds[appIds[i]] = sandboxIds[i];
+    }
+    return 0;
+}
+
+int VolumeManager::mountExternalStorageForApp(const std::string& packageName, appid_t appId,
+        const std::string& sandboxId, userid_t userId) {
+    if (!GetBoolProperty(kIsolatedStorage, false)) {
+        return 0;
+    } else if (mStartedUsers.find(userId) == mStartedUsers.end()) {
+        // User not started, no need to do anything now. Required bind mounts for the package will
+        // be created when the user starts.
+        return 0;
+    }
+    mUserPackages[userId].push_back(packageName);
+    mAppIds[packageName] = appId;
+    mSandboxIds[appId] = sandboxId;
+    if (mPrimary) {
+        return mountSandboxesForPrimaryVol(userId, {packageName});
+    }
+    return 0;
+}
+
 int VolumeManager::onSecureKeyguardStateChanged(bool isShowing) {
     mSecureKeyguardShowing = isShowing;
     if (!mSecureKeyguardShowing) {
@@ -408,7 +672,7 @@
 int VolumeManager::setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol) {
     mPrimary = vol;
     for (userid_t userId : mStartedUsers) {
-        linkPrimary(userId);
+        linkPrimary(userId, mUserPackages[userId]);
     }
     return 0;
 }
@@ -441,6 +705,11 @@
 }
 
 int VolumeManager::remountUid(uid_t uid, const std::string& mode) {
+    // If the isolated storage is enabled, return -1 since in the isolated storage world, there
+    // are no longer any runtime storage permissions, so this shouldn't be called anymore.
+    if (GetBoolProperty(kIsolatedStorage, false)) {
+        return -1;
+    }
     LOG(DEBUG) << "Remounting " << uid << " as mode " << mode;
 
     DIR* dir;
@@ -577,6 +846,17 @@
     updateVirtualDisk();
     mAddedUsers.clear();
     mStartedUsers.clear();
+
+    mUserPackages.clear();
+    mAppIds.clear();
+    mSandboxIds.clear();
+
+    // For unmounting dirs under /mnt/user/<user-id>/package/<package-name>
+    unmount_tree("/mnt/user/");
+    // For unmounting dirs under /mnt/storage including the bind mount at /mnt/storage, that's
+    // why no trailing '/'
+    unmount_tree("/mnt/storage");
+    mMntStorageCreated = false;
     return 0;
 }
 
@@ -625,7 +905,8 @@
         auto test = std::string(mentry->mnt_dir);
         if ((android::base::StartsWith(test, "/mnt/") &&
              !android::base::StartsWith(test, "/mnt/vendor") &&
-             !android::base::StartsWith(test, "/mnt/product")) ||
+             !android::base::StartsWith(test, "/mnt/product") &&
+             !android::base::StartsWith(test, "/mnt/storage")) ||
             android::base::StartsWith(test, "/storage/")) {
             toUnmount.push_front(test);
         }
diff --git a/VolumeManager.h b/VolumeManager.h
index fb455d8..38355fc 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -91,9 +91,15 @@
 
     int onUserAdded(userid_t userId, int userSerialNumber);
     int onUserRemoved(userid_t userId);
-    int onUserStarted(userid_t userId);
+    int onUserStarted(userid_t userId, const std::vector<std::string>& packageNames);
     int onUserStopped(userid_t userId);
 
+    int addAppIds(const std::vector<std::string>& packageNames, const std::vector<int32_t>& appIds);
+    int addSandboxIds(const std::vector<int32_t>& appIds,
+            const std::vector<std::string>& sandboxIds);
+    int mountExternalStorageForApp(const std::string& packageName, appid_t appId,
+            const std::string& sandboxId, userid_t userId);
+
     int onSecureKeyguardStateChanged(bool isShowing);
 
     int setPrimary(const std::shared_ptr<android::vold::VolumeBase>& vol);
@@ -132,7 +138,20 @@
     VolumeManager();
     void readInitialState();
 
-    int linkPrimary(userid_t userId);
+    int linkPrimary(userid_t userId, const std::vector<std::string>& packageNames);
+
+    std::string prepareSandboxSource(uid_t uid, const std::string& sandboxId,
+            const std::string& sandboxRootDir);
+    std::string prepareSandboxTarget(const std::string& packageName, uid_t uid,
+            const std::string& volumeLabel, const std::string& mntTargetRootDir, bool isUserDependent);
+    std::string preparePkgDataSource(const std::string& packageName, uid_t uid,
+            const std::string& dataRootDir);
+    std::string preparePkgDataTarget(const std::string& packageName, uid_t uid,
+            const std::string& pkgSandboxDir);
+    int mountSandboxesForPrimaryVol(userid_t userId,
+            const std::vector<std::string>& packageNames);
+    std::string prepareSubDirs(const std::string& pathPrefix, const std::string& subDirs,
+            mode_t mode, uid_t uid, gid_t gid);
 
     void handleDiskAdded(const std::shared_ptr<android::vold::Disk>& disk);
     void handleDiskChanged(dev_t device);
@@ -156,8 +175,13 @@
     std::shared_ptr<android::vold::VolumeBase> mInternalEmulated;
     std::shared_ptr<android::vold::VolumeBase> mPrimary;
 
+    std::unordered_map<std::string, appid_t> mAppIds;
+    std::unordered_map<appid_t, std::string> mSandboxIds;
+    std::unordered_map<userid_t, std::vector<std::string>> mUserPackages;
+
     int mNextObbId;
     bool mSecureKeyguardShowing;
+    bool mMntStorageCreated;
 };
 
 #endif
diff --git a/binder/android/os/IVold.aidl b/binder/android/os/IVold.aidl
index f386889..cff1baa 100644
--- a/binder/android/os/IVold.aidl
+++ b/binder/android/os/IVold.aidl
@@ -29,9 +29,12 @@
 
     void onUserAdded(int userId, int userSerial);
     void onUserRemoved(int userId);
-    void onUserStarted(int userId);
+    void onUserStarted(int userId, in @utf8InCpp String[] packageNames);
     void onUserStopped(int userId);
 
+    void addAppIds(in @utf8InCpp String[] packageNames, in int[] appIds);
+    void addSandboxIds(in int[] appIds, in @utf8InCpp String[] sandboxIds);
+
     void onSecureKeyguardStateChanged(boolean isShowing);
 
     void partition(@utf8InCpp String diskId, int partitionType, int ratio);
@@ -93,6 +96,9 @@
     void prepareUserStorage(@nullable @utf8InCpp String uuid, int userId, int userSerial, int storageFlags);
     void destroyUserStorage(@nullable @utf8InCpp String uuid, int userId, int storageFlags);
 
+    void mountExternalStorageForApp(in @utf8InCpp String packageName,
+            int appId, in @utf8InCpp String sandboxId, int userId);
+
     const int ENCRYPTION_FLAG_NO_UI = 4;
 
     const int ENCRYPTION_STATE_NONE = 1;
@@ -123,6 +129,7 @@
     const int REMOUNT_MODE_DEFAULT = 1;
     const int REMOUNT_MODE_READ = 2;
     const int REMOUNT_MODE_WRITE = 3;
+    const int REMOUNT_MODE_FULL = 4;
 
     const int VOLUME_STATE_UNMOUNTED = 0;
     const int VOLUME_STATE_CHECKING = 1;
diff --git a/model/EmulatedVolume.cpp b/model/EmulatedVolume.cpp
index 6e1ffce..25ea602 100644
--- a/model/EmulatedVolume.cpp
+++ b/model/EmulatedVolume.cpp
@@ -17,8 +17,8 @@
 #include "EmulatedVolume.h"
 #include "Utils.h"
 
-#include <android-base/stringprintf.h>
 #include <android-base/logging.h>
+#include <android-base/stringprintf.h>
 #include <cutils/fs.h>
 #include <private/android_filesystem_config.h>
 #include <utils/Timers.h>
@@ -69,6 +69,7 @@
 
     setInternalPath(mRawPath);
     setPath(StringPrintf("/storage/%s", label.c_str()));
+    setLabel(label);
 
     if (fs_prepare_dir(mFuseDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
             fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
diff --git a/model/PublicVolume.cpp b/model/PublicVolume.cpp
index 9f2ed85..4076e73 100644
--- a/model/PublicVolume.cpp
+++ b/model/PublicVolume.cpp
@@ -129,6 +129,7 @@
     } else {
         setPath(mRawPath);
     }
+    setLabel(stableName);
 
     if (fs_prepare_dir(mRawPath.c_str(), 0700, AID_ROOT, AID_ROOT)) {
         PLOG(ERROR) << getId() << " failed to create mount points";
diff --git a/model/VolumeBase.cpp b/model/VolumeBase.cpp
index 429f134..cf3d54e 100644
--- a/model/VolumeBase.cpp
+++ b/model/VolumeBase.cpp
@@ -136,6 +136,16 @@
     return OK;
 }
 
+status_t VolumeBase::setLabel(const std::string& label) {
+    if (mState != State::kChecking) {
+        LOG(WARNING) << getId() << " label change requires state checking";
+        return -EBUSY;
+    }
+
+    mLabel = label;
+    return OK;
+}
+
 android::sp<android::os::IVoldListener> VolumeBase::getListener() {
     if (mSilent) {
         return nullptr;
diff --git a/model/VolumeBase.h b/model/VolumeBase.h
index 4aa8b02..2052c15 100644
--- a/model/VolumeBase.h
+++ b/model/VolumeBase.h
@@ -84,6 +84,7 @@
     State getState() { return mState; }
     const std::string& getPath() { return mPath; }
     const std::string& getInternalPath() { return mInternalPath; }
+    const std::string& getLabel() { return mLabel; }
 
     status_t setDiskId(const std::string& diskId);
     status_t setPartGuid(const std::string& partGuid);
@@ -114,6 +115,7 @@
     status_t setId(const std::string& id);
     status_t setPath(const std::string& path);
     status_t setInternalPath(const std::string& internalPath);
+    status_t setLabel(const std::string& label);
 
     android::sp<android::os::IVoldListener> getListener();
 
@@ -140,6 +142,12 @@
     std::string mInternalPath;
     /* Flag indicating that volume should emit no events */
     bool mSilent;
+    /**
+     * Label used for representing the package sandboxes on external storage volumes.
+     * For emulated volume, this would be "emulated" and for public volumes, UUID if available,
+     * otherwise some other unique id.
+     */
+    std::string mLabel;
 
     /* Volumes stacked on top of this volume */
     std::list<std::shared_ptr<VolumeBase>> mVolumes;