Keymaster: IWYU
am: 8264033678

Change-Id: Ia58e5508a19c4ba516a840e5f5287bfa1cb31bd1
diff --git a/Android.mk b/Android.mk
index 06d98eb..69be87d 100644
--- a/Android.mk
+++ b/Android.mk
@@ -29,12 +29,16 @@
 	TrimTask.cpp \
 	Keymaster.cpp \
 	KeyStorage.cpp \
+	KeyUtil.cpp \
 	ScryptParameters.cpp \
 	secontext.cpp \
+	EncryptInplace.cpp \
+	MetadataCrypt.cpp \
 
 common_c_includes := \
 	system/extras/f2fs_utils \
 	external/scrypt/lib/crypto \
+	external/f2fs-tools/include \
 	frameworks/native/include \
 	system/security/keystore \
 
@@ -69,6 +73,11 @@
 	libbatteryservice \
 	libavb \
 
+# TODO: include "cert-err34-c" once we move to Binder
+# TODO: include "cert-err58-cpp" once 36656327 is fixed
+common_local_tidy_flags := -warnings-as-errors=clang-analyzer-security*,cert-*
+common_local_tidy_checks := -*,clang-analyzer-security*,cert-*,-cert-err34-c,-cert-err58-cpp
+
 vold_conlyflags := -std=c11
 vold_cflags := -Werror -Wall -Wno-missing-field-initializers -Wno-unused-variable -Wno-unused-parameter
 
@@ -87,6 +96,9 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := libvold
 LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
 LOCAL_SRC_FILES := $(common_src_files)
 LOCAL_C_INCLUDES := $(common_c_includes)
 LOCAL_SHARED_LIBRARIES := $(common_shared_libraries)
@@ -103,6 +115,9 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := vold
 LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
 LOCAL_SRC_FILES := \
 	main.cpp \
 	$(common_src_files)
@@ -123,6 +138,9 @@
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
 LOCAL_SRC_FILES := vdc.cpp
 LOCAL_MODULE := vdc
 LOCAL_SHARED_LIBRARIES := libcutils libbase
@@ -136,6 +154,9 @@
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CLANG := true
+LOCAL_TIDY := true
+LOCAL_TIDY_FLAGS := $(common_local_tidy_flags)
+LOCAL_TIDY_CHECKS := $(common_local_tidy_checks)
 LOCAL_SRC_FILES:= secdiscard.cpp
 LOCAL_MODULE:= secdiscard
 LOCAL_SHARED_LIBRARIES := libbase
diff --git a/CommandListener.cpp b/CommandListener.cpp
index c2b8310..78973db 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -327,8 +327,8 @@
                 continue;
             }
 
-            char processName[255];
-            Process::getProcessName(pid, processName, sizeof(processName));
+            std::string processName;
+            Process::getProcessName(pid, processName);
 
             if (Process::checkFileDescriptorSymLinks(pid, argv[2]) ||
                 Process::checkFileMaps(pid, argv[2]) ||
@@ -337,7 +337,7 @@
                 Process::checkSymLink(pid, argv[2], "exe")) {
 
                 char msg[1024];
-                snprintf(msg, sizeof(msg), "%d %s", pid, processName);
+                snprintf(msg, sizeof(msg), "%d %s", pid, processName.c_str());
                 cli->sendMsg(ResponseCode::StorageUsersListResult, msg, false);
             }
         }
diff --git a/CryptCommandListener.cpp b/CryptCommandListener.cpp
index e4a2d3a..5c2ac84 100644
--- a/CryptCommandListener.cpp
+++ b/CryptCommandListener.cpp
@@ -50,6 +50,7 @@
 #include "ResponseCode.h"
 #include "cryptfs.h"
 #include "Ext4Crypt.h"
+#include "MetadataCrypt.h"
 #include "Utils.h"
 
 #define DUMP_ARGS 0
@@ -201,6 +202,15 @@
         dumpArgs(argc, argv, -1);
         rc = cryptfs_crypto_complete();
     } else if (subcommand == "enablecrypto") {
+        if (e4crypt_is_native()) {
+            if (argc != 5 || strcmp(argv[2], "inplace") || strcmp(argv[3], "default")
+                    || strcmp(argv[4], "noui")) {
+                cli->sendMsg(ResponseCode::CommandSyntaxError,
+                        "Usage with ext4crypt: cryptfs enablecrypto inplace default noui", false);
+                return 0;
+            }
+            return sendGenericOkFailOnBool(cli, e4crypt_enable_crypto());
+        }
         const char* syntax = "Usage: cryptfs enablecrypto <wipe|inplace> "
                              "default|password|pin|pattern [passwd] [noui]";
 
@@ -260,7 +270,7 @@
     } else if (subcommand == "enablefilecrypto") {
         if (!check_argc(cli, subcommand, argc, 2, "")) return 0;
         dumpArgs(argc, argv, -1);
-        rc = cryptfs_enable_file();
+        rc = e4crypt_initialize_global_de();
     } else if (subcommand == "changepw") {
         const char* syntax = "Usage: cryptfs changepw "
                              "default|password|pin|pattern [newpasswd]";
@@ -318,6 +328,9 @@
         SLOGD("cryptfs mountdefaultencrypted");
         dumpArgs(argc, argv, -1);
 
+        if (e4crypt_is_native()) {
+            return sendGenericOkFailOnBool(cli, e4crypt_mount_metadata_encrypted());
+        }
         // Spawn as thread so init can issue commands back to vold without
         // causing deadlock, usually as a result of prep_data_fs.
         std::thread(&cryptfs_mount_default_encrypted).detach();
diff --git a/Devmapper.cpp b/Devmapper.cpp
index e56a4da..4b6942d 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -195,7 +195,7 @@
 
     char *geoParams = buffer + sizeof(struct dm_ioctl);
     // bps=512 spc=8 res=32 nft=2 sec=8190 mid=0xf0 spt=63 hds=64 hid=0 bspf=8 rdcl=2 infs=1 bkbs=2
-    strcpy(geoParams, "0 64 63 0");
+    strlcpy(geoParams, "0 64 63 0", DEVMAPPER_BUFFER_SIZE - sizeof(struct dm_ioctl));
     geoParams += strlen(geoParams) + 1;
     geoParams = (char *) _align(geoParams, 8);
     if (ioctl(fd, DM_DEV_SET_GEOMETRY, io)) {
diff --git a/EncryptInplace.cpp b/EncryptInplace.cpp
new file mode 100644
index 0000000..9aa2a21
--- /dev/null
+++ b/EncryptInplace.cpp
@@ -0,0 +1,656 @@
+/*
+ * Copyright (C) 2016 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 "EncryptInplace.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <inttypes.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <ext4_utils/ext4.h>
+#include <ext4_utils/ext4_utils.h>
+#include <f2fs_sparseblock.h>
+
+#include <algorithm>
+
+#include "cutils/properties.h"
+#define LOG_TAG "EncryptInplace"
+#include "cutils/log.h"
+#include "CheckBattery.h"
+
+// HORRIBLE HACK, FIXME
+#include "cryptfs.h"
+
+// FIXME horrible cut-and-paste code
+static inline int unix_read(int  fd, void*  buff, int  len)
+{
+    return TEMP_FAILURE_RETRY(read(fd, buff, len));
+}
+
+static inline int unix_write(int  fd, const void*  buff, int  len)
+{
+    return TEMP_FAILURE_RETRY(write(fd, buff, len));
+}
+
+#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
+
+/* aligned 32K writes tends to make flash happy.
+ * SD card association recommends it.
+ */
+#ifndef CONFIG_HW_DISK_ENCRYPTION
+#define BLOCKS_AT_A_TIME 8
+#else
+#define BLOCKS_AT_A_TIME 1024
+#endif
+
+struct encryptGroupsData
+{
+    int realfd;
+    int cryptofd;
+    off64_t numblocks;
+    off64_t one_pct, cur_pct, new_pct;
+    off64_t blocks_already_done, tot_numblocks;
+    off64_t used_blocks_already_done, tot_used_blocks;
+    char* real_blkdev, * crypto_blkdev;
+    int count;
+    off64_t offset;
+    char* buffer;
+    off64_t last_written_sector;
+    int completed;
+    time_t time_started;
+    int remaining_time;
+};
+
+static void update_progress(struct encryptGroupsData* data, int is_used)
+{
+    data->blocks_already_done++;
+
+    if (is_used) {
+        data->used_blocks_already_done++;
+    }
+    if (data->tot_used_blocks) {
+        data->new_pct = data->used_blocks_already_done / data->one_pct;
+    } else {
+        data->new_pct = data->blocks_already_done / data->one_pct;
+    }
+
+    if (data->new_pct > data->cur_pct) {
+        char buf[8];
+        data->cur_pct = data->new_pct;
+        snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
+        property_set("vold.encrypt_progress", buf);
+    }
+
+    if (data->cur_pct >= 5) {
+        struct timespec time_now;
+        if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
+            SLOGW("Error getting time");
+        } else {
+            double elapsed_time = difftime(time_now.tv_sec, data->time_started);
+            off64_t remaining_blocks = data->tot_used_blocks
+                                       - data->used_blocks_already_done;
+            int remaining_time = (int)(elapsed_time * remaining_blocks
+                                       / data->used_blocks_already_done);
+
+            // Change time only if not yet set, lower, or a lot higher for
+            // best user experience
+            if (data->remaining_time == -1
+                || remaining_time < data->remaining_time
+                || remaining_time > data->remaining_time + 60) {
+                char buf[8];
+                snprintf(buf, sizeof(buf), "%d", remaining_time);
+                property_set("vold.encrypt_time_remaining", buf);
+                data->remaining_time = remaining_time;
+            }
+        }
+    }
+}
+
+static void log_progress(struct encryptGroupsData const* data, bool completed)
+{
+    // Precondition - if completed data = 0 else data != 0
+
+    // Track progress so we can skip logging blocks
+    static off64_t offset = -1;
+
+    // Need to close existing 'Encrypting from' log?
+    if (completed || (offset != -1 && data->offset != offset)) {
+        SLOGI("Encrypted to sector %" PRId64,
+              offset / info.block_size * CRYPT_SECTOR_SIZE);
+        offset = -1;
+    }
+
+    // Need to start new 'Encrypting from' log?
+    if (!completed && offset != data->offset) {
+        SLOGI("Encrypting from sector %" PRId64,
+              data->offset / info.block_size * CRYPT_SECTOR_SIZE);
+    }
+
+    // Update offset
+    if (!completed) {
+        offset = data->offset + (off64_t)data->count * info.block_size;
+    }
+}
+
+static int flush_outstanding_data(struct encryptGroupsData* data)
+{
+    if (data->count == 0) {
+        return 0;
+    }
+
+    SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
+
+    if (pread64(data->realfd, data->buffer,
+                info.block_size * data->count, data->offset)
+        <= 0) {
+        SLOGE("Error reading real_blkdev %s for inplace encrypt",
+              data->real_blkdev);
+        return -1;
+    }
+
+    if (pwrite64(data->cryptofd, data->buffer,
+                 info.block_size * data->count, data->offset)
+        <= 0) {
+        SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
+              data->crypto_blkdev);
+        return -1;
+    } else {
+      log_progress(data, false);
+    }
+
+    data->count = 0;
+    data->last_written_sector = (data->offset + data->count)
+                                / info.block_size * CRYPT_SECTOR_SIZE - 1;
+    return 0;
+}
+
+static int encrypt_groups(struct encryptGroupsData* data)
+{
+    unsigned int i;
+    u8 *block_bitmap = 0;
+    unsigned int block;
+    off64_t ret;
+    int rc = -1;
+
+    data->buffer = (char*) malloc(info.block_size * BLOCKS_AT_A_TIME);
+    if (!data->buffer) {
+        SLOGE("Failed to allocate crypto buffer");
+        goto errout;
+    }
+
+    block_bitmap = (u8*) malloc(info.block_size);
+    if (!block_bitmap) {
+        SLOGE("failed to allocate block bitmap");
+        goto errout;
+    }
+
+    for (i = 0; i < aux_info.groups; ++i) {
+        SLOGI("Encrypting group %d", i);
+
+        u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
+        u32 block_count = std::min(info.blocks_per_group,
+                             (u32)(aux_info.len_blocks - first_block));
+
+        off64_t offset = (u64)info.block_size
+                         * aux_info.bg_desc[i].bg_block_bitmap;
+
+        ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
+        if (ret != (int)info.block_size) {
+            SLOGE("failed to read all of block group bitmap %d", i);
+            goto errout;
+        }
+
+        offset = (u64)info.block_size * first_block;
+
+        data->count = 0;
+
+        for (block = 0; block < block_count; block++) {
+            int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
+                    0 : bitmap_get_bit(block_bitmap, block);
+            update_progress(data, used);
+            if (used) {
+                if (data->count == 0) {
+                    data->offset = offset;
+                }
+                data->count++;
+            } else {
+                if (flush_outstanding_data(data)) {
+                    goto errout;
+                }
+            }
+
+            offset += info.block_size;
+
+            /* Write data if we are aligned or buffer size reached */
+            if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
+                || data->count == BLOCKS_AT_A_TIME) {
+                if (flush_outstanding_data(data)) {
+                    goto errout;
+                }
+            }
+
+            if (!is_battery_ok_to_continue()) {
+                SLOGE("Stopping encryption due to low battery");
+                rc = 0;
+                goto errout;
+            }
+
+        }
+        if (flush_outstanding_data(data)) {
+            goto errout;
+        }
+    }
+
+    data->completed = 1;
+    rc = 0;
+
+errout:
+    log_progress(0, true);
+    free(data->buffer);
+    free(block_bitmap);
+    return rc;
+}
+
+static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
+                                       char *real_blkdev,
+                                       off64_t size,
+                                       off64_t *size_already_done,
+                                       off64_t tot_size,
+                                       off64_t previously_encrypted_upto)
+{
+    u32 i;
+    struct encryptGroupsData data;
+    int rc; // Can't initialize without causing warning -Wclobbered
+    int retries = RETRY_MOUNT_ATTEMPTS;
+    struct timespec time_started = {0};
+
+    if (previously_encrypted_upto > *size_already_done) {
+        SLOGD("Not fast encrypting since resuming part way through");
+        return -1;
+    }
+
+    memset(&data, 0, sizeof(data));
+    data.real_blkdev = real_blkdev;
+    data.crypto_blkdev = crypto_blkdev;
+
+    if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
+        SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
+              real_blkdev, errno, strerror(errno));
+        rc = -1;
+        goto errout;
+    }
+
+    // Wait until the block device appears.  Re-use the mount retry values since it is reasonable.
+    while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+        if (--retries) {
+            SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
+                  crypto_blkdev, errno, strerror(errno));
+            sleep(RETRY_MOUNT_DELAY_SECONDS);
+        } else {
+            SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
+                  crypto_blkdev, errno, strerror(errno));
+            rc = ENABLE_INPLACE_ERR_DEV;
+            goto errout;
+        }
+    }
+
+    if (setjmp(setjmp_env)) { // NOLINT
+        SLOGE("Reading ext4 extent caused an exception\n");
+        rc = -1;
+        goto errout;
+    }
+
+    if (read_ext(data.realfd, 0) != 0) {
+        SLOGE("Failed to read ext4 extent\n");
+        rc = -1;
+        goto errout;
+    }
+
+    data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+    data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+    data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+    SLOGI("Encrypting ext4 filesystem in place...");
+
+    data.tot_used_blocks = data.numblocks;
+    for (i = 0; i < aux_info.groups; ++i) {
+      data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
+    }
+
+    data.one_pct = data.tot_used_blocks / 100;
+    data.cur_pct = 0;
+
+    if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
+        SLOGW("Error getting time at start");
+        // Note - continue anyway - we'll run with 0
+    }
+    data.time_started = time_started.tv_sec;
+    data.remaining_time = -1;
+
+    rc = encrypt_groups(&data);
+    if (rc) {
+        SLOGE("Error encrypting groups");
+        goto errout;
+    }
+
+    *size_already_done += data.completed ? size : data.last_written_sector;
+    rc = 0;
+
+errout:
+    close(data.realfd);
+    close(data.cryptofd);
+
+    return rc;
+}
+
+static void log_progress_f2fs(u64 block, bool completed)
+{
+    // Precondition - if completed data = 0 else data != 0
+
+    // Track progress so we can skip logging blocks
+    static u64 last_block = (u64)-1;
+
+    // Need to close existing 'Encrypting from' log?
+    if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
+        SLOGI("Encrypted to block %" PRId64, last_block);
+        last_block = -1;
+    }
+
+    // Need to start new 'Encrypting from' log?
+    if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
+        SLOGI("Encrypting from block %" PRId64, block);
+    }
+
+    // Update offset
+    if (!completed) {
+        last_block = block;
+    }
+}
+
+static int encrypt_one_block_f2fs(u64 pos, void *data)
+{
+    struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
+
+    priv_dat->blocks_already_done = pos - 1;
+    update_progress(priv_dat, 1);
+
+    off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
+
+    if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
+        SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
+        return -1;
+    }
+
+    if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
+        SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
+        return -1;
+    } else {
+        log_progress_f2fs(pos, false);
+    }
+
+    return 0;
+}
+
+static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
+                                       char *real_blkdev,
+                                       off64_t size,
+                                       off64_t *size_already_done,
+                                       off64_t tot_size,
+                                       off64_t previously_encrypted_upto)
+{
+    struct encryptGroupsData data;
+    struct f2fs_info *f2fs_info = NULL;
+    int rc = ENABLE_INPLACE_ERR_OTHER;
+    if (previously_encrypted_upto > *size_already_done) {
+        SLOGD("Not fast encrypting since resuming part way through");
+        return ENABLE_INPLACE_ERR_OTHER;
+    }
+    memset(&data, 0, sizeof(data));
+    data.real_blkdev = real_blkdev;
+    data.crypto_blkdev = crypto_blkdev;
+    data.realfd = -1;
+    data.cryptofd = -1;
+    if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
+        SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
+              real_blkdev);
+        goto errout;
+    }
+    if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+        SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
+              crypto_blkdev, errno, strerror(errno));
+        rc = ENABLE_INPLACE_ERR_DEV;
+        goto errout;
+    }
+
+    f2fs_info = generate_f2fs_info(data.realfd);
+    if (!f2fs_info)
+      goto errout;
+
+    data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+    data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+    data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+    data.tot_used_blocks = get_num_blocks_used(f2fs_info);
+
+    data.one_pct = data.tot_used_blocks / 100;
+    data.cur_pct = 0;
+    data.time_started = time(NULL);
+    data.remaining_time = -1;
+
+    data.buffer = (char*) malloc(f2fs_info->block_size);
+    if (!data.buffer) {
+        SLOGE("Failed to allocate crypto buffer");
+        goto errout;
+    }
+
+    data.count = 0;
+
+    /* Currently, this either runs to completion, or hits a nonrecoverable error */
+    rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
+
+    if (rc) {
+        SLOGE("Error in running over f2fs blocks");
+        rc = ENABLE_INPLACE_ERR_OTHER;
+        goto errout;
+    }
+
+    *size_already_done += size;
+    rc = 0;
+
+errout:
+    if (rc)
+        SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
+
+    log_progress_f2fs(0, true);
+    free(f2fs_info);
+    free(data.buffer);
+    close(data.realfd);
+    close(data.cryptofd);
+
+    return rc;
+}
+
+static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
+                                       off64_t size, off64_t *size_already_done,
+                                       off64_t tot_size,
+                                       off64_t previously_encrypted_upto)
+{
+    int realfd, cryptofd;
+    char *buf[CRYPT_INPLACE_BUFSIZE];
+    int rc = ENABLE_INPLACE_ERR_OTHER;
+    off64_t numblocks, i, remainder;
+    off64_t one_pct, cur_pct, new_pct;
+    off64_t blocks_already_done, tot_numblocks;
+
+    if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
+        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
+        return ENABLE_INPLACE_ERR_OTHER;
+    }
+
+    if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
+        SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
+              crypto_blkdev, errno, strerror(errno));
+        close(realfd);
+        return ENABLE_INPLACE_ERR_DEV;
+    }
+
+    /* This is pretty much a simple loop of reading 4K, and writing 4K.
+     * The size passed in is the number of 512 byte sectors in the filesystem.
+     * So compute the number of whole 4K blocks we should read/write,
+     * and the remainder.
+     */
+    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
+    tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+    blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+    SLOGE("Encrypting filesystem in place...");
+
+    i = previously_encrypted_upto + 1 - *size_already_done;
+
+    if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
+        SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
+        goto errout;
+    }
+
+    if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
+        SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
+        goto errout;
+    }
+
+    for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
+        if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+            SLOGE("Error reading initial sectors from real_blkdev %s for "
+                  "inplace encrypt\n", crypto_blkdev);
+            goto errout;
+        }
+        if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+            SLOGE("Error writing initial sectors to crypto_blkdev %s for "
+                  "inplace encrypt\n", crypto_blkdev);
+            goto errout;
+        } else {
+            SLOGI("Encrypted 1 block at %" PRId64, i);
+        }
+    }
+
+    one_pct = tot_numblocks / 100;
+    cur_pct = 0;
+    /* process the majority of the filesystem in blocks */
+    for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
+        new_pct = (i + blocks_already_done) / one_pct;
+        if (new_pct > cur_pct) {
+            char buf[8];
+
+            cur_pct = new_pct;
+            snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
+            property_set("vold.encrypt_progress", buf);
+        }
+        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
+            SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
+            goto errout;
+        }
+        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
+            SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
+            goto errout;
+        } else {
+            SLOGD("Encrypted %d block at %" PRId64,
+                  CRYPT_SECTORS_PER_BUFSIZE,
+                  i * CRYPT_SECTORS_PER_BUFSIZE);
+        }
+
+       if (!is_battery_ok_to_continue()) {
+            SLOGE("Stopping encryption due to low battery");
+            *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
+            rc = 0;
+            goto errout;
+        }
+    }
+
+    /* Do any remaining sectors */
+    for (i=0; i<remainder; i++) {
+        if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+            SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
+            goto errout;
+        }
+        if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
+            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
+            goto errout;
+        } else {
+            SLOGI("Encrypted 1 block at next location");
+        }
+    }
+
+    *size_already_done += size;
+    rc = 0;
+
+errout:
+    close(realfd);
+    close(cryptofd);
+
+    return rc;
+}
+
+/* returns on of the ENABLE_INPLACE_* return codes */
+int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
+                           off64_t size, off64_t *size_already_done,
+                           off64_t tot_size,
+                           off64_t previously_encrypted_upto)
+{
+    int rc_ext4, rc_f2fs, rc_full;
+    if (previously_encrypted_upto) {
+        SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
+    }
+
+    if (*size_already_done + size < previously_encrypted_upto) {
+        *size_already_done += size;
+        return 0;
+    }
+
+    /* TODO: identify filesystem type.
+     * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
+     * then we will drop down to cryptfs_enable_inplace_f2fs.
+     * */
+    if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
+                                size, size_already_done,
+                                tot_size, previously_encrypted_upto)) == 0) {
+      return 0;
+    }
+    SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
+
+    if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
+                                size, size_already_done,
+                                tot_size, previously_encrypted_upto)) == 0) {
+      return 0;
+    }
+    SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
+
+    rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
+                                       size, size_already_done, tot_size,
+                                       previously_encrypted_upto);
+    SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
+
+    /* Hack for b/17898962, the following is the symptom... */
+    if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
+        && rc_f2fs == ENABLE_INPLACE_ERR_DEV
+        && rc_full == ENABLE_INPLACE_ERR_DEV) {
+            return ENABLE_INPLACE_ERR_DEV;
+    }
+    return rc_full;
+}
diff --git a/EncryptInplace.h b/EncryptInplace.h
new file mode 100644
index 0000000..de5a1c5
--- /dev/null
+++ b/EncryptInplace.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef _ENCRYPT_INPLACE_H
+#define _ENCRYPT_INPLACE_H
+
+#include <sys/types.h>
+
+#define CRYPT_INPLACE_BUFSIZE 4096
+#define CRYPT_SECTOR_SIZE 512
+#define RETRY_MOUNT_ATTEMPTS 10
+#define RETRY_MOUNT_DELAY_SECONDS 1
+
+int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
+                           off64_t size, off64_t *size_already_done,
+                           off64_t tot_size,
+                           off64_t previously_encrypted_upto);
+
+#endif
diff --git a/Ext4Crypt.cpp b/Ext4Crypt.cpp
index e40593e..cb5f6d0 100644
--- a/Ext4Crypt.cpp
+++ b/Ext4Crypt.cpp
@@ -17,22 +17,21 @@
 #include "Ext4Crypt.h"
 
 #include "KeyStorage.h"
+#include "KeyUtil.h"
 #include "Utils.h"
 
 #include <algorithm>
-#include <iomanip>
 #include <map>
 #include <set>
 #include <sstream>
 #include <string>
+#include <vector>
 
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <limits.h>
-#include <openssl/sha.h>
 #include <selinux/android.h>
-#include <stdio.h>
 #include <sys/mount.h>
 #include <sys/stat.h>
 #include <sys/types.h>
@@ -45,8 +44,10 @@
 #define MANAGE_MISC_DIRS 0
 
 #include <cutils/fs.h>
-#include <ext4_utils/ext4_crypt.h>
+#include <cutils/properties.h>
+
 #include <ext4_utils/key_control.h>
+#include <ext4_utils/ext4_crypt.h>
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
@@ -79,19 +80,6 @@
 // TODO abolish this map, per b/26948053
 std::map<userid_t, std::string> s_ce_keys;
 
-// ext4enc:TODO get this const from somewhere good
-const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
-
-// ext4enc:TODO Include structure from somewhere sensible
-// MUST be in sync with ext4_crypto.c in kernel
-constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
-constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
-constexpr int EXT4_MAX_KEY_SIZE = 64;
-struct ext4_encryption_key {
-    uint32_t mode;
-    char raw[EXT4_MAX_KEY_SIZE];
-    uint32_t size;
-};
 }
 
 static bool e4crypt_is_emulated() {
@@ -102,78 +90,6 @@
     return (value == nullptr) ? "null" : value;
 }
 
-// Get raw keyref - used to make keyname and to pass to ioctl
-static std::string generate_key_ref(const char* key, int length) {
-    SHA512_CTX c;
-
-    SHA512_Init(&c);
-    SHA512_Update(&c, key, length);
-    unsigned char key_ref1[SHA512_DIGEST_LENGTH];
-    SHA512_Final(key_ref1, &c);
-
-    SHA512_Init(&c);
-    SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
-    unsigned char key_ref2[SHA512_DIGEST_LENGTH];
-    SHA512_Final(key_ref2, &c);
-
-    static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
-                  "Hash too short for descriptor");
-    return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
-}
-
-static bool fill_key(const std::string& key, ext4_encryption_key* ext4_key) {
-    if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
-        LOG(ERROR) << "Wrong size key " << key.size();
-        return false;
-    }
-    static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
-    ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
-    ext4_key->size = key.size();
-    memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
-    memcpy(ext4_key->raw, key.data(), key.size());
-    return true;
-}
-
-static std::string keyname(const std::string& raw_ref) {
-    std::ostringstream o;
-    o << "ext4:";
-    for (unsigned char i : raw_ref) {
-        o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
-    }
-    return o.str();
-}
-
-// Get the keyring we store all keys in
-static bool e4crypt_keyring(key_serial_t* device_keyring) {
-    *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
-    if (*device_keyring == -1) {
-        PLOG(ERROR) << "Unable to find device keyring";
-        return false;
-    }
-    return true;
-}
-
-// Install password into global keyring
-// Return raw key reference for use in policy
-static bool install_key(const std::string& key, std::string* raw_ref) {
-    ext4_encryption_key ext4_key;
-    if (!fill_key(key, &ext4_key)) return false;
-    *raw_ref = generate_key_ref(ext4_key.raw, ext4_key.size);
-    auto ref = keyname(*raw_ref);
-    key_serial_t device_keyring;
-    if (!e4crypt_keyring(&device_keyring)) return false;
-    key_serial_t key_id =
-        add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
-    if (key_id == -1) {
-        PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
-        return false;
-    }
-    LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
-               << " in process " << getpid();
-
-    return true;
-}
-
 static std::string get_de_key_path(userid_t user_id) {
     return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
 }
@@ -273,7 +189,7 @@
     std::string ce_key;
     if (!read_and_fixate_user_ce_key(user_id, auth, &ce_key)) return false;
     std::string ce_raw_ref;
-    if (!install_key(ce_key, &ce_raw_ref)) return false;
+    if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
     s_ce_keys[user_id] = ce_key;
     s_ce_key_raw_refs[user_id] = ce_raw_ref;
     LOG(DEBUG) << "Installed ce key for user " << user_id;
@@ -298,43 +214,12 @@
     return true;
 }
 
-static bool random_key(std::string* key) {
-    if (android::vold::ReadRandomBytes(EXT4_AES_256_XTS_KEY_SIZE, *key) != 0) {
-        // TODO status_t plays badly with PLOG, fix it.
-        LOG(ERROR) << "Random read failed";
-        return false;
-    }
-    return true;
-}
-
-static bool path_exists(const std::string& path) {
-    return access(path.c_str(), F_OK) == 0;
-}
-
 // NB this assumes that there is only one thread listening for crypt commands, because
 // it creates keys in a fixed location.
-static bool store_key(const std::string& key_path, const std::string& tmp_path,
-                      const android::vold::KeyAuthentication& auth, const std::string& key) {
-    if (path_exists(key_path)) {
-        LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
-        return false;
-    }
-    if (path_exists(tmp_path)) {
-        android::vold::destroyKey(tmp_path);  // May be partially created so ignore errors
-    }
-    if (!android::vold::storeKey(tmp_path, auth, key)) return false;
-    if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
-        PLOG(ERROR) << "Unable to move new key to location: " << key_path;
-        return false;
-    }
-    LOG(DEBUG) << "Created key " << key_path;
-    return true;
-}
-
 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
     std::string de_key, ce_key;
-    if (!random_key(&de_key)) return false;
-    if (!random_key(&ce_key)) return false;
+    if (!android::vold::randomKey(&de_key)) return false;
+    if (!android::vold::randomKey(&ce_key)) return false;
     if (create_ephemeral) {
         // If the key should be created as ephemeral, don't store it.
         s_ephemeral_users.insert(user_id);
@@ -344,18 +229,18 @@
         auto const paths = get_ce_key_paths(directory_path);
         std::string ce_key_path;
         if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
-        if (!store_key(ce_key_path, user_key_temp,
+        if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp,
                 kEmptyAuthentication, ce_key)) return false;
         fixate_user_ce_key(directory_path, ce_key_path, paths);
         // Write DE key second; once this is written, all is good.
-        if (!store_key(get_de_key_path(user_id), user_key_temp,
+        if (!android::vold::storeKeyAtomically(get_de_key_path(user_id), user_key_temp,
                 kEmptyAuthentication, de_key)) return false;
     }
     std::string de_raw_ref;
-    if (!install_key(de_key, &de_raw_ref)) return false;
+    if (!android::vold::installKey(de_key, &de_raw_ref)) return false;
     s_de_key_raw_refs[user_id] = de_raw_ref;
     std::string ce_raw_ref;
-    if (!install_key(ce_key, &ce_raw_ref)) return false;
+    if (!android::vold::installKey(ce_key, &ce_raw_ref)) return false;
     s_ce_keys[user_id] = ce_key;
     s_ce_key_raw_refs[user_id] = ce_raw_ref;
     LOG(DEBUG) << "Created keys for user " << user_id;
@@ -422,7 +307,7 @@
             std::string key;
             if (!android::vold::retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
             std::string raw_ref;
-            if (!install_key(key, &raw_ref)) return false;
+            if (!android::vold::installKey(key, &raw_ref)) return false;
             s_de_key_raw_refs[user_id] = raw_ref;
             LOG(DEBUG) << "Installed de key for user " << user_id;
         }
@@ -451,28 +336,16 @@
         return false;
     }
 
-    std::string device_key;
-    if (path_exists(device_key_path)) {
-        if (!android::vold::retrieveKey(device_key_path,
-                kEmptyAuthentication, &device_key)) return false;
-    } else {
-        LOG(INFO) << "Creating new key";
-        if (!random_key(&device_key)) return false;
-        if (!store_key(device_key_path, device_key_temp,
-                kEmptyAuthentication, device_key)) return false;
-    }
-
     std::string device_key_ref;
-    if (!install_key(device_key, &device_key_ref)) {
-        LOG(ERROR) << "Failed to install device key";
-        return false;
-    }
+    if (!android::vold::retrieveAndInstallKey(true,
+        device_key_path, device_key_temp, &device_key_ref)) return false;
 
     std::string ref_filename = std::string("/data") + e4crypt_key_ref;
     if (!android::base::WriteStringToFile(device_key_ref, ref_filename)) {
-        PLOG(ERROR) << "Cannot save key reference";
+        PLOG(ERROR) << "Cannot save key reference to:" << ref_filename;
         return false;
     }
+    LOG(INFO) << "Wrote system DE key reference to:" << ref_filename;
 
     s_global_de_initialized = true;
     return true;
@@ -484,7 +357,7 @@
         if (!prepare_dir(user_key_dir, 0700, AID_ROOT, AID_ROOT)) return false;
         if (!prepare_dir(user_key_dir + "/ce", 0700, AID_ROOT, AID_ROOT)) return false;
         if (!prepare_dir(user_key_dir + "/de", 0700, AID_ROOT, AID_ROOT)) return false;
-        if (!path_exists(get_de_key_path(0))) {
+        if (!android::vold::pathExists(get_de_key_path(0))) {
             if (!create_and_install_user_keys(0, false)) return false;
         }
         // TODO: switch to loading only DE_0 here once framework makes
@@ -526,31 +399,13 @@
     return true;
 }
 
-static bool evict_key(const std::string &raw_ref) {
-    auto ref = keyname(raw_ref);
-    key_serial_t device_keyring;
-    if (!e4crypt_keyring(&device_keyring)) return false;
-    auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
-
-    // Unlink the key from the keyring.  Prefer unlinking to revoking or
-    // invalidating, since unlinking is actually no less secure currently, and
-    // it avoids bugs in certain kernel versions where the keyring key is
-    // referenced from places it shouldn't be.
-    if (keyctl_unlink(key_serial, device_keyring) != 0) {
-        PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
-        return false;
-    }
-    LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
-    return true;
-}
-
 static bool evict_ce_key(userid_t user_id) {
-    s_ce_keys.erase(user_id);
+   s_ce_keys.erase(user_id);
     bool success = true;
     std::string raw_ref;
     // 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_key(raw_ref);
+        success &= android::vold::evictKey(raw_ref);
     }
     s_ce_key_raw_refs.erase(user_id);
     return success;
@@ -564,7 +419,8 @@
     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_key(raw_ref);
+    success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)
+        && android::vold::evictKey(raw_ref);
     s_de_key_raw_refs.erase(user_id);
     auto it = s_ephemeral_users.find(user_id);
     if (it != s_ephemeral_users.end()) {
@@ -574,7 +430,7 @@
             success &= android::vold::destroyKey(path);
         }
         auto de_key_path = get_de_key_path(user_id);
-        if (path_exists(de_key_path)) {
+        if (android::vold::pathExists(de_key_path)) {
             success &= android::vold::destroyKey(de_key_path);
         } else {
             LOG(INFO) << "Not present so not erasing: " << de_key_path;
@@ -646,7 +502,7 @@
     auto const paths = get_ce_key_paths(directory_path);
     std::string ce_key_path;
     if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
-    if (!store_key(ce_key_path, user_key_temp, auth, ce_key)) return false;
+    if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
     return true;
 }
 
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 34dd6c0..ddecbb8 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -400,6 +400,10 @@
     return true;
 }
 
+bool pathExists(const std::string& path) {
+    return access(path.c_str(), F_OK) == 0;
+}
+
 bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key) {
     if (TEMP_FAILURE_RETRY(mkdir(dir.c_str(), 0700)) == -1) {
         PLOG(ERROR) << "key mkdir " << dir;
@@ -437,6 +441,25 @@
     return true;
 }
 
+bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
+                        const KeyAuthentication& auth, const std::string& key) {
+    if (pathExists(key_path)) {
+        LOG(ERROR) << "Already exists, cannot create key at: " << key_path;
+        return false;
+    }
+    if (pathExists(tmp_path)) {
+        LOG(DEBUG) << "Already exists, destroying: " << tmp_path;
+        destroyKey(tmp_path);  // May be partially created so ignore errors
+    }
+    if (!storeKey(tmp_path, auth, key)) return false;
+    if (rename(tmp_path.c_str(), key_path.c_str()) != 0) {
+        PLOG(ERROR) << "Unable to move new key to location: " << key_path;
+        return false;
+    }
+    LOG(DEBUG) << "Created key: " << key_path;
+    return true;
+}
+
 bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key) {
     std::string version;
     if (!readFileToString(dir + "/" + kFn_version, &version)) return false;
diff --git a/KeyStorage.h b/KeyStorage.h
index 65458d4..6186d19 100644
--- a/KeyStorage.h
+++ b/KeyStorage.h
@@ -39,12 +39,22 @@
 
 extern const KeyAuthentication kEmptyAuthentication;
 
+// Checks if path "path" exists.
+bool pathExists(const std::string& path);
+
 // Create a directory at the named path, and store "key" in it,
 // in such a way that it can only be retrieved via Keymaster and
 // can be securely deleted.
 // It's safe to move/rename the directory after creation.
 bool storeKey(const std::string& dir, const KeyAuthentication& auth, const std::string& key);
 
+// Create a directory at the named path, and store "key" in it as storeKey
+// This version creates the key in "tmp_path" then atomically renames "tmp_path"
+// to "key_path" thereby ensuring that the key is either stored entirely or
+// not at all.
+bool storeKeyAtomically(const std::string& key_path, const std::string& tmp_path,
+                        const KeyAuthentication& auth, const std::string& key);
+
 // Retrieve the key from the named directory.
 bool retrieveKey(const std::string& dir, const KeyAuthentication& auth, std::string* key);
 
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
new file mode 100644
index 0000000..fe0f3cb
--- /dev/null
+++ b/KeyUtil.cpp
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2016 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 "KeyUtil.h"
+
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+#include <ext4_utils/key_control.h>
+
+#include <openssl/sha.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+
+#include "KeyStorage.h"
+#include "Utils.h"
+
+namespace android {
+namespace vold {
+
+bool randomKey(std::string* key) {
+    if (ReadRandomBytes(EXT4_AES_256_XTS_KEY_SIZE, *key) != 0) {
+        // TODO status_t plays badly with PLOG, fix it.
+        LOG(ERROR) << "Random read failed";
+        return false;
+    }
+    return true;
+}
+
+// Get raw keyref - used to make keyname and to pass to ioctl
+static std::string generateKeyRef(const char* key, int length) {
+    SHA512_CTX c;
+
+    SHA512_Init(&c);
+    SHA512_Update(&c, key, length);
+    unsigned char key_ref1[SHA512_DIGEST_LENGTH];
+    SHA512_Final(key_ref1, &c);
+
+    SHA512_Init(&c);
+    SHA512_Update(&c, key_ref1, SHA512_DIGEST_LENGTH);
+    unsigned char key_ref2[SHA512_DIGEST_LENGTH];
+    SHA512_Final(key_ref2, &c);
+
+    static_assert(EXT4_KEY_DESCRIPTOR_SIZE <= SHA512_DIGEST_LENGTH,
+                  "Hash too short for descriptor");
+    return std::string((char*)key_ref2, EXT4_KEY_DESCRIPTOR_SIZE);
+}
+
+static bool fillKey(const std::string& key, ext4_encryption_key* ext4_key) {
+    if (key.size() != EXT4_AES_256_XTS_KEY_SIZE) {
+        LOG(ERROR) << "Wrong size key " << key.size();
+        return false;
+    }
+    static_assert(EXT4_AES_256_XTS_KEY_SIZE <= sizeof(ext4_key->raw), "Key too long!");
+    ext4_key->mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
+    ext4_key->size = key.size();
+    memset(ext4_key->raw, 0, sizeof(ext4_key->raw));
+    memcpy(ext4_key->raw, key.data(), key.size());
+    return true;
+}
+
+std::string keyname(const std::string& raw_ref) {
+    std::ostringstream o;
+    o << "ext4:";
+    for (auto i : raw_ref) {
+        o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
+    }
+    return o.str();
+}
+
+// Get the keyring we store all keys in
+static bool e4cryptKeyring(key_serial_t* device_keyring) {
+    *device_keyring = keyctl_search(KEY_SPEC_SESSION_KEYRING, "keyring", "e4crypt", 0);
+    if (*device_keyring == -1) {
+        PLOG(ERROR) << "Unable to find device keyring";
+        return false;
+    }
+    return true;
+}
+
+// Install password into global keyring
+// Return raw key reference for use in policy
+bool installKey(const std::string& key, std::string* raw_ref) {
+    ext4_encryption_key ext4_key;
+    if (!fillKey(key, &ext4_key)) return false;
+    *raw_ref = generateKeyRef(ext4_key.raw, ext4_key.size);
+    auto ref = keyname(*raw_ref);
+    key_serial_t device_keyring;
+    if (!e4cryptKeyring(&device_keyring)) return false;
+    key_serial_t key_id =
+        add_key("logon", ref.c_str(), (void*)&ext4_key, sizeof(ext4_key), device_keyring);
+    if (key_id == -1) {
+        PLOG(ERROR) << "Failed to insert key into keyring " << device_keyring;
+        return false;
+    }
+    LOG(DEBUG) << "Added key " << key_id << " (" << ref << ") to keyring " << device_keyring
+               << " in process " << getpid();
+
+    return true;
+}
+
+bool evictKey(const std::string& raw_ref) {
+    auto ref = keyname(raw_ref);
+    key_serial_t device_keyring;
+    if (!e4cryptKeyring(&device_keyring)) return false;
+    auto key_serial = keyctl_search(device_keyring, "logon", ref.c_str(), 0);
+
+    // Unlink the key from the keyring.  Prefer unlinking to revoking or
+    // invalidating, since unlinking is actually no less secure currently, and
+    // it avoids bugs in certain kernel versions where the keyring key is
+    // referenced from places it shouldn't be.
+    if (keyctl_unlink(key_serial, device_keyring) != 0) {
+        PLOG(ERROR) << "Failed to unlink key with serial " << key_serial << " ref " << ref;
+        return false;
+    }
+    LOG(DEBUG) << "Unlinked key with serial " << key_serial << " ref " << ref;
+    return true;
+}
+
+bool retrieveAndInstallKey(bool create_if_absent, const std::string& key_path,
+                           const std::string& tmp_path, std::string* key_ref) {
+    std::string key;
+    if (pathExists(key_path)) {
+        LOG(DEBUG) << "Key exists, using: " << key_path;
+        if (!retrieveKey(key_path, kEmptyAuthentication, &key)) return false;
+    } else {
+        if (!create_if_absent) {
+           LOG(ERROR) << "No key found in " << key_path;
+           return false;
+        }
+        LOG(INFO) << "Creating new key in " << key_path;
+        if (!randomKey(&key)) return false;
+        if (!storeKeyAtomically(key_path, tmp_path,
+                kEmptyAuthentication, key)) return false;
+    }
+
+    if (!installKey(key, 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, std::string* key) {
+    if (pathExists(key_path)) {
+        LOG(DEBUG) << "Key exists, using: " << key_path;
+        if (!retrieveKey(key_path, kEmptyAuthentication, key)) return false;
+    } else {
+        if (!create_if_absent) {
+           LOG(ERROR) << "No key found in " << key_path;
+           return false;
+        }
+        LOG(INFO) << "Creating new key in " << key_path;
+        if (!randomKey(key)) return false;
+        if (!storeKeyAtomically(key_path, tmp_path,
+                kEmptyAuthentication, *key)) return false;
+    }
+    return true;
+}
+
+}  // namespace vold
+}  // namespace android
diff --git a/KeyUtil.h b/KeyUtil.h
new file mode 100644
index 0000000..f8fb634
--- /dev/null
+++ b/KeyUtil.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef ANDROID_VOLD_KEYUTIL_H
+#define ANDROID_VOLD_KEYUTIL_H
+
+#include <string>
+
+namespace android {
+namespace vold {
+
+// ext4enc:TODO get this const from somewhere good
+const int EXT4_KEY_DESCRIPTOR_SIZE = 8;
+
+// ext4enc:TODO Include structure from somewhere sensible
+// MUST be in sync with ext4_crypto.c in kernel
+constexpr int EXT4_ENCRYPTION_MODE_AES_256_XTS = 1;
+constexpr int EXT4_AES_256_XTS_KEY_SIZE = 64;
+constexpr int EXT4_MAX_KEY_SIZE = 64;
+struct ext4_encryption_key {
+    uint32_t mode;
+    char raw[EXT4_MAX_KEY_SIZE];
+    uint32_t size;
+};
+
+std::string keyname(const std::string& raw_ref);
+bool randomKey(std::string* key);
+bool installKey(const std::string& key, std::string* raw_ref);
+bool evictKey(const std::string& raw_ref);
+bool retrieveAndInstallKey(bool create_if_absent, const std::string& key_path,
+                           const std::string& tmp_path, std::string* key_ref);
+bool retrieveKey(bool create_if_absent, const std::string& key_path,
+                 const std::string& tmp_path, std::string* key);
+
+}  // namespace vold
+}  // namespace android
+
+#endif
diff --git a/MetadataCrypt.cpp b/MetadataCrypt.cpp
new file mode 100644
index 0000000..b707549
--- /dev/null
+++ b/MetadataCrypt.cpp
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2016 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 "MetadataCrypt.h"
+
+#include <string>
+#include <thread>
+#include <vector>
+
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <linux/dm-ioctl.h>
+
+#include <android-base/logging.h>
+#include <cutils/properties.h>
+#include <fs_mgr.h>
+
+#include "AutoCloseFD.h"
+#include "EncryptInplace.h"
+#include "KeyStorage.h"
+#include "KeyUtil.h"
+#include "secontext.h"
+#include "Utils.h"
+#include "VoldUtil.h"
+
+extern struct fstab *fstab;
+#define DM_CRYPT_BUF_SIZE 4096
+#define TABLE_LOAD_RETRIES 10
+#define DEFAULT_KEY_TARGET_TYPE "default-key"
+
+static const std::string kDmNameUserdata = "userdata";
+
+static bool mount_via_fs_mgr(const char* mount_point, const char* blk_device) {
+    // fs_mgr_do_mount runs fsck. Use setexeccon to run trusted
+    // partitions in the fsck domain.
+    if (setexeccon(secontextFsck())) {
+        PLOG(ERROR) << "Failed to setexeccon";
+        return false;
+    }
+    auto mount_rc = fs_mgr_do_mount(fstab, const_cast<char*>(mount_point),
+                                    const_cast<char*>(blk_device), nullptr);
+    if (setexeccon(nullptr)) {
+        PLOG(ERROR) << "Failed to clear setexeccon";
+        return false;
+    }
+    if (mount_rc != 0) {
+        LOG(ERROR) << "fs_mgr_do_mount failed with rc " << mount_rc;
+        return false;
+    }
+    LOG(DEBUG) << "Mounted " << mount_point;
+    return true;
+}
+
+static bool read_key(bool create_if_absent, std::string* key) {
+    auto data_rec = fs_mgr_get_crypt_entry(fstab);
+    if (!data_rec) {
+        LOG(ERROR) << "Failed to get data_rec";
+        return false;
+    }
+    if (!data_rec->key_dir) {
+        LOG(ERROR) << "Failed to get key_dir";
+        return false;
+    }
+    LOG(DEBUG) << "key_dir: " << data_rec->key_dir;
+    if (!android::vold::pathExists(data_rec->key_dir)) {
+        if (mkdir(data_rec->key_dir, 0777) != 0) {
+            PLOG(ERROR) << "Unable to create: " << data_rec->key_dir;
+            return false;
+        }
+        LOG(DEBUG) << "Created: " << data_rec->key_dir;
+    }
+    std::string key_dir = data_rec->key_dir;
+    auto dir = key_dir + "/key";
+    auto temp = key_dir + "/tmp";
+    if (!android::vold::retrieveKey(create_if_absent, dir, temp, key)) return false;
+    return true;
+}
+
+static std::string default_key_params(const std::string& real_blkdev, const std::string& key) {
+    std::string hex_key;
+    if (android::vold::StrToHex(key, hex_key) != android::OK) {
+        LOG(ERROR) << "Failed to turn key to hex";
+        return "";
+    }
+    auto res = std::string() + "AES-256-XTS " + hex_key + " " + real_blkdev + " 0";
+    LOG(DEBUG) << "crypt_params: " << res;
+    return res;
+}
+
+static bool get_number_of_sectors(const std::string& real_blkdev, uint64_t *nr_sec) {
+    AutoCloseFD dev_fd(real_blkdev, O_RDONLY);
+    if (!dev_fd) {
+        PLOG(ERROR) << "Unable to open " << real_blkdev << " to measure size";
+        return false;
+    }
+    unsigned long res;
+    // TODO: should use BLKGETSIZE64
+    get_blkdev_size(dev_fd.get(), &res);
+    if (res == 0) {
+        PLOG(ERROR) << "Unable to measure size of " << real_blkdev;
+        return false;
+    }
+    *nr_sec = res;
+    return true;
+}
+
+static struct dm_ioctl* dm_ioctl_init(char *buffer, size_t buffer_size,
+                                      const std::string& dm_name) {
+    if (buffer_size < sizeof(dm_ioctl)) {
+        LOG(ERROR) << "dm_ioctl buffer too small";
+        return nullptr;
+    }
+
+    memset(buffer, 0, buffer_size);
+    struct dm_ioctl* io = (struct dm_ioctl*) buffer;
+    io->data_size = buffer_size;
+    io->data_start = sizeof(struct dm_ioctl);
+    io->version[0] = 4;
+    io->version[1] = 0;
+    io->version[2] = 0;
+    io->flags = 0;
+    dm_name.copy(io->name, sizeof(io->name));
+    return io;
+}
+
+static bool create_crypto_blk_dev(const std::string& dm_name, uint64_t nr_sec,
+                                  const std::string& target_type, const std::string& crypt_params,
+                                  std::string* crypto_blkdev) {
+    AutoCloseFD dm_fd("/dev/device-mapper", O_RDWR);
+    if (!dm_fd) {
+        PLOG(ERROR) << "Cannot open device-mapper";
+        return false;
+    }
+    alignas(struct dm_ioctl) char buffer[DM_CRYPT_BUF_SIZE];
+    auto io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+    if (!io || ioctl(dm_fd.get(), DM_DEV_CREATE, io) != 0) {
+        PLOG(ERROR) << "Cannot create dm-crypt device " << dm_name;
+        return false;
+    }
+
+    // Get the device status, in particular, the name of its device file
+    io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+    if (ioctl(dm_fd.get(), DM_DEV_STATUS, io) != 0) {
+        PLOG(ERROR) << "Cannot retrieve dm-crypt device status " << dm_name;
+        return false;
+    }
+    *crypto_blkdev = std::string() + "/dev/block/dm-" + std::to_string(
+        (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00));
+
+    io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+    unsigned long paramix = io->data_start + sizeof(struct dm_target_spec);
+    unsigned long nullix = paramix + crypt_params.size();
+    unsigned long endix = (nullix + 1 + 7) & 8; // Add room for \0 and align to 8 byte boundary
+
+    if (endix > sizeof(buffer)) {
+        LOG(ERROR) << "crypt_params too big for DM_CRYPT_BUF_SIZE";
+        return false;
+    }
+
+    io->target_count = 1;
+    auto tgt = (struct dm_target_spec *) (buffer + io->data_start);
+    tgt->status = 0;
+    tgt->sector_start = 0;
+    tgt->length = nr_sec;
+    target_type.copy(tgt->target_type, sizeof(tgt->target_type));
+    crypt_params.copy(buffer + paramix, sizeof(buffer) - paramix);
+    buffer[nullix] = '\0';
+    tgt->next = endix;
+
+    for (int i = 0; ; i++) {
+        if (ioctl(dm_fd.get(), DM_TABLE_LOAD, io) == 0) {
+            break;
+        }
+        if (i+1 >= TABLE_LOAD_RETRIES) {
+            PLOG(ERROR) << "DM_TABLE_LOAD ioctl failed";
+            return false;
+        }
+        PLOG(INFO) << "DM_TABLE_LOAD ioctl failed, retrying";
+        usleep(500000);
+    }
+
+    // Resume this device to activate it
+    io = dm_ioctl_init(buffer, sizeof(buffer), dm_name);
+    if (ioctl(dm_fd.get(), DM_DEV_SUSPEND, io)) {
+        PLOG(ERROR) << "Cannot resume dm-crypt device " << dm_name;
+        return false;
+    }
+    return true;
+}
+
+#define DATA_PREP_TIMEOUT 1000
+static bool prep_data_fs(void)
+{
+    // NOTE: post_fs_data results in init calling back around to vold, so all
+    // callers to this method must be async
+
+    /* Do the prep of the /data filesystem */
+    property_set("vold.post_fs_data_done", "0");
+    property_set("vold.decrypt", "trigger_post_fs_data");
+    LOG(DEBUG) << "Waiting for post_fs_data_done";
+
+    /* Wait a max of 50 seconds, hopefully it takes much less */
+    for (int i = 0; ; i++) {
+        char p[PROPERTY_VALUE_MAX];
+
+        property_get("vold.post_fs_data_done", p, "0");
+        if (*p == '1') {
+            LOG(INFO) << "Successful data prep";
+            return true;
+        }
+        if (i + 1 == DATA_PREP_TIMEOUT) {
+            LOG(ERROR) << "post_fs_data timed out";
+            return false;
+        }
+        usleep(50000);
+    }
+}
+
+static void async_kick_off() {
+    LOG(DEBUG) << "Asynchronously restarting framework";
+    sleep(2); // TODO: this mirrors cryptfs, but can it be made shorter?
+    property_set("vold.decrypt", "trigger_load_persist_props");
+    if (!prep_data_fs()) return;
+    /* startup service classes main and late_start */
+    property_set("vold.decrypt", "trigger_restart_framework");
+}
+
+bool e4crypt_mount_metadata_encrypted() {
+    LOG(DEBUG) << "e4crypt_mount_default_encrypted";
+    std::string key;
+    if (!read_key(false, &key)) return false;
+    auto data_rec = fs_mgr_get_crypt_entry(fstab);
+    if (!data_rec) {
+        LOG(ERROR) << "Failed to get data_rec";
+        return false;
+    }
+    uint64_t nr_sec;
+    if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
+    std::string crypto_blkdev;
+    if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
+        default_key_params(data_rec->blk_device, key), &crypto_blkdev)) return false;
+    // FIXME handle the corrupt case
+
+    LOG(DEBUG) << "Restarting filesystem for metadata encryption";
+    mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
+    std::thread(&async_kick_off).detach();
+    return true;
+}
+
+bool e4crypt_enable_crypto() {
+    LOG(DEBUG) << "e4crypt_enable_crypto";
+    char encrypted_state[PROPERTY_VALUE_MAX];
+    property_get("ro.crypto.state", encrypted_state, "");
+    if (strcmp(encrypted_state, "")) {
+        LOG(DEBUG) << "e4crypt_enable_crypto got unexpected starting state: " << encrypted_state;
+        return false;
+    }
+
+    std::string key_ref;
+    if (!read_key(true, &key_ref)) return false;
+
+    auto data_rec = fs_mgr_get_crypt_entry(fstab);
+    if (!data_rec) {
+        LOG(ERROR) << "Failed to get data_rec";
+        return false;
+    }
+    uint64_t nr_sec;
+    if (!get_number_of_sectors(data_rec->blk_device, &nr_sec)) return false;
+
+    std::string crypto_blkdev;
+    if (!create_crypto_blk_dev(kDmNameUserdata, nr_sec, DEFAULT_KEY_TARGET_TYPE,
+        default_key_params(data_rec->blk_device, key_ref), &crypto_blkdev)) return false;
+
+    LOG(INFO) << "Beginning inplace encryption, nr_sec: " << nr_sec;
+    off64_t size_already_done = 0;
+    auto rc = cryptfs_enable_inplace(const_cast<char *>(crypto_blkdev.c_str()),
+                                     data_rec->blk_device, nr_sec, &size_already_done, nr_sec, 0);
+    if (rc != 0) {
+        LOG(ERROR) << "Inplace crypto failed with code: " << rc;
+        return false;
+    }
+    if (static_cast<uint64_t>(size_already_done) != nr_sec) {
+        LOG(ERROR) << "Inplace crypto only got up to sector: " << size_already_done;
+        return false;
+    }
+    LOG(INFO) << "Inplace encryption complete";
+
+    property_set("ro.crypto.state", "encrypted");
+    property_set("ro.crypto.type", "file");
+
+    mount_via_fs_mgr(data_rec->mount_point, crypto_blkdev.c_str());
+    property_set("vold.decrypt", "trigger_reset_main");
+    std::thread(&async_kick_off).detach();
+    return true;
+}
diff --git a/MetadataCrypt.h b/MetadataCrypt.h
new file mode 100644
index 0000000..f6634ea
--- /dev/null
+++ b/MetadataCrypt.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef _METADATA_CRYPT_H
+#define _METADATA_CRYPT_H
+
+bool e4crypt_mount_metadata_encrypted();
+bool e4crypt_enable_crypto();
+
+#endif
diff --git a/Process.cpp b/Process.cpp
index fd757d5..1c0f504 100644
--- a/Process.cpp
+++ b/Process.cpp
@@ -28,10 +28,17 @@
 #include <signal.h>
 
 #define LOG_TAG "ProcessKiller"
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/logging.h>
 #include <cutils/log.h>
 
 #include "Process.h"
 
+using android::base::ReadFileToString;
+using android::base::StringPrintf;
+
 int Process::readSymLink(const char *path, char *link, size_t max) {
     struct stat s;
     int length;
@@ -40,10 +47,10 @@
         return 0;
     if ((s.st_mode & S_IFMT) != S_IFLNK)
         return 0;
-   
-    // we have a symlink    
+
+    // we have a symlink
     length = readlink(path, link, max- 1);
-    if (length <= 0) 
+    if (length <= 0)
         return 0;
     link[length] = 0;
     return 1;
@@ -63,16 +70,9 @@
     return 0;
 }
 
-void Process::getProcessName(int pid, char *buffer, size_t max) {
-    int fd;
-    snprintf(buffer, max, "/proc/%d/cmdline", pid);
-    fd = open(buffer, O_RDONLY | O_CLOEXEC);
-    if (fd < 0) {
-        strcpy(buffer, "???");
-    } else {
-        int length = read(fd, buffer, max - 1);
-        buffer[length] = 0;
-        close(fd);
+void Process::getProcessName(int pid, std::string& out_name) {
+    if (!ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &out_name)) {
+        out_name = "???";
     }
 }
 
@@ -103,7 +103,7 @@
         
         // append the file name, after truncating to parent directory
         path[parent_length] = 0;
-        strcat(path, de->d_name);
+        strlcat(path, de->d_name, PATH_MAX);
 
         char link[PATH_MAX];
 
@@ -189,24 +189,24 @@
 
     while ((de = readdir(dir))) {
         int pid = getPid(de->d_name);
-        char name[PATH_MAX];
-
         if (pid == -1)
             continue;
-        getProcessName(pid, name, sizeof(name));
+
+        std::string name;
+        getProcessName(pid, name);
 
         char openfile[PATH_MAX];
 
         if (checkFileDescriptorSymLinks(pid, path, openfile, sizeof(openfile))) {
-            SLOGE("Process %s (%d) has open file %s", name, pid, openfile);
+            SLOGE("Process %s (%d) has open file %s", name.c_str(), pid, openfile);
         } else if (checkFileMaps(pid, path, openfile, sizeof(openfile))) {
-            SLOGE("Process %s (%d) has open filemap for %s", name, pid, openfile);
+            SLOGE("Process %s (%d) has open filemap for %s", name.c_str(), pid, openfile);
         } else if (checkSymLink(pid, path, "cwd")) {
-            SLOGE("Process %s (%d) has cwd within %s", name, pid, path);
+            SLOGE("Process %s (%d) has cwd within %s", name.c_str(), pid, path);
         } else if (checkSymLink(pid, path, "root")) {
-            SLOGE("Process %s (%d) has chroot within %s", name, pid, path);
+            SLOGE("Process %s (%d) has chroot within %s", name.c_str(), pid, path);
         } else if (checkSymLink(pid, path, "exe")) {
-            SLOGE("Process %s (%d) has executable path within %s", name, pid, path);
+            SLOGE("Process %s (%d) has executable path within %s", name.c_str(), pid, path);
         } else {
             continue;
         }
diff --git a/Process.h b/Process.h
index 62a9313..4ddbdb9 100644
--- a/Process.h
+++ b/Process.h
@@ -28,7 +28,7 @@
     static int checkFileMaps(int pid, const char *path, char *openFilename, size_t max);
     static int checkFileDescriptorSymLinks(int pid, const char *mountPoint);
     static int checkFileDescriptorSymLinks(int pid, const char *mountPoint, char *openFilename, size_t max);
-    static void getProcessName(int pid, char *buffer, size_t max);
+    static void getProcessName(int pid, std::string& out_name);
 private:
     static int readSymLink(const char *path, char *link, size_t max);
     static int pathMatchesMountPoint(const char *path, const char *mountPoint);
diff --git a/Utils.cpp b/Utils.cpp
index 443df1d..050a92b 100644
--- a/Utils.cpp
+++ b/Utils.cpp
@@ -292,7 +292,7 @@
         LOG(ERROR) << "Failed to setexeccon";
         abort();
     }
-    FILE* fp = popen(cmd.c_str(), "r");
+    FILE* fp = popen(cmd.c_str(), "r"); // NOLINT
     if (setexeccon(nullptr)) {
         LOG(ERROR) << "Failed to setexeccon";
         abort();
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 3b4c054..e038303 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -180,7 +180,7 @@
         }
         *createdDMDevice = true;
     } else {
-        strcpy(buffer, loopDevice);
+        strlcpy(buffer, loopDevice, len);
         *createdDMDevice = false;
     }
     return 0;
@@ -931,7 +931,7 @@
         cleanupDm = true;
     } else {
         sb.c_cipher = ASEC_SB_C_CIPHER_NONE;
-        strcpy(dmDevice, loopDevice);
+        strlcpy(dmDevice, loopDevice, sizeof(dmDevice));
     }
 
     /*
@@ -1895,7 +1895,7 @@
     // Create a string to compare against that has a trailing slash
     int loopDirLen = strlen(VolumeManager::LOOPDIR);
     char loopDir[loopDirLen + 2];
-    strcpy(loopDir, VolumeManager::LOOPDIR);
+    strlcpy(loopDir, VolumeManager::LOOPDIR, sizeof(loopDir));
     loopDir[loopDirLen++] = '/';
     loopDir[loopDirLen] = '\0';
 
diff --git a/cryptfs.cpp b/cryptfs.cpp
index f2f0f18..6319362 100644
--- a/cryptfs.cpp
+++ b/cryptfs.cpp
@@ -59,6 +59,7 @@
 #include "Ext4Crypt.h"
 #include "f2fs_sparseblock.h"
 #include "CheckBattery.h"
+#include "EncryptInplace.h"
 #include "Process.h"
 #include "Keymaster.h"
 #include "android-base/properties.h"
@@ -1725,7 +1726,8 @@
     memset(&ext_crypt_ftr, 0, sizeof(ext_crypt_ftr));
     ext_crypt_ftr.fs_size = nr_sec;
     ext_crypt_ftr.keysize = keysize;
-    strcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
+    strlcpy((char*) ext_crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256",
+            MAX_CRYPTO_TYPE_NAME_LEN);
 
     return create_crypto_blk_dev(&ext_crypt_ftr, key, real_blkdev,
             out_crypto_blkdev, label);
@@ -1978,610 +1980,6 @@
     return rc;
 }
 
-#define CRYPT_INPLACE_BUFSIZE 4096
-#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
-#define CRYPT_SECTOR_SIZE 512
-
-/* aligned 32K writes tends to make flash happy.
- * SD card association recommends it.
- */
-#define BLOCKS_AT_A_TIME 8
-
-struct encryptGroupsData
-{
-    int realfd;
-    int cryptofd;
-    off64_t numblocks;
-    off64_t one_pct, cur_pct, new_pct;
-    off64_t blocks_already_done, tot_numblocks;
-    off64_t used_blocks_already_done, tot_used_blocks;
-    char* real_blkdev, * crypto_blkdev;
-    int count;
-    off64_t offset;
-    char* buffer;
-    off64_t last_written_sector;
-    int completed;
-    time_t time_started;
-    int remaining_time;
-};
-
-static void update_progress(struct encryptGroupsData* data, int is_used)
-{
-    data->blocks_already_done++;
-
-    if (is_used) {
-        data->used_blocks_already_done++;
-    }
-    if (data->tot_used_blocks) {
-        data->new_pct = data->used_blocks_already_done / data->one_pct;
-    } else {
-        data->new_pct = data->blocks_already_done / data->one_pct;
-    }
-
-    if (data->new_pct > data->cur_pct) {
-        char buf[8];
-        data->cur_pct = data->new_pct;
-        snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
-        property_set("vold.encrypt_progress", buf);
-    }
-
-    if (data->cur_pct >= 5) {
-        struct timespec time_now;
-        if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
-            SLOGW("Error getting time");
-        } else {
-            double elapsed_time = difftime(time_now.tv_sec, data->time_started);
-            off64_t remaining_blocks = data->tot_used_blocks
-                                       - data->used_blocks_already_done;
-            int remaining_time = (int)(elapsed_time * remaining_blocks
-                                       / data->used_blocks_already_done);
-
-            // Change time only if not yet set, lower, or a lot higher for
-            // best user experience
-            if (data->remaining_time == -1
-                || remaining_time < data->remaining_time
-                || remaining_time > data->remaining_time + 60) {
-                char buf[8];
-                snprintf(buf, sizeof(buf), "%d", remaining_time);
-                property_set("vold.encrypt_time_remaining", buf);
-                data->remaining_time = remaining_time;
-            }
-        }
-    }
-}
-
-static void log_progress(struct encryptGroupsData const* data, bool completed)
-{
-    // Precondition - if completed data = 0 else data != 0
-
-    // Track progress so we can skip logging blocks
-    static off64_t offset = -1;
-
-    // Need to close existing 'Encrypting from' log?
-    if (completed || (offset != -1 && data->offset != offset)) {
-        SLOGI("Encrypted to sector %" PRId64,
-              offset / info.block_size * CRYPT_SECTOR_SIZE);
-        offset = -1;
-    }
-
-    // Need to start new 'Encrypting from' log?
-    if (!completed && offset != data->offset) {
-        SLOGI("Encrypting from sector %" PRId64,
-              data->offset / info.block_size * CRYPT_SECTOR_SIZE);
-    }
-
-    // Update offset
-    if (!completed) {
-        offset = data->offset + (off64_t)data->count * info.block_size;
-    }
-}
-
-static int flush_outstanding_data(struct encryptGroupsData* data)
-{
-    if (data->count == 0) {
-        return 0;
-    }
-
-    SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
-
-    if (pread64(data->realfd, data->buffer,
-                info.block_size * data->count, data->offset)
-        <= 0) {
-        SLOGE("Error reading real_blkdev %s for inplace encrypt",
-              data->real_blkdev);
-        return -1;
-    }
-
-    if (pwrite64(data->cryptofd, data->buffer,
-                 info.block_size * data->count, data->offset)
-        <= 0) {
-        SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
-              data->crypto_blkdev);
-        return -1;
-    } else {
-      log_progress(data, false);
-    }
-
-    data->count = 0;
-    data->last_written_sector = (data->offset + data->count)
-                                / info.block_size * CRYPT_SECTOR_SIZE - 1;
-    return 0;
-}
-
-static int encrypt_groups(struct encryptGroupsData* data)
-{
-    unsigned int i;
-    u8 *block_bitmap = 0;
-    unsigned int block;
-    off64_t ret;
-    int rc = -1;
-
-    data->buffer = (char *)malloc(info.block_size * BLOCKS_AT_A_TIME);
-    if (!data->buffer) {
-        SLOGE("Failed to allocate crypto buffer");
-        goto errout;
-    }
-
-    block_bitmap = (u8 *)malloc(info.block_size);
-    if (!block_bitmap) {
-        SLOGE("failed to allocate block bitmap");
-        goto errout;
-    }
-
-    for (i = 0; i < aux_info.groups; ++i) {
-        SLOGI("Encrypting group %d", i);
-
-        u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
-        u32 block_count = std::min(info.blocks_per_group,
-                                   (u32)(aux_info.len_blocks - first_block));
-
-        off64_t offset = (u64)info.block_size
-                         * aux_info.bg_desc[i].bg_block_bitmap;
-
-        ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
-        if (ret != (int)info.block_size) {
-            SLOGE("failed to read all of block group bitmap %d", i);
-            goto errout;
-        }
-
-        offset = (u64)info.block_size * first_block;
-
-        data->count = 0;
-
-        for (block = 0; block < block_count; block++) {
-            int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
-                    0 : bitmap_get_bit(block_bitmap, block);
-            update_progress(data, used);
-            if (used) {
-                if (data->count == 0) {
-                    data->offset = offset;
-                }
-                data->count++;
-            } else {
-                if (flush_outstanding_data(data)) {
-                    goto errout;
-                }
-            }
-
-            offset += info.block_size;
-
-            /* Write data if we are aligned or buffer size reached */
-            if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
-                || data->count == BLOCKS_AT_A_TIME) {
-                if (flush_outstanding_data(data)) {
-                    goto errout;
-                }
-            }
-
-            if (!is_battery_ok_to_continue()) {
-                SLOGE("Stopping encryption due to low battery");
-                rc = 0;
-                goto errout;
-            }
-
-        }
-        if (flush_outstanding_data(data)) {
-            goto errout;
-        }
-    }
-
-    data->completed = 1;
-    rc = 0;
-
-errout:
-    log_progress(0, true);
-    free(data->buffer);
-    free(block_bitmap);
-    return rc;
-}
-
-static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
-                                       char *real_blkdev,
-                                       off64_t size,
-                                       off64_t *size_already_done,
-                                       off64_t tot_size,
-                                       off64_t previously_encrypted_upto)
-{
-    u32 i;
-    struct encryptGroupsData data;
-    int rc; // Can't initialize without causing warning -Wclobbered
-    struct timespec time_started = {0};
-    int retries = RETRY_MOUNT_ATTEMPTS;
-
-    if (previously_encrypted_upto > *size_already_done) {
-        SLOGD("Not fast encrypting since resuming part way through");
-        return -1;
-    }
-
-    memset(&data, 0, sizeof(data));
-    data.real_blkdev = real_blkdev;
-    data.crypto_blkdev = crypto_blkdev;
-
-    if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
-        SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
-              real_blkdev, errno, strerror(errno));
-        rc = -1;
-        goto errout;
-    }
-
-    // Wait until the block device appears.  Re-use the mount retry values since it is reasonable.
-    while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
-        if (--retries) {
-            SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
-                  crypto_blkdev, errno, strerror(errno));
-            sleep(RETRY_MOUNT_DELAY_SECONDS);
-        } else {
-            SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
-                  crypto_blkdev, errno, strerror(errno));
-            rc = ENABLE_INPLACE_ERR_DEV;
-            goto errout;
-        }
-    }
-
-    if (setjmp(setjmp_env)) {
-        SLOGE("Reading ext4 extent caused an exception\n");
-        rc = -1;
-        goto errout;
-    }
-
-    if (read_ext(data.realfd, 0) != 0) {
-        SLOGE("Failed to read ext4 extent\n");
-        rc = -1;
-        goto errout;
-    }
-
-    data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
-    data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
-    data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
-
-    SLOGI("Encrypting ext4 filesystem in place...");
-
-    data.tot_used_blocks = data.numblocks;
-    for (i = 0; i < aux_info.groups; ++i) {
-      data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
-    }
-
-    data.one_pct = data.tot_used_blocks / 100;
-    data.cur_pct = 0;
-
-    if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
-        SLOGW("Error getting time at start");
-        // Note - continue anyway - we'll run with 0
-    }
-    data.time_started = time_started.tv_sec;
-    data.remaining_time = -1;
-
-    rc = encrypt_groups(&data);
-    if (rc) {
-        SLOGE("Error encrypting groups");
-        goto errout;
-    }
-
-    *size_already_done += data.completed ? size : data.last_written_sector;
-    rc = 0;
-
-errout:
-    close(data.realfd);
-    close(data.cryptofd);
-
-    return rc;
-}
-
-static void log_progress_f2fs(u64 block, bool completed)
-{
-    // Precondition - if completed data = 0 else data != 0
-
-    // Track progress so we can skip logging blocks
-    static u64 last_block = (u64)-1;
-
-    // Need to close existing 'Encrypting from' log?
-    if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
-        SLOGI("Encrypted to block %" PRId64, last_block);
-        last_block = -1;
-    }
-
-    // Need to start new 'Encrypting from' log?
-    if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
-        SLOGI("Encrypting from block %" PRId64, block);
-    }
-
-    // Update offset
-    if (!completed) {
-        last_block = block;
-    }
-}
-
-static int encrypt_one_block_f2fs(u64 pos, void *data)
-{
-    struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
-
-    priv_dat->blocks_already_done = pos - 1;
-    update_progress(priv_dat, 1);
-
-    off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
-
-    if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
-        SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
-        return -1;
-    }
-
-    if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
-        SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
-        return -1;
-    } else {
-        log_progress_f2fs(pos, false);
-    }
-
-    return 0;
-}
-
-static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
-                                       char *real_blkdev,
-                                       off64_t size,
-                                       off64_t *size_already_done,
-                                       off64_t tot_size,
-                                       off64_t previously_encrypted_upto)
-{
-    struct encryptGroupsData data;
-    struct f2fs_info *f2fs_info = NULL;
-    int rc = ENABLE_INPLACE_ERR_OTHER;
-    if (previously_encrypted_upto > *size_already_done) {
-        SLOGD("Not fast encrypting since resuming part way through");
-        return ENABLE_INPLACE_ERR_OTHER;
-    }
-    memset(&data, 0, sizeof(data));
-    data.real_blkdev = real_blkdev;
-    data.crypto_blkdev = crypto_blkdev;
-    data.realfd = -1;
-    data.cryptofd = -1;
-    if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
-        SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
-              real_blkdev);
-        goto errout;
-    }
-    if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
-        SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
-              crypto_blkdev, errno, strerror(errno));
-        rc = ENABLE_INPLACE_ERR_DEV;
-        goto errout;
-    }
-
-    f2fs_info = generate_f2fs_info(data.realfd);
-    if (!f2fs_info)
-      goto errout;
-
-    data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
-    data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
-    data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
-
-    data.tot_used_blocks = get_num_blocks_used(f2fs_info);
-
-    data.one_pct = data.tot_used_blocks / 100;
-    data.cur_pct = 0;
-    data.time_started = time(NULL);
-    data.remaining_time = -1;
-
-    data.buffer = (char *)malloc(f2fs_info->block_size);
-    if (!data.buffer) {
-        SLOGE("Failed to allocate crypto buffer");
-        goto errout;
-    }
-
-    data.count = 0;
-
-    /* Currently, this either runs to completion, or hits a nonrecoverable error */
-    rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
-
-    if (rc) {
-        SLOGE("Error in running over f2fs blocks");
-        rc = ENABLE_INPLACE_ERR_OTHER;
-        goto errout;
-    }
-
-    *size_already_done += size;
-    rc = 0;
-
-errout:
-    if (rc)
-        SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
-
-    log_progress_f2fs(0, true);
-    free(f2fs_info);
-    free(data.buffer);
-    close(data.realfd);
-    close(data.cryptofd);
-
-    return rc;
-}
-
-static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
-                                       off64_t size, off64_t *size_already_done,
-                                       off64_t tot_size,
-                                       off64_t previously_encrypted_upto)
-{
-    int realfd, cryptofd;
-    char *buf[CRYPT_INPLACE_BUFSIZE];
-    int rc = ENABLE_INPLACE_ERR_OTHER;
-    off64_t numblocks, i, remainder;
-    off64_t one_pct, cur_pct, new_pct;
-    off64_t blocks_already_done, tot_numblocks;
-
-    if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
-        SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
-        return ENABLE_INPLACE_ERR_OTHER;
-    }
-
-    if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
-        SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
-              crypto_blkdev, errno, strerror(errno));
-        close(realfd);
-        return ENABLE_INPLACE_ERR_DEV;
-    }
-
-    /* This is pretty much a simple loop of reading 4K, and writing 4K.
-     * The size passed in is the number of 512 byte sectors in the filesystem.
-     * So compute the number of whole 4K blocks we should read/write,
-     * and the remainder.
-     */
-    numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
-    remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
-    tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
-    blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
-
-    SLOGE("Encrypting filesystem in place...");
-
-    i = previously_encrypted_upto + 1 - *size_already_done;
-
-    if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
-        SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
-        goto errout;
-    }
-
-    if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
-        SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
-        goto errout;
-    }
-
-    for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
-        if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
-            SLOGE("Error reading initial sectors from real_blkdev %s for "
-                  "inplace encrypt\n", crypto_blkdev);
-            goto errout;
-        }
-        if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
-            SLOGE("Error writing initial sectors to crypto_blkdev %s for "
-                  "inplace encrypt\n", crypto_blkdev);
-            goto errout;
-        } else {
-            SLOGI("Encrypted 1 block at %" PRId64, i);
-        }
-    }
-
-    one_pct = tot_numblocks / 100;
-    cur_pct = 0;
-    /* process the majority of the filesystem in blocks */
-    for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
-        new_pct = (i + blocks_already_done) / one_pct;
-        if (new_pct > cur_pct) {
-            char buf[8];
-
-            cur_pct = new_pct;
-            snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
-            property_set("vold.encrypt_progress", buf);
-        }
-        if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
-            SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
-            goto errout;
-        }
-        if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
-            SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
-            goto errout;
-        } else {
-            SLOGD("Encrypted %d block at %" PRId64,
-                  CRYPT_SECTORS_PER_BUFSIZE,
-                  i * CRYPT_SECTORS_PER_BUFSIZE);
-        }
-
-       if (!is_battery_ok_to_continue()) {
-            SLOGE("Stopping encryption due to low battery");
-            *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
-            rc = 0;
-            goto errout;
-        }
-    }
-
-    /* Do any remaining sectors */
-    for (i=0; i<remainder; i++) {
-        if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
-            SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
-            goto errout;
-        }
-        if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
-            SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
-            goto errout;
-        } else {
-            SLOGI("Encrypted 1 block at next location");
-        }
-    }
-
-    *size_already_done += size;
-    rc = 0;
-
-errout:
-    close(realfd);
-    close(cryptofd);
-
-    return rc;
-}
-
-/* returns on of the ENABLE_INPLACE_* return codes */
-static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
-                                  off64_t size, off64_t *size_already_done,
-                                  off64_t tot_size,
-                                  off64_t previously_encrypted_upto)
-{
-    int rc_ext4, rc_f2fs, rc_full;
-    if (previously_encrypted_upto) {
-        SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
-    }
-
-    if (*size_already_done + size < previously_encrypted_upto) {
-        *size_already_done += size;
-        return 0;
-    }
-
-    /* TODO: identify filesystem type.
-     * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
-     * then we will drop down to cryptfs_enable_inplace_f2fs.
-     * */
-    if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
-                                size, size_already_done,
-                                tot_size, previously_encrypted_upto)) == 0) {
-      return 0;
-    }
-    SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
-
-    if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
-                                size, size_already_done,
-                                tot_size, previously_encrypted_upto)) == 0) {
-      return 0;
-    }
-    SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
-
-    rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
-                                       size, size_already_done, tot_size,
-                                       previously_encrypted_upto);
-    SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
-
-    /* Hack for b/17898962, the following is the symptom... */
-    if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
-        && rc_f2fs == ENABLE_INPLACE_ERR_DEV
-        && rc_full == ENABLE_INPLACE_ERR_DEV) {
-            return ENABLE_INPLACE_ERR_DEV;
-    }
-    return rc_full;
-}
-
 #define CRYPTO_ENABLE_WIPE 1
 #define CRYPTO_ENABLE_INPLACE 2
 
@@ -3496,11 +2894,6 @@
     }
 }
 
-int cryptfs_enable_file()
-{
-    return e4crypt_initialize_global_de();
-}
-
 int cryptfs_isConvertibleToFBE()
 {
     struct fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab, DATA_MNT_POINT);
diff --git a/cryptfs.h b/cryptfs.h
index 352a576..d20d96d 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -237,7 +237,6 @@
   int cryptfs_setup_ext_volume(const char* label, const char* real_blkdev,
           const unsigned char* key, int keysize, char* out_crypto_blkdev);
   int cryptfs_revert_ext_volume(const char* label);
-  int cryptfs_enable_file();
   int cryptfs_getfield(const char *fieldname, char *value, int len);
   int cryptfs_setfield(const char *fieldname, const char *value);
   int cryptfs_mount_default_encrypted(void);