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>
25 #include <sys/types.h>
29 #include <uuid/uuid.h>
30 #include <linux/limits.h>
36 #include "transaction.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
48 * Compatibility code for e2fsprogs 1.41 which doesn't support RO compat flag
50 * Unlike normal RO compat flag, BIGALLOC affects how e2fsprogs check used
51 * space, and btrfs-convert heavily relies on it.
53 #ifdef HAVE_OLD_E2FSPROGS
54 #define EXT2FS_CLUSTER_RATIO(fs) (1)
55 #define EXT2_CLUSTERS_PER_GROUP(s) (EXT2_BLOCKS_PER_GROUP(s))
56 #define EXT2FS_B2C(fs, blk) (blk)
60 uint32_t max_copy_inodes;
61 uint32_t cur_copy_inodes;
62 struct task_info *info;
65 static void *print_copied_inodes(void *p)
67 struct task_ctx *priv = p;
68 const char work_indicator[] = { '.', 'o', 'O', 'o' };
71 task_period_start(priv->info, 1000 /* 1s */);
74 printf("copy inodes [%c] [%10d/%10d]\r",
75 work_indicator[count % 4], priv->cur_copy_inodes,
76 priv->max_copy_inodes);
78 task_period_wait(priv->info);
84 static int after_copied_inodes(void *p)
92 struct btrfs_convert_context;
93 struct btrfs_convert_operations {
95 int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
96 int (*read_used_space)(struct btrfs_convert_context *cctx);
97 int (*copy_inodes)(struct btrfs_convert_context *cctx,
98 struct btrfs_root *root, int datacsum,
99 int packing, int noxattr, struct task_ctx *p);
100 void (*close_fs)(struct btrfs_convert_context *cctx);
103 static void init_convert_context(struct btrfs_convert_context *cctx)
105 cache_tree_init(&cctx->used);
106 cache_tree_init(&cctx->data_chunks);
107 cache_tree_init(&cctx->free);
110 static void clean_convert_context(struct btrfs_convert_context *cctx)
112 free_extent_cache_tree(&cctx->used);
113 free_extent_cache_tree(&cctx->data_chunks);
114 free_extent_cache_tree(&cctx->free);
117 static inline int copy_inodes(struct btrfs_convert_context *cctx,
118 struct btrfs_root *root, int datacsum,
119 int packing, int noxattr, struct task_ctx *p)
121 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
125 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
127 cctx->convert_ops->close_fs(cctx);
131 * Open Ext2fs in readonly mode, read block allocation bitmap and
132 * inode bitmap into memory.
134 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
141 ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
143 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
147 * We need to know exactly the used space, some RO compat flags like
148 * BIGALLOC will affect how used space is present.
149 * So we need manuall check any unsupported RO compat flags
151 ro_feature = ext2_fs->super->s_feature_ro_compat;
152 if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
154 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
155 ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
158 ret = ext2fs_read_inode_bitmap(ext2_fs);
160 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
164 ret = ext2fs_read_block_bitmap(ext2_fs);
166 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
171 * search each block group for a free inode. this set up
172 * uninit block/inode bitmaps appropriately.
175 while (ino <= ext2_fs->super->s_inodes_count) {
177 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
178 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
181 if (!(ext2_fs->super->s_feature_incompat &
182 EXT2_FEATURE_INCOMPAT_FILETYPE)) {
183 fprintf(stderr, "filetype feature is missing\n");
187 cctx->fs_data = ext2_fs;
188 cctx->blocksize = ext2_fs->blocksize;
189 cctx->block_count = ext2_fs->super->s_blocks_count;
190 cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
191 cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
192 cctx->first_data_block = ext2_fs->super->s_first_data_block;
193 cctx->inodes_count = ext2_fs->super->s_inodes_count;
194 cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
197 ext2fs_close(ext2_fs);
201 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
202 unsigned long group_nr, struct cache_tree *used)
204 unsigned long offset;
208 offset = fs->super->s_first_data_block;
209 offset /= EXT2FS_CLUSTER_RATIO(fs);
210 offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
211 for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
212 if (ext2fs_test_bit(i, bitmap)) {
215 start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
216 start *= fs->blocksize;
217 ret = add_merge_cache_extent(used, start,
227 * Read all used ext2 space into cctx->used cache tree
229 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
231 ext2_filsys fs = (ext2_filsys)cctx->fs_data;
232 blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
233 struct cache_tree *used_tree = &cctx->used;
234 char *block_bitmap = NULL;
239 block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
240 /* Shouldn't happen */
241 BUG_ON(!fs->block_map);
243 block_bitmap = malloc(block_nbytes);
247 for (i = 0; i < fs->group_desc_count; i++) {
248 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
249 block_nbytes * 8, block_bitmap);
251 error("fail to get bitmap from ext2, %s",
255 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
257 error("fail to build used space tree, %s",
261 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
268 static void ext2_close_fs(struct btrfs_convert_context *cctx)
270 if (cctx->volume_name) {
271 free(cctx->volume_name);
272 cctx->volume_name = NULL;
274 ext2fs_close(cctx->fs_data);
277 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
282 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
283 offset = btrfs_sb_offset(i);
284 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
286 if (bytenr < offset + BTRFS_STRIPE_LEN &&
287 bytenr + num_bytes > offset)
293 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
294 struct btrfs_root *root,
295 const char *name, size_t name_len,
296 u64 dir, u64 objectid,
297 u8 file_type, u64 index_cnt,
298 struct btrfs_inode_item *inode)
302 struct btrfs_key location = {
303 .objectid = objectid,
305 .type = BTRFS_INODE_ITEM_KEY,
308 ret = btrfs_insert_dir_item(trans, root, name, name_len,
309 dir, &location, file_type, index_cnt);
312 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
313 objectid, dir, index_cnt);
316 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
317 btrfs_set_stack_inode_size(inode, inode_size);
322 struct dir_iterate_data {
323 struct btrfs_trans_handle *trans;
324 struct btrfs_root *root;
325 struct btrfs_inode_item *inode;
332 static u8 filetype_conversion_table[EXT2_FT_MAX] = {
333 [EXT2_FT_UNKNOWN] = BTRFS_FT_UNKNOWN,
334 [EXT2_FT_REG_FILE] = BTRFS_FT_REG_FILE,
335 [EXT2_FT_DIR] = BTRFS_FT_DIR,
336 [EXT2_FT_CHRDEV] = BTRFS_FT_CHRDEV,
337 [EXT2_FT_BLKDEV] = BTRFS_FT_BLKDEV,
338 [EXT2_FT_FIFO] = BTRFS_FT_FIFO,
339 [EXT2_FT_SOCK] = BTRFS_FT_SOCK,
340 [EXT2_FT_SYMLINK] = BTRFS_FT_SYMLINK,
343 static int dir_iterate_proc(ext2_ino_t dir, int entry,
344 struct ext2_dir_entry *dirent,
345 int offset, int blocksize,
346 char *buf,void *priv_data)
351 char dotdot[] = "..";
352 struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
355 name_len = dirent->name_len & 0xFF;
357 objectid = dirent->inode + INO_OFFSET;
358 if (!strncmp(dirent->name, dotdot, name_len)) {
360 BUG_ON(idata->parent != 0);
361 idata->parent = objectid;
365 if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
368 file_type = dirent->name_len >> 8;
369 BUG_ON(file_type > EXT2_FT_SYMLINK);
371 ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
372 name_len, idata->objectid, objectid,
373 filetype_conversion_table[file_type],
374 idata->index_cnt, idata->inode);
376 idata->errcode = ret;
384 static int create_dir_entries(struct btrfs_trans_handle *trans,
385 struct btrfs_root *root, u64 objectid,
386 struct btrfs_inode_item *btrfs_inode,
387 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
391 struct dir_iterate_data data = {
394 .inode = btrfs_inode,
395 .objectid = objectid,
401 err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
402 dir_iterate_proc, &data);
406 if (ret == 0 && data.parent == objectid) {
407 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
408 objectid, objectid, 0);
412 fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
416 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
417 u32 num_bytes, char *buffer)
420 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
422 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
423 if (ret != num_bytes)
432 static int csum_disk_extent(struct btrfs_trans_handle *trans,
433 struct btrfs_root *root,
434 u64 disk_bytenr, u64 num_bytes)
436 u32 blocksize = root->sectorsize;
441 buffer = malloc(blocksize);
444 for (offset = 0; offset < num_bytes; offset += blocksize) {
445 ret = read_disk_extent(root, disk_bytenr + offset,
449 ret = btrfs_csum_file_block(trans,
450 root->fs_info->csum_root,
451 disk_bytenr + num_bytes,
452 disk_bytenr + offset,
461 struct blk_iterate_data {
462 struct btrfs_trans_handle *trans;
463 struct btrfs_root *root;
464 struct btrfs_root *convert_root;
465 struct btrfs_inode_item *inode;
476 static void init_blk_iterate_data(struct blk_iterate_data *data,
477 struct btrfs_trans_handle *trans,
478 struct btrfs_root *root,
479 struct btrfs_inode_item *inode,
480 u64 objectid, int checksum)
482 struct btrfs_key key;
487 data->objectid = objectid;
488 data->first_block = 0;
489 data->disk_block = 0;
490 data->num_blocks = 0;
491 data->boundary = (u64)-1;
492 data->checksum = checksum;
495 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
496 key.type = BTRFS_ROOT_ITEM_KEY;
497 key.offset = (u64)-1;
498 data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
499 /* Impossible as we just opened it before */
500 BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
501 data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
505 * Record a file extent in original filesystem into btrfs one.
506 * The special point is, old disk_block can point to a reserved range.
507 * So here, we don't use disk_block directly but search convert_root
508 * to get the real disk_bytenr.
510 static int record_file_blocks(struct blk_iterate_data *data,
511 u64 file_block, u64 disk_block, u64 num_blocks)
514 struct btrfs_root *root = data->root;
515 struct btrfs_root *convert_root = data->convert_root;
516 struct btrfs_path *path;
517 u64 file_pos = file_block * root->sectorsize;
518 u64 old_disk_bytenr = disk_block * root->sectorsize;
519 u64 num_bytes = num_blocks * root->sectorsize;
520 u64 cur_off = old_disk_bytenr;
522 /* Hole, pass it to record_file_extent directly */
523 if (old_disk_bytenr == 0)
524 return btrfs_record_file_extent(data->trans, root,
525 data->objectid, data->inode, file_pos, 0,
528 path = btrfs_alloc_path();
533 * Search real disk bytenr from convert root
535 while (cur_off < old_disk_bytenr + num_bytes) {
536 struct btrfs_key key;
537 struct btrfs_file_extent_item *fi;
538 struct extent_buffer *node;
540 u64 extent_disk_bytenr;
541 u64 extent_num_bytes;
542 u64 real_disk_bytenr;
545 key.objectid = data->convert_ino;
546 key.type = BTRFS_EXTENT_DATA_KEY;
547 key.offset = cur_off;
549 ret = btrfs_search_slot(NULL, convert_root, &key, path, 0, 0);
553 ret = btrfs_previous_item(convert_root, path,
555 BTRFS_EXTENT_DATA_KEY);
563 node = path->nodes[0];
564 slot = path->slots[0];
565 btrfs_item_key_to_cpu(node, &key, slot);
566 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
567 key.objectid != data->convert_ino ||
568 key.offset > cur_off);
569 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
570 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
571 extent_num_bytes = btrfs_file_extent_disk_num_bytes(node, fi);
572 BUG_ON(cur_off - key.offset >= extent_num_bytes);
573 btrfs_release_path(path);
575 if (extent_disk_bytenr)
576 real_disk_bytenr = cur_off - key.offset +
579 real_disk_bytenr = 0;
580 cur_len = min(key.offset + extent_num_bytes,
581 old_disk_bytenr + num_bytes) - cur_off;
582 ret = btrfs_record_file_extent(data->trans, data->root,
583 data->objectid, data->inode, file_pos,
584 real_disk_bytenr, cur_len);
591 * No need to care about csum
592 * As every byte of old fs image is calculated for csum, no
593 * need to waste CPU cycles now.
596 btrfs_free_path(path);
600 static int block_iterate_proc(u64 disk_block, u64 file_block,
601 struct blk_iterate_data *idata)
606 struct btrfs_root *root = idata->root;
607 struct btrfs_block_group_cache *cache;
608 u64 bytenr = disk_block * root->sectorsize;
610 sb_region = intersect_with_sb(bytenr, root->sectorsize);
611 do_barrier = sb_region || disk_block >= idata->boundary;
612 if ((idata->num_blocks > 0 && do_barrier) ||
613 (file_block > idata->first_block + idata->num_blocks) ||
614 (disk_block != idata->disk_block + idata->num_blocks)) {
615 if (idata->num_blocks > 0) {
616 ret = record_file_blocks(idata, idata->first_block,
621 idata->first_block += idata->num_blocks;
622 idata->num_blocks = 0;
624 if (file_block > idata->first_block) {
625 ret = record_file_blocks(idata, idata->first_block,
626 0, file_block - idata->first_block);
632 bytenr += BTRFS_STRIPE_LEN - 1;
633 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
635 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
637 bytenr = cache->key.objectid + cache->key.offset;
640 idata->first_block = file_block;
641 idata->disk_block = disk_block;
642 idata->boundary = bytenr / root->sectorsize;
649 static int __block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
650 e2_blkcnt_t blockcnt, blk_t ref_block,
651 int ref_offset, void *priv_data)
654 struct blk_iterate_data *idata;
655 idata = (struct blk_iterate_data *)priv_data;
656 ret = block_iterate_proc(*blocknr, blockcnt, idata);
658 idata->errcode = ret;
665 * traverse file's data blocks, record these data blocks as file extents.
667 static int create_file_extents(struct btrfs_trans_handle *trans,
668 struct btrfs_root *root, u64 objectid,
669 struct btrfs_inode_item *btrfs_inode,
670 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
671 int datacsum, int packing)
677 u32 sectorsize = root->sectorsize;
678 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
679 struct blk_iterate_data data;
681 init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
684 err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
685 NULL, __block_iterate_proc, &data);
691 if (packing && data.first_block == 0 && data.num_blocks > 0 &&
692 inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
693 u64 num_bytes = data.num_blocks * sectorsize;
694 u64 disk_bytenr = data.disk_block * sectorsize;
697 buffer = malloc(num_bytes);
700 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
703 if (num_bytes > inode_size)
704 num_bytes = inode_size;
705 ret = btrfs_insert_inline_extent(trans, root, objectid,
706 0, buffer, num_bytes);
709 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
710 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
711 } else if (data.num_blocks > 0) {
712 ret = record_file_blocks(&data, data.first_block,
713 data.disk_block, data.num_blocks);
717 data.first_block += data.num_blocks;
718 last_block = (inode_size + sectorsize - 1) / sectorsize;
719 if (last_block > data.first_block) {
720 ret = record_file_blocks(&data, data.first_block, 0,
721 last_block - data.first_block);
727 fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
731 static int create_symbol_link(struct btrfs_trans_handle *trans,
732 struct btrfs_root *root, u64 objectid,
733 struct btrfs_inode_item *btrfs_inode,
734 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
735 struct ext2_inode *ext2_inode)
739 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
740 if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
741 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
742 ret = create_file_extents(trans, root, objectid, btrfs_inode,
743 ext2_fs, ext2_ino, 1, 1);
744 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
748 pathname = (char *)&(ext2_inode->i_block[0]);
749 BUG_ON(pathname[inode_size] != 0);
750 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
751 pathname, inode_size + 1);
752 btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
757 * Following xattr/acl related codes are based on codes in
758 * fs/ext3/xattr.c and fs/ext3/acl.c
760 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
761 #define EXT2_XATTR_BFIRST(ptr) \
762 ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
763 #define EXT2_XATTR_IHDR(inode) \
764 ((struct ext2_ext_attr_header *) ((void *)(inode) + \
765 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
766 #define EXT2_XATTR_IFIRST(inode) \
767 ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
768 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
770 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
773 struct ext2_ext_attr_entry *next;
775 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
776 next = EXT2_EXT_ATTR_NEXT(entry);
777 if ((void *)next >= end)
784 static int ext2_xattr_check_block(const char *buf, size_t size)
787 struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
789 if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
790 header->h_blocks != 1)
792 error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
796 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
799 size_t value_size = entry->e_value_size;
801 if (entry->e_value_block != 0 || value_size > size ||
802 entry->e_value_offs + value_size > size)
807 #define EXT2_ACL_VERSION 0x0001
809 /* 23.2.5 acl_tag_t values */
811 #define ACL_UNDEFINED_TAG (0x00)
812 #define ACL_USER_OBJ (0x01)
813 #define ACL_USER (0x02)
814 #define ACL_GROUP_OBJ (0x04)
815 #define ACL_GROUP (0x08)
816 #define ACL_MASK (0x10)
817 #define ACL_OTHER (0x20)
819 /* 23.2.7 ACL qualifier constants */
821 #define ACL_UNDEFINED_ID ((id_t)-1)
832 } ext2_acl_entry_short;
838 static inline int ext2_acl_count(size_t size)
841 size -= sizeof(ext2_acl_header);
842 s = size - 4 * sizeof(ext2_acl_entry_short);
844 if (size % sizeof(ext2_acl_entry_short))
846 return size / sizeof(ext2_acl_entry_short);
848 if (s % sizeof(ext2_acl_entry))
850 return s / sizeof(ext2_acl_entry) + 4;
854 #define ACL_EA_VERSION 0x0002
864 acl_ea_entry a_entries[0];
867 static inline size_t acl_ea_size(int count)
869 return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
872 static int ext2_acl_to_xattr(void *dst, const void *src,
873 size_t dst_size, size_t src_size)
876 const void *end = src + src_size;
877 acl_ea_header *ext_acl = (acl_ea_header *)dst;
878 acl_ea_entry *dst_entry = ext_acl->a_entries;
879 ext2_acl_entry *src_entry;
881 if (src_size < sizeof(ext2_acl_header))
883 if (((ext2_acl_header *)src)->a_version !=
884 cpu_to_le32(EXT2_ACL_VERSION))
886 src += sizeof(ext2_acl_header);
887 count = ext2_acl_count(src_size);
891 BUG_ON(dst_size < acl_ea_size(count));
892 ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
893 for (i = 0; i < count; i++, dst_entry++) {
894 src_entry = (ext2_acl_entry *)src;
895 if (src + sizeof(ext2_acl_entry_short) > end)
897 dst_entry->e_tag = src_entry->e_tag;
898 dst_entry->e_perm = src_entry->e_perm;
899 switch (le16_to_cpu(src_entry->e_tag)) {
904 src += sizeof(ext2_acl_entry_short);
905 dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
909 src += sizeof(ext2_acl_entry);
912 dst_entry->e_id = src_entry->e_id;
925 static char *xattr_prefix_table[] = {
927 [2] = "system.posix_acl_access",
928 [3] = "system.posix_acl_default",
933 static int copy_single_xattr(struct btrfs_trans_handle *trans,
934 struct btrfs_root *root, u64 objectid,
935 struct ext2_ext_attr_entry *entry,
936 const void *data, u32 datalen)
941 void *databuf = NULL;
942 char namebuf[XATTR_NAME_MAX + 1];
944 name_index = entry->e_name_index;
945 if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
946 xattr_prefix_table[name_index] == NULL)
948 name_len = strlen(xattr_prefix_table[name_index]) +
950 if (name_len >= sizeof(namebuf))
953 if (name_index == 2 || name_index == 3) {
954 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
955 databuf = malloc(bufsize);
958 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
964 strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
965 strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
966 if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
967 sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
968 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
969 objectid - INO_OFFSET, name_len, namebuf);
972 ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
973 data, datalen, objectid);
979 static int copy_extended_attrs(struct btrfs_trans_handle *trans,
980 struct btrfs_root *root, u64 objectid,
981 struct btrfs_inode_item *btrfs_inode,
982 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
988 u32 block_size = ext2_fs->blocksize;
989 u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
990 struct ext2_inode_large *ext2_inode;
991 struct ext2_ext_attr_entry *entry;
994 char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
996 if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
997 ext2_inode = (struct ext2_inode_large *)inode_buf;
999 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
1003 err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
1006 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
1007 error_message(err));
1012 if (ext2_ino > ext2_fs->super->s_first_ino &&
1013 inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
1014 if (EXT2_GOOD_OLD_INODE_SIZE +
1015 ext2_inode->i_extra_isize > inode_size) {
1019 if (ext2_inode->i_extra_isize != 0 &&
1020 EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
1021 EXT2_EXT_ATTR_MAGIC) {
1027 void *end = (void *)ext2_inode + inode_size;
1028 entry = EXT2_XATTR_IFIRST(ext2_inode);
1029 total = end - (void *)entry;
1030 ret = ext2_xattr_check_names(entry, end);
1033 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1034 ret = ext2_xattr_check_entry(entry, total);
1037 data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
1038 entry->e_value_offs;
1039 datalen = entry->e_value_size;
1040 ret = copy_single_xattr(trans, root, objectid,
1041 entry, data, datalen);
1044 entry = EXT2_EXT_ATTR_NEXT(entry);
1048 if (ext2_inode->i_file_acl == 0)
1051 buffer = malloc(block_size);
1056 err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
1058 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
1059 error_message(err));
1063 ret = ext2_xattr_check_block(buffer, block_size);
1067 entry = EXT2_XATTR_BFIRST(buffer);
1068 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1069 ret = ext2_xattr_check_entry(entry, block_size);
1072 data = buffer + entry->e_value_offs;
1073 datalen = entry->e_value_size;
1074 ret = copy_single_xattr(trans, root, objectid,
1075 entry, data, datalen);
1078 entry = EXT2_EXT_ATTR_NEXT(entry);
1082 if ((void *)ext2_inode != inode_buf)
1086 #define MINORBITS 20
1087 #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
1089 static inline dev_t old_decode_dev(u16 val)
1091 return MKDEV((val >> 8) & 255, val & 255);
1094 static inline dev_t new_decode_dev(u32 dev)
1096 unsigned major = (dev & 0xfff00) >> 8;
1097 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
1098 return MKDEV(major, minor);
1101 static int copy_inode_item(struct btrfs_inode_item *dst,
1102 struct ext2_inode *src, u32 blocksize)
1104 btrfs_set_stack_inode_generation(dst, 1);
1105 btrfs_set_stack_inode_sequence(dst, 0);
1106 btrfs_set_stack_inode_transid(dst, 1);
1107 btrfs_set_stack_inode_size(dst, src->i_size);
1108 btrfs_set_stack_inode_nbytes(dst, 0);
1109 btrfs_set_stack_inode_block_group(dst, 0);
1110 btrfs_set_stack_inode_nlink(dst, src->i_links_count);
1111 btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
1112 btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
1113 btrfs_set_stack_inode_mode(dst, src->i_mode);
1114 btrfs_set_stack_inode_rdev(dst, 0);
1115 btrfs_set_stack_inode_flags(dst, 0);
1116 btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
1117 btrfs_set_stack_timespec_nsec(&dst->atime, 0);
1118 btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
1119 btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
1120 btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
1121 btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
1122 btrfs_set_stack_timespec_sec(&dst->otime, 0);
1123 btrfs_set_stack_timespec_nsec(&dst->otime, 0);
1125 if (S_ISDIR(src->i_mode)) {
1126 btrfs_set_stack_inode_size(dst, 0);
1127 btrfs_set_stack_inode_nlink(dst, 1);
1129 if (S_ISREG(src->i_mode)) {
1130 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
1133 if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
1134 !S_ISLNK(src->i_mode)) {
1135 if (src->i_block[0]) {
1136 btrfs_set_stack_inode_rdev(dst,
1137 old_decode_dev(src->i_block[0]));
1139 btrfs_set_stack_inode_rdev(dst,
1140 new_decode_dev(src->i_block[1]));
1143 memset(&dst->reserved, 0, sizeof(dst->reserved));
1149 * copy a single inode. do all the required works, such as cloning
1150 * inode item, creating file extents and creating directory entries.
1152 static int copy_single_inode(struct btrfs_trans_handle *trans,
1153 struct btrfs_root *root, u64 objectid,
1154 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1155 struct ext2_inode *ext2_inode,
1156 int datacsum, int packing, int noxattr)
1159 struct btrfs_inode_item btrfs_inode;
1161 if (ext2_inode->i_links_count == 0)
1164 copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
1165 if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
1166 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
1167 BTRFS_INODE_NODATASUM;
1168 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
1171 switch (ext2_inode->i_mode & S_IFMT) {
1173 ret = create_file_extents(trans, root, objectid, &btrfs_inode,
1174 ext2_fs, ext2_ino, datacsum, packing);
1177 ret = create_dir_entries(trans, root, objectid, &btrfs_inode,
1181 ret = create_symbol_link(trans, root, objectid, &btrfs_inode,
1182 ext2_fs, ext2_ino, ext2_inode);
1192 ret = copy_extended_attrs(trans, root, objectid, &btrfs_inode,
1197 return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
1201 * scan ext2's inode bitmap and copy all used inodes.
1203 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
1204 struct btrfs_root *root,
1205 int datacsum, int packing, int noxattr, struct task_ctx *p)
1207 ext2_filsys ext2_fs = cctx->fs_data;
1210 ext2_inode_scan ext2_scan;
1211 struct ext2_inode ext2_inode;
1212 ext2_ino_t ext2_ino;
1214 struct btrfs_trans_handle *trans;
1216 trans = btrfs_start_transaction(root, 1);
1219 err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
1221 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
1224 while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
1226 /* no more inodes */
1229 /* skip special inode in ext2fs */
1230 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
1231 ext2_ino != EXT2_ROOT_INO)
1233 objectid = ext2_ino + INO_OFFSET;
1234 ret = copy_single_inode(trans, root,
1235 objectid, ext2_fs, ext2_ino,
1236 &ext2_inode, datacsum, packing,
1238 p->cur_copy_inodes++;
1241 if (trans->blocks_used >= 4096) {
1242 ret = btrfs_commit_transaction(trans, root);
1244 trans = btrfs_start_transaction(root, 1);
1249 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
1252 ret = btrfs_commit_transaction(trans, root);
1254 ext2fs_close_inode_scan(ext2_scan);
1259 static int create_image_file_range(struct btrfs_trans_handle *trans,
1260 struct btrfs_root *root,
1261 struct cache_tree *used,
1262 struct btrfs_inode_item *inode,
1263 u64 ino, u64 bytenr, u64 *ret_len,
1266 struct cache_extent *cache;
1267 struct btrfs_block_group_cache *bg_cache;
1273 BUG_ON(bytenr != round_down(bytenr, root->sectorsize));
1274 BUG_ON(len != round_down(len, root->sectorsize));
1275 len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
1278 * Skip sb ranges first
1279 * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
1281 * Or we will insert a hole into current image file, and later
1282 * migrate block will fail as there is already a file extent.
1284 if (bytenr < 1024 * 1024) {
1285 *ret_len = 1024 * 1024 - bytenr;
1288 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1289 u64 cur = btrfs_sb_offset(i);
1291 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
1292 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
1296 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1297 u64 cur = btrfs_sb_offset(i);
1301 * |----range-------|
1302 * May still need to go through file extent inserts
1304 if (bytenr < cur && bytenr + len >= cur) {
1305 len = min_t(u64, len, cur - bytenr);
1311 * Drop out, no need to insert anything
1313 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
1314 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
1319 cache = search_cache_extent(used, bytenr);
1321 if (cache->start <= bytenr) {
1323 * |///////Used///////|
1327 len = min_t(u64, len, cache->start + cache->size -
1329 disk_bytenr = bytenr;
1336 len = min(len, cache->start - bytenr);
1351 /* Check if the range is in a data block group */
1352 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
1355 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
1358 /* The extent should never cross block group boundary */
1359 len = min_t(u64, len, bg_cache->key.objectid +
1360 bg_cache->key.offset - bytenr);
1363 BUG_ON(len != round_down(len, root->sectorsize));
1364 ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
1370 ret = csum_disk_extent(trans, root, bytenr, len);
1377 * Relocate old fs data in one reserved ranges
1379 * Since all old fs data in reserved range is not covered by any chunk nor
1380 * data extent, we don't need to handle any reference but add new
1381 * extent/reference, which makes codes more clear
1383 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
1384 struct btrfs_root *root,
1385 struct cache_tree *used,
1386 struct btrfs_inode_item *inode, int fd,
1387 u64 ino, u64 start, u64 len, int datacsum)
1389 u64 cur_off = start;
1391 u64 hole_start = start;
1393 struct cache_extent *cache;
1394 struct btrfs_key key;
1395 struct extent_buffer *eb;
1398 while (cur_off < start + len) {
1399 cache = lookup_cache_extent(used, cur_off, cur_len);
1402 cur_off = max(cache->start, cur_off);
1403 cur_len = min(cache->start + cache->size, start + len) -
1405 BUG_ON(cur_len < root->sectorsize);
1407 /* reserve extent for the data */
1408 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
1413 eb = malloc(sizeof(*eb) + cur_len);
1419 ret = pread(fd, eb->data, cur_len, cur_off);
1420 if (ret < cur_len) {
1421 ret = (ret < 0 ? ret : -EIO);
1425 eb->start = key.objectid;
1426 eb->len = key.offset;
1428 /* Write the data */
1429 ret = write_and_map_eb(trans, root, eb);
1434 /* Now handle extent item and file extent things */
1435 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
1436 key.objectid, key.offset);
1439 /* Finally, insert csum items */
1441 ret = csum_disk_extent(trans, root, key.objectid,
1444 /* Don't forget to insert hole */
1445 hole_len = cur_off - hole_start;
1447 ret = btrfs_record_file_extent(trans, root, ino, inode,
1448 hole_start, 0, hole_len);
1453 cur_off += key.offset;
1454 hole_start = cur_off;
1455 cur_len = start + len - cur_off;
1458 if (start + len - hole_start > 0)
1459 ret = btrfs_record_file_extent(trans, root, ino, inode,
1460 hole_start, 0, start + len - hole_start);
1465 * Relocate the used ext2 data in reserved ranges
1467 * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
1468 * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
1470 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
1471 struct btrfs_root *root,
1472 struct cache_tree *used,
1473 struct btrfs_inode_item *inode, int fd,
1474 u64 ino, u64 total_bytes, int datacsum)
1482 cur_len = 1024 * 1024;
1483 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
1484 cur_off, cur_len, datacsum);
1488 /* second sb(fisrt sb is included in 0~1M) */
1489 cur_off = btrfs_sb_offset(1);
1490 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
1491 if (cur_off > total_bytes)
1493 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
1494 cur_off, cur_len, datacsum);
1499 cur_off = btrfs_sb_offset(2);
1500 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
1501 if (cur_off > total_bytes)
1503 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
1504 cur_off, cur_len, datacsum);
1508 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
1512 * Create the fs image file of old filesystem.
1514 * This is completely fs independent as we have cctx->used, only
1515 * need to create file extents pointing to all the positions.
1517 static int create_image(struct btrfs_root *root,
1518 struct btrfs_mkfs_config *cfg,
1519 struct btrfs_convert_context *cctx, int fd,
1520 u64 size, char *name, int datacsum)
1522 struct btrfs_inode_item buf;
1523 struct btrfs_trans_handle *trans;
1524 struct btrfs_path *path = NULL;
1525 struct btrfs_key key;
1526 struct cache_extent *cache;
1527 struct cache_tree used_tmp;
1530 u64 flags = BTRFS_INODE_READONLY;
1534 flags |= BTRFS_INODE_NODATASUM;
1536 trans = btrfs_start_transaction(root, 1);
1540 cache_tree_init(&used_tmp);
1542 ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
1546 ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
1549 ret = btrfs_change_inode_flags(trans, root, ino, flags);
1552 ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1553 strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1557 path = btrfs_alloc_path();
1563 key.type = BTRFS_INODE_ITEM_KEY;
1566 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1568 ret = (ret > 0 ? -ENOENT : ret);
1571 read_extent_buffer(path->nodes[0], &buf,
1572 btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
1574 btrfs_release_path(path);
1577 * Create a new used space cache, which doesn't contain the reserved
1580 for (cache = first_cache_extent(&cctx->used); cache;
1581 cache = next_cache_extent(cache)) {
1582 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
1586 ret = wipe_reserved_ranges(&used_tmp, 0, 0);
1591 * Start from 1M, as 0~1M is reserved, and create_image_file_range()
1592 * can't handle bytenr 0(will consider it as a hole)
1595 while (cur < size) {
1596 u64 len = size - cur;
1598 ret = create_image_file_range(trans, root, &used_tmp,
1599 &buf, ino, cur, &len, datacsum);
1604 /* Handle the reserved ranges */
1605 ret = migrate_reserved_ranges(trans, root, &cctx->used, &buf, fd, ino,
1606 cfg->num_bytes, datacsum);
1610 key.type = BTRFS_INODE_ITEM_KEY;
1612 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1614 ret = (ret > 0 ? -ENOENT : ret);
1617 btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1618 write_extent_buffer(path->nodes[0], &buf,
1619 btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
1622 free_extent_cache_tree(&used_tmp);
1623 btrfs_free_path(path);
1624 btrfs_commit_transaction(trans, root);
1628 static struct btrfs_root * link_subvol(struct btrfs_root *root,
1629 const char *base, u64 root_objectid)
1631 struct btrfs_trans_handle *trans;
1632 struct btrfs_fs_info *fs_info = root->fs_info;
1633 struct btrfs_root *tree_root = fs_info->tree_root;
1634 struct btrfs_root *new_root = NULL;
1635 struct btrfs_path *path;
1636 struct btrfs_inode_item *inode_item;
1637 struct extent_buffer *leaf;
1638 struct btrfs_key key;
1639 u64 dirid = btrfs_root_dirid(&root->root_item);
1641 char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1647 if (len == 0 || len > BTRFS_NAME_LEN)
1650 path = btrfs_alloc_path();
1653 key.objectid = dirid;
1654 key.type = BTRFS_DIR_INDEX_KEY;
1655 key.offset = (u64)-1;
1657 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1660 if (path->slots[0] > 0) {
1662 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1663 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1664 index = key.offset + 1;
1666 btrfs_release_path(path);
1668 trans = btrfs_start_transaction(root, 1);
1671 key.objectid = dirid;
1673 key.type = BTRFS_INODE_ITEM_KEY;
1675 ret = btrfs_lookup_inode(trans, root, path, &key, 1);
1677 leaf = path->nodes[0];
1678 inode_item = btrfs_item_ptr(leaf, path->slots[0],
1679 struct btrfs_inode_item);
1681 key.objectid = root_objectid;
1682 key.offset = (u64)-1;
1683 key.type = BTRFS_ROOT_ITEM_KEY;
1685 memcpy(buf, base, len);
1686 for (i = 0; i < 1024; i++) {
1687 ret = btrfs_insert_dir_item(trans, root, buf, len,
1688 dirid, &key, BTRFS_FT_DIR, index);
1691 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1692 if (len < 1 || len > BTRFS_NAME_LEN) {
1700 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1701 btrfs_inode_size(leaf, inode_item));
1702 btrfs_mark_buffer_dirty(leaf);
1703 btrfs_release_path(path);
1705 /* add the backref first */
1706 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1707 BTRFS_ROOT_BACKREF_KEY,
1708 root->root_key.objectid,
1709 dirid, index, buf, len);
1712 /* now add the forward ref */
1713 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1714 BTRFS_ROOT_REF_KEY, root_objectid,
1715 dirid, index, buf, len);
1717 ret = btrfs_commit_transaction(trans, root);
1720 new_root = btrfs_read_fs_root(fs_info, &key);
1721 if (IS_ERR(new_root))
1724 btrfs_free_path(path);
1728 static int create_subvol(struct btrfs_trans_handle *trans,
1729 struct btrfs_root *root, u64 root_objectid)
1731 struct extent_buffer *tmp;
1732 struct btrfs_root *new_root;
1733 struct btrfs_key key;
1734 struct btrfs_root_item root_item;
1737 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1741 memcpy(&root_item, &root->root_item, sizeof(root_item));
1742 btrfs_set_root_bytenr(&root_item, tmp->start);
1743 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1744 btrfs_set_root_generation(&root_item, trans->transid);
1745 free_extent_buffer(tmp);
1747 key.objectid = root_objectid;
1748 key.type = BTRFS_ROOT_ITEM_KEY;
1749 key.offset = trans->transid;
1750 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1753 key.offset = (u64)-1;
1754 new_root = btrfs_read_fs_root(root->fs_info, &key);
1755 BUG_ON(!new_root || IS_ERR(new_root));
1757 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1764 * New make_btrfs() has handle system and meta chunks quite well.
1765 * So only need to add remaining data chunks.
1767 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1768 struct btrfs_fs_info *fs_info,
1769 struct btrfs_mkfs_config *cfg,
1770 struct btrfs_convert_context *cctx)
1772 struct btrfs_root *extent_root = fs_info->extent_root;
1773 struct cache_tree *data_chunks = &cctx->data_chunks;
1774 struct cache_extent *cache;
1779 * Don't create data chunk over 10% of the convert device
1780 * And for single chunk, don't create chunk larger than 1G.
1782 max_chunk_size = cfg->num_bytes / 10;
1783 max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1784 max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1786 for (cache = first_cache_extent(data_chunks); cache;
1787 cache = next_cache_extent(cache)) {
1788 u64 cur = cache->start;
1790 while (cur < cache->start + cache->size) {
1792 u64 cur_backup = cur;
1794 len = min(max_chunk_size,
1795 cache->start + cache->size - cur);
1796 ret = btrfs_alloc_data_chunk(trans, extent_root,
1798 BTRFS_BLOCK_GROUP_DATA, 1);
1801 ret = btrfs_make_block_group(trans, extent_root, 0,
1802 BTRFS_BLOCK_GROUP_DATA,
1803 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1814 * Init the temp btrfs to a operational status.
1816 * It will fix the extent usage accounting(XXX: Do we really need?) and
1817 * insert needed data chunks, to ensure all old fs data extents are covered
1818 * by DATA chunks, preventing wrong chunks are allocated.
1820 * And also create convert image subvolume and relocation tree.
1821 * (XXX: Not need again?)
1822 * But the convert image subvolume is *NOT* linked to fs tree yet.
1824 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1825 struct btrfs_convert_context *cctx, int datacsum,
1826 int packing, int noxattr)
1828 struct btrfs_key location;
1829 struct btrfs_trans_handle *trans;
1830 struct btrfs_fs_info *fs_info = root->fs_info;
1834 * Don't alloc any metadata/system chunk, as we don't want
1835 * any meta/sys chunk allcated before all data chunks are inserted.
1836 * Or we screw up the chunk layout just like the old implement.
1838 fs_info->avoid_sys_chunk_alloc = 1;
1839 fs_info->avoid_meta_chunk_alloc = 1;
1840 trans = btrfs_start_transaction(root, 1);
1842 ret = btrfs_fix_block_accounting(trans, root);
1845 ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1848 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1849 BTRFS_ROOT_TREE_DIR_OBJECTID);
1852 memcpy(&location, &root->root_key, sizeof(location));
1853 location.offset = (u64)-1;
1854 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1855 btrfs_super_root_dir(fs_info->super_copy),
1856 &location, BTRFS_FT_DIR, 0);
1859 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1861 btrfs_super_root_dir(fs_info->super_copy), 0);
1864 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1865 BTRFS_FIRST_FREE_OBJECTID);
1867 /* subvol for fs image file */
1868 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1871 /* subvol for data relocation tree */
1872 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1876 ret = btrfs_commit_transaction(trans, root);
1877 fs_info->avoid_sys_chunk_alloc = 0;
1878 fs_info->avoid_meta_chunk_alloc = 0;
1884 * Migrate super block to its default position and zero 0 ~ 16k
1886 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
1889 struct extent_buffer *buf;
1890 struct btrfs_super_block *super;
1894 BUG_ON(sectorsize < sizeof(*super));
1895 buf = malloc(sizeof(*buf) + sectorsize);
1899 buf->len = sectorsize;
1900 ret = pread(fd, buf->data, sectorsize, old_bytenr);
1901 if (ret != sectorsize)
1904 super = (struct btrfs_super_block *)buf->data;
1905 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1906 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1908 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1909 ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1910 if (ret != sectorsize)
1917 memset(buf->data, 0, sectorsize);
1918 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1919 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1920 if (len > sectorsize)
1922 ret = pwrite(fd, buf->data, len, bytenr);
1924 fprintf(stderr, "unable to zero fill device\n");
1938 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1940 struct btrfs_chunk *chunk;
1941 struct btrfs_disk_key *key;
1942 u32 sectorsize = btrfs_super_sectorsize(super);
1944 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1945 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1946 sizeof(struct btrfs_disk_key));
1948 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1949 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1950 btrfs_set_disk_key_offset(key, 0);
1952 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1953 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1954 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1955 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1956 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1957 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1958 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1959 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1960 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1961 chunk->stripe.devid = super->dev_item.devid;
1962 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1963 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1964 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1968 static const struct btrfs_convert_operations ext2_convert_ops = {
1970 .open_fs = ext2_open_fs,
1971 .read_used_space = ext2_read_used_space,
1972 .copy_inodes = ext2_copy_inodes,
1973 .close_fs = ext2_close_fs,
1976 static const struct btrfs_convert_operations *convert_operations[] = {
1980 static int convert_open_fs(const char *devname,
1981 struct btrfs_convert_context *cctx)
1985 memset(cctx, 0, sizeof(*cctx));
1987 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1988 int ret = convert_operations[i]->open_fs(cctx, devname);
1991 cctx->convert_ops = convert_operations[i];
1996 fprintf(stderr, "No file system found to convert.\n");
2001 * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
2002 * handle wiping a range that exists in cache.
2004 static int _expand_extent_cache(struct cache_tree *tree,
2005 struct cache_extent *entry,
2006 u64 min_stripe_size, int backward)
2008 struct cache_extent *ce;
2011 if (entry->size >= min_stripe_size)
2013 diff = min_stripe_size - entry->size;
2016 ce = prev_cache_extent(entry);
2019 if (ce->start + ce->size >= entry->start - diff) {
2020 /* Directly merge with previous extent */
2021 ce->size = entry->start + entry->size - ce->start;
2022 remove_cache_extent(tree, entry);
2027 /* No overlap, normal extent */
2028 if (entry->start < diff) {
2029 error("cannot find space for data chunk layout");
2032 entry->start -= diff;
2033 entry->size += diff;
2036 ce = next_cache_extent(entry);
2039 if (entry->start + entry->size + diff >= ce->start) {
2040 /* Directly merge with next extent */
2041 entry->size = ce->start + ce->size - entry->start;
2042 remove_cache_extent(tree, ce);
2047 entry->size += diff;
2052 * Remove one reserve range from given cache tree
2053 * if min_stripe_size is non-zero, it will ensure for split case,
2054 * all its split cache extent is no smaller than @min_strip_size / 2.
2056 static int wipe_one_reserved_range(struct cache_tree *tree,
2057 u64 start, u64 len, u64 min_stripe_size,
2060 struct cache_extent *cache;
2063 BUG_ON(ensure_size && min_stripe_size == 0);
2065 * The logical here is simplified to handle special cases only
2066 * So we don't need to consider merge case for ensure_size
2068 BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
2069 min_stripe_size / 2 < BTRFS_STRIPE_LEN));
2071 /* Also, wipe range should already be aligned */
2072 BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
2073 start + len != round_up(start + len, BTRFS_STRIPE_LEN));
2075 min_stripe_size /= 2;
2077 cache = lookup_cache_extent(tree, start, len);
2081 if (start <= cache->start) {
2083 * |--------cache---------|
2086 BUG_ON(start + len <= cache->start);
2089 * The wipe size is smaller than min_stripe_size / 2,
2090 * so the result length should still meet min_stripe_size
2091 * And no need to do alignment
2093 cache->size -= (start + len - cache->start);
2094 if (cache->size == 0) {
2095 remove_cache_extent(tree, cache);
2100 BUG_ON(ensure_size && cache->size < min_stripe_size);
2102 cache->start = start + len;
2104 } else if (start > cache->start && start + len < cache->start +
2107 * |-------cache-----|
2110 u64 old_start = cache->start;
2111 u64 old_len = cache->size;
2112 u64 insert_start = start + len;
2115 cache->size = start - cache->start;
2116 /* Expand the leading half part if needed */
2117 if (ensure_size && cache->size < min_stripe_size) {
2118 ret = _expand_extent_cache(tree, cache,
2119 min_stripe_size, 1);
2124 /* And insert the new one */
2125 insert_len = old_start + old_len - start - len;
2126 ret = add_merge_cache_extent(tree, insert_start, insert_len);
2130 /* Expand the last half part if needed */
2131 if (ensure_size && insert_len < min_stripe_size) {
2132 cache = lookup_cache_extent(tree, insert_start,
2134 if (!cache || cache->start != insert_start ||
2135 cache->size != insert_len)
2137 ret = _expand_extent_cache(tree, cache,
2138 min_stripe_size, 0);
2146 * Wipe len should be small enough and no need to expand the
2149 cache->size = start - cache->start;
2150 BUG_ON(ensure_size && cache->size < min_stripe_size);
2155 * Remove reserved ranges from given cache_tree
2157 * It will remove the following ranges
2159 * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
2160 * 3) 3rd superblock, +64K
2162 * @min_stripe must be given for safety check
2163 * and if @ensure_size is given, it will ensure affected cache_extent will be
2164 * larger than min_stripe_size
2166 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
2171 ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
2175 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
2176 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2179 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
2180 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
2184 static int calculate_available_space(struct btrfs_convert_context *cctx)
2186 struct cache_tree *used = &cctx->used;
2187 struct cache_tree *data_chunks = &cctx->data_chunks;
2188 struct cache_tree *free = &cctx->free;
2189 struct cache_extent *cache;
2192 * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
2193 * works without need to consider overlap
2195 u64 min_stripe_size = 2 * 16 * 1024 * 1024;
2198 /* Calculate data_chunks */
2199 for (cache = first_cache_extent(used); cache;
2200 cache = next_cache_extent(cache)) {
2203 if (cache->start + cache->size < cur_off)
2205 if (cache->start > cur_off + min_stripe_size)
2206 cur_off = cache->start;
2207 cur_len = max(cache->start + cache->size - cur_off,
2209 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
2215 * remove reserved ranges, so we won't ever bother relocating an old
2216 * filesystem extent to other place.
2218 ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
2224 * Calculate free space
2225 * Always round up the start bytenr, to avoid metadata extent corss
2226 * stripe boundary, as later mkfs_convert() won't have all the extent
2229 for (cache = first_cache_extent(data_chunks); cache;
2230 cache = next_cache_extent(cache)) {
2231 if (cache->start < cur_off)
2233 if (cache->start > cur_off) {
2237 len = cache->start - round_up(cur_off,
2239 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2241 ret = add_merge_cache_extent(free, insert_start, len);
2245 cur_off = cache->start + cache->size;
2247 /* Don't forget the last range */
2248 if (cctx->total_bytes > cur_off) {
2249 u64 len = cctx->total_bytes - cur_off;
2252 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
2254 ret = add_merge_cache_extent(free, insert_start, len);
2259 /* Remove reserved bytes */
2260 ret = wipe_reserved_ranges(free, min_stripe_size, 0);
2265 * Read used space, and since we have the used space,
2266 * calcuate data_chunks and free for later mkfs
2268 static int convert_read_used_space(struct btrfs_convert_context *cctx)
2272 ret = cctx->convert_ops->read_used_space(cctx);
2276 ret = calculate_available_space(cctx);
2280 static int do_convert(const char *devname, int datacsum, int packing,
2281 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
2282 int progress, u64 features)
2289 struct btrfs_root *root;
2290 struct btrfs_root *image_root;
2291 struct btrfs_convert_context cctx;
2292 struct btrfs_key key;
2293 char *subvol_name = NULL;
2294 struct task_ctx ctx;
2295 char features_buf[64];
2296 struct btrfs_mkfs_config mkfs_cfg;
2298 init_convert_context(&cctx);
2299 ret = convert_open_fs(devname, &cctx);
2302 ret = convert_read_used_space(&cctx);
2306 blocksize = cctx.blocksize;
2307 total_bytes = (u64)blocksize * (u64)cctx.block_count;
2308 if (blocksize < 4096) {
2309 fprintf(stderr, "block size is too small\n");
2312 if (btrfs_check_nodesize(nodesize, blocksize, features))
2314 fd = open(devname, O_RDWR);
2316 fprintf(stderr, "unable to open %s\n", devname);
2319 btrfs_parse_features_to_string(features_buf, features);
2320 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2321 strcat(features_buf, " (default)");
2323 printf("create btrfs filesystem:\n");
2324 printf("\tblocksize: %u\n", blocksize);
2325 printf("\tnodesize: %u\n", nodesize);
2326 printf("\tfeatures: %s\n", features_buf);
2328 mkfs_cfg.label = cctx.volume_name;
2329 mkfs_cfg.num_bytes = total_bytes;
2330 mkfs_cfg.nodesize = nodesize;
2331 mkfs_cfg.sectorsize = blocksize;
2332 mkfs_cfg.stripesize = blocksize;
2333 mkfs_cfg.features = features;
2334 /* New convert need these space */
2335 mkfs_cfg.fs_uuid = malloc(BTRFS_UUID_UNPARSED_SIZE);
2336 mkfs_cfg.chunk_uuid = malloc(BTRFS_UUID_UNPARSED_SIZE);
2337 *(mkfs_cfg.fs_uuid) = '\0';
2338 *(mkfs_cfg.chunk_uuid) = '\0';
2340 ret = make_btrfs(fd, &mkfs_cfg, &cctx);
2342 fprintf(stderr, "unable to create initial ctree: %s\n",
2347 root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
2350 fprintf(stderr, "unable to open ctree\n");
2353 ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
2355 fprintf(stderr, "unable to setup the root tree\n");
2359 printf("creating %s image file.\n", cctx.convert_ops->name);
2360 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2362 fprintf(stderr, "error allocating subvolume name: %s_saved\n",
2363 cctx.convert_ops->name);
2366 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2367 key.offset = (u64)-1;
2368 key.type = BTRFS_ROOT_ITEM_KEY;
2369 image_root = btrfs_read_fs_root(root->fs_info, &key);
2371 fprintf(stderr, "unable to create subvol\n");
2374 ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
2375 mkfs_cfg.num_bytes, "image", datacsum);
2377 fprintf(stderr, "error during create_image %d\n", ret);
2381 printf("creating btrfs metadata.\n");
2382 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2383 ctx.cur_copy_inodes = 0;
2386 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
2388 task_start(ctx.info);
2390 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2392 fprintf(stderr, "error during copy_inodes %d\n", ret);
2396 task_stop(ctx.info);
2397 task_deinit(ctx.info);
2400 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2404 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2405 if (copylabel == 1) {
2406 __strncpy_null(root->fs_info->super_copy->label,
2407 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2408 fprintf(stderr, "copy label '%s'\n",
2409 root->fs_info->super_copy->label);
2410 } else if (copylabel == -1) {
2411 strcpy(root->fs_info->super_copy->label, fslabel);
2412 fprintf(stderr, "set label to '%s'\n", fslabel);
2415 ret = close_ctree(root);
2417 fprintf(stderr, "error during close_ctree %d\n", ret);
2420 convert_close_fs(&cctx);
2421 clean_convert_context(&cctx);
2424 * If this step succeed, we get a mountable btrfs. Otherwise
2425 * the source fs is left unchanged.
2427 ret = migrate_super_block(fd, mkfs_cfg.super_bytenr, blocksize);
2429 fprintf(stderr, "unable to migrate super block\n");
2434 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2436 fprintf(stderr, "unable to open ctree\n");
2441 printf("conversion complete.\n");
2444 clean_convert_context(&cctx);
2449 "WARNING: an error occurred during chunk mapping fixup, filesystem mountable but not finalized\n");
2451 fprintf(stderr, "conversion aborted\n");
2456 * Check if a non 1:1 mapped chunk can be rolled back.
2457 * For new convert, it's OK while for old convert it's not.
2459 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
2461 struct btrfs_block_group_cache *bg;
2462 struct btrfs_key key;
2463 struct btrfs_path path;
2464 struct btrfs_root *extent_root = fs_info->extent_root;
2469 bg = btrfs_lookup_first_block_group(fs_info, bytenr);
2472 bg_start = bg->key.objectid;
2473 bg_end = bg->key.objectid + bg->key.offset;
2475 key.objectid = bg_end;
2476 key.type = BTRFS_METADATA_ITEM_KEY;
2478 btrfs_init_path(&path);
2480 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2485 struct btrfs_extent_item *ei;
2487 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
2495 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2496 if (key.type == BTRFS_METADATA_ITEM_KEY)
2498 /* Now it's EXTENT_ITEM_KEY only */
2499 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
2500 struct btrfs_extent_item);
2502 * Found data extent, means this is old convert must follow 1:1
2505 if (btrfs_extent_flags(path.nodes[0], ei)
2506 & BTRFS_EXTENT_FLAG_DATA) {
2511 btrfs_release_path(&path);
2515 static int may_rollback(struct btrfs_root *root)
2517 struct btrfs_fs_info *info = root->fs_info;
2518 struct btrfs_multi_bio *multi = NULL;
2526 if (btrfs_super_num_devices(info->super_copy) != 1)
2529 bytenr = BTRFS_SUPER_INFO_OFFSET;
2530 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2533 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2534 &length, &multi, 0, NULL);
2536 if (ret == -ENOENT) {
2537 /* removed block group at the tail */
2538 if (length == (u64)-1)
2541 /* removed block group in the middle */
2547 num_stripes = multi->num_stripes;
2548 physical = multi->stripes[0].physical;
2551 if (num_stripes != 1) {
2552 error("num stripes for bytenr %llu is not 1", bytenr);
2557 * Extra check for new convert, as metadata chunk from new
2558 * convert is much more free than old convert, it doesn't need
2559 * to do 1:1 mapping.
2561 if (physical != bytenr) {
2563 * Check if it's a metadata chunk and has only metadata
2566 ret = may_rollback_chunk(info, bytenr);
2572 if (bytenr >= total_bytes)
2580 static int do_rollback(const char *devname)
2585 struct btrfs_root *root;
2586 struct btrfs_root *image_root;
2587 struct btrfs_root *chunk_root;
2588 struct btrfs_dir_item *dir;
2589 struct btrfs_inode_item *inode;
2590 struct btrfs_file_extent_item *fi;
2591 struct btrfs_trans_handle *trans;
2592 struct extent_buffer *leaf;
2593 struct btrfs_block_group_cache *cache1;
2594 struct btrfs_block_group_cache *cache2;
2595 struct btrfs_key key;
2596 struct btrfs_path path;
2597 struct extent_io_tree io_tree;
2612 extent_io_tree_init(&io_tree);
2614 fd = open(devname, O_RDWR);
2616 fprintf(stderr, "unable to open %s\n", devname);
2619 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2621 fprintf(stderr, "unable to open ctree\n");
2624 ret = may_rollback(root);
2626 fprintf(stderr, "unable to do rollback\n");
2630 sectorsize = root->sectorsize;
2631 buf = malloc(sectorsize);
2633 fprintf(stderr, "unable to allocate memory\n");
2637 btrfs_init_path(&path);
2639 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2640 key.type = BTRFS_ROOT_BACKREF_KEY;
2641 key.offset = BTRFS_FS_TREE_OBJECTID;
2642 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2644 btrfs_release_path(&path);
2647 "ERROR: unable to convert ext2 image subvolume, is it deleted?\n");
2649 } else if (ret < 0) {
2651 "ERROR: unable to open ext2_saved, id=%llu: %s\n",
2652 (unsigned long long)key.objectid, strerror(-ret));
2656 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2657 key.type = BTRFS_ROOT_ITEM_KEY;
2658 key.offset = (u64)-1;
2659 image_root = btrfs_read_fs_root(root->fs_info, &key);
2660 if (!image_root || IS_ERR(image_root)) {
2661 fprintf(stderr, "unable to open subvol %llu\n",
2662 (unsigned long long)key.objectid);
2667 root_dir = btrfs_root_dirid(&root->root_item);
2668 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2669 root_dir, name, strlen(name), 0);
2670 if (!dir || IS_ERR(dir)) {
2671 fprintf(stderr, "unable to find file %s\n", name);
2674 leaf = path.nodes[0];
2675 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2676 btrfs_release_path(&path);
2678 objectid = key.objectid;
2680 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2682 fprintf(stderr, "unable to find inode item\n");
2685 leaf = path.nodes[0];
2686 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2687 total_bytes = btrfs_inode_size(leaf, inode);
2688 btrfs_release_path(&path);
2690 key.objectid = objectid;
2692 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
2693 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2695 fprintf(stderr, "unable to find first file extent\n");
2696 btrfs_release_path(&path);
2700 /* build mapping tree for the relocated blocks */
2701 for (offset = 0; offset < total_bytes; ) {
2702 leaf = path.nodes[0];
2703 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2704 ret = btrfs_next_leaf(root, &path);
2710 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2711 if (key.objectid != objectid || key.offset != offset ||
2712 btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2715 fi = btrfs_item_ptr(leaf, path.slots[0],
2716 struct btrfs_file_extent_item);
2717 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2719 if (btrfs_file_extent_compression(leaf, fi) ||
2720 btrfs_file_extent_encryption(leaf, fi) ||
2721 btrfs_file_extent_other_encoding(leaf, fi))
2724 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2725 /* skip holes and direct mapped extents */
2726 if (bytenr == 0 || bytenr == offset)
2729 bytenr += btrfs_file_extent_offset(leaf, fi);
2730 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2732 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2733 cache2 = btrfs_lookup_block_group(root->fs_info,
2734 offset + num_bytes - 1);
2736 * Here we must take consideration of old and new convert
2738 * For old convert case, sign, there is no consist chunk type
2739 * that will cover the extent. META/DATA/SYS are all possible.
2740 * Just ensure relocate one is in SYS chunk.
2741 * For new convert case, they are all covered by DATA chunk.
2743 * So, there is not valid chunk type check for it now.
2745 if (cache1 != cache2)
2748 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2749 EXTENT_LOCKED, GFP_NOFS);
2750 set_state_private(&io_tree, offset, bytenr);
2752 offset += btrfs_file_extent_num_bytes(leaf, fi);
2755 btrfs_release_path(&path);
2757 if (offset < total_bytes) {
2758 fprintf(stderr, "unable to build extent mapping\n");
2759 fprintf(stderr, "converted filesystem after balance is unable to rollback\n");
2763 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2764 first_free &= ~((u64)sectorsize - 1);
2765 /* backup for extent #0 should exist */
2766 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2767 fprintf(stderr, "no backup for the first extent\n");
2770 /* force no allocation from system block group */
2771 root->fs_info->system_allocs = -1;
2772 trans = btrfs_start_transaction(root, 1);
2775 * recow the whole chunk tree, this will remove all chunk tree blocks
2776 * from system block group
2778 chunk_root = root->fs_info->chunk_root;
2779 memset(&key, 0, sizeof(key));
2781 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2785 ret = btrfs_next_leaf(chunk_root, &path);
2789 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2790 btrfs_release_path(&path);
2792 btrfs_release_path(&path);
2797 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2801 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2802 num_bytes += btrfs_block_group_used(&cache1->item);
2804 offset = cache1->key.objectid + cache1->key.offset;
2806 /* only extent #0 left in system block group? */
2807 if (num_bytes > first_free) {
2808 fprintf(stderr, "unable to empty system block group\n");
2811 /* create a system chunk that maps the whole device */
2812 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2814 fprintf(stderr, "unable to update system chunk\n");
2818 ret = btrfs_commit_transaction(trans, root);
2821 ret = close_ctree(root);
2823 fprintf(stderr, "error during close_ctree %d\n", ret);
2827 /* zero btrfs super block mirrors */
2828 memset(buf, 0, sectorsize);
2829 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2830 bytenr = btrfs_sb_offset(i);
2831 if (bytenr >= total_bytes)
2833 ret = pwrite(fd, buf, sectorsize, bytenr);
2834 if (ret != sectorsize) {
2836 "error during zeroing superblock %d: %d\n",
2842 sb_bytenr = (u64)-1;
2843 /* copy all relocated blocks back */
2845 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2850 ret = get_state_private(&io_tree, start, &bytenr);
2853 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2856 while (start <= end) {
2857 if (start == BTRFS_SUPER_INFO_OFFSET) {
2861 ret = pread(fd, buf, sectorsize, bytenr);
2863 fprintf(stderr, "error during pread %d\n", ret);
2866 BUG_ON(ret != sectorsize);
2867 ret = pwrite(fd, buf, sectorsize, start);
2869 fprintf(stderr, "error during pwrite %d\n", ret);
2872 BUG_ON(ret != sectorsize);
2874 start += sectorsize;
2875 bytenr += sectorsize;
2881 fprintf(stderr, "error during fsync %d\n", ret);
2885 * finally, overwrite btrfs super block.
2887 ret = pread(fd, buf, sectorsize, sb_bytenr);
2889 fprintf(stderr, "error during pread %d\n", ret);
2892 BUG_ON(ret != sectorsize);
2893 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
2895 fprintf(stderr, "error during pwrite %d\n", ret);
2898 BUG_ON(ret != sectorsize);
2901 fprintf(stderr, "error during fsync %d\n", ret);
2907 extent_io_tree_cleanup(&io_tree);
2908 printf("rollback complete.\n");
2915 fprintf(stderr, "rollback aborted.\n");
2919 static void print_usage(void)
2921 printf("usage: btrfs-convert [options] device\n");
2922 printf("options:\n");
2923 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
2924 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
2925 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
2926 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
2927 printf("\t-r|--rollback roll back to the original filesystem\n");
2928 printf("\t-l|--label LABEL set filesystem label\n");
2929 printf("\t-L|--copy-label use label from converted filesystem\n");
2930 printf("\t-p|--progress show converting progress (default)\n");
2931 printf("\t-O|--features LIST comma separated list of filesystem features\n");
2932 printf("\t--no-progress show only overview, not the detailed progress\n");
2935 int main(int argc, char *argv[])
2941 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
2942 BTRFS_MKFS_DEFAULT_NODE_SIZE);
2945 int usage_error = 0;
2948 char fslabel[BTRFS_LABEL_SIZE];
2949 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
2952 enum { GETOPT_VAL_NO_PROGRESS = 256 };
2953 static const struct option long_options[] = {
2954 { "no-progress", no_argument, NULL,
2955 GETOPT_VAL_NO_PROGRESS },
2956 { "no-datasum", no_argument, NULL, 'd' },
2957 { "no-inline", no_argument, NULL, 'n' },
2958 { "no-xattr", no_argument, NULL, 'i' },
2959 { "rollback", no_argument, NULL, 'r' },
2960 { "features", required_argument, NULL, 'O' },
2961 { "progress", no_argument, NULL, 'p' },
2962 { "label", required_argument, NULL, 'l' },
2963 { "copy-label", no_argument, NULL, 'L' },
2964 { "nodesize", required_argument, NULL, 'N' },
2965 { "help", no_argument, NULL, GETOPT_VAL_HELP},
2966 { NULL, 0, NULL, 0 }
2968 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
2983 nodesize = parse_size(optarg);
2990 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
2992 "WARNING: label too long, trimmed to %d bytes\n",
2993 BTRFS_LABEL_SIZE - 1);
2995 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3004 char *orig = strdup(optarg);
3007 tmp = btrfs_parse_fs_features(tmp, &features);
3010 "Unrecognized filesystem feature '%s'\n",
3016 if (features & BTRFS_FEATURE_LIST_ALL) {
3017 btrfs_list_all_fs_features(
3018 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3021 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3024 btrfs_parse_features_to_string(buf,
3025 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3027 "ERROR: features not allowed for convert: %s\n",
3034 case GETOPT_VAL_NO_PROGRESS:
3037 case GETOPT_VAL_HELP:
3040 return c != GETOPT_VAL_HELP;
3044 if (check_argc_exact(argc - optind, 1)) {
3049 if (rollback && (!datacsum || noxattr || !packing)) {
3051 "Usage error: -d, -i, -n options do not apply to rollback\n");
3060 file = argv[optind];
3061 ret = check_mounted(file);
3063 fprintf(stderr, "Could not check mount status: %s\n",
3067 fprintf(stderr, "%s is mounted\n", file);
3072 ret = do_rollback(file);
3074 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3075 copylabel, fslabel, progress, features);