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"
41 #include "mkfs/common.h"
44 #include <ext2fs/ext2_fs.h>
45 #include <ext2fs/ext2fs.h>
46 #include <ext2fs/ext2_ext_attr.h>
48 #define INO_OFFSET (BTRFS_FIRST_FREE_OBJECTID - EXT2_ROOT_INO)
51 * Compatibility code for e2fsprogs 1.41 which doesn't support RO compat flag
53 * Unlike normal RO compat flag, BIGALLOC affects how e2fsprogs check used
54 * space, and btrfs-convert heavily relies on it.
56 #ifdef HAVE_OLD_E2FSPROGS
57 #define EXT2FS_CLUSTER_RATIO(fs) (1)
58 #define EXT2_CLUSTERS_PER_GROUP(s) (EXT2_BLOCKS_PER_GROUP(s))
59 #define EXT2FS_B2C(fs, blk) (blk)
64 #define CONV_IMAGE_SUBVOL_OBJECTID BTRFS_FIRST_FREE_OBJECTID
67 uint32_t max_copy_inodes;
68 uint32_t cur_copy_inodes;
69 struct task_info *info;
72 static void *print_copied_inodes(void *p)
74 struct task_ctx *priv = p;
75 const char work_indicator[] = { '.', 'o', 'O', 'o' };
78 task_period_start(priv->info, 1000 /* 1s */);
81 printf("copy inodes [%c] [%10d/%10d]\r",
82 work_indicator[count % 4], priv->cur_copy_inodes,
83 priv->max_copy_inodes);
85 task_period_wait(priv->info);
91 static int after_copied_inodes(void *p)
99 struct btrfs_convert_context;
100 struct btrfs_convert_operations {
102 int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
103 int (*read_used_space)(struct btrfs_convert_context *cctx);
104 int (*copy_inodes)(struct btrfs_convert_context *cctx,
105 struct btrfs_root *root, int datacsum,
106 int packing, int noxattr, struct task_ctx *p);
107 void (*close_fs)(struct btrfs_convert_context *cctx);
108 int (*check_state)(struct btrfs_convert_context *cctx);
111 static void init_convert_context(struct btrfs_convert_context *cctx)
113 cache_tree_init(&cctx->used);
114 cache_tree_init(&cctx->data_chunks);
115 cache_tree_init(&cctx->free);
118 static void clean_convert_context(struct btrfs_convert_context *cctx)
120 free_extent_cache_tree(&cctx->used);
121 free_extent_cache_tree(&cctx->data_chunks);
122 free_extent_cache_tree(&cctx->free);
125 static inline int copy_inodes(struct btrfs_convert_context *cctx,
126 struct btrfs_root *root, int datacsum,
127 int packing, int noxattr, struct task_ctx *p)
129 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
133 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
135 cctx->convert_ops->close_fs(cctx);
138 static inline int convert_check_state(struct btrfs_convert_context *cctx)
140 return cctx->convert_ops->check_state(cctx);
143 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
148 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
149 offset = btrfs_sb_offset(i);
150 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
152 if (bytenr < offset + BTRFS_STRIPE_LEN &&
153 bytenr + num_bytes > offset)
159 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
160 struct btrfs_root *root,
161 const char *name, size_t name_len,
162 u64 dir, u64 objectid,
163 u8 file_type, u64 index_cnt,
164 struct btrfs_inode_item *inode)
168 struct btrfs_key location = {
169 .objectid = objectid,
171 .type = BTRFS_INODE_ITEM_KEY,
174 ret = btrfs_insert_dir_item(trans, root, name, name_len,
175 dir, &location, file_type, index_cnt);
178 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
179 objectid, dir, index_cnt);
182 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
183 btrfs_set_stack_inode_size(inode, inode_size);
188 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
189 u32 num_bytes, char *buffer)
192 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
194 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
195 if (ret != num_bytes)
204 static int csum_disk_extent(struct btrfs_trans_handle *trans,
205 struct btrfs_root *root,
206 u64 disk_bytenr, u64 num_bytes)
208 u32 blocksize = root->sectorsize;
213 buffer = malloc(blocksize);
216 for (offset = 0; offset < num_bytes; offset += blocksize) {
217 ret = read_disk_extent(root, disk_bytenr + offset,
221 ret = btrfs_csum_file_block(trans,
222 root->fs_info->csum_root,
223 disk_bytenr + num_bytes,
224 disk_bytenr + offset,
233 struct blk_iterate_data {
234 struct btrfs_trans_handle *trans;
235 struct btrfs_root *root;
236 struct btrfs_root *convert_root;
237 struct btrfs_inode_item *inode;
248 static void init_blk_iterate_data(struct blk_iterate_data *data,
249 struct btrfs_trans_handle *trans,
250 struct btrfs_root *root,
251 struct btrfs_inode_item *inode,
252 u64 objectid, int checksum)
254 struct btrfs_key key;
259 data->objectid = objectid;
260 data->first_block = 0;
261 data->disk_block = 0;
262 data->num_blocks = 0;
263 data->boundary = (u64)-1;
264 data->checksum = checksum;
267 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
268 key.type = BTRFS_ROOT_ITEM_KEY;
269 key.offset = (u64)-1;
270 data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
271 /* Impossible as we just opened it before */
272 BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
273 data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
277 * Record a file extent in original filesystem into btrfs one.
278 * The special point is, old disk_block can point to a reserved range.
279 * So here, we don't use disk_block directly but search convert_root
280 * to get the real disk_bytenr.
282 static int record_file_blocks(struct blk_iterate_data *data,
283 u64 file_block, u64 disk_block, u64 num_blocks)
286 struct btrfs_root *root = data->root;
287 struct btrfs_root *convert_root = data->convert_root;
288 struct btrfs_path path;
289 u64 file_pos = file_block * root->sectorsize;
290 u64 old_disk_bytenr = disk_block * root->sectorsize;
291 u64 num_bytes = num_blocks * root->sectorsize;
292 u64 cur_off = old_disk_bytenr;
294 /* Hole, pass it to record_file_extent directly */
295 if (old_disk_bytenr == 0)
296 return btrfs_record_file_extent(data->trans, root,
297 data->objectid, data->inode, file_pos, 0,
300 btrfs_init_path(&path);
303 * Search real disk bytenr from convert root
305 while (cur_off < old_disk_bytenr + num_bytes) {
306 struct btrfs_key key;
307 struct btrfs_file_extent_item *fi;
308 struct extent_buffer *node;
310 u64 extent_disk_bytenr;
311 u64 extent_num_bytes;
312 u64 real_disk_bytenr;
315 key.objectid = data->convert_ino;
316 key.type = BTRFS_EXTENT_DATA_KEY;
317 key.offset = cur_off;
319 ret = btrfs_search_slot(NULL, convert_root, &key, &path, 0, 0);
323 ret = btrfs_previous_item(convert_root, &path,
325 BTRFS_EXTENT_DATA_KEY);
333 node = path.nodes[0];
334 slot = path.slots[0];
335 btrfs_item_key_to_cpu(node, &key, slot);
336 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
337 key.objectid != data->convert_ino ||
338 key.offset > cur_off);
339 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
340 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
341 extent_num_bytes = btrfs_file_extent_num_bytes(node, fi);
342 BUG_ON(cur_off - key.offset >= extent_num_bytes);
343 btrfs_release_path(&path);
345 if (extent_disk_bytenr)
346 real_disk_bytenr = cur_off - key.offset +
349 real_disk_bytenr = 0;
350 cur_len = min(key.offset + extent_num_bytes,
351 old_disk_bytenr + num_bytes) - cur_off;
352 ret = btrfs_record_file_extent(data->trans, data->root,
353 data->objectid, data->inode, file_pos,
354 real_disk_bytenr, cur_len);
361 * No need to care about csum
362 * As every byte of old fs image is calculated for csum, no
363 * need to waste CPU cycles now.
366 btrfs_release_path(&path);
370 static int block_iterate_proc(u64 disk_block, u64 file_block,
371 struct blk_iterate_data *idata)
376 struct btrfs_root *root = idata->root;
377 struct btrfs_block_group_cache *cache;
378 u64 bytenr = disk_block * root->sectorsize;
380 sb_region = intersect_with_sb(bytenr, root->sectorsize);
381 do_barrier = sb_region || disk_block >= idata->boundary;
382 if ((idata->num_blocks > 0 && do_barrier) ||
383 (file_block > idata->first_block + idata->num_blocks) ||
384 (disk_block != idata->disk_block + idata->num_blocks)) {
385 if (idata->num_blocks > 0) {
386 ret = record_file_blocks(idata, idata->first_block,
391 idata->first_block += idata->num_blocks;
392 idata->num_blocks = 0;
394 if (file_block > idata->first_block) {
395 ret = record_file_blocks(idata, idata->first_block,
396 0, file_block - idata->first_block);
402 bytenr += BTRFS_STRIPE_LEN - 1;
403 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
405 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
407 bytenr = cache->key.objectid + cache->key.offset;
410 idata->first_block = file_block;
411 idata->disk_block = disk_block;
412 idata->boundary = bytenr / root->sectorsize;
419 static int create_image_file_range(struct btrfs_trans_handle *trans,
420 struct btrfs_root *root,
421 struct cache_tree *used,
422 struct btrfs_inode_item *inode,
423 u64 ino, u64 bytenr, u64 *ret_len,
426 struct cache_extent *cache;
427 struct btrfs_block_group_cache *bg_cache;
433 if (bytenr != round_down(bytenr, root->sectorsize)) {
434 error("bytenr not sectorsize aligned: %llu",
435 (unsigned long long)bytenr);
438 if (len != round_down(len, root->sectorsize)) {
439 error("length not sectorsize aligned: %llu",
440 (unsigned long long)len);
443 len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
446 * Skip sb ranges first
447 * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
449 * Or we will insert a hole into current image file, and later
450 * migrate block will fail as there is already a file extent.
452 if (bytenr < 1024 * 1024) {
453 *ret_len = 1024 * 1024 - bytenr;
456 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
457 u64 cur = btrfs_sb_offset(i);
459 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
460 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
464 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
465 u64 cur = btrfs_sb_offset(i);
470 * May still need to go through file extent inserts
472 if (bytenr < cur && bytenr + len >= cur) {
473 len = min_t(u64, len, cur - bytenr);
479 * Drop out, no need to insert anything
481 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
482 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
487 cache = search_cache_extent(used, bytenr);
489 if (cache->start <= bytenr) {
491 * |///////Used///////|
495 len = min_t(u64, len, cache->start + cache->size -
497 disk_bytenr = bytenr;
504 len = min(len, cache->start - bytenr);
519 /* Check if the range is in a data block group */
520 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
523 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
526 /* The extent should never cross block group boundary */
527 len = min_t(u64, len, bg_cache->key.objectid +
528 bg_cache->key.offset - bytenr);
531 if (len != round_down(len, root->sectorsize)) {
532 error("remaining length not sectorsize aligned: %llu",
533 (unsigned long long)len);
536 ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
542 ret = csum_disk_extent(trans, root, bytenr, len);
548 * Relocate old fs data in one reserved ranges
550 * Since all old fs data in reserved range is not covered by any chunk nor
551 * data extent, we don't need to handle any reference but add new
552 * extent/reference, which makes codes more clear
554 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
555 struct btrfs_root *root,
556 struct cache_tree *used,
557 struct btrfs_inode_item *inode, int fd,
558 u64 ino, u64 start, u64 len, int datacsum)
562 u64 hole_start = start;
564 struct cache_extent *cache;
565 struct btrfs_key key;
566 struct extent_buffer *eb;
569 while (cur_off < start + len) {
570 cache = lookup_cache_extent(used, cur_off, cur_len);
573 cur_off = max(cache->start, cur_off);
574 cur_len = min(cache->start + cache->size, start + len) -
576 BUG_ON(cur_len < root->sectorsize);
578 /* reserve extent for the data */
579 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
584 eb = malloc(sizeof(*eb) + cur_len);
590 ret = pread(fd, eb->data, cur_len, cur_off);
592 ret = (ret < 0 ? ret : -EIO);
596 eb->start = key.objectid;
597 eb->len = key.offset;
600 ret = write_and_map_eb(trans, root, eb);
605 /* Now handle extent item and file extent things */
606 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
607 key.objectid, key.offset);
610 /* Finally, insert csum items */
612 ret = csum_disk_extent(trans, root, key.objectid,
615 /* Don't forget to insert hole */
616 hole_len = cur_off - hole_start;
618 ret = btrfs_record_file_extent(trans, root, ino, inode,
619 hole_start, 0, hole_len);
624 cur_off += key.offset;
625 hole_start = cur_off;
626 cur_len = start + len - cur_off;
629 if (start + len - hole_start > 0)
630 ret = btrfs_record_file_extent(trans, root, ino, inode,
631 hole_start, 0, start + len - hole_start);
636 * Relocate the used ext2 data in reserved ranges
638 * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
639 * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
641 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
642 struct btrfs_root *root,
643 struct cache_tree *used,
644 struct btrfs_inode_item *inode, int fd,
645 u64 ino, u64 total_bytes, int datacsum)
653 cur_len = 1024 * 1024;
654 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
655 cur_off, cur_len, datacsum);
659 /* second sb(fisrt sb is included in 0~1M) */
660 cur_off = btrfs_sb_offset(1);
661 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
662 if (cur_off > total_bytes)
664 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
665 cur_off, cur_len, datacsum);
670 cur_off = btrfs_sb_offset(2);
671 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
672 if (cur_off > total_bytes)
674 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
675 cur_off, cur_len, datacsum);
680 * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
681 * handle wiping a range that exists in cache.
683 static int _expand_extent_cache(struct cache_tree *tree,
684 struct cache_extent *entry,
685 u64 min_stripe_size, int backward)
687 struct cache_extent *ce;
690 if (entry->size >= min_stripe_size)
692 diff = min_stripe_size - entry->size;
695 ce = prev_cache_extent(entry);
698 if (ce->start + ce->size >= entry->start - diff) {
699 /* Directly merge with previous extent */
700 ce->size = entry->start + entry->size - ce->start;
701 remove_cache_extent(tree, entry);
706 /* No overlap, normal extent */
707 if (entry->start < diff) {
708 error("cannot find space for data chunk layout");
711 entry->start -= diff;
715 ce = next_cache_extent(entry);
718 if (entry->start + entry->size + diff >= ce->start) {
719 /* Directly merge with next extent */
720 entry->size = ce->start + ce->size - entry->start;
721 remove_cache_extent(tree, ce);
731 * Remove one reserve range from given cache tree
732 * if min_stripe_size is non-zero, it will ensure for split case,
733 * all its split cache extent is no smaller than @min_strip_size / 2.
735 static int wipe_one_reserved_range(struct cache_tree *tree,
736 u64 start, u64 len, u64 min_stripe_size,
739 struct cache_extent *cache;
742 BUG_ON(ensure_size && min_stripe_size == 0);
744 * The logical here is simplified to handle special cases only
745 * So we don't need to consider merge case for ensure_size
747 BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
748 min_stripe_size / 2 < BTRFS_STRIPE_LEN));
750 /* Also, wipe range should already be aligned */
751 BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
752 start + len != round_up(start + len, BTRFS_STRIPE_LEN));
754 min_stripe_size /= 2;
756 cache = lookup_cache_extent(tree, start, len);
760 if (start <= cache->start) {
762 * |--------cache---------|
765 BUG_ON(start + len <= cache->start);
768 * The wipe size is smaller than min_stripe_size / 2,
769 * so the result length should still meet min_stripe_size
770 * And no need to do alignment
772 cache->size -= (start + len - cache->start);
773 if (cache->size == 0) {
774 remove_cache_extent(tree, cache);
779 BUG_ON(ensure_size && cache->size < min_stripe_size);
781 cache->start = start + len;
783 } else if (start > cache->start && start + len < cache->start +
786 * |-------cache-----|
789 u64 old_start = cache->start;
790 u64 old_len = cache->size;
791 u64 insert_start = start + len;
794 cache->size = start - cache->start;
795 /* Expand the leading half part if needed */
796 if (ensure_size && cache->size < min_stripe_size) {
797 ret = _expand_extent_cache(tree, cache,
803 /* And insert the new one */
804 insert_len = old_start + old_len - start - len;
805 ret = add_merge_cache_extent(tree, insert_start, insert_len);
809 /* Expand the last half part if needed */
810 if (ensure_size && insert_len < min_stripe_size) {
811 cache = lookup_cache_extent(tree, insert_start,
813 if (!cache || cache->start != insert_start ||
814 cache->size != insert_len)
816 ret = _expand_extent_cache(tree, cache,
825 * Wipe len should be small enough and no need to expand the
828 cache->size = start - cache->start;
829 BUG_ON(ensure_size && cache->size < min_stripe_size);
834 * Remove reserved ranges from given cache_tree
836 * It will remove the following ranges
838 * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
839 * 3) 3rd superblock, +64K
841 * @min_stripe must be given for safety check
842 * and if @ensure_size is given, it will ensure affected cache_extent will be
843 * larger than min_stripe_size
845 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
850 ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
854 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
855 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
858 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
859 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
863 static int calculate_available_space(struct btrfs_convert_context *cctx)
865 struct cache_tree *used = &cctx->used;
866 struct cache_tree *data_chunks = &cctx->data_chunks;
867 struct cache_tree *free = &cctx->free;
868 struct cache_extent *cache;
871 * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
872 * works without need to consider overlap
874 u64 min_stripe_size = 2 * 16 * 1024 * 1024;
877 /* Calculate data_chunks */
878 for (cache = first_cache_extent(used); cache;
879 cache = next_cache_extent(cache)) {
882 if (cache->start + cache->size < cur_off)
884 if (cache->start > cur_off + min_stripe_size)
885 cur_off = cache->start;
886 cur_len = max(cache->start + cache->size - cur_off,
888 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
894 * remove reserved ranges, so we won't ever bother relocating an old
895 * filesystem extent to other place.
897 ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
903 * Calculate free space
904 * Always round up the start bytenr, to avoid metadata extent corss
905 * stripe boundary, as later mkfs_convert() won't have all the extent
908 for (cache = first_cache_extent(data_chunks); cache;
909 cache = next_cache_extent(cache)) {
910 if (cache->start < cur_off)
912 if (cache->start > cur_off) {
916 len = cache->start - round_up(cur_off,
918 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
920 ret = add_merge_cache_extent(free, insert_start, len);
924 cur_off = cache->start + cache->size;
926 /* Don't forget the last range */
927 if (cctx->total_bytes > cur_off) {
928 u64 len = cctx->total_bytes - cur_off;
931 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
933 ret = add_merge_cache_extent(free, insert_start, len);
938 /* Remove reserved bytes */
939 ret = wipe_reserved_ranges(free, min_stripe_size, 0);
945 * Read used space, and since we have the used space,
946 * calcuate data_chunks and free for later mkfs
948 static int convert_read_used_space(struct btrfs_convert_context *cctx)
952 ret = cctx->convert_ops->read_used_space(cctx);
956 ret = calculate_available_space(cctx);
961 * Create the fs image file of old filesystem.
963 * This is completely fs independent as we have cctx->used, only
964 * need to create file extents pointing to all the positions.
966 static int create_image(struct btrfs_root *root,
967 struct btrfs_mkfs_config *cfg,
968 struct btrfs_convert_context *cctx, int fd,
969 u64 size, char *name, int datacsum)
971 struct btrfs_inode_item buf;
972 struct btrfs_trans_handle *trans;
973 struct btrfs_path path;
974 struct btrfs_key key;
975 struct cache_extent *cache;
976 struct cache_tree used_tmp;
979 u64 flags = BTRFS_INODE_READONLY;
983 flags |= BTRFS_INODE_NODATASUM;
985 trans = btrfs_start_transaction(root, 1);
989 cache_tree_init(&used_tmp);
990 btrfs_init_path(&path);
992 ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
996 ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
999 ret = btrfs_change_inode_flags(trans, root, ino, flags);
1002 ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1003 strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1008 key.type = BTRFS_INODE_ITEM_KEY;
1011 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1013 ret = (ret > 0 ? -ENOENT : ret);
1016 read_extent_buffer(path.nodes[0], &buf,
1017 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1019 btrfs_release_path(&path);
1022 * Create a new used space cache, which doesn't contain the reserved
1025 for (cache = first_cache_extent(&cctx->used); cache;
1026 cache = next_cache_extent(cache)) {
1027 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
1031 ret = wipe_reserved_ranges(&used_tmp, 0, 0);
1036 * Start from 1M, as 0~1M is reserved, and create_image_file_range()
1037 * can't handle bytenr 0(will consider it as a hole)
1040 while (cur < size) {
1041 u64 len = size - cur;
1043 ret = create_image_file_range(trans, root, &used_tmp,
1044 &buf, ino, cur, &len, datacsum);
1049 /* Handle the reserved ranges */
1050 ret = migrate_reserved_ranges(trans, root, &cctx->used, &buf, fd, ino,
1051 cfg->num_bytes, datacsum);
1055 key.type = BTRFS_INODE_ITEM_KEY;
1057 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1059 ret = (ret > 0 ? -ENOENT : ret);
1062 btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1063 write_extent_buffer(path.nodes[0], &buf,
1064 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1067 free_extent_cache_tree(&used_tmp);
1068 btrfs_release_path(&path);
1069 btrfs_commit_transaction(trans, root);
1073 static struct btrfs_root* link_subvol(struct btrfs_root *root,
1074 const char *base, u64 root_objectid)
1076 struct btrfs_trans_handle *trans;
1077 struct btrfs_fs_info *fs_info = root->fs_info;
1078 struct btrfs_root *tree_root = fs_info->tree_root;
1079 struct btrfs_root *new_root = NULL;
1080 struct btrfs_path path;
1081 struct btrfs_inode_item *inode_item;
1082 struct extent_buffer *leaf;
1083 struct btrfs_key key;
1084 u64 dirid = btrfs_root_dirid(&root->root_item);
1086 char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1092 if (len == 0 || len > BTRFS_NAME_LEN)
1095 btrfs_init_path(&path);
1096 key.objectid = dirid;
1097 key.type = BTRFS_DIR_INDEX_KEY;
1098 key.offset = (u64)-1;
1100 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1102 error("search for DIR_INDEX dirid %llu failed: %d",
1103 (unsigned long long)dirid, ret);
1107 if (path.slots[0] > 0) {
1109 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1110 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1111 index = key.offset + 1;
1113 btrfs_release_path(&path);
1115 trans = btrfs_start_transaction(root, 1);
1117 error("unable to start transaction");
1121 key.objectid = dirid;
1123 key.type = BTRFS_INODE_ITEM_KEY;
1125 ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
1127 error("search for INODE_ITEM %llu failed: %d",
1128 (unsigned long long)dirid, ret);
1131 leaf = path.nodes[0];
1132 inode_item = btrfs_item_ptr(leaf, path.slots[0],
1133 struct btrfs_inode_item);
1135 key.objectid = root_objectid;
1136 key.offset = (u64)-1;
1137 key.type = BTRFS_ROOT_ITEM_KEY;
1139 memcpy(buf, base, len);
1140 for (i = 0; i < 1024; i++) {
1141 ret = btrfs_insert_dir_item(trans, root, buf, len,
1142 dirid, &key, BTRFS_FT_DIR, index);
1145 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1146 if (len < 1 || len > BTRFS_NAME_LEN) {
1154 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1155 btrfs_inode_size(leaf, inode_item));
1156 btrfs_mark_buffer_dirty(leaf);
1157 btrfs_release_path(&path);
1159 /* add the backref first */
1160 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1161 BTRFS_ROOT_BACKREF_KEY,
1162 root->root_key.objectid,
1163 dirid, index, buf, len);
1165 error("unable to add root backref for %llu: %d",
1166 root->root_key.objectid, ret);
1170 /* now add the forward ref */
1171 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1172 BTRFS_ROOT_REF_KEY, root_objectid,
1173 dirid, index, buf, len);
1175 error("unable to add root ref for %llu: %d",
1176 root->root_key.objectid, ret);
1180 ret = btrfs_commit_transaction(trans, root);
1182 error("transaction commit failed: %d", ret);
1186 new_root = btrfs_read_fs_root(fs_info, &key);
1187 if (IS_ERR(new_root)) {
1188 error("unable to fs read root: %lu", PTR_ERR(new_root));
1192 btrfs_init_path(&path);
1196 static int create_subvol(struct btrfs_trans_handle *trans,
1197 struct btrfs_root *root, u64 root_objectid)
1199 struct extent_buffer *tmp;
1200 struct btrfs_root *new_root;
1201 struct btrfs_key key;
1202 struct btrfs_root_item root_item;
1205 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1210 memcpy(&root_item, &root->root_item, sizeof(root_item));
1211 btrfs_set_root_bytenr(&root_item, tmp->start);
1212 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1213 btrfs_set_root_generation(&root_item, trans->transid);
1214 free_extent_buffer(tmp);
1216 key.objectid = root_objectid;
1217 key.type = BTRFS_ROOT_ITEM_KEY;
1218 key.offset = trans->transid;
1219 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1222 key.offset = (u64)-1;
1223 new_root = btrfs_read_fs_root(root->fs_info, &key);
1224 if (!new_root || IS_ERR(new_root)) {
1225 error("unable to fs read root: %lu", PTR_ERR(new_root));
1226 return PTR_ERR(new_root);
1229 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1235 * New make_btrfs() has handle system and meta chunks quite well.
1236 * So only need to add remaining data chunks.
1238 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1239 struct btrfs_fs_info *fs_info,
1240 struct btrfs_mkfs_config *cfg,
1241 struct btrfs_convert_context *cctx)
1243 struct btrfs_root *extent_root = fs_info->extent_root;
1244 struct cache_tree *data_chunks = &cctx->data_chunks;
1245 struct cache_extent *cache;
1250 * Don't create data chunk over 10% of the convert device
1251 * And for single chunk, don't create chunk larger than 1G.
1253 max_chunk_size = cfg->num_bytes / 10;
1254 max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1255 max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1257 for (cache = first_cache_extent(data_chunks); cache;
1258 cache = next_cache_extent(cache)) {
1259 u64 cur = cache->start;
1261 while (cur < cache->start + cache->size) {
1263 u64 cur_backup = cur;
1265 len = min(max_chunk_size,
1266 cache->start + cache->size - cur);
1267 ret = btrfs_alloc_data_chunk(trans, extent_root,
1269 BTRFS_BLOCK_GROUP_DATA, 1);
1272 ret = btrfs_make_block_group(trans, extent_root, 0,
1273 BTRFS_BLOCK_GROUP_DATA,
1274 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1285 * Init the temp btrfs to a operational status.
1287 * It will fix the extent usage accounting(XXX: Do we really need?) and
1288 * insert needed data chunks, to ensure all old fs data extents are covered
1289 * by DATA chunks, preventing wrong chunks are allocated.
1291 * And also create convert image subvolume and relocation tree.
1292 * (XXX: Not need again?)
1293 * But the convert image subvolume is *NOT* linked to fs tree yet.
1295 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1296 struct btrfs_convert_context *cctx, int datacsum,
1297 int packing, int noxattr)
1299 struct btrfs_key location;
1300 struct btrfs_trans_handle *trans;
1301 struct btrfs_fs_info *fs_info = root->fs_info;
1305 * Don't alloc any metadata/system chunk, as we don't want
1306 * any meta/sys chunk allcated before all data chunks are inserted.
1307 * Or we screw up the chunk layout just like the old implement.
1309 fs_info->avoid_sys_chunk_alloc = 1;
1310 fs_info->avoid_meta_chunk_alloc = 1;
1311 trans = btrfs_start_transaction(root, 1);
1313 error("unable to start transaction");
1317 ret = btrfs_fix_block_accounting(trans, root);
1320 ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1323 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1324 BTRFS_ROOT_TREE_DIR_OBJECTID);
1327 memcpy(&location, &root->root_key, sizeof(location));
1328 location.offset = (u64)-1;
1329 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1330 btrfs_super_root_dir(fs_info->super_copy),
1331 &location, BTRFS_FT_DIR, 0);
1334 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1336 btrfs_super_root_dir(fs_info->super_copy), 0);
1339 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1340 BTRFS_FIRST_FREE_OBJECTID);
1342 /* subvol for fs image file */
1343 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1345 error("failed to create subvolume image root: %d", ret);
1348 /* subvol for data relocation tree */
1349 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1351 error("failed to create DATA_RELOC root: %d", ret);
1355 ret = btrfs_commit_transaction(trans, root);
1356 fs_info->avoid_sys_chunk_alloc = 0;
1357 fs_info->avoid_meta_chunk_alloc = 0;
1363 * Migrate super block to its default position and zero 0 ~ 16k
1365 static int migrate_super_block(int fd, u64 old_bytenr)
1368 struct extent_buffer *buf;
1369 struct btrfs_super_block *super;
1373 buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1377 buf->len = BTRFS_SUPER_INFO_SIZE;
1378 ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1379 if (ret != BTRFS_SUPER_INFO_SIZE)
1382 super = (struct btrfs_super_block *)buf->data;
1383 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1384 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1386 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1387 ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1388 BTRFS_SUPER_INFO_OFFSET);
1389 if (ret != BTRFS_SUPER_INFO_SIZE)
1396 memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1397 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1398 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1399 if (len > BTRFS_SUPER_INFO_SIZE)
1400 len = BTRFS_SUPER_INFO_SIZE;
1401 ret = pwrite(fd, buf->data, len, bytenr);
1403 fprintf(stderr, "unable to zero fill device\n");
1417 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1419 struct btrfs_chunk *chunk;
1420 struct btrfs_disk_key *key;
1421 u32 sectorsize = btrfs_super_sectorsize(super);
1423 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1424 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1425 sizeof(struct btrfs_disk_key));
1427 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1428 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1429 btrfs_set_disk_key_offset(key, 0);
1431 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1432 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1433 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1434 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1435 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1436 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1437 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1438 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1439 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1440 chunk->stripe.devid = super->dev_item.devid;
1441 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1442 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1443 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1447 #if BTRFSCONVERT_EXT2
1450 * Open Ext2fs in readonly mode, read block allocation bitmap and
1451 * inode bitmap into memory.
1453 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
1456 ext2_filsys ext2_fs;
1460 ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
1462 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
1466 * We need to know exactly the used space, some RO compat flags like
1467 * BIGALLOC will affect how used space is present.
1468 * So we need manuall check any unsupported RO compat flags
1470 ro_feature = ext2_fs->super->s_feature_ro_compat;
1471 if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
1473 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
1474 ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1477 ret = ext2fs_read_inode_bitmap(ext2_fs);
1479 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
1480 error_message(ret));
1483 ret = ext2fs_read_block_bitmap(ext2_fs);
1485 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
1486 error_message(ret));
1490 * search each block group for a free inode. this set up
1491 * uninit block/inode bitmaps appropriately.
1494 while (ino <= ext2_fs->super->s_inodes_count) {
1496 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
1497 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
1500 if (!(ext2_fs->super->s_feature_incompat &
1501 EXT2_FEATURE_INCOMPAT_FILETYPE)) {
1502 error("filetype feature is missing");
1506 cctx->fs_data = ext2_fs;
1507 cctx->blocksize = ext2_fs->blocksize;
1508 cctx->block_count = ext2_fs->super->s_blocks_count;
1509 cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
1510 cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
1511 cctx->first_data_block = ext2_fs->super->s_first_data_block;
1512 cctx->inodes_count = ext2_fs->super->s_inodes_count;
1513 cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
1516 ext2fs_close(ext2_fs);
1520 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
1521 unsigned long group_nr, struct cache_tree *used)
1523 unsigned long offset;
1527 offset = fs->super->s_first_data_block;
1528 offset /= EXT2FS_CLUSTER_RATIO(fs);
1529 offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
1530 for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
1531 if ((i + offset) >= ext2fs_blocks_count(fs->super))
1534 if (ext2fs_test_bit(i, bitmap)) {
1537 start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
1538 start *= fs->blocksize;
1539 ret = add_merge_cache_extent(used, start,
1549 * Read all used ext2 space into cctx->used cache tree
1551 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
1553 ext2_filsys fs = (ext2_filsys)cctx->fs_data;
1554 blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
1555 struct cache_tree *used_tree = &cctx->used;
1556 char *block_bitmap = NULL;
1561 block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
1562 /* Shouldn't happen */
1563 BUG_ON(!fs->block_map);
1565 block_bitmap = malloc(block_nbytes);
1569 for (i = 0; i < fs->group_desc_count; i++) {
1570 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
1571 block_nbytes * 8, block_bitmap);
1573 error("fail to get bitmap from ext2, %s",
1577 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
1579 error("fail to build used space tree, %s",
1583 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
1590 static void ext2_close_fs(struct btrfs_convert_context *cctx)
1592 if (cctx->volume_name) {
1593 free(cctx->volume_name);
1594 cctx->volume_name = NULL;
1596 ext2fs_close(cctx->fs_data);
1599 struct dir_iterate_data {
1600 struct btrfs_trans_handle *trans;
1601 struct btrfs_root *root;
1602 struct btrfs_inode_item *inode;
1609 static u8 ext2_filetype_conversion_table[EXT2_FT_MAX] = {
1610 [EXT2_FT_UNKNOWN] = BTRFS_FT_UNKNOWN,
1611 [EXT2_FT_REG_FILE] = BTRFS_FT_REG_FILE,
1612 [EXT2_FT_DIR] = BTRFS_FT_DIR,
1613 [EXT2_FT_CHRDEV] = BTRFS_FT_CHRDEV,
1614 [EXT2_FT_BLKDEV] = BTRFS_FT_BLKDEV,
1615 [EXT2_FT_FIFO] = BTRFS_FT_FIFO,
1616 [EXT2_FT_SOCK] = BTRFS_FT_SOCK,
1617 [EXT2_FT_SYMLINK] = BTRFS_FT_SYMLINK,
1620 static int ext2_dir_iterate_proc(ext2_ino_t dir, int entry,
1621 struct ext2_dir_entry *dirent,
1622 int offset, int blocksize,
1623 char *buf,void *priv_data)
1628 char dotdot[] = "..";
1629 struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
1632 name_len = dirent->name_len & 0xFF;
1634 objectid = dirent->inode + INO_OFFSET;
1635 if (!strncmp(dirent->name, dotdot, name_len)) {
1636 if (name_len == 2) {
1637 BUG_ON(idata->parent != 0);
1638 idata->parent = objectid;
1642 if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
1645 file_type = dirent->name_len >> 8;
1646 BUG_ON(file_type > EXT2_FT_SYMLINK);
1648 ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
1649 name_len, idata->objectid, objectid,
1650 ext2_filetype_conversion_table[file_type],
1651 idata->index_cnt, idata->inode);
1653 idata->errcode = ret;
1661 static int ext2_create_dir_entries(struct btrfs_trans_handle *trans,
1662 struct btrfs_root *root, u64 objectid,
1663 struct btrfs_inode_item *btrfs_inode,
1664 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
1668 struct dir_iterate_data data = {
1671 .inode = btrfs_inode,
1672 .objectid = objectid,
1678 err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
1679 ext2_dir_iterate_proc, &data);
1683 if (ret == 0 && data.parent == objectid) {
1684 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
1685 objectid, objectid, 0);
1689 fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
1693 static int ext2_block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
1694 e2_blkcnt_t blockcnt, blk_t ref_block,
1695 int ref_offset, void *priv_data)
1698 struct blk_iterate_data *idata;
1699 idata = (struct blk_iterate_data *)priv_data;
1700 ret = block_iterate_proc(*blocknr, blockcnt, idata);
1702 idata->errcode = ret;
1709 * traverse file's data blocks, record these data blocks as file extents.
1711 static int ext2_create_file_extents(struct btrfs_trans_handle *trans,
1712 struct btrfs_root *root, u64 objectid,
1713 struct btrfs_inode_item *btrfs_inode,
1714 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1715 int datacsum, int packing)
1718 char *buffer = NULL;
1721 u32 sectorsize = root->sectorsize;
1722 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1723 struct blk_iterate_data data;
1725 init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
1728 err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
1729 NULL, ext2_block_iterate_proc, &data);
1735 if (packing && data.first_block == 0 && data.num_blocks > 0 &&
1736 inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
1737 u64 num_bytes = data.num_blocks * sectorsize;
1738 u64 disk_bytenr = data.disk_block * sectorsize;
1741 buffer = malloc(num_bytes);
1744 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
1747 if (num_bytes > inode_size)
1748 num_bytes = inode_size;
1749 ret = btrfs_insert_inline_extent(trans, root, objectid,
1750 0, buffer, num_bytes);
1753 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
1754 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
1755 } else if (data.num_blocks > 0) {
1756 ret = record_file_blocks(&data, data.first_block,
1757 data.disk_block, data.num_blocks);
1761 data.first_block += data.num_blocks;
1762 last_block = (inode_size + sectorsize - 1) / sectorsize;
1763 if (last_block > data.first_block) {
1764 ret = record_file_blocks(&data, data.first_block, 0,
1765 last_block - data.first_block);
1771 fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
1775 static int ext2_create_symbol_link(struct btrfs_trans_handle *trans,
1776 struct btrfs_root *root, u64 objectid,
1777 struct btrfs_inode_item *btrfs_inode,
1778 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1779 struct ext2_inode *ext2_inode)
1783 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1784 if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
1785 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
1786 ret = ext2_create_file_extents(trans, root, objectid,
1787 btrfs_inode, ext2_fs, ext2_ino, 1, 1);
1788 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
1792 pathname = (char *)&(ext2_inode->i_block[0]);
1793 BUG_ON(pathname[inode_size] != 0);
1794 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
1795 pathname, inode_size + 1);
1796 btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
1801 * Following xattr/acl related codes are based on codes in
1802 * fs/ext3/xattr.c and fs/ext3/acl.c
1804 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
1805 #define EXT2_XATTR_BFIRST(ptr) \
1806 ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
1807 #define EXT2_XATTR_IHDR(inode) \
1808 ((struct ext2_ext_attr_header *) ((void *)(inode) + \
1809 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
1810 #define EXT2_XATTR_IFIRST(inode) \
1811 ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
1812 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
1814 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
1817 struct ext2_ext_attr_entry *next;
1819 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1820 next = EXT2_EXT_ATTR_NEXT(entry);
1821 if ((void *)next >= end)
1828 static int ext2_xattr_check_block(const char *buf, size_t size)
1831 struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
1833 if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
1834 header->h_blocks != 1)
1836 error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
1840 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
1843 size_t value_size = entry->e_value_size;
1845 if (entry->e_value_block != 0 || value_size > size ||
1846 entry->e_value_offs + value_size > size)
1851 #define EXT2_ACL_VERSION 0x0001
1853 /* 23.2.5 acl_tag_t values */
1855 #define ACL_UNDEFINED_TAG (0x00)
1856 #define ACL_USER_OBJ (0x01)
1857 #define ACL_USER (0x02)
1858 #define ACL_GROUP_OBJ (0x04)
1859 #define ACL_GROUP (0x08)
1860 #define ACL_MASK (0x10)
1861 #define ACL_OTHER (0x20)
1863 /* 23.2.7 ACL qualifier constants */
1865 #define ACL_UNDEFINED_ID ((id_t)-1)
1876 } ext2_acl_entry_short;
1882 static inline int ext2_acl_count(size_t size)
1885 size -= sizeof(ext2_acl_header);
1886 s = size - 4 * sizeof(ext2_acl_entry_short);
1888 if (size % sizeof(ext2_acl_entry_short))
1890 return size / sizeof(ext2_acl_entry_short);
1892 if (s % sizeof(ext2_acl_entry))
1894 return s / sizeof(ext2_acl_entry) + 4;
1898 #define ACL_EA_VERSION 0x0002
1908 acl_ea_entry a_entries[0];
1911 static inline size_t acl_ea_size(int count)
1913 return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
1916 static int ext2_acl_to_xattr(void *dst, const void *src,
1917 size_t dst_size, size_t src_size)
1920 const void *end = src + src_size;
1921 acl_ea_header *ext_acl = (acl_ea_header *)dst;
1922 acl_ea_entry *dst_entry = ext_acl->a_entries;
1923 ext2_acl_entry *src_entry;
1925 if (src_size < sizeof(ext2_acl_header))
1927 if (((ext2_acl_header *)src)->a_version !=
1928 cpu_to_le32(EXT2_ACL_VERSION))
1930 src += sizeof(ext2_acl_header);
1931 count = ext2_acl_count(src_size);
1935 BUG_ON(dst_size < acl_ea_size(count));
1936 ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
1937 for (i = 0; i < count; i++, dst_entry++) {
1938 src_entry = (ext2_acl_entry *)src;
1939 if (src + sizeof(ext2_acl_entry_short) > end)
1941 dst_entry->e_tag = src_entry->e_tag;
1942 dst_entry->e_perm = src_entry->e_perm;
1943 switch (le16_to_cpu(src_entry->e_tag)) {
1948 src += sizeof(ext2_acl_entry_short);
1949 dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
1953 src += sizeof(ext2_acl_entry);
1956 dst_entry->e_id = src_entry->e_id;
1969 static char *xattr_prefix_table[] = {
1971 [2] = "system.posix_acl_access",
1972 [3] = "system.posix_acl_default",
1977 static int ext2_copy_single_xattr(struct btrfs_trans_handle *trans,
1978 struct btrfs_root *root, u64 objectid,
1979 struct ext2_ext_attr_entry *entry,
1980 const void *data, u32 datalen)
1985 void *databuf = NULL;
1986 char namebuf[XATTR_NAME_MAX + 1];
1988 name_index = entry->e_name_index;
1989 if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
1990 xattr_prefix_table[name_index] == NULL)
1992 name_len = strlen(xattr_prefix_table[name_index]) +
1994 if (name_len >= sizeof(namebuf))
1997 if (name_index == 2 || name_index == 3) {
1998 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
1999 databuf = malloc(bufsize);
2002 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
2008 strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
2009 strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
2010 if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
2011 sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
2012 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
2013 objectid - INO_OFFSET, name_len, namebuf);
2016 ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
2017 data, datalen, objectid);
2023 static int ext2_copy_extended_attrs(struct btrfs_trans_handle *trans,
2024 struct btrfs_root *root, u64 objectid,
2025 struct btrfs_inode_item *btrfs_inode,
2026 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
2032 u32 block_size = ext2_fs->blocksize;
2033 u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
2034 struct ext2_inode_large *ext2_inode;
2035 struct ext2_ext_attr_entry *entry;
2037 char *buffer = NULL;
2038 char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
2040 if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
2041 ext2_inode = (struct ext2_inode_large *)inode_buf;
2043 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
2047 err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
2050 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
2051 error_message(err));
2056 if (ext2_ino > ext2_fs->super->s_first_ino &&
2057 inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
2058 if (EXT2_GOOD_OLD_INODE_SIZE +
2059 ext2_inode->i_extra_isize > inode_size) {
2063 if (ext2_inode->i_extra_isize != 0 &&
2064 EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
2065 EXT2_EXT_ATTR_MAGIC) {
2071 void *end = (void *)ext2_inode + inode_size;
2072 entry = EXT2_XATTR_IFIRST(ext2_inode);
2073 total = end - (void *)entry;
2074 ret = ext2_xattr_check_names(entry, end);
2077 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2078 ret = ext2_xattr_check_entry(entry, total);
2081 data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
2082 entry->e_value_offs;
2083 datalen = entry->e_value_size;
2084 ret = ext2_copy_single_xattr(trans, root, objectid,
2085 entry, data, datalen);
2088 entry = EXT2_EXT_ATTR_NEXT(entry);
2092 if (ext2_inode->i_file_acl == 0)
2095 buffer = malloc(block_size);
2100 err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
2102 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
2103 error_message(err));
2107 ret = ext2_xattr_check_block(buffer, block_size);
2111 entry = EXT2_XATTR_BFIRST(buffer);
2112 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2113 ret = ext2_xattr_check_entry(entry, block_size);
2116 data = buffer + entry->e_value_offs;
2117 datalen = entry->e_value_size;
2118 ret = ext2_copy_single_xattr(trans, root, objectid,
2119 entry, data, datalen);
2122 entry = EXT2_EXT_ATTR_NEXT(entry);
2126 if ((void *)ext2_inode != inode_buf)
2130 #define MINORBITS 20
2131 #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
2133 static inline dev_t old_decode_dev(u16 val)
2135 return MKDEV((val >> 8) & 255, val & 255);
2138 static inline dev_t new_decode_dev(u32 dev)
2140 unsigned major = (dev & 0xfff00) >> 8;
2141 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
2142 return MKDEV(major, minor);
2145 static void ext2_copy_inode_item(struct btrfs_inode_item *dst,
2146 struct ext2_inode *src, u32 blocksize)
2148 btrfs_set_stack_inode_generation(dst, 1);
2149 btrfs_set_stack_inode_sequence(dst, 0);
2150 btrfs_set_stack_inode_transid(dst, 1);
2151 btrfs_set_stack_inode_size(dst, src->i_size);
2152 btrfs_set_stack_inode_nbytes(dst, 0);
2153 btrfs_set_stack_inode_block_group(dst, 0);
2154 btrfs_set_stack_inode_nlink(dst, src->i_links_count);
2155 btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
2156 btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
2157 btrfs_set_stack_inode_mode(dst, src->i_mode);
2158 btrfs_set_stack_inode_rdev(dst, 0);
2159 btrfs_set_stack_inode_flags(dst, 0);
2160 btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
2161 btrfs_set_stack_timespec_nsec(&dst->atime, 0);
2162 btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
2163 btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
2164 btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
2165 btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
2166 btrfs_set_stack_timespec_sec(&dst->otime, 0);
2167 btrfs_set_stack_timespec_nsec(&dst->otime, 0);
2169 if (S_ISDIR(src->i_mode)) {
2170 btrfs_set_stack_inode_size(dst, 0);
2171 btrfs_set_stack_inode_nlink(dst, 1);
2173 if (S_ISREG(src->i_mode)) {
2174 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
2177 if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
2178 !S_ISLNK(src->i_mode)) {
2179 if (src->i_block[0]) {
2180 btrfs_set_stack_inode_rdev(dst,
2181 old_decode_dev(src->i_block[0]));
2183 btrfs_set_stack_inode_rdev(dst,
2184 new_decode_dev(src->i_block[1]));
2187 memset(&dst->reserved, 0, sizeof(dst->reserved));
2189 static int ext2_check_state(struct btrfs_convert_context *cctx)
2191 ext2_filsys fs = cctx->fs_data;
2193 if (!(fs->super->s_state & EXT2_VALID_FS))
2195 else if (fs->super->s_state & EXT2_ERROR_FS)
2201 /* EXT2_*_FL to BTRFS_INODE_FLAG_* stringification helper */
2202 #define COPY_ONE_EXT2_FLAG(flags, ext2_inode, name) ({ \
2203 if (ext2_inode->i_flags & EXT2_##name##_FL) \
2204 flags |= BTRFS_INODE_##name; \
2208 * Convert EXT2_*_FL to corresponding BTRFS_INODE_* flags
2210 * Only a subset of EXT_*_FL is supported in btrfs.
2212 static void ext2_convert_inode_flags(struct btrfs_inode_item *dst,
2213 struct ext2_inode *src)
2217 COPY_ONE_EXT2_FLAG(flags, src, APPEND);
2218 COPY_ONE_EXT2_FLAG(flags, src, SYNC);
2219 COPY_ONE_EXT2_FLAG(flags, src, IMMUTABLE);
2220 COPY_ONE_EXT2_FLAG(flags, src, NODUMP);
2221 COPY_ONE_EXT2_FLAG(flags, src, NOATIME);
2222 COPY_ONE_EXT2_FLAG(flags, src, DIRSYNC);
2223 btrfs_set_stack_inode_flags(dst, flags);
2227 * copy a single inode. do all the required works, such as cloning
2228 * inode item, creating file extents and creating directory entries.
2230 static int ext2_copy_single_inode(struct btrfs_trans_handle *trans,
2231 struct btrfs_root *root, u64 objectid,
2232 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
2233 struct ext2_inode *ext2_inode,
2234 int datacsum, int packing, int noxattr)
2237 struct btrfs_inode_item btrfs_inode;
2239 if (ext2_inode->i_links_count == 0)
2242 ext2_copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
2243 if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
2244 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
2245 BTRFS_INODE_NODATASUM;
2246 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
2248 ext2_convert_inode_flags(&btrfs_inode, ext2_inode);
2250 switch (ext2_inode->i_mode & S_IFMT) {
2252 ret = ext2_create_file_extents(trans, root, objectid,
2253 &btrfs_inode, ext2_fs, ext2_ino, datacsum, packing);
2256 ret = ext2_create_dir_entries(trans, root, objectid,
2257 &btrfs_inode, ext2_fs, ext2_ino);
2260 ret = ext2_create_symbol_link(trans, root, objectid,
2261 &btrfs_inode, ext2_fs, ext2_ino, ext2_inode);
2271 ret = ext2_copy_extended_attrs(trans, root, objectid,
2272 &btrfs_inode, ext2_fs, ext2_ino);
2276 return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
2280 * scan ext2's inode bitmap and copy all used inodes.
2282 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
2283 struct btrfs_root *root,
2284 int datacsum, int packing, int noxattr, struct task_ctx *p)
2286 ext2_filsys ext2_fs = cctx->fs_data;
2289 ext2_inode_scan ext2_scan;
2290 struct ext2_inode ext2_inode;
2291 ext2_ino_t ext2_ino;
2293 struct btrfs_trans_handle *trans;
2295 trans = btrfs_start_transaction(root, 1);
2298 err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
2300 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
2303 while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
2305 /* no more inodes */
2308 /* skip special inode in ext2fs */
2309 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
2310 ext2_ino != EXT2_ROOT_INO)
2312 objectid = ext2_ino + INO_OFFSET;
2313 ret = ext2_copy_single_inode(trans, root,
2314 objectid, ext2_fs, ext2_ino,
2315 &ext2_inode, datacsum, packing,
2317 p->cur_copy_inodes++;
2320 if (trans->blocks_used >= 4096) {
2321 ret = btrfs_commit_transaction(trans, root);
2323 trans = btrfs_start_transaction(root, 1);
2328 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
2331 ret = btrfs_commit_transaction(trans, root);
2333 ext2fs_close_inode_scan(ext2_scan);
2338 static const struct btrfs_convert_operations ext2_convert_ops = {
2340 .open_fs = ext2_open_fs,
2341 .read_used_space = ext2_read_used_space,
2342 .copy_inodes = ext2_copy_inodes,
2343 .close_fs = ext2_close_fs,
2344 .check_state = ext2_check_state,
2349 static const struct btrfs_convert_operations *convert_operations[] = {
2350 #if BTRFSCONVERT_EXT2
2355 static int convert_open_fs(const char *devname,
2356 struct btrfs_convert_context *cctx)
2360 memset(cctx, 0, sizeof(*cctx));
2362 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2363 int ret = convert_operations[i]->open_fs(cctx, devname);
2366 cctx->convert_ops = convert_operations[i];
2371 error("no file system found to convert");
2375 static int do_convert(const char *devname, int datacsum, int packing,
2376 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
2377 int progress, u64 features)
2383 struct btrfs_root *root;
2384 struct btrfs_root *image_root;
2385 struct btrfs_convert_context cctx;
2386 struct btrfs_key key;
2387 char *subvol_name = NULL;
2388 struct task_ctx ctx;
2389 char features_buf[64];
2390 struct btrfs_mkfs_config mkfs_cfg;
2392 init_convert_context(&cctx);
2393 ret = convert_open_fs(devname, &cctx);
2396 ret = convert_check_state(&cctx);
2399 "source filesystem is not clean, running filesystem check is recommended");
2400 ret = convert_read_used_space(&cctx);
2404 blocksize = cctx.blocksize;
2405 total_bytes = (u64)blocksize * (u64)cctx.block_count;
2406 if (blocksize < 4096) {
2407 error("block size is too small: %u < 4096", blocksize);
2410 if (btrfs_check_nodesize(nodesize, blocksize, features))
2412 fd = open(devname, O_RDWR);
2414 error("unable to open %s: %s", devname, strerror(errno));
2417 btrfs_parse_features_to_string(features_buf, features);
2418 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2419 strcat(features_buf, " (default)");
2421 printf("create btrfs filesystem:\n");
2422 printf("\tblocksize: %u\n", blocksize);
2423 printf("\tnodesize: %u\n", nodesize);
2424 printf("\tfeatures: %s\n", features_buf);
2426 mkfs_cfg.label = cctx.volume_name;
2427 mkfs_cfg.num_bytes = total_bytes;
2428 mkfs_cfg.nodesize = nodesize;
2429 mkfs_cfg.sectorsize = blocksize;
2430 mkfs_cfg.stripesize = blocksize;
2431 mkfs_cfg.features = features;
2432 /* New convert need these space */
2433 memset(mkfs_cfg.chunk_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2434 memset(mkfs_cfg.fs_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2436 ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
2438 error("unable to create initial ctree: %s", strerror(-ret));
2442 root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
2443 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2445 error("unable to open ctree");
2448 ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
2450 error("unable to setup the root tree: %d", ret);
2454 printf("creating %s image file\n", cctx.convert_ops->name);
2455 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2457 error("memory allocation failure for subvolume name: %s_saved",
2458 cctx.convert_ops->name);
2461 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2462 key.offset = (u64)-1;
2463 key.type = BTRFS_ROOT_ITEM_KEY;
2464 image_root = btrfs_read_fs_root(root->fs_info, &key);
2466 error("unable to create image subvolume");
2469 ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
2470 mkfs_cfg.num_bytes, "image", datacsum);
2472 error("failed to create %s/image: %d", subvol_name, ret);
2476 printf("creating btrfs metadata");
2477 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2478 ctx.cur_copy_inodes = 0;
2481 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
2483 task_start(ctx.info);
2485 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2487 error("error during copy_inodes %d", ret);
2491 task_stop(ctx.info);
2492 task_deinit(ctx.info);
2495 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2497 error("unable to link subvolume %s", subvol_name);
2503 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2504 if (copylabel == 1) {
2505 __strncpy_null(root->fs_info->super_copy->label,
2506 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2507 printf("copy label '%s'\n", root->fs_info->super_copy->label);
2508 } else if (copylabel == -1) {
2509 strcpy(root->fs_info->super_copy->label, fslabel);
2510 printf("set label to '%s'\n", fslabel);
2513 ret = close_ctree(root);
2515 error("close_ctree failed: %d", ret);
2518 convert_close_fs(&cctx);
2519 clean_convert_context(&cctx);
2522 * If this step succeed, we get a mountable btrfs. Otherwise
2523 * the source fs is left unchanged.
2525 ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
2527 error("unable to migrate super block: %d", ret);
2531 root = open_ctree_fd(fd, devname, 0,
2532 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2534 error("unable to open ctree for finalization");
2537 root->fs_info->finalize_on_close = 1;
2541 printf("conversion complete");
2544 clean_convert_context(&cctx);
2548 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
2553 * Check if a non 1:1 mapped chunk can be rolled back.
2554 * For new convert, it's OK while for old convert it's not.
2556 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
2558 struct btrfs_block_group_cache *bg;
2559 struct btrfs_key key;
2560 struct btrfs_path path;
2561 struct btrfs_root *extent_root = fs_info->extent_root;
2566 bg = btrfs_lookup_first_block_group(fs_info, bytenr);
2569 bg_start = bg->key.objectid;
2570 bg_end = bg->key.objectid + bg->key.offset;
2572 key.objectid = bg_end;
2573 key.type = BTRFS_METADATA_ITEM_KEY;
2575 btrfs_init_path(&path);
2577 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2582 struct btrfs_extent_item *ei;
2584 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
2592 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2593 if (key.type == BTRFS_METADATA_ITEM_KEY)
2595 /* Now it's EXTENT_ITEM_KEY only */
2596 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
2597 struct btrfs_extent_item);
2599 * Found data extent, means this is old convert must follow 1:1
2602 if (btrfs_extent_flags(path.nodes[0], ei)
2603 & BTRFS_EXTENT_FLAG_DATA) {
2608 btrfs_release_path(&path);
2612 static int may_rollback(struct btrfs_root *root)
2614 struct btrfs_fs_info *info = root->fs_info;
2615 struct btrfs_multi_bio *multi = NULL;
2623 if (btrfs_super_num_devices(info->super_copy) != 1)
2626 bytenr = BTRFS_SUPER_INFO_OFFSET;
2627 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2630 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2631 &length, &multi, 0, NULL);
2633 if (ret == -ENOENT) {
2634 /* removed block group at the tail */
2635 if (length == (u64)-1)
2638 /* removed block group in the middle */
2644 num_stripes = multi->num_stripes;
2645 physical = multi->stripes[0].physical;
2648 if (num_stripes != 1) {
2649 error("num stripes for bytenr %llu is not 1", bytenr);
2654 * Extra check for new convert, as metadata chunk from new
2655 * convert is much more free than old convert, it doesn't need
2656 * to do 1:1 mapping.
2658 if (physical != bytenr) {
2660 * Check if it's a metadata chunk and has only metadata
2663 ret = may_rollback_chunk(info, bytenr);
2669 if (bytenr >= total_bytes)
2677 static int do_rollback(const char *devname)
2682 struct btrfs_root *root;
2683 struct btrfs_root *image_root;
2684 struct btrfs_root *chunk_root;
2685 struct btrfs_dir_item *dir;
2686 struct btrfs_inode_item *inode;
2687 struct btrfs_file_extent_item *fi;
2688 struct btrfs_trans_handle *trans;
2689 struct extent_buffer *leaf;
2690 struct btrfs_block_group_cache *cache1;
2691 struct btrfs_block_group_cache *cache2;
2692 struct btrfs_key key;
2693 struct btrfs_path path;
2694 struct extent_io_tree io_tree;
2709 extent_io_tree_init(&io_tree);
2711 fd = open(devname, O_RDWR);
2713 error("unable to open %s: %s", devname, strerror(errno));
2716 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2718 error("unable to open ctree");
2721 ret = may_rollback(root);
2723 error("unable to do rollback: %d", ret);
2727 sectorsize = root->sectorsize;
2728 buf = malloc(sectorsize);
2730 error("unable to allocate memory");
2734 btrfs_init_path(&path);
2736 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2737 key.type = BTRFS_ROOT_BACKREF_KEY;
2738 key.offset = BTRFS_FS_TREE_OBJECTID;
2739 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2741 btrfs_release_path(&path);
2743 error("unable to convert ext2 image subvolume, is it deleted?");
2745 } else if (ret < 0) {
2746 error("unable to open ext2_saved, id %llu: %s",
2747 (unsigned long long)key.objectid, strerror(-ret));
2751 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2752 key.type = BTRFS_ROOT_ITEM_KEY;
2753 key.offset = (u64)-1;
2754 image_root = btrfs_read_fs_root(root->fs_info, &key);
2755 if (!image_root || IS_ERR(image_root)) {
2756 error("unable to open subvolume %llu: %ld",
2757 (unsigned long long)key.objectid, PTR_ERR(image_root));
2762 root_dir = btrfs_root_dirid(&root->root_item);
2763 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2764 root_dir, name, strlen(name), 0);
2765 if (!dir || IS_ERR(dir)) {
2766 error("unable to find file %s: %ld", name, PTR_ERR(dir));
2769 leaf = path.nodes[0];
2770 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2771 btrfs_release_path(&path);
2773 objectid = key.objectid;
2775 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2777 error("unable to find inode item: %d", ret);
2780 leaf = path.nodes[0];
2781 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2782 total_bytes = btrfs_inode_size(leaf, inode);
2783 btrfs_release_path(&path);
2785 key.objectid = objectid;
2787 key.type = BTRFS_EXTENT_DATA_KEY;
2788 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2790 error("unable to find first file extent: %d", ret);
2791 btrfs_release_path(&path);
2795 /* build mapping tree for the relocated blocks */
2796 for (offset = 0; offset < total_bytes; ) {
2797 leaf = path.nodes[0];
2798 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2799 ret = btrfs_next_leaf(root, &path);
2805 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2806 if (key.objectid != objectid || key.offset != offset ||
2807 key.type != BTRFS_EXTENT_DATA_KEY)
2810 fi = btrfs_item_ptr(leaf, path.slots[0],
2811 struct btrfs_file_extent_item);
2812 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2814 if (btrfs_file_extent_compression(leaf, fi) ||
2815 btrfs_file_extent_encryption(leaf, fi) ||
2816 btrfs_file_extent_other_encoding(leaf, fi))
2819 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2820 /* skip holes and direct mapped extents */
2821 if (bytenr == 0 || bytenr == offset)
2824 bytenr += btrfs_file_extent_offset(leaf, fi);
2825 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2827 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2828 cache2 = btrfs_lookup_block_group(root->fs_info,
2829 offset + num_bytes - 1);
2831 * Here we must take consideration of old and new convert
2833 * For old convert case, sign, there is no consist chunk type
2834 * that will cover the extent. META/DATA/SYS are all possible.
2835 * Just ensure relocate one is in SYS chunk.
2836 * For new convert case, they are all covered by DATA chunk.
2838 * So, there is not valid chunk type check for it now.
2840 if (cache1 != cache2)
2843 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2844 EXTENT_LOCKED, GFP_NOFS);
2845 set_state_private(&io_tree, offset, bytenr);
2847 offset += btrfs_file_extent_num_bytes(leaf, fi);
2850 btrfs_release_path(&path);
2852 if (offset < total_bytes) {
2853 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
2854 (unsigned long long)offset,
2855 (unsigned long long)total_bytes);
2856 error("converted filesystem after balance is unable to rollback");
2860 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2861 first_free &= ~((u64)sectorsize - 1);
2862 /* backup for extent #0 should exist */
2863 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2864 error("no backup for the first extent");
2867 /* force no allocation from system block group */
2868 root->fs_info->system_allocs = -1;
2869 trans = btrfs_start_transaction(root, 1);
2871 error("unable to start transaction");
2875 * recow the whole chunk tree, this will remove all chunk tree blocks
2876 * from system block group
2878 chunk_root = root->fs_info->chunk_root;
2879 memset(&key, 0, sizeof(key));
2881 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2885 ret = btrfs_next_leaf(chunk_root, &path);
2889 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2890 btrfs_release_path(&path);
2892 btrfs_release_path(&path);
2897 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2901 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2902 num_bytes += btrfs_block_group_used(&cache1->item);
2904 offset = cache1->key.objectid + cache1->key.offset;
2906 /* only extent #0 left in system block group? */
2907 if (num_bytes > first_free) {
2909 "unable to empty system block group (num_bytes %llu, first_free %llu",
2910 (unsigned long long)num_bytes,
2911 (unsigned long long)first_free);
2914 /* create a system chunk that maps the whole device */
2915 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2917 error("unable to update system chunk: %d", ret);
2921 ret = btrfs_commit_transaction(trans, root);
2923 error("transaction commit failed: %d", ret);
2927 ret = close_ctree(root);
2929 error("close_ctree failed: %d", ret);
2933 /* zero btrfs super block mirrors */
2934 memset(buf, 0, sectorsize);
2935 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2936 bytenr = btrfs_sb_offset(i);
2937 if (bytenr >= total_bytes)
2939 ret = pwrite(fd, buf, sectorsize, bytenr);
2940 if (ret != sectorsize) {
2941 error("zeroing superblock mirror %d failed: %d",
2947 sb_bytenr = (u64)-1;
2948 /* copy all relocated blocks back */
2950 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2955 ret = get_state_private(&io_tree, start, &bytenr);
2958 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2961 while (start <= end) {
2962 if (start == BTRFS_SUPER_INFO_OFFSET) {
2966 ret = pread(fd, buf, sectorsize, bytenr);
2968 error("reading superblock at %llu failed: %d",
2969 (unsigned long long)bytenr, ret);
2972 BUG_ON(ret != sectorsize);
2973 ret = pwrite(fd, buf, sectorsize, start);
2975 error("writing superblock at %llu failed: %d",
2976 (unsigned long long)start, ret);
2979 BUG_ON(ret != sectorsize);
2981 start += sectorsize;
2982 bytenr += sectorsize;
2988 error("fsync failed: %s", strerror(errno));
2992 * finally, overwrite btrfs super block.
2994 ret = pread(fd, buf, sectorsize, sb_bytenr);
2996 error("reading primary superblock failed: %s",
3000 BUG_ON(ret != sectorsize);
3001 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3003 error("writing primary superblock failed: %s",
3007 BUG_ON(ret != sectorsize);
3010 error("fsync failed: %s", strerror(errno));
3016 extent_io_tree_cleanup(&io_tree);
3017 printf("rollback complete\n");
3024 error("rollback aborted");
3028 static void print_usage(void)
3030 printf("usage: btrfs-convert [options] device\n");
3031 printf("options:\n");
3032 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
3033 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
3034 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
3035 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
3036 printf("\t-r|--rollback roll back to the original filesystem\n");
3037 printf("\t-l|--label LABEL set filesystem label\n");
3038 printf("\t-L|--copy-label use label from converted filesystem\n");
3039 printf("\t-p|--progress show converting progress (default)\n");
3040 printf("\t-O|--features LIST comma separated list of filesystem features\n");
3041 printf("\t--no-progress show only overview, not the detailed progress\n");
3043 printf("Supported filesystems:\n");
3044 printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
3047 int main(int argc, char *argv[])
3053 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3054 BTRFS_MKFS_DEFAULT_NODE_SIZE);
3057 int usage_error = 0;
3060 char fslabel[BTRFS_LABEL_SIZE];
3061 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3064 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3065 static const struct option long_options[] = {
3066 { "no-progress", no_argument, NULL,
3067 GETOPT_VAL_NO_PROGRESS },
3068 { "no-datasum", no_argument, NULL, 'd' },
3069 { "no-inline", no_argument, NULL, 'n' },
3070 { "no-xattr", no_argument, NULL, 'i' },
3071 { "rollback", no_argument, NULL, 'r' },
3072 { "features", required_argument, NULL, 'O' },
3073 { "progress", no_argument, NULL, 'p' },
3074 { "label", required_argument, NULL, 'l' },
3075 { "copy-label", no_argument, NULL, 'L' },
3076 { "nodesize", required_argument, NULL, 'N' },
3077 { "help", no_argument, NULL, GETOPT_VAL_HELP},
3078 { NULL, 0, NULL, 0 }
3080 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3095 nodesize = parse_size(optarg);
3102 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3104 "label too long, trimmed to %d bytes",
3105 BTRFS_LABEL_SIZE - 1);
3107 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3116 char *orig = strdup(optarg);
3119 tmp = btrfs_parse_fs_features(tmp, &features);
3121 error("unrecognized filesystem feature: %s",
3127 if (features & BTRFS_FEATURE_LIST_ALL) {
3128 btrfs_list_all_fs_features(
3129 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3132 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3135 btrfs_parse_features_to_string(buf,
3136 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3137 error("features not allowed for convert: %s",
3144 case GETOPT_VAL_NO_PROGRESS:
3147 case GETOPT_VAL_HELP:
3150 return c != GETOPT_VAL_HELP;
3154 if (check_argc_exact(argc - optind, 1)) {
3159 if (rollback && (!datacsum || noxattr || !packing)) {
3161 "Usage error: -d, -i, -n options do not apply to rollback\n");
3170 file = argv[optind];
3171 ret = check_mounted(file);
3173 error("could not check mount status: %s", strerror(-ret));
3176 error("%s is mounted", file);
3181 ret = do_rollback(file);
3183 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3184 copylabel, fslabel, progress, features);