2 * Copyright (C) 2016 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "EncryptInplace.h"
24 #include <sys/types.h>
27 #include <ext4_utils/ext4.h>
28 #include <ext4_utils/ext4_utils.h>
29 #include <f2fs_sparseblock.h>
33 #include "cutils/properties.h"
34 #define LOG_TAG "EncryptInplace"
35 #include "cutils/log.h"
36 #include "CheckBattery.h"
38 // HORRIBLE HACK, FIXME
41 // FIXME horrible cut-and-paste code
42 static inline int unix_read(int fd, void* buff, int len)
44 return TEMP_FAILURE_RETRY(read(fd, buff, len));
47 static inline int unix_write(int fd, const void* buff, int len)
49 return TEMP_FAILURE_RETRY(write(fd, buff, len));
52 #define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
54 /* aligned 32K writes tends to make flash happy.
55 * SD card association recommends it.
57 #ifndef CONFIG_HW_DISK_ENCRYPTION
58 #define BLOCKS_AT_A_TIME 8
60 #define BLOCKS_AT_A_TIME 1024
63 struct encryptGroupsData
68 off64_t one_pct, cur_pct, new_pct;
69 off64_t blocks_already_done, tot_numblocks;
70 off64_t used_blocks_already_done, tot_used_blocks;
71 char* real_blkdev, * crypto_blkdev;
75 off64_t last_written_sector;
81 static void update_progress(struct encryptGroupsData* data, int is_used)
83 data->blocks_already_done++;
86 data->used_blocks_already_done++;
88 if (data->tot_used_blocks) {
89 data->new_pct = data->used_blocks_already_done / data->one_pct;
91 data->new_pct = data->blocks_already_done / data->one_pct;
94 if (data->new_pct > data->cur_pct) {
96 data->cur_pct = data->new_pct;
97 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
98 property_set("vold.encrypt_progress", buf);
101 if (data->cur_pct >= 5) {
102 struct timespec time_now;
103 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
104 SLOGW("Error getting time");
106 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
107 off64_t remaining_blocks = data->tot_used_blocks
108 - data->used_blocks_already_done;
109 int remaining_time = (int)(elapsed_time * remaining_blocks
110 / data->used_blocks_already_done);
112 // Change time only if not yet set, lower, or a lot higher for
113 // best user experience
114 if (data->remaining_time == -1
115 || remaining_time < data->remaining_time
116 || remaining_time > data->remaining_time + 60) {
118 snprintf(buf, sizeof(buf), "%d", remaining_time);
119 property_set("vold.encrypt_time_remaining", buf);
120 data->remaining_time = remaining_time;
126 static void log_progress(struct encryptGroupsData const* data, bool completed)
128 // Precondition - if completed data = 0 else data != 0
130 // Track progress so we can skip logging blocks
131 static off64_t offset = -1;
133 // Need to close existing 'Encrypting from' log?
134 if (completed || (offset != -1 && data->offset != offset)) {
135 SLOGI("Encrypted to sector %" PRId64,
136 offset / info.block_size * CRYPT_SECTOR_SIZE);
140 // Need to start new 'Encrypting from' log?
141 if (!completed && offset != data->offset) {
142 SLOGI("Encrypting from sector %" PRId64,
143 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
148 offset = data->offset + (off64_t)data->count * info.block_size;
152 static int flush_outstanding_data(struct encryptGroupsData* data)
154 if (data->count == 0) {
158 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
160 if (pread64(data->realfd, data->buffer,
161 info.block_size * data->count, data->offset)
163 SLOGE("Error reading real_blkdev %s for inplace encrypt",
168 if (pwrite64(data->cryptofd, data->buffer,
169 info.block_size * data->count, data->offset)
171 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
172 data->crypto_blkdev);
175 log_progress(data, false);
179 data->last_written_sector = (data->offset + data->count)
180 / info.block_size * CRYPT_SECTOR_SIZE - 1;
184 static int encrypt_groups(struct encryptGroupsData* data)
187 u8 *block_bitmap = 0;
192 data->buffer = (char*) malloc(info.block_size * BLOCKS_AT_A_TIME);
194 SLOGE("Failed to allocate crypto buffer");
198 block_bitmap = (u8*) malloc(info.block_size);
200 SLOGE("failed to allocate block bitmap");
204 for (i = 0; i < aux_info.groups; ++i) {
205 SLOGI("Encrypting group %d", i);
207 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
208 u32 block_count = std::min(info.blocks_per_group,
209 (u32)(aux_info.len_blocks - first_block));
211 off64_t offset = (u64)info.block_size
212 * aux_info.bg_desc[i].bg_block_bitmap;
214 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
215 if (ret != (int)info.block_size) {
216 SLOGE("failed to read all of block group bitmap %d", i);
220 offset = (u64)info.block_size * first_block;
224 for (block = 0; block < block_count; block++) {
225 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
226 0 : bitmap_get_bit(block_bitmap, block);
227 update_progress(data, used);
229 if (data->count == 0) {
230 data->offset = offset;
234 if (flush_outstanding_data(data)) {
239 offset += info.block_size;
241 /* Write data if we are aligned or buffer size reached */
242 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
243 || data->count == BLOCKS_AT_A_TIME) {
244 if (flush_outstanding_data(data)) {
249 if (!is_battery_ok_to_continue()) {
250 SLOGE("Stopping encryption due to low battery");
256 if (flush_outstanding_data(data)) {
265 log_progress(0, true);
271 static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
274 off64_t *size_already_done,
276 off64_t previously_encrypted_upto)
279 struct encryptGroupsData data;
280 int rc; // Can't initialize without causing warning -Wclobbered
281 int retries = RETRY_MOUNT_ATTEMPTS;
282 struct timespec time_started = {0};
284 if (previously_encrypted_upto > *size_already_done) {
285 SLOGD("Not fast encrypting since resuming part way through");
289 memset(&data, 0, sizeof(data));
290 data.real_blkdev = real_blkdev;
291 data.crypto_blkdev = crypto_blkdev;
293 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
294 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
295 real_blkdev, errno, strerror(errno));
300 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
301 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
303 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
304 crypto_blkdev, errno, strerror(errno));
305 sleep(RETRY_MOUNT_DELAY_SECONDS);
307 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
308 crypto_blkdev, errno, strerror(errno));
309 rc = ENABLE_INPLACE_ERR_DEV;
314 if (setjmp(setjmp_env)) { // NOLINT
315 SLOGE("Reading ext4 extent caused an exception\n");
320 if (read_ext(data.realfd, 0) != 0) {
321 SLOGE("Failed to read ext4 extent\n");
326 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
327 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
328 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
330 SLOGI("Encrypting ext4 filesystem in place...");
332 data.tot_used_blocks = data.numblocks;
333 for (i = 0; i < aux_info.groups; ++i) {
334 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
337 data.one_pct = data.tot_used_blocks / 100;
340 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
341 SLOGW("Error getting time at start");
342 // Note - continue anyway - we'll run with 0
344 data.time_started = time_started.tv_sec;
345 data.remaining_time = -1;
347 rc = encrypt_groups(&data);
349 SLOGE("Error encrypting groups");
353 *size_already_done += data.completed ? size : data.last_written_sector;
358 close(data.cryptofd);
363 static void log_progress_f2fs(u64 block, bool completed)
365 // Precondition - if completed data = 0 else data != 0
367 // Track progress so we can skip logging blocks
368 static u64 last_block = (u64)-1;
370 // Need to close existing 'Encrypting from' log?
371 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
372 SLOGI("Encrypted to block %" PRId64, last_block);
376 // Need to start new 'Encrypting from' log?
377 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
378 SLOGI("Encrypting from block %" PRId64, block);
387 static int encrypt_one_block_f2fs(u64 pos, void *data)
389 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
391 priv_dat->blocks_already_done = pos - 1;
392 update_progress(priv_dat, 1);
394 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
396 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
397 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
401 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
402 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
405 log_progress_f2fs(pos, false);
411 static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
414 off64_t *size_already_done,
416 off64_t previously_encrypted_upto)
418 struct encryptGroupsData data;
419 struct f2fs_info *f2fs_info = NULL;
420 int rc = ENABLE_INPLACE_ERR_OTHER;
421 if (previously_encrypted_upto > *size_already_done) {
422 SLOGD("Not fast encrypting since resuming part way through");
423 return ENABLE_INPLACE_ERR_OTHER;
425 memset(&data, 0, sizeof(data));
426 data.real_blkdev = real_blkdev;
427 data.crypto_blkdev = crypto_blkdev;
430 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
431 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
435 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
436 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
437 crypto_blkdev, errno, strerror(errno));
438 rc = ENABLE_INPLACE_ERR_DEV;
442 f2fs_info = generate_f2fs_info(data.realfd);
446 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
447 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
448 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
450 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
452 data.one_pct = data.tot_used_blocks / 100;
454 data.time_started = time(NULL);
455 data.remaining_time = -1;
457 data.buffer = (char*) malloc(f2fs_info->block_size);
459 SLOGE("Failed to allocate crypto buffer");
465 /* Currently, this either runs to completion, or hits a nonrecoverable error */
466 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
469 SLOGE("Error in running over f2fs blocks");
470 rc = ENABLE_INPLACE_ERR_OTHER;
474 *size_already_done += size;
479 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
481 log_progress_f2fs(0, true);
485 close(data.cryptofd);
490 static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
491 off64_t size, off64_t *size_already_done,
493 off64_t previously_encrypted_upto)
495 int realfd, cryptofd;
496 char *buf[CRYPT_INPLACE_BUFSIZE];
497 int rc = ENABLE_INPLACE_ERR_OTHER;
498 off64_t numblocks, i, remainder;
499 off64_t one_pct, cur_pct, new_pct;
500 off64_t blocks_already_done, tot_numblocks;
502 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
503 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
504 return ENABLE_INPLACE_ERR_OTHER;
507 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
508 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
509 crypto_blkdev, errno, strerror(errno));
511 return ENABLE_INPLACE_ERR_DEV;
514 /* This is pretty much a simple loop of reading 4K, and writing 4K.
515 * The size passed in is the number of 512 byte sectors in the filesystem.
516 * So compute the number of whole 4K blocks we should read/write,
519 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
520 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
521 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
522 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
524 SLOGE("Encrypting filesystem in place...");
526 i = previously_encrypted_upto + 1 - *size_already_done;
528 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
529 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
533 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
534 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
538 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
539 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
540 SLOGE("Error reading initial sectors from real_blkdev %s for "
541 "inplace encrypt\n", crypto_blkdev);
544 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
545 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
546 "inplace encrypt\n", crypto_blkdev);
549 SLOGI("Encrypted 1 block at %" PRId64, i);
553 one_pct = tot_numblocks / 100;
555 /* process the majority of the filesystem in blocks */
556 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
557 new_pct = (i + blocks_already_done) / one_pct;
558 if (new_pct > cur_pct) {
562 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
563 property_set("vold.encrypt_progress", buf);
565 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
566 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
569 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
570 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
573 SLOGD("Encrypted %d block at %" PRId64,
574 CRYPT_SECTORS_PER_BUFSIZE,
575 i * CRYPT_SECTORS_PER_BUFSIZE);
578 if (!is_battery_ok_to_continue()) {
579 SLOGE("Stopping encryption due to low battery");
580 *size_already_done += (i + 1) * CRYPT_SECTORS_PER_BUFSIZE - 1;
586 /* Do any remaining sectors */
587 for (i=0; i<remainder; i++) {
588 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
589 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
592 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
593 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
596 SLOGI("Encrypted 1 block at next location");
600 *size_already_done += size;
610 /* returns on of the ENABLE_INPLACE_* return codes */
611 int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
612 off64_t size, off64_t *size_already_done,
614 off64_t previously_encrypted_upto)
616 int rc_ext4, rc_f2fs, rc_full;
617 if (previously_encrypted_upto) {
618 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
621 if (*size_already_done + size < previously_encrypted_upto) {
622 *size_already_done += size;
626 /* TODO: identify filesystem type.
627 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
628 * then we will drop down to cryptfs_enable_inplace_f2fs.
630 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
631 size, size_already_done,
632 tot_size, previously_encrypted_upto)) == 0) {
635 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
637 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
638 size, size_already_done,
639 tot_size, previously_encrypted_upto)) == 0) {
642 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
644 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
645 size, size_already_done, tot_size,
646 previously_encrypted_upto);
647 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
649 /* Hack for b/17898962, the following is the symptom... */
650 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
651 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
652 && rc_full == ENABLE_INPLACE_ERR_DEV) {
653 return ENABLE_INPLACE_ERR_DEV;