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"
43 #include <ext2fs/ext2_fs.h>
44 #include <ext2fs/ext2fs.h>
45 #include <ext2fs/ext2_ext_attr.h>
47 #define INO_OFFSET (BTRFS_FIRST_FREE_OBJECTID - EXT2_ROOT_INO)
50 * Compatibility code for e2fsprogs 1.41 which doesn't support RO compat flag
52 * Unlike normal RO compat flag, BIGALLOC affects how e2fsprogs check used
53 * space, and btrfs-convert heavily relies on it.
55 #ifdef HAVE_OLD_E2FSPROGS
56 #define EXT2FS_CLUSTER_RATIO(fs) (1)
57 #define EXT2_CLUSTERS_PER_GROUP(s) (EXT2_BLOCKS_PER_GROUP(s))
58 #define EXT2FS_B2C(fs, blk) (blk)
63 #define CONV_IMAGE_SUBVOL_OBJECTID BTRFS_FIRST_FREE_OBJECTID
66 uint32_t max_copy_inodes;
67 uint32_t cur_copy_inodes;
68 struct task_info *info;
71 static void *print_copied_inodes(void *p)
73 struct task_ctx *priv = p;
74 const char work_indicator[] = { '.', 'o', 'O', 'o' };
77 task_period_start(priv->info, 1000 /* 1s */);
80 printf("copy inodes [%c] [%10d/%10d]\r",
81 work_indicator[count % 4], priv->cur_copy_inodes,
82 priv->max_copy_inodes);
84 task_period_wait(priv->info);
90 static int after_copied_inodes(void *p)
98 struct btrfs_convert_context;
99 struct btrfs_convert_operations {
101 int (*open_fs)(struct btrfs_convert_context *cctx, const char *devname);
102 int (*read_used_space)(struct btrfs_convert_context *cctx);
103 int (*copy_inodes)(struct btrfs_convert_context *cctx,
104 struct btrfs_root *root, int datacsum,
105 int packing, int noxattr, struct task_ctx *p);
106 void (*close_fs)(struct btrfs_convert_context *cctx);
107 int (*check_state)(struct btrfs_convert_context *cctx);
110 static void init_convert_context(struct btrfs_convert_context *cctx)
112 cache_tree_init(&cctx->used);
113 cache_tree_init(&cctx->data_chunks);
114 cache_tree_init(&cctx->free);
117 static void clean_convert_context(struct btrfs_convert_context *cctx)
119 free_extent_cache_tree(&cctx->used);
120 free_extent_cache_tree(&cctx->data_chunks);
121 free_extent_cache_tree(&cctx->free);
124 static inline int copy_inodes(struct btrfs_convert_context *cctx,
125 struct btrfs_root *root, int datacsum,
126 int packing, int noxattr, struct task_ctx *p)
128 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
132 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
134 cctx->convert_ops->close_fs(cctx);
137 static inline int convert_check_state(struct btrfs_convert_context *cctx)
139 return cctx->convert_ops->check_state(cctx);
142 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
147 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
148 offset = btrfs_sb_offset(i);
149 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
151 if (bytenr < offset + BTRFS_STRIPE_LEN &&
152 bytenr + num_bytes > offset)
158 static int convert_insert_dirent(struct btrfs_trans_handle *trans,
159 struct btrfs_root *root,
160 const char *name, size_t name_len,
161 u64 dir, u64 objectid,
162 u8 file_type, u64 index_cnt,
163 struct btrfs_inode_item *inode)
167 struct btrfs_key location = {
168 .objectid = objectid,
170 .type = BTRFS_INODE_ITEM_KEY,
173 ret = btrfs_insert_dir_item(trans, root, name, name_len,
174 dir, &location, file_type, index_cnt);
177 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
178 objectid, dir, index_cnt);
181 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
182 btrfs_set_stack_inode_size(inode, inode_size);
187 static int read_disk_extent(struct btrfs_root *root, u64 bytenr,
188 u32 num_bytes, char *buffer)
191 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
193 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
194 if (ret != num_bytes)
203 static int csum_disk_extent(struct btrfs_trans_handle *trans,
204 struct btrfs_root *root,
205 u64 disk_bytenr, u64 num_bytes)
207 u32 blocksize = root->sectorsize;
212 buffer = malloc(blocksize);
215 for (offset = 0; offset < num_bytes; offset += blocksize) {
216 ret = read_disk_extent(root, disk_bytenr + offset,
220 ret = btrfs_csum_file_block(trans,
221 root->fs_info->csum_root,
222 disk_bytenr + num_bytes,
223 disk_bytenr + offset,
232 struct blk_iterate_data {
233 struct btrfs_trans_handle *trans;
234 struct btrfs_root *root;
235 struct btrfs_root *convert_root;
236 struct btrfs_inode_item *inode;
247 static void init_blk_iterate_data(struct blk_iterate_data *data,
248 struct btrfs_trans_handle *trans,
249 struct btrfs_root *root,
250 struct btrfs_inode_item *inode,
251 u64 objectid, int checksum)
253 struct btrfs_key key;
258 data->objectid = objectid;
259 data->first_block = 0;
260 data->disk_block = 0;
261 data->num_blocks = 0;
262 data->boundary = (u64)-1;
263 data->checksum = checksum;
266 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
267 key.type = BTRFS_ROOT_ITEM_KEY;
268 key.offset = (u64)-1;
269 data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
270 /* Impossible as we just opened it before */
271 BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
272 data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
276 * Record a file extent in original filesystem into btrfs one.
277 * The special point is, old disk_block can point to a reserved range.
278 * So here, we don't use disk_block directly but search convert_root
279 * to get the real disk_bytenr.
281 static int record_file_blocks(struct blk_iterate_data *data,
282 u64 file_block, u64 disk_block, u64 num_blocks)
285 struct btrfs_root *root = data->root;
286 struct btrfs_root *convert_root = data->convert_root;
287 struct btrfs_path path;
288 u64 file_pos = file_block * root->sectorsize;
289 u64 old_disk_bytenr = disk_block * root->sectorsize;
290 u64 num_bytes = num_blocks * root->sectorsize;
291 u64 cur_off = old_disk_bytenr;
293 /* Hole, pass it to record_file_extent directly */
294 if (old_disk_bytenr == 0)
295 return btrfs_record_file_extent(data->trans, root,
296 data->objectid, data->inode, file_pos, 0,
299 btrfs_init_path(&path);
302 * Search real disk bytenr from convert root
304 while (cur_off < old_disk_bytenr + num_bytes) {
305 struct btrfs_key key;
306 struct btrfs_file_extent_item *fi;
307 struct extent_buffer *node;
309 u64 extent_disk_bytenr;
310 u64 extent_num_bytes;
311 u64 real_disk_bytenr;
314 key.objectid = data->convert_ino;
315 key.type = BTRFS_EXTENT_DATA_KEY;
316 key.offset = cur_off;
318 ret = btrfs_search_slot(NULL, convert_root, &key, &path, 0, 0);
322 ret = btrfs_previous_item(convert_root, &path,
324 BTRFS_EXTENT_DATA_KEY);
332 node = path.nodes[0];
333 slot = path.slots[0];
334 btrfs_item_key_to_cpu(node, &key, slot);
335 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
336 key.objectid != data->convert_ino ||
337 key.offset > cur_off);
338 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
339 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
340 extent_num_bytes = btrfs_file_extent_num_bytes(node, fi);
341 BUG_ON(cur_off - key.offset >= extent_num_bytes);
342 btrfs_release_path(&path);
344 if (extent_disk_bytenr)
345 real_disk_bytenr = cur_off - key.offset +
348 real_disk_bytenr = 0;
349 cur_len = min(key.offset + extent_num_bytes,
350 old_disk_bytenr + num_bytes) - cur_off;
351 ret = btrfs_record_file_extent(data->trans, data->root,
352 data->objectid, data->inode, file_pos,
353 real_disk_bytenr, cur_len);
360 * No need to care about csum
361 * As every byte of old fs image is calculated for csum, no
362 * need to waste CPU cycles now.
365 btrfs_release_path(&path);
369 static int block_iterate_proc(u64 disk_block, u64 file_block,
370 struct blk_iterate_data *idata)
375 struct btrfs_root *root = idata->root;
376 struct btrfs_block_group_cache *cache;
377 u64 bytenr = disk_block * root->sectorsize;
379 sb_region = intersect_with_sb(bytenr, root->sectorsize);
380 do_barrier = sb_region || disk_block >= idata->boundary;
381 if ((idata->num_blocks > 0 && do_barrier) ||
382 (file_block > idata->first_block + idata->num_blocks) ||
383 (disk_block != idata->disk_block + idata->num_blocks)) {
384 if (idata->num_blocks > 0) {
385 ret = record_file_blocks(idata, idata->first_block,
390 idata->first_block += idata->num_blocks;
391 idata->num_blocks = 0;
393 if (file_block > idata->first_block) {
394 ret = record_file_blocks(idata, idata->first_block,
395 0, file_block - idata->first_block);
401 bytenr += BTRFS_STRIPE_LEN - 1;
402 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
404 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
406 bytenr = cache->key.objectid + cache->key.offset;
409 idata->first_block = file_block;
410 idata->disk_block = disk_block;
411 idata->boundary = bytenr / root->sectorsize;
418 static int create_image_file_range(struct btrfs_trans_handle *trans,
419 struct btrfs_root *root,
420 struct cache_tree *used,
421 struct btrfs_inode_item *inode,
422 u64 ino, u64 bytenr, u64 *ret_len,
425 struct cache_extent *cache;
426 struct btrfs_block_group_cache *bg_cache;
432 if (bytenr != round_down(bytenr, root->sectorsize)) {
433 error("bytenr not sectorsize aligned: %llu",
434 (unsigned long long)bytenr);
437 if (len != round_down(len, root->sectorsize)) {
438 error("length not sectorsize aligned: %llu",
439 (unsigned long long)len);
442 len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
445 * Skip sb ranges first
446 * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
448 * Or we will insert a hole into current image file, and later
449 * migrate block will fail as there is already a file extent.
451 if (bytenr < 1024 * 1024) {
452 *ret_len = 1024 * 1024 - bytenr;
455 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
456 u64 cur = btrfs_sb_offset(i);
458 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
459 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
463 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
464 u64 cur = btrfs_sb_offset(i);
469 * May still need to go through file extent inserts
471 if (bytenr < cur && bytenr + len >= cur) {
472 len = min_t(u64, len, cur - bytenr);
478 * Drop out, no need to insert anything
480 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
481 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
486 cache = search_cache_extent(used, bytenr);
488 if (cache->start <= bytenr) {
490 * |///////Used///////|
494 len = min_t(u64, len, cache->start + cache->size -
496 disk_bytenr = bytenr;
503 len = min(len, cache->start - bytenr);
518 /* Check if the range is in a data block group */
519 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
522 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
525 /* The extent should never cross block group boundary */
526 len = min_t(u64, len, bg_cache->key.objectid +
527 bg_cache->key.offset - bytenr);
530 if (len != round_down(len, root->sectorsize)) {
531 error("remaining length not sectorsize aligned: %llu",
532 (unsigned long long)len);
535 ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
541 ret = csum_disk_extent(trans, root, bytenr, len);
547 * Relocate old fs data in one reserved ranges
549 * Since all old fs data in reserved range is not covered by any chunk nor
550 * data extent, we don't need to handle any reference but add new
551 * extent/reference, which makes codes more clear
553 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
554 struct btrfs_root *root,
555 struct cache_tree *used,
556 struct btrfs_inode_item *inode, int fd,
557 u64 ino, u64 start, u64 len, int datacsum)
561 u64 hole_start = start;
563 struct cache_extent *cache;
564 struct btrfs_key key;
565 struct extent_buffer *eb;
568 while (cur_off < start + len) {
569 cache = lookup_cache_extent(used, cur_off, cur_len);
572 cur_off = max(cache->start, cur_off);
573 cur_len = min(cache->start + cache->size, start + len) -
575 BUG_ON(cur_len < root->sectorsize);
577 /* reserve extent for the data */
578 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
583 eb = malloc(sizeof(*eb) + cur_len);
589 ret = pread(fd, eb->data, cur_len, cur_off);
591 ret = (ret < 0 ? ret : -EIO);
595 eb->start = key.objectid;
596 eb->len = key.offset;
599 ret = write_and_map_eb(trans, root, eb);
604 /* Now handle extent item and file extent things */
605 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
606 key.objectid, key.offset);
609 /* Finally, insert csum items */
611 ret = csum_disk_extent(trans, root, key.objectid,
614 /* Don't forget to insert hole */
615 hole_len = cur_off - hole_start;
617 ret = btrfs_record_file_extent(trans, root, ino, inode,
618 hole_start, 0, hole_len);
623 cur_off += key.offset;
624 hole_start = cur_off;
625 cur_len = start + len - cur_off;
628 if (start + len - hole_start > 0)
629 ret = btrfs_record_file_extent(trans, root, ino, inode,
630 hole_start, 0, start + len - hole_start);
635 * Relocate the used ext2 data in reserved ranges
637 * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
638 * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
640 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
641 struct btrfs_root *root,
642 struct cache_tree *used,
643 struct btrfs_inode_item *inode, int fd,
644 u64 ino, u64 total_bytes, int datacsum)
652 cur_len = 1024 * 1024;
653 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
654 cur_off, cur_len, datacsum);
658 /* second sb(fisrt sb is included in 0~1M) */
659 cur_off = btrfs_sb_offset(1);
660 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
661 if (cur_off > total_bytes)
663 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
664 cur_off, cur_len, datacsum);
669 cur_off = btrfs_sb_offset(2);
670 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
671 if (cur_off > total_bytes)
673 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
674 cur_off, cur_len, datacsum);
679 * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
680 * handle wiping a range that exists in cache.
682 static int _expand_extent_cache(struct cache_tree *tree,
683 struct cache_extent *entry,
684 u64 min_stripe_size, int backward)
686 struct cache_extent *ce;
689 if (entry->size >= min_stripe_size)
691 diff = min_stripe_size - entry->size;
694 ce = prev_cache_extent(entry);
697 if (ce->start + ce->size >= entry->start - diff) {
698 /* Directly merge with previous extent */
699 ce->size = entry->start + entry->size - ce->start;
700 remove_cache_extent(tree, entry);
705 /* No overlap, normal extent */
706 if (entry->start < diff) {
707 error("cannot find space for data chunk layout");
710 entry->start -= diff;
714 ce = next_cache_extent(entry);
717 if (entry->start + entry->size + diff >= ce->start) {
718 /* Directly merge with next extent */
719 entry->size = ce->start + ce->size - entry->start;
720 remove_cache_extent(tree, ce);
730 * Remove one reserve range from given cache tree
731 * if min_stripe_size is non-zero, it will ensure for split case,
732 * all its split cache extent is no smaller than @min_strip_size / 2.
734 static int wipe_one_reserved_range(struct cache_tree *tree,
735 u64 start, u64 len, u64 min_stripe_size,
738 struct cache_extent *cache;
741 BUG_ON(ensure_size && min_stripe_size == 0);
743 * The logical here is simplified to handle special cases only
744 * So we don't need to consider merge case for ensure_size
746 BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
747 min_stripe_size / 2 < BTRFS_STRIPE_LEN));
749 /* Also, wipe range should already be aligned */
750 BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
751 start + len != round_up(start + len, BTRFS_STRIPE_LEN));
753 min_stripe_size /= 2;
755 cache = lookup_cache_extent(tree, start, len);
759 if (start <= cache->start) {
761 * |--------cache---------|
764 BUG_ON(start + len <= cache->start);
767 * The wipe size is smaller than min_stripe_size / 2,
768 * so the result length should still meet min_stripe_size
769 * And no need to do alignment
771 cache->size -= (start + len - cache->start);
772 if (cache->size == 0) {
773 remove_cache_extent(tree, cache);
778 BUG_ON(ensure_size && cache->size < min_stripe_size);
780 cache->start = start + len;
782 } else if (start > cache->start && start + len < cache->start +
785 * |-------cache-----|
788 u64 old_start = cache->start;
789 u64 old_len = cache->size;
790 u64 insert_start = start + len;
793 cache->size = start - cache->start;
794 /* Expand the leading half part if needed */
795 if (ensure_size && cache->size < min_stripe_size) {
796 ret = _expand_extent_cache(tree, cache,
802 /* And insert the new one */
803 insert_len = old_start + old_len - start - len;
804 ret = add_merge_cache_extent(tree, insert_start, insert_len);
808 /* Expand the last half part if needed */
809 if (ensure_size && insert_len < min_stripe_size) {
810 cache = lookup_cache_extent(tree, insert_start,
812 if (!cache || cache->start != insert_start ||
813 cache->size != insert_len)
815 ret = _expand_extent_cache(tree, cache,
824 * Wipe len should be small enough and no need to expand the
827 cache->size = start - cache->start;
828 BUG_ON(ensure_size && cache->size < min_stripe_size);
833 * Remove reserved ranges from given cache_tree
835 * It will remove the following ranges
837 * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
838 * 3) 3rd superblock, +64K
840 * @min_stripe must be given for safety check
841 * and if @ensure_size is given, it will ensure affected cache_extent will be
842 * larger than min_stripe_size
844 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
849 ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
853 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
854 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
857 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
858 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
862 static int calculate_available_space(struct btrfs_convert_context *cctx)
864 struct cache_tree *used = &cctx->used;
865 struct cache_tree *data_chunks = &cctx->data_chunks;
866 struct cache_tree *free = &cctx->free;
867 struct cache_extent *cache;
870 * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
871 * works without need to consider overlap
873 u64 min_stripe_size = 2 * 16 * 1024 * 1024;
876 /* Calculate data_chunks */
877 for (cache = first_cache_extent(used); cache;
878 cache = next_cache_extent(cache)) {
881 if (cache->start + cache->size < cur_off)
883 if (cache->start > cur_off + min_stripe_size)
884 cur_off = cache->start;
885 cur_len = max(cache->start + cache->size - cur_off,
887 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
893 * remove reserved ranges, so we won't ever bother relocating an old
894 * filesystem extent to other place.
896 ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
902 * Calculate free space
903 * Always round up the start bytenr, to avoid metadata extent corss
904 * stripe boundary, as later mkfs_convert() won't have all the extent
907 for (cache = first_cache_extent(data_chunks); cache;
908 cache = next_cache_extent(cache)) {
909 if (cache->start < cur_off)
911 if (cache->start > cur_off) {
915 len = cache->start - round_up(cur_off,
917 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
919 ret = add_merge_cache_extent(free, insert_start, len);
923 cur_off = cache->start + cache->size;
925 /* Don't forget the last range */
926 if (cctx->total_bytes > cur_off) {
927 u64 len = cctx->total_bytes - cur_off;
930 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
932 ret = add_merge_cache_extent(free, insert_start, len);
937 /* Remove reserved bytes */
938 ret = wipe_reserved_ranges(free, min_stripe_size, 0);
944 * Read used space, and since we have the used space,
945 * calcuate data_chunks and free for later mkfs
947 static int convert_read_used_space(struct btrfs_convert_context *cctx)
951 ret = cctx->convert_ops->read_used_space(cctx);
955 ret = calculate_available_space(cctx);
960 * Create the fs image file of old filesystem.
962 * This is completely fs independent as we have cctx->used, only
963 * need to create file extents pointing to all the positions.
965 static int create_image(struct btrfs_root *root,
966 struct btrfs_mkfs_config *cfg,
967 struct btrfs_convert_context *cctx, int fd,
968 u64 size, char *name, int datacsum)
970 struct btrfs_inode_item buf;
971 struct btrfs_trans_handle *trans;
972 struct btrfs_path path;
973 struct btrfs_key key;
974 struct cache_extent *cache;
975 struct cache_tree used_tmp;
978 u64 flags = BTRFS_INODE_READONLY;
982 flags |= BTRFS_INODE_NODATASUM;
984 trans = btrfs_start_transaction(root, 1);
988 cache_tree_init(&used_tmp);
989 btrfs_init_path(&path);
991 ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
995 ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
998 ret = btrfs_change_inode_flags(trans, root, ino, flags);
1001 ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
1002 strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
1007 key.type = BTRFS_INODE_ITEM_KEY;
1010 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1012 ret = (ret > 0 ? -ENOENT : ret);
1015 read_extent_buffer(path.nodes[0], &buf,
1016 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1018 btrfs_release_path(&path);
1021 * Create a new used space cache, which doesn't contain the reserved
1024 for (cache = first_cache_extent(&cctx->used); cache;
1025 cache = next_cache_extent(cache)) {
1026 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
1030 ret = wipe_reserved_ranges(&used_tmp, 0, 0);
1035 * Start from 1M, as 0~1M is reserved, and create_image_file_range()
1036 * can't handle bytenr 0(will consider it as a hole)
1039 while (cur < size) {
1040 u64 len = size - cur;
1042 ret = create_image_file_range(trans, root, &used_tmp,
1043 &buf, ino, cur, &len, datacsum);
1048 /* Handle the reserved ranges */
1049 ret = migrate_reserved_ranges(trans, root, &cctx->used, &buf, fd, ino,
1050 cfg->num_bytes, datacsum);
1054 key.type = BTRFS_INODE_ITEM_KEY;
1056 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1058 ret = (ret > 0 ? -ENOENT : ret);
1061 btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1062 write_extent_buffer(path.nodes[0], &buf,
1063 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1066 free_extent_cache_tree(&used_tmp);
1067 btrfs_release_path(&path);
1068 btrfs_commit_transaction(trans, root);
1072 static struct btrfs_root* link_subvol(struct btrfs_root *root,
1073 const char *base, u64 root_objectid)
1075 struct btrfs_trans_handle *trans;
1076 struct btrfs_fs_info *fs_info = root->fs_info;
1077 struct btrfs_root *tree_root = fs_info->tree_root;
1078 struct btrfs_root *new_root = NULL;
1079 struct btrfs_path path;
1080 struct btrfs_inode_item *inode_item;
1081 struct extent_buffer *leaf;
1082 struct btrfs_key key;
1083 u64 dirid = btrfs_root_dirid(&root->root_item);
1085 char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1091 if (len == 0 || len > BTRFS_NAME_LEN)
1094 btrfs_init_path(&path);
1095 key.objectid = dirid;
1096 key.type = BTRFS_DIR_INDEX_KEY;
1097 key.offset = (u64)-1;
1099 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1101 error("search for DIR_INDEX dirid %llu failed: %d",
1102 (unsigned long long)dirid, ret);
1106 if (path.slots[0] > 0) {
1108 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1109 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1110 index = key.offset + 1;
1112 btrfs_release_path(&path);
1114 trans = btrfs_start_transaction(root, 1);
1116 error("unable to start transaction");
1120 key.objectid = dirid;
1122 key.type = BTRFS_INODE_ITEM_KEY;
1124 ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
1126 error("search for INODE_ITEM %llu failed: %d",
1127 (unsigned long long)dirid, ret);
1130 leaf = path.nodes[0];
1131 inode_item = btrfs_item_ptr(leaf, path.slots[0],
1132 struct btrfs_inode_item);
1134 key.objectid = root_objectid;
1135 key.offset = (u64)-1;
1136 key.type = BTRFS_ROOT_ITEM_KEY;
1138 memcpy(buf, base, len);
1139 for (i = 0; i < 1024; i++) {
1140 ret = btrfs_insert_dir_item(trans, root, buf, len,
1141 dirid, &key, BTRFS_FT_DIR, index);
1144 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1145 if (len < 1 || len > BTRFS_NAME_LEN) {
1153 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1154 btrfs_inode_size(leaf, inode_item));
1155 btrfs_mark_buffer_dirty(leaf);
1156 btrfs_release_path(&path);
1158 /* add the backref first */
1159 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1160 BTRFS_ROOT_BACKREF_KEY,
1161 root->root_key.objectid,
1162 dirid, index, buf, len);
1164 error("unable to add root backref for %llu: %d",
1165 root->root_key.objectid, ret);
1169 /* now add the forward ref */
1170 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1171 BTRFS_ROOT_REF_KEY, root_objectid,
1172 dirid, index, buf, len);
1174 error("unable to add root ref for %llu: %d",
1175 root->root_key.objectid, ret);
1179 ret = btrfs_commit_transaction(trans, root);
1181 error("transaction commit failed: %d", ret);
1185 new_root = btrfs_read_fs_root(fs_info, &key);
1186 if (IS_ERR(new_root)) {
1187 error("unable to fs read root: %lu", PTR_ERR(new_root));
1191 btrfs_init_path(&path);
1195 static int create_subvol(struct btrfs_trans_handle *trans,
1196 struct btrfs_root *root, u64 root_objectid)
1198 struct extent_buffer *tmp;
1199 struct btrfs_root *new_root;
1200 struct btrfs_key key;
1201 struct btrfs_root_item root_item;
1204 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1209 memcpy(&root_item, &root->root_item, sizeof(root_item));
1210 btrfs_set_root_bytenr(&root_item, tmp->start);
1211 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1212 btrfs_set_root_generation(&root_item, trans->transid);
1213 free_extent_buffer(tmp);
1215 key.objectid = root_objectid;
1216 key.type = BTRFS_ROOT_ITEM_KEY;
1217 key.offset = trans->transid;
1218 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1221 key.offset = (u64)-1;
1222 new_root = btrfs_read_fs_root(root->fs_info, &key);
1223 if (!new_root || IS_ERR(new_root)) {
1224 error("unable to fs read root: %lu", PTR_ERR(new_root));
1225 return PTR_ERR(new_root);
1228 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1234 * New make_btrfs() has handle system and meta chunks quite well.
1235 * So only need to add remaining data chunks.
1237 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1238 struct btrfs_fs_info *fs_info,
1239 struct btrfs_mkfs_config *cfg,
1240 struct btrfs_convert_context *cctx)
1242 struct btrfs_root *extent_root = fs_info->extent_root;
1243 struct cache_tree *data_chunks = &cctx->data_chunks;
1244 struct cache_extent *cache;
1249 * Don't create data chunk over 10% of the convert device
1250 * And for single chunk, don't create chunk larger than 1G.
1252 max_chunk_size = cfg->num_bytes / 10;
1253 max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1254 max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1256 for (cache = first_cache_extent(data_chunks); cache;
1257 cache = next_cache_extent(cache)) {
1258 u64 cur = cache->start;
1260 while (cur < cache->start + cache->size) {
1262 u64 cur_backup = cur;
1264 len = min(max_chunk_size,
1265 cache->start + cache->size - cur);
1266 ret = btrfs_alloc_data_chunk(trans, extent_root,
1268 BTRFS_BLOCK_GROUP_DATA, 1);
1271 ret = btrfs_make_block_group(trans, extent_root, 0,
1272 BTRFS_BLOCK_GROUP_DATA,
1273 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1284 * Init the temp btrfs to a operational status.
1286 * It will fix the extent usage accounting(XXX: Do we really need?) and
1287 * insert needed data chunks, to ensure all old fs data extents are covered
1288 * by DATA chunks, preventing wrong chunks are allocated.
1290 * And also create convert image subvolume and relocation tree.
1291 * (XXX: Not need again?)
1292 * But the convert image subvolume is *NOT* linked to fs tree yet.
1294 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1295 struct btrfs_convert_context *cctx, int datacsum,
1296 int packing, int noxattr)
1298 struct btrfs_key location;
1299 struct btrfs_trans_handle *trans;
1300 struct btrfs_fs_info *fs_info = root->fs_info;
1304 * Don't alloc any metadata/system chunk, as we don't want
1305 * any meta/sys chunk allcated before all data chunks are inserted.
1306 * Or we screw up the chunk layout just like the old implement.
1308 fs_info->avoid_sys_chunk_alloc = 1;
1309 fs_info->avoid_meta_chunk_alloc = 1;
1310 trans = btrfs_start_transaction(root, 1);
1312 error("unable to start transaction");
1316 ret = btrfs_fix_block_accounting(trans, root);
1319 ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1322 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1323 BTRFS_ROOT_TREE_DIR_OBJECTID);
1326 memcpy(&location, &root->root_key, sizeof(location));
1327 location.offset = (u64)-1;
1328 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1329 btrfs_super_root_dir(fs_info->super_copy),
1330 &location, BTRFS_FT_DIR, 0);
1333 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1335 btrfs_super_root_dir(fs_info->super_copy), 0);
1338 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1339 BTRFS_FIRST_FREE_OBJECTID);
1341 /* subvol for fs image file */
1342 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1344 error("failed to create subvolume image root: %d", ret);
1347 /* subvol for data relocation tree */
1348 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1350 error("failed to create DATA_RELOC root: %d", ret);
1354 ret = btrfs_commit_transaction(trans, root);
1355 fs_info->avoid_sys_chunk_alloc = 0;
1356 fs_info->avoid_meta_chunk_alloc = 0;
1362 * Migrate super block to its default position and zero 0 ~ 16k
1364 static int migrate_super_block(int fd, u64 old_bytenr)
1367 struct extent_buffer *buf;
1368 struct btrfs_super_block *super;
1372 buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1376 buf->len = BTRFS_SUPER_INFO_SIZE;
1377 ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1378 if (ret != BTRFS_SUPER_INFO_SIZE)
1381 super = (struct btrfs_super_block *)buf->data;
1382 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1383 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1385 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1386 ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1387 BTRFS_SUPER_INFO_OFFSET);
1388 if (ret != BTRFS_SUPER_INFO_SIZE)
1395 memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1396 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1397 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1398 if (len > BTRFS_SUPER_INFO_SIZE)
1399 len = BTRFS_SUPER_INFO_SIZE;
1400 ret = pwrite(fd, buf->data, len, bytenr);
1402 fprintf(stderr, "unable to zero fill device\n");
1416 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1418 struct btrfs_chunk *chunk;
1419 struct btrfs_disk_key *key;
1420 u32 sectorsize = btrfs_super_sectorsize(super);
1422 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1423 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1424 sizeof(struct btrfs_disk_key));
1426 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1427 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1428 btrfs_set_disk_key_offset(key, 0);
1430 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1431 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1432 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1433 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1434 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1435 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1436 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1437 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1438 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1439 chunk->stripe.devid = super->dev_item.devid;
1440 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1441 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1442 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1446 #if BTRFSCONVERT_EXT2
1449 * Open Ext2fs in readonly mode, read block allocation bitmap and
1450 * inode bitmap into memory.
1452 static int ext2_open_fs(struct btrfs_convert_context *cctx, const char *name)
1455 ext2_filsys ext2_fs;
1459 ret = ext2fs_open(name, 0, 0, 0, unix_io_manager, &ext2_fs);
1461 fprintf(stderr, "ext2fs_open: %s\n", error_message(ret));
1465 * We need to know exactly the used space, some RO compat flags like
1466 * BIGALLOC will affect how used space is present.
1467 * So we need manuall check any unsupported RO compat flags
1469 ro_feature = ext2_fs->super->s_feature_ro_compat;
1470 if (ro_feature & ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP) {
1472 "unsupported RO features detected: %x, abort convert to avoid possible corruption",
1473 ro_feature & ~EXT2_LIB_FEATURE_COMPAT_SUPP);
1476 ret = ext2fs_read_inode_bitmap(ext2_fs);
1478 fprintf(stderr, "ext2fs_read_inode_bitmap: %s\n",
1479 error_message(ret));
1482 ret = ext2fs_read_block_bitmap(ext2_fs);
1484 fprintf(stderr, "ext2fs_read_block_bitmap: %s\n",
1485 error_message(ret));
1489 * search each block group for a free inode. this set up
1490 * uninit block/inode bitmaps appropriately.
1493 while (ino <= ext2_fs->super->s_inodes_count) {
1495 ext2fs_new_inode(ext2_fs, ino, 0, NULL, &foo);
1496 ino += EXT2_INODES_PER_GROUP(ext2_fs->super);
1499 if (!(ext2_fs->super->s_feature_incompat &
1500 EXT2_FEATURE_INCOMPAT_FILETYPE)) {
1501 error("filetype feature is missing");
1505 cctx->fs_data = ext2_fs;
1506 cctx->blocksize = ext2_fs->blocksize;
1507 cctx->block_count = ext2_fs->super->s_blocks_count;
1508 cctx->total_bytes = ext2_fs->blocksize * ext2_fs->super->s_blocks_count;
1509 cctx->volume_name = strndup(ext2_fs->super->s_volume_name, 16);
1510 cctx->first_data_block = ext2_fs->super->s_first_data_block;
1511 cctx->inodes_count = ext2_fs->super->s_inodes_count;
1512 cctx->free_inodes_count = ext2_fs->super->s_free_inodes_count;
1515 ext2fs_close(ext2_fs);
1519 static int __ext2_add_one_block(ext2_filsys fs, char *bitmap,
1520 unsigned long group_nr, struct cache_tree *used)
1522 unsigned long offset;
1526 offset = fs->super->s_first_data_block;
1527 offset /= EXT2FS_CLUSTER_RATIO(fs);
1528 offset += group_nr * EXT2_CLUSTERS_PER_GROUP(fs->super);
1529 for (i = 0; i < EXT2_CLUSTERS_PER_GROUP(fs->super); i++) {
1530 if ((i + offset) >= ext2fs_blocks_count(fs->super))
1533 if (ext2fs_test_bit(i, bitmap)) {
1536 start = (i + offset) * EXT2FS_CLUSTER_RATIO(fs);
1537 start *= fs->blocksize;
1538 ret = add_merge_cache_extent(used, start,
1548 * Read all used ext2 space into cctx->used cache tree
1550 static int ext2_read_used_space(struct btrfs_convert_context *cctx)
1552 ext2_filsys fs = (ext2_filsys)cctx->fs_data;
1553 blk64_t blk_itr = EXT2FS_B2C(fs, fs->super->s_first_data_block);
1554 struct cache_tree *used_tree = &cctx->used;
1555 char *block_bitmap = NULL;
1560 block_nbytes = EXT2_CLUSTERS_PER_GROUP(fs->super) / 8;
1561 /* Shouldn't happen */
1562 BUG_ON(!fs->block_map);
1564 block_bitmap = malloc(block_nbytes);
1568 for (i = 0; i < fs->group_desc_count; i++) {
1569 ret = ext2fs_get_block_bitmap_range(fs->block_map, blk_itr,
1570 block_nbytes * 8, block_bitmap);
1572 error("fail to get bitmap from ext2, %s",
1576 ret = __ext2_add_one_block(fs, block_bitmap, i, used_tree);
1578 error("fail to build used space tree, %s",
1582 blk_itr += EXT2_CLUSTERS_PER_GROUP(fs->super);
1589 static void ext2_close_fs(struct btrfs_convert_context *cctx)
1591 if (cctx->volume_name) {
1592 free(cctx->volume_name);
1593 cctx->volume_name = NULL;
1595 ext2fs_close(cctx->fs_data);
1598 struct dir_iterate_data {
1599 struct btrfs_trans_handle *trans;
1600 struct btrfs_root *root;
1601 struct btrfs_inode_item *inode;
1608 static u8 ext2_filetype_conversion_table[EXT2_FT_MAX] = {
1609 [EXT2_FT_UNKNOWN] = BTRFS_FT_UNKNOWN,
1610 [EXT2_FT_REG_FILE] = BTRFS_FT_REG_FILE,
1611 [EXT2_FT_DIR] = BTRFS_FT_DIR,
1612 [EXT2_FT_CHRDEV] = BTRFS_FT_CHRDEV,
1613 [EXT2_FT_BLKDEV] = BTRFS_FT_BLKDEV,
1614 [EXT2_FT_FIFO] = BTRFS_FT_FIFO,
1615 [EXT2_FT_SOCK] = BTRFS_FT_SOCK,
1616 [EXT2_FT_SYMLINK] = BTRFS_FT_SYMLINK,
1619 static int ext2_dir_iterate_proc(ext2_ino_t dir, int entry,
1620 struct ext2_dir_entry *dirent,
1621 int offset, int blocksize,
1622 char *buf,void *priv_data)
1627 char dotdot[] = "..";
1628 struct dir_iterate_data *idata = (struct dir_iterate_data *)priv_data;
1631 name_len = dirent->name_len & 0xFF;
1633 objectid = dirent->inode + INO_OFFSET;
1634 if (!strncmp(dirent->name, dotdot, name_len)) {
1635 if (name_len == 2) {
1636 BUG_ON(idata->parent != 0);
1637 idata->parent = objectid;
1641 if (dirent->inode < EXT2_GOOD_OLD_FIRST_INO)
1644 file_type = dirent->name_len >> 8;
1645 BUG_ON(file_type > EXT2_FT_SYMLINK);
1647 ret = convert_insert_dirent(idata->trans, idata->root, dirent->name,
1648 name_len, idata->objectid, objectid,
1649 ext2_filetype_conversion_table[file_type],
1650 idata->index_cnt, idata->inode);
1652 idata->errcode = ret;
1660 static int ext2_create_dir_entries(struct btrfs_trans_handle *trans,
1661 struct btrfs_root *root, u64 objectid,
1662 struct btrfs_inode_item *btrfs_inode,
1663 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
1667 struct dir_iterate_data data = {
1670 .inode = btrfs_inode,
1671 .objectid = objectid,
1677 err = ext2fs_dir_iterate2(ext2_fs, ext2_ino, 0, NULL,
1678 ext2_dir_iterate_proc, &data);
1682 if (ret == 0 && data.parent == objectid) {
1683 ret = btrfs_insert_inode_ref(trans, root, "..", 2,
1684 objectid, objectid, 0);
1688 fprintf(stderr, "ext2fs_dir_iterate2: %s\n", error_message(err));
1692 static int ext2_block_iterate_proc(ext2_filsys fs, blk_t *blocknr,
1693 e2_blkcnt_t blockcnt, blk_t ref_block,
1694 int ref_offset, void *priv_data)
1697 struct blk_iterate_data *idata;
1698 idata = (struct blk_iterate_data *)priv_data;
1699 ret = block_iterate_proc(*blocknr, blockcnt, idata);
1701 idata->errcode = ret;
1708 * traverse file's data blocks, record these data blocks as file extents.
1710 static int ext2_create_file_extents(struct btrfs_trans_handle *trans,
1711 struct btrfs_root *root, u64 objectid,
1712 struct btrfs_inode_item *btrfs_inode,
1713 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1714 int datacsum, int packing)
1717 char *buffer = NULL;
1720 u32 sectorsize = root->sectorsize;
1721 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1722 struct blk_iterate_data data;
1724 init_blk_iterate_data(&data, trans, root, btrfs_inode, objectid,
1727 err = ext2fs_block_iterate2(ext2_fs, ext2_ino, BLOCK_FLAG_DATA_ONLY,
1728 NULL, ext2_block_iterate_proc, &data);
1734 if (packing && data.first_block == 0 && data.num_blocks > 0 &&
1735 inode_size <= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
1736 u64 num_bytes = data.num_blocks * sectorsize;
1737 u64 disk_bytenr = data.disk_block * sectorsize;
1740 buffer = malloc(num_bytes);
1743 ret = read_disk_extent(root, disk_bytenr, num_bytes, buffer);
1746 if (num_bytes > inode_size)
1747 num_bytes = inode_size;
1748 ret = btrfs_insert_inline_extent(trans, root, objectid,
1749 0, buffer, num_bytes);
1752 nbytes = btrfs_stack_inode_nbytes(btrfs_inode) + num_bytes;
1753 btrfs_set_stack_inode_nbytes(btrfs_inode, nbytes);
1754 } else if (data.num_blocks > 0) {
1755 ret = record_file_blocks(&data, data.first_block,
1756 data.disk_block, data.num_blocks);
1760 data.first_block += data.num_blocks;
1761 last_block = (inode_size + sectorsize - 1) / sectorsize;
1762 if (last_block > data.first_block) {
1763 ret = record_file_blocks(&data, data.first_block, 0,
1764 last_block - data.first_block);
1770 fprintf(stderr, "ext2fs_block_iterate2: %s\n", error_message(err));
1774 static int ext2_create_symbol_link(struct btrfs_trans_handle *trans,
1775 struct btrfs_root *root, u64 objectid,
1776 struct btrfs_inode_item *btrfs_inode,
1777 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
1778 struct ext2_inode *ext2_inode)
1782 u64 inode_size = btrfs_stack_inode_size(btrfs_inode);
1783 if (ext2fs_inode_data_blocks(ext2_fs, ext2_inode)) {
1784 btrfs_set_stack_inode_size(btrfs_inode, inode_size + 1);
1785 ret = ext2_create_file_extents(trans, root, objectid,
1786 btrfs_inode, ext2_fs, ext2_ino, 1, 1);
1787 btrfs_set_stack_inode_size(btrfs_inode, inode_size);
1791 pathname = (char *)&(ext2_inode->i_block[0]);
1792 BUG_ON(pathname[inode_size] != 0);
1793 ret = btrfs_insert_inline_extent(trans, root, objectid, 0,
1794 pathname, inode_size + 1);
1795 btrfs_set_stack_inode_nbytes(btrfs_inode, inode_size + 1);
1800 * Following xattr/acl related codes are based on codes in
1801 * fs/ext3/xattr.c and fs/ext3/acl.c
1803 #define EXT2_XATTR_BHDR(ptr) ((struct ext2_ext_attr_header *)(ptr))
1804 #define EXT2_XATTR_BFIRST(ptr) \
1805 ((struct ext2_ext_attr_entry *)(EXT2_XATTR_BHDR(ptr) + 1))
1806 #define EXT2_XATTR_IHDR(inode) \
1807 ((struct ext2_ext_attr_header *) ((void *)(inode) + \
1808 EXT2_GOOD_OLD_INODE_SIZE + (inode)->i_extra_isize))
1809 #define EXT2_XATTR_IFIRST(inode) \
1810 ((struct ext2_ext_attr_entry *) ((void *)EXT2_XATTR_IHDR(inode) + \
1811 sizeof(EXT2_XATTR_IHDR(inode)->h_magic)))
1813 static int ext2_xattr_check_names(struct ext2_ext_attr_entry *entry,
1816 struct ext2_ext_attr_entry *next;
1818 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
1819 next = EXT2_EXT_ATTR_NEXT(entry);
1820 if ((void *)next >= end)
1827 static int ext2_xattr_check_block(const char *buf, size_t size)
1830 struct ext2_ext_attr_header *header = EXT2_XATTR_BHDR(buf);
1832 if (header->h_magic != EXT2_EXT_ATTR_MAGIC ||
1833 header->h_blocks != 1)
1835 error = ext2_xattr_check_names(EXT2_XATTR_BFIRST(buf), buf + size);
1839 static int ext2_xattr_check_entry(struct ext2_ext_attr_entry *entry,
1842 size_t value_size = entry->e_value_size;
1844 if (entry->e_value_block != 0 || value_size > size ||
1845 entry->e_value_offs + value_size > size)
1850 #define EXT2_ACL_VERSION 0x0001
1852 /* 23.2.5 acl_tag_t values */
1854 #define ACL_UNDEFINED_TAG (0x00)
1855 #define ACL_USER_OBJ (0x01)
1856 #define ACL_USER (0x02)
1857 #define ACL_GROUP_OBJ (0x04)
1858 #define ACL_GROUP (0x08)
1859 #define ACL_MASK (0x10)
1860 #define ACL_OTHER (0x20)
1862 /* 23.2.7 ACL qualifier constants */
1864 #define ACL_UNDEFINED_ID ((id_t)-1)
1875 } ext2_acl_entry_short;
1881 static inline int ext2_acl_count(size_t size)
1884 size -= sizeof(ext2_acl_header);
1885 s = size - 4 * sizeof(ext2_acl_entry_short);
1887 if (size % sizeof(ext2_acl_entry_short))
1889 return size / sizeof(ext2_acl_entry_short);
1891 if (s % sizeof(ext2_acl_entry))
1893 return s / sizeof(ext2_acl_entry) + 4;
1897 #define ACL_EA_VERSION 0x0002
1907 acl_ea_entry a_entries[0];
1910 static inline size_t acl_ea_size(int count)
1912 return sizeof(acl_ea_header) + count * sizeof(acl_ea_entry);
1915 static int ext2_acl_to_xattr(void *dst, const void *src,
1916 size_t dst_size, size_t src_size)
1919 const void *end = src + src_size;
1920 acl_ea_header *ext_acl = (acl_ea_header *)dst;
1921 acl_ea_entry *dst_entry = ext_acl->a_entries;
1922 ext2_acl_entry *src_entry;
1924 if (src_size < sizeof(ext2_acl_header))
1926 if (((ext2_acl_header *)src)->a_version !=
1927 cpu_to_le32(EXT2_ACL_VERSION))
1929 src += sizeof(ext2_acl_header);
1930 count = ext2_acl_count(src_size);
1934 BUG_ON(dst_size < acl_ea_size(count));
1935 ext_acl->a_version = cpu_to_le32(ACL_EA_VERSION);
1936 for (i = 0; i < count; i++, dst_entry++) {
1937 src_entry = (ext2_acl_entry *)src;
1938 if (src + sizeof(ext2_acl_entry_short) > end)
1940 dst_entry->e_tag = src_entry->e_tag;
1941 dst_entry->e_perm = src_entry->e_perm;
1942 switch (le16_to_cpu(src_entry->e_tag)) {
1947 src += sizeof(ext2_acl_entry_short);
1948 dst_entry->e_id = cpu_to_le32(ACL_UNDEFINED_ID);
1952 src += sizeof(ext2_acl_entry);
1955 dst_entry->e_id = src_entry->e_id;
1968 static char *xattr_prefix_table[] = {
1970 [2] = "system.posix_acl_access",
1971 [3] = "system.posix_acl_default",
1976 static int ext2_copy_single_xattr(struct btrfs_trans_handle *trans,
1977 struct btrfs_root *root, u64 objectid,
1978 struct ext2_ext_attr_entry *entry,
1979 const void *data, u32 datalen)
1984 void *databuf = NULL;
1985 char namebuf[XATTR_NAME_MAX + 1];
1987 name_index = entry->e_name_index;
1988 if (name_index >= ARRAY_SIZE(xattr_prefix_table) ||
1989 xattr_prefix_table[name_index] == NULL)
1991 name_len = strlen(xattr_prefix_table[name_index]) +
1993 if (name_len >= sizeof(namebuf))
1996 if (name_index == 2 || name_index == 3) {
1997 size_t bufsize = acl_ea_size(ext2_acl_count(datalen));
1998 databuf = malloc(bufsize);
2001 ret = ext2_acl_to_xattr(databuf, data, bufsize, datalen);
2007 strncpy(namebuf, xattr_prefix_table[name_index], XATTR_NAME_MAX);
2008 strncat(namebuf, EXT2_EXT_ATTR_NAME(entry), entry->e_name_len);
2009 if (name_len + datalen > BTRFS_LEAF_DATA_SIZE(root) -
2010 sizeof(struct btrfs_item) - sizeof(struct btrfs_dir_item)) {
2011 fprintf(stderr, "skip large xattr on inode %Lu name %.*s\n",
2012 objectid - INO_OFFSET, name_len, namebuf);
2015 ret = btrfs_insert_xattr_item(trans, root, namebuf, name_len,
2016 data, datalen, objectid);
2022 static int ext2_copy_extended_attrs(struct btrfs_trans_handle *trans,
2023 struct btrfs_root *root, u64 objectid,
2024 struct btrfs_inode_item *btrfs_inode,
2025 ext2_filsys ext2_fs, ext2_ino_t ext2_ino)
2031 u32 block_size = ext2_fs->blocksize;
2032 u32 inode_size = EXT2_INODE_SIZE(ext2_fs->super);
2033 struct ext2_inode_large *ext2_inode;
2034 struct ext2_ext_attr_entry *entry;
2036 char *buffer = NULL;
2037 char inode_buf[EXT2_GOOD_OLD_INODE_SIZE];
2039 if (inode_size <= EXT2_GOOD_OLD_INODE_SIZE) {
2040 ext2_inode = (struct ext2_inode_large *)inode_buf;
2042 ext2_inode = (struct ext2_inode_large *)malloc(inode_size);
2046 err = ext2fs_read_inode_full(ext2_fs, ext2_ino, (void *)ext2_inode,
2049 fprintf(stderr, "ext2fs_read_inode_full: %s\n",
2050 error_message(err));
2055 if (ext2_ino > ext2_fs->super->s_first_ino &&
2056 inode_size > EXT2_GOOD_OLD_INODE_SIZE) {
2057 if (EXT2_GOOD_OLD_INODE_SIZE +
2058 ext2_inode->i_extra_isize > inode_size) {
2062 if (ext2_inode->i_extra_isize != 0 &&
2063 EXT2_XATTR_IHDR(ext2_inode)->h_magic ==
2064 EXT2_EXT_ATTR_MAGIC) {
2070 void *end = (void *)ext2_inode + inode_size;
2071 entry = EXT2_XATTR_IFIRST(ext2_inode);
2072 total = end - (void *)entry;
2073 ret = ext2_xattr_check_names(entry, end);
2076 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2077 ret = ext2_xattr_check_entry(entry, total);
2080 data = (void *)EXT2_XATTR_IFIRST(ext2_inode) +
2081 entry->e_value_offs;
2082 datalen = entry->e_value_size;
2083 ret = ext2_copy_single_xattr(trans, root, objectid,
2084 entry, data, datalen);
2087 entry = EXT2_EXT_ATTR_NEXT(entry);
2091 if (ext2_inode->i_file_acl == 0)
2094 buffer = malloc(block_size);
2099 err = ext2fs_read_ext_attr(ext2_fs, ext2_inode->i_file_acl, buffer);
2101 fprintf(stderr, "ext2fs_read_ext_attr: %s\n",
2102 error_message(err));
2106 ret = ext2_xattr_check_block(buffer, block_size);
2110 entry = EXT2_XATTR_BFIRST(buffer);
2111 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
2112 ret = ext2_xattr_check_entry(entry, block_size);
2115 data = buffer + entry->e_value_offs;
2116 datalen = entry->e_value_size;
2117 ret = ext2_copy_single_xattr(trans, root, objectid,
2118 entry, data, datalen);
2121 entry = EXT2_EXT_ATTR_NEXT(entry);
2125 if ((void *)ext2_inode != inode_buf)
2129 #define MINORBITS 20
2130 #define MKDEV(ma, mi) (((ma) << MINORBITS) | (mi))
2132 static inline dev_t old_decode_dev(u16 val)
2134 return MKDEV((val >> 8) & 255, val & 255);
2137 static inline dev_t new_decode_dev(u32 dev)
2139 unsigned major = (dev & 0xfff00) >> 8;
2140 unsigned minor = (dev & 0xff) | ((dev >> 12) & 0xfff00);
2141 return MKDEV(major, minor);
2144 static void ext2_copy_inode_item(struct btrfs_inode_item *dst,
2145 struct ext2_inode *src, u32 blocksize)
2147 btrfs_set_stack_inode_generation(dst, 1);
2148 btrfs_set_stack_inode_sequence(dst, 0);
2149 btrfs_set_stack_inode_transid(dst, 1);
2150 btrfs_set_stack_inode_size(dst, src->i_size);
2151 btrfs_set_stack_inode_nbytes(dst, 0);
2152 btrfs_set_stack_inode_block_group(dst, 0);
2153 btrfs_set_stack_inode_nlink(dst, src->i_links_count);
2154 btrfs_set_stack_inode_uid(dst, src->i_uid | (src->i_uid_high << 16));
2155 btrfs_set_stack_inode_gid(dst, src->i_gid | (src->i_gid_high << 16));
2156 btrfs_set_stack_inode_mode(dst, src->i_mode);
2157 btrfs_set_stack_inode_rdev(dst, 0);
2158 btrfs_set_stack_inode_flags(dst, 0);
2159 btrfs_set_stack_timespec_sec(&dst->atime, src->i_atime);
2160 btrfs_set_stack_timespec_nsec(&dst->atime, 0);
2161 btrfs_set_stack_timespec_sec(&dst->ctime, src->i_ctime);
2162 btrfs_set_stack_timespec_nsec(&dst->ctime, 0);
2163 btrfs_set_stack_timespec_sec(&dst->mtime, src->i_mtime);
2164 btrfs_set_stack_timespec_nsec(&dst->mtime, 0);
2165 btrfs_set_stack_timespec_sec(&dst->otime, 0);
2166 btrfs_set_stack_timespec_nsec(&dst->otime, 0);
2168 if (S_ISDIR(src->i_mode)) {
2169 btrfs_set_stack_inode_size(dst, 0);
2170 btrfs_set_stack_inode_nlink(dst, 1);
2172 if (S_ISREG(src->i_mode)) {
2173 btrfs_set_stack_inode_size(dst, (u64)src->i_size_high << 32 |
2176 if (!S_ISREG(src->i_mode) && !S_ISDIR(src->i_mode) &&
2177 !S_ISLNK(src->i_mode)) {
2178 if (src->i_block[0]) {
2179 btrfs_set_stack_inode_rdev(dst,
2180 old_decode_dev(src->i_block[0]));
2182 btrfs_set_stack_inode_rdev(dst,
2183 new_decode_dev(src->i_block[1]));
2186 memset(&dst->reserved, 0, sizeof(dst->reserved));
2188 static int ext2_check_state(struct btrfs_convert_context *cctx)
2190 ext2_filsys fs = cctx->fs_data;
2192 if (!(fs->super->s_state & EXT2_VALID_FS))
2194 else if (fs->super->s_state & EXT2_ERROR_FS)
2200 /* EXT2_*_FL to BTRFS_INODE_FLAG_* stringification helper */
2201 #define COPY_ONE_EXT2_FLAG(flags, ext2_inode, name) ({ \
2202 if (ext2_inode->i_flags & EXT2_##name##_FL) \
2203 flags |= BTRFS_INODE_##name; \
2207 * Convert EXT2_*_FL to corresponding BTRFS_INODE_* flags
2209 * Only a subset of EXT_*_FL is supported in btrfs.
2211 static void ext2_convert_inode_flags(struct btrfs_inode_item *dst,
2212 struct ext2_inode *src)
2216 COPY_ONE_EXT2_FLAG(flags, src, APPEND);
2217 COPY_ONE_EXT2_FLAG(flags, src, SYNC);
2218 COPY_ONE_EXT2_FLAG(flags, src, IMMUTABLE);
2219 COPY_ONE_EXT2_FLAG(flags, src, NODUMP);
2220 COPY_ONE_EXT2_FLAG(flags, src, NOATIME);
2221 COPY_ONE_EXT2_FLAG(flags, src, DIRSYNC);
2222 btrfs_set_stack_inode_flags(dst, flags);
2226 * copy a single inode. do all the required works, such as cloning
2227 * inode item, creating file extents and creating directory entries.
2229 static int ext2_copy_single_inode(struct btrfs_trans_handle *trans,
2230 struct btrfs_root *root, u64 objectid,
2231 ext2_filsys ext2_fs, ext2_ino_t ext2_ino,
2232 struct ext2_inode *ext2_inode,
2233 int datacsum, int packing, int noxattr)
2236 struct btrfs_inode_item btrfs_inode;
2238 if (ext2_inode->i_links_count == 0)
2241 ext2_copy_inode_item(&btrfs_inode, ext2_inode, ext2_fs->blocksize);
2242 if (!datacsum && S_ISREG(ext2_inode->i_mode)) {
2243 u32 flags = btrfs_stack_inode_flags(&btrfs_inode) |
2244 BTRFS_INODE_NODATASUM;
2245 btrfs_set_stack_inode_flags(&btrfs_inode, flags);
2247 ext2_convert_inode_flags(&btrfs_inode, ext2_inode);
2249 switch (ext2_inode->i_mode & S_IFMT) {
2251 ret = ext2_create_file_extents(trans, root, objectid,
2252 &btrfs_inode, ext2_fs, ext2_ino, datacsum, packing);
2255 ret = ext2_create_dir_entries(trans, root, objectid,
2256 &btrfs_inode, ext2_fs, ext2_ino);
2259 ret = ext2_create_symbol_link(trans, root, objectid,
2260 &btrfs_inode, ext2_fs, ext2_ino, ext2_inode);
2270 ret = ext2_copy_extended_attrs(trans, root, objectid,
2271 &btrfs_inode, ext2_fs, ext2_ino);
2275 return btrfs_insert_inode(trans, root, objectid, &btrfs_inode);
2279 * scan ext2's inode bitmap and copy all used inodes.
2281 static int ext2_copy_inodes(struct btrfs_convert_context *cctx,
2282 struct btrfs_root *root,
2283 int datacsum, int packing, int noxattr, struct task_ctx *p)
2285 ext2_filsys ext2_fs = cctx->fs_data;
2288 ext2_inode_scan ext2_scan;
2289 struct ext2_inode ext2_inode;
2290 ext2_ino_t ext2_ino;
2292 struct btrfs_trans_handle *trans;
2294 trans = btrfs_start_transaction(root, 1);
2297 err = ext2fs_open_inode_scan(ext2_fs, 0, &ext2_scan);
2299 fprintf(stderr, "ext2fs_open_inode_scan: %s\n", error_message(err));
2302 while (!(err = ext2fs_get_next_inode(ext2_scan, &ext2_ino,
2304 /* no more inodes */
2307 /* skip special inode in ext2fs */
2308 if (ext2_ino < EXT2_GOOD_OLD_FIRST_INO &&
2309 ext2_ino != EXT2_ROOT_INO)
2311 objectid = ext2_ino + INO_OFFSET;
2312 ret = ext2_copy_single_inode(trans, root,
2313 objectid, ext2_fs, ext2_ino,
2314 &ext2_inode, datacsum, packing,
2316 p->cur_copy_inodes++;
2319 if (trans->blocks_used >= 4096) {
2320 ret = btrfs_commit_transaction(trans, root);
2322 trans = btrfs_start_transaction(root, 1);
2327 fprintf(stderr, "ext2fs_get_next_inode: %s\n", error_message(err));
2330 ret = btrfs_commit_transaction(trans, root);
2332 ext2fs_close_inode_scan(ext2_scan);
2337 static const struct btrfs_convert_operations ext2_convert_ops = {
2339 .open_fs = ext2_open_fs,
2340 .read_used_space = ext2_read_used_space,
2341 .copy_inodes = ext2_copy_inodes,
2342 .close_fs = ext2_close_fs,
2343 .check_state = ext2_check_state,
2348 static const struct btrfs_convert_operations *convert_operations[] = {
2349 #if BTRFSCONVERT_EXT2
2354 static int convert_open_fs(const char *devname,
2355 struct btrfs_convert_context *cctx)
2359 memset(cctx, 0, sizeof(*cctx));
2361 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
2362 int ret = convert_operations[i]->open_fs(cctx, devname);
2365 cctx->convert_ops = convert_operations[i];
2370 error("no file system found to convert");
2374 static int do_convert(const char *devname, int datacsum, int packing,
2375 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
2376 int progress, u64 features)
2382 struct btrfs_root *root;
2383 struct btrfs_root *image_root;
2384 struct btrfs_convert_context cctx;
2385 struct btrfs_key key;
2386 char *subvol_name = NULL;
2387 struct task_ctx ctx;
2388 char features_buf[64];
2389 struct btrfs_mkfs_config mkfs_cfg;
2391 init_convert_context(&cctx);
2392 ret = convert_open_fs(devname, &cctx);
2395 ret = convert_check_state(&cctx);
2398 "source filesystem is not clean, running filesystem check is recommended");
2399 ret = convert_read_used_space(&cctx);
2403 blocksize = cctx.blocksize;
2404 total_bytes = (u64)blocksize * (u64)cctx.block_count;
2405 if (blocksize < 4096) {
2406 error("block size is too small: %u < 4096", blocksize);
2409 if (btrfs_check_nodesize(nodesize, blocksize, features))
2411 fd = open(devname, O_RDWR);
2413 error("unable to open %s: %s", devname, strerror(errno));
2416 btrfs_parse_features_to_string(features_buf, features);
2417 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
2418 strcat(features_buf, " (default)");
2420 printf("create btrfs filesystem:\n");
2421 printf("\tblocksize: %u\n", blocksize);
2422 printf("\tnodesize: %u\n", nodesize);
2423 printf("\tfeatures: %s\n", features_buf);
2425 mkfs_cfg.label = cctx.volume_name;
2426 mkfs_cfg.num_bytes = total_bytes;
2427 mkfs_cfg.nodesize = nodesize;
2428 mkfs_cfg.sectorsize = blocksize;
2429 mkfs_cfg.stripesize = blocksize;
2430 mkfs_cfg.features = features;
2431 /* New convert need these space */
2432 memset(mkfs_cfg.chunk_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2433 memset(mkfs_cfg.fs_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
2435 ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
2437 error("unable to create initial ctree: %s", strerror(-ret));
2441 root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
2442 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2444 error("unable to open ctree");
2447 ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
2449 error("unable to setup the root tree: %d", ret);
2453 printf("creating %s image file\n", cctx.convert_ops->name);
2454 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
2456 error("memory allocation failure for subvolume name: %s_saved",
2457 cctx.convert_ops->name);
2460 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2461 key.offset = (u64)-1;
2462 key.type = BTRFS_ROOT_ITEM_KEY;
2463 image_root = btrfs_read_fs_root(root->fs_info, &key);
2465 error("unable to create image subvolume");
2468 ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
2469 mkfs_cfg.num_bytes, "image", datacsum);
2471 error("failed to create %s/image: %d", subvol_name, ret);
2475 printf("creating btrfs metadata");
2476 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
2477 ctx.cur_copy_inodes = 0;
2480 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
2482 task_start(ctx.info);
2484 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
2486 error("error during copy_inodes %d", ret);
2490 task_stop(ctx.info);
2491 task_deinit(ctx.info);
2494 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
2496 error("unable to link subvolume %s", subvol_name);
2502 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
2503 if (copylabel == 1) {
2504 __strncpy_null(root->fs_info->super_copy->label,
2505 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
2506 printf("copy label '%s'\n", root->fs_info->super_copy->label);
2507 } else if (copylabel == -1) {
2508 strcpy(root->fs_info->super_copy->label, fslabel);
2509 printf("set label to '%s'\n", fslabel);
2512 ret = close_ctree(root);
2514 error("close_ctree failed: %d", ret);
2517 convert_close_fs(&cctx);
2518 clean_convert_context(&cctx);
2521 * If this step succeed, we get a mountable btrfs. Otherwise
2522 * the source fs is left unchanged.
2524 ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
2526 error("unable to migrate super block: %d", ret);
2530 root = open_ctree_fd(fd, devname, 0,
2531 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
2533 error("unable to open ctree for finalization");
2536 root->fs_info->finalize_on_close = 1;
2540 printf("conversion complete");
2543 clean_convert_context(&cctx);
2547 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
2552 * Check if a non 1:1 mapped chunk can be rolled back.
2553 * For new convert, it's OK while for old convert it's not.
2555 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
2557 struct btrfs_block_group_cache *bg;
2558 struct btrfs_key key;
2559 struct btrfs_path path;
2560 struct btrfs_root *extent_root = fs_info->extent_root;
2565 bg = btrfs_lookup_first_block_group(fs_info, bytenr);
2568 bg_start = bg->key.objectid;
2569 bg_end = bg->key.objectid + bg->key.offset;
2571 key.objectid = bg_end;
2572 key.type = BTRFS_METADATA_ITEM_KEY;
2574 btrfs_init_path(&path);
2576 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
2581 struct btrfs_extent_item *ei;
2583 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
2591 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2592 if (key.type == BTRFS_METADATA_ITEM_KEY)
2594 /* Now it's EXTENT_ITEM_KEY only */
2595 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
2596 struct btrfs_extent_item);
2598 * Found data extent, means this is old convert must follow 1:1
2601 if (btrfs_extent_flags(path.nodes[0], ei)
2602 & BTRFS_EXTENT_FLAG_DATA) {
2607 btrfs_release_path(&path);
2611 static int may_rollback(struct btrfs_root *root)
2613 struct btrfs_fs_info *info = root->fs_info;
2614 struct btrfs_multi_bio *multi = NULL;
2622 if (btrfs_super_num_devices(info->super_copy) != 1)
2625 bytenr = BTRFS_SUPER_INFO_OFFSET;
2626 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
2629 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
2630 &length, &multi, 0, NULL);
2632 if (ret == -ENOENT) {
2633 /* removed block group at the tail */
2634 if (length == (u64)-1)
2637 /* removed block group in the middle */
2643 num_stripes = multi->num_stripes;
2644 physical = multi->stripes[0].physical;
2647 if (num_stripes != 1) {
2648 error("num stripes for bytenr %llu is not 1", bytenr);
2653 * Extra check for new convert, as metadata chunk from new
2654 * convert is much more free than old convert, it doesn't need
2655 * to do 1:1 mapping.
2657 if (physical != bytenr) {
2659 * Check if it's a metadata chunk and has only metadata
2662 ret = may_rollback_chunk(info, bytenr);
2668 if (bytenr >= total_bytes)
2676 static int do_rollback(const char *devname)
2681 struct btrfs_root *root;
2682 struct btrfs_root *image_root;
2683 struct btrfs_root *chunk_root;
2684 struct btrfs_dir_item *dir;
2685 struct btrfs_inode_item *inode;
2686 struct btrfs_file_extent_item *fi;
2687 struct btrfs_trans_handle *trans;
2688 struct extent_buffer *leaf;
2689 struct btrfs_block_group_cache *cache1;
2690 struct btrfs_block_group_cache *cache2;
2691 struct btrfs_key key;
2692 struct btrfs_path path;
2693 struct extent_io_tree io_tree;
2708 extent_io_tree_init(&io_tree);
2710 fd = open(devname, O_RDWR);
2712 error("unable to open %s: %s", devname, strerror(errno));
2715 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
2717 error("unable to open ctree");
2720 ret = may_rollback(root);
2722 error("unable to do rollback: %d", ret);
2726 sectorsize = root->sectorsize;
2727 buf = malloc(sectorsize);
2729 error("unable to allocate memory");
2733 btrfs_init_path(&path);
2735 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2736 key.type = BTRFS_ROOT_BACKREF_KEY;
2737 key.offset = BTRFS_FS_TREE_OBJECTID;
2738 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
2740 btrfs_release_path(&path);
2742 error("unable to convert ext2 image subvolume, is it deleted?");
2744 } else if (ret < 0) {
2745 error("unable to open ext2_saved, id %llu: %s",
2746 (unsigned long long)key.objectid, strerror(-ret));
2750 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
2751 key.type = BTRFS_ROOT_ITEM_KEY;
2752 key.offset = (u64)-1;
2753 image_root = btrfs_read_fs_root(root->fs_info, &key);
2754 if (!image_root || IS_ERR(image_root)) {
2755 error("unable to open subvolume %llu: %ld",
2756 (unsigned long long)key.objectid, PTR_ERR(image_root));
2761 root_dir = btrfs_root_dirid(&root->root_item);
2762 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
2763 root_dir, name, strlen(name), 0);
2764 if (!dir || IS_ERR(dir)) {
2765 error("unable to find file %s: %ld", name, PTR_ERR(dir));
2768 leaf = path.nodes[0];
2769 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
2770 btrfs_release_path(&path);
2772 objectid = key.objectid;
2774 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
2776 error("unable to find inode item: %d", ret);
2779 leaf = path.nodes[0];
2780 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
2781 total_bytes = btrfs_inode_size(leaf, inode);
2782 btrfs_release_path(&path);
2784 key.objectid = objectid;
2786 key.type = BTRFS_EXTENT_DATA_KEY;
2787 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
2789 error("unable to find first file extent: %d", ret);
2790 btrfs_release_path(&path);
2794 /* build mapping tree for the relocated blocks */
2795 for (offset = 0; offset < total_bytes; ) {
2796 leaf = path.nodes[0];
2797 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2798 ret = btrfs_next_leaf(root, &path);
2804 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2805 if (key.objectid != objectid || key.offset != offset ||
2806 key.type != BTRFS_EXTENT_DATA_KEY)
2809 fi = btrfs_item_ptr(leaf, path.slots[0],
2810 struct btrfs_file_extent_item);
2811 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2813 if (btrfs_file_extent_compression(leaf, fi) ||
2814 btrfs_file_extent_encryption(leaf, fi) ||
2815 btrfs_file_extent_other_encoding(leaf, fi))
2818 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
2819 /* skip holes and direct mapped extents */
2820 if (bytenr == 0 || bytenr == offset)
2823 bytenr += btrfs_file_extent_offset(leaf, fi);
2824 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
2826 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2827 cache2 = btrfs_lookup_block_group(root->fs_info,
2828 offset + num_bytes - 1);
2830 * Here we must take consideration of old and new convert
2832 * For old convert case, sign, there is no consist chunk type
2833 * that will cover the extent. META/DATA/SYS are all possible.
2834 * Just ensure relocate one is in SYS chunk.
2835 * For new convert case, they are all covered by DATA chunk.
2837 * So, there is not valid chunk type check for it now.
2839 if (cache1 != cache2)
2842 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
2843 EXTENT_LOCKED, GFP_NOFS);
2844 set_state_private(&io_tree, offset, bytenr);
2846 offset += btrfs_file_extent_num_bytes(leaf, fi);
2849 btrfs_release_path(&path);
2851 if (offset < total_bytes) {
2852 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
2853 (unsigned long long)offset,
2854 (unsigned long long)total_bytes);
2855 error("converted filesystem after balance is unable to rollback");
2859 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
2860 first_free &= ~((u64)sectorsize - 1);
2861 /* backup for extent #0 should exist */
2862 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
2863 error("no backup for the first extent");
2866 /* force no allocation from system block group */
2867 root->fs_info->system_allocs = -1;
2868 trans = btrfs_start_transaction(root, 1);
2870 error("unable to start transaction");
2874 * recow the whole chunk tree, this will remove all chunk tree blocks
2875 * from system block group
2877 chunk_root = root->fs_info->chunk_root;
2878 memset(&key, 0, sizeof(key));
2880 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
2884 ret = btrfs_next_leaf(chunk_root, &path);
2888 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
2889 btrfs_release_path(&path);
2891 btrfs_release_path(&path);
2896 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
2900 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2901 num_bytes += btrfs_block_group_used(&cache1->item);
2903 offset = cache1->key.objectid + cache1->key.offset;
2905 /* only extent #0 left in system block group? */
2906 if (num_bytes > first_free) {
2908 "unable to empty system block group (num_bytes %llu, first_free %llu",
2909 (unsigned long long)num_bytes,
2910 (unsigned long long)first_free);
2913 /* create a system chunk that maps the whole device */
2914 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
2916 error("unable to update system chunk: %d", ret);
2920 ret = btrfs_commit_transaction(trans, root);
2922 error("transaction commit failed: %d", ret);
2926 ret = close_ctree(root);
2928 error("close_ctree failed: %d", ret);
2932 /* zero btrfs super block mirrors */
2933 memset(buf, 0, sectorsize);
2934 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2935 bytenr = btrfs_sb_offset(i);
2936 if (bytenr >= total_bytes)
2938 ret = pwrite(fd, buf, sectorsize, bytenr);
2939 if (ret != sectorsize) {
2940 error("zeroing superblock mirror %d failed: %d",
2946 sb_bytenr = (u64)-1;
2947 /* copy all relocated blocks back */
2949 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2954 ret = get_state_private(&io_tree, start, &bytenr);
2957 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2960 while (start <= end) {
2961 if (start == BTRFS_SUPER_INFO_OFFSET) {
2965 ret = pread(fd, buf, sectorsize, bytenr);
2967 error("reading superblock at %llu failed: %d",
2968 (unsigned long long)bytenr, ret);
2971 BUG_ON(ret != sectorsize);
2972 ret = pwrite(fd, buf, sectorsize, start);
2974 error("writing superblock at %llu failed: %d",
2975 (unsigned long long)start, ret);
2978 BUG_ON(ret != sectorsize);
2980 start += sectorsize;
2981 bytenr += sectorsize;
2987 error("fsync failed: %s", strerror(errno));
2991 * finally, overwrite btrfs super block.
2993 ret = pread(fd, buf, sectorsize, sb_bytenr);
2995 error("reading primary superblock failed: %s",
2999 BUG_ON(ret != sectorsize);
3000 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
3002 error("writing primary superblock failed: %s",
3006 BUG_ON(ret != sectorsize);
3009 error("fsync failed: %s", strerror(errno));
3015 extent_io_tree_cleanup(&io_tree);
3016 printf("rollback complete\n");
3023 error("rollback aborted");
3027 static void print_usage(void)
3029 printf("usage: btrfs-convert [options] device\n");
3030 printf("options:\n");
3031 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
3032 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
3033 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
3034 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
3035 printf("\t-r|--rollback roll back to the original filesystem\n");
3036 printf("\t-l|--label LABEL set filesystem label\n");
3037 printf("\t-L|--copy-label use label from converted filesystem\n");
3038 printf("\t-p|--progress show converting progress (default)\n");
3039 printf("\t-O|--features LIST comma separated list of filesystem features\n");
3040 printf("\t--no-progress show only overview, not the detailed progress\n");
3042 printf("Supported filesystems:\n");
3043 printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
3046 int main(int argc, char *argv[])
3052 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
3053 BTRFS_MKFS_DEFAULT_NODE_SIZE);
3056 int usage_error = 0;
3059 char fslabel[BTRFS_LABEL_SIZE];
3060 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
3063 enum { GETOPT_VAL_NO_PROGRESS = 256 };
3064 static const struct option long_options[] = {
3065 { "no-progress", no_argument, NULL,
3066 GETOPT_VAL_NO_PROGRESS },
3067 { "no-datasum", no_argument, NULL, 'd' },
3068 { "no-inline", no_argument, NULL, 'n' },
3069 { "no-xattr", no_argument, NULL, 'i' },
3070 { "rollback", no_argument, NULL, 'r' },
3071 { "features", required_argument, NULL, 'O' },
3072 { "progress", no_argument, NULL, 'p' },
3073 { "label", required_argument, NULL, 'l' },
3074 { "copy-label", no_argument, NULL, 'L' },
3075 { "nodesize", required_argument, NULL, 'N' },
3076 { "help", no_argument, NULL, GETOPT_VAL_HELP},
3077 { NULL, 0, NULL, 0 }
3079 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
3094 nodesize = parse_size(optarg);
3101 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
3103 "label too long, trimmed to %d bytes",
3104 BTRFS_LABEL_SIZE - 1);
3106 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
3115 char *orig = strdup(optarg);
3118 tmp = btrfs_parse_fs_features(tmp, &features);
3120 error("unrecognized filesystem feature: %s",
3126 if (features & BTRFS_FEATURE_LIST_ALL) {
3127 btrfs_list_all_fs_features(
3128 ~BTRFS_CONVERT_ALLOWED_FEATURES);
3131 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
3134 btrfs_parse_features_to_string(buf,
3135 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
3136 error("features not allowed for convert: %s",
3143 case GETOPT_VAL_NO_PROGRESS:
3146 case GETOPT_VAL_HELP:
3149 return c != GETOPT_VAL_HELP;
3153 if (check_argc_exact(argc - optind, 1)) {
3158 if (rollback && (!datacsum || noxattr || !packing)) {
3160 "Usage error: -d, -i, -n options do not apply to rollback\n");
3169 file = argv[optind];
3170 ret = check_mounted(file);
3172 error("could not check mount status: %s", strerror(-ret));
3175 error("%s is mounted", file);
3180 ret = do_rollback(file);
3182 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
3183 copylabel, fslabel, progress, features);