btrfs-progs: handle memory allocation error in cmd_device_stats
[btrfs-progs-unstable/devel.git] / btrfs-convert.c
blobb49775cc00109243e7fc0abf978487117443eedf
1 /*
2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include "kerncompat.h"
21 #include <sys/ioctl.h>
22 #include <sys/mount.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <uuid/uuid.h>
30 #include <linux/limits.h>
31 #include <getopt.h>
33 #include "ctree.h"
34 #include "disk-io.h"
35 #include "volumes.h"
36 #include "transaction.h"
37 #include "crc32c.h"
38 #include "utils.h"
39 #include "task-utils.h"
40 #include <ext2fs/ext2_fs.h>
41 #include <ext2fs/ext2fs.h>
42 #include <ext2fs/ext2_ext_attr.h>
44 #define INO_OFFSET (BTRFS_FIRST_FREE_OBJECTID - EXT2_ROOT_INO)
45 #define CONV_IMAGE_SUBVOL_OBJECTID BTRFS_FIRST_FREE_OBJECTID
47 struct task_ctx {
48 uint32_t max_copy_inodes;
49 uint32_t cur_copy_inodes;
50 struct task_info *info;
53 static void *print_copied_inodes(void *p)
55 struct task_ctx *priv = p;
56 const char work_indicator[] = { '.', 'o', 'O', 'o' };
57 uint32_t count = 0;
59 task_period_start(priv->info, 1000 /* 1s */);
60 while (1) {
61 count++;
62 printf("copy inodes [%c] [%10d/%10d]\r",
63 work_indicator[count % 4], priv->cur_copy_inodes,
64 priv->max_copy_inodes);
65 fflush(stdout);
66 task_period_wait(priv->info);
69 return NULL;
72 static int after_copied_inodes(void *p)
74 printf("\n");
75 fflush(stdout);
77 return 0;
80 struct btrfs_convert_context;
81 struct btrfs_convert_operations {
82 const char *name;
83 int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
84 int (*alloc_block)(struct btrfs_convert_context *cctx, u64 goal,
85 u64 *block_ret);
86 int (*alloc_block_range)(struct btrfs_convert_context *cctx, u64 goal,
87 int num, u64 *block_ret);
88 int (*test_block)(struct btrfs_convert_context *cctx, u64 block);
89 void (*free_block)(struct btrfs_convert_context *cctx, u64 block);
90 void (*free_block_range)(struct btrfs_convert_context *cctx, u64 block,
91 int num);
92 int (*copy_inodes)(struct btrfs_convert_context *cctx,
93 struct btrfs_root *root, int datacsum,
94 int packing, int noxattr, struct task_ctx *p);
95 void (*close_fs)(struct btrfs_convert_context *cctx);
98 struct btrfs_convert_context {
99 u32 blocksize;
100 u32 first_data_block;
101 u32 block_count;
102 u32 inodes_count;
103 u32 free_inodes_count;
104 u64 total_bytes;
105 char *volume_name;
106 const struct btrfs_convert_operations *convert_ops;
108 /* The accurate used space of old filesystem */
109 struct cache_tree used;
111 /* Batched ranges which must be covered by data chunks */
112 struct cache_tree data_chunks;
114 /* Free space which is not covered by data_chunks */
115 struct cache_tree free;
117 void *fs_data;
120 static void init_convert_context(struct btrfs_convert_context *cctx)
122 cache_tree_init(&cctx->used);
123 cache_tree_init(&cctx->data_chunks);
124 cache_tree_init(&cctx->free);
127 static void clean_convert_context(struct btrfs_convert_context *cctx)
129 free_extent_cache_tree(&cctx->used);
130 free_extent_cache_tree(&cctx->data_chunks);
131 free_extent_cache_tree(&cctx->free);
134 static inline int convert_alloc_block(struct btrfs_convert_context *cctx,
135 u64 goal, u64 *ret)
137 return cctx->convert_ops->alloc_block(cctx, goal, ret);
140 static inline int convert_alloc_block_range(struct btrfs_convert_context *cctx,
141 u64 goal, int num, u64 *ret)
143 return cctx->convert_ops->alloc_block_range(cctx, goal, num, ret);
146 static inline int convert_test_block(struct btrfs_convert_context *cctx,
147 u64 block)
149 return cctx->convert_ops->test_block(cctx, block);
152 static inline void convert_free_block(struct btrfs_convert_context *cctx,
153 u64 block)
155 cctx->convert_ops->free_block(cctx, block);
158 static inline void convert_free_block_range(struct btrfs_convert_context *cctx,
159 u64 block, int num)
161 cctx->convert_ops->free_block_range(cctx, block, num);
164 static inline int copy_inodes(struct btrfs_convert_context *cctx,
165 struct btrfs_root *root, int datacsum,
166 int packing, int noxattr, struct task_ctx *p)
168 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
169 noxattr, p);
172 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
174 cctx->convert_ops->close_fs(cctx);
178 * Open Ext2fs in readonly mode, read block allocation bitmap and
179 * inode bitmap into memory.
181 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
183 errcode_t ret;
184 ext2_filsys ext2_fs;
185 ext2_ino_t ino;
186 ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
187 if (ret) {
188 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
189 goto fail;
191 ret = ext2fs_read_inode_bitmap(ext2_fs);
192 if (ret) {
193 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
194 error_message(ret));
195 goto fail;
197 ret = ext2fs_read_block_bitmap(ext2_fs);
198 if (ret) {
199 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
200 error_message(ret));
201 goto fail;
204 * search each block group for a free inode. this set up
205 * uninit block/inode bitmaps appropriately.
207 ino = 1;
208 while (ino <= ext2_fs->super->s_inodes_count) {
209 ext2_ino_t foo;
210 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
211 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
214 if (!(ext2_fs->super->s_feature_incompat &
215 EXT2_FEATURE_INCOMPAT_FILETYPE)) {
216 fprintf(stderr, "filetype feature is missing\n");
217 goto fail;
220 cctx->fs_data = ext2_fs;
221 cctx->blocksize = ext2_fs->blocksize;
222 cctx->block_count = ext2_fs->super->s_blocks_count;
223 cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
224 cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
225 cctx->first_data_block = ext2_fs->super->s_first_data_block;
226 cctx->inodes_count = ext2_fs->super->s_inodes_count;
227 cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
228 return 0;
229 fail:
230 return -1;
233 static void ext2_close_fs(struct btrfs_convert_context *cctx)
235 if (cctx->volume_name) {
236 free(cctx->volume_name);
237 cctx->volume_name = NULL;
239 ext2fs_close(cctx->fs_data);
242 static int ext2_alloc_block(struct btrfs_convert_context *cctx,
243 u64 goal, u64 *block_ret)
245 ext2_filsys fs = cctx->fs_data;
246 blk_t block;
248 if (!ext2fs_new_block(fs, goal, NULL, &block)) {
249 ext2fs_fast_mark_block_bitmap(fs->block_map, block);
250 *block_ret = block;
251 return 0;
253 return -ENOSPC;
256 static int ext2_alloc_block_range(struct btrfs_convert_context *cctx, u64 goal,
257 int num, u64 *block_ret)
259 ext2_filsys fs = cctx->fs_data;
260 blk_t block;
261 ext2fs_block_bitmap bitmap = fs->block_map;
262 blk_t start = ext2fs_get_block_bitmap_start(bitmap);
263 blk_t end = ext2fs_get_block_bitmap_end(bitmap);
265 for (block = max_t(u64, goal, start); block + num < end; block++) {
266 if (ext2fs_fast_test_block_bitmap_range(bitmap, block, num)) {
267 ext2fs_fast_mark_block_bitmap_range(bitmap, block,
268 num);
269 *block_ret = block;
270 return 0;
273 return -ENOSPC;
276 static void ext2_free_block(struct btrfs_convert_context *cctx, u64 block)
278 ext2_filsys fs = cctx->fs_data;
280 BUG_ON(block != (blk_t)block);
281 ext2fs_fast_unmark_block_bitmap(fs->block_map, block);
284 static void ext2_free_block_range(struct btrfs_convert_context *cctx, u64 block, int num)
286 ext2_filsys fs = cctx->fs_data;
288 BUG_ON(block != (blk_t)block);
289 ext2fs_fast_unmark_block_bitmap_range(fs->block_map, block, num);
292 static int cache_free_extents(struct btrfs_root *root,
293 struct btrfs_convert_context *cctx)
296 int i, ret = 0;
297 blk_t block;
298 u64 bytenr;
299 u64 blocksize = cctx->blocksize;
301 block = cctx->first_data_block;
302 for (; block < cctx->block_count; block++) {
303 if (convert_test_block(cctx, block))
304 continue;
305 bytenr = block * blocksize;
306 ret = set_extent_dirty(&root->fs_info->free_space_cache,
307 bytenr, bytenr + blocksize - 1, 0);
308 BUG_ON(ret);
311 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
312 bytenr = btrfs_sb_offset(i);
313 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
314 if (bytenr >= blocksize * cctx->block_count)
315 break;
316 clear_extent_dirty(&root->fs_info->free_space_cache, bytenr,
317 bytenr + BTRFS_STRIPE_LEN - 1, 0);
320 clear_extent_dirty(&root->fs_info->free_space_cache,
321 0, BTRFS_SUPER_INFO_OFFSET - 1, 0);
323 return 0;
326 static int custom_alloc_extent(struct btrfs_root *root, u64 num_bytes,
327 u64 hint_byte, struct btrfs_key *ins,
328 int metadata)
330 u64 start;
331 u64 end;
332 u64 last = hint_byte;
333 int ret;
334 int wrapped = 0;
335 struct btrfs_block_group_cache *cache;
337 while(1) {
338 ret = find_first_extent_bit(&root->fs_info->free_space_cache,
339 last, &start, &end, EXTENT_DIRTY);
340 if (ret) {
341 if (wrapped++ == 0) {
342 last = 0;
343 continue;
344 } else {
345 goto fail;
349 start = max(last, start);
350 last = end + 1;
351 if (last - start < num_bytes)
352 continue;
354 last = start + num_bytes;
355 if (test_range_bit(&root->fs_info->pinned_extents,
356 start, last - 1, EXTENT_DIRTY, 0))
357 continue;
359 cache = btrfs_lookup_block_group(root->fs_info, start);
360 BUG_ON(!cache);
361 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM ||
362 last > cache->key.objectid + cache->key.offset) {
363 last = cache->key.objectid + cache->key.offset;
364 continue;
367 if (metadata) {
368 BUG_ON(num_bytes != root->nodesize);
369 if (check_crossing_stripes(start, num_bytes)) {
370 last = round_down(start + num_bytes,
371 BTRFS_STRIPE_LEN);
372 continue;
375 clear_extent_dirty(&root->fs_info->free_space_cache,
376 start, start + num_bytes - 1, 0);
378 ins->objectid = start;
379 ins->offset = num_bytes;
380 ins->type = BTRFS_EXTENT_ITEM_KEY;
381 return 0;
383 fail:
384 fprintf(stderr, "not enough free space\n");
385 return -ENOSPC;
388 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
390 int i;
391 u64 offset;
393 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
394 offset = btrfs_sb_offset(i);
395 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
397 if (bytenr < offset + BTRFS_STRIPE_LEN &&
398 bytenr + num_bytes > offset)
399 return 1;
401 return 0;
404 static int custom_free_extent(struct btrfs_root *root, u64 bytenr,
405 u64 num_bytes)
407 return intersect_with_sb(bytenr, num_bytes);
410 static struct btrfs_extent_ops extent_ops = {
411 .alloc_extent = custom_alloc_extent,
412 .free_extent = custom_free_extent,
415 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
416 struct btrfs_root *root,
417 const char *name, size_t name_len,
418 u64 dir, u64 objectid,
419 u8 file_type, u64 index_cnt,
420 struct btrfs_inode_item *inode)
422 int ret;
423 u64 inode_size;
424 struct btrfs_key location = {
425 .objectid = objectid,
426 .offset = 0,
427 .type = BTRFS_INODE_ITEM_KEY,
430 ret = btrfs_insert_dir_item(trans, root, name, name_len,
431 dir, &location, file_type, index_cnt);
432 if (ret)
433 return ret;
434 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
435 objectid, dir, index_cnt);
436 if (ret)
437 return ret;
438 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
439 btrfs_set_stack_inode_size(inode, inode_size);
441 return 0;
444 struct dir_iterate_data {
445 struct btrfs_trans_handle *trans;
446 struct btrfs_root *root;
447 struct btrfs_inode_item *inode;
448 u64 objectid;
449 u64 index_cnt;
450 u64 parent;
451 int errcode;
454 static u8 filetype_conversion_table[EXT2_FT_MAX] = {
455 [EXT2_FT_UNKNOWN] = BTRFS_FT_UNKNOWN,
456 [EXT2_FT_REG_FILE] = BTRFS_FT_REG_FILE,
457 [EXT2_FT_DIR] = BTRFS_FT_DIR,
458 [EXT2_FT_CHRDEV] = BTRFS_FT_CHRDEV,
459 [EXT2_FT_BLKDEV] = BTRFS_FT_BLKDEV,
460 [EXT2_FT_FIFO] = BTRFS_FT_FIFO,
461 [EXT2_FT_SOCK] = BTRFS_FT_SOCK,
462 [EXT2_FT_SYMLINK] = BTRFS_FT_SYMLINK,
465 static int dir_iterate_proc(ext2_ino_t dir, int entry,
466 struct ext2_dir_entry *dirent,
467 int offset, int blocksize,
468 char *buf,void *priv_data)
470 int ret;
471 int file_type;
472 u64 objectid;
473 char dotdot[] = "..";
474 struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
475 int name_len;
477 name_len = dirent->name_len & 0xFF;
479 objectid = dirent->inode + INO_OFFSET;
480 if (!strncmp(dirent->name, dotdot, name_len)) {
481 if (name_len == 2) {
482 BUG_ON(idata->parent != 0);
483 idata->parent = objectid;
485 return 0;
487 if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
488 return 0;
490 file_type = dirent->name_len >> 8;
491 BUG_ON(file_type > EXT2_FT_SYMLINK);
493 ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
494 name_len, idata->objectid, objectid,
495 filetype_conversion_table[file_type],
496 idata->index_cnt, idata->inode);
497 if (ret < 0) {
498 idata->errcode = ret;
499 return BLOCK_ABORT;
502 idata->index_cnt++;
503 return 0;
506 static int create_dir_entries(struct btrfs_trans_handle *trans,
507 struct btrfs_root *root, u64 objectid,
508 struct btrfs_inode_item *btrfs_inode,
509 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
511 int ret;
512 errcode_t err;
513 struct dir_iterate_data data = {
514 .trans = trans,
515 .root = root,
516 .inode = btrfs_inode,
517 .objectid = objectid,
518 .index_cnt = 2,
519 .parent = 0,
520 .errcode = 0,
523 err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
524 dir_iterate_proc, &data);
525 if (err)
526 goto error;
527 ret = data.errcode;
528 if (ret == 0 && data.parent == objectid) {
529 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
530 objectid, objectid, 0);
532 return ret;
533 error:
534 fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
535 return -1;
538 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
539 u32 num_bytes, char *buffer)
541 int ret;
542 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
544 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
545 if (ret != num_bytes)
546 goto fail;
547 ret = 0;
548 fail:
549 if (ret > 0)
550 ret = -1;
551 return ret;
554 static int csum_disk_extent(struct btrfs_trans_handle *trans,
555 struct btrfs_root *root,
556 u64 disk_bytenr, u64 num_bytes)
558 u32 blocksize = root->sectorsize;
559 u64 offset;
560 char *buffer;
561 int ret = 0;
563 buffer = malloc(blocksize);
564 if (!buffer)
565 return -ENOMEM;
566 for (offset = 0; offset < num_bytes; offset += blocksize) {
567 ret = read_disk_extent(root, disk_bytenr + offset,
568 blocksize, buffer);
569 if (ret)
570 break;
571 ret = btrfs_csum_file_block(trans,
572 root->fs_info->csum_root,
573 disk_bytenr + num_bytes,
574 disk_bytenr + offset,
575 buffer, blocksize);
576 if (ret)
577 break;
579 free(buffer);
580 return ret;
583 struct blk_iterate_data {
584 struct btrfs_trans_handle *trans;
585 struct btrfs_root *root;
586 struct btrfs_inode_item *inode;
587 u64 objectid;
588 u64 first_block;
589 u64 disk_block;
590 u64 num_blocks;
591 u64 boundary;
592 int checksum;
593 int errcode;
596 static void init_blk_iterate_data(struct blk_iterate_data *data,
597 struct btrfs_trans_handle *trans,
598 struct btrfs_root *root,
599 struct btrfs_inode_item *inode,
600 u64 objectid, int checksum)
602 data->trans = trans;
603 data->root = root;
604 data->inode = inode;
605 data->objectid = objectid;
606 data->first_block = 0;
607 data->disk_block = 0;
608 data->num_blocks = 0;
609 data->boundary = (u64)-1;
610 data->checksum = checksum;
611 data->errcode = 0;
614 static int record_file_blocks(struct blk_iterate_data *data,
615 u64 file_block, u64 disk_block, u64 num_blocks)
617 int ret;
618 struct btrfs_root *root = data->root;
619 u64 file_pos = file_block * root->sectorsize;
620 u64 disk_bytenr = disk_block * root->sectorsize;
621 u64 num_bytes = num_blocks * root->sectorsize;
622 ret = btrfs_record_file_extent(data->trans, data->root,
623 data->objectid, data->inode, file_pos,
624 disk_bytenr, num_bytes);
626 if (ret || !data->checksum || disk_bytenr == 0)
627 return ret;
629 return csum_disk_extent(data->trans, data->root, disk_bytenr,
630 num_bytes);
633 static int block_iterate_proc(u64 disk_block, u64 file_block,
634 struct blk_iterate_data *idata)
636 int ret = 0;
637 int sb_region;
638 int do_barrier;
639 struct btrfs_root *root = idata->root;
640 struct btrfs_block_group_cache *cache;
641 u64 bytenr = disk_block * root->sectorsize;
643 sb_region = intersect_with_sb(bytenr, root->sectorsize);
644 do_barrier = sb_region || disk_block >= idata->boundary;
645 if ((idata->num_blocks > 0 && do_barrier) ||
646 (file_block > idata->first_block + idata->num_blocks) ||
647 (disk_block != idata->disk_block + idata->num_blocks)) {
648 if (idata->num_blocks > 0) {
649 ret = record_file_blocks(idata, idata->first_block,
650 idata->disk_block,
651 idata->num_blocks);
652 if (ret)
653 goto fail;
654 idata->first_block += idata->num_blocks;
655 idata->num_blocks = 0;
657 if (file_block > idata->first_block) {
658 ret = record_file_blocks(idata, idata->first_block,
659 0, file_block - idata->first_block);
660 if (ret)
661 goto fail;
664 if (sb_region) {
665 bytenr += BTRFS_STRIPE_LEN - 1;
666 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
667 } else {
668 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
669 BUG_ON(!cache);
670 bytenr = cache->key.objectid + cache->key.offset;
673 idata->first_block = file_block;
674 idata->disk_block = disk_block;
675 idata->boundary = bytenr / root->sectorsize;
677 idata->num_blocks++;
678 fail:
679 return ret;
682 static int __block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
683 e2_blkcnt_t blockcnt, blk_t ref_block,
684 int ref_offset, void *priv_data)
686 int ret;
687 struct blk_iterate_data *idata;
688 idata = (struct blk_iterate_data *)priv_data;
689 ret = block_iterate_proc(*blocknr, blockcnt, idata);
690 if (ret) {
691 idata->errcode = ret;
692 return BLOCK_ABORT;
694 return 0;
698 * traverse file's data blocks, record these data blocks as file extents.
700 static int create_file_extents(struct btrfs_trans_handle *trans,
701 struct btrfs_root *root, u64 objectid,
702 struct btrfs_inode_item *btrfs_inode,
703 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
704 int datacsum, int packing)
706 int ret;
707 char *buffer = NULL;
708 errcode_t err;
709 u32 last_block;
710 u32 sectorsize = root->sectorsize;
711 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
712 struct blk_iterate_data data;
714 init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
715 datacsum);
717 err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
718 NULL, __block_iterate_proc, &data);
719 if (err)
720 goto error;
721 ret = data.errcode;
722 if (ret)
723 goto fail;
724 if (packing && data.first_block == 0 && data.num_blocks > 0 &&
725 inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
726 u64 num_bytes = data.num_blocks * sectorsize;
727 u64 disk_bytenr = data.disk_block * sectorsize;
728 u64 nbytes;
730 buffer = malloc(num_bytes);
731 if (!buffer)
732 return -ENOMEM;
733 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
734 if (ret)
735 goto fail;
736 if (num_bytes > inode_size)
737 num_bytes = inode_size;
738 ret = btrfs_insert_inline_extent(trans, root, objectid,
739 0, buffer, num_bytes);
740 if (ret)
741 goto fail;
742 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
743 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
744 } else if (data.num_blocks > 0) {
745 ret = record_file_blocks(&data, data.first_block,
746 data.disk_block, data.num_blocks);
747 if (ret)
748 goto fail;
750 data.first_block += data.num_blocks;
751 last_block = (inode_size + sectorsize - 1) / sectorsize;
752 if (last_block > data.first_block) {
753 ret = record_file_blocks(&data, data.first_block, 0,
754 last_block - data.first_block);
756 fail:
757 free(buffer);
758 return ret;
759 error:
760 fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
761 return -1;
764 static int create_symbol_link(struct btrfs_trans_handle *trans,
765 struct btrfs_root *root, u64 objectid,
766 struct btrfs_inode_item *btrfs_inode,
767 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
768 struct ext2_inode *ext2_inode)
770 int ret;
771 char *pathname;
772 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
773 if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
774 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
775 ret = create_file_extents(trans, root, objectid, btrfs_inode,
776 ext2_fs, ext2_ino, 1, 1);
777 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
778 return ret;
781 pathname = (char *)&(ext2_inode->i_block[0]);
782 BUG_ON(pathname[inode_size] != 0);
783 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
784 pathname, inode_size + 1);
785 btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
786 return ret;
790 * Following xattr/acl related codes are based on codes in
791 * fs/ext3/xattr.c and fs/ext3/acl.c
793 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
794 #define EXT2_XATTR_BFIRST(ptr) \
795 ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
796 #define EXT2_XATTR_IHDR(inode) \
797 ((struct ext2_ext_attr_header *) ((void *)(inode) + \
798 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
799 #define EXT2_XATTR_IFIRST(inode) \
800 ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
801 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
803 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
804 const void *end)
806 struct ext2_ext_attr_entry *next;
808 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
809 next = EXT2_EXT_ATTR_NEXT(entry);
810 if ((void *)next >= end)
811 return -EIO;
812 entry = next;
814 return 0;
817 static int ext2_xattr_check_block(const char *buf, size_t size)
819 int error;
820 struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
822 if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
823 header->h_blocks != 1)
824 return -EIO;
825 error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
826 return error;
829 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
830 size_t size)
832 size_t value_size = entry->e_value_size;
834 if (entry->e_value_block != 0 || value_size > size ||
835 entry->e_value_offs + value_size > size)
836 return -EIO;
837 return 0;
840 #define EXT2_ACL_VERSION 0x0001
842 /* 23.2.5 acl_tag_t values */
844 #define ACL_UNDEFINED_TAG (0x00)
845 #define ACL_USER_OBJ (0x01)
846 #define ACL_USER (0x02)
847 #define ACL_GROUP_OBJ (0x04)
848 #define ACL_GROUP (0x08)
849 #define ACL_MASK (0x10)
850 #define ACL_OTHER (0x20)
852 /* 23.2.7 ACL qualifier constants */
854 #define ACL_UNDEFINED_ID ((id_t)-1)
856 typedef struct {
857 __le16 e_tag;
858 __le16 e_perm;
859 __le32 e_id;
860 } ext2_acl_entry;
862 typedef struct {
863 __le16 e_tag;
864 __le16 e_perm;
865 } ext2_acl_entry_short;
867 typedef struct {
868 __le32 a_version;
869 } ext2_acl_header;
871 static inline int ext2_acl_count(size_t size)
873 ssize_t s;
874 size -= sizeof(ext2_acl_header);
875 s = size - 4 * sizeof(ext2_acl_entry_short);
876 if (s < 0) {
877 if (size % sizeof(ext2_acl_entry_short))
878 return -1;
879 return size / sizeof(ext2_acl_entry_short);
880 } else {
881 if (s % sizeof(ext2_acl_entry))
882 return -1;
883 return s / sizeof(ext2_acl_entry) + 4;
887 #define ACL_EA_VERSION 0x0002
889 typedef struct {
890 __le16 e_tag;
891 __le16 e_perm;
892 __le32 e_id;
893 } acl_ea_entry;
895 typedef struct {
896 __le32 a_version;
897 acl_ea_entry a_entries[0];
898 } acl_ea_header;
900 static inline size_t acl_ea_size(int count)
902 return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
905 static int ext2_acl_to_xattr(void *dst, const void *src,
906 size_t dst_size, size_t src_size)
908 int i, count;
909 const void *end = src + src_size;
910 acl_ea_header *ext_acl = (acl_ea_header *)dst;
911 acl_ea_entry *dst_entry = ext_acl->a_entries;
912 ext2_acl_entry *src_entry;
914 if (src_size < sizeof(ext2_acl_header))
915 goto fail;
916 if (((ext2_acl_header *)src)->a_version !=
917 cpu_to_le32(EXT2_ACL_VERSION))
918 goto fail;
919 src += sizeof(ext2_acl_header);
920 count = ext2_acl_count(src_size);
921 if (count <= 0)
922 goto fail;
924 BUG_ON(dst_size < acl_ea_size(count));
925 ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
926 for (i = 0; i < count; i++, dst_entry++) {
927 src_entry = (ext2_acl_entry *)src;
928 if (src + sizeof(ext2_acl_entry_short) > end)
929 goto fail;
930 dst_entry->e_tag = src_entry->e_tag;
931 dst_entry->e_perm = src_entry->e_perm;
932 switch (le16_to_cpu(src_entry->e_tag)) {
933 case ACL_USER_OBJ:
934 case ACL_GROUP_OBJ:
935 case ACL_MASK:
936 case ACL_OTHER:
937 src += sizeof(ext2_acl_entry_short);
938 dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
939 break;
940 case ACL_USER:
941 case ACL_GROUP:
942 src += sizeof(ext2_acl_entry);
943 if (src > end)
944 goto fail;
945 dst_entry->e_id = src_entry->e_id;
946 break;
947 default:
948 goto fail;
951 if (src != end)
952 goto fail;
953 return 0;
954 fail:
955 return -EINVAL;
958 static char *xattr_prefix_table[] = {
959 [1] = "user.",
960 [2] = "system.posix_acl_access",
961 [3] = "system.posix_acl_default",
962 [4] = "trusted.",
963 [6] = "security.",
966 static int copy_single_xattr(struct btrfs_trans_handle *trans,
967 struct btrfs_root *root, u64 objectid,
968 struct ext2_ext_attr_entry *entry,
969 const void *data, u32 datalen)
971 int ret = 0;
972 int name_len;
973 int name_index;
974 void *databuf = NULL;
975 char namebuf[XATTR_NAME_MAX + 1];
977 name_index = entry->e_name_index;
978 if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
979 xattr_prefix_table[name_index] == NULL)
980 return -EOPNOTSUPP;
981 name_len = strlen(xattr_prefix_table[name_index]) +
982 entry->e_name_len;
983 if (name_len >= sizeof(namebuf))
984 return -ERANGE;
986 if (name_index == 2 || name_index == 3) {
987 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
988 databuf = malloc(bufsize);
989 if (!databuf)
990 return -ENOMEM;
991 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
992 if (ret)
993 goto out;
994 data = databuf;
995 datalen = bufsize;
997 strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
998 strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
999 if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
1000 sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
1001 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
1002 objectid - INO_OFFSET, name_len, namebuf);
1003 goto out;
1005 ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
1006 data, datalen, objectid);
1007 out:
1008 free(databuf);
1009 return ret;
1012 static int copy_extended_attrs(struct btrfs_trans_handle *trans,
1013 struct btrfs_root *root, u64 objectid,
1014 struct btrfs_inode_item *btrfs_inode,
1015 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
1017 int ret = 0;
1018 int inline_ea = 0;
1019 errcode_t err;
1020 u32 datalen;
1021 u32 block_size = ext2_fs->blocksize;
1022 u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
1023 struct ext2_inode_large *ext2_inode;
1024 struct ext2_ext_attr_entry *entry;
1025 void *data;
1026 char *buffer = NULL;
1027 char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
1029 if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
1030 ext2_inode = (struct ext2_inode_large *)inode_buf;
1031 } else {
1032 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
1033 if (!ext2_inode)
1034 return -ENOMEM;
1036 err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
1037 inode_size);
1038 if (err) {
1039 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
1040 error_message(err));
1041 ret = -1;
1042 goto out;
1045 if (ext2_ino > ext2_fs->super->s_first_ino &&
1046 inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
1047 if (EXT2_GOOD_OLD_INODE_SIZE +
1048 ext2_inode->i_extra_isize > inode_size) {
1049 ret = -EIO;
1050 goto out;
1052 if (ext2_inode->i_extra_isize != 0 &&
1053 EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
1054 EXT2_EXT_ATTR_MAGIC) {
1055 inline_ea = 1;
1058 if (inline_ea) {
1059 int total;
1060 void *end = (void *)ext2_inode + inode_size;
1061 entry = EXT2_XATTR_IFIRST(ext2_inode);
1062 total = end - (void *)entry;
1063 ret = ext2_xattr_check_names(entry, end);
1064 if (ret)
1065 goto out;
1066 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1067 ret = ext2_xattr_check_entry(entry, total);
1068 if (ret)
1069 goto out;
1070 data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
1071 entry->e_value_offs;
1072 datalen = entry->e_value_size;
1073 ret = copy_single_xattr(trans, root, objectid,
1074 entry, data, datalen);
1075 if (ret)
1076 goto out;
1077 entry = EXT2_EXT_ATTR_NEXT(entry);
1081 if (ext2_inode->i_file_acl == 0)
1082 goto out;
1084 buffer = malloc(block_size);
1085 if (!buffer) {
1086 ret = -ENOMEM;
1087 goto out;
1089 err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
1090 if (err) {
1091 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
1092 error_message(err));
1093 ret = -1;
1094 goto out;
1096 ret = ext2_xattr_check_block(buffer, block_size);
1097 if (ret)
1098 goto out;
1100 entry = EXT2_XATTR_BFIRST(buffer);
1101 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1102 ret = ext2_xattr_check_entry(entry, block_size);
1103 if (ret)
1104 goto out;
1105 data = buffer + entry->e_value_offs;
1106 datalen = entry->e_value_size;
1107 ret = copy_single_xattr(trans, root, objectid,
1108 entry, data, datalen);
1109 if (ret)
1110 goto out;
1111 entry = EXT2_EXT_ATTR_NEXT(entry);
1113 out:
1114 free(buffer);
1115 if ((void *)ext2_inode != inode_buf)
1116 free(ext2_inode);
1117 return ret;
1119 #define MINORBITS 20
1120 #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
1122 static inline dev_t old_decode_dev(u16 val)
1124 return MKDEV((val >> 8) & 255, val & 255);
1127 static inline dev_t new_decode_dev(u32 dev)
1129 unsigned major = (dev & 0xfff00) >> 8;
1130 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
1131 return MKDEV(major, minor);
1134 static int copy_inode_item(struct btrfs_inode_item *dst,
1135 struct ext2_inode *src, u32 blocksize)
1137 btrfs_set_stack_inode_generation(dst, 1);
1138 btrfs_set_stack_inode_sequence(dst, 0);
1139 btrfs_set_stack_inode_transid(dst, 1);
1140 btrfs_set_stack_inode_size(dst, src->i_size);
1141 btrfs_set_stack_inode_nbytes(dst, 0);
1142 btrfs_set_stack_inode_block_group(dst, 0);
1143 btrfs_set_stack_inode_nlink(dst, src->i_links_count);
1144 btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
1145 btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
1146 btrfs_set_stack_inode_mode(dst, src->i_mode);
1147 btrfs_set_stack_inode_rdev(dst, 0);
1148 btrfs_set_stack_inode_flags(dst, 0);
1149 btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
1150 btrfs_set_stack_timespec_nsec(&dst->atime, 0);
1151 btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
1152 btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
1153 btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
1154 btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
1155 btrfs_set_stack_timespec_sec(&dst->otime, 0);
1156 btrfs_set_stack_timespec_nsec(&dst->otime, 0);
1158 if (S_ISDIR(src->i_mode)) {
1159 btrfs_set_stack_inode_size(dst, 0);
1160 btrfs_set_stack_inode_nlink(dst, 1);
1162 if (S_ISREG(src->i_mode)) {
1163 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
1164 (u64)src->i_size);
1166 if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
1167 !S_ISLNK(src->i_mode)) {
1168 if (src->i_block[0]) {
1169 btrfs_set_stack_inode_rdev(dst,
1170 old_decode_dev(src->i_block[0]));
1171 } else {
1172 btrfs_set_stack_inode_rdev(dst,
1173 new_decode_dev(src->i_block[1]));
1176 memset(&dst->reserved, 0, sizeof(dst->reserved));
1178 return 0;
1182 * copy a single inode. do all the required works, such as cloning
1183 * inode item, creating file extents and creating directory entries.
1185 static int copy_single_inode(struct btrfs_trans_handle *trans,
1186 struct btrfs_root *root, u64 objectid,
1187 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1188 struct ext2_inode *ext2_inode,
1189 int datacsum, int packing, int noxattr)
1191 int ret;
1192 struct btrfs_inode_item btrfs_inode;
1194 if (ext2_inode->i_links_count == 0)
1195 return 0;
1197 copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
1198 if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
1199 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
1200 BTRFS_INODE_NODATASUM;
1201 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
1204 switch (ext2_inode->i_mode & S_IFMT) {
1205 case S_IFREG:
1206 ret = create_file_extents(trans, root, objectid, &btrfs_inode,
1207 ext2_fs, ext2_ino, datacsum, packing);
1208 break;
1209 case S_IFDIR:
1210 ret = create_dir_entries(trans, root, objectid, &btrfs_inode,
1211 ext2_fs, ext2_ino);
1212 break;
1213 case S_IFLNK:
1214 ret = create_symbol_link(trans, root, objectid, &btrfs_inode,
1215 ext2_fs, ext2_ino, ext2_inode);
1216 break;
1217 default:
1218 ret = 0;
1219 break;
1221 if (ret)
1222 return ret;
1224 if (!noxattr) {
1225 ret = copy_extended_attrs(trans, root, objectid, &btrfs_inode,
1226 ext2_fs, ext2_ino);
1227 if (ret)
1228 return ret;
1230 return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1233 static int copy_disk_extent(struct btrfs_root *root, u64 dst_bytenr,
1234 u64 src_bytenr, u32 num_bytes)
1236 int ret;
1237 char *buffer;
1238 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
1240 buffer = malloc(num_bytes);
1241 if (!buffer)
1242 return -ENOMEM;
1243 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, src_bytenr);
1244 if (ret != num_bytes)
1245 goto fail;
1246 ret = pwrite(fs_devs->latest_bdev, buffer, num_bytes, dst_bytenr);
1247 if (ret != num_bytes)
1248 goto fail;
1249 ret = 0;
1250 fail:
1251 free(buffer);
1252 if (ret > 0)
1253 ret = -1;
1254 return ret;
1257 * scan ext2's inode bitmap and copy all used inodes.
1259 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
1260 struct btrfs_root *root,
1261 int datacsum, int packing, int noxattr, struct task_ctx *p)
1263 ext2_filsys ext2_fs = cctx->fs_data;
1264 int ret;
1265 errcode_t err;
1266 ext2_inode_scan ext2_scan;
1267 struct ext2_inode ext2_inode;
1268 ext2_ino_t ext2_ino;
1269 u64 objectid;
1270 struct btrfs_trans_handle *trans;
1272 trans = btrfs_start_transaction(root, 1);
1273 if (!trans)
1274 return -ENOMEM;
1275 err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
1276 if (err) {
1277 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
1278 return -1;
1280 while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
1281 &ext2_inode))) {
1282 /* no more inodes */
1283 if (ext2_ino == 0)
1284 break;
1285 /* skip special inode in ext2fs */
1286 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
1287 ext2_ino != EXT2_ROOT_INO)
1288 continue;
1289 objectid = ext2_ino + INO_OFFSET;
1290 ret = copy_single_inode(trans, root,
1291 objectid, ext2_fs, ext2_ino,
1292 &ext2_inode, datacsum, packing,
1293 noxattr);
1294 p->cur_copy_inodes++;
1295 if (ret)
1296 return ret;
1297 if (trans->blocks_used >= 4096) {
1298 ret = btrfs_commit_transaction(trans, root);
1299 BUG_ON(ret);
1300 trans = btrfs_start_transaction(root, 1);
1301 BUG_ON(!trans);
1304 if (err) {
1305 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
1306 return -1;
1308 ret = btrfs_commit_transaction(trans, root);
1309 BUG_ON(ret);
1310 ext2fs_close_inode_scan(ext2_scan);
1312 return ret;
1315 static int ext2_test_block(struct btrfs_convert_context *cctx, u64 block)
1317 ext2_filsys ext2_fs = cctx->fs_data;
1319 BUG_ON(block != (u32)block);
1320 return ext2fs_fast_test_block_bitmap(ext2_fs->block_map, block);
1324 * Construct a range of ext2fs image file.
1325 * scan block allocation bitmap, find all blocks used by the ext2fs
1326 * in this range and create file extents that point to these blocks.
1328 * Note: Before calling the function, no file extent points to blocks
1329 * in this range
1331 static int create_image_file_range(struct btrfs_trans_handle *trans,
1332 struct btrfs_root *root, u64 objectid,
1333 struct btrfs_inode_item *inode,
1334 u64 start_byte, u64 end_byte,
1335 struct btrfs_convert_context *cctx, int datacsum)
1337 u32 blocksize = cctx->blocksize;
1338 u32 block = start_byte / blocksize;
1339 u32 last_block = (end_byte + blocksize - 1) / blocksize;
1340 int ret = 0;
1341 struct blk_iterate_data data;
1343 init_blk_iterate_data(&data, trans, root, inode, objectid, datacsum);
1344 data.first_block = block;
1346 for (; start_byte < end_byte; block++, start_byte += blocksize) {
1347 if (!convert_test_block(cctx, block))
1348 continue;
1349 ret = block_iterate_proc(block, block, &data);
1350 if (ret < 0)
1351 goto fail;
1353 if (data.num_blocks > 0) {
1354 ret = record_file_blocks(&data, data.first_block,
1355 data.disk_block, data.num_blocks);
1356 if (ret)
1357 goto fail;
1358 data.first_block += data.num_blocks;
1360 if (last_block > data.first_block) {
1361 ret = record_file_blocks(&data, data.first_block, 0,
1362 last_block - data.first_block);
1363 if (ret)
1364 goto fail;
1366 fail:
1367 return ret;
1370 * Create the fs image file.
1372 static int create_image(struct btrfs_convert_context *cctx,
1373 struct btrfs_root *root, const char *name, int datacsum)
1375 int ret;
1376 struct btrfs_key key;
1377 struct btrfs_key location;
1378 struct btrfs_path path;
1379 struct btrfs_inode_item btrfs_inode;
1380 struct btrfs_inode_item *inode_item;
1381 struct extent_buffer *leaf;
1382 struct btrfs_fs_info *fs_info = root->fs_info;
1383 struct btrfs_root *extent_root = fs_info->extent_root;
1384 struct btrfs_trans_handle *trans;
1385 struct btrfs_extent_item *ei;
1386 struct btrfs_extent_inline_ref *iref;
1387 struct btrfs_extent_data_ref *dref;
1388 u64 bytenr;
1389 u64 num_bytes;
1390 u64 objectid;
1391 u64 last_byte;
1392 u64 first_free;
1393 u64 total_bytes;
1394 u64 flags = BTRFS_INODE_READONLY;
1395 u32 sectorsize = root->sectorsize;
1397 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
1398 first_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;
1399 first_free &= ~((u64)sectorsize - 1);
1400 if (!datacsum)
1401 flags |= BTRFS_INODE_NODATASUM;
1403 memset(&btrfs_inode, 0, sizeof(btrfs_inode));
1404 btrfs_set_stack_inode_generation(&btrfs_inode, 1);
1405 btrfs_set_stack_inode_size(&btrfs_inode, total_bytes);
1406 btrfs_set_stack_inode_nlink(&btrfs_inode, 1);
1407 btrfs_set_stack_inode_nbytes(&btrfs_inode, 0);
1408 btrfs_set_stack_inode_mode(&btrfs_inode, S_IFREG | 0400);
1409 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
1410 btrfs_init_path(&path);
1411 trans = btrfs_start_transaction(root, 1);
1412 BUG_ON(!trans);
1414 objectid = btrfs_root_dirid(&root->root_item);
1415 ret = btrfs_find_free_objectid(trans, root, objectid, &objectid);
1416 if (ret)
1417 goto fail;
1420 * copy blocks covered by extent #0 to new positions. extent #0 is
1421 * special, we can't rely on relocate_extents_range to relocate it.
1423 for (last_byte = 0; last_byte < first_free; last_byte += sectorsize) {
1424 ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
1425 if (ret)
1426 goto fail;
1427 ret = copy_disk_extent(root, key.objectid, last_byte,
1428 sectorsize);
1429 if (ret)
1430 goto fail;
1431 ret = btrfs_record_file_extent(trans, root, objectid,
1432 &btrfs_inode, last_byte,
1433 key.objectid, sectorsize);
1434 if (ret)
1435 goto fail;
1436 if (datacsum) {
1437 ret = csum_disk_extent(trans, root, key.objectid,
1438 sectorsize);
1439 if (ret)
1440 goto fail;
1444 while(1) {
1445 key.objectid = last_byte;
1446 key.offset = 0;
1447 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1448 ret = btrfs_search_slot(trans, fs_info->extent_root,
1449 &key, &path, 0, 0);
1450 if (ret < 0)
1451 goto fail;
1452 next:
1453 leaf = path.nodes[0];
1454 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1455 ret = btrfs_next_leaf(extent_root, &path);
1456 if (ret < 0)
1457 goto fail;
1458 if (ret > 0)
1459 break;
1460 leaf = path.nodes[0];
1462 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1463 if (last_byte > key.objectid ||
1464 key.type != BTRFS_EXTENT_ITEM_KEY) {
1465 path.slots[0]++;
1466 goto next;
1469 bytenr = key.objectid;
1470 num_bytes = key.offset;
1471 ei = btrfs_item_ptr(leaf, path.slots[0],
1472 struct btrfs_extent_item);
1473 if (!(btrfs_extent_flags(leaf, ei) & BTRFS_EXTENT_FLAG_DATA)) {
1474 path.slots[0]++;
1475 goto next;
1478 BUG_ON(btrfs_item_size_nr(leaf, path.slots[0]) != sizeof(*ei) +
1479 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY));
1481 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
1482 key.type = btrfs_extent_inline_ref_type(leaf, iref);
1483 BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
1484 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1485 if (btrfs_extent_data_ref_root(leaf, dref) !=
1486 BTRFS_FS_TREE_OBJECTID) {
1487 path.slots[0]++;
1488 goto next;
1491 if (bytenr > last_byte) {
1492 ret = create_image_file_range(trans, root, objectid,
1493 &btrfs_inode, last_byte,
1494 bytenr, cctx,
1495 datacsum);
1496 if (ret)
1497 goto fail;
1499 ret = btrfs_record_file_extent(trans, root, objectid,
1500 &btrfs_inode, bytenr, bytenr,
1501 num_bytes);
1502 if (ret)
1503 goto fail;
1504 last_byte = bytenr + num_bytes;
1505 btrfs_release_path(&path);
1507 if (trans->blocks_used >= 4096) {
1508 ret = btrfs_commit_transaction(trans, root);
1509 BUG_ON(ret);
1510 trans = btrfs_start_transaction(root, 1);
1511 BUG_ON(!trans);
1514 btrfs_release_path(&path);
1515 if (total_bytes > last_byte) {
1516 ret = create_image_file_range(trans, root, objectid,
1517 &btrfs_inode, last_byte,
1518 total_bytes, cctx,
1519 datacsum);
1520 if (ret)
1521 goto fail;
1524 ret = btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1525 if (ret)
1526 goto fail;
1528 location.objectid = objectid;
1529 location.offset = 0;
1530 btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
1531 ret = btrfs_insert_dir_item(trans, root, name, strlen(name),
1532 btrfs_root_dirid(&root->root_item),
1533 &location, BTRFS_FT_REG_FILE, objectid);
1534 if (ret)
1535 goto fail;
1536 ret = btrfs_insert_inode_ref(trans, root, name, strlen(name),
1537 objectid,
1538 btrfs_root_dirid(&root->root_item),
1539 objectid);
1540 if (ret)
1541 goto fail;
1542 location.objectid = btrfs_root_dirid(&root->root_item);
1543 location.offset = 0;
1544 btrfs_set_key_type(&location, BTRFS_INODE_ITEM_KEY);
1545 ret = btrfs_lookup_inode(trans, root, &path, &location, 1);
1546 if (ret)
1547 goto fail;
1548 leaf = path.nodes[0];
1549 inode_item = btrfs_item_ptr(leaf, path.slots[0],
1550 struct btrfs_inode_item);
1551 btrfs_set_inode_size(leaf, inode_item, strlen(name) * 2 +
1552 btrfs_inode_size(leaf, inode_item));
1553 btrfs_mark_buffer_dirty(leaf);
1554 btrfs_release_path(&path);
1555 ret = btrfs_commit_transaction(trans, root);
1556 BUG_ON(ret);
1557 fail:
1558 btrfs_release_path(&path);
1559 return ret;
1562 static struct btrfs_root * link_subvol(struct btrfs_root *root,
1563 const char *base, u64 root_objectid)
1565 struct btrfs_trans_handle *trans;
1566 struct btrfs_fs_info *fs_info = root->fs_info;
1567 struct btrfs_root *tree_root = fs_info->tree_root;
1568 struct btrfs_root *new_root = NULL;
1569 struct btrfs_path *path;
1570 struct btrfs_inode_item *inode_item;
1571 struct extent_buffer *leaf;
1572 struct btrfs_key key;
1573 u64 dirid = btrfs_root_dirid(&root->root_item);
1574 u64 index = 2;
1575 char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1576 int len;
1577 int i;
1578 int ret;
1580 len = strlen(base);
1581 if (len == 0 || len > BTRFS_NAME_LEN)
1582 return NULL;
1584 path = btrfs_alloc_path();
1585 BUG_ON(!path);
1587 key.objectid = dirid;
1588 key.type = BTRFS_DIR_INDEX_KEY;
1589 key.offset = (u64)-1;
1591 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1592 BUG_ON(ret <= 0);
1594 if (path->slots[0] > 0) {
1595 path->slots[0]--;
1596 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1597 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1598 index = key.offset + 1;
1600 btrfs_release_path(path);
1602 trans = btrfs_start_transaction(root, 1);
1603 BUG_ON(!trans);
1605 key.objectid = dirid;
1606 key.offset = 0;
1607 key.type = BTRFS_INODE_ITEM_KEY;
1609 ret = btrfs_lookup_inode(trans, root, path, &key, 1);
1610 BUG_ON(ret);
1611 leaf = path->nodes[0];
1612 inode_item = btrfs_item_ptr(leaf, path->slots[0],
1613 struct btrfs_inode_item);
1615 key.objectid = root_objectid;
1616 key.offset = (u64)-1;
1617 key.type = BTRFS_ROOT_ITEM_KEY;
1619 memcpy(buf, base, len);
1620 for (i = 0; i < 1024; i++) {
1621 ret = btrfs_insert_dir_item(trans, root, buf, len,
1622 dirid, &key, BTRFS_FT_DIR, index);
1623 if (ret != -EEXIST)
1624 break;
1625 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1626 if (len < 1 || len > BTRFS_NAME_LEN) {
1627 ret = -EINVAL;
1628 break;
1631 if (ret)
1632 goto fail;
1634 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1635 btrfs_inode_size(leaf, inode_item));
1636 btrfs_mark_buffer_dirty(leaf);
1637 btrfs_release_path(path);
1639 /* add the backref first */
1640 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1641 BTRFS_ROOT_BACKREF_KEY,
1642 root->root_key.objectid,
1643 dirid, index, buf, len);
1644 BUG_ON(ret);
1646 /* now add the forward ref */
1647 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1648 BTRFS_ROOT_REF_KEY, root_objectid,
1649 dirid, index, buf, len);
1651 ret = btrfs_commit_transaction(trans, root);
1652 BUG_ON(ret);
1654 new_root = btrfs_read_fs_root(fs_info, &key);
1655 if (IS_ERR(new_root))
1656 new_root = NULL;
1657 fail:
1658 btrfs_free_path(path);
1659 return new_root;
1662 static int create_chunk_mapping(struct btrfs_trans_handle *trans,
1663 struct btrfs_root *root)
1665 struct btrfs_fs_info *info = root->fs_info;
1666 struct btrfs_root *chunk_root = info->chunk_root;
1667 struct btrfs_root *extent_root = info->extent_root;
1668 struct btrfs_device *device;
1669 struct btrfs_block_group_cache *cache;
1670 struct btrfs_dev_extent *extent;
1671 struct extent_buffer *leaf;
1672 struct btrfs_chunk chunk;
1673 struct btrfs_key key;
1674 struct btrfs_path path;
1675 u64 cur_start;
1676 u64 total_bytes;
1677 u64 chunk_objectid;
1678 int ret;
1680 btrfs_init_path(&path);
1682 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1683 chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1685 BUG_ON(list_empty(&info->fs_devices->devices));
1686 device = list_entry(info->fs_devices->devices.next,
1687 struct btrfs_device, dev_list);
1688 BUG_ON(device->devid != info->fs_devices->latest_devid);
1690 /* delete device extent created by make_btrfs */
1691 key.objectid = device->devid;
1692 key.offset = 0;
1693 key.type = BTRFS_DEV_EXTENT_KEY;
1694 ret = btrfs_search_slot(trans, device->dev_root, &key, &path, -1, 1);
1695 if (ret < 0)
1696 goto err;
1698 BUG_ON(ret > 0);
1699 ret = btrfs_del_item(trans, device->dev_root, &path);
1700 if (ret)
1701 goto err;
1702 btrfs_release_path(&path);
1704 /* delete chunk item created by make_btrfs */
1705 key.objectid = chunk_objectid;
1706 key.offset = 0;
1707 key.type = BTRFS_CHUNK_ITEM_KEY;
1708 ret = btrfs_search_slot(trans, chunk_root, &key, &path, -1, 1);
1709 if (ret < 0)
1710 goto err;
1712 BUG_ON(ret > 0);
1713 ret = btrfs_del_item(trans, chunk_root, &path);
1714 if (ret)
1715 goto err;
1716 btrfs_release_path(&path);
1718 /* for each block group, create device extent and chunk item */
1719 cur_start = 0;
1720 while (cur_start < total_bytes) {
1721 cache = btrfs_lookup_block_group(root->fs_info, cur_start);
1722 BUG_ON(!cache);
1724 /* insert device extent */
1725 key.objectid = device->devid;
1726 key.offset = cache->key.objectid;
1727 key.type = BTRFS_DEV_EXTENT_KEY;
1728 ret = btrfs_insert_empty_item(trans, device->dev_root, &path,
1729 &key, sizeof(*extent));
1730 if (ret)
1731 goto err;
1733 leaf = path.nodes[0];
1734 extent = btrfs_item_ptr(leaf, path.slots[0],
1735 struct btrfs_dev_extent);
1737 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1738 chunk_root->root_key.objectid);
1739 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1740 chunk_objectid);
1741 btrfs_set_dev_extent_chunk_offset(leaf, extent,
1742 cache->key.objectid);
1743 btrfs_set_dev_extent_length(leaf, extent, cache->key.offset);
1744 write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1745 (unsigned long)btrfs_dev_extent_chunk_tree_uuid(extent),
1746 BTRFS_UUID_SIZE);
1747 btrfs_mark_buffer_dirty(leaf);
1748 btrfs_release_path(&path);
1750 /* insert chunk item */
1751 btrfs_set_stack_chunk_length(&chunk, cache->key.offset);
1752 btrfs_set_stack_chunk_owner(&chunk,
1753 extent_root->root_key.objectid);
1754 btrfs_set_stack_chunk_stripe_len(&chunk, BTRFS_STRIPE_LEN);
1755 btrfs_set_stack_chunk_type(&chunk, cache->flags);
1756 btrfs_set_stack_chunk_io_align(&chunk, device->io_align);
1757 btrfs_set_stack_chunk_io_width(&chunk, device->io_width);
1758 btrfs_set_stack_chunk_sector_size(&chunk, device->sector_size);
1759 btrfs_set_stack_chunk_num_stripes(&chunk, 1);
1760 btrfs_set_stack_chunk_sub_stripes(&chunk, 0);
1761 btrfs_set_stack_stripe_devid(&chunk.stripe, device->devid);
1762 btrfs_set_stack_stripe_offset(&chunk.stripe,
1763 cache->key.objectid);
1764 memcpy(&chunk.stripe.dev_uuid, device->uuid, BTRFS_UUID_SIZE);
1766 key.objectid = chunk_objectid;
1767 key.offset = cache->key.objectid;
1768 key.type = BTRFS_CHUNK_ITEM_KEY;
1770 ret = btrfs_insert_item(trans, chunk_root, &key, &chunk,
1771 btrfs_chunk_item_size(1));
1772 if (ret)
1773 goto err;
1775 cur_start = cache->key.objectid + cache->key.offset;
1778 device->bytes_used = total_bytes;
1779 ret = btrfs_update_device(trans, device);
1780 err:
1781 btrfs_release_path(&path);
1782 return ret;
1785 static int create_subvol(struct btrfs_trans_handle *trans,
1786 struct btrfs_root *root, u64 root_objectid)
1788 struct extent_buffer *tmp;
1789 struct btrfs_root *new_root;
1790 struct btrfs_key key;
1791 struct btrfs_root_item root_item;
1792 int ret;
1794 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1795 root_objectid);
1796 BUG_ON(ret);
1798 memcpy(&root_item, &root->root_item, sizeof(root_item));
1799 btrfs_set_root_bytenr(&root_item, tmp->start);
1800 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1801 btrfs_set_root_generation(&root_item, trans->transid);
1802 free_extent_buffer(tmp);
1804 key.objectid = root_objectid;
1805 key.type = BTRFS_ROOT_ITEM_KEY;
1806 key.offset = trans->transid;
1807 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1808 &key, &root_item);
1810 key.offset = (u64)-1;
1811 new_root = btrfs_read_fs_root(root->fs_info, &key);
1812 BUG_ON(!new_root || IS_ERR(new_root));
1814 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1815 BUG_ON(ret);
1817 return 0;
1820 static int init_btrfs(struct btrfs_root *root)
1822 int ret;
1823 struct btrfs_key location;
1824 struct btrfs_trans_handle *trans;
1825 struct btrfs_fs_info *fs_info = root->fs_info;
1826 struct extent_buffer *tmp;
1828 trans = btrfs_start_transaction(root, 1);
1829 BUG_ON(!trans);
1830 ret = btrfs_make_block_groups(trans, root);
1831 if (ret)
1832 goto err;
1833 ret = btrfs_fix_block_accounting(trans, root);
1834 if (ret)
1835 goto err;
1836 ret = create_chunk_mapping(trans, root);
1837 if (ret)
1838 goto err;
1839 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1840 BTRFS_ROOT_TREE_DIR_OBJECTID);
1841 if (ret)
1842 goto err;
1843 memcpy(&location, &root->root_key, sizeof(location));
1844 location.offset = (u64)-1;
1845 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1846 btrfs_super_root_dir(fs_info->super_copy),
1847 &location, BTRFS_FT_DIR, 0);
1848 if (ret)
1849 goto err;
1850 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1851 location.objectid,
1852 btrfs_super_root_dir(fs_info->super_copy), 0);
1853 if (ret)
1854 goto err;
1855 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1856 BTRFS_FIRST_FREE_OBJECTID);
1858 /* subvol for fs image file */
1859 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1860 BUG_ON(ret);
1861 /* subvol for data relocation */
1862 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1863 BUG_ON(ret);
1865 extent_buffer_get(fs_info->csum_root->node);
1866 ret = __btrfs_cow_block(trans, fs_info->csum_root,
1867 fs_info->csum_root->node, NULL, 0, &tmp, 0, 0);
1868 BUG_ON(ret);
1869 free_extent_buffer(tmp);
1871 ret = btrfs_commit_transaction(trans, root);
1872 BUG_ON(ret);
1873 err:
1874 return ret;
1878 * Migrate super block to its default position and zero 0 ~ 16k
1880 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
1882 int ret;
1883 struct extent_buffer *buf;
1884 struct btrfs_super_block *super;
1885 u32 len;
1886 u32 bytenr;
1888 BUG_ON(sectorsize < sizeof(*super));
1889 buf = malloc(sizeof(*buf) + sectorsize);
1890 if (!buf)
1891 return -ENOMEM;
1893 buf->len = sectorsize;
1894 ret = pread(fd, buf->data, sectorsize, old_bytenr);
1895 if (ret != sectorsize)
1896 goto fail;
1898 super = (struct btrfs_super_block *)buf->data;
1899 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1900 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1902 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1903 ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1904 if (ret != sectorsize)
1905 goto fail;
1907 ret = fsync(fd);
1908 if (ret)
1909 goto fail;
1911 memset(buf->data, 0, sectorsize);
1912 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1913 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1914 if (len > sectorsize)
1915 len = sectorsize;
1916 ret = pwrite(fd, buf->data, len, bytenr);
1917 if (ret != len) {
1918 fprintf(stderr, "unable to zero fill device\n");
1919 break;
1921 bytenr += len;
1923 ret = 0;
1924 fsync(fd);
1925 fail:
1926 free(buf);
1927 if (ret > 0)
1928 ret = -1;
1929 return ret;
1932 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1934 struct btrfs_chunk *chunk;
1935 struct btrfs_disk_key *key;
1936 u32 sectorsize = btrfs_super_sectorsize(super);
1938 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1939 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1940 sizeof(struct btrfs_disk_key));
1942 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1943 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1944 btrfs_set_disk_key_offset(key, 0);
1946 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1947 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1948 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1949 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1950 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1951 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1952 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1953 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1954 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1955 chunk->stripe.devid = super->dev_item.devid;
1956 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1957 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1958 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1959 return 0;
1962 static int prepare_system_chunk(int fd, u64 sb_bytenr)
1964 int ret;
1965 struct extent_buffer *buf;
1966 struct btrfs_super_block *super;
1968 BUG_ON(BTRFS_SUPER_INFO_SIZE < sizeof(*super));
1969 buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1970 if (!buf)
1971 return -ENOMEM;
1973 buf->len = BTRFS_SUPER_INFO_SIZE;
1974 ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
1975 if (ret != BTRFS_SUPER_INFO_SIZE)
1976 goto fail;
1978 super = (struct btrfs_super_block *)buf->data;
1979 BUG_ON(btrfs_super_bytenr(super) != sb_bytenr);
1980 BUG_ON(btrfs_super_num_devices(super) != 1);
1982 ret = prepare_system_chunk_sb(super);
1983 if (ret)
1984 goto fail;
1986 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1987 ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE, sb_bytenr);
1988 if (ret != BTRFS_SUPER_INFO_SIZE)
1989 goto fail;
1991 ret = 0;
1992 fail:
1993 free(buf);
1994 if (ret > 0)
1995 ret = -1;
1996 return ret;
1999 static int relocate_one_reference(struct btrfs_trans_handle *trans,
2000 struct btrfs_root *root,
2001 u64 extent_start, u64 extent_size,
2002 struct btrfs_key *extent_key,
2003 struct extent_io_tree *reloc_tree)
2005 struct extent_buffer *leaf;
2006 struct btrfs_file_extent_item *fi;
2007 struct btrfs_key key;
2008 struct btrfs_path path;
2009 struct btrfs_inode_item inode;
2010 struct blk_iterate_data data;
2011 u64 bytenr;
2012 u64 num_bytes;
2013 u64 cur_offset;
2014 u64 new_pos;
2015 u64 nbytes;
2016 u64 sector_end;
2017 u32 sectorsize = root->sectorsize;
2018 unsigned long ptr;
2019 int datacsum;
2020 int fd;
2021 int ret;
2023 btrfs_init_path(&path);
2024 ret = btrfs_search_slot(trans, root, extent_key, &path, -1, 1);
2025 if (ret)
2026 goto fail;
2028 leaf = path.nodes[0];
2029 fi = btrfs_item_ptr(leaf, path.slots[0],
2030 struct btrfs_file_extent_item);
2031 BUG_ON(btrfs_file_extent_offset(leaf, fi) > 0);
2032 if (extent_start != btrfs_file_extent_disk_bytenr(leaf, fi) ||
2033 extent_size != btrfs_file_extent_disk_num_bytes(leaf, fi)) {
2034 ret = 1;
2035 goto fail;
2038 bytenr = extent_start + btrfs_file_extent_offset(leaf, fi);
2039 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2041 ret = btrfs_del_item(trans, root, &path);
2042 if (ret)
2043 goto fail;
2045 ret = btrfs_free_extent(trans, root, extent_start, extent_size, 0,
2046 root->root_key.objectid,
2047 extent_key->objectid, extent_key->offset);
2048 if (ret)
2049 goto fail;
2051 btrfs_release_path(&path);
2053 key.objectid = extent_key->objectid;
2054 key.offset = 0;
2055 key.type = BTRFS_INODE_ITEM_KEY;
2056 ret = btrfs_lookup_inode(trans, root, &path, &key, 0);
2057 if (ret)
2058 goto fail;
2060 leaf = path.nodes[0];
2061 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2062 read_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2063 btrfs_release_path(&path);
2065 BUG_ON(num_bytes & (sectorsize - 1));
2066 nbytes = btrfs_stack_inode_nbytes(&inode) - num_bytes;
2067 btrfs_set_stack_inode_nbytes(&inode, nbytes);
2068 datacsum = !(btrfs_stack_inode_flags(&inode) & BTRFS_INODE_NODATASUM);
2070 init_blk_iterate_data(&data, trans, root, &inode, extent_key->objectid,
2071 datacsum);
2072 data.first_block = extent_key->offset;
2074 cur_offset = extent_key->offset;
2075 while (num_bytes > 0) {
2076 sector_end = bytenr + sectorsize - 1;
2077 if (test_range_bit(reloc_tree, bytenr, sector_end,
2078 EXTENT_LOCKED, 1)) {
2079 ret = get_state_private(reloc_tree, bytenr, &new_pos);
2080 BUG_ON(ret);
2081 } else {
2082 ret = custom_alloc_extent(root, sectorsize, 0, &key, 0);
2083 if (ret)
2084 goto fail;
2085 new_pos = key.objectid;
2087 if (cur_offset == extent_key->offset) {
2088 fd = root->fs_info->fs_devices->latest_bdev;
2089 readahead(fd, bytenr, num_bytes);
2091 ret = copy_disk_extent(root, new_pos, bytenr,
2092 sectorsize);
2093 if (ret)
2094 goto fail;
2095 ret = set_extent_bits(reloc_tree, bytenr, sector_end,
2096 EXTENT_LOCKED, GFP_NOFS);
2097 BUG_ON(ret);
2098 ret = set_state_private(reloc_tree, bytenr, new_pos);
2099 BUG_ON(ret);
2102 ret = block_iterate_proc(new_pos / sectorsize,
2103 cur_offset / sectorsize, &data);
2104 if (ret < 0)
2105 goto fail;
2107 cur_offset += sectorsize;
2108 bytenr += sectorsize;
2109 num_bytes -= sectorsize;
2112 if (data.num_blocks > 0) {
2113 ret = record_file_blocks(&data, data.first_block,
2114 data.disk_block, data.num_blocks);
2115 if (ret)
2116 goto fail;
2119 key.objectid = extent_key->objectid;
2120 key.offset = 0;
2121 key.type = BTRFS_INODE_ITEM_KEY;
2122 ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
2123 if (ret)
2124 goto fail;
2126 leaf = path.nodes[0];
2127 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2128 write_extent_buffer(leaf, &inode, ptr, sizeof(inode));
2129 btrfs_mark_buffer_dirty(leaf);
2130 btrfs_release_path(&path);
2132 fail:
2133 btrfs_release_path(&path);
2134 return ret;
2137 static int relocate_extents_range(struct btrfs_root *fs_root,
2138 struct btrfs_root *image_root,
2139 u64 start_byte, u64 end_byte)
2141 struct btrfs_fs_info *info = fs_root->fs_info;
2142 struct btrfs_root *extent_root = info->extent_root;
2143 struct btrfs_root *cur_root = NULL;
2144 struct btrfs_trans_handle *trans;
2145 struct btrfs_extent_data_ref *dref;
2146 struct btrfs_extent_inline_ref *iref;
2147 struct btrfs_extent_item *ei;
2148 struct extent_buffer *leaf;
2149 struct btrfs_key key;
2150 struct btrfs_key extent_key;
2151 struct btrfs_path path;
2152 struct extent_io_tree reloc_tree;
2153 unsigned long ptr;
2154 unsigned long end;
2155 u64 cur_byte;
2156 u64 num_bytes;
2157 u64 ref_root;
2158 u64 num_extents;
2159 int pass = 0;
2160 int ret;
2162 btrfs_init_path(&path);
2163 extent_io_tree_init(&reloc_tree);
2165 key.objectid = start_byte;
2166 key.offset = 0;
2167 key.type = BTRFS_EXTENT_ITEM_KEY;
2168 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2169 if (ret < 0)
2170 goto fail;
2171 if (ret > 0) {
2172 ret = btrfs_previous_item(extent_root, &path, 0,
2173 BTRFS_EXTENT_ITEM_KEY);
2174 if (ret < 0)
2175 goto fail;
2176 if (ret == 0) {
2177 leaf = path.nodes[0];
2178 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2179 if (key.objectid + key.offset > start_byte)
2180 start_byte = key.objectid;
2183 btrfs_release_path(&path);
2184 again:
2185 cur_root = (pass % 2 == 0) ? image_root : fs_root;
2186 num_extents = 0;
2188 trans = btrfs_start_transaction(cur_root, 1);
2189 BUG_ON(!trans);
2191 cur_byte = start_byte;
2192 while (1) {
2193 key.objectid = cur_byte;
2194 key.offset = 0;
2195 key.type = BTRFS_EXTENT_ITEM_KEY;
2196 ret = btrfs_search_slot(trans, extent_root,
2197 &key, &path, 0, 0);
2198 if (ret < 0)
2199 goto fail;
2200 next:
2201 leaf = path.nodes[0];
2202 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2203 ret = btrfs_next_leaf(extent_root, &path);
2204 if (ret < 0)
2205 goto fail;
2206 if (ret > 0)
2207 break;
2208 leaf = path.nodes[0];
2211 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2212 if (key.objectid < cur_byte ||
2213 key.type != BTRFS_EXTENT_ITEM_KEY) {
2214 path.slots[0]++;
2215 goto next;
2217 if (key.objectid >= end_byte)
2218 break;
2220 num_extents++;
2222 cur_byte = key.objectid;
2223 num_bytes = key.offset;
2224 ei = btrfs_item_ptr(leaf, path.slots[0],
2225 struct btrfs_extent_item);
2226 BUG_ON(!(btrfs_extent_flags(leaf, ei) &
2227 BTRFS_EXTENT_FLAG_DATA));
2229 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2230 end = ptr + btrfs_item_size_nr(leaf, path.slots[0]);
2232 ptr += sizeof(struct btrfs_extent_item);
2234 while (ptr < end) {
2235 iref = (struct btrfs_extent_inline_ref *)ptr;
2236 key.type = btrfs_extent_inline_ref_type(leaf, iref);
2237 BUG_ON(key.type != BTRFS_EXTENT_DATA_REF_KEY);
2238 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
2239 ref_root = btrfs_extent_data_ref_root(leaf, dref);
2240 extent_key.objectid =
2241 btrfs_extent_data_ref_objectid(leaf, dref);
2242 extent_key.offset =
2243 btrfs_extent_data_ref_offset(leaf, dref);
2244 extent_key.type = BTRFS_EXTENT_DATA_KEY;
2245 BUG_ON(btrfs_extent_data_ref_count(leaf, dref) != 1);
2247 if (ref_root == cur_root->root_key.objectid)
2248 break;
2250 ptr += btrfs_extent_inline_ref_size(key.type);
2253 if (ptr >= end) {
2254 path.slots[0]++;
2255 goto next;
2258 ret = relocate_one_reference(trans, cur_root, cur_byte,
2259 num_bytes, &extent_key,
2260 &reloc_tree);
2261 if (ret < 0)
2262 goto fail;
2264 cur_byte += num_bytes;
2265 btrfs_release_path(&path);
2267 if (trans->blocks_used >= 4096) {
2268 ret = btrfs_commit_transaction(trans, cur_root);
2269 BUG_ON(ret);
2270 trans = btrfs_start_transaction(cur_root, 1);
2271 BUG_ON(!trans);
2274 btrfs_release_path(&path);
2276 ret = btrfs_commit_transaction(trans, cur_root);
2277 BUG_ON(ret);
2279 if (num_extents > 0 && pass++ < 16)
2280 goto again;
2282 ret = (num_extents > 0) ? -1 : 0;
2283 fail:
2284 btrfs_release_path(&path);
2285 extent_io_tree_cleanup(&reloc_tree);
2286 return ret;
2290 * relocate data in system chunk
2292 static int cleanup_sys_chunk(struct btrfs_root *fs_root,
2293 struct btrfs_root *image_root)
2295 struct btrfs_block_group_cache *cache;
2296 int i, ret = 0;
2297 u64 offset = 0;
2298 u64 end_byte;
2300 while(1) {
2301 cache = btrfs_lookup_block_group(fs_root->fs_info, offset);
2302 if (!cache)
2303 break;
2305 end_byte = cache->key.objectid + cache->key.offset;
2306 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2307 ret = relocate_extents_range(fs_root, image_root,
2308 cache->key.objectid,
2309 end_byte);
2310 if (ret)
2311 goto fail;
2313 offset = end_byte;
2315 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2316 offset = btrfs_sb_offset(i);
2317 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
2319 ret = relocate_extents_range(fs_root, image_root,
2320 offset, offset + BTRFS_STRIPE_LEN);
2321 if (ret)
2322 goto fail;
2324 ret = 0;
2325 fail:
2326 return ret;
2329 static int fixup_chunk_mapping(struct btrfs_root *root)
2331 struct btrfs_trans_handle *trans;
2332 struct btrfs_fs_info *info = root->fs_info;
2333 struct btrfs_root *chunk_root = info->chunk_root;
2334 struct extent_buffer *leaf;
2335 struct btrfs_key key;
2336 struct btrfs_path path;
2337 struct btrfs_chunk chunk;
2338 unsigned long ptr;
2339 u32 size;
2340 u64 type;
2341 int ret;
2343 btrfs_init_path(&path);
2345 trans = btrfs_start_transaction(root, 1);
2346 BUG_ON(!trans);
2349 * recow the whole chunk tree. this will move all chunk tree blocks
2350 * into system block group.
2352 memset(&key, 0, sizeof(key));
2353 while (1) {
2354 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2355 if (ret < 0)
2356 goto err;
2358 ret = btrfs_next_leaf(chunk_root, &path);
2359 if (ret < 0)
2360 goto err;
2361 if (ret > 0)
2362 break;
2364 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2365 btrfs_release_path(&path);
2367 btrfs_release_path(&path);
2369 /* fixup the system chunk array in super block */
2370 btrfs_set_super_sys_array_size(info->super_copy, 0);
2372 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2373 key.offset = 0;
2374 key.type = BTRFS_CHUNK_ITEM_KEY;
2376 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 0);
2377 if (ret < 0)
2378 goto err;
2379 BUG_ON(ret != 0);
2380 while(1) {
2381 leaf = path.nodes[0];
2382 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2383 ret = btrfs_next_leaf(chunk_root, &path);
2384 if (ret < 0)
2385 goto err;
2386 if (ret > 0)
2387 break;
2388 leaf = path.nodes[0];
2390 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2391 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2392 goto next;
2394 ptr = btrfs_item_ptr_offset(leaf, path.slots[0]);
2395 size = btrfs_item_size_nr(leaf, path.slots[0]);
2396 BUG_ON(size != sizeof(chunk));
2397 read_extent_buffer(leaf, &chunk, ptr, size);
2398 type = btrfs_stack_chunk_type(&chunk);
2400 if (!(type & BTRFS_BLOCK_GROUP_SYSTEM))
2401 goto next;
2403 ret = btrfs_add_system_chunk(trans, chunk_root, &key,
2404 &chunk, size);
2405 if (ret)
2406 goto err;
2407 next:
2408 path.slots[0]++;
2411 ret = btrfs_commit_transaction(trans, root);
2412 BUG_ON(ret);
2413 err:
2414 btrfs_release_path(&path);
2415 return ret;
2418 static const struct btrfs_convert_operations ext2_convert_ops = {
2419 .name = "ext2",
2420 .open_fs = ext2_open_fs,
2421 .alloc_block = ext2_alloc_block,
2422 .alloc_block_range = ext2_alloc_block_range,
2423 .copy_inodes = ext2_copy_inodes,
2424 .test_block = ext2_test_block,
2425 .free_block = ext2_free_block,
2426 .free_block_range = ext2_free_block_range,
2427 .close_fs = ext2_close_fs,
2430 static const struct btrfs_convert_operations *convert_operations[] = {
2431 &ext2_convert_ops,
2434 static int convert_open_fs(const char *devname,
2435 struct btrfs_convert_context *cctx)
2437 int i;
2439 memset(cctx, 0, sizeof(*cctx));
2441 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2442 int ret = convert_operations[i]->open_fs(cctx, devname);
2444 if (ret == 0) {
2445 cctx->convert_ops = convert_operations[i];
2446 return ret;
2450 fprintf(stderr, "No file system found to convert.\n");
2451 return -1;
2454 static int do_convert(const char *devname, int datacsum, int packing, int noxattr,
2455 u32 nodesize, int copylabel, const char *fslabel, int progress,
2456 u64 features)
2458 int i, ret, blocks_per_node;
2459 int fd = -1;
2460 int is_btrfs = 0;
2461 u32 blocksize;
2462 u64 blocks[7];
2463 u64 total_bytes;
2464 u64 super_bytenr;
2465 struct btrfs_root *root;
2466 struct btrfs_root *image_root;
2467 struct btrfs_convert_context cctx;
2468 char *subvol_name = NULL;
2469 struct task_ctx ctx;
2470 char features_buf[64];
2471 struct btrfs_mkfs_config mkfs_cfg;
2473 init_convert_context(&cctx);
2474 ret = convert_open_fs(devname, &cctx);
2475 if (ret)
2476 goto fail;
2478 blocksize = cctx.blocksize;
2479 total_bytes = (u64)blocksize * (u64)cctx.block_count;
2480 if (blocksize < 4096) {
2481 fprintf(stderr, "block size is too small\n");
2482 goto fail;
2484 if (btrfs_check_nodesize(nodesize, blocksize, features))
2485 goto fail;
2486 blocks_per_node = nodesize / blocksize;
2487 ret = -blocks_per_node;
2488 for (i = 0; i < 7; i++) {
2489 if (nodesize == blocksize)
2490 ret = convert_alloc_block(&cctx, 0, blocks + i);
2491 else
2492 ret = convert_alloc_block_range(&cctx,
2493 ret + blocks_per_node, blocks_per_node,
2494 blocks + i);
2495 if (ret) {
2496 fprintf(stderr, "not enough free space\n");
2497 goto fail;
2499 blocks[i] *= blocksize;
2501 super_bytenr = blocks[0];
2502 fd = open(devname, O_RDWR);
2503 if (fd < 0) {
2504 fprintf(stderr, "unable to open %s\n", devname);
2505 goto fail;
2507 btrfs_parse_features_to_string(features_buf, features);
2508 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2509 strcat(features_buf, " (default)");
2511 printf("create btrfs filesystem:\n");
2512 printf("\tblocksize: %u\n", blocksize);
2513 printf("\tnodesize: %u\n", nodesize);
2514 printf("\tfeatures: %s\n", features_buf);
2516 mkfs_cfg.label = cctx.volume_name;
2517 mkfs_cfg.fs_uuid = NULL;
2518 memcpy(mkfs_cfg.blocks, blocks, sizeof(blocks));
2519 mkfs_cfg.num_bytes = total_bytes;
2520 mkfs_cfg.nodesize = nodesize;
2521 mkfs_cfg.sectorsize = blocksize;
2522 mkfs_cfg.stripesize = blocksize;
2523 mkfs_cfg.features = features;
2525 ret = make_btrfs(fd, &mkfs_cfg);
2526 if (ret) {
2527 fprintf(stderr, "unable to create initial ctree: %s\n",
2528 strerror(-ret));
2529 goto fail;
2531 /* create a system chunk that maps the whole device */
2532 ret = prepare_system_chunk(fd, super_bytenr);
2533 if (ret) {
2534 fprintf(stderr, "unable to update system chunk\n");
2535 goto fail;
2537 root = open_ctree_fd(fd, devname, super_bytenr, OPEN_CTREE_WRITES);
2538 if (!root) {
2539 fprintf(stderr, "unable to open ctree\n");
2540 goto fail;
2542 ret = cache_free_extents(root, &cctx);
2543 if (ret) {
2544 fprintf(stderr, "error during cache_free_extents %d\n", ret);
2545 goto fail;
2547 root->fs_info->extent_ops = &extent_ops;
2548 /* recover block allocation bitmap */
2549 for (i = 0; i < 7; i++) {
2550 blocks[i] /= blocksize;
2551 if (nodesize == blocksize)
2552 convert_free_block(&cctx, blocks[i]);
2553 else
2554 convert_free_block_range(&cctx, blocks[i],
2555 blocks_per_node);
2557 ret = init_btrfs(root);
2558 if (ret) {
2559 fprintf(stderr, "unable to setup the root tree\n");
2560 goto fail;
2562 printf("creating btrfs metadata.\n");
2563 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2564 ctx.cur_copy_inodes = 0;
2566 if (progress) {
2567 ctx.info = task_init(print_copied_inodes, after_copied_inodes, &ctx);
2568 task_start(ctx.info);
2570 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2571 if (ret) {
2572 fprintf(stderr, "error during copy_inodes %d\n", ret);
2573 goto fail;
2575 if (progress) {
2576 task_stop(ctx.info);
2577 task_deinit(ctx.info);
2580 printf("creating %s image file.\n", cctx.convert_ops->name);
2581 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2582 if (ret < 0) {
2583 fprintf(stderr, "error allocating subvolume name: %s_saved\n",
2584 cctx.convert_ops->name);
2585 goto fail;
2588 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2590 free(subvol_name);
2592 if (!image_root) {
2593 fprintf(stderr, "unable to create subvol\n");
2594 goto fail;
2596 ret = create_image(&cctx, image_root, "image", datacsum);
2597 if (ret) {
2598 fprintf(stderr, "error during create_image %d\n", ret);
2599 goto fail;
2601 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2602 if (copylabel == 1) {
2603 __strncpy_null(root->fs_info->super_copy->label,
2604 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2605 fprintf(stderr, "copy label '%s'\n",
2606 root->fs_info->super_copy->label);
2607 } else if (copylabel == -1) {
2608 strcpy(root->fs_info->super_copy->label, fslabel);
2609 fprintf(stderr, "set label to '%s'\n", fslabel);
2612 printf("cleaning up system chunk.\n");
2613 ret = cleanup_sys_chunk(root, image_root);
2614 if (ret) {
2615 fprintf(stderr, "error during cleanup_sys_chunk %d\n", ret);
2616 goto fail;
2618 ret = close_ctree(root);
2619 if (ret) {
2620 fprintf(stderr, "error during close_ctree %d\n", ret);
2621 goto fail;
2623 convert_close_fs(&cctx);
2624 clean_convert_context(&cctx);
2627 * If this step succeed, we get a mountable btrfs. Otherwise
2628 * the source fs is left unchanged.
2630 ret = migrate_super_block(fd, super_bytenr, blocksize);
2631 if (ret) {
2632 fprintf(stderr, "unable to migrate super block\n");
2633 goto fail;
2635 is_btrfs = 1;
2637 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2638 if (!root) {
2639 fprintf(stderr, "unable to open ctree\n");
2640 goto fail;
2642 /* move chunk tree into system chunk. */
2643 ret = fixup_chunk_mapping(root);
2644 if (ret) {
2645 fprintf(stderr, "error during fixup_chunk_tree\n");
2646 goto fail;
2648 ret = close_ctree(root);
2649 close(fd);
2651 printf("conversion complete.\n");
2652 return 0;
2653 fail:
2654 clean_convert_context(&cctx);
2655 if (fd != -1)
2656 close(fd);
2657 if (is_btrfs)
2658 fprintf(stderr,
2659 "WARNING: an error occured during chunk mapping fixup, filesystem mountable but not finalized\n");
2660 else
2661 fprintf(stderr, "conversion aborted\n");
2662 return -1;
2665 static int may_rollback(struct btrfs_root *root)
2667 struct btrfs_fs_info *info = root->fs_info;
2668 struct btrfs_multi_bio *multi = NULL;
2669 u64 bytenr;
2670 u64 length;
2671 u64 physical;
2672 u64 total_bytes;
2673 int num_stripes;
2674 int ret;
2676 if (btrfs_super_num_devices(info->super_copy) != 1)
2677 goto fail;
2679 bytenr = BTRFS_SUPER_INFO_OFFSET;
2680 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2682 while (1) {
2683 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2684 &length, &multi, 0, NULL);
2685 if (ret) {
2686 if (ret == -ENOENT) {
2687 /* removed block group at the tail */
2688 if (length == (u64)-1)
2689 break;
2691 /* removed block group in the middle */
2692 goto next;
2694 goto fail;
2697 num_stripes = multi->num_stripes;
2698 physical = multi->stripes[0].physical;
2699 kfree(multi);
2701 if (num_stripes != 1 || physical != bytenr)
2702 goto fail;
2703 next:
2704 bytenr += length;
2705 if (bytenr >= total_bytes)
2706 break;
2708 return 0;
2709 fail:
2710 return -1;
2713 static int do_rollback(const char *devname)
2715 int fd = -1;
2716 int ret;
2717 int i;
2718 struct btrfs_root *root;
2719 struct btrfs_root *image_root;
2720 struct btrfs_root *chunk_root;
2721 struct btrfs_dir_item *dir;
2722 struct btrfs_inode_item *inode;
2723 struct btrfs_file_extent_item *fi;
2724 struct btrfs_trans_handle *trans;
2725 struct extent_buffer *leaf;
2726 struct btrfs_block_group_cache *cache1;
2727 struct btrfs_block_group_cache *cache2;
2728 struct btrfs_key key;
2729 struct btrfs_path path;
2730 struct extent_io_tree io_tree;
2731 char *buf = NULL;
2732 char *name;
2733 u64 bytenr;
2734 u64 num_bytes;
2735 u64 root_dir;
2736 u64 objectid;
2737 u64 offset;
2738 u64 start;
2739 u64 end;
2740 u64 sb_bytenr;
2741 u64 first_free;
2742 u64 total_bytes;
2743 u32 sectorsize;
2745 extent_io_tree_init(&io_tree);
2747 fd = open(devname, O_RDWR);
2748 if (fd < 0) {
2749 fprintf(stderr, "unable to open %s\n", devname);
2750 goto fail;
2752 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2753 if (!root) {
2754 fprintf(stderr, "unable to open ctree\n");
2755 goto fail;
2757 ret = may_rollback(root);
2758 if (ret < 0) {
2759 fprintf(stderr, "unable to do rollback\n");
2760 goto fail;
2763 sectorsize = root->sectorsize;
2764 buf = malloc(sectorsize);
2765 if (!buf) {
2766 fprintf(stderr, "unable to allocate memory\n");
2767 goto fail;
2770 btrfs_init_path(&path);
2772 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2773 key.type = BTRFS_ROOT_BACKREF_KEY;
2774 key.offset = BTRFS_FS_TREE_OBJECTID;
2775 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2777 btrfs_release_path(&path);
2778 if (ret > 0) {
2779 fprintf(stderr,
2780 "ERROR: unable to convert ext2 image subvolume, is it deleted?\n");
2781 goto fail;
2782 } else if (ret < 0) {
2783 fprintf(stderr,
2784 "ERROR: unable to open ext2_saved, id=%llu: %s\n",
2785 (unsigned long long)key.objectid, strerror(-ret));
2786 goto fail;
2789 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2790 key.type = BTRFS_ROOT_ITEM_KEY;
2791 key.offset = (u64)-1;
2792 image_root = btrfs_read_fs_root(root->fs_info, &key);
2793 if (!image_root || IS_ERR(image_root)) {
2794 fprintf(stderr, "unable to open subvol %llu\n",
2795 (unsigned long long)key.objectid);
2796 goto fail;
2799 name = "image";
2800 root_dir = btrfs_root_dirid(&root->root_item);
2801 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2802 root_dir, name, strlen(name), 0);
2803 if (!dir || IS_ERR(dir)) {
2804 fprintf(stderr, "unable to find file %s\n", name);
2805 goto fail;
2807 leaf = path.nodes[0];
2808 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2809 btrfs_release_path(&path);
2811 objectid = key.objectid;
2813 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2814 if (ret) {
2815 fprintf(stderr, "unable to find inode item\n");
2816 goto fail;
2818 leaf = path.nodes[0];
2819 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2820 total_bytes = btrfs_inode_size(leaf, inode);
2821 btrfs_release_path(&path);
2823 key.objectid = objectid;
2824 key.offset = 0;
2825 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
2826 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2827 if (ret != 0) {
2828 fprintf(stderr, "unable to find first file extent\n");
2829 btrfs_release_path(&path);
2830 goto fail;
2833 /* build mapping tree for the relocated blocks */
2834 for (offset = 0; offset < total_bytes; ) {
2835 leaf = path.nodes[0];
2836 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2837 ret = btrfs_next_leaf(root, &path);
2838 if (ret != 0)
2839 break;
2840 continue;
2843 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2844 if (key.objectid != objectid || key.offset != offset ||
2845 btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2846 break;
2848 fi = btrfs_item_ptr(leaf, path.slots[0],
2849 struct btrfs_file_extent_item);
2850 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2851 break;
2852 if (btrfs_file_extent_compression(leaf, fi) ||
2853 btrfs_file_extent_encryption(leaf, fi) ||
2854 btrfs_file_extent_other_encoding(leaf, fi))
2855 break;
2857 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2858 /* skip holes and direct mapped extents */
2859 if (bytenr == 0 || bytenr == offset)
2860 goto next_extent;
2862 bytenr += btrfs_file_extent_offset(leaf, fi);
2863 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2865 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2866 cache2 = btrfs_lookup_block_group(root->fs_info,
2867 offset + num_bytes - 1);
2868 if (!cache1 || cache1 != cache2 ||
2869 (!(cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM) &&
2870 !intersect_with_sb(offset, num_bytes)))
2871 break;
2873 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2874 EXTENT_LOCKED, GFP_NOFS);
2875 set_state_private(&io_tree, offset, bytenr);
2876 next_extent:
2877 offset += btrfs_file_extent_num_bytes(leaf, fi);
2878 path.slots[0]++;
2880 btrfs_release_path(&path);
2882 if (offset < total_bytes) {
2883 fprintf(stderr, "unable to build extent mapping\n");
2884 goto fail;
2887 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2888 first_free &= ~((u64)sectorsize - 1);
2889 /* backup for extent #0 should exist */
2890 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2891 fprintf(stderr, "no backup for the first extent\n");
2892 goto fail;
2894 /* force no allocation from system block group */
2895 root->fs_info->system_allocs = -1;
2896 trans = btrfs_start_transaction(root, 1);
2897 BUG_ON(!trans);
2899 * recow the whole chunk tree, this will remove all chunk tree blocks
2900 * from system block group
2902 chunk_root = root->fs_info->chunk_root;
2903 memset(&key, 0, sizeof(key));
2904 while (1) {
2905 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2906 if (ret < 0)
2907 break;
2909 ret = btrfs_next_leaf(chunk_root, &path);
2910 if (ret)
2911 break;
2913 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2914 btrfs_release_path(&path);
2916 btrfs_release_path(&path);
2918 offset = 0;
2919 num_bytes = 0;
2920 while(1) {
2921 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2922 if (!cache1)
2923 break;
2925 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2926 num_bytes += btrfs_block_group_used(&cache1->item);
2928 offset = cache1->key.objectid + cache1->key.offset;
2930 /* only extent #0 left in system block group? */
2931 if (num_bytes > first_free) {
2932 fprintf(stderr, "unable to empty system block group\n");
2933 goto fail;
2935 /* create a system chunk that maps the whole device */
2936 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2937 if (ret) {
2938 fprintf(stderr, "unable to update system chunk\n");
2939 goto fail;
2942 ret = btrfs_commit_transaction(trans, root);
2943 BUG_ON(ret);
2945 ret = close_ctree(root);
2946 if (ret) {
2947 fprintf(stderr, "error during close_ctree %d\n", ret);
2948 goto fail;
2951 /* zero btrfs super block mirrors */
2952 memset(buf, 0, sectorsize);
2953 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2954 bytenr = btrfs_sb_offset(i);
2955 if (bytenr >= total_bytes)
2956 break;
2957 ret = pwrite(fd, buf, sectorsize, bytenr);
2958 if (ret != sectorsize) {
2959 fprintf(stderr,
2960 "error during zeroing supreblock %d: %d\n",
2961 i, ret);
2962 goto fail;
2966 sb_bytenr = (u64)-1;
2967 /* copy all relocated blocks back */
2968 while(1) {
2969 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2970 EXTENT_LOCKED);
2971 if (ret)
2972 break;
2974 ret = get_state_private(&io_tree, start, &bytenr);
2975 BUG_ON(ret);
2977 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2978 GFP_NOFS);
2980 while (start <= end) {
2981 if (start == BTRFS_SUPER_INFO_OFFSET) {
2982 sb_bytenr = bytenr;
2983 goto next_sector;
2985 ret = pread(fd, buf, sectorsize, bytenr);
2986 if (ret < 0) {
2987 fprintf(stderr, "error during pread %d\n", ret);
2988 goto fail;
2990 BUG_ON(ret != sectorsize);
2991 ret = pwrite(fd, buf, sectorsize, start);
2992 if (ret < 0) {
2993 fprintf(stderr, "error during pwrite %d\n", ret);
2994 goto fail;
2996 BUG_ON(ret != sectorsize);
2997 next_sector:
2998 start += sectorsize;
2999 bytenr += sectorsize;
3003 ret = fsync(fd);
3004 if (ret) {
3005 fprintf(stderr, "error during fsync %d\n", ret);
3006 goto fail;
3009 * finally, overwrite btrfs super block.
3011 ret = pread(fd, buf, sectorsize, sb_bytenr);
3012 if (ret < 0) {
3013 fprintf(stderr, "error during pread %d\n", ret);
3014 goto fail;
3016 BUG_ON(ret != sectorsize);
3017 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3018 if (ret < 0) {
3019 fprintf(stderr, "error during pwrite %d\n", ret);
3020 goto fail;
3022 BUG_ON(ret != sectorsize);
3023 ret = fsync(fd);
3024 if (ret) {
3025 fprintf(stderr, "error during fsync %d\n", ret);
3026 goto fail;
3029 close(fd);
3030 free(buf);
3031 extent_io_tree_cleanup(&io_tree);
3032 printf("rollback complete.\n");
3033 return 0;
3035 fail:
3036 if (fd != -1)
3037 close(fd);
3038 free(buf);
3039 fprintf(stderr, "rollback aborted.\n");
3040 return -1;
3043 static void print_usage(void)
3045 printf("usage: btrfs-convert [options] device\n");
3046 printf("options:\n");
3047 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
3048 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
3049 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
3050 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
3051 printf("\t-r|--rollback roll back to the original filesystem\n");
3052 printf("\t-l|--label LABEL set filesystem label\n");
3053 printf("\t-L|--copy-label use label from converted filesystem\n");
3054 printf("\t-p|--progress show converting progress (default)\n");
3055 printf("\t-O|--features LIST comma separated list of filesystem features\n");
3056 printf("\t--no-progress show only overview, not the detailed progress\n");
3059 int main(int argc, char *argv[])
3061 int ret;
3062 int packing = 1;
3063 int noxattr = 0;
3064 int datacsum = 1;
3065 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3066 BTRFS_MKFS_DEFAULT_NODE_SIZE);
3067 int rollback = 0;
3068 int copylabel = 0;
3069 int usage_error = 0;
3070 int progress = 1;
3071 char *file;
3072 char fslabel[BTRFS_LABEL_SIZE];
3073 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3075 while(1) {
3076 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3077 static const struct option long_options[] = {
3078 { "no-progress", no_argument, NULL,
3079 GETOPT_VAL_NO_PROGRESS },
3080 { "no-datasum", no_argument, NULL, 'd' },
3081 { "no-inline", no_argument, NULL, 'n' },
3082 { "no-xattr", no_argument, NULL, 'i' },
3083 { "rollback", no_argument, NULL, 'r' },
3084 { "features", required_argument, NULL, 'O' },
3085 { "progress", no_argument, NULL, 'p' },
3086 { "label", required_argument, NULL, 'l' },
3087 { "copy-label", no_argument, NULL, 'L' },
3088 { "nodesize", required_argument, NULL, 'N' },
3089 { "help", no_argument, NULL, GETOPT_VAL_HELP},
3090 { NULL, 0, NULL, 0 }
3092 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3094 if (c < 0)
3095 break;
3096 switch(c) {
3097 case 'd':
3098 datacsum = 0;
3099 break;
3100 case 'i':
3101 noxattr = 1;
3102 break;
3103 case 'n':
3104 packing = 0;
3105 break;
3106 case 'N':
3107 nodesize = parse_size(optarg);
3108 break;
3109 case 'r':
3110 rollback = 1;
3111 break;
3112 case 'l':
3113 copylabel = -1;
3114 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3115 fprintf(stderr,
3116 "WARNING: label too long, trimmed to %d bytes\n",
3117 BTRFS_LABEL_SIZE - 1);
3119 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3120 break;
3121 case 'L':
3122 copylabel = 1;
3123 break;
3124 case 'p':
3125 progress = 1;
3126 break;
3127 case 'O': {
3128 char *orig = strdup(optarg);
3129 char *tmp = orig;
3131 tmp = btrfs_parse_fs_features(tmp, &features);
3132 if (tmp) {
3133 fprintf(stderr,
3134 "Unrecognized filesystem feature '%s'\n",
3135 tmp);
3136 free(orig);
3137 exit(1);
3139 free(orig);
3140 if (features & BTRFS_FEATURE_LIST_ALL) {
3141 btrfs_list_all_fs_features(
3142 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3143 exit(0);
3145 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3146 char buf[64];
3148 btrfs_parse_features_to_string(buf,
3149 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3150 fprintf(stderr,
3151 "ERROR: features not allowed for convert: %s\n",
3152 buf);
3153 exit(1);
3156 break;
3158 case GETOPT_VAL_NO_PROGRESS:
3159 progress = 0;
3160 break;
3161 case GETOPT_VAL_HELP:
3162 default:
3163 print_usage();
3164 return c != GETOPT_VAL_HELP;
3167 set_argv0(argv);
3168 if (check_argc_exact(argc - optind, 1)) {
3169 print_usage();
3170 return 1;
3173 if (rollback && (!datacsum || noxattr || !packing)) {
3174 fprintf(stderr,
3175 "Usage error: -d, -i, -n options do not apply to rollback\n");
3176 usage_error++;
3179 if (usage_error) {
3180 print_usage();
3181 return 1;
3184 file = argv[optind];
3185 ret = check_mounted(file);
3186 if (ret < 0) {
3187 fprintf(stderr, "Could not check mount status: %s\n",
3188 strerror(-ret));
3189 return 1;
3190 } else if (ret) {
3191 fprintf(stderr, "%s is mounted\n", file);
3192 return 1;
3195 if (rollback) {
3196 ret = do_rollback(file);
3197 } else {
3198 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3199 copylabel, fslabel, progress, features);
3201 if (ret)
3202 return 1;
3203 return 0;