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"
42 #include "convert/common.h"
43 #include "fsfeatures.h"
46 #include <ext2fs/ext2_fs.h>
47 #include <ext2fs/ext2fs.h>
48 #include <ext2fs/ext2_ext_attr.h>
50 #define INO_OFFSET (BTRFS_FIRST_FREE_OBJECTID - EXT2_ROOT_INO)
53 * Compatibility code for e2fsprogs 1.41 which doesn't support RO compat flag
55 * Unlike normal RO compat flag, BIGALLOC affects how e2fsprogs check used
56 * space, and btrfs-convert heavily relies on it.
58 #ifdef HAVE_OLD_E2FSPROGS
59 #define EXT2FS_CLUSTER_RATIO(fs) (1)
60 #define EXT2_CLUSTERS_PER_GROUP(s) (EXT2_BLOCKS_PER_GROUP(s))
61 #define EXT2FS_B2C(fs, blk) (blk)
66 #define CONV_IMAGE_SUBVOL_OBJECTID BTRFS_FIRST_FREE_OBJECTID
69 uint32_t max_copy_inodes;
70 uint32_t cur_copy_inodes;
71 struct task_info *info;
74 static void *print_copied_inodes(void *p)
76 struct task_ctx *priv = p;
77 const char work_indicator[] = { '.', 'o', 'O', 'o' };
80 task_period_start(priv->info, 1000 /* 1s */);
83 printf("copy inodes [%c] [%10d/%10d]\r",
84 work_indicator[count % 4], priv->cur_copy_inodes,
85 priv->max_copy_inodes);
87 task_period_wait(priv->info);
93 static int after_copied_inodes(void *p)
101 struct btrfs_convert_context;
102 struct btrfs_convert_operations {
104 int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
105 int (*read_used_space)(struct btrfs_convert_context *cctx);
106 int (*copy_inodes)(struct btrfs_convert_context *cctx,
107 struct btrfs_root *root, int datacsum,
108 int packing, int noxattr, struct task_ctx *p);
109 void (*close_fs)(struct btrfs_convert_context *cctx);
110 int (*check_state)(struct btrfs_convert_context *cctx);
113 static void init_convert_context(struct btrfs_convert_context *cctx)
115 cache_tree_init(&cctx->used);
116 cache_tree_init(&cctx->data_chunks);
117 cache_tree_init(&cctx->free);
120 static void clean_convert_context(struct btrfs_convert_context *cctx)
122 free_extent_cache_tree(&cctx->used);
123 free_extent_cache_tree(&cctx->data_chunks);
124 free_extent_cache_tree(&cctx->free);
127 static inline int copy_inodes(struct btrfs_convert_context *cctx,
128 struct btrfs_root *root, int datacsum,
129 int packing, int noxattr, struct task_ctx *p)
131 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
135 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
137 cctx->convert_ops->close_fs(cctx);
140 static inline int convert_check_state(struct btrfs_convert_context *cctx)
142 return cctx->convert_ops->check_state(cctx);
145 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
150 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
151 offset = btrfs_sb_offset(i);
152 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
154 if (bytenr < offset + BTRFS_STRIPE_LEN &&
155 bytenr + num_bytes > offset)
161 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
162 struct btrfs_root *root,
163 const char *name, size_t name_len,
164 u64 dir, u64 objectid,
165 u8 file_type, u64 index_cnt,
166 struct btrfs_inode_item *inode)
170 struct btrfs_key location = {
171 .objectid = objectid,
173 .type = BTRFS_INODE_ITEM_KEY,
176 ret = btrfs_insert_dir_item(trans, root, name, name_len,
177 dir, &location, file_type, index_cnt);
180 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
181 objectid, dir, index_cnt);
184 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
185 btrfs_set_stack_inode_size(inode, inode_size);
190 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
191 u32 num_bytes, char *buffer)
194 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
196 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
197 if (ret != num_bytes)
206 static int csum_disk_extent(struct btrfs_trans_handle *trans,
207 struct btrfs_root *root,
208 u64 disk_bytenr, u64 num_bytes)
210 u32 blocksize = root->sectorsize;
215 buffer = malloc(blocksize);
218 for (offset = 0; offset < num_bytes; offset += blocksize) {
219 ret = read_disk_extent(root, disk_bytenr + offset,
223 ret = btrfs_csum_file_block(trans,
224 root->fs_info->csum_root,
225 disk_bytenr + num_bytes,
226 disk_bytenr + offset,
235 struct blk_iterate_data {
236 struct btrfs_trans_handle *trans;
237 struct btrfs_root *root;
238 struct btrfs_root *convert_root;
239 struct btrfs_inode_item *inode;
250 static void init_blk_iterate_data(struct blk_iterate_data *data,
251 struct btrfs_trans_handle *trans,
252 struct btrfs_root *root,
253 struct btrfs_inode_item *inode,
254 u64 objectid, int checksum)
256 struct btrfs_key key;
261 data->objectid = objectid;
262 data->first_block = 0;
263 data->disk_block = 0;
264 data->num_blocks = 0;
265 data->boundary = (u64)-1;
266 data->checksum = checksum;
269 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
270 key.type = BTRFS_ROOT_ITEM_KEY;
271 key.offset = (u64)-1;
272 data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
273 /* Impossible as we just opened it before */
274 BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
275 data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
279 * Record a file extent in original filesystem into btrfs one.
280 * The special point is, old disk_block can point to a reserved range.
281 * So here, we don't use disk_block directly but search convert_root
282 * to get the real disk_bytenr.
284 static int record_file_blocks(struct blk_iterate_data *data,
285 u64 file_block, u64 disk_block, u64 num_blocks)
288 struct btrfs_root *root = data->root;
289 struct btrfs_root *convert_root = data->convert_root;
290 struct btrfs_path path;
291 u64 file_pos = file_block * root->sectorsize;
292 u64 old_disk_bytenr = disk_block * root->sectorsize;
293 u64 num_bytes = num_blocks * root->sectorsize;
294 u64 cur_off = old_disk_bytenr;
296 /* Hole, pass it to record_file_extent directly */
297 if (old_disk_bytenr == 0)
298 return btrfs_record_file_extent(data->trans, root,
299 data->objectid, data->inode, file_pos, 0,
302 btrfs_init_path(&path);
305 * Search real disk bytenr from convert root
307 while (cur_off < old_disk_bytenr + num_bytes) {
308 struct btrfs_key key;
309 struct btrfs_file_extent_item *fi;
310 struct extent_buffer *node;
312 u64 extent_disk_bytenr;
313 u64 extent_num_bytes;
314 u64 real_disk_bytenr;
317 key.objectid = data->convert_ino;
318 key.type = BTRFS_EXTENT_DATA_KEY;
319 key.offset = cur_off;
321 ret = btrfs_search_slot(NULL, convert_root, &key, &path, 0, 0);
325 ret = btrfs_previous_item(convert_root, &path,
327 BTRFS_EXTENT_DATA_KEY);
335 node = path.nodes[0];
336 slot = path.slots[0];
337 btrfs_item_key_to_cpu(node, &key, slot);
338 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
339 key.objectid != data->convert_ino ||
340 key.offset > cur_off);
341 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
342 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
343 extent_num_bytes = btrfs_file_extent_num_bytes(node, fi);
344 BUG_ON(cur_off - key.offset >= extent_num_bytes);
345 btrfs_release_path(&path);
347 if (extent_disk_bytenr)
348 real_disk_bytenr = cur_off - key.offset +
351 real_disk_bytenr = 0;
352 cur_len = min(key.offset + extent_num_bytes,
353 old_disk_bytenr + num_bytes) - cur_off;
354 ret = btrfs_record_file_extent(data->trans, data->root,
355 data->objectid, data->inode, file_pos,
356 real_disk_bytenr, cur_len);
363 * No need to care about csum
364 * As every byte of old fs image is calculated for csum, no
365 * need to waste CPU cycles now.
368 btrfs_release_path(&path);
372 static int block_iterate_proc(u64 disk_block, u64 file_block,
373 struct blk_iterate_data *idata)
378 struct btrfs_root *root = idata->root;
379 struct btrfs_block_group_cache *cache;
380 u64 bytenr = disk_block * root->sectorsize;
382 sb_region = intersect_with_sb(bytenr, root->sectorsize);
383 do_barrier = sb_region || disk_block >= idata->boundary;
384 if ((idata->num_blocks > 0 && do_barrier) ||
385 (file_block > idata->first_block + idata->num_blocks) ||
386 (disk_block != idata->disk_block + idata->num_blocks)) {
387 if (idata->num_blocks > 0) {
388 ret = record_file_blocks(idata, idata->first_block,
393 idata->first_block += idata->num_blocks;
394 idata->num_blocks = 0;
396 if (file_block > idata->first_block) {
397 ret = record_file_blocks(idata, idata->first_block,
398 0, file_block - idata->first_block);
404 bytenr += BTRFS_STRIPE_LEN - 1;
405 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
407 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
409 bytenr = cache->key.objectid + cache->key.offset;
412 idata->first_block = file_block;
413 idata->disk_block = disk_block;
414 idata->boundary = bytenr / root->sectorsize;
421 static int create_image_file_range(struct btrfs_trans_handle *trans,
422 struct btrfs_root *root,
423 struct cache_tree *used,
424 struct btrfs_inode_item *inode,
425 u64 ino, u64 bytenr, u64 *ret_len,
428 struct cache_extent *cache;
429 struct btrfs_block_group_cache *bg_cache;
435 if (bytenr != round_down(bytenr, root->sectorsize)) {
436 error("bytenr not sectorsize aligned: %llu",
437 (unsigned long long)bytenr);
440 if (len != round_down(len, root->sectorsize)) {
441 error("length not sectorsize aligned: %llu",
442 (unsigned long long)len);
445 len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
448 * Skip sb ranges first
449 * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
451 * Or we will insert a hole into current image file, and later
452 * migrate block will fail as there is already a file extent.
454 if (bytenr < 1024 * 1024) {
455 *ret_len = 1024 * 1024 - bytenr;
458 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
459 u64 cur = btrfs_sb_offset(i);
461 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
462 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
466 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
467 u64 cur = btrfs_sb_offset(i);
472 * May still need to go through file extent inserts
474 if (bytenr < cur && bytenr + len >= cur) {
475 len = min_t(u64, len, cur - bytenr);
481 * Drop out, no need to insert anything
483 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
484 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
489 cache = search_cache_extent(used, bytenr);
491 if (cache->start <= bytenr) {
493 * |///////Used///////|
497 len = min_t(u64, len, cache->start + cache->size -
499 disk_bytenr = bytenr;
506 len = min(len, cache->start - bytenr);
521 /* Check if the range is in a data block group */
522 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
525 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
528 /* The extent should never cross block group boundary */
529 len = min_t(u64, len, bg_cache->key.objectid +
530 bg_cache->key.offset - bytenr);
533 if (len != round_down(len, root->sectorsize)) {
534 error("remaining length not sectorsize aligned: %llu",
535 (unsigned long long)len);
538 ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
544 ret = csum_disk_extent(trans, root, bytenr, len);
550 * Relocate old fs data in one reserved ranges
552 * Since all old fs data in reserved range is not covered by any chunk nor
553 * data extent, we don't need to handle any reference but add new
554 * extent/reference, which makes codes more clear
556 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
557 struct btrfs_root *root,
558 struct cache_tree *used,
559 struct btrfs_inode_item *inode, int fd,
560 u64 ino, u64 start, u64 len, int datacsum)
564 u64 hole_start = start;
566 struct cache_extent *cache;
567 struct btrfs_key key;
568 struct extent_buffer *eb;
571 while (cur_off < start + len) {
572 cache = lookup_cache_extent(used, cur_off, cur_len);
575 cur_off = max(cache->start, cur_off);
576 cur_len = min(cache->start + cache->size, start + len) -
578 BUG_ON(cur_len < root->sectorsize);
580 /* reserve extent for the data */
581 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
586 eb = malloc(sizeof(*eb) + cur_len);
592 ret = pread(fd, eb->data, cur_len, cur_off);
594 ret = (ret < 0 ? ret : -EIO);
598 eb->start = key.objectid;
599 eb->len = key.offset;
602 ret = write_and_map_eb(trans, root, eb);
607 /* Now handle extent item and file extent things */
608 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
609 key.objectid, key.offset);
612 /* Finally, insert csum items */
614 ret = csum_disk_extent(trans, root, key.objectid,
617 /* Don't forget to insert hole */
618 hole_len = cur_off - hole_start;
620 ret = btrfs_record_file_extent(trans, root, ino, inode,
621 hole_start, 0, hole_len);
626 cur_off += key.offset;
627 hole_start = cur_off;
628 cur_len = start + len - cur_off;
631 if (start + len - hole_start > 0)
632 ret = btrfs_record_file_extent(trans, root, ino, inode,
633 hole_start, 0, start + len - hole_start);
638 * Relocate the used ext2 data in reserved ranges
640 * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
641 * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
643 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
644 struct btrfs_root *root,
645 struct cache_tree *used,
646 struct btrfs_inode_item *inode, int fd,
647 u64 ino, u64 total_bytes, int datacsum)
655 cur_len = 1024 * 1024;
656 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
657 cur_off, cur_len, datacsum);
661 /* second sb(fisrt sb is included in 0~1M) */
662 cur_off = btrfs_sb_offset(1);
663 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
664 if (cur_off > total_bytes)
666 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
667 cur_off, cur_len, datacsum);
672 cur_off = btrfs_sb_offset(2);
673 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
674 if (cur_off > total_bytes)
676 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
677 cur_off, cur_len, datacsum);
682 * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
683 * handle wiping a range that exists in cache.
685 static int _expand_extent_cache(struct cache_tree *tree,
686 struct cache_extent *entry,
687 u64 min_stripe_size, int backward)
689 struct cache_extent *ce;
692 if (entry->size >= min_stripe_size)
694 diff = min_stripe_size - entry->size;
697 ce = prev_cache_extent(entry);
700 if (ce->start + ce->size >= entry->start - diff) {
701 /* Directly merge with previous extent */
702 ce->size = entry->start + entry->size - ce->start;
703 remove_cache_extent(tree, entry);
708 /* No overlap, normal extent */
709 if (entry->start < diff) {
710 error("cannot find space for data chunk layout");
713 entry->start -= diff;
717 ce = next_cache_extent(entry);
720 if (entry->start + entry->size + diff >= ce->start) {
721 /* Directly merge with next extent */
722 entry->size = ce->start + ce->size - entry->start;
723 remove_cache_extent(tree, ce);
733 * Remove one reserve range from given cache tree
734 * if min_stripe_size is non-zero, it will ensure for split case,
735 * all its split cache extent is no smaller than @min_strip_size / 2.
737 static int wipe_one_reserved_range(struct cache_tree *tree,
738 u64 start, u64 len, u64 min_stripe_size,
741 struct cache_extent *cache;
744 BUG_ON(ensure_size && min_stripe_size == 0);
746 * The logical here is simplified to handle special cases only
747 * So we don't need to consider merge case for ensure_size
749 BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
750 min_stripe_size / 2 < BTRFS_STRIPE_LEN));
752 /* Also, wipe range should already be aligned */
753 BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
754 start + len != round_up(start + len, BTRFS_STRIPE_LEN));
756 min_stripe_size /= 2;
758 cache = lookup_cache_extent(tree, start, len);
762 if (start <= cache->start) {
764 * |--------cache---------|
767 BUG_ON(start + len <= cache->start);
770 * The wipe size is smaller than min_stripe_size / 2,
771 * so the result length should still meet min_stripe_size
772 * And no need to do alignment
774 cache->size -= (start + len - cache->start);
775 if (cache->size == 0) {
776 remove_cache_extent(tree, cache);
781 BUG_ON(ensure_size && cache->size < min_stripe_size);
783 cache->start = start + len;
785 } else if (start > cache->start && start + len < cache->start +
788 * |-------cache-----|
791 u64 old_start = cache->start;
792 u64 old_len = cache->size;
793 u64 insert_start = start + len;
796 cache->size = start - cache->start;
797 /* Expand the leading half part if needed */
798 if (ensure_size && cache->size < min_stripe_size) {
799 ret = _expand_extent_cache(tree, cache,
805 /* And insert the new one */
806 insert_len = old_start + old_len - start - len;
807 ret = add_merge_cache_extent(tree, insert_start, insert_len);
811 /* Expand the last half part if needed */
812 if (ensure_size && insert_len < min_stripe_size) {
813 cache = lookup_cache_extent(tree, insert_start,
815 if (!cache || cache->start != insert_start ||
816 cache->size != insert_len)
818 ret = _expand_extent_cache(tree, cache,
827 * Wipe len should be small enough and no need to expand the
830 cache->size = start - cache->start;
831 BUG_ON(ensure_size && cache->size < min_stripe_size);
836 * Remove reserved ranges from given cache_tree
838 * It will remove the following ranges
840 * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
841 * 3) 3rd superblock, +64K
843 * @min_stripe must be given for safety check
844 * and if @ensure_size is given, it will ensure affected cache_extent will be
845 * larger than min_stripe_size
847 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
852 ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
856 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
857 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
860 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
861 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
865 static int calculate_available_space(struct btrfs_convert_context *cctx)
867 struct cache_tree *used = &cctx->used;
868 struct cache_tree *data_chunks = &cctx->data_chunks;
869 struct cache_tree *free = &cctx->free;
870 struct cache_extent *cache;
873 * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
874 * works without need to consider overlap
876 u64 min_stripe_size = 2 * 16 * 1024 * 1024;
879 /* Calculate data_chunks */
880 for (cache = first_cache_extent(used); cache;
881 cache = next_cache_extent(cache)) {
884 if (cache->start + cache->size < cur_off)
886 if (cache->start > cur_off + min_stripe_size)
887 cur_off = cache->start;
888 cur_len = max(cache->start + cache->size - cur_off,
890 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
896 * remove reserved ranges, so we won't ever bother relocating an old
897 * filesystem extent to other place.
899 ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
905 * Calculate free space
906 * Always round up the start bytenr, to avoid metadata extent corss
907 * stripe boundary, as later mkfs_convert() won't have all the extent
910 for (cache = first_cache_extent(data_chunks); cache;
911 cache = next_cache_extent(cache)) {
912 if (cache->start < cur_off)
914 if (cache->start > cur_off) {
918 len = cache->start - round_up(cur_off,
920 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
922 ret = add_merge_cache_extent(free, insert_start, len);
926 cur_off = cache->start + cache->size;
928 /* Don't forget the last range */
929 if (cctx->total_bytes > cur_off) {
930 u64 len = cctx->total_bytes - cur_off;
933 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
935 ret = add_merge_cache_extent(free, insert_start, len);
940 /* Remove reserved bytes */
941 ret = wipe_reserved_ranges(free, min_stripe_size, 0);
947 * Read used space, and since we have the used space,
948 * calcuate data_chunks and free for later mkfs
950 static int convert_read_used_space(struct btrfs_convert_context *cctx)
954 ret = cctx->convert_ops->read_used_space(cctx);
958 ret = calculate_available_space(cctx);
963 * Create the fs image file of old filesystem.
965 * This is completely fs independent as we have cctx->used, only
966 * need to create file extents pointing to all the positions.
968 static int create_image(struct btrfs_root *root,
969 struct btrfs_mkfs_config *cfg,
970 struct btrfs_convert_context *cctx, int fd,
971 u64 size, char *name, int datacsum)
973 struct btrfs_inode_item buf;
974 struct btrfs_trans_handle *trans;
975 struct btrfs_path path;
976 struct btrfs_key key;
977 struct cache_extent *cache;
978 struct cache_tree used_tmp;
981 u64 flags = BTRFS_INODE_READONLY;
985 flags |= BTRFS_INODE_NODATASUM;
987 trans = btrfs_start_transaction(root, 1);
991 cache_tree_init(&used_tmp);
992 btrfs_init_path(&path);
994 ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
998 ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
1001 ret = btrfs_change_inode_flags(trans, root, ino, flags);
1004 ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1005 strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1010 key.type = BTRFS_INODE_ITEM_KEY;
1013 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1015 ret = (ret > 0 ? -ENOENT : ret);
1018 read_extent_buffer(path.nodes[0], &buf,
1019 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1021 btrfs_release_path(&path);
1024 * Create a new used space cache, which doesn't contain the reserved
1027 for (cache = first_cache_extent(&cctx->used); cache;
1028 cache = next_cache_extent(cache)) {
1029 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
1033 ret = wipe_reserved_ranges(&used_tmp, 0, 0);
1038 * Start from 1M, as 0~1M is reserved, and create_image_file_range()
1039 * can't handle bytenr 0(will consider it as a hole)
1042 while (cur < size) {
1043 u64 len = size - cur;
1045 ret = create_image_file_range(trans, root, &used_tmp,
1046 &buf, ino, cur, &len, datacsum);
1051 /* Handle the reserved ranges */
1052 ret = migrate_reserved_ranges(trans, root, &cctx->used, &buf, fd, ino,
1053 cfg->num_bytes, datacsum);
1057 key.type = BTRFS_INODE_ITEM_KEY;
1059 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1061 ret = (ret > 0 ? -ENOENT : ret);
1064 btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1065 write_extent_buffer(path.nodes[0], &buf,
1066 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1069 free_extent_cache_tree(&used_tmp);
1070 btrfs_release_path(&path);
1071 btrfs_commit_transaction(trans, root);
1075 static struct btrfs_root* link_subvol(struct btrfs_root *root,
1076 const char *base, u64 root_objectid)
1078 struct btrfs_trans_handle *trans;
1079 struct btrfs_fs_info *fs_info = root->fs_info;
1080 struct btrfs_root *tree_root = fs_info->tree_root;
1081 struct btrfs_root *new_root = NULL;
1082 struct btrfs_path path;
1083 struct btrfs_inode_item *inode_item;
1084 struct extent_buffer *leaf;
1085 struct btrfs_key key;
1086 u64 dirid = btrfs_root_dirid(&root->root_item);
1088 char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1094 if (len == 0 || len > BTRFS_NAME_LEN)
1097 btrfs_init_path(&path);
1098 key.objectid = dirid;
1099 key.type = BTRFS_DIR_INDEX_KEY;
1100 key.offset = (u64)-1;
1102 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1104 error("search for DIR_INDEX dirid %llu failed: %d",
1105 (unsigned long long)dirid, ret);
1109 if (path.slots[0] > 0) {
1111 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1112 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1113 index = key.offset + 1;
1115 btrfs_release_path(&path);
1117 trans = btrfs_start_transaction(root, 1);
1119 error("unable to start transaction");
1123 key.objectid = dirid;
1125 key.type = BTRFS_INODE_ITEM_KEY;
1127 ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
1129 error("search for INODE_ITEM %llu failed: %d",
1130 (unsigned long long)dirid, ret);
1133 leaf = path.nodes[0];
1134 inode_item = btrfs_item_ptr(leaf, path.slots[0],
1135 struct btrfs_inode_item);
1137 key.objectid = root_objectid;
1138 key.offset = (u64)-1;
1139 key.type = BTRFS_ROOT_ITEM_KEY;
1141 memcpy(buf, base, len);
1142 for (i = 0; i < 1024; i++) {
1143 ret = btrfs_insert_dir_item(trans, root, buf, len,
1144 dirid, &key, BTRFS_FT_DIR, index);
1147 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1148 if (len < 1 || len > BTRFS_NAME_LEN) {
1156 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1157 btrfs_inode_size(leaf, inode_item));
1158 btrfs_mark_buffer_dirty(leaf);
1159 btrfs_release_path(&path);
1161 /* add the backref first */
1162 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1163 BTRFS_ROOT_BACKREF_KEY,
1164 root->root_key.objectid,
1165 dirid, index, buf, len);
1167 error("unable to add root backref for %llu: %d",
1168 root->root_key.objectid, ret);
1172 /* now add the forward ref */
1173 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1174 BTRFS_ROOT_REF_KEY, root_objectid,
1175 dirid, index, buf, len);
1177 error("unable to add root ref for %llu: %d",
1178 root->root_key.objectid, ret);
1182 ret = btrfs_commit_transaction(trans, root);
1184 error("transaction commit failed: %d", ret);
1188 new_root = btrfs_read_fs_root(fs_info, &key);
1189 if (IS_ERR(new_root)) {
1190 error("unable to fs read root: %lu", PTR_ERR(new_root));
1194 btrfs_init_path(&path);
1198 static int create_subvol(struct btrfs_trans_handle *trans,
1199 struct btrfs_root *root, u64 root_objectid)
1201 struct extent_buffer *tmp;
1202 struct btrfs_root *new_root;
1203 struct btrfs_key key;
1204 struct btrfs_root_item root_item;
1207 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1212 memcpy(&root_item, &root->root_item, sizeof(root_item));
1213 btrfs_set_root_bytenr(&root_item, tmp->start);
1214 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1215 btrfs_set_root_generation(&root_item, trans->transid);
1216 free_extent_buffer(tmp);
1218 key.objectid = root_objectid;
1219 key.type = BTRFS_ROOT_ITEM_KEY;
1220 key.offset = trans->transid;
1221 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1224 key.offset = (u64)-1;
1225 new_root = btrfs_read_fs_root(root->fs_info, &key);
1226 if (!new_root || IS_ERR(new_root)) {
1227 error("unable to fs read root: %lu", PTR_ERR(new_root));
1228 return PTR_ERR(new_root);
1231 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1237 * New make_btrfs() has handle system and meta chunks quite well.
1238 * So only need to add remaining data chunks.
1240 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1241 struct btrfs_fs_info *fs_info,
1242 struct btrfs_mkfs_config *cfg,
1243 struct btrfs_convert_context *cctx)
1245 struct btrfs_root *extent_root = fs_info->extent_root;
1246 struct cache_tree *data_chunks = &cctx->data_chunks;
1247 struct cache_extent *cache;
1252 * Don't create data chunk over 10% of the convert device
1253 * And for single chunk, don't create chunk larger than 1G.
1255 max_chunk_size = cfg->num_bytes / 10;
1256 max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1257 max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1259 for (cache = first_cache_extent(data_chunks); cache;
1260 cache = next_cache_extent(cache)) {
1261 u64 cur = cache->start;
1263 while (cur < cache->start + cache->size) {
1265 u64 cur_backup = cur;
1267 len = min(max_chunk_size,
1268 cache->start + cache->size - cur);
1269 ret = btrfs_alloc_data_chunk(trans, extent_root,
1271 BTRFS_BLOCK_GROUP_DATA, 1);
1274 ret = btrfs_make_block_group(trans, extent_root, 0,
1275 BTRFS_BLOCK_GROUP_DATA,
1276 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1287 * Init the temp btrfs to a operational status.
1289 * It will fix the extent usage accounting(XXX: Do we really need?) and
1290 * insert needed data chunks, to ensure all old fs data extents are covered
1291 * by DATA chunks, preventing wrong chunks are allocated.
1293 * And also create convert image subvolume and relocation tree.
1294 * (XXX: Not need again?)
1295 * But the convert image subvolume is *NOT* linked to fs tree yet.
1297 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1298 struct btrfs_convert_context *cctx, int datacsum,
1299 int packing, int noxattr)
1301 struct btrfs_key location;
1302 struct btrfs_trans_handle *trans;
1303 struct btrfs_fs_info *fs_info = root->fs_info;
1307 * Don't alloc any metadata/system chunk, as we don't want
1308 * any meta/sys chunk allcated before all data chunks are inserted.
1309 * Or we screw up the chunk layout just like the old implement.
1311 fs_info->avoid_sys_chunk_alloc = 1;
1312 fs_info->avoid_meta_chunk_alloc = 1;
1313 trans = btrfs_start_transaction(root, 1);
1315 error("unable to start transaction");
1319 ret = btrfs_fix_block_accounting(trans, root);
1322 ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1325 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1326 BTRFS_ROOT_TREE_DIR_OBJECTID);
1329 memcpy(&location, &root->root_key, sizeof(location));
1330 location.offset = (u64)-1;
1331 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1332 btrfs_super_root_dir(fs_info->super_copy),
1333 &location, BTRFS_FT_DIR, 0);
1336 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1338 btrfs_super_root_dir(fs_info->super_copy), 0);
1341 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1342 BTRFS_FIRST_FREE_OBJECTID);
1344 /* subvol for fs image file */
1345 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1347 error("failed to create subvolume image root: %d", ret);
1350 /* subvol for data relocation tree */
1351 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1353 error("failed to create DATA_RELOC root: %d", ret);
1357 ret = btrfs_commit_transaction(trans, root);
1358 fs_info->avoid_sys_chunk_alloc = 0;
1359 fs_info->avoid_meta_chunk_alloc = 0;
1365 * Migrate super block to its default position and zero 0 ~ 16k
1367 static int migrate_super_block(int fd, u64 old_bytenr)
1370 struct extent_buffer *buf;
1371 struct btrfs_super_block *super;
1375 buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1379 buf->len = BTRFS_SUPER_INFO_SIZE;
1380 ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1381 if (ret != BTRFS_SUPER_INFO_SIZE)
1384 super = (struct btrfs_super_block *)buf->data;
1385 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1386 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1388 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1389 ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1390 BTRFS_SUPER_INFO_OFFSET);
1391 if (ret != BTRFS_SUPER_INFO_SIZE)
1398 memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1399 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1400 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1401 if (len > BTRFS_SUPER_INFO_SIZE)
1402 len = BTRFS_SUPER_INFO_SIZE;
1403 ret = pwrite(fd, buf->data, len, bytenr);
1405 fprintf(stderr, "unable to zero fill device\n");
1419 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1421 struct btrfs_chunk *chunk;
1422 struct btrfs_disk_key *key;
1423 u32 sectorsize = btrfs_super_sectorsize(super);
1425 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1426 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1427 sizeof(struct btrfs_disk_key));
1429 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1430 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1431 btrfs_set_disk_key_offset(key, 0);
1433 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1434 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1435 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1436 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1437 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1438 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1439 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1440 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1441 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1442 chunk->stripe.devid = super->dev_item.devid;
1443 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1444 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1445 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1449 #if BTRFSCONVERT_EXT2
1452 * Open Ext2fs in readonly mode, read block allocation bitmap and
1453 * inode bitmap into memory.
1455 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
1458 ext2_filsys ext2_fs;
1462 ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
1464 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
1468 * We need to know exactly the used space, some RO compat flags like
1469 * BIGALLOC will affect how used space is present.
1470 * So we need manuall check any unsupported RO compat flags
1472 ro_feature = ext2_fs->super->s_feature_ro_compat;
1473 if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
1475 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
1476 ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1479 ret = ext2fs_read_inode_bitmap(ext2_fs);
1481 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
1482 error_message(ret));
1485 ret = ext2fs_read_block_bitmap(ext2_fs);
1487 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
1488 error_message(ret));
1492 * search each block group for a free inode. this set up
1493 * uninit block/inode bitmaps appropriately.
1496 while (ino <= ext2_fs->super->s_inodes_count) {
1498 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
1499 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
1502 if (!(ext2_fs->super->s_feature_incompat &
1503 EXT2_FEATURE_INCOMPAT_FILETYPE)) {
1504 error("filetype feature is missing");
1508 cctx->fs_data = ext2_fs;
1509 cctx->blocksize = ext2_fs->blocksize;
1510 cctx->block_count = ext2_fs->super->s_blocks_count;
1511 cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
1512 cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
1513 cctx->first_data_block = ext2_fs->super->s_first_data_block;
1514 cctx->inodes_count = ext2_fs->super->s_inodes_count;
1515 cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
1518 ext2fs_close(ext2_fs);
1522 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
1523 unsigned long group_nr, struct cache_tree *used)
1525 unsigned long offset;
1529 offset = fs->super->s_first_data_block;
1530 offset /= EXT2FS_CLUSTER_RATIO(fs);
1531 offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
1532 for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
1533 if ((i + offset) >= ext2fs_blocks_count(fs->super))
1536 if (ext2fs_test_bit(i, bitmap)) {
1539 start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
1540 start *= fs->blocksize;
1541 ret = add_merge_cache_extent(used, start,
1551 * Read all used ext2 space into cctx->used cache tree
1553 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
1555 ext2_filsys fs = (ext2_filsys)cctx->fs_data;
1556 blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
1557 struct cache_tree *used_tree = &cctx->used;
1558 char *block_bitmap = NULL;
1563 block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
1564 /* Shouldn't happen */
1565 BUG_ON(!fs->block_map);
1567 block_bitmap = malloc(block_nbytes);
1571 for (i = 0; i < fs->group_desc_count; i++) {
1572 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
1573 block_nbytes * 8, block_bitmap);
1575 error("fail to get bitmap from ext2, %s",
1579 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
1581 error("fail to build used space tree, %s",
1585 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
1592 static void ext2_close_fs(struct btrfs_convert_context *cctx)
1594 if (cctx->volume_name) {
1595 free(cctx->volume_name);
1596 cctx->volume_name = NULL;
1598 ext2fs_close(cctx->fs_data);
1601 struct dir_iterate_data {
1602 struct btrfs_trans_handle *trans;
1603 struct btrfs_root *root;
1604 struct btrfs_inode_item *inode;
1611 static u8 ext2_filetype_conversion_table[EXT2_FT_MAX] = {
1612 [EXT2_FT_UNKNOWN] = BTRFS_FT_UNKNOWN,
1613 [EXT2_FT_REG_FILE] = BTRFS_FT_REG_FILE,
1614 [EXT2_FT_DIR] = BTRFS_FT_DIR,
1615 [EXT2_FT_CHRDEV] = BTRFS_FT_CHRDEV,
1616 [EXT2_FT_BLKDEV] = BTRFS_FT_BLKDEV,
1617 [EXT2_FT_FIFO] = BTRFS_FT_FIFO,
1618 [EXT2_FT_SOCK] = BTRFS_FT_SOCK,
1619 [EXT2_FT_SYMLINK] = BTRFS_FT_SYMLINK,
1622 static int ext2_dir_iterate_proc(ext2_ino_t dir, int entry,
1623 struct ext2_dir_entry *dirent,
1624 int offset, int blocksize,
1625 char *buf,void *priv_data)
1630 char dotdot[] = "..";
1631 struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
1634 name_len = dirent->name_len & 0xFF;
1636 objectid = dirent->inode + INO_OFFSET;
1637 if (!strncmp(dirent->name, dotdot, name_len)) {
1638 if (name_len == 2) {
1639 BUG_ON(idata->parent != 0);
1640 idata->parent = objectid;
1644 if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
1647 file_type = dirent->name_len >> 8;
1648 BUG_ON(file_type > EXT2_FT_SYMLINK);
1650 ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
1651 name_len, idata->objectid, objectid,
1652 ext2_filetype_conversion_table[file_type],
1653 idata->index_cnt, idata->inode);
1655 idata->errcode = ret;
1663 static int ext2_create_dir_entries(struct btrfs_trans_handle *trans,
1664 struct btrfs_root *root, u64 objectid,
1665 struct btrfs_inode_item *btrfs_inode,
1666 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
1670 struct dir_iterate_data data = {
1673 .inode = btrfs_inode,
1674 .objectid = objectid,
1680 err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
1681 ext2_dir_iterate_proc, &data);
1685 if (ret == 0 && data.parent == objectid) {
1686 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
1687 objectid, objectid, 0);
1691 fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
1695 static int ext2_block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
1696 e2_blkcnt_t blockcnt, blk_t ref_block,
1697 int ref_offset, void *priv_data)
1700 struct blk_iterate_data *idata;
1701 idata = (struct blk_iterate_data *)priv_data;
1702 ret = block_iterate_proc(*blocknr, blockcnt, idata);
1704 idata->errcode = ret;
1711 * traverse file's data blocks, record these data blocks as file extents.
1713 static int ext2_create_file_extents(struct btrfs_trans_handle *trans,
1714 struct btrfs_root *root, u64 objectid,
1715 struct btrfs_inode_item *btrfs_inode,
1716 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1717 int datacsum, int packing)
1720 char *buffer = NULL;
1723 u32 sectorsize = root->sectorsize;
1724 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1725 struct blk_iterate_data data;
1727 init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
1730 err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
1731 NULL, ext2_block_iterate_proc, &data);
1737 if (packing && data.first_block == 0 && data.num_blocks > 0 &&
1738 inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
1739 u64 num_bytes = data.num_blocks * sectorsize;
1740 u64 disk_bytenr = data.disk_block * sectorsize;
1743 buffer = malloc(num_bytes);
1746 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
1749 if (num_bytes > inode_size)
1750 num_bytes = inode_size;
1751 ret = btrfs_insert_inline_extent(trans, root, objectid,
1752 0, buffer, num_bytes);
1755 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
1756 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
1757 } else if (data.num_blocks > 0) {
1758 ret = record_file_blocks(&data, data.first_block,
1759 data.disk_block, data.num_blocks);
1763 data.first_block += data.num_blocks;
1764 last_block = (inode_size + sectorsize - 1) / sectorsize;
1765 if (last_block > data.first_block) {
1766 ret = record_file_blocks(&data, data.first_block, 0,
1767 last_block - data.first_block);
1773 fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
1777 static int ext2_create_symbol_link(struct btrfs_trans_handle *trans,
1778 struct btrfs_root *root, u64 objectid,
1779 struct btrfs_inode_item *btrfs_inode,
1780 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1781 struct ext2_inode *ext2_inode)
1785 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1786 if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
1787 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
1788 ret = ext2_create_file_extents(trans, root, objectid,
1789 btrfs_inode, ext2_fs, ext2_ino, 1, 1);
1790 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
1794 pathname = (char *)&(ext2_inode->i_block[0]);
1795 BUG_ON(pathname[inode_size] != 0);
1796 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
1797 pathname, inode_size + 1);
1798 btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
1803 * Following xattr/acl related codes are based on codes in
1804 * fs/ext3/xattr.c and fs/ext3/acl.c
1806 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
1807 #define EXT2_XATTR_BFIRST(ptr) \
1808 ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
1809 #define EXT2_XATTR_IHDR(inode) \
1810 ((struct ext2_ext_attr_header *) ((void *)(inode) + \
1811 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
1812 #define EXT2_XATTR_IFIRST(inode) \
1813 ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
1814 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
1816 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
1819 struct ext2_ext_attr_entry *next;
1821 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1822 next = EXT2_EXT_ATTR_NEXT(entry);
1823 if ((void *)next >= end)
1830 static int ext2_xattr_check_block(const char *buf, size_t size)
1833 struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
1835 if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
1836 header->h_blocks != 1)
1838 error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
1842 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
1845 size_t value_size = entry->e_value_size;
1847 if (entry->e_value_block != 0 || value_size > size ||
1848 entry->e_value_offs + value_size > size)
1853 #define EXT2_ACL_VERSION 0x0001
1855 /* 23.2.5 acl_tag_t values */
1857 #define ACL_UNDEFINED_TAG (0x00)
1858 #define ACL_USER_OBJ (0x01)
1859 #define ACL_USER (0x02)
1860 #define ACL_GROUP_OBJ (0x04)
1861 #define ACL_GROUP (0x08)
1862 #define ACL_MASK (0x10)
1863 #define ACL_OTHER (0x20)
1865 /* 23.2.7 ACL qualifier constants */
1867 #define ACL_UNDEFINED_ID ((id_t)-1)
1878 } ext2_acl_entry_short;
1884 static inline int ext2_acl_count(size_t size)
1887 size -= sizeof(ext2_acl_header);
1888 s = size - 4 * sizeof(ext2_acl_entry_short);
1890 if (size % sizeof(ext2_acl_entry_short))
1892 return size / sizeof(ext2_acl_entry_short);
1894 if (s % sizeof(ext2_acl_entry))
1896 return s / sizeof(ext2_acl_entry) + 4;
1900 #define ACL_EA_VERSION 0x0002
1910 acl_ea_entry a_entries[0];
1913 static inline size_t acl_ea_size(int count)
1915 return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
1918 static int ext2_acl_to_xattr(void *dst, const void *src,
1919 size_t dst_size, size_t src_size)
1922 const void *end = src + src_size;
1923 acl_ea_header *ext_acl = (acl_ea_header *)dst;
1924 acl_ea_entry *dst_entry = ext_acl->a_entries;
1925 ext2_acl_entry *src_entry;
1927 if (src_size < sizeof(ext2_acl_header))
1929 if (((ext2_acl_header *)src)->a_version !=
1930 cpu_to_le32(EXT2_ACL_VERSION))
1932 src += sizeof(ext2_acl_header);
1933 count = ext2_acl_count(src_size);
1937 BUG_ON(dst_size < acl_ea_size(count));
1938 ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
1939 for (i = 0; i < count; i++, dst_entry++) {
1940 src_entry = (ext2_acl_entry *)src;
1941 if (src + sizeof(ext2_acl_entry_short) > end)
1943 dst_entry->e_tag = src_entry->e_tag;
1944 dst_entry->e_perm = src_entry->e_perm;
1945 switch (le16_to_cpu(src_entry->e_tag)) {
1950 src += sizeof(ext2_acl_entry_short);
1951 dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
1955 src += sizeof(ext2_acl_entry);
1958 dst_entry->e_id = src_entry->e_id;
1971 static char *xattr_prefix_table[] = {
1973 [2] = "system.posix_acl_access",
1974 [3] = "system.posix_acl_default",
1979 static int ext2_copy_single_xattr(struct btrfs_trans_handle *trans,
1980 struct btrfs_root *root, u64 objectid,
1981 struct ext2_ext_attr_entry *entry,
1982 const void *data, u32 datalen)
1987 void *databuf = NULL;
1988 char namebuf[XATTR_NAME_MAX + 1];
1990 name_index = entry->e_name_index;
1991 if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
1992 xattr_prefix_table[name_index] == NULL)
1994 name_len = strlen(xattr_prefix_table[name_index]) +
1996 if (name_len >= sizeof(namebuf))
1999 if (name_index == 2 || name_index == 3) {
2000 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
2001 databuf = malloc(bufsize);
2004 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
2010 strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
2011 strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
2012 if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
2013 sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
2014 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
2015 objectid - INO_OFFSET, name_len, namebuf);
2018 ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
2019 data, datalen, objectid);
2025 static int ext2_copy_extended_attrs(struct btrfs_trans_handle *trans,
2026 struct btrfs_root *root, u64 objectid,
2027 struct btrfs_inode_item *btrfs_inode,
2028 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
2034 u32 block_size = ext2_fs->blocksize;
2035 u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
2036 struct ext2_inode_large *ext2_inode;
2037 struct ext2_ext_attr_entry *entry;
2039 char *buffer = NULL;
2040 char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
2042 if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
2043 ext2_inode = (struct ext2_inode_large *)inode_buf;
2045 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
2049 err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
2052 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
2053 error_message(err));
2058 if (ext2_ino > ext2_fs->super->s_first_ino &&
2059 inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
2060 if (EXT2_GOOD_OLD_INODE_SIZE +
2061 ext2_inode->i_extra_isize > inode_size) {
2065 if (ext2_inode->i_extra_isize != 0 &&
2066 EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
2067 EXT2_EXT_ATTR_MAGIC) {
2073 void *end = (void *)ext2_inode + inode_size;
2074 entry = EXT2_XATTR_IFIRST(ext2_inode);
2075 total = end - (void *)entry;
2076 ret = ext2_xattr_check_names(entry, end);
2079 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2080 ret = ext2_xattr_check_entry(entry, total);
2083 data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
2084 entry->e_value_offs;
2085 datalen = entry->e_value_size;
2086 ret = ext2_copy_single_xattr(trans, root, objectid,
2087 entry, data, datalen);
2090 entry = EXT2_EXT_ATTR_NEXT(entry);
2094 if (ext2_inode->i_file_acl == 0)
2097 buffer = malloc(block_size);
2102 err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
2104 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
2105 error_message(err));
2109 ret = ext2_xattr_check_block(buffer, block_size);
2113 entry = EXT2_XATTR_BFIRST(buffer);
2114 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2115 ret = ext2_xattr_check_entry(entry, block_size);
2118 data = buffer + entry->e_value_offs;
2119 datalen = entry->e_value_size;
2120 ret = ext2_copy_single_xattr(trans, root, objectid,
2121 entry, data, datalen);
2124 entry = EXT2_EXT_ATTR_NEXT(entry);
2128 if ((void *)ext2_inode != inode_buf)
2132 #define MINORBITS 20
2133 #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
2135 static inline dev_t old_decode_dev(u16 val)
2137 return MKDEV((val >> 8) & 255, val & 255);
2140 static inline dev_t new_decode_dev(u32 dev)
2142 unsigned major = (dev & 0xfff00) >> 8;
2143 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
2144 return MKDEV(major, minor);
2147 static void ext2_copy_inode_item(struct btrfs_inode_item *dst,
2148 struct ext2_inode *src, u32 blocksize)
2150 btrfs_set_stack_inode_generation(dst, 1);
2151 btrfs_set_stack_inode_sequence(dst, 0);
2152 btrfs_set_stack_inode_transid(dst, 1);
2153 btrfs_set_stack_inode_size(dst, src->i_size);
2154 btrfs_set_stack_inode_nbytes(dst, 0);
2155 btrfs_set_stack_inode_block_group(dst, 0);
2156 btrfs_set_stack_inode_nlink(dst, src->i_links_count);
2157 btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
2158 btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
2159 btrfs_set_stack_inode_mode(dst, src->i_mode);
2160 btrfs_set_stack_inode_rdev(dst, 0);
2161 btrfs_set_stack_inode_flags(dst, 0);
2162 btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
2163 btrfs_set_stack_timespec_nsec(&dst->atime, 0);
2164 btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
2165 btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
2166 btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
2167 btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
2168 btrfs_set_stack_timespec_sec(&dst->otime, 0);
2169 btrfs_set_stack_timespec_nsec(&dst->otime, 0);
2171 if (S_ISDIR(src->i_mode)) {
2172 btrfs_set_stack_inode_size(dst, 0);
2173 btrfs_set_stack_inode_nlink(dst, 1);
2175 if (S_ISREG(src->i_mode)) {
2176 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
2179 if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
2180 !S_ISLNK(src->i_mode)) {
2181 if (src->i_block[0]) {
2182 btrfs_set_stack_inode_rdev(dst,
2183 old_decode_dev(src->i_block[0]));
2185 btrfs_set_stack_inode_rdev(dst,
2186 new_decode_dev(src->i_block[1]));
2189 memset(&dst->reserved, 0, sizeof(dst->reserved));
2191 static int ext2_check_state(struct btrfs_convert_context *cctx)
2193 ext2_filsys fs = cctx->fs_data;
2195 if (!(fs->super->s_state & EXT2_VALID_FS))
2197 else if (fs->super->s_state & EXT2_ERROR_FS)
2203 /* EXT2_*_FL to BTRFS_INODE_FLAG_* stringification helper */
2204 #define COPY_ONE_EXT2_FLAG(flags, ext2_inode, name) ({ \
2205 if (ext2_inode->i_flags & EXT2_##name##_FL) \
2206 flags |= BTRFS_INODE_##name; \
2210 * Convert EXT2_*_FL to corresponding BTRFS_INODE_* flags
2212 * Only a subset of EXT_*_FL is supported in btrfs.
2214 static void ext2_convert_inode_flags(struct btrfs_inode_item *dst,
2215 struct ext2_inode *src)
2219 COPY_ONE_EXT2_FLAG(flags, src, APPEND);
2220 COPY_ONE_EXT2_FLAG(flags, src, SYNC);
2221 COPY_ONE_EXT2_FLAG(flags, src, IMMUTABLE);
2222 COPY_ONE_EXT2_FLAG(flags, src, NODUMP);
2223 COPY_ONE_EXT2_FLAG(flags, src, NOATIME);
2224 COPY_ONE_EXT2_FLAG(flags, src, DIRSYNC);
2225 btrfs_set_stack_inode_flags(dst, flags);
2229 * copy a single inode. do all the required works, such as cloning
2230 * inode item, creating file extents and creating directory entries.
2232 static int ext2_copy_single_inode(struct btrfs_trans_handle *trans,
2233 struct btrfs_root *root, u64 objectid,
2234 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
2235 struct ext2_inode *ext2_inode,
2236 int datacsum, int packing, int noxattr)
2239 struct btrfs_inode_item btrfs_inode;
2241 if (ext2_inode->i_links_count == 0)
2244 ext2_copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
2245 if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
2246 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
2247 BTRFS_INODE_NODATASUM;
2248 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
2250 ext2_convert_inode_flags(&btrfs_inode, ext2_inode);
2252 switch (ext2_inode->i_mode & S_IFMT) {
2254 ret = ext2_create_file_extents(trans, root, objectid,
2255 &btrfs_inode, ext2_fs, ext2_ino, datacsum, packing);
2258 ret = ext2_create_dir_entries(trans, root, objectid,
2259 &btrfs_inode, ext2_fs, ext2_ino);
2262 ret = ext2_create_symbol_link(trans, root, objectid,
2263 &btrfs_inode, ext2_fs, ext2_ino, ext2_inode);
2273 ret = ext2_copy_extended_attrs(trans, root, objectid,
2274 &btrfs_inode, ext2_fs, ext2_ino);
2278 return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
2282 * scan ext2's inode bitmap and copy all used inodes.
2284 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
2285 struct btrfs_root *root,
2286 int datacsum, int packing, int noxattr, struct task_ctx *p)
2288 ext2_filsys ext2_fs = cctx->fs_data;
2291 ext2_inode_scan ext2_scan;
2292 struct ext2_inode ext2_inode;
2293 ext2_ino_t ext2_ino;
2295 struct btrfs_trans_handle *trans;
2297 trans = btrfs_start_transaction(root, 1);
2300 err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
2302 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
2305 while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
2307 /* no more inodes */
2310 /* skip special inode in ext2fs */
2311 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
2312 ext2_ino != EXT2_ROOT_INO)
2314 objectid = ext2_ino + INO_OFFSET;
2315 ret = ext2_copy_single_inode(trans, root,
2316 objectid, ext2_fs, ext2_ino,
2317 &ext2_inode, datacsum, packing,
2319 p->cur_copy_inodes++;
2322 if (trans->blocks_used >= 4096) {
2323 ret = btrfs_commit_transaction(trans, root);
2325 trans = btrfs_start_transaction(root, 1);
2330 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
2333 ret = btrfs_commit_transaction(trans, root);
2335 ext2fs_close_inode_scan(ext2_scan);
2340 static const struct btrfs_convert_operations ext2_convert_ops = {
2342 .open_fs = ext2_open_fs,
2343 .read_used_space = ext2_read_used_space,
2344 .copy_inodes = ext2_copy_inodes,
2345 .close_fs = ext2_close_fs,
2346 .check_state = ext2_check_state,
2351 static const struct btrfs_convert_operations *convert_operations[] = {
2352 #if BTRFSCONVERT_EXT2
2357 static int convert_open_fs(const char *devname,
2358 struct btrfs_convert_context *cctx)
2362 memset(cctx, 0, sizeof(*cctx));
2364 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2365 int ret = convert_operations[i]->open_fs(cctx, devname);
2368 cctx->convert_ops = convert_operations[i];
2373 error("no file system found to convert");
2377 static int do_convert(const char *devname, int datacsum, int packing,
2378 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
2379 int progress, u64 features)
2385 struct btrfs_root *root;
2386 struct btrfs_root *image_root;
2387 struct btrfs_convert_context cctx;
2388 struct btrfs_key key;
2389 char *subvol_name = NULL;
2390 struct task_ctx ctx;
2391 char features_buf[64];
2392 struct btrfs_mkfs_config mkfs_cfg;
2394 init_convert_context(&cctx);
2395 ret = convert_open_fs(devname, &cctx);
2398 ret = convert_check_state(&cctx);
2401 "source filesystem is not clean, running filesystem check is recommended");
2402 ret = convert_read_used_space(&cctx);
2406 blocksize = cctx.blocksize;
2407 total_bytes = (u64)blocksize * (u64)cctx.block_count;
2408 if (blocksize < 4096) {
2409 error("block size is too small: %u < 4096", blocksize);
2412 if (btrfs_check_nodesize(nodesize, blocksize, features))
2414 fd = open(devname, O_RDWR);
2416 error("unable to open %s: %s", devname, strerror(errno));
2419 btrfs_parse_features_to_string(features_buf, features);
2420 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2421 strcat(features_buf, " (default)");
2423 printf("create btrfs filesystem:\n");
2424 printf("\tblocksize: %u\n", blocksize);
2425 printf("\tnodesize: %u\n", nodesize);
2426 printf("\tfeatures: %s\n", features_buf);
2428 mkfs_cfg.label = cctx.volume_name;
2429 mkfs_cfg.num_bytes = total_bytes;
2430 mkfs_cfg.nodesize = nodesize;
2431 mkfs_cfg.sectorsize = blocksize;
2432 mkfs_cfg.stripesize = blocksize;
2433 mkfs_cfg.features = features;
2434 /* New convert need these space */
2435 memset(mkfs_cfg.chunk_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2436 memset(mkfs_cfg.fs_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2438 ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
2440 error("unable to create initial ctree: %s", strerror(-ret));
2444 root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
2445 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2447 error("unable to open ctree");
2450 ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
2452 error("unable to setup the root tree: %d", ret);
2456 printf("creating %s image file\n", cctx.convert_ops->name);
2457 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2459 error("memory allocation failure for subvolume name: %s_saved",
2460 cctx.convert_ops->name);
2463 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2464 key.offset = (u64)-1;
2465 key.type = BTRFS_ROOT_ITEM_KEY;
2466 image_root = btrfs_read_fs_root(root->fs_info, &key);
2468 error("unable to create image subvolume");
2471 ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
2472 mkfs_cfg.num_bytes, "image", datacsum);
2474 error("failed to create %s/image: %d", subvol_name, ret);
2478 printf("creating btrfs metadata");
2479 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2480 ctx.cur_copy_inodes = 0;
2483 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
2485 task_start(ctx.info);
2487 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2489 error("error during copy_inodes %d", ret);
2493 task_stop(ctx.info);
2494 task_deinit(ctx.info);
2497 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2499 error("unable to link subvolume %s", subvol_name);
2505 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2506 if (copylabel == 1) {
2507 __strncpy_null(root->fs_info->super_copy->label,
2508 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2509 printf("copy label '%s'\n", root->fs_info->super_copy->label);
2510 } else if (copylabel == -1) {
2511 strcpy(root->fs_info->super_copy->label, fslabel);
2512 printf("set label to '%s'\n", fslabel);
2515 ret = close_ctree(root);
2517 error("close_ctree failed: %d", ret);
2520 convert_close_fs(&cctx);
2521 clean_convert_context(&cctx);
2524 * If this step succeed, we get a mountable btrfs. Otherwise
2525 * the source fs is left unchanged.
2527 ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
2529 error("unable to migrate super block: %d", ret);
2533 root = open_ctree_fd(fd, devname, 0,
2534 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2536 error("unable to open ctree for finalization");
2539 root->fs_info->finalize_on_close = 1;
2543 printf("conversion complete");
2546 clean_convert_context(&cctx);
2550 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
2555 * Check if a non 1:1 mapped chunk can be rolled back.
2556 * For new convert, it's OK while for old convert it's not.
2558 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
2560 struct btrfs_block_group_cache *bg;
2561 struct btrfs_key key;
2562 struct btrfs_path path;
2563 struct btrfs_root *extent_root = fs_info->extent_root;
2568 bg = btrfs_lookup_first_block_group(fs_info, bytenr);
2571 bg_start = bg->key.objectid;
2572 bg_end = bg->key.objectid + bg->key.offset;
2574 key.objectid = bg_end;
2575 key.type = BTRFS_METADATA_ITEM_KEY;
2577 btrfs_init_path(&path);
2579 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2584 struct btrfs_extent_item *ei;
2586 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
2594 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2595 if (key.type == BTRFS_METADATA_ITEM_KEY)
2597 /* Now it's EXTENT_ITEM_KEY only */
2598 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
2599 struct btrfs_extent_item);
2601 * Found data extent, means this is old convert must follow 1:1
2604 if (btrfs_extent_flags(path.nodes[0], ei)
2605 & BTRFS_EXTENT_FLAG_DATA) {
2610 btrfs_release_path(&path);
2614 static int may_rollback(struct btrfs_root *root)
2616 struct btrfs_fs_info *info = root->fs_info;
2617 struct btrfs_multi_bio *multi = NULL;
2625 if (btrfs_super_num_devices(info->super_copy) != 1)
2628 bytenr = BTRFS_SUPER_INFO_OFFSET;
2629 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2632 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2633 &length, &multi, 0, NULL);
2635 if (ret == -ENOENT) {
2636 /* removed block group at the tail */
2637 if (length == (u64)-1)
2640 /* removed block group in the middle */
2646 num_stripes = multi->num_stripes;
2647 physical = multi->stripes[0].physical;
2650 if (num_stripes != 1) {
2651 error("num stripes for bytenr %llu is not 1", bytenr);
2656 * Extra check for new convert, as metadata chunk from new
2657 * convert is much more free than old convert, it doesn't need
2658 * to do 1:1 mapping.
2660 if (physical != bytenr) {
2662 * Check if it's a metadata chunk and has only metadata
2665 ret = may_rollback_chunk(info, bytenr);
2671 if (bytenr >= total_bytes)
2679 static int do_rollback(const char *devname)
2684 struct btrfs_root *root;
2685 struct btrfs_root *image_root;
2686 struct btrfs_root *chunk_root;
2687 struct btrfs_dir_item *dir;
2688 struct btrfs_inode_item *inode;
2689 struct btrfs_file_extent_item *fi;
2690 struct btrfs_trans_handle *trans;
2691 struct extent_buffer *leaf;
2692 struct btrfs_block_group_cache *cache1;
2693 struct btrfs_block_group_cache *cache2;
2694 struct btrfs_key key;
2695 struct btrfs_path path;
2696 struct extent_io_tree io_tree;
2711 extent_io_tree_init(&io_tree);
2713 fd = open(devname, O_RDWR);
2715 error("unable to open %s: %s", devname, strerror(errno));
2718 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2720 error("unable to open ctree");
2723 ret = may_rollback(root);
2725 error("unable to do rollback: %d", ret);
2729 sectorsize = root->sectorsize;
2730 buf = malloc(sectorsize);
2732 error("unable to allocate memory");
2736 btrfs_init_path(&path);
2738 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2739 key.type = BTRFS_ROOT_BACKREF_KEY;
2740 key.offset = BTRFS_FS_TREE_OBJECTID;
2741 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2743 btrfs_release_path(&path);
2745 error("unable to convert ext2 image subvolume, is it deleted?");
2747 } else if (ret < 0) {
2748 error("unable to open ext2_saved, id %llu: %s",
2749 (unsigned long long)key.objectid, strerror(-ret));
2753 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2754 key.type = BTRFS_ROOT_ITEM_KEY;
2755 key.offset = (u64)-1;
2756 image_root = btrfs_read_fs_root(root->fs_info, &key);
2757 if (!image_root || IS_ERR(image_root)) {
2758 error("unable to open subvolume %llu: %ld",
2759 (unsigned long long)key.objectid, PTR_ERR(image_root));
2764 root_dir = btrfs_root_dirid(&root->root_item);
2765 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2766 root_dir, name, strlen(name), 0);
2767 if (!dir || IS_ERR(dir)) {
2768 error("unable to find file %s: %ld", name, PTR_ERR(dir));
2771 leaf = path.nodes[0];
2772 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2773 btrfs_release_path(&path);
2775 objectid = key.objectid;
2777 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2779 error("unable to find inode item: %d", ret);
2782 leaf = path.nodes[0];
2783 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2784 total_bytes = btrfs_inode_size(leaf, inode);
2785 btrfs_release_path(&path);
2787 key.objectid = objectid;
2789 key.type = BTRFS_EXTENT_DATA_KEY;
2790 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2792 error("unable to find first file extent: %d", ret);
2793 btrfs_release_path(&path);
2797 /* build mapping tree for the relocated blocks */
2798 for (offset = 0; offset < total_bytes; ) {
2799 leaf = path.nodes[0];
2800 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2801 ret = btrfs_next_leaf(root, &path);
2807 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2808 if (key.objectid != objectid || key.offset != offset ||
2809 key.type != BTRFS_EXTENT_DATA_KEY)
2812 fi = btrfs_item_ptr(leaf, path.slots[0],
2813 struct btrfs_file_extent_item);
2814 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2816 if (btrfs_file_extent_compression(leaf, fi) ||
2817 btrfs_file_extent_encryption(leaf, fi) ||
2818 btrfs_file_extent_other_encoding(leaf, fi))
2821 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2822 /* skip holes and direct mapped extents */
2823 if (bytenr == 0 || bytenr == offset)
2826 bytenr += btrfs_file_extent_offset(leaf, fi);
2827 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2829 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2830 cache2 = btrfs_lookup_block_group(root->fs_info,
2831 offset + num_bytes - 1);
2833 * Here we must take consideration of old and new convert
2835 * For old convert case, sign, there is no consist chunk type
2836 * that will cover the extent. META/DATA/SYS are all possible.
2837 * Just ensure relocate one is in SYS chunk.
2838 * For new convert case, they are all covered by DATA chunk.
2840 * So, there is not valid chunk type check for it now.
2842 if (cache1 != cache2)
2845 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2846 EXTENT_LOCKED, GFP_NOFS);
2847 set_state_private(&io_tree, offset, bytenr);
2849 offset += btrfs_file_extent_num_bytes(leaf, fi);
2852 btrfs_release_path(&path);
2854 if (offset < total_bytes) {
2855 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
2856 (unsigned long long)offset,
2857 (unsigned long long)total_bytes);
2858 error("converted filesystem after balance is unable to rollback");
2862 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2863 first_free &= ~((u64)sectorsize - 1);
2864 /* backup for extent #0 should exist */
2865 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2866 error("no backup for the first extent");
2869 /* force no allocation from system block group */
2870 root->fs_info->system_allocs = -1;
2871 trans = btrfs_start_transaction(root, 1);
2873 error("unable to start transaction");
2877 * recow the whole chunk tree, this will remove all chunk tree blocks
2878 * from system block group
2880 chunk_root = root->fs_info->chunk_root;
2881 memset(&key, 0, sizeof(key));
2883 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2887 ret = btrfs_next_leaf(chunk_root, &path);
2891 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2892 btrfs_release_path(&path);
2894 btrfs_release_path(&path);
2899 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2903 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2904 num_bytes += btrfs_block_group_used(&cache1->item);
2906 offset = cache1->key.objectid + cache1->key.offset;
2908 /* only extent #0 left in system block group? */
2909 if (num_bytes > first_free) {
2911 "unable to empty system block group (num_bytes %llu, first_free %llu",
2912 (unsigned long long)num_bytes,
2913 (unsigned long long)first_free);
2916 /* create a system chunk that maps the whole device */
2917 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2919 error("unable to update system chunk: %d", ret);
2923 ret = btrfs_commit_transaction(trans, root);
2925 error("transaction commit failed: %d", ret);
2929 ret = close_ctree(root);
2931 error("close_ctree failed: %d", ret);
2935 /* zero btrfs super block mirrors */
2936 memset(buf, 0, sectorsize);
2937 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2938 bytenr = btrfs_sb_offset(i);
2939 if (bytenr >= total_bytes)
2941 ret = pwrite(fd, buf, sectorsize, bytenr);
2942 if (ret != sectorsize) {
2943 error("zeroing superblock mirror %d failed: %d",
2949 sb_bytenr = (u64)-1;
2950 /* copy all relocated blocks back */
2952 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2957 ret = get_state_private(&io_tree, start, &bytenr);
2960 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2963 while (start <= end) {
2964 if (start == BTRFS_SUPER_INFO_OFFSET) {
2968 ret = pread(fd, buf, sectorsize, bytenr);
2970 error("reading superblock at %llu failed: %d",
2971 (unsigned long long)bytenr, ret);
2974 BUG_ON(ret != sectorsize);
2975 ret = pwrite(fd, buf, sectorsize, start);
2977 error("writing superblock at %llu failed: %d",
2978 (unsigned long long)start, ret);
2981 BUG_ON(ret != sectorsize);
2983 start += sectorsize;
2984 bytenr += sectorsize;
2990 error("fsync failed: %s", strerror(errno));
2994 * finally, overwrite btrfs super block.
2996 ret = pread(fd, buf, sectorsize, sb_bytenr);
2998 error("reading primary superblock failed: %s",
3002 BUG_ON(ret != sectorsize);
3003 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3005 error("writing primary superblock failed: %s",
3009 BUG_ON(ret != sectorsize);
3012 error("fsync failed: %s", strerror(errno));
3018 extent_io_tree_cleanup(&io_tree);
3019 printf("rollback complete\n");
3026 error("rollback aborted");
3030 static void print_usage(void)
3032 printf("usage: btrfs-convert [options] device\n");
3033 printf("options:\n");
3034 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
3035 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
3036 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
3037 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
3038 printf("\t-r|--rollback roll back to the original filesystem\n");
3039 printf("\t-l|--label LABEL set filesystem label\n");
3040 printf("\t-L|--copy-label use label from converted filesystem\n");
3041 printf("\t-p|--progress show converting progress (default)\n");
3042 printf("\t-O|--features LIST comma separated list of filesystem features\n");
3043 printf("\t--no-progress show only overview, not the detailed progress\n");
3045 printf("Supported filesystems:\n");
3046 printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
3049 int main(int argc, char *argv[])
3055 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3056 BTRFS_MKFS_DEFAULT_NODE_SIZE);
3059 int usage_error = 0;
3062 char fslabel[BTRFS_LABEL_SIZE];
3063 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3066 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3067 static const struct option long_options[] = {
3068 { "no-progress", no_argument, NULL,
3069 GETOPT_VAL_NO_PROGRESS },
3070 { "no-datasum", no_argument, NULL, 'd' },
3071 { "no-inline", no_argument, NULL, 'n' },
3072 { "no-xattr", no_argument, NULL, 'i' },
3073 { "rollback", no_argument, NULL, 'r' },
3074 { "features", required_argument, NULL, 'O' },
3075 { "progress", no_argument, NULL, 'p' },
3076 { "label", required_argument, NULL, 'l' },
3077 { "copy-label", no_argument, NULL, 'L' },
3078 { "nodesize", required_argument, NULL, 'N' },
3079 { "help", no_argument, NULL, GETOPT_VAL_HELP},
3080 { NULL, 0, NULL, 0 }
3082 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3097 nodesize = parse_size(optarg);
3104 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3106 "label too long, trimmed to %d bytes",
3107 BTRFS_LABEL_SIZE - 1);
3109 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3118 char *orig = strdup(optarg);
3121 tmp = btrfs_parse_fs_features(tmp, &features);
3123 error("unrecognized filesystem feature: %s",
3129 if (features & BTRFS_FEATURE_LIST_ALL) {
3130 btrfs_list_all_fs_features(
3131 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3134 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3137 btrfs_parse_features_to_string(buf,
3138 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3139 error("features not allowed for convert: %s",
3146 case GETOPT_VAL_NO_PROGRESS:
3149 case GETOPT_VAL_HELP:
3152 return c != GETOPT_VAL_HELP;
3156 if (check_argc_exact(argc - optind, 1)) {
3161 if (rollback && (!datacsum || noxattr || !packing)) {
3163 "Usage error: -d, -i, -n options do not apply to rollback\n");
3172 file = argv[optind];
3173 ret = check_mounted(file);
3175 error("could not check mount status: %s", strerror(-ret));
3178 error("%s is mounted", file);
3183 ret = do_rollback(file);
3185 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3186 copylabel, fslabel, progress, features);