blob: 6ef1cb0d538973a371c095e26a814a32cf133027 [file] [log] [blame]
Paul Crowleyf71ace32016-06-02 11:01:19 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "EncryptInplace.h"
18
19#include <stdio.h>
20#include <stdint.h>
21#include <stdbool.h>
22#include <inttypes.h>
23#include <time.h>
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <fcntl.h>
27#include <ext4_utils/ext4.h>
28#include <ext4_utils/ext4_utils.h>
29#include <f2fs_sparseblock.h>
30
31#include <algorithm>
32
33#include "cutils/properties.h"
34#define LOG_TAG "EncryptInplace"
35#include "cutils/log.h"
Paul Crowleyf71ace32016-06-02 11:01:19 -070036
37// HORRIBLE HACK, FIXME
38#include "cryptfs.h"
39
40// FIXME horrible cut-and-paste code
41static inline int unix_read(int fd, void* buff, int len)
42{
43 return TEMP_FAILURE_RETRY(read(fd, buff, len));
44}
45
46static inline int unix_write(int fd, const void* buff, int len)
47{
48 return TEMP_FAILURE_RETRY(write(fd, buff, len));
49}
50
51#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / CRYPT_SECTOR_SIZE)
52
53/* aligned 32K writes tends to make flash happy.
54 * SD card association recommends it.
55 */
56#ifndef CONFIG_HW_DISK_ENCRYPTION
57#define BLOCKS_AT_A_TIME 8
58#else
59#define BLOCKS_AT_A_TIME 1024
60#endif
61
62struct encryptGroupsData
63{
64 int realfd;
65 int cryptofd;
66 off64_t numblocks;
67 off64_t one_pct, cur_pct, new_pct;
68 off64_t blocks_already_done, tot_numblocks;
69 off64_t used_blocks_already_done, tot_used_blocks;
70 char* real_blkdev, * crypto_blkdev;
71 int count;
72 off64_t offset;
73 char* buffer;
74 off64_t last_written_sector;
75 int completed;
76 time_t time_started;
77 int remaining_time;
78};
79
80static void update_progress(struct encryptGroupsData* data, int is_used)
81{
82 data->blocks_already_done++;
83
84 if (is_used) {
85 data->used_blocks_already_done++;
86 }
87 if (data->tot_used_blocks) {
88 data->new_pct = data->used_blocks_already_done / data->one_pct;
89 } else {
90 data->new_pct = data->blocks_already_done / data->one_pct;
91 }
92
93 if (data->new_pct > data->cur_pct) {
94 char buf[8];
95 data->cur_pct = data->new_pct;
96 snprintf(buf, sizeof(buf), "%" PRId64, data->cur_pct);
97 property_set("vold.encrypt_progress", buf);
98 }
99
100 if (data->cur_pct >= 5) {
101 struct timespec time_now;
102 if (clock_gettime(CLOCK_MONOTONIC, &time_now)) {
103 SLOGW("Error getting time");
104 } else {
105 double elapsed_time = difftime(time_now.tv_sec, data->time_started);
106 off64_t remaining_blocks = data->tot_used_blocks
107 - data->used_blocks_already_done;
108 int remaining_time = (int)(elapsed_time * remaining_blocks
109 / data->used_blocks_already_done);
110
111 // Change time only if not yet set, lower, or a lot higher for
112 // best user experience
113 if (data->remaining_time == -1
114 || remaining_time < data->remaining_time
115 || remaining_time > data->remaining_time + 60) {
116 char buf[8];
117 snprintf(buf, sizeof(buf), "%d", remaining_time);
118 property_set("vold.encrypt_time_remaining", buf);
119 data->remaining_time = remaining_time;
120 }
121 }
122 }
123}
124
125static void log_progress(struct encryptGroupsData const* data, bool completed)
126{
127 // Precondition - if completed data = 0 else data != 0
128
129 // Track progress so we can skip logging blocks
130 static off64_t offset = -1;
131
132 // Need to close existing 'Encrypting from' log?
133 if (completed || (offset != -1 && data->offset != offset)) {
134 SLOGI("Encrypted to sector %" PRId64,
135 offset / info.block_size * CRYPT_SECTOR_SIZE);
136 offset = -1;
137 }
138
139 // Need to start new 'Encrypting from' log?
140 if (!completed && offset != data->offset) {
141 SLOGI("Encrypting from sector %" PRId64,
142 data->offset / info.block_size * CRYPT_SECTOR_SIZE);
143 }
144
145 // Update offset
146 if (!completed) {
147 offset = data->offset + (off64_t)data->count * info.block_size;
148 }
149}
150
151static int flush_outstanding_data(struct encryptGroupsData* data)
152{
153 if (data->count == 0) {
154 return 0;
155 }
156
157 SLOGV("Copying %d blocks at offset %" PRIx64, data->count, data->offset);
158
159 if (pread64(data->realfd, data->buffer,
160 info.block_size * data->count, data->offset)
161 <= 0) {
162 SLOGE("Error reading real_blkdev %s for inplace encrypt",
163 data->real_blkdev);
164 return -1;
165 }
166
167 if (pwrite64(data->cryptofd, data->buffer,
168 info.block_size * data->count, data->offset)
169 <= 0) {
170 SLOGE("Error writing crypto_blkdev %s for inplace encrypt",
171 data->crypto_blkdev);
172 return -1;
173 } else {
174 log_progress(data, false);
175 }
176
177 data->count = 0;
178 data->last_written_sector = (data->offset + data->count)
179 / info.block_size * CRYPT_SECTOR_SIZE - 1;
180 return 0;
181}
182
183static int encrypt_groups(struct encryptGroupsData* data)
184{
185 unsigned int i;
186 u8 *block_bitmap = 0;
187 unsigned int block;
188 off64_t ret;
189 int rc = -1;
190
191 data->buffer = (char*) malloc(info.block_size * BLOCKS_AT_A_TIME);
192 if (!data->buffer) {
193 SLOGE("Failed to allocate crypto buffer");
194 goto errout;
195 }
196
197 block_bitmap = (u8*) malloc(info.block_size);
198 if (!block_bitmap) {
199 SLOGE("failed to allocate block bitmap");
200 goto errout;
201 }
202
203 for (i = 0; i < aux_info.groups; ++i) {
204 SLOGI("Encrypting group %d", i);
205
206 u32 first_block = aux_info.first_data_block + i * info.blocks_per_group;
207 u32 block_count = std::min(info.blocks_per_group,
208 (u32)(aux_info.len_blocks - first_block));
209
210 off64_t offset = (u64)info.block_size
211 * aux_info.bg_desc[i].bg_block_bitmap;
212
213 ret = pread64(data->realfd, block_bitmap, info.block_size, offset);
214 if (ret != (int)info.block_size) {
215 SLOGE("failed to read all of block group bitmap %d", i);
216 goto errout;
217 }
218
219 offset = (u64)info.block_size * first_block;
220
221 data->count = 0;
222
223 for (block = 0; block < block_count; block++) {
224 int used = (aux_info.bg_desc[i].bg_flags & EXT4_BG_BLOCK_UNINIT) ?
225 0 : bitmap_get_bit(block_bitmap, block);
226 update_progress(data, used);
227 if (used) {
228 if (data->count == 0) {
229 data->offset = offset;
230 }
231 data->count++;
232 } else {
233 if (flush_outstanding_data(data)) {
234 goto errout;
235 }
236 }
237
238 offset += info.block_size;
239
240 /* Write data if we are aligned or buffer size reached */
241 if (offset % (info.block_size * BLOCKS_AT_A_TIME) == 0
242 || data->count == BLOCKS_AT_A_TIME) {
243 if (flush_outstanding_data(data)) {
244 goto errout;
245 }
246 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700247 }
248 if (flush_outstanding_data(data)) {
249 goto errout;
250 }
251 }
252
253 data->completed = 1;
254 rc = 0;
255
256errout:
257 log_progress(0, true);
258 free(data->buffer);
259 free(block_bitmap);
260 return rc;
261}
262
263static int cryptfs_enable_inplace_ext4(char *crypto_blkdev,
264 char *real_blkdev,
265 off64_t size,
266 off64_t *size_already_done,
267 off64_t tot_size,
268 off64_t previously_encrypted_upto)
269{
270 u32 i;
271 struct encryptGroupsData data;
272 int rc; // Can't initialize without causing warning -Wclobbered
273 int retries = RETRY_MOUNT_ATTEMPTS;
274 struct timespec time_started = {0};
275
276 if (previously_encrypted_upto > *size_already_done) {
277 SLOGD("Not fast encrypting since resuming part way through");
278 return -1;
279 }
280
281 memset(&data, 0, sizeof(data));
282 data.real_blkdev = real_blkdev;
283 data.crypto_blkdev = crypto_blkdev;
284
285 if ( (data.realfd = open(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
286 SLOGE("Error opening real_blkdev %s for inplace encrypt. err=%d(%s)\n",
287 real_blkdev, errno, strerror(errno));
288 rc = -1;
289 goto errout;
290 }
291
292 // Wait until the block device appears. Re-use the mount retry values since it is reasonable.
293 while ((data.cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
294 if (--retries) {
295 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s), retrying\n",
296 crypto_blkdev, errno, strerror(errno));
297 sleep(RETRY_MOUNT_DELAY_SECONDS);
298 } else {
299 SLOGE("Error opening crypto_blkdev %s for ext4 inplace encrypt. err=%d(%s)\n",
300 crypto_blkdev, errno, strerror(errno));
301 rc = ENABLE_INPLACE_ERR_DEV;
302 goto errout;
303 }
304 }
305
306 if (setjmp(setjmp_env)) { // NOLINT
307 SLOGE("Reading ext4 extent caused an exception\n");
308 rc = -1;
309 goto errout;
310 }
311
312 if (read_ext(data.realfd, 0) != 0) {
313 SLOGE("Failed to read ext4 extent\n");
314 rc = -1;
315 goto errout;
316 }
317
318 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
319 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
320 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
321
322 SLOGI("Encrypting ext4 filesystem in place...");
323
324 data.tot_used_blocks = data.numblocks;
325 for (i = 0; i < aux_info.groups; ++i) {
326 data.tot_used_blocks -= aux_info.bg_desc[i].bg_free_blocks_count;
327 }
328
329 data.one_pct = data.tot_used_blocks / 100;
330 data.cur_pct = 0;
331
332 if (clock_gettime(CLOCK_MONOTONIC, &time_started)) {
333 SLOGW("Error getting time at start");
334 // Note - continue anyway - we'll run with 0
335 }
336 data.time_started = time_started.tv_sec;
337 data.remaining_time = -1;
338
339 rc = encrypt_groups(&data);
340 if (rc) {
341 SLOGE("Error encrypting groups");
342 goto errout;
343 }
344
345 *size_already_done += data.completed ? size : data.last_written_sector;
346 rc = 0;
347
348errout:
349 close(data.realfd);
350 close(data.cryptofd);
351
352 return rc;
353}
354
355static void log_progress_f2fs(u64 block, bool completed)
356{
357 // Precondition - if completed data = 0 else data != 0
358
359 // Track progress so we can skip logging blocks
360 static u64 last_block = (u64)-1;
361
362 // Need to close existing 'Encrypting from' log?
363 if (completed || (last_block != (u64)-1 && block != last_block + 1)) {
364 SLOGI("Encrypted to block %" PRId64, last_block);
365 last_block = -1;
366 }
367
368 // Need to start new 'Encrypting from' log?
369 if (!completed && (last_block == (u64)-1 || block != last_block + 1)) {
370 SLOGI("Encrypting from block %" PRId64, block);
371 }
372
373 // Update offset
374 if (!completed) {
375 last_block = block;
376 }
377}
378
379static int encrypt_one_block_f2fs(u64 pos, void *data)
380{
381 struct encryptGroupsData *priv_dat = (struct encryptGroupsData *)data;
382
383 priv_dat->blocks_already_done = pos - 1;
384 update_progress(priv_dat, 1);
385
386 off64_t offset = pos * CRYPT_INPLACE_BUFSIZE;
387
388 if (pread64(priv_dat->realfd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
389 SLOGE("Error reading real_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
390 return -1;
391 }
392
393 if (pwrite64(priv_dat->cryptofd, priv_dat->buffer, CRYPT_INPLACE_BUFSIZE, offset) <= 0) {
394 SLOGE("Error writing crypto_blkdev %s for f2fs inplace encrypt", priv_dat->crypto_blkdev);
395 return -1;
396 } else {
397 log_progress_f2fs(pos, false);
398 }
399
400 return 0;
401}
402
403static int cryptfs_enable_inplace_f2fs(char *crypto_blkdev,
404 char *real_blkdev,
405 off64_t size,
406 off64_t *size_already_done,
407 off64_t tot_size,
408 off64_t previously_encrypted_upto)
409{
410 struct encryptGroupsData data;
411 struct f2fs_info *f2fs_info = NULL;
412 int rc = ENABLE_INPLACE_ERR_OTHER;
413 if (previously_encrypted_upto > *size_already_done) {
414 SLOGD("Not fast encrypting since resuming part way through");
415 return ENABLE_INPLACE_ERR_OTHER;
416 }
417 memset(&data, 0, sizeof(data));
418 data.real_blkdev = real_blkdev;
419 data.crypto_blkdev = crypto_blkdev;
420 data.realfd = -1;
421 data.cryptofd = -1;
422 if ( (data.realfd = open64(real_blkdev, O_RDWR|O_CLOEXEC)) < 0) {
423 SLOGE("Error opening real_blkdev %s for f2fs inplace encrypt\n",
424 real_blkdev);
425 goto errout;
426 }
427 if ( (data.cryptofd = open64(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
428 SLOGE("Error opening crypto_blkdev %s for f2fs inplace encrypt. err=%d(%s)\n",
429 crypto_blkdev, errno, strerror(errno));
430 rc = ENABLE_INPLACE_ERR_DEV;
431 goto errout;
432 }
433
434 f2fs_info = generate_f2fs_info(data.realfd);
435 if (!f2fs_info)
436 goto errout;
437
438 data.numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
439 data.tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
440 data.blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
441
442 data.tot_used_blocks = get_num_blocks_used(f2fs_info);
443
444 data.one_pct = data.tot_used_blocks / 100;
445 data.cur_pct = 0;
446 data.time_started = time(NULL);
447 data.remaining_time = -1;
448
449 data.buffer = (char*) malloc(f2fs_info->block_size);
450 if (!data.buffer) {
451 SLOGE("Failed to allocate crypto buffer");
452 goto errout;
453 }
454
455 data.count = 0;
456
457 /* Currently, this either runs to completion, or hits a nonrecoverable error */
458 rc = run_on_used_blocks(data.blocks_already_done, f2fs_info, &encrypt_one_block_f2fs, &data);
459
460 if (rc) {
461 SLOGE("Error in running over f2fs blocks");
462 rc = ENABLE_INPLACE_ERR_OTHER;
463 goto errout;
464 }
465
466 *size_already_done += size;
467 rc = 0;
468
469errout:
470 if (rc)
471 SLOGE("Failed to encrypt f2fs filesystem on %s", real_blkdev);
472
473 log_progress_f2fs(0, true);
474 free(f2fs_info);
475 free(data.buffer);
476 close(data.realfd);
477 close(data.cryptofd);
478
479 return rc;
480}
481
482static int cryptfs_enable_inplace_full(char *crypto_blkdev, char *real_blkdev,
483 off64_t size, off64_t *size_already_done,
484 off64_t tot_size,
485 off64_t previously_encrypted_upto)
486{
487 int realfd, cryptofd;
488 char *buf[CRYPT_INPLACE_BUFSIZE];
489 int rc = ENABLE_INPLACE_ERR_OTHER;
490 off64_t numblocks, i, remainder;
491 off64_t one_pct, cur_pct, new_pct;
492 off64_t blocks_already_done, tot_numblocks;
493
494 if ( (realfd = open(real_blkdev, O_RDONLY|O_CLOEXEC)) < 0) {
495 SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
496 return ENABLE_INPLACE_ERR_OTHER;
497 }
498
499 if ( (cryptofd = open(crypto_blkdev, O_WRONLY|O_CLOEXEC)) < 0) {
500 SLOGE("Error opening crypto_blkdev %s for inplace encrypt. err=%d(%s)\n",
501 crypto_blkdev, errno, strerror(errno));
502 close(realfd);
503 return ENABLE_INPLACE_ERR_DEV;
504 }
505
506 /* This is pretty much a simple loop of reading 4K, and writing 4K.
507 * The size passed in is the number of 512 byte sectors in the filesystem.
508 * So compute the number of whole 4K blocks we should read/write,
509 * and the remainder.
510 */
511 numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
512 remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
513 tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
514 blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
515
516 SLOGE("Encrypting filesystem in place...");
517
518 i = previously_encrypted_upto + 1 - *size_already_done;
519
520 if (lseek64(realfd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
521 SLOGE("Cannot seek to previously encrypted point on %s", real_blkdev);
522 goto errout;
523 }
524
525 if (lseek64(cryptofd, i * CRYPT_SECTOR_SIZE, SEEK_SET) < 0) {
526 SLOGE("Cannot seek to previously encrypted point on %s", crypto_blkdev);
527 goto errout;
528 }
529
530 for (;i < size && i % CRYPT_SECTORS_PER_BUFSIZE != 0; ++i) {
531 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
532 SLOGE("Error reading initial sectors from real_blkdev %s for "
533 "inplace encrypt\n", crypto_blkdev);
534 goto errout;
535 }
536 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
537 SLOGE("Error writing initial sectors to crypto_blkdev %s for "
538 "inplace encrypt\n", crypto_blkdev);
539 goto errout;
540 } else {
541 SLOGI("Encrypted 1 block at %" PRId64, i);
542 }
543 }
544
545 one_pct = tot_numblocks / 100;
546 cur_pct = 0;
547 /* process the majority of the filesystem in blocks */
548 for (i/=CRYPT_SECTORS_PER_BUFSIZE; i<numblocks; i++) {
549 new_pct = (i + blocks_already_done) / one_pct;
550 if (new_pct > cur_pct) {
551 char buf[8];
552
553 cur_pct = new_pct;
554 snprintf(buf, sizeof(buf), "%" PRId64, cur_pct);
555 property_set("vold.encrypt_progress", buf);
556 }
557 if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
558 SLOGE("Error reading real_blkdev %s for inplace encrypt", crypto_blkdev);
559 goto errout;
560 }
561 if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
562 SLOGE("Error writing crypto_blkdev %s for inplace encrypt", crypto_blkdev);
563 goto errout;
564 } else {
565 SLOGD("Encrypted %d block at %" PRId64,
566 CRYPT_SECTORS_PER_BUFSIZE,
567 i * CRYPT_SECTORS_PER_BUFSIZE);
568 }
Paul Crowleyf71ace32016-06-02 11:01:19 -0700569 }
570
571 /* Do any remaining sectors */
572 for (i=0; i<remainder; i++) {
573 if (unix_read(realfd, buf, CRYPT_SECTOR_SIZE) <= 0) {
574 SLOGE("Error reading final sectors from real_blkdev %s for inplace encrypt", crypto_blkdev);
575 goto errout;
576 }
577 if (unix_write(cryptofd, buf, CRYPT_SECTOR_SIZE) <= 0) {
578 SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt", crypto_blkdev);
579 goto errout;
580 } else {
581 SLOGI("Encrypted 1 block at next location");
582 }
583 }
584
585 *size_already_done += size;
586 rc = 0;
587
588errout:
589 close(realfd);
590 close(cryptofd);
591
592 return rc;
593}
594
595/* returns on of the ENABLE_INPLACE_* return codes */
596int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev,
597 off64_t size, off64_t *size_already_done,
598 off64_t tot_size,
599 off64_t previously_encrypted_upto)
600{
601 int rc_ext4, rc_f2fs, rc_full;
602 if (previously_encrypted_upto) {
603 SLOGD("Continuing encryption from %" PRId64, previously_encrypted_upto);
604 }
605
606 if (*size_already_done + size < previously_encrypted_upto) {
607 *size_already_done += size;
608 return 0;
609 }
610
611 /* TODO: identify filesystem type.
612 * As is, cryptfs_enable_inplace_ext4 will fail on an f2fs partition, and
613 * then we will drop down to cryptfs_enable_inplace_f2fs.
614 * */
615 if ((rc_ext4 = cryptfs_enable_inplace_ext4(crypto_blkdev, real_blkdev,
616 size, size_already_done,
617 tot_size, previously_encrypted_upto)) == 0) {
618 return 0;
619 }
620 SLOGD("cryptfs_enable_inplace_ext4()=%d\n", rc_ext4);
621
622 if ((rc_f2fs = cryptfs_enable_inplace_f2fs(crypto_blkdev, real_blkdev,
623 size, size_already_done,
624 tot_size, previously_encrypted_upto)) == 0) {
625 return 0;
626 }
627 SLOGD("cryptfs_enable_inplace_f2fs()=%d\n", rc_f2fs);
628
629 rc_full = cryptfs_enable_inplace_full(crypto_blkdev, real_blkdev,
630 size, size_already_done, tot_size,
631 previously_encrypted_upto);
632 SLOGD("cryptfs_enable_inplace_full()=%d\n", rc_full);
633
634 /* Hack for b/17898962, the following is the symptom... */
635 if (rc_ext4 == ENABLE_INPLACE_ERR_DEV
636 && rc_f2fs == ENABLE_INPLACE_ERR_DEV
637 && rc_full == ENABLE_INPLACE_ERR_DEV) {
638 return ENABLE_INPLACE_ERR_DEV;
639 }
640 return rc_full;
641}