resolve merge conflicts of b7d5a47cec to master.

Change-Id: I0c5211a00d92d0ee796bb9c77d2e13675a2a3e8d
diff --git a/AutoCloseFD.h b/AutoCloseFD.h
new file mode 100644
index 0000000..f9d7c86
--- /dev/null
+++ b/AutoCloseFD.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2015 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 <string>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+// File descriptor which is automatically closed when this object is destroyed.
+// Cannot be copied, since that would cause double-closes.
+class AutoCloseFD {
+public:
+    AutoCloseFD(const char *path, int flags = O_RDONLY, int mode = 0):
+        fd{TEMP_FAILURE_RETRY(open(path, flags | O_CLOEXEC, mode))} {}
+    AutoCloseFD(const std::string &path, int flags = O_RDONLY, int mode = 0):
+        AutoCloseFD(path.c_str(), flags, mode) {}
+    ~AutoCloseFD() {
+        if (fd != -1) {
+            int preserve_errno = errno;
+            if (close(fd) == -1) {
+                SLOGE("close(2) failed: %s", strerror(errno));
+            };
+            errno = preserve_errno;
+        }
+    }
+    AutoCloseFD(const AutoCloseFD&) = delete;
+    AutoCloseFD& operator=(const AutoCloseFD&) = delete;
+    explicit operator bool() {return fd != -1;}
+    int get() const {return fd;}
+private:
+    const int fd;
+};
+
diff --git a/CommandListener.cpp b/CommandListener.cpp
index 4a8ed75..8b02073 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -44,8 +44,6 @@
 #include "Process.h"
 #include "Loop.h"
 #include "Devmapper.h"
-#include "Ext4Crypt.h"
-#include "cryptfs.h"
 #include "MoveTask.h"
 #include "TrimTask.h"
 
diff --git a/CryptCommandListener.cpp b/CryptCommandListener.cpp
index 1babef7..ac2607a 100644
--- a/CryptCommandListener.cpp
+++ b/CryptCommandListener.cpp
@@ -16,6 +16,7 @@
 
 #include <stdlib.h>
 #include <sys/socket.h>
+#include <sys/stat.h>
 #include <sys/types.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
@@ -30,7 +31,9 @@
 
 #define LOG_TAG "VoldCryptCmdListener"
 
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
+
 #include <cutils/fs.h>
 #include <cutils/log.h>
 #include <cutils/sockets.h>
@@ -43,6 +46,7 @@
 #include "ResponseCode.h"
 #include "cryptfs.h"
 #include "Ext4Crypt.h"
+#include "Utils.h"
 
 #define DUMP_ARGS 0
 
@@ -110,6 +114,14 @@
     }
 }
 
+static char* parseNull(char* arg) {
+    if (strcmp(arg, "!") == 0) {
+        return nullptr;
+    } else {
+        return arg;
+    }
+}
+
 int CryptCommandListener::CryptfsCmd::runCommand(SocketClient *cli,
                                                  int argc, char **argv) {
     if ((cli->getUid() != 0) && (cli->getUid() != AID_SYSTEM)) {
@@ -124,6 +136,7 @@
 
     int rc = 0;
 
+    std::string cmd(argv[1]);
     if (!strcmp(argv[1], "checkpw")) {
         if (argc != 3) {
             cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs checkpw <passwd>", false);
@@ -338,26 +351,39 @@
         SLOGD("cryptfs setusercryptopolicies");
         dumpArgs(argc, argv, -1);
         rc = e4crypt_set_user_crypto_policies(argv[2]);
-    } else if (!strcmp(argv[1], "createnewuserdir")) {
-        if (argc != 4) {
+
+    } else if (!strcmp(argv[1], "isConvertibleToFBE")) {
+        if (argc != 2) {
             cli->sendMsg(ResponseCode::CommandSyntaxError,
-                "Usage: cryptfs createnewuserdir <userHandle> <path>", false);
+                "Usage: cryptfs isConvertibleToFBE", false);
             return 0;
         }
         // ext4enc:TODO: send a CommandSyntaxError if argv[2] not an integer
-        SLOGD("cryptfs createnewuserdir");
+        SLOGD("cryptfs isConvertibleToFBE");
         dumpArgs(argc, argv, -1);
-        rc = e4crypt_create_new_user_dir(argv[2], argv[3]);
-    } else if (!strcmp(argv[1], "deleteuserkey")) {
-        if (argc != 3) {
-            cli->sendMsg(ResponseCode::CommandSyntaxError,
-                "Usage: cryptfs deleteuserkey <userHandle>", false);
-            return 0;
-        }
-        // ext4enc:TODO: send a CommandSyntaxError if argv[2] not an integer
-        SLOGD("cryptfs deleteuserkey");
-        dumpArgs(argc, argv, -1);
-        rc = e4crypt_delete_user_key(argv[2]);
+        rc = cryptfs_isConvertibleToFBE();
+
+    } else if (cmd == "create_user_key" && argc > 3) {
+        // create_user_key [user] [serial]
+        return sendGenericOkFail(cli, e4crypt_create_user_key(atoi(argv[2])));
+
+    } else if (cmd == "destroy_user_key" && argc > 2) {
+        // destroy_user_key [user]
+        return sendGenericOkFail(cli, e4crypt_destroy_user_key(atoi(argv[2])));
+
+    } else if (cmd == "unlock_user_key" && argc > 4) {
+        // unlock_user_key [user] [serial] [token]
+        return sendGenericOkFail(cli, e4crypt_unlock_user_key(atoi(argv[2]), parseNull(argv[4])));
+
+    } else if (cmd == "lock_user_key" && argc > 2) {
+        // lock_user_key [user]
+        return sendGenericOkFail(cli, e4crypt_lock_user_key(atoi(argv[2])));
+
+    } else if (cmd == "prepare_user_storage" && argc > 4) {
+        // prepare_user_storage [uuid] [user] [serial]
+        return sendGenericOkFail(cli,
+                e4crypt_prepare_user_storage(parseNull(argv[2]), atoi(argv[3])));
+
     } else {
         dumpArgs(argc, argv, -1);
         cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown cryptfs cmd", false);
diff --git a/Ext4Crypt.cpp b/Ext4Crypt.cpp
index 0807c2c..1f92e57 100644
--- a/Ext4Crypt.cpp
+++ b/Ext4Crypt.cpp
@@ -1,5 +1,23 @@
+/*
+ * Copyright (C) 2015 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 "Ext4Crypt.h"
 
+#include "Utils.h"
+
 #include <iomanip>
 #include <map>
 #include <fstream>
@@ -23,11 +41,19 @@
 #include "ext4_crypt_init_extensions.h"
 
 #define LOG_TAG "Ext4Crypt"
-#include "cutils/log.h"
+
+#include <cutils/fs.h>
+#include <cutils/log.h>
 #include <cutils/klog.h>
+
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/stringprintf.h>
 
+using android::base::StringPrintf;
+
+static const char* kPropEmulateFbe = "persist.sys.emulate_fbe";
+
 namespace {
     // Key length in bits
     const int key_length = 128;
@@ -509,18 +535,14 @@
         .Set(fieldname, std::string(value)) ? 0 : -1;
 }
 
-static std::string get_key_path(
-    const char *mount_path,
-    const char *user_handle)
-{
+static std::string get_key_path(const char *mount_path, userid_t user_id) {
     // ext4enc:TODO get the path properly
-    auto key_dir = android::base::StringPrintf("%s/misc/vold/user_keys",
-        mount_path);
-    if (mkdir(key_dir.c_str(), 0700) < 0 && errno != EEXIST) {
-        SLOGE("Unable to create %s (%s)", key_dir.c_str(), strerror(errno));
+    auto key_dir = StringPrintf("%s/misc/vold/user_keys", mount_path);
+    if (fs_prepare_dir(key_dir.c_str(), 0700, AID_ROOT, AID_ROOT)) {
+        PLOG(ERROR) << "Failed to prepare " << key_dir;
         return "";
     }
-    return key_dir + "/" + user_handle;
+    return StringPrintf("%s/%d", key_dir.c_str(), user_id);
 }
 
 // ext4enc:TODO this can't be the only place keys are read from /dev/urandom
@@ -562,13 +584,11 @@
     return key;
 }
 
-static int e4crypt_set_user_policy(const char *mount_path, const char *user_handle,
-                            const char *path, bool create_if_absent)
-{
-    SLOGD("e4crypt_set_user_policy for %s", user_handle);
-    auto user_key = e4crypt_get_key(
-        get_key_path(mount_path, user_handle),
-        create_if_absent);
+static int e4crypt_set_user_policy(const char *mount_path, userid_t user_id,
+        const char *path, bool create_if_absent) {
+    SLOGD("e4crypt_set_user_policy for %d", user_id);
+    auto user_key = e4crypt_get_key(get_key_path(mount_path, user_id),
+            create_if_absent);
     if (user_key.empty()) {
         return -1;
     }
@@ -579,24 +599,6 @@
     return do_policy_set(path, raw_ref.c_str(), raw_ref.size());
 }
 
-int e4crypt_create_new_user_dir(const char *user_handle, const char *path) {
-    SLOGD("e4crypt_create_new_user_dir(\"%s\", \"%s\")", user_handle, path);
-    if (mkdir(path, S_IRWXU | S_IRWXG | S_IXOTH) < 0) {
-        return -1;
-    }
-    if (chmod(path, S_IRWXU | S_IRWXG | S_IXOTH) < 0) {
-        return -1;
-    }
-    if (chown(path, AID_SYSTEM, AID_SYSTEM) < 0) {
-        return -1;
-    }
-    if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
-        // ext4enc:TODO handle errors from this.
-        e4crypt_set_user_policy(DATA_MNT_POINT, user_handle, path, true);
-    }
-    return 0;
-}
-
 static bool is_numeric(const char *name) {
     for (const char *p = name; *p != '\0'; p++) {
         if (!isdigit(*p))
@@ -626,10 +628,10 @@
         if (result->d_type != DT_DIR || !is_numeric(result->d_name)) {
             continue; // skips user 0, which is a symlink
         }
+        auto user_id = atoi(result->d_name);
         auto user_dir = std::string() + dir + "/" + result->d_name;
         // ext4enc:TODO don't hardcode /data
-        if (e4crypt_set_user_policy("/data", result->d_name,
-                user_dir.c_str(), false)) {
+        if (e4crypt_set_user_policy("/data", user_id, user_dir.c_str(), false)) {
             // ext4enc:TODO If this function fails, stop the boot: we must
             // deliver on promised encryption.
             SLOGE("Unable to set policy on %s\n", user_dir.c_str());
@@ -638,9 +640,20 @@
     return 0;
 }
 
-int e4crypt_delete_user_key(const char *user_handle) {
-    SLOGD("e4crypt_delete_user_key(\"%s\")", user_handle);
-    auto key_path = get_key_path(DATA_MNT_POINT, user_handle);
+int e4crypt_create_user_key(userid_t user_id) {
+    SLOGD("e4crypt_create_user_key(%d)", user_id);
+    // TODO: create second key for user_de data
+    if (e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), true).empty()) {
+        return -1;
+    } else {
+        return 0;
+    }
+}
+
+int e4crypt_destroy_user_key(userid_t user_id) {
+    SLOGD("e4crypt_destroy_user_key(%d)", user_id);
+    // TODO: destroy second key for user_de data
+    auto key_path = get_key_path(DATA_MNT_POINT, user_id);
     auto key = e4crypt_get_key(key_path, false);
     auto ext4_key = fill_key(key);
     auto ref = keyname(generate_key_ref(ext4_key.raw, ext4_key.size));
@@ -660,6 +673,7 @@
         SLOGD("Forked for secdiscard");
         execl("/system/bin/secdiscard",
             "/system/bin/secdiscard",
+            "--",
             key_path.c_str(),
             NULL);
         SLOGE("Unable to launch secdiscard on %s: %s\n", key_path.c_str(),
@@ -669,3 +683,66 @@
     // ext4enc:TODO reap the zombie
     return 0;
 }
+
+int e4crypt_unlock_user_key(userid_t user_id, const char* token) {
+    if (property_get_bool(kPropEmulateFbe, false)) {
+        // When in emulation mode, we just use chmod
+        if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0771) ||
+                chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0771)) {
+            PLOG(ERROR) << "Failed to unlock user " << user_id;
+            return -1;
+        }
+    } else {
+        auto user_key = e4crypt_get_key(get_key_path(DATA_MNT_POINT, user_id), false);
+        if (user_key.empty()) {
+            return -1;
+        }
+        auto raw_ref = e4crypt_install_key(user_key);
+        if (raw_ref.empty()) {
+            return -1;
+        }
+    }
+    return 0;
+}
+
+int e4crypt_lock_user_key(userid_t user_id) {
+    if (property_get_bool(kPropEmulateFbe, false)) {
+        // When in emulation mode, we just use chmod
+        if (chmod(android::vold::BuildDataSystemCePath(user_id).c_str(), 0000) ||
+                chmod(android::vold::BuildDataUserPath(nullptr, user_id).c_str(), 0000)) {
+            PLOG(ERROR) << "Failed to lock user " << user_id;
+            return -1;
+        }
+    } else {
+        // TODO: remove from kernel keyring
+    }
+    return 0;
+}
+
+int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id) {
+    std::string system_ce_path(android::vold::BuildDataSystemCePath(user_id));
+    std::string user_ce_path(android::vold::BuildDataUserPath(volume_uuid, user_id));
+    std::string user_de_path(android::vold::BuildDataUserDePath(volume_uuid, user_id));
+
+    if (fs_prepare_dir(system_ce_path.c_str(), 0700, AID_SYSTEM, AID_SYSTEM)) {
+        PLOG(ERROR) << "Failed to prepare " << system_ce_path;
+        return -1;
+    }
+    if (fs_prepare_dir(user_ce_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
+        PLOG(ERROR) << "Failed to prepare " << user_ce_path;
+        return -1;
+    }
+    if (fs_prepare_dir(user_de_path.c_str(), 0771, AID_SYSTEM, AID_SYSTEM)) {
+        PLOG(ERROR) << "Failed to prepare " << user_de_path;
+        return -1;
+    }
+
+    if (e4crypt_crypto_complete(DATA_MNT_POINT) == 0) {
+        if (e4crypt_set_user_policy(DATA_MNT_POINT, user_id, system_ce_path.c_str(), true)
+                || e4crypt_set_user_policy(DATA_MNT_POINT, user_id, user_ce_path.c_str(), true)) {
+            return -1;
+        }
+    }
+
+    return 0;
+}
diff --git a/Ext4Crypt.h b/Ext4Crypt.h
index f5c2871..43b229c 100644
--- a/Ext4Crypt.h
+++ b/Ext4Crypt.h
@@ -1,6 +1,24 @@
+/*
+ * Copyright (C) 2015 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 <stddef.h>
 #include <sys/cdefs.h>
 
+#include <cutils/multiuser.h>
+
 __BEGIN_DECLS
 
 // General functions
@@ -19,7 +37,13 @@
 int e4crypt_set_field(const char* path, const char* fieldname,
                       const char* value);
 int e4crypt_set_user_crypto_policies(const char *path);
-int e4crypt_create_new_user_dir(const char *user_handle, const char *path);
-int e4crypt_delete_user_key(const char *user_handle);
+
+int e4crypt_create_user_key(userid_t user_id);
+int e4crypt_destroy_user_key(userid_t user_id);
+
+int e4crypt_unlock_user_key(userid_t user_id, const char* token);
+int e4crypt_lock_user_key(userid_t user_id);
+
+int e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id);
 
 __END_DECLS
diff --git a/PrivateVolume.cpp b/PrivateVolume.cpp
index a106481..21746b2 100644
--- a/PrivateVolume.cpp
+++ b/PrivateVolume.cpp
@@ -158,6 +158,7 @@
     // Verify that common directories are ready to roll
     if (PrepareDir(mPath + "/app", 0771, AID_SYSTEM, AID_SYSTEM) ||
             PrepareDir(mPath + "/user", 0711, AID_SYSTEM, AID_SYSTEM) ||
+            PrepareDir(mPath + "/user_de", 0711, AID_SYSTEM, AID_SYSTEM) ||
             PrepareDir(mPath + "/media", 0770, AID_MEDIA_RW, AID_MEDIA_RW) ||
             PrepareDir(mPath + "/media/0", 0770, AID_MEDIA_RW, AID_MEDIA_RW) ||
             PrepareDir(mPath + "/local", 0751, AID_ROOT, AID_ROOT) ||
diff --git a/Utils.cpp b/Utils.cpp
index e4f473a..5276bba 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -547,10 +547,55 @@
     return res;
 }
 
+static bool isValidFilename(const std::string& name) {
+    if (name.empty() || (name == ".") || (name == "..")
+            || (name.find('/') != std::string::npos)) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
 std::string BuildKeyPath(const std::string& partGuid) {
     return StringPrintf("%s/expand_%s.key", kKeyPath, partGuid.c_str());
 }
 
+std::string BuildDataSystemCePath(userid_t userId) {
+    // TODO: unify with installd path generation logic
+    std::string data(BuildDataPath(nullptr));
+    return StringPrintf("%s/system_ce/%u", data.c_str(), userId);
+}
+
+std::string BuildDataPath(const char* volumeUuid) {
+    // TODO: unify with installd path generation logic
+    if (volumeUuid == nullptr) {
+        return "/data";
+    } else {
+        CHECK(isValidFilename(volumeUuid));
+        return StringPrintf("/mnt/expand/%s", volumeUuid);
+    }
+}
+
+std::string BuildDataUserPath(const char* volumeUuid, userid_t userId) {
+    // TODO: unify with installd path generation logic
+    std::string data(BuildDataPath(volumeUuid));
+    if (volumeUuid == nullptr) {
+        if (userId == 0) {
+            return StringPrintf("%s/data", data.c_str());
+        } else {
+            return StringPrintf("%s/user/%u", data.c_str(), userId);
+        }
+    } else {
+        return StringPrintf("%s/user/%u", data.c_str(), userId);
+    }
+}
+
+std::string BuildDataUserDePath(const char* volumeUuid, userid_t userId) {
+    // TODO: unify with installd path generation logic
+    std::string data(BuildDataPath(volumeUuid));
+    return StringPrintf("%s/user_de/%u", data.c_str(), userId);
+}
+
 dev_t GetDevice(const std::string& path) {
     struct stat sb;
     if (stat(path.c_str(), &sb)) {
diff --git a/Utils.h b/Utils.h
index 228727a..c88325a 100644
--- a/Utils.h
+++ b/Utils.h
@@ -18,6 +18,7 @@
 #define ANDROID_VOLD_UTILS_H
 
 #include <utils/Errors.h>
+#include <cutils/multiuser.h>
 #include <selinux/selinux.h>
 
 #include <vector>
@@ -93,6 +94,12 @@
 
 std::string BuildKeyPath(const std::string& partGuid);
 
+std::string BuildDataSystemCePath(userid_t userid);
+
+std::string BuildDataPath(const char* volumeUuid);
+std::string BuildDataUserPath(const char* volumeUuid, userid_t userid);
+std::string BuildDataUserDePath(const char* volumeUuid, userid_t userid);
+
 dev_t GetDevice(const std::string& path);
 
 std::string DefaultFstabPath();
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
old mode 100755
new mode 100644
diff --git a/cryptfs.c b/cryptfs.c
index 1f70847..b0aafc2 100644
--- a/cryptfs.c
+++ b/cryptfs.c
@@ -81,6 +81,10 @@
 
 #define DEFAULT_PASSWORD "default_password"
 
+#define CRYPTO_BLOCK_DEVICE "userdata"
+
+#define BREADCRUMB_FILE "/data/misc/vold/convert_fde"
+
 #define EXT4_FS 1
 #define F2FS_FS 2
 
@@ -188,6 +192,11 @@
     keymaster0_device_t *keymaster0_dev = 0;
     keymaster1_device_t *keymaster1_dev = 0;
 
+    if (ftr->keymaster_blob_size) {
+        SLOGI("Already have key");
+        return 0;
+    }
+
     if (keymaster_init(&keymaster0_dev, &keymaster1_dev)) {
         SLOGE("Failed to init keymaster");
         return -1;
@@ -597,6 +606,16 @@
   return rc;
 }
 
+/* Set sha256 checksum in structure */
+static void set_ftr_sha(struct crypt_mnt_ftr *crypt_ftr)
+{
+    SHA256_CTX c;
+    SHA256_Init(&c);
+    memset(crypt_ftr->sha256, 0, sizeof(crypt_ftr->sha256));
+    SHA256_Update(&c, crypt_ftr, sizeof(*crypt_ftr));
+    SHA256_Final(crypt_ftr->sha256, &c);
+}
+
 /* key or salt can be NULL, in which case just skip writing that value.  Useful to
  * update the failed mount count but not change the key.
  */
@@ -612,6 +631,8 @@
   char *fname = NULL;
   struct stat statbuf;
 
+  set_ftr_sha(crypt_ftr);
+
   if (get_crypt_ftr_info(&fname, &starting_off)) {
     SLOGE("Unable to get crypt_ftr_info\n");
     return -1;
@@ -654,6 +675,14 @@
 
 }
 
+static bool check_ftr_sha(const struct crypt_mnt_ftr *crypt_ftr)
+{
+    struct crypt_mnt_ftr copy;
+    memcpy(&copy, crypt_ftr, sizeof(copy));
+    set_ftr_sha(&copy);
+    return memcmp(copy.sha256, crypt_ftr->sha256, sizeof(copy.sha256)) == 0;
+}
+
 static inline int unix_read(int  fd, void*  buff, int  len)
 {
     return TEMP_FAILURE_RETRY(read(fd, buff, len));
@@ -2034,13 +2063,41 @@
     int rc;
 
     rc = check_unmounted_and_get_ftr(&crypt_ftr);
-    if (rc)
+    if (rc) {
+        SLOGE("Could not get footer");
         return rc;
+    }
 
     rc = test_mount_encrypted_fs(&crypt_ftr, passwd,
-                                 DATA_MNT_POINT, "userdata");
+                                 DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
+    if (rc) {
+        SLOGE("Password did not match");
+        return rc;
+    }
 
-    if (rc == 0 && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
+    if (crypt_ftr.flags & CRYPT_FORCE_COMPLETE) {
+        // Here we have a default actual password but a real password
+        // we must test against the scrypted value
+        // First, we must delete the crypto block device that
+        // test_mount_encrypted_fs leaves behind as a side effect
+        delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
+        rc = test_mount_encrypted_fs(&crypt_ftr, DEFAULT_PASSWORD,
+                                     DATA_MNT_POINT, CRYPTO_BLOCK_DEVICE);
+        if (rc) {
+            SLOGE("Default password did not match on reboot encryption");
+            return rc;
+        }
+
+        crypt_ftr.flags &= ~CRYPT_FORCE_COMPLETE;
+        put_crypt_ftr_and_key(&crypt_ftr);
+        rc = cryptfs_changepw(crypt_ftr.crypt_type, passwd);
+        if (rc) {
+            SLOGE("Could not change password on reboot encryption");
+            return rc;
+        }
+    }
+
+    if (crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
         cryptfs_clear_password();
         password = strdup(passwd);
         struct timespec now;
@@ -2912,6 +2969,7 @@
     char key_loc[PROPERTY_VALUE_MAX];
     int num_vols;
     off64_t previously_encrypted_upto = 0;
+    bool rebootEncryption = false;
 
     if (!strcmp(howarg, "wipe")) {
       how = CRYPTO_ENABLE_WIPE;
@@ -2922,21 +2980,33 @@
       goto error_unencrypted;
     }
 
-    /* See if an encryption was underway and interrupted */
     if (how == CRYPTO_ENABLE_INPLACE
-          && get_crypt_ftr_and_key(&crypt_ftr) == 0
-          && (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS)) {
-        previously_encrypted_upto = crypt_ftr.encrypted_upto;
-        crypt_ftr.encrypted_upto = 0;
-        crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
+          && get_crypt_ftr_and_key(&crypt_ftr) == 0) {
+        if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
+            /* An encryption was underway and was interrupted */
+            previously_encrypted_upto = crypt_ftr.encrypted_upto;
+            crypt_ftr.encrypted_upto = 0;
+            crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
 
-        /* At this point, we are in an inconsistent state. Until we successfully
-           complete encryption, a reboot will leave us broken. So mark the
-           encryption failed in case that happens.
-           On successfully completing encryption, remove this flag */
-        crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
+            /* At this point, we are in an inconsistent state. Until we successfully
+               complete encryption, a reboot will leave us broken. So mark the
+               encryption failed in case that happens.
+               On successfully completing encryption, remove this flag */
+            crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
 
-        put_crypt_ftr_and_key(&crypt_ftr);
+            put_crypt_ftr_and_key(&crypt_ftr);
+        } else if (crypt_ftr.flags & CRYPT_FORCE_ENCRYPTION) {
+            if (!check_ftr_sha(&crypt_ftr)) {
+                memset(&crypt_ftr, 0, sizeof(crypt_ftr));
+                put_crypt_ftr_and_key(&crypt_ftr);
+                goto error_unencrypted;
+            }
+
+            /* Doing a reboot-encryption*/
+            crypt_ftr.flags &= ~CRYPT_FORCE_ENCRYPTION;
+            crypt_ftr.flags |= CRYPT_FORCE_COMPLETE;
+            rebootEncryption = true;
+        }
     }
 
     property_get("ro.crypto.state", encrypted_state, "");
@@ -2996,13 +3066,23 @@
         SLOGE("Failed to unmount all vold managed devices");
     }
 
-    /* Now unmount the /data partition. */
-    if (wait_and_unmount(DATA_MNT_POINT, false)) {
-        goto error_unencrypted;
+    /* no_ui means we are being called from init, not settings.
+       Now we always reboot from settings, so !no_ui means reboot
+     */
+    bool onlyCreateHeader = false;
+    if (!no_ui) {
+        /* Try fallback, which is to reboot and try there */
+        onlyCreateHeader = true;
+        FILE* breadcrumb = fopen(BREADCRUMB_FILE, "we");
+        if (breadcrumb == 0) {
+            SLOGE("Failed to create breadcrumb file");
+            goto error_shutting_down;
+        }
+        fclose(breadcrumb);
     }
 
     /* Do extra work for a better UX when doing the long inplace encryption */
-    if (how == CRYPTO_ENABLE_INPLACE) {
+    if (how == CRYPTO_ENABLE_INPLACE && !onlyCreateHeader) {
         /* Now that /data is unmounted, we need to mount a tmpfs
          * /data, set a property saying we're doing inplace encryption,
          * and restart the framework.
@@ -3029,7 +3109,7 @@
 
     /* Start the actual work of making an encrypted filesystem */
     /* Initialize a crypt_mnt_ftr for the partition */
-    if (previously_encrypted_upto == 0) {
+    if (previously_encrypted_upto == 0 && !rebootEncryption) {
         if (cryptfs_init_crypt_mnt_ftr(&crypt_ftr)) {
             goto error_shutting_down;
         }
@@ -3044,7 +3124,11 @@
            complete encryption, a reboot will leave us broken. So mark the
            encryption failed in case that happens.
            On successfully completing encryption, remove this flag */
-        crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
+        if (onlyCreateHeader) {
+            crypt_ftr.flags |= CRYPT_FORCE_ENCRYPTION;
+        } else {
+            crypt_ftr.flags |= CRYPT_INCONSISTENT_STATE;
+        }
         crypt_ftr.crypt_type = crypt_type;
 #ifndef CONFIG_HW_DISK_ENCRYPTION
         strlcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256", MAX_CRYPTO_TYPE_NAME_LEN);
@@ -3065,11 +3149,21 @@
 #endif
 
         /* Make an encrypted master key */
-        if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
+        if (create_encrypted_random_key(onlyCreateHeader ? DEFAULT_PASSWORD : passwd,
+                                        crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
             SLOGE("Cannot create encrypted master key\n");
             goto error_shutting_down;
         }
 
+        /* Replace scrypted intermediate key if we are preparing for a reboot */
+        if (onlyCreateHeader) {
+            unsigned char fake_master_key[KEY_LEN_BYTES];
+            unsigned char encrypted_fake_master_key[KEY_LEN_BYTES];
+            memset(fake_master_key, 0, sizeof(fake_master_key));
+            encrypt_master_key(passwd, crypt_ftr.salt, fake_master_key,
+                               encrypted_fake_master_key, &crypt_ftr);
+        }
+
         /* Write the key to the end of the partition */
         put_crypt_ftr_and_key(&crypt_ftr);
 
@@ -3088,7 +3182,12 @@
         }
     }
 
-    if (how == CRYPTO_ENABLE_INPLACE && !no_ui) {
+    if (onlyCreateHeader) {
+        sleep(2);
+        cryptfs_reboot(reboot);
+    }
+
+    if (how == CRYPTO_ENABLE_INPLACE && (!no_ui || rebootEncryption)) {
         /* startup service classes main and late_start */
         property_set("vold.decrypt", "trigger_restart_min_framework");
         SLOGD("Just triggered restart_min_framework\n");
@@ -3102,7 +3201,7 @@
 
     decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr, 0, 0);
     create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
-                          "userdata");
+                          CRYPTO_BLOCK_DEVICE);
 
     /* If we are continuing, check checksums match */
     rc = 0;
@@ -3135,7 +3234,7 @@
     }
 
     /* Undo the dm-crypt mapping whether we succeed or not */
-    delete_crypto_blk_dev("userdata");
+    delete_crypto_blk_dev(CRYPTO_BLOCK_DEVICE);
 
     if (! rc) {
         /* Success */
@@ -3158,8 +3257,16 @@
             /* default encryption - continue first boot sequence */
             property_set("ro.crypto.state", "encrypted");
             release_wake_lock(lockid);
-            cryptfs_check_passwd(DEFAULT_PASSWORD);
-            cryptfs_restart_internal(1);
+            if (rebootEncryption && crypt_ftr.crypt_type != CRYPT_TYPE_DEFAULT) {
+                // Bring up cryptkeeper that will check the password and set it
+                property_set("vold.decrypt", "trigger_shutdown_framework");
+                sleep(2);
+                property_set("vold.encrypt_progress", "");
+                cryptfs_trigger_restart_min_framework();
+            } else {
+                cryptfs_check_passwd(DEFAULT_PASSWORD);
+                cryptfs_restart_internal(1);
+            }
             return 0;
           } else {
             sleep(2); /* Give the UI a chance to show 100% progress */
@@ -3710,6 +3817,12 @@
     return e4crypt_enable(DATA_MNT_POINT);
 }
 
+int cryptfs_isConvertibleToFBE()
+{
+    struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
+    return fs_mgr_is_convertible_to_fbe(rec) ? 1 : 0;
+}
+
 int cryptfs_create_default_ftr(struct crypt_mnt_ftr* crypt_ftr, __attribute__((unused))int key_length)
 {
     if (cryptfs_init_crypt_mnt_ftr(crypt_ftr)) {
diff --git a/cryptfs.h b/cryptfs.h
index fd6f3da..033767f 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -52,6 +52,16 @@
                                         correctly marked partial encryption */
 #define CRYPT_DATA_CORRUPT 0x8 /* Set when encryption is fine, but the
                                   underlying volume is corrupt */
+#define CRYPT_FORCE_ENCRYPTION 0x10 /* Set when it is time to encrypt this
+                                       volume on boot. Everything in this
+                                       structure is set up correctly as
+                                       though device is encrypted except
+                                       that the master key is encrypted with the
+                                       default password. */
+#define CRYPT_FORCE_COMPLETE 0x20 /* Set when the above encryption cycle is
+                                     complete. On next cryptkeeper entry, match
+                                     the password. If it matches fix the master
+                                     key and remove this flag. */
 
 /* Allowed values for type in the structure below */
 #define CRYPT_TYPE_PASSWORD 0 /* master_key is encrypted with a password
@@ -94,7 +104,7 @@
   __le32 keysize;       /* in bytes */
   __le32 crypt_type;    /* how master_key is encrypted. Must be a
                          * CRYPT_TYPE_XXX value */
-  __le64 fs_size;	/* Size of the encrypted fs, in 512 byte sectors */
+  __le64 fs_size;       /* Size of the encrypted fs, in 512 byte sectors */
   __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
                                   mount, set to 0 on successful mount */
   unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
@@ -145,6 +155,12 @@
      then we will be OK.
    */
   unsigned char scrypted_intermediate_key[SCRYPT_LEN];
+
+  /* sha of this structure with this element set to zero
+     Used when encrypting on reboot to validate structure before doing something
+     fatal
+   */
+  unsigned char sha256[SHA256_DIGEST_LENGTH];
 };
 
 /* Persistant data that should be available before decryption.
@@ -231,6 +247,7 @@
   int cryptfs_get_password_type(void);
   const char* cryptfs_get_password(void);
   void cryptfs_clear_password(void);
+  int cryptfs_isConvertibleToFBE(void);
 
   // Functions for file encryption to use to inherit our encryption logic
   int cryptfs_create_default_ftr(struct crypt_mnt_ftr* ftr, int key_length);
@@ -238,6 +255,7 @@
                              unsigned char* master_key);
   int cryptfs_set_password(struct crypt_mnt_ftr* ftr, const char* password,
                            const unsigned char* master_key);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/fs/F2fs.cpp b/fs/F2fs.cpp
index 84d27c4..0d12b07 100644
--- a/fs/F2fs.cpp
+++ b/fs/F2fs.cpp
@@ -43,7 +43,7 @@
 status_t Check(const std::string& source) {
     std::vector<std::string> cmd;
     cmd.push_back(kFsckPath);
-    cmd.push_back("-f");
+    cmd.push_back("-a");
     cmd.push_back(source);
 
     // f2fs devices are currently always trusted
diff --git a/main.cpp b/main.cpp
index 9cbcf88..279405f 100644
--- a/main.cpp
+++ b/main.cpp
@@ -18,6 +18,7 @@
 #include "VolumeManager.h"
 #include "CommandListener.h"
 #include "CryptCommandListener.h"
+#include "Ext4Crypt.h"
 #include "NetlinkManager.h"
 #include "cryptfs.h"
 #include "sehandle.h"
@@ -96,6 +97,9 @@
         vm->setDebug(true);
     }
 
+    // Prepare owner storage
+    e4crypt_prepare_user_storage(nullptr, 0);
+
     cl = new CommandListener();
     ccl = new CryptCommandListener();
     vm->setBroadcaster((SocketListener *) cl);
diff --git a/secdiscard.cpp b/secdiscard.cpp
index 3f4ab2e..f7adb0d 100644
--- a/secdiscard.cpp
+++ b/secdiscard.cpp
@@ -14,7 +14,9 @@
  * limitations under the License.
  */
 
+#include <memory>
 #include <string>
+#include <vector>
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -24,213 +26,184 @@
 #include <fcntl.h>
 #include <linux/fs.h>
 #include <linux/fiemap.h>
+#include <mntent.h>
 
 #define LOG_TAG "secdiscard"
 #include "cutils/log.h"
 
-// Deliberately limit ourselves to wiping small files.
-#define MAX_WIPE_LENGTH 4096
-#define INIT_BUFFER_SIZE 2048
+#include <AutoCloseFD.h>
 
-static void usage(char *progname);
-static void destroy_key(const std::string &path);
-static int file_device_range(const std::string &path, uint64_t range[2]);
-static int open_block_device_for_path(const std::string &path);
-static int read_file_as_string_atomically(const std::string &path, std::string &contents);
-static int find_block_device_for_path(
-    const std::string &mounts,
-    const std::string &path,
-    std::string &block_device);
+namespace {
 
-int main(int argc, char **argv) {
-    if (argc != 2 || argv[1][0] != '/') {
+struct Options {
+    std::vector<std::string> targets;
+    bool unlink{true};
+};
+
+constexpr uint32_t max_extents = 32;
+
+bool read_command_line(int argc, const char * const argv[], Options &options);
+void usage(const char *progname);
+int secdiscard_path(const std::string &path);
+std::unique_ptr<struct fiemap> path_fiemap(const std::string &path, uint32_t extent_count);
+bool check_fiemap(const struct fiemap &fiemap, const std::string &path);
+std::unique_ptr<struct fiemap> alloc_fiemap(uint32_t extent_count);
+std::string block_device_for_path(const std::string &path);
+
+}
+
+int main(int argc, const char * const argv[]) {
+    Options options;
+    if (!read_command_line(argc, argv, options)) {
         usage(argv[0]);
         return -1;
     }
-    SLOGD("Running: %s %s", argv[0], argv[1]);
-    std::string target(argv[1]);
-    destroy_key(target);
-    if (unlink(argv[1]) != 0 && errno != ENOENT) {
-        SLOGE("Unable to delete %s: %s",
-            argv[1], strerror(errno));
-        return -1;
+    for (auto target: options.targets) {
+        SLOGD("Securely discarding '%s' unlink=%d", target.c_str(), options.unlink);
+        secdiscard_path(target);
+        if (options.unlink) {
+            if (unlink(target.c_str()) != 0 && errno != ENOENT) {
+                SLOGE("Unable to unlink %s: %s",
+                    target.c_str(), strerror(errno));
+            }
+        }
+        SLOGD("Discarded %s", target.c_str());
     }
     return 0;
 }
 
-static void usage(char *progname) {
-    fprintf(stderr, "Usage: %s <absolute path>\n", progname);
+namespace {
+
+bool read_command_line(int argc, const char * const argv[], Options &options) {
+    for (int i = 1; i < argc; i++) {
+        if (!strcmp("--no-unlink", argv[i])) {
+            options.unlink = false;
+        } else if (!strcmp("--", argv[i])) {
+            for (int j = i+1; j < argc; j++) {
+                if (argv[j][0] != '/') return false; // Must be absolute path
+                options.targets.emplace_back(argv[j]);
+            }
+            return options.targets.size() > 0;
+        } else {
+            return false; // Unknown option
+        }
+    }
+    return false; // "--" not found
+}
+
+void usage(const char *progname) {
+    fprintf(stderr, "Usage: %s [--no-unlink] -- <absolute path> ...\n", progname);
 }
 
 // BLKSECDISCARD all content in "path", if it's small enough.
-static void destroy_key(const std::string &path) {
-    uint64_t range[2];
-    if (file_device_range(path, range) < 0) {
-        return;
+int secdiscard_path(const std::string &path) {
+    auto fiemap = path_fiemap(path, max_extents);
+    if (!fiemap || !check_fiemap(*fiemap, path)) {
+        return -1;
     }
-    int fs_fd = open_block_device_for_path(path);
-    if (fs_fd < 0) {
-        return;
+    auto block_device = block_device_for_path(path);
+    if (block_device.empty()) {
+        return -1;
     }
-    if (ioctl(fs_fd, BLKSECDISCARD, range) != 0) {
-        SLOGE("Unable to BLKSECDISCARD %s: %s", path.c_str(), strerror(errno));
-        close(fs_fd);
-        return;
+    AutoCloseFD fs_fd(block_device, O_RDWR | O_LARGEFILE);
+    if (!fs_fd) {
+        SLOGE("Failed to open device %s: %s", block_device.c_str(), strerror(errno));
+        return -1;
     }
-    close(fs_fd);
-    SLOGD("Discarded %s", path.c_str());
+    for (uint32_t i = 0; i < fiemap->fm_mapped_extents; i++) {
+        uint64_t range[2];
+        range[0] = fiemap->fm_extents[i].fe_physical;
+        range[1] = fiemap->fm_extents[i].fe_length;
+        if (ioctl(fs_fd.get(), BLKSECDISCARD, range) == -1) {
+            SLOGE("Unable to BLKSECDISCARD %s: %s", path.c_str(), strerror(errno));
+            return -1;
+        }
+    }
+    return 0;
 }
 
-// Find a short range that completely covers the file.
-// If there isn't one, return -1, otherwise 0.
-static int file_device_range(const std::string &path, uint64_t range[2])
+// Read the file's FIEMAP
+std::unique_ptr<struct fiemap> path_fiemap(const std::string &path, uint32_t extent_count)
 {
-    int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
-    if (fd < 0) {
+    AutoCloseFD fd(path);
+    if (!fd) {
         if (errno == ENOENT) {
             SLOGD("Unable to open %s: %s", path.c_str(), strerror(errno));
         } else {
             SLOGE("Unable to open %s: %s", path.c_str(), strerror(errno));
         }
-        return -1;
+        return nullptr;
     }
-    alignas(struct fiemap) char fiemap_buffer[offsetof(struct fiemap, fm_extents[1])];
-    memset(fiemap_buffer, 0, sizeof(fiemap_buffer));
-    struct fiemap *fiemap = (struct fiemap *)fiemap_buffer;
-    fiemap->fm_start = 0;
-    fiemap->fm_length = UINT64_MAX;
-    fiemap->fm_flags = 0;
-    fiemap->fm_extent_count = 1;
-    fiemap->fm_mapped_extents = 0;
-    if (ioctl(fd, FS_IOC_FIEMAP, fiemap) != 0) {
+    auto fiemap = alloc_fiemap(extent_count);
+    if (ioctl(fd.get(), FS_IOC_FIEMAP, fiemap.get()) != 0) {
         SLOGE("Unable to FIEMAP %s: %s", path.c_str(), strerror(errno));
-        close(fd);
-        return -1;
+        return nullptr;
     }
-    close(fd);
-    if (fiemap->fm_mapped_extents != 1) {
-        SLOGE("Expecting one extent, got %d in %s", fiemap->fm_mapped_extents, path.c_str());
-        return -1;
+    auto mapped = fiemap->fm_mapped_extents;
+    if (mapped < 1 || mapped > extent_count) {
+        SLOGE("Extent count not in bounds 1 <= %u <= %u in %s", mapped, extent_count, path.c_str());
+        return nullptr;
     }
-    struct fiemap_extent *extent = &fiemap->fm_extents[0];
-    if (!(extent->fe_flags & FIEMAP_EXTENT_LAST)) {
-        SLOGE("First extent was not the last in %s", path.c_str());
-        return -1;
-    }
-    if (extent->fe_flags &
-            (FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_DELALLOC | FIEMAP_EXTENT_NOT_ALIGNED)) {
-        SLOGE("Extent has unexpected flags %ulx: %s", extent->fe_flags, path.c_str());
-        return -1;
-    }
-    if (extent->fe_length > MAX_WIPE_LENGTH) {
-        SLOGE("Extent too big, %llu bytes in %s", extent->fe_length, path.c_str());
-        return -1;
-    }
-    range[0] = extent->fe_physical;
-    range[1] = extent->fe_length;
-    return 0;
+    return fiemap;
 }
 
-// Given a file path, look for the corresponding
-// block device in /proc/mounts and open it.
-static int open_block_device_for_path(const std::string &path)
+// Ensure that the FIEMAP covers the file and is OK to discard
+bool check_fiemap(const struct fiemap &fiemap, const std::string &path) {
+    auto mapped = fiemap.fm_mapped_extents;
+    if (!(fiemap.fm_extents[mapped - 1].fe_flags & FIEMAP_EXTENT_LAST)) {
+        SLOGE("Extent %u was not the last in %s", mapped - 1, path.c_str());
+        return false;
+    }
+    for (uint32_t i = 0; i < mapped; i++) {
+        auto flags = fiemap.fm_extents[i].fe_flags;
+        if (flags & (FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_DELALLOC | FIEMAP_EXTENT_NOT_ALIGNED)) {
+            SLOGE("Extent %u has unexpected flags %ulx: %s", i, flags, path.c_str());
+            return false;
+        }
+    }
+    return true;
+}
+
+std::unique_ptr<struct fiemap> alloc_fiemap(uint32_t extent_count)
 {
-    std::string mountsfile("/proc/mounts");
-    std::string mounts;
-    if (read_file_as_string_atomically(mountsfile, mounts) < 0) {
-        return -1;
-    }
-    std::string block_device;
-    if (find_block_device_for_path(mounts, path, block_device) < 0) {
-        return -1;
-    }
-    SLOGD("For path %s block device is %s", path.c_str(), block_device.c_str());
-    int res = open(block_device.c_str(), O_RDWR | O_LARGEFILE | O_CLOEXEC);
-    if (res < 0) {
-        SLOGE("Failed to open device %s: %s", block_device.c_str(), strerror(errno));
-        return -1;
-    }
+    size_t allocsize = offsetof(struct fiemap, fm_extents[extent_count]);
+    std::unique_ptr<struct fiemap> res(new (::operator new (allocsize)) struct fiemap);
+    memset(res.get(), 0, allocsize);
+    res->fm_start = 0;
+    res->fm_length = UINT64_MAX;
+    res->fm_flags = 0;
+    res->fm_extent_count = extent_count;
+    res->fm_mapped_extents = 0;
     return res;
 }
 
-// Read a file into a buffer in a single gulp, for atomicity.
-// Null-terminate the buffer.
-// Retry until the buffer is big enough.
-static int read_file_as_string_atomically(const std::string &path, std::string &contents)
+// Given a file path, look for the corresponding block device in /proc/mount
+std::string block_device_for_path(const std::string &path)
 {
-    ssize_t buffer_size = INIT_BUFFER_SIZE;
-    while (true) {
-        int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
-        if (fd < 0) {
-            SLOGE("Failed to open %s: %s", path.c_str(), strerror(errno));
-            return -1;
-        }
-        contents.resize(buffer_size);
-        ssize_t read_size = read(fd, &contents[0], buffer_size);
-        if (read_size < 0) {
-            SLOGE("Failed to read from %s: %s", path.c_str(), strerror(errno));
-            close(fd);
-            return -1;
-        }
-        close(fd);
-        if (read_size < buffer_size) {
-            contents.resize(read_size);
-            return 0;
-        }
-        SLOGD("%s too big for buffer of size %zu", path.c_str(), buffer_size);
-        buffer_size <<= 1;
+    std::unique_ptr<FILE, int(*)(FILE*)> mnts(setmntent("/proc/mounts", "re"), endmntent);
+    if (!mnts) {
+        SLOGE("Unable to open /proc/mounts: %s", strerror(errno));
+        return "";
     }
+    std::string result;
+    size_t best_length = 0;
+    struct mntent *mnt; // getmntent returns a thread local, so it's safe.
+    while ((mnt = getmntent(mnts.get())) != nullptr) {
+        auto l = strlen(mnt->mnt_dir);
+        if (l > best_length &&
+            path.size() > l &&
+            path[l] == '/' &&
+            path.compare(0, l, mnt->mnt_dir) == 0) {
+                result = mnt->mnt_fsname;
+                best_length = l;
+        }
+    }
+    if (result.empty()) {
+        SLOGE("Didn't find a mountpoint to match path %s", path.c_str());
+        return "";
+    }
+    SLOGD("For path %s block device is %s", path.c_str(), result.c_str());
+    return result;
 }
 
-// Search a string representing the contents of /proc/mounts
-// for the mount point of a particular file by prefix matching
-// and return the corresponding block device.
-static int find_block_device_for_path(
-    const std::string &mounts,
-    const std::string &path,
-    std::string &block_device)
-{
-    auto line_begin = mounts.begin();
-    size_t best_prefix = 0;
-    std::string::const_iterator line_end;
-    while (line_begin != mounts.end()) {
-        line_end = std::find(line_begin, mounts.end(), '\n');
-        if (line_end == mounts.end()) {
-            break;
-        }
-        auto device_end = std::find(line_begin, line_end, ' ');
-        if (device_end == line_end) {
-            break;
-        }
-        auto mountpoint_begin = device_end + 1;
-        auto mountpoint_end = std::find(mountpoint_begin, line_end, ' ');
-        if (mountpoint_end == line_end) {
-            break;
-        }
-        if (std::find(line_begin, mountpoint_end, '\\') != mountpoint_end) {
-            // We don't correctly handle escape sequences, and we don't expect
-            // to encounter any, so fail if we do.
-            break;
-        }
-        size_t mountpoint_len = mountpoint_end - mountpoint_begin;
-        if (mountpoint_len > best_prefix &&
-                mountpoint_len < path.length() &&
-                path[mountpoint_len] == '/' &&
-                std::equal(mountpoint_begin, mountpoint_end, path.begin())) {
-            block_device = std::string(line_begin, device_end);
-            best_prefix = mountpoint_len;
-        }
-        line_begin = line_end + 1;
-    }
-    // All of the "break"s above are fatal parse errors.
-    if (line_begin != mounts.end()) {
-        auto bad_line = std::string(line_begin, line_end);
-        SLOGE("Unable to parse line in %s: %s", path.c_str(), bad_line.c_str());
-        return -1;
-    }
-    if (best_prefix == 0) {
-        SLOGE("No prefix found for path: %s", path.c_str());
-        return -1;
-    }
-    return 0;
 }