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"
42 #include <ext2fs/ext2_fs.h>
43 #include <ext2fs/ext2fs.h>
44 #include <ext2fs/ext2_ext_attr.h>
46 #define INO_OFFSET (BTRFS_FIRST_FREE_OBJECTID - EXT2_ROOT_INO)
49 * Compatibility code for e2fsprogs 1.41 which doesn't support RO compat flag
51 * Unlike normal RO compat flag, BIGALLOC affects how e2fsprogs check used
52 * space, and btrfs-convert heavily relies on it.
54 #ifdef HAVE_OLD_E2FSPROGS
55 #define EXT2FS_CLUSTER_RATIO(fs) (1)
56 #define EXT2_CLUSTERS_PER_GROUP(s) (EXT2_BLOCKS_PER_GROUP(s))
57 #define EXT2FS_B2C(fs, blk) (blk)
62 #define CONV_IMAGE_SUBVOL_OBJECTID BTRFS_FIRST_FREE_OBJECTID
65 uint32_t max_copy_inodes;
66 uint32_t cur_copy_inodes;
67 struct task_info *info;
70 static void *print_copied_inodes(void *p)
72 struct task_ctx *priv = p;
73 const char work_indicator[] = { '.', 'o', 'O', 'o' };
76 task_period_start(priv->info, 1000 /* 1s */);
79 printf("copy inodes [%c] [%10d/%10d]\r",
80 work_indicator[count % 4], priv->cur_copy_inodes,
81 priv->max_copy_inodes);
83 task_period_wait(priv->info);
89 static int after_copied_inodes(void *p)
97 struct btrfs_convert_context;
98 struct btrfs_convert_operations {
100 int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
101 int (*read_used_space)(struct btrfs_convert_context *cctx);
102 int (*copy_inodes)(struct btrfs_convert_context *cctx,
103 struct btrfs_root *root, int datacsum,
104 int packing, int noxattr, struct task_ctx *p);
105 void (*close_fs)(struct btrfs_convert_context *cctx);
106 int (*check_state)(struct btrfs_convert_context *cctx);
109 static void init_convert_context(struct btrfs_convert_context *cctx)
111 cache_tree_init(&cctx->used);
112 cache_tree_init(&cctx->data_chunks);
113 cache_tree_init(&cctx->free);
116 static void clean_convert_context(struct btrfs_convert_context *cctx)
118 free_extent_cache_tree(&cctx->used);
119 free_extent_cache_tree(&cctx->data_chunks);
120 free_extent_cache_tree(&cctx->free);
123 static inline int copy_inodes(struct btrfs_convert_context *cctx,
124 struct btrfs_root *root, int datacsum,
125 int packing, int noxattr, struct task_ctx *p)
127 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
131 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
133 cctx->convert_ops->close_fs(cctx);
136 static inline int convert_check_state(struct btrfs_convert_context *cctx)
138 return cctx->convert_ops->check_state(cctx);
141 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
146 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
147 offset = btrfs_sb_offset(i);
148 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
150 if (bytenr < offset + BTRFS_STRIPE_LEN &&
151 bytenr + num_bytes > offset)
157 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
158 struct btrfs_root *root,
159 const char *name, size_t name_len,
160 u64 dir, u64 objectid,
161 u8 file_type, u64 index_cnt,
162 struct btrfs_inode_item *inode)
166 struct btrfs_key location = {
167 .objectid = objectid,
169 .type = BTRFS_INODE_ITEM_KEY,
172 ret = btrfs_insert_dir_item(trans, root, name, name_len,
173 dir, &location, file_type, index_cnt);
176 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
177 objectid, dir, index_cnt);
180 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
181 btrfs_set_stack_inode_size(inode, inode_size);
186 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
187 u32 num_bytes, char *buffer)
190 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
192 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
193 if (ret != num_bytes)
202 static int csum_disk_extent(struct btrfs_trans_handle *trans,
203 struct btrfs_root *root,
204 u64 disk_bytenr, u64 num_bytes)
206 u32 blocksize = root->sectorsize;
211 buffer = malloc(blocksize);
214 for (offset = 0; offset < num_bytes; offset += blocksize) {
215 ret = read_disk_extent(root, disk_bytenr + offset,
219 ret = btrfs_csum_file_block(trans,
220 root->fs_info->csum_root,
221 disk_bytenr + num_bytes,
222 disk_bytenr + offset,
231 struct blk_iterate_data {
232 struct btrfs_trans_handle *trans;
233 struct btrfs_root *root;
234 struct btrfs_root *convert_root;
235 struct btrfs_inode_item *inode;
246 static void init_blk_iterate_data(struct blk_iterate_data *data,
247 struct btrfs_trans_handle *trans,
248 struct btrfs_root *root,
249 struct btrfs_inode_item *inode,
250 u64 objectid, int checksum)
252 struct btrfs_key key;
257 data->objectid = objectid;
258 data->first_block = 0;
259 data->disk_block = 0;
260 data->num_blocks = 0;
261 data->boundary = (u64)-1;
262 data->checksum = checksum;
265 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
266 key.type = BTRFS_ROOT_ITEM_KEY;
267 key.offset = (u64)-1;
268 data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
269 /* Impossible as we just opened it before */
270 BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
271 data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
275 * Record a file extent in original filesystem into btrfs one.
276 * The special point is, old disk_block can point to a reserved range.
277 * So here, we don't use disk_block directly but search convert_root
278 * to get the real disk_bytenr.
280 static int record_file_blocks(struct blk_iterate_data *data,
281 u64 file_block, u64 disk_block, u64 num_blocks)
284 struct btrfs_root *root = data->root;
285 struct btrfs_root *convert_root = data->convert_root;
286 struct btrfs_path path;
287 u64 file_pos = file_block * root->sectorsize;
288 u64 old_disk_bytenr = disk_block * root->sectorsize;
289 u64 num_bytes = num_blocks * root->sectorsize;
290 u64 cur_off = old_disk_bytenr;
292 /* Hole, pass it to record_file_extent directly */
293 if (old_disk_bytenr == 0)
294 return btrfs_record_file_extent(data->trans, root,
295 data->objectid, data->inode, file_pos, 0,
298 btrfs_init_path(&path);
301 * Search real disk bytenr from convert root
303 while (cur_off < old_disk_bytenr + num_bytes) {
304 struct btrfs_key key;
305 struct btrfs_file_extent_item *fi;
306 struct extent_buffer *node;
308 u64 extent_disk_bytenr;
309 u64 extent_num_bytes;
310 u64 real_disk_bytenr;
313 key.objectid = data->convert_ino;
314 key.type = BTRFS_EXTENT_DATA_KEY;
315 key.offset = cur_off;
317 ret = btrfs_search_slot(NULL, convert_root, &key, &path, 0, 0);
321 ret = btrfs_previous_item(convert_root, &path,
323 BTRFS_EXTENT_DATA_KEY);
331 node = path.nodes[0];
332 slot = path.slots[0];
333 btrfs_item_key_to_cpu(node, &key, slot);
334 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
335 key.objectid != data->convert_ino ||
336 key.offset > cur_off);
337 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
338 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
339 extent_num_bytes = btrfs_file_extent_disk_num_bytes(node, fi);
340 BUG_ON(cur_off - key.offset >= extent_num_bytes);
341 btrfs_release_path(&path);
343 if (extent_disk_bytenr)
344 real_disk_bytenr = cur_off - key.offset +
347 real_disk_bytenr = 0;
348 cur_len = min(key.offset + extent_num_bytes,
349 old_disk_bytenr + num_bytes) - cur_off;
350 ret = btrfs_record_file_extent(data->trans, data->root,
351 data->objectid, data->inode, file_pos,
352 real_disk_bytenr, cur_len);
359 * No need to care about csum
360 * As every byte of old fs image is calculated for csum, no
361 * need to waste CPU cycles now.
364 btrfs_release_path(&path);
368 static int block_iterate_proc(u64 disk_block, u64 file_block,
369 struct blk_iterate_data *idata)
374 struct btrfs_root *root = idata->root;
375 struct btrfs_block_group_cache *cache;
376 u64 bytenr = disk_block * root->sectorsize;
378 sb_region = intersect_with_sb(bytenr, root->sectorsize);
379 do_barrier = sb_region || disk_block >= idata->boundary;
380 if ((idata->num_blocks > 0 && do_barrier) ||
381 (file_block > idata->first_block + idata->num_blocks) ||
382 (disk_block != idata->disk_block + idata->num_blocks)) {
383 if (idata->num_blocks > 0) {
384 ret = record_file_blocks(idata, idata->first_block,
389 idata->first_block += idata->num_blocks;
390 idata->num_blocks = 0;
392 if (file_block > idata->first_block) {
393 ret = record_file_blocks(idata, idata->first_block,
394 0, file_block - idata->first_block);
400 bytenr += BTRFS_STRIPE_LEN - 1;
401 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
403 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
405 bytenr = cache->key.objectid + cache->key.offset;
408 idata->first_block = file_block;
409 idata->disk_block = disk_block;
410 idata->boundary = bytenr / root->sectorsize;
417 static int create_image_file_range(struct btrfs_trans_handle *trans,
418 struct btrfs_root *root,
419 struct cache_tree *used,
420 struct btrfs_inode_item *inode,
421 u64 ino, u64 bytenr, u64 *ret_len,
424 struct cache_extent *cache;
425 struct btrfs_block_group_cache *bg_cache;
431 if (bytenr != round_down(bytenr, root->sectorsize)) {
432 error("bytenr not sectorsize aligned: %llu",
433 (unsigned long long)bytenr);
436 if (len != round_down(len, root->sectorsize)) {
437 error("length not sectorsize aligned: %llu",
438 (unsigned long long)len);
441 len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
444 * Skip sb ranges first
445 * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
447 * Or we will insert a hole into current image file, and later
448 * migrate block will fail as there is already a file extent.
450 if (bytenr < 1024 * 1024) {
451 *ret_len = 1024 * 1024 - bytenr;
454 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
455 u64 cur = btrfs_sb_offset(i);
457 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
458 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
462 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
463 u64 cur = btrfs_sb_offset(i);
468 * May still need to go through file extent inserts
470 if (bytenr < cur && bytenr + len >= cur) {
471 len = min_t(u64, len, cur - bytenr);
477 * Drop out, no need to insert anything
479 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
480 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
485 cache = search_cache_extent(used, bytenr);
487 if (cache->start <= bytenr) {
489 * |///////Used///////|
493 len = min_t(u64, len, cache->start + cache->size -
495 disk_bytenr = bytenr;
502 len = min(len, cache->start - bytenr);
517 /* Check if the range is in a data block group */
518 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
521 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
524 /* The extent should never cross block group boundary */
525 len = min_t(u64, len, bg_cache->key.objectid +
526 bg_cache->key.offset - bytenr);
529 if (len != round_down(len, root->sectorsize)) {
530 error("remaining length not sectorsize aligned: %llu",
531 (unsigned long long)len);
534 ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
540 ret = csum_disk_extent(trans, root, bytenr, len);
546 * Relocate old fs data in one reserved ranges
548 * Since all old fs data in reserved range is not covered by any chunk nor
549 * data extent, we don't need to handle any reference but add new
550 * extent/reference, which makes codes more clear
552 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
553 struct btrfs_root *root,
554 struct cache_tree *used,
555 struct btrfs_inode_item *inode, int fd,
556 u64 ino, u64 start, u64 len, int datacsum)
560 u64 hole_start = start;
562 struct cache_extent *cache;
563 struct btrfs_key key;
564 struct extent_buffer *eb;
567 while (cur_off < start + len) {
568 cache = lookup_cache_extent(used, cur_off, cur_len);
571 cur_off = max(cache->start, cur_off);
572 cur_len = min(cache->start + cache->size, start + len) -
574 BUG_ON(cur_len < root->sectorsize);
576 /* reserve extent for the data */
577 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
582 eb = malloc(sizeof(*eb) + cur_len);
588 ret = pread(fd, eb->data, cur_len, cur_off);
590 ret = (ret < 0 ? ret : -EIO);
594 eb->start = key.objectid;
595 eb->len = key.offset;
598 ret = write_and_map_eb(trans, root, eb);
603 /* Now handle extent item and file extent things */
604 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
605 key.objectid, key.offset);
608 /* Finally, insert csum items */
610 ret = csum_disk_extent(trans, root, key.objectid,
613 /* Don't forget to insert hole */
614 hole_len = cur_off - hole_start;
616 ret = btrfs_record_file_extent(trans, root, ino, inode,
617 hole_start, 0, hole_len);
622 cur_off += key.offset;
623 hole_start = cur_off;
624 cur_len = start + len - cur_off;
627 if (start + len - hole_start > 0)
628 ret = btrfs_record_file_extent(trans, root, ino, inode,
629 hole_start, 0, start + len - hole_start);
634 * Relocate the used ext2 data in reserved ranges
636 * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
637 * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
639 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
640 struct btrfs_root *root,
641 struct cache_tree *used,
642 struct btrfs_inode_item *inode, int fd,
643 u64 ino, u64 total_bytes, int datacsum)
651 cur_len = 1024 * 1024;
652 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
653 cur_off, cur_len, datacsum);
657 /* second sb(fisrt sb is included in 0~1M) */
658 cur_off = btrfs_sb_offset(1);
659 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
660 if (cur_off > total_bytes)
662 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
663 cur_off, cur_len, datacsum);
668 cur_off = btrfs_sb_offset(2);
669 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
670 if (cur_off > total_bytes)
672 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
673 cur_off, cur_len, datacsum);
678 * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
679 * handle wiping a range that exists in cache.
681 static int _expand_extent_cache(struct cache_tree *tree,
682 struct cache_extent *entry,
683 u64 min_stripe_size, int backward)
685 struct cache_extent *ce;
688 if (entry->size >= min_stripe_size)
690 diff = min_stripe_size - entry->size;
693 ce = prev_cache_extent(entry);
696 if (ce->start + ce->size >= entry->start - diff) {
697 /* Directly merge with previous extent */
698 ce->size = entry->start + entry->size - ce->start;
699 remove_cache_extent(tree, entry);
704 /* No overlap, normal extent */
705 if (entry->start < diff) {
706 error("cannot find space for data chunk layout");
709 entry->start -= diff;
713 ce = next_cache_extent(entry);
716 if (entry->start + entry->size + diff >= ce->start) {
717 /* Directly merge with next extent */
718 entry->size = ce->start + ce->size - entry->start;
719 remove_cache_extent(tree, ce);
729 * Remove one reserve range from given cache tree
730 * if min_stripe_size is non-zero, it will ensure for split case,
731 * all its split cache extent is no smaller than @min_strip_size / 2.
733 static int wipe_one_reserved_range(struct cache_tree *tree,
734 u64 start, u64 len, u64 min_stripe_size,
737 struct cache_extent *cache;
740 BUG_ON(ensure_size && min_stripe_size == 0);
742 * The logical here is simplified to handle special cases only
743 * So we don't need to consider merge case for ensure_size
745 BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
746 min_stripe_size / 2 < BTRFS_STRIPE_LEN));
748 /* Also, wipe range should already be aligned */
749 BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
750 start + len != round_up(start + len, BTRFS_STRIPE_LEN));
752 min_stripe_size /= 2;
754 cache = lookup_cache_extent(tree, start, len);
758 if (start <= cache->start) {
760 * |--------cache---------|
763 BUG_ON(start + len <= cache->start);
766 * The wipe size is smaller than min_stripe_size / 2,
767 * so the result length should still meet min_stripe_size
768 * And no need to do alignment
770 cache->size -= (start + len - cache->start);
771 if (cache->size == 0) {
772 remove_cache_extent(tree, cache);
777 BUG_ON(ensure_size && cache->size < min_stripe_size);
779 cache->start = start + len;
781 } else if (start > cache->start && start + len < cache->start +
784 * |-------cache-----|
787 u64 old_start = cache->start;
788 u64 old_len = cache->size;
789 u64 insert_start = start + len;
792 cache->size = start - cache->start;
793 /* Expand the leading half part if needed */
794 if (ensure_size && cache->size < min_stripe_size) {
795 ret = _expand_extent_cache(tree, cache,
801 /* And insert the new one */
802 insert_len = old_start + old_len - start - len;
803 ret = add_merge_cache_extent(tree, insert_start, insert_len);
807 /* Expand the last half part if needed */
808 if (ensure_size && insert_len < min_stripe_size) {
809 cache = lookup_cache_extent(tree, insert_start,
811 if (!cache || cache->start != insert_start ||
812 cache->size != insert_len)
814 ret = _expand_extent_cache(tree, cache,
823 * Wipe len should be small enough and no need to expand the
826 cache->size = start - cache->start;
827 BUG_ON(ensure_size && cache->size < min_stripe_size);
832 * Remove reserved ranges from given cache_tree
834 * It will remove the following ranges
836 * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
837 * 3) 3rd superblock, +64K
839 * @min_stripe must be given for safety check
840 * and if @ensure_size is given, it will ensure affected cache_extent will be
841 * larger than min_stripe_size
843 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
848 ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
852 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
853 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
856 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
857 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
861 static int calculate_available_space(struct btrfs_convert_context *cctx)
863 struct cache_tree *used = &cctx->used;
864 struct cache_tree *data_chunks = &cctx->data_chunks;
865 struct cache_tree *free = &cctx->free;
866 struct cache_extent *cache;
869 * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
870 * works without need to consider overlap
872 u64 min_stripe_size = 2 * 16 * 1024 * 1024;
875 /* Calculate data_chunks */
876 for (cache = first_cache_extent(used); cache;
877 cache = next_cache_extent(cache)) {
880 if (cache->start + cache->size < cur_off)
882 if (cache->start > cur_off + min_stripe_size)
883 cur_off = cache->start;
884 cur_len = max(cache->start + cache->size - cur_off,
886 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
892 * remove reserved ranges, so we won't ever bother relocating an old
893 * filesystem extent to other place.
895 ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
901 * Calculate free space
902 * Always round up the start bytenr, to avoid metadata extent corss
903 * stripe boundary, as later mkfs_convert() won't have all the extent
906 for (cache = first_cache_extent(data_chunks); cache;
907 cache = next_cache_extent(cache)) {
908 if (cache->start < cur_off)
910 if (cache->start > cur_off) {
914 len = cache->start - round_up(cur_off,
916 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
918 ret = add_merge_cache_extent(free, insert_start, len);
922 cur_off = cache->start + cache->size;
924 /* Don't forget the last range */
925 if (cctx->total_bytes > cur_off) {
926 u64 len = cctx->total_bytes - cur_off;
929 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
931 ret = add_merge_cache_extent(free, insert_start, len);
936 /* Remove reserved bytes */
937 ret = wipe_reserved_ranges(free, min_stripe_size, 0);
943 * Read used space, and since we have the used space,
944 * calcuate data_chunks and free for later mkfs
946 static int convert_read_used_space(struct btrfs_convert_context *cctx)
950 ret = cctx->convert_ops->read_used_space(cctx);
954 ret = calculate_available_space(cctx);
959 * Create the fs image file of old filesystem.
961 * This is completely fs independent as we have cctx->used, only
962 * need to create file extents pointing to all the positions.
964 static int create_image(struct btrfs_root *root,
965 struct btrfs_mkfs_config *cfg,
966 struct btrfs_convert_context *cctx, int fd,
967 u64 size, char *name, int datacsum)
969 struct btrfs_inode_item buf;
970 struct btrfs_trans_handle *trans;
971 struct btrfs_path *path = NULL;
972 struct btrfs_key key;
973 struct cache_extent *cache;
974 struct cache_tree used_tmp;
977 u64 flags = BTRFS_INODE_READONLY;
981 flags |= BTRFS_INODE_NODATASUM;
983 trans = btrfs_start_transaction(root, 1);
987 cache_tree_init(&used_tmp);
989 ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
993 ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
996 ret = btrfs_change_inode_flags(trans, root, ino, flags);
999 ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1000 strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1004 path = btrfs_alloc_path();
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_free_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 path = btrfs_alloc_path();
1101 key.objectid = dirid;
1102 key.type = BTRFS_DIR_INDEX_KEY;
1103 key.offset = (u64)-1;
1105 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1107 error("search for DIR_INDEX dirid %llu failed: %d",
1108 (unsigned long long)dirid, ret);
1112 if (path->slots[0] > 0) {
1114 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1115 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1116 index = key.offset + 1;
1118 btrfs_release_path(path);
1120 trans = btrfs_start_transaction(root, 1);
1122 error("unable to start transaction");
1126 key.objectid = dirid;
1128 key.type = BTRFS_INODE_ITEM_KEY;
1130 ret = btrfs_lookup_inode(trans, root, path, &key, 1);
1132 error("search for INODE_ITEM %llu failed: %d",
1133 (unsigned long long)dirid, ret);
1136 leaf = path->nodes[0];
1137 inode_item = btrfs_item_ptr(leaf, path->slots[0],
1138 struct btrfs_inode_item);
1140 key.objectid = root_objectid;
1141 key.offset = (u64)-1;
1142 key.type = BTRFS_ROOT_ITEM_KEY;
1144 memcpy(buf, base, len);
1145 for (i = 0; i < 1024; i++) {
1146 ret = btrfs_insert_dir_item(trans, root, buf, len,
1147 dirid, &key, BTRFS_FT_DIR, index);
1150 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1151 if (len < 1 || len > BTRFS_NAME_LEN) {
1159 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1160 btrfs_inode_size(leaf, inode_item));
1161 btrfs_mark_buffer_dirty(leaf);
1162 btrfs_release_path(path);
1164 /* add the backref first */
1165 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1166 BTRFS_ROOT_BACKREF_KEY,
1167 root->root_key.objectid,
1168 dirid, index, buf, len);
1170 error("unable to add root backref for %llu: %d",
1171 root->root_key.objectid, ret);
1175 /* now add the forward ref */
1176 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1177 BTRFS_ROOT_REF_KEY, root_objectid,
1178 dirid, index, buf, len);
1180 error("unable to add root ref for %llu: %d",
1181 root->root_key.objectid, ret);
1185 ret = btrfs_commit_transaction(trans, root);
1187 error("transaction commit failed: %d", ret);
1191 new_root = btrfs_read_fs_root(fs_info, &key);
1192 if (IS_ERR(new_root)) {
1193 error("unable to fs read root: %lu", PTR_ERR(new_root));
1197 btrfs_free_path(path);
1201 static int create_subvol(struct btrfs_trans_handle *trans,
1202 struct btrfs_root *root, u64 root_objectid)
1204 struct extent_buffer *tmp;
1205 struct btrfs_root *new_root;
1206 struct btrfs_key key;
1207 struct btrfs_root_item root_item;
1210 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1215 memcpy(&root_item, &root->root_item, sizeof(root_item));
1216 btrfs_set_root_bytenr(&root_item, tmp->start);
1217 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1218 btrfs_set_root_generation(&root_item, trans->transid);
1219 free_extent_buffer(tmp);
1221 key.objectid = root_objectid;
1222 key.type = BTRFS_ROOT_ITEM_KEY;
1223 key.offset = trans->transid;
1224 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1227 key.offset = (u64)-1;
1228 new_root = btrfs_read_fs_root(root->fs_info, &key);
1229 if (!new_root || IS_ERR(new_root)) {
1230 error("unable to fs read root: %lu", PTR_ERR(new_root));
1231 return PTR_ERR(new_root);
1234 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1240 * New make_btrfs() has handle system and meta chunks quite well.
1241 * So only need to add remaining data chunks.
1243 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1244 struct btrfs_fs_info *fs_info,
1245 struct btrfs_mkfs_config *cfg,
1246 struct btrfs_convert_context *cctx)
1248 struct btrfs_root *extent_root = fs_info->extent_root;
1249 struct cache_tree *data_chunks = &cctx->data_chunks;
1250 struct cache_extent *cache;
1255 * Don't create data chunk over 10% of the convert device
1256 * And for single chunk, don't create chunk larger than 1G.
1258 max_chunk_size = cfg->num_bytes / 10;
1259 max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1260 max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1262 for (cache = first_cache_extent(data_chunks); cache;
1263 cache = next_cache_extent(cache)) {
1264 u64 cur = cache->start;
1266 while (cur < cache->start + cache->size) {
1268 u64 cur_backup = cur;
1270 len = min(max_chunk_size,
1271 cache->start + cache->size - cur);
1272 ret = btrfs_alloc_data_chunk(trans, extent_root,
1274 BTRFS_BLOCK_GROUP_DATA, 1);
1277 ret = btrfs_make_block_group(trans, extent_root, 0,
1278 BTRFS_BLOCK_GROUP_DATA,
1279 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1290 * Init the temp btrfs to a operational status.
1292 * It will fix the extent usage accounting(XXX: Do we really need?) and
1293 * insert needed data chunks, to ensure all old fs data extents are covered
1294 * by DATA chunks, preventing wrong chunks are allocated.
1296 * And also create convert image subvolume and relocation tree.
1297 * (XXX: Not need again?)
1298 * But the convert image subvolume is *NOT* linked to fs tree yet.
1300 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1301 struct btrfs_convert_context *cctx, int datacsum,
1302 int packing, int noxattr)
1304 struct btrfs_key location;
1305 struct btrfs_trans_handle *trans;
1306 struct btrfs_fs_info *fs_info = root->fs_info;
1310 * Don't alloc any metadata/system chunk, as we don't want
1311 * any meta/sys chunk allcated before all data chunks are inserted.
1312 * Or we screw up the chunk layout just like the old implement.
1314 fs_info->avoid_sys_chunk_alloc = 1;
1315 fs_info->avoid_meta_chunk_alloc = 1;
1316 trans = btrfs_start_transaction(root, 1);
1318 error("unable to start transaction");
1322 ret = btrfs_fix_block_accounting(trans, root);
1325 ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1328 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1329 BTRFS_ROOT_TREE_DIR_OBJECTID);
1332 memcpy(&location, &root->root_key, sizeof(location));
1333 location.offset = (u64)-1;
1334 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1335 btrfs_super_root_dir(fs_info->super_copy),
1336 &location, BTRFS_FT_DIR, 0);
1339 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1341 btrfs_super_root_dir(fs_info->super_copy), 0);
1344 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1345 BTRFS_FIRST_FREE_OBJECTID);
1347 /* subvol for fs image file */
1348 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1350 error("failed to create subvolume image root: %d", ret);
1353 /* subvol for data relocation tree */
1354 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1356 error("failed to create DATA_RELOC root: %d", ret);
1360 ret = btrfs_commit_transaction(trans, root);
1361 fs_info->avoid_sys_chunk_alloc = 0;
1362 fs_info->avoid_meta_chunk_alloc = 0;
1368 * Migrate super block to its default position and zero 0 ~ 16k
1370 static int migrate_super_block(int fd, u64 old_bytenr, u32 sectorsize)
1373 struct extent_buffer *buf;
1374 struct btrfs_super_block *super;
1378 buf = malloc(sizeof(*buf) + sectorsize);
1382 buf->len = sectorsize;
1383 ret = pread(fd, buf->data, sectorsize, old_bytenr);
1384 if (ret != sectorsize)
1387 super = (struct btrfs_super_block *)buf->data;
1388 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1389 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1391 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1392 ret = pwrite(fd, buf->data, sectorsize, BTRFS_SUPER_INFO_OFFSET);
1393 if (ret != sectorsize)
1400 memset(buf->data, 0, sectorsize);
1401 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1402 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1403 if (len > sectorsize)
1405 ret = pwrite(fd, buf->data, len, bytenr);
1407 fprintf(stderr, "unable to zero fill device\n");
1421 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1423 struct btrfs_chunk *chunk;
1424 struct btrfs_disk_key *key;
1425 u32 sectorsize = btrfs_super_sectorsize(super);
1427 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1428 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1429 sizeof(struct btrfs_disk_key));
1431 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1432 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1433 btrfs_set_disk_key_offset(key, 0);
1435 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1436 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1437 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1438 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1439 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1440 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1441 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1442 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1443 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1444 chunk->stripe.devid = super->dev_item.devid;
1445 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1446 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1447 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1451 #if BTRFSCONVERT_EXT2
1454 * Open Ext2fs in readonly mode, read block allocation bitmap and
1455 * inode bitmap into memory.
1457 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
1460 ext2_filsys ext2_fs;
1464 ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
1466 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
1470 * We need to know exactly the used space, some RO compat flags like
1471 * BIGALLOC will affect how used space is present.
1472 * So we need manuall check any unsupported RO compat flags
1474 ro_feature = ext2_fs->super->s_feature_ro_compat;
1475 if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
1477 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
1478 ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1481 ret = ext2fs_read_inode_bitmap(ext2_fs);
1483 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
1484 error_message(ret));
1487 ret = ext2fs_read_block_bitmap(ext2_fs);
1489 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
1490 error_message(ret));
1494 * search each block group for a free inode. this set up
1495 * uninit block/inode bitmaps appropriately.
1498 while (ino <= ext2_fs->super->s_inodes_count) {
1500 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
1501 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
1504 if (!(ext2_fs->super->s_feature_incompat &
1505 EXT2_FEATURE_INCOMPAT_FILETYPE)) {
1506 error("filetype feature is missing");
1510 cctx->fs_data = ext2_fs;
1511 cctx->blocksize = ext2_fs->blocksize;
1512 cctx->block_count = ext2_fs->super->s_blocks_count;
1513 cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
1514 cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
1515 cctx->first_data_block = ext2_fs->super->s_first_data_block;
1516 cctx->inodes_count = ext2_fs->super->s_inodes_count;
1517 cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
1520 ext2fs_close(ext2_fs);
1524 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
1525 unsigned long group_nr, struct cache_tree *used)
1527 unsigned long offset;
1531 offset = fs->super->s_first_data_block;
1532 offset /= EXT2FS_CLUSTER_RATIO(fs);
1533 offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
1534 for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
1535 if (ext2fs_test_bit(i, bitmap)) {
1538 start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
1539 start *= fs->blocksize;
1540 ret = add_merge_cache_extent(used, start,
1550 * Read all used ext2 space into cctx->used cache tree
1552 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
1554 ext2_filsys fs = (ext2_filsys)cctx->fs_data;
1555 blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
1556 struct cache_tree *used_tree = &cctx->used;
1557 char *block_bitmap = NULL;
1562 block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
1563 /* Shouldn't happen */
1564 BUG_ON(!fs->block_map);
1566 block_bitmap = malloc(block_nbytes);
1570 for (i = 0; i < fs->group_desc_count; i++) {
1571 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
1572 block_nbytes * 8, block_bitmap);
1574 error("fail to get bitmap from ext2, %s",
1578 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
1580 error("fail to build used space tree, %s",
1584 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
1591 static void ext2_close_fs(struct btrfs_convert_context *cctx)
1593 if (cctx->volume_name) {
1594 free(cctx->volume_name);
1595 cctx->volume_name = NULL;
1597 ext2fs_close(cctx->fs_data);
1600 struct dir_iterate_data {
1601 struct btrfs_trans_handle *trans;
1602 struct btrfs_root *root;
1603 struct btrfs_inode_item *inode;
1610 static u8 ext2_filetype_conversion_table[EXT2_FT_MAX] = {
1611 [EXT2_FT_UNKNOWN] = BTRFS_FT_UNKNOWN,
1612 [EXT2_FT_REG_FILE] = BTRFS_FT_REG_FILE,
1613 [EXT2_FT_DIR] = BTRFS_FT_DIR,
1614 [EXT2_FT_CHRDEV] = BTRFS_FT_CHRDEV,
1615 [EXT2_FT_BLKDEV] = BTRFS_FT_BLKDEV,
1616 [EXT2_FT_FIFO] = BTRFS_FT_FIFO,
1617 [EXT2_FT_SOCK] = BTRFS_FT_SOCK,
1618 [EXT2_FT_SYMLINK] = BTRFS_FT_SYMLINK,
1621 static int ext2_dir_iterate_proc(ext2_ino_t dir, int entry,
1622 struct ext2_dir_entry *dirent,
1623 int offset, int blocksize,
1624 char *buf,void *priv_data)
1629 char dotdot[] = "..";
1630 struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
1633 name_len = dirent->name_len & 0xFF;
1635 objectid = dirent->inode + INO_OFFSET;
1636 if (!strncmp(dirent->name, dotdot, name_len)) {
1637 if (name_len == 2) {
1638 BUG_ON(idata->parent != 0);
1639 idata->parent = objectid;
1643 if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
1646 file_type = dirent->name_len >> 8;
1647 BUG_ON(file_type > EXT2_FT_SYMLINK);
1649 ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
1650 name_len, idata->objectid, objectid,
1651 ext2_filetype_conversion_table[file_type],
1652 idata->index_cnt, idata->inode);
1654 idata->errcode = ret;
1662 static int ext2_create_dir_entries(struct btrfs_trans_handle *trans,
1663 struct btrfs_root *root, u64 objectid,
1664 struct btrfs_inode_item *btrfs_inode,
1665 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
1669 struct dir_iterate_data data = {
1672 .inode = btrfs_inode,
1673 .objectid = objectid,
1679 err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
1680 ext2_dir_iterate_proc, &data);
1684 if (ret == 0 && data.parent == objectid) {
1685 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
1686 objectid, objectid, 0);
1690 fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
1694 static int ext2_block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
1695 e2_blkcnt_t blockcnt, blk_t ref_block,
1696 int ref_offset, void *priv_data)
1699 struct blk_iterate_data *idata;
1700 idata = (struct blk_iterate_data *)priv_data;
1701 ret = block_iterate_proc(*blocknr, blockcnt, idata);
1703 idata->errcode = ret;
1710 * traverse file's data blocks, record these data blocks as file extents.
1712 static int ext2_create_file_extents(struct btrfs_trans_handle *trans,
1713 struct btrfs_root *root, u64 objectid,
1714 struct btrfs_inode_item *btrfs_inode,
1715 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1716 int datacsum, int packing)
1719 char *buffer = NULL;
1722 u32 sectorsize = root->sectorsize;
1723 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1724 struct blk_iterate_data data;
1726 init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
1729 err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
1730 NULL, ext2_block_iterate_proc, &data);
1736 if (packing && data.first_block == 0 && data.num_blocks > 0 &&
1737 inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
1738 u64 num_bytes = data.num_blocks * sectorsize;
1739 u64 disk_bytenr = data.disk_block * sectorsize;
1742 buffer = malloc(num_bytes);
1745 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
1748 if (num_bytes > inode_size)
1749 num_bytes = inode_size;
1750 ret = btrfs_insert_inline_extent(trans, root, objectid,
1751 0, buffer, num_bytes);
1754 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
1755 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
1756 } else if (data.num_blocks > 0) {
1757 ret = record_file_blocks(&data, data.first_block,
1758 data.disk_block, data.num_blocks);
1762 data.first_block += data.num_blocks;
1763 last_block = (inode_size + sectorsize - 1) / sectorsize;
1764 if (last_block > data.first_block) {
1765 ret = record_file_blocks(&data, data.first_block, 0,
1766 last_block - data.first_block);
1772 fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
1776 static int ext2_create_symbol_link(struct btrfs_trans_handle *trans,
1777 struct btrfs_root *root, u64 objectid,
1778 struct btrfs_inode_item *btrfs_inode,
1779 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1780 struct ext2_inode *ext2_inode)
1784 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1785 if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
1786 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
1787 ret = ext2_create_file_extents(trans, root, objectid,
1788 btrfs_inode, ext2_fs, ext2_ino, 1, 1);
1789 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
1793 pathname = (char *)&(ext2_inode->i_block[0]);
1794 BUG_ON(pathname[inode_size] != 0);
1795 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
1796 pathname, inode_size + 1);
1797 btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
1802 * Following xattr/acl related codes are based on codes in
1803 * fs/ext3/xattr.c and fs/ext3/acl.c
1805 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
1806 #define EXT2_XATTR_BFIRST(ptr) \
1807 ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
1808 #define EXT2_XATTR_IHDR(inode) \
1809 ((struct ext2_ext_attr_header *) ((void *)(inode) + \
1810 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
1811 #define EXT2_XATTR_IFIRST(inode) \
1812 ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
1813 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
1815 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
1818 struct ext2_ext_attr_entry *next;
1820 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1821 next = EXT2_EXT_ATTR_NEXT(entry);
1822 if ((void *)next >= end)
1829 static int ext2_xattr_check_block(const char *buf, size_t size)
1832 struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
1834 if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
1835 header->h_blocks != 1)
1837 error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
1841 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
1844 size_t value_size = entry->e_value_size;
1846 if (entry->e_value_block != 0 || value_size > size ||
1847 entry->e_value_offs + value_size > size)
1852 #define EXT2_ACL_VERSION 0x0001
1854 /* 23.2.5 acl_tag_t values */
1856 #define ACL_UNDEFINED_TAG (0x00)
1857 #define ACL_USER_OBJ (0x01)
1858 #define ACL_USER (0x02)
1859 #define ACL_GROUP_OBJ (0x04)
1860 #define ACL_GROUP (0x08)
1861 #define ACL_MASK (0x10)
1862 #define ACL_OTHER (0x20)
1864 /* 23.2.7 ACL qualifier constants */
1866 #define ACL_UNDEFINED_ID ((id_t)-1)
1877 } ext2_acl_entry_short;
1883 static inline int ext2_acl_count(size_t size)
1886 size -= sizeof(ext2_acl_header);
1887 s = size - 4 * sizeof(ext2_acl_entry_short);
1889 if (size % sizeof(ext2_acl_entry_short))
1891 return size / sizeof(ext2_acl_entry_short);
1893 if (s % sizeof(ext2_acl_entry))
1895 return s / sizeof(ext2_acl_entry) + 4;
1899 #define ACL_EA_VERSION 0x0002
1909 acl_ea_entry a_entries[0];
1912 static inline size_t acl_ea_size(int count)
1914 return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
1917 static int ext2_acl_to_xattr(void *dst, const void *src,
1918 size_t dst_size, size_t src_size)
1921 const void *end = src + src_size;
1922 acl_ea_header *ext_acl = (acl_ea_header *)dst;
1923 acl_ea_entry *dst_entry = ext_acl->a_entries;
1924 ext2_acl_entry *src_entry;
1926 if (src_size < sizeof(ext2_acl_header))
1928 if (((ext2_acl_header *)src)->a_version !=
1929 cpu_to_le32(EXT2_ACL_VERSION))
1931 src += sizeof(ext2_acl_header);
1932 count = ext2_acl_count(src_size);
1936 BUG_ON(dst_size < acl_ea_size(count));
1937 ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
1938 for (i = 0; i < count; i++, dst_entry++) {
1939 src_entry = (ext2_acl_entry *)src;
1940 if (src + sizeof(ext2_acl_entry_short) > end)
1942 dst_entry->e_tag = src_entry->e_tag;
1943 dst_entry->e_perm = src_entry->e_perm;
1944 switch (le16_to_cpu(src_entry->e_tag)) {
1949 src += sizeof(ext2_acl_entry_short);
1950 dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
1954 src += sizeof(ext2_acl_entry);
1957 dst_entry->e_id = src_entry->e_id;
1970 static char *xattr_prefix_table[] = {
1972 [2] = "system.posix_acl_access",
1973 [3] = "system.posix_acl_default",
1978 static int ext2_copy_single_xattr(struct btrfs_trans_handle *trans,
1979 struct btrfs_root *root, u64 objectid,
1980 struct ext2_ext_attr_entry *entry,
1981 const void *data, u32 datalen)
1986 void *databuf = NULL;
1987 char namebuf[XATTR_NAME_MAX + 1];
1989 name_index = entry->e_name_index;
1990 if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
1991 xattr_prefix_table[name_index] == NULL)
1993 name_len = strlen(xattr_prefix_table[name_index]) +
1995 if (name_len >= sizeof(namebuf))
1998 if (name_index == 2 || name_index == 3) {
1999 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
2000 databuf = malloc(bufsize);
2003 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
2009 strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
2010 strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
2011 if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
2012 sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
2013 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
2014 objectid - INO_OFFSET, name_len, namebuf);
2017 ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
2018 data, datalen, objectid);
2024 static int ext2_copy_extended_attrs(struct btrfs_trans_handle *trans,
2025 struct btrfs_root *root, u64 objectid,
2026 struct btrfs_inode_item *btrfs_inode,
2027 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
2033 u32 block_size = ext2_fs->blocksize;
2034 u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
2035 struct ext2_inode_large *ext2_inode;
2036 struct ext2_ext_attr_entry *entry;
2038 char *buffer = NULL;
2039 char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
2041 if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
2042 ext2_inode = (struct ext2_inode_large *)inode_buf;
2044 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
2048 err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
2051 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
2052 error_message(err));
2057 if (ext2_ino > ext2_fs->super->s_first_ino &&
2058 inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
2059 if (EXT2_GOOD_OLD_INODE_SIZE +
2060 ext2_inode->i_extra_isize > inode_size) {
2064 if (ext2_inode->i_extra_isize != 0 &&
2065 EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
2066 EXT2_EXT_ATTR_MAGIC) {
2072 void *end = (void *)ext2_inode + inode_size;
2073 entry = EXT2_XATTR_IFIRST(ext2_inode);
2074 total = end - (void *)entry;
2075 ret = ext2_xattr_check_names(entry, end);
2078 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2079 ret = ext2_xattr_check_entry(entry, total);
2082 data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
2083 entry->e_value_offs;
2084 datalen = entry->e_value_size;
2085 ret = ext2_copy_single_xattr(trans, root, objectid,
2086 entry, data, datalen);
2089 entry = EXT2_EXT_ATTR_NEXT(entry);
2093 if (ext2_inode->i_file_acl == 0)
2096 buffer = malloc(block_size);
2101 err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
2103 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
2104 error_message(err));
2108 ret = ext2_xattr_check_block(buffer, block_size);
2112 entry = EXT2_XATTR_BFIRST(buffer);
2113 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2114 ret = ext2_xattr_check_entry(entry, block_size);
2117 data = buffer + entry->e_value_offs;
2118 datalen = entry->e_value_size;
2119 ret = ext2_copy_single_xattr(trans, root, objectid,
2120 entry, data, datalen);
2123 entry = EXT2_EXT_ATTR_NEXT(entry);
2127 if ((void *)ext2_inode != inode_buf)
2131 #define MINORBITS 20
2132 #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
2134 static inline dev_t old_decode_dev(u16 val)
2136 return MKDEV((val >> 8) & 255, val & 255);
2139 static inline dev_t new_decode_dev(u32 dev)
2141 unsigned major = (dev & 0xfff00) >> 8;
2142 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
2143 return MKDEV(major, minor);
2146 static void ext2_copy_inode_item(struct btrfs_inode_item *dst,
2147 struct ext2_inode *src, u32 blocksize)
2149 btrfs_set_stack_inode_generation(dst, 1);
2150 btrfs_set_stack_inode_sequence(dst, 0);
2151 btrfs_set_stack_inode_transid(dst, 1);
2152 btrfs_set_stack_inode_size(dst, src->i_size);
2153 btrfs_set_stack_inode_nbytes(dst, 0);
2154 btrfs_set_stack_inode_block_group(dst, 0);
2155 btrfs_set_stack_inode_nlink(dst, src->i_links_count);
2156 btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
2157 btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
2158 btrfs_set_stack_inode_mode(dst, src->i_mode);
2159 btrfs_set_stack_inode_rdev(dst, 0);
2160 btrfs_set_stack_inode_flags(dst, 0);
2161 btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
2162 btrfs_set_stack_timespec_nsec(&dst->atime, 0);
2163 btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
2164 btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
2165 btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
2166 btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
2167 btrfs_set_stack_timespec_sec(&dst->otime, 0);
2168 btrfs_set_stack_timespec_nsec(&dst->otime, 0);
2170 if (S_ISDIR(src->i_mode)) {
2171 btrfs_set_stack_inode_size(dst, 0);
2172 btrfs_set_stack_inode_nlink(dst, 1);
2174 if (S_ISREG(src->i_mode)) {
2175 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
2178 if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
2179 !S_ISLNK(src->i_mode)) {
2180 if (src->i_block[0]) {
2181 btrfs_set_stack_inode_rdev(dst,
2182 old_decode_dev(src->i_block[0]));
2184 btrfs_set_stack_inode_rdev(dst,
2185 new_decode_dev(src->i_block[1]));
2188 memset(&dst->reserved, 0, sizeof(dst->reserved));
2190 static int ext2_check_state(struct btrfs_convert_context *cctx)
2192 ext2_filsys fs = cctx->fs_data;
2194 if (!(fs->super->s_state & EXT2_VALID_FS))
2196 else if (fs->super->s_state & EXT2_ERROR_FS)
2202 /* EXT2_*_FL to BTRFS_INODE_FLAG_* stringification helper */
2203 #define COPY_ONE_EXT2_FLAG(flags, ext2_inode, name) ({ \
2204 if (ext2_inode->i_flags & EXT2_##name##_FL) \
2205 flags |= BTRFS_INODE_##name; \
2209 * Convert EXT2_*_FL to corresponding BTRFS_INODE_* flags
2211 * Only a subset of EXT_*_FL is supported in btrfs.
2213 static void ext2_convert_inode_flags(struct btrfs_inode_item *dst,
2214 struct ext2_inode *src)
2218 COPY_ONE_EXT2_FLAG(flags, src, APPEND);
2219 COPY_ONE_EXT2_FLAG(flags, src, SYNC);
2220 COPY_ONE_EXT2_FLAG(flags, src, IMMUTABLE);
2221 COPY_ONE_EXT2_FLAG(flags, src, NODUMP);
2222 COPY_ONE_EXT2_FLAG(flags, src, NOATIME);
2223 COPY_ONE_EXT2_FLAG(flags, src, DIRSYNC);
2224 btrfs_set_stack_inode_flags(dst, flags);
2228 * copy a single inode. do all the required works, such as cloning
2229 * inode item, creating file extents and creating directory entries.
2231 static int ext2_copy_single_inode(struct btrfs_trans_handle *trans,
2232 struct btrfs_root *root, u64 objectid,
2233 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
2234 struct ext2_inode *ext2_inode,
2235 int datacsum, int packing, int noxattr)
2238 struct btrfs_inode_item btrfs_inode;
2240 if (ext2_inode->i_links_count == 0)
2243 ext2_copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
2244 if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
2245 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
2246 BTRFS_INODE_NODATASUM;
2247 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
2249 ext2_convert_inode_flags(&btrfs_inode, ext2_inode);
2251 switch (ext2_inode->i_mode & S_IFMT) {
2253 ret = ext2_create_file_extents(trans, root, objectid,
2254 &btrfs_inode, ext2_fs, ext2_ino, datacsum, packing);
2257 ret = ext2_create_dir_entries(trans, root, objectid,
2258 &btrfs_inode, ext2_fs, ext2_ino);
2261 ret = ext2_create_symbol_link(trans, root, objectid,
2262 &btrfs_inode, ext2_fs, ext2_ino, ext2_inode);
2272 ret = ext2_copy_extended_attrs(trans, root, objectid,
2273 &btrfs_inode, ext2_fs, ext2_ino);
2277 return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
2281 * scan ext2's inode bitmap and copy all used inodes.
2283 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
2284 struct btrfs_root *root,
2285 int datacsum, int packing, int noxattr, struct task_ctx *p)
2287 ext2_filsys ext2_fs = cctx->fs_data;
2290 ext2_inode_scan ext2_scan;
2291 struct ext2_inode ext2_inode;
2292 ext2_ino_t ext2_ino;
2294 struct btrfs_trans_handle *trans;
2296 trans = btrfs_start_transaction(root, 1);
2299 err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
2301 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
2304 while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
2306 /* no more inodes */
2309 /* skip special inode in ext2fs */
2310 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
2311 ext2_ino != EXT2_ROOT_INO)
2313 objectid = ext2_ino + INO_OFFSET;
2314 ret = ext2_copy_single_inode(trans, root,
2315 objectid, ext2_fs, ext2_ino,
2316 &ext2_inode, datacsum, packing,
2318 p->cur_copy_inodes++;
2321 if (trans->blocks_used >= 4096) {
2322 ret = btrfs_commit_transaction(trans, root);
2324 trans = btrfs_start_transaction(root, 1);
2329 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
2332 ret = btrfs_commit_transaction(trans, root);
2334 ext2fs_close_inode_scan(ext2_scan);
2339 static const struct btrfs_convert_operations ext2_convert_ops = {
2341 .open_fs = ext2_open_fs,
2342 .read_used_space = ext2_read_used_space,
2343 .copy_inodes = ext2_copy_inodes,
2344 .close_fs = ext2_close_fs,
2345 .check_state = ext2_check_state,
2350 static const struct btrfs_convert_operations *convert_operations[] = {
2351 #if BTRFSCONVERT_EXT2
2356 static int convert_open_fs(const char *devname,
2357 struct btrfs_convert_context *cctx)
2361 memset(cctx, 0, sizeof(*cctx));
2363 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2364 int ret = convert_operations[i]->open_fs(cctx, devname);
2367 cctx->convert_ops = convert_operations[i];
2372 error("no file system found to convert");
2376 static int do_convert(const char *devname, int datacsum, int packing,
2377 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
2378 int progress, u64 features)
2384 struct btrfs_root *root;
2385 struct btrfs_root *image_root;
2386 struct btrfs_convert_context cctx;
2387 struct btrfs_key key;
2388 char *subvol_name = NULL;
2389 struct task_ctx ctx;
2390 char features_buf[64];
2391 struct btrfs_mkfs_config mkfs_cfg;
2393 init_convert_context(&cctx);
2394 ret = convert_open_fs(devname, &cctx);
2397 ret = convert_check_state(&cctx);
2400 "source filesystem is not clean, running filesystem check is recommended");
2401 ret = convert_read_used_space(&cctx);
2405 blocksize = cctx.blocksize;
2406 total_bytes = (u64)blocksize * (u64)cctx.block_count;
2407 if (blocksize < 4096) {
2408 error("block size is too small: %u < 4096", blocksize);
2411 if (btrfs_check_nodesize(nodesize, blocksize, features))
2413 fd = open(devname, O_RDWR);
2415 error("unable to open %s: %s", devname, strerror(errno));
2418 btrfs_parse_features_to_string(features_buf, features);
2419 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2420 strcat(features_buf, " (default)");
2422 printf("create btrfs filesystem:\n");
2423 printf("\tblocksize: %u\n", blocksize);
2424 printf("\tnodesize: %u\n", nodesize);
2425 printf("\tfeatures: %s\n", features_buf);
2427 mkfs_cfg.label = cctx.volume_name;
2428 mkfs_cfg.num_bytes = total_bytes;
2429 mkfs_cfg.nodesize = nodesize;
2430 mkfs_cfg.sectorsize = blocksize;
2431 mkfs_cfg.stripesize = blocksize;
2432 mkfs_cfg.features = features;
2433 /* New convert need these space */
2434 memset(mkfs_cfg.chunk_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2435 memset(mkfs_cfg.fs_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2437 ret = make_btrfs(fd, &mkfs_cfg, &cctx);
2439 error("unable to create initial ctree: %s", strerror(-ret));
2443 root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
2444 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2446 error("unable to open ctree");
2449 ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
2451 error("unable to setup the root tree: %d", ret);
2455 printf("creating %s image file\n", cctx.convert_ops->name);
2456 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2458 error("memory allocation failure for subvolume name: %s_saved",
2459 cctx.convert_ops->name);
2462 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2463 key.offset = (u64)-1;
2464 key.type = BTRFS_ROOT_ITEM_KEY;
2465 image_root = btrfs_read_fs_root(root->fs_info, &key);
2467 error("unable to create image subvolume");
2470 ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
2471 mkfs_cfg.num_bytes, "image", datacsum);
2473 error("failed to create %s/image: %d", subvol_name, ret);
2477 printf("creating btrfs metadata");
2478 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2479 ctx.cur_copy_inodes = 0;
2482 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
2484 task_start(ctx.info);
2486 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2488 error("error during copy_inodes %d", ret);
2492 task_stop(ctx.info);
2493 task_deinit(ctx.info);
2496 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2498 error("unable to link subvolume %s", subvol_name);
2504 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2505 if (copylabel == 1) {
2506 __strncpy_null(root->fs_info->super_copy->label,
2507 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2508 printf("copy label '%s'\n", root->fs_info->super_copy->label);
2509 } else if (copylabel == -1) {
2510 strcpy(root->fs_info->super_copy->label, fslabel);
2511 printf("set label to '%s'\n", fslabel);
2514 ret = close_ctree(root);
2516 error("close_ctree failed: %d", ret);
2519 convert_close_fs(&cctx);
2520 clean_convert_context(&cctx);
2523 * If this step succeed, we get a mountable btrfs. Otherwise
2524 * the source fs is left unchanged.
2526 ret = migrate_super_block(fd, mkfs_cfg.super_bytenr, blocksize);
2528 error("unable to migrate super block: %d", ret);
2532 root = open_ctree_fd(fd, devname, 0,
2533 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2535 error("unable to open ctree for finalization");
2538 root->fs_info->finalize_on_close = 1;
2542 printf("conversion complete");
2545 clean_convert_context(&cctx);
2549 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
2554 * Check if a non 1:1 mapped chunk can be rolled back.
2555 * For new convert, it's OK while for old convert it's not.
2557 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
2559 struct btrfs_block_group_cache *bg;
2560 struct btrfs_key key;
2561 struct btrfs_path path;
2562 struct btrfs_root *extent_root = fs_info->extent_root;
2567 bg = btrfs_lookup_first_block_group(fs_info, bytenr);
2570 bg_start = bg->key.objectid;
2571 bg_end = bg->key.objectid + bg->key.offset;
2573 key.objectid = bg_end;
2574 key.type = BTRFS_METADATA_ITEM_KEY;
2576 btrfs_init_path(&path);
2578 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2583 struct btrfs_extent_item *ei;
2585 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
2593 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2594 if (key.type == BTRFS_METADATA_ITEM_KEY)
2596 /* Now it's EXTENT_ITEM_KEY only */
2597 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
2598 struct btrfs_extent_item);
2600 * Found data extent, means this is old convert must follow 1:1
2603 if (btrfs_extent_flags(path.nodes[0], ei)
2604 & BTRFS_EXTENT_FLAG_DATA) {
2609 btrfs_release_path(&path);
2613 static int may_rollback(struct btrfs_root *root)
2615 struct btrfs_fs_info *info = root->fs_info;
2616 struct btrfs_multi_bio *multi = NULL;
2624 if (btrfs_super_num_devices(info->super_copy) != 1)
2627 bytenr = BTRFS_SUPER_INFO_OFFSET;
2628 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2631 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2632 &length, &multi, 0, NULL);
2634 if (ret == -ENOENT) {
2635 /* removed block group at the tail */
2636 if (length == (u64)-1)
2639 /* removed block group in the middle */
2645 num_stripes = multi->num_stripes;
2646 physical = multi->stripes[0].physical;
2649 if (num_stripes != 1) {
2650 error("num stripes for bytenr %llu is not 1", bytenr);
2655 * Extra check for new convert, as metadata chunk from new
2656 * convert is much more free than old convert, it doesn't need
2657 * to do 1:1 mapping.
2659 if (physical != bytenr) {
2661 * Check if it's a metadata chunk and has only metadata
2664 ret = may_rollback_chunk(info, bytenr);
2670 if (bytenr >= total_bytes)
2678 static int do_rollback(const char *devname)
2683 struct btrfs_root *root;
2684 struct btrfs_root *image_root;
2685 struct btrfs_root *chunk_root;
2686 struct btrfs_dir_item *dir;
2687 struct btrfs_inode_item *inode;
2688 struct btrfs_file_extent_item *fi;
2689 struct btrfs_trans_handle *trans;
2690 struct extent_buffer *leaf;
2691 struct btrfs_block_group_cache *cache1;
2692 struct btrfs_block_group_cache *cache2;
2693 struct btrfs_key key;
2694 struct btrfs_path path;
2695 struct extent_io_tree io_tree;
2710 extent_io_tree_init(&io_tree);
2712 fd = open(devname, O_RDWR);
2714 error("unable to open %s: %s", devname, strerror(errno));
2717 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2719 error("unable to open ctree");
2722 ret = may_rollback(root);
2724 error("unable to do rollback: %d", ret);
2728 sectorsize = root->sectorsize;
2729 buf = malloc(sectorsize);
2731 error("unable to allocate memory");
2735 btrfs_init_path(&path);
2737 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2738 key.type = BTRFS_ROOT_BACKREF_KEY;
2739 key.offset = BTRFS_FS_TREE_OBJECTID;
2740 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2742 btrfs_release_path(&path);
2744 error("unable to convert ext2 image subvolume, is it deleted?");
2746 } else if (ret < 0) {
2747 error("unable to open ext2_saved, id %llu: %s",
2748 (unsigned long long)key.objectid, strerror(-ret));
2752 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2753 key.type = BTRFS_ROOT_ITEM_KEY;
2754 key.offset = (u64)-1;
2755 image_root = btrfs_read_fs_root(root->fs_info, &key);
2756 if (!image_root || IS_ERR(image_root)) {
2757 error("unable to open subvolume %llu: %ld",
2758 (unsigned long long)key.objectid, PTR_ERR(image_root));
2763 root_dir = btrfs_root_dirid(&root->root_item);
2764 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2765 root_dir, name, strlen(name), 0);
2766 if (!dir || IS_ERR(dir)) {
2767 error("unable to find file %s: %ld", name, PTR_ERR(dir));
2770 leaf = path.nodes[0];
2771 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2772 btrfs_release_path(&path);
2774 objectid = key.objectid;
2776 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2778 error("unable to find inode item: %d", ret);
2781 leaf = path.nodes[0];
2782 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2783 total_bytes = btrfs_inode_size(leaf, inode);
2784 btrfs_release_path(&path);
2786 key.objectid = objectid;
2788 key.type = BTRFS_EXTENT_DATA_KEY;
2789 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2791 error("unable to find first file extent: %d", ret);
2792 btrfs_release_path(&path);
2796 /* build mapping tree for the relocated blocks */
2797 for (offset = 0; offset < total_bytes; ) {
2798 leaf = path.nodes[0];
2799 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2800 ret = btrfs_next_leaf(root, &path);
2806 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2807 if (key.objectid != objectid || key.offset != offset ||
2808 key.type != BTRFS_EXTENT_DATA_KEY)
2811 fi = btrfs_item_ptr(leaf, path.slots[0],
2812 struct btrfs_file_extent_item);
2813 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2815 if (btrfs_file_extent_compression(leaf, fi) ||
2816 btrfs_file_extent_encryption(leaf, fi) ||
2817 btrfs_file_extent_other_encoding(leaf, fi))
2820 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2821 /* skip holes and direct mapped extents */
2822 if (bytenr == 0 || bytenr == offset)
2825 bytenr += btrfs_file_extent_offset(leaf, fi);
2826 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2828 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2829 cache2 = btrfs_lookup_block_group(root->fs_info,
2830 offset + num_bytes - 1);
2832 * Here we must take consideration of old and new convert
2834 * For old convert case, sign, there is no consist chunk type
2835 * that will cover the extent. META/DATA/SYS are all possible.
2836 * Just ensure relocate one is in SYS chunk.
2837 * For new convert case, they are all covered by DATA chunk.
2839 * So, there is not valid chunk type check for it now.
2841 if (cache1 != cache2)
2844 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2845 EXTENT_LOCKED, GFP_NOFS);
2846 set_state_private(&io_tree, offset, bytenr);
2848 offset += btrfs_file_extent_num_bytes(leaf, fi);
2851 btrfs_release_path(&path);
2853 if (offset < total_bytes) {
2854 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
2855 (unsigned long long)offset,
2856 (unsigned long long)total_bytes);
2857 error("converted filesystem after balance is unable to rollback");
2861 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2862 first_free &= ~((u64)sectorsize - 1);
2863 /* backup for extent #0 should exist */
2864 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2865 error("no backup for the first extent");
2868 /* force no allocation from system block group */
2869 root->fs_info->system_allocs = -1;
2870 trans = btrfs_start_transaction(root, 1);
2872 error("unable to start transaction");
2876 * recow the whole chunk tree, this will remove all chunk tree blocks
2877 * from system block group
2879 chunk_root = root->fs_info->chunk_root;
2880 memset(&key, 0, sizeof(key));
2882 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2886 ret = btrfs_next_leaf(chunk_root, &path);
2890 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2891 btrfs_release_path(&path);
2893 btrfs_release_path(&path);
2898 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2902 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2903 num_bytes += btrfs_block_group_used(&cache1->item);
2905 offset = cache1->key.objectid + cache1->key.offset;
2907 /* only extent #0 left in system block group? */
2908 if (num_bytes > first_free) {
2910 "unable to empty system block group (num_bytes %llu, first_free %llu",
2911 (unsigned long long)num_bytes,
2912 (unsigned long long)first_free);
2915 /* create a system chunk that maps the whole device */
2916 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2918 error("unable to update system chunk: %d", ret);
2922 ret = btrfs_commit_transaction(trans, root);
2924 error("transaction commit failed: %d", ret);
2928 ret = close_ctree(root);
2930 error("close_ctree failed: %d", ret);
2934 /* zero btrfs super block mirrors */
2935 memset(buf, 0, sectorsize);
2936 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2937 bytenr = btrfs_sb_offset(i);
2938 if (bytenr >= total_bytes)
2940 ret = pwrite(fd, buf, sectorsize, bytenr);
2941 if (ret != sectorsize) {
2942 error("zeroing superblock mirror %d failed: %d",
2948 sb_bytenr = (u64)-1;
2949 /* copy all relocated blocks back */
2951 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2956 ret = get_state_private(&io_tree, start, &bytenr);
2959 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2962 while (start <= end) {
2963 if (start == BTRFS_SUPER_INFO_OFFSET) {
2967 ret = pread(fd, buf, sectorsize, bytenr);
2969 error("reading superblock at %llu failed: %d",
2970 (unsigned long long)bytenr, ret);
2973 BUG_ON(ret != sectorsize);
2974 ret = pwrite(fd, buf, sectorsize, start);
2976 error("writing superblock at %llu failed: %d",
2977 (unsigned long long)start, ret);
2980 BUG_ON(ret != sectorsize);
2982 start += sectorsize;
2983 bytenr += sectorsize;
2989 error("fsync failed: %s", strerror(errno));
2993 * finally, overwrite btrfs super block.
2995 ret = pread(fd, buf, sectorsize, sb_bytenr);
2997 error("reading primary superblock failed: %s",
3001 BUG_ON(ret != sectorsize);
3002 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3004 error("writing primary superblock failed: %s",
3008 BUG_ON(ret != sectorsize);
3011 error("fsync failed: %s", strerror(errno));
3017 extent_io_tree_cleanup(&io_tree);
3018 printf("rollback complete\n");
3025 error("rollback aborted");
3029 static void print_usage(void)
3031 printf("usage: btrfs-convert [options] device\n");
3032 printf("options:\n");
3033 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
3034 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
3035 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
3036 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
3037 printf("\t-r|--rollback roll back to the original filesystem\n");
3038 printf("\t-l|--label LABEL set filesystem label\n");
3039 printf("\t-L|--copy-label use label from converted filesystem\n");
3040 printf("\t-p|--progress show converting progress (default)\n");
3041 printf("\t-O|--features LIST comma separated list of filesystem features\n");
3042 printf("\t--no-progress show only overview, not the detailed progress\n");
3044 printf("Supported filesystems:\n");
3045 printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
3048 int main(int argc, char *argv[])
3054 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3055 BTRFS_MKFS_DEFAULT_NODE_SIZE);
3058 int usage_error = 0;
3061 char fslabel[BTRFS_LABEL_SIZE];
3062 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3065 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3066 static const struct option long_options[] = {
3067 { "no-progress", no_argument, NULL,
3068 GETOPT_VAL_NO_PROGRESS },
3069 { "no-datasum", no_argument, NULL, 'd' },
3070 { "no-inline", no_argument, NULL, 'n' },
3071 { "no-xattr", no_argument, NULL, 'i' },
3072 { "rollback", no_argument, NULL, 'r' },
3073 { "features", required_argument, NULL, 'O' },
3074 { "progress", no_argument, NULL, 'p' },
3075 { "label", required_argument, NULL, 'l' },
3076 { "copy-label", no_argument, NULL, 'L' },
3077 { "nodesize", required_argument, NULL, 'N' },
3078 { "help", no_argument, NULL, GETOPT_VAL_HELP},
3079 { NULL, 0, NULL, 0 }
3081 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3096 nodesize = parse_size(optarg);
3103 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3105 "label too long, trimmed to %d bytes",
3106 BTRFS_LABEL_SIZE - 1);
3108 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3117 char *orig = strdup(optarg);
3120 tmp = btrfs_parse_fs_features(tmp, &features);
3122 error("unrecognized filesystem feature: %s",
3128 if (features & BTRFS_FEATURE_LIST_ALL) {
3129 btrfs_list_all_fs_features(
3130 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3133 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3136 btrfs_parse_features_to_string(buf,
3137 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3138 error("features not allowed for convert: %s",
3145 case GETOPT_VAL_NO_PROGRESS:
3148 case GETOPT_VAL_HELP:
3151 return c != GETOPT_VAL_HELP;
3155 if (check_argc_exact(argc - optind, 1)) {
3160 if (rollback && (!datacsum || noxattr || !packing)) {
3162 "Usage error: -d, -i, -n options do not apply to rollback\n");
3171 file = argv[optind];
3172 ret = check_mounted(file);
3174 error("could not check mount status: %s", strerror(-ret));
3177 error("%s is mounted", file);
3182 ret = do_rollback(file);
3184 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3185 copylabel, fslabel, progress, features);