2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include "kerncompat.h"
21 #include <sys/ioctl.h>
22 #include <sys/mount.h>
25 #include <sys/types.h>
29 #include <uuid/uuid.h>
30 #include <linux/limits.h>
36 #include "transaction.h"
39 #include "task-utils.h"
41 #include "mkfs/common.h"
42 #include "convert/common.h"
43 #include "convert/source-fs.h"
44 #include "fsfeatures.h"
46 static void *print_copied_inodes(void *p)
48 struct task_ctx *priv = p;
49 const char work_indicator[] = { '.', 'o', 'O', 'o' };
52 task_period_start(priv->info, 1000 /* 1s */);
55 printf("copy inodes [%c] [%10d/%10d]\r",
56 work_indicator[count % 4], priv->cur_copy_inodes,
57 priv->max_copy_inodes);
59 task_period_wait(priv->info);
65 static int after_copied_inodes(void *p)
73 void init_convert_context(struct btrfs_convert_context *cctx)
75 cache_tree_init(&cctx->used);
76 cache_tree_init(&cctx->data_chunks);
77 cache_tree_init(&cctx->free);
80 void clean_convert_context(struct btrfs_convert_context *cctx)
82 free_extent_cache_tree(&cctx->used);
83 free_extent_cache_tree(&cctx->data_chunks);
84 free_extent_cache_tree(&cctx->free);
87 static inline int copy_inodes(struct btrfs_convert_context *cctx,
88 struct btrfs_root *root, int datacsum,
89 int packing, int noxattr, struct task_ctx *p)
91 return cctx->convert_ops->copy_inodes(cctx, root, datacsum, packing,
95 static inline void convert_close_fs(struct btrfs_convert_context *cctx)
97 cctx->convert_ops->close_fs(cctx);
100 static inline int convert_check_state(struct btrfs_convert_context *cctx)
102 return cctx->convert_ops->check_state(cctx);
105 static int intersect_with_sb(u64 bytenr, u64 num_bytes)
110 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
111 offset = btrfs_sb_offset(i);
112 offset &= ~((u64)BTRFS_STRIPE_LEN - 1);
114 if (bytenr < offset + BTRFS_STRIPE_LEN &&
115 bytenr + num_bytes > offset)
121 int convert_insert_dirent(struct btrfs_trans_handle *trans,
122 struct btrfs_root *root,
123 const char *name, size_t name_len,
124 u64 dir, u64 objectid,
125 u8 file_type, u64 index_cnt,
126 struct btrfs_inode_item *inode)
130 struct btrfs_key location = {
131 .objectid = objectid,
133 .type = BTRFS_INODE_ITEM_KEY,
136 ret = btrfs_insert_dir_item(trans, root, name, name_len,
137 dir, &location, file_type, index_cnt);
140 ret = btrfs_insert_inode_ref(trans, root, name, name_len,
141 objectid, dir, index_cnt);
144 inode_size = btrfs_stack_inode_size(inode) + name_len * 2;
145 btrfs_set_stack_inode_size(inode, inode_size);
150 int read_disk_extent(struct btrfs_root *root, u64 bytenr,
151 u32 num_bytes, char *buffer)
154 struct btrfs_fs_devices *fs_devs = root->fs_info->fs_devices;
156 ret = pread(fs_devs->latest_bdev, buffer, num_bytes, bytenr);
157 if (ret != num_bytes)
166 static int csum_disk_extent(struct btrfs_trans_handle *trans,
167 struct btrfs_root *root,
168 u64 disk_bytenr, u64 num_bytes)
170 u32 blocksize = root->sectorsize;
175 buffer = malloc(blocksize);
178 for (offset = 0; offset < num_bytes; offset += blocksize) {
179 ret = read_disk_extent(root, disk_bytenr + offset,
183 ret = btrfs_csum_file_block(trans,
184 root->fs_info->csum_root,
185 disk_bytenr + num_bytes,
186 disk_bytenr + offset,
195 void init_blk_iterate_data(struct blk_iterate_data *data,
196 struct btrfs_trans_handle *trans,
197 struct btrfs_root *root,
198 struct btrfs_inode_item *inode,
199 u64 objectid, int checksum)
201 struct btrfs_key key;
206 data->objectid = objectid;
207 data->first_block = 0;
208 data->disk_block = 0;
209 data->num_blocks = 0;
210 data->boundary = (u64)-1;
211 data->checksum = checksum;
214 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
215 key.type = BTRFS_ROOT_ITEM_KEY;
216 key.offset = (u64)-1;
217 data->convert_root = btrfs_read_fs_root(root->fs_info, &key);
218 /* Impossible as we just opened it before */
219 BUG_ON(!data->convert_root || IS_ERR(data->convert_root));
220 data->convert_ino = BTRFS_FIRST_FREE_OBJECTID + 1;
224 * Record a file extent in original filesystem into btrfs one.
225 * The special point is, old disk_block can point to a reserved range.
226 * So here, we don't use disk_block directly but search convert_root
227 * to get the real disk_bytenr.
229 int record_file_blocks(struct blk_iterate_data *data,
230 u64 file_block, u64 disk_block, u64 num_blocks)
233 struct btrfs_root *root = data->root;
234 struct btrfs_root *convert_root = data->convert_root;
235 struct btrfs_path path;
236 u64 file_pos = file_block * root->sectorsize;
237 u64 old_disk_bytenr = disk_block * root->sectorsize;
238 u64 num_bytes = num_blocks * root->sectorsize;
239 u64 cur_off = old_disk_bytenr;
241 /* Hole, pass it to record_file_extent directly */
242 if (old_disk_bytenr == 0)
243 return btrfs_record_file_extent(data->trans, root,
244 data->objectid, data->inode, file_pos, 0,
247 btrfs_init_path(&path);
250 * Search real disk bytenr from convert root
252 while (cur_off < old_disk_bytenr + num_bytes) {
253 struct btrfs_key key;
254 struct btrfs_file_extent_item *fi;
255 struct extent_buffer *node;
257 u64 extent_disk_bytenr;
258 u64 extent_num_bytes;
259 u64 real_disk_bytenr;
262 key.objectid = data->convert_ino;
263 key.type = BTRFS_EXTENT_DATA_KEY;
264 key.offset = cur_off;
266 ret = btrfs_search_slot(NULL, convert_root, &key, &path, 0, 0);
270 ret = btrfs_previous_item(convert_root, &path,
272 BTRFS_EXTENT_DATA_KEY);
280 node = path.nodes[0];
281 slot = path.slots[0];
282 btrfs_item_key_to_cpu(node, &key, slot);
283 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY ||
284 key.objectid != data->convert_ino ||
285 key.offset > cur_off);
286 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
287 extent_disk_bytenr = btrfs_file_extent_disk_bytenr(node, fi);
288 extent_num_bytes = btrfs_file_extent_num_bytes(node, fi);
289 BUG_ON(cur_off - key.offset >= extent_num_bytes);
290 btrfs_release_path(&path);
292 if (extent_disk_bytenr)
293 real_disk_bytenr = cur_off - key.offset +
296 real_disk_bytenr = 0;
297 cur_len = min(key.offset + extent_num_bytes,
298 old_disk_bytenr + num_bytes) - cur_off;
299 ret = btrfs_record_file_extent(data->trans, data->root,
300 data->objectid, data->inode, file_pos,
301 real_disk_bytenr, cur_len);
308 * No need to care about csum
309 * As every byte of old fs image is calculated for csum, no
310 * need to waste CPU cycles now.
313 btrfs_release_path(&path);
317 int block_iterate_proc(u64 disk_block, u64 file_block,
318 struct blk_iterate_data *idata)
323 struct btrfs_root *root = idata->root;
324 struct btrfs_block_group_cache *cache;
325 u64 bytenr = disk_block * root->sectorsize;
327 sb_region = intersect_with_sb(bytenr, root->sectorsize);
328 do_barrier = sb_region || disk_block >= idata->boundary;
329 if ((idata->num_blocks > 0 && do_barrier) ||
330 (file_block > idata->first_block + idata->num_blocks) ||
331 (disk_block != idata->disk_block + idata->num_blocks)) {
332 if (idata->num_blocks > 0) {
333 ret = record_file_blocks(idata, idata->first_block,
338 idata->first_block += idata->num_blocks;
339 idata->num_blocks = 0;
341 if (file_block > idata->first_block) {
342 ret = record_file_blocks(idata, idata->first_block,
343 0, file_block - idata->first_block);
349 bytenr += BTRFS_STRIPE_LEN - 1;
350 bytenr &= ~((u64)BTRFS_STRIPE_LEN - 1);
352 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
354 bytenr = cache->key.objectid + cache->key.offset;
357 idata->first_block = file_block;
358 idata->disk_block = disk_block;
359 idata->boundary = bytenr / root->sectorsize;
366 static int create_image_file_range(struct btrfs_trans_handle *trans,
367 struct btrfs_root *root,
368 struct cache_tree *used,
369 struct btrfs_inode_item *inode,
370 u64 ino, u64 bytenr, u64 *ret_len,
373 struct cache_extent *cache;
374 struct btrfs_block_group_cache *bg_cache;
380 if (bytenr != round_down(bytenr, root->sectorsize)) {
381 error("bytenr not sectorsize aligned: %llu",
382 (unsigned long long)bytenr);
385 if (len != round_down(len, root->sectorsize)) {
386 error("length not sectorsize aligned: %llu",
387 (unsigned long long)len);
390 len = min_t(u64, len, BTRFS_MAX_EXTENT_SIZE);
393 * Skip sb ranges first
394 * [0, 1M), [sb_offset(1), +64K), [sb_offset(2), +64K].
396 * Or we will insert a hole into current image file, and later
397 * migrate block will fail as there is already a file extent.
399 if (bytenr < 1024 * 1024) {
400 *ret_len = 1024 * 1024 - bytenr;
403 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
404 u64 cur = btrfs_sb_offset(i);
406 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
407 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
411 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
412 u64 cur = btrfs_sb_offset(i);
417 * May still need to go through file extent inserts
419 if (bytenr < cur && bytenr + len >= cur) {
420 len = min_t(u64, len, cur - bytenr);
426 * Drop out, no need to insert anything
428 if (bytenr >= cur && bytenr < cur + BTRFS_STRIPE_LEN) {
429 *ret_len = cur + BTRFS_STRIPE_LEN - bytenr;
434 cache = search_cache_extent(used, bytenr);
436 if (cache->start <= bytenr) {
438 * |///////Used///////|
442 len = min_t(u64, len, cache->start + cache->size -
444 disk_bytenr = bytenr;
451 len = min(len, cache->start - bytenr);
466 /* Check if the range is in a data block group */
467 bg_cache = btrfs_lookup_block_group(root->fs_info, bytenr);
470 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
473 /* The extent should never cross block group boundary */
474 len = min_t(u64, len, bg_cache->key.objectid +
475 bg_cache->key.offset - bytenr);
478 if (len != round_down(len, root->sectorsize)) {
479 error("remaining length not sectorsize aligned: %llu",
480 (unsigned long long)len);
483 ret = btrfs_record_file_extent(trans, root, ino, inode, bytenr,
489 ret = csum_disk_extent(trans, root, bytenr, len);
495 * Relocate old fs data in one reserved ranges
497 * Since all old fs data in reserved range is not covered by any chunk nor
498 * data extent, we don't need to handle any reference but add new
499 * extent/reference, which makes codes more clear
501 static int migrate_one_reserved_range(struct btrfs_trans_handle *trans,
502 struct btrfs_root *root,
503 struct cache_tree *used,
504 struct btrfs_inode_item *inode, int fd,
505 u64 ino, u64 start, u64 len, int datacsum)
509 u64 hole_start = start;
511 struct cache_extent *cache;
512 struct btrfs_key key;
513 struct extent_buffer *eb;
516 while (cur_off < start + len) {
517 cache = lookup_cache_extent(used, cur_off, cur_len);
520 cur_off = max(cache->start, cur_off);
521 cur_len = min(cache->start + cache->size, start + len) -
523 BUG_ON(cur_len < root->sectorsize);
525 /* reserve extent for the data */
526 ret = btrfs_reserve_extent(trans, root, cur_len, 0, 0, (u64)-1,
531 eb = malloc(sizeof(*eb) + cur_len);
537 ret = pread(fd, eb->data, cur_len, cur_off);
539 ret = (ret < 0 ? ret : -EIO);
543 eb->start = key.objectid;
544 eb->len = key.offset;
547 ret = write_and_map_eb(trans, root, eb);
552 /* Now handle extent item and file extent things */
553 ret = btrfs_record_file_extent(trans, root, ino, inode, cur_off,
554 key.objectid, key.offset);
557 /* Finally, insert csum items */
559 ret = csum_disk_extent(trans, root, key.objectid,
562 /* Don't forget to insert hole */
563 hole_len = cur_off - hole_start;
565 ret = btrfs_record_file_extent(trans, root, ino, inode,
566 hole_start, 0, hole_len);
571 cur_off += key.offset;
572 hole_start = cur_off;
573 cur_len = start + len - cur_off;
576 if (start + len - hole_start > 0)
577 ret = btrfs_record_file_extent(trans, root, ino, inode,
578 hole_start, 0, start + len - hole_start);
583 * Relocate the used ext2 data in reserved ranges
585 * [btrfs_sb_offset(1), +BTRFS_STRIPE_LEN)
586 * [btrfs_sb_offset(2), +BTRFS_STRIPE_LEN)
588 static int migrate_reserved_ranges(struct btrfs_trans_handle *trans,
589 struct btrfs_root *root,
590 struct cache_tree *used,
591 struct btrfs_inode_item *inode, int fd,
592 u64 ino, u64 total_bytes, int datacsum)
600 cur_len = 1024 * 1024;
601 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
602 cur_off, cur_len, datacsum);
606 /* second sb(fisrt sb is included in 0~1M) */
607 cur_off = btrfs_sb_offset(1);
608 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
609 if (cur_off > total_bytes)
611 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
612 cur_off, cur_len, datacsum);
617 cur_off = btrfs_sb_offset(2);
618 cur_len = min(total_bytes, cur_off + BTRFS_STRIPE_LEN) - cur_off;
619 if (cur_off > total_bytes)
621 ret = migrate_one_reserved_range(trans, root, used, inode, fd, ino,
622 cur_off, cur_len, datacsum);
627 * Helper for expand and merge extent_cache for wipe_one_reserved_range() to
628 * handle wiping a range that exists in cache.
630 static int _expand_extent_cache(struct cache_tree *tree,
631 struct cache_extent *entry,
632 u64 min_stripe_size, int backward)
634 struct cache_extent *ce;
637 if (entry->size >= min_stripe_size)
639 diff = min_stripe_size - entry->size;
642 ce = prev_cache_extent(entry);
645 if (ce->start + ce->size >= entry->start - diff) {
646 /* Directly merge with previous extent */
647 ce->size = entry->start + entry->size - ce->start;
648 remove_cache_extent(tree, entry);
653 /* No overlap, normal extent */
654 if (entry->start < diff) {
655 error("cannot find space for data chunk layout");
658 entry->start -= diff;
662 ce = next_cache_extent(entry);
665 if (entry->start + entry->size + diff >= ce->start) {
666 /* Directly merge with next extent */
667 entry->size = ce->start + ce->size - entry->start;
668 remove_cache_extent(tree, ce);
678 * Remove one reserve range from given cache tree
679 * if min_stripe_size is non-zero, it will ensure for split case,
680 * all its split cache extent is no smaller than @min_strip_size / 2.
682 static int wipe_one_reserved_range(struct cache_tree *tree,
683 u64 start, u64 len, u64 min_stripe_size,
686 struct cache_extent *cache;
689 BUG_ON(ensure_size && min_stripe_size == 0);
691 * The logical here is simplified to handle special cases only
692 * So we don't need to consider merge case for ensure_size
694 BUG_ON(min_stripe_size && (min_stripe_size < len * 2 ||
695 min_stripe_size / 2 < BTRFS_STRIPE_LEN));
697 /* Also, wipe range should already be aligned */
698 BUG_ON(start != round_down(start, BTRFS_STRIPE_LEN) ||
699 start + len != round_up(start + len, BTRFS_STRIPE_LEN));
701 min_stripe_size /= 2;
703 cache = lookup_cache_extent(tree, start, len);
707 if (start <= cache->start) {
709 * |--------cache---------|
712 BUG_ON(start + len <= cache->start);
715 * The wipe size is smaller than min_stripe_size / 2,
716 * so the result length should still meet min_stripe_size
717 * And no need to do alignment
719 cache->size -= (start + len - cache->start);
720 if (cache->size == 0) {
721 remove_cache_extent(tree, cache);
726 BUG_ON(ensure_size && cache->size < min_stripe_size);
728 cache->start = start + len;
730 } else if (start > cache->start && start + len < cache->start +
733 * |-------cache-----|
736 u64 old_start = cache->start;
737 u64 old_len = cache->size;
738 u64 insert_start = start + len;
741 cache->size = start - cache->start;
742 /* Expand the leading half part if needed */
743 if (ensure_size && cache->size < min_stripe_size) {
744 ret = _expand_extent_cache(tree, cache,
750 /* And insert the new one */
751 insert_len = old_start + old_len - start - len;
752 ret = add_merge_cache_extent(tree, insert_start, insert_len);
756 /* Expand the last half part if needed */
757 if (ensure_size && insert_len < min_stripe_size) {
758 cache = lookup_cache_extent(tree, insert_start,
760 if (!cache || cache->start != insert_start ||
761 cache->size != insert_len)
763 ret = _expand_extent_cache(tree, cache,
772 * Wipe len should be small enough and no need to expand the
775 cache->size = start - cache->start;
776 BUG_ON(ensure_size && cache->size < min_stripe_size);
781 * Remove reserved ranges from given cache_tree
783 * It will remove the following ranges
785 * 2) 2nd superblock, +64K (make sure chunks are 64K aligned)
786 * 3) 3rd superblock, +64K
788 * @min_stripe must be given for safety check
789 * and if @ensure_size is given, it will ensure affected cache_extent will be
790 * larger than min_stripe_size
792 static int wipe_reserved_ranges(struct cache_tree *tree, u64 min_stripe_size,
797 ret = wipe_one_reserved_range(tree, 0, 1024 * 1024, min_stripe_size,
801 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(1),
802 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
805 ret = wipe_one_reserved_range(tree, btrfs_sb_offset(2),
806 BTRFS_STRIPE_LEN, min_stripe_size, ensure_size);
810 static int calculate_available_space(struct btrfs_convert_context *cctx)
812 struct cache_tree *used = &cctx->used;
813 struct cache_tree *data_chunks = &cctx->data_chunks;
814 struct cache_tree *free = &cctx->free;
815 struct cache_extent *cache;
818 * Twice the minimal chunk size, to allow later wipe_reserved_ranges()
819 * works without need to consider overlap
821 u64 min_stripe_size = 2 * 16 * 1024 * 1024;
824 /* Calculate data_chunks */
825 for (cache = first_cache_extent(used); cache;
826 cache = next_cache_extent(cache)) {
829 if (cache->start + cache->size < cur_off)
831 if (cache->start > cur_off + min_stripe_size)
832 cur_off = cache->start;
833 cur_len = max(cache->start + cache->size - cur_off,
835 ret = add_merge_cache_extent(data_chunks, cur_off, cur_len);
841 * remove reserved ranges, so we won't ever bother relocating an old
842 * filesystem extent to other place.
844 ret = wipe_reserved_ranges(data_chunks, min_stripe_size, 1);
850 * Calculate free space
851 * Always round up the start bytenr, to avoid metadata extent corss
852 * stripe boundary, as later mkfs_convert() won't have all the extent
855 for (cache = first_cache_extent(data_chunks); cache;
856 cache = next_cache_extent(cache)) {
857 if (cache->start < cur_off)
859 if (cache->start > cur_off) {
863 len = cache->start - round_up(cur_off,
865 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
867 ret = add_merge_cache_extent(free, insert_start, len);
871 cur_off = cache->start + cache->size;
873 /* Don't forget the last range */
874 if (cctx->total_bytes > cur_off) {
875 u64 len = cctx->total_bytes - cur_off;
878 insert_start = round_up(cur_off, BTRFS_STRIPE_LEN);
880 ret = add_merge_cache_extent(free, insert_start, len);
885 /* Remove reserved bytes */
886 ret = wipe_reserved_ranges(free, min_stripe_size, 0);
892 * Read used space, and since we have the used space,
893 * calcuate data_chunks and free for later mkfs
895 static int convert_read_used_space(struct btrfs_convert_context *cctx)
899 ret = cctx->convert_ops->read_used_space(cctx);
903 ret = calculate_available_space(cctx);
908 * Create the fs image file of old filesystem.
910 * This is completely fs independent as we have cctx->used, only
911 * need to create file extents pointing to all the positions.
913 static int create_image(struct btrfs_root *root,
914 struct btrfs_mkfs_config *cfg,
915 struct btrfs_convert_context *cctx, int fd,
916 u64 size, char *name, int datacsum)
918 struct btrfs_inode_item buf;
919 struct btrfs_trans_handle *trans;
920 struct btrfs_path path;
921 struct btrfs_key key;
922 struct cache_extent *cache;
923 struct cache_tree used_tmp;
926 u64 flags = BTRFS_INODE_READONLY;
930 flags |= BTRFS_INODE_NODATASUM;
932 trans = btrfs_start_transaction(root, 1);
936 cache_tree_init(&used_tmp);
937 btrfs_init_path(&path);
939 ret = btrfs_find_free_objectid(trans, root, BTRFS_FIRST_FREE_OBJECTID,
943 ret = btrfs_new_inode(trans, root, ino, 0400 | S_IFREG);
946 ret = btrfs_change_inode_flags(trans, root, ino, flags);
949 ret = btrfs_add_link(trans, root, ino, BTRFS_FIRST_FREE_OBJECTID, name,
950 strlen(name), BTRFS_FT_REG_FILE, NULL, 1);
955 key.type = BTRFS_INODE_ITEM_KEY;
958 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
960 ret = (ret > 0 ? -ENOENT : ret);
963 read_extent_buffer(path.nodes[0], &buf,
964 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
966 btrfs_release_path(&path);
969 * Create a new used space cache, which doesn't contain the reserved
972 for (cache = first_cache_extent(&cctx->used); cache;
973 cache = next_cache_extent(cache)) {
974 ret = add_cache_extent(&used_tmp, cache->start, cache->size);
978 ret = wipe_reserved_ranges(&used_tmp, 0, 0);
983 * Start from 1M, as 0~1M is reserved, and create_image_file_range()
984 * can't handle bytenr 0(will consider it as a hole)
988 u64 len = size - cur;
990 ret = create_image_file_range(trans, root, &used_tmp,
991 &buf, ino, cur, &len, datacsum);
996 /* Handle the reserved ranges */
997 ret = migrate_reserved_ranges(trans, root, &cctx->used, &buf, fd, ino,
998 cfg->num_bytes, datacsum);
1002 key.type = BTRFS_INODE_ITEM_KEY;
1004 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
1006 ret = (ret > 0 ? -ENOENT : ret);
1009 btrfs_set_stack_inode_size(&buf, cfg->num_bytes);
1010 write_extent_buffer(path.nodes[0], &buf,
1011 btrfs_item_ptr_offset(path.nodes[0], path.slots[0]),
1014 free_extent_cache_tree(&used_tmp);
1015 btrfs_release_path(&path);
1016 btrfs_commit_transaction(trans, root);
1020 static struct btrfs_root* link_subvol(struct btrfs_root *root,
1021 const char *base, u64 root_objectid)
1023 struct btrfs_trans_handle *trans;
1024 struct btrfs_fs_info *fs_info = root->fs_info;
1025 struct btrfs_root *tree_root = fs_info->tree_root;
1026 struct btrfs_root *new_root = NULL;
1027 struct btrfs_path path;
1028 struct btrfs_inode_item *inode_item;
1029 struct extent_buffer *leaf;
1030 struct btrfs_key key;
1031 u64 dirid = btrfs_root_dirid(&root->root_item);
1033 char buf[BTRFS_NAME_LEN + 1]; /* for snprintf null */
1039 if (len == 0 || len > BTRFS_NAME_LEN)
1042 btrfs_init_path(&path);
1043 key.objectid = dirid;
1044 key.type = BTRFS_DIR_INDEX_KEY;
1045 key.offset = (u64)-1;
1047 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1049 error("search for DIR_INDEX dirid %llu failed: %d",
1050 (unsigned long long)dirid, ret);
1054 if (path.slots[0] > 0) {
1056 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1057 if (key.objectid == dirid && key.type == BTRFS_DIR_INDEX_KEY)
1058 index = key.offset + 1;
1060 btrfs_release_path(&path);
1062 trans = btrfs_start_transaction(root, 1);
1064 error("unable to start transaction");
1068 key.objectid = dirid;
1070 key.type = BTRFS_INODE_ITEM_KEY;
1072 ret = btrfs_lookup_inode(trans, root, &path, &key, 1);
1074 error("search for INODE_ITEM %llu failed: %d",
1075 (unsigned long long)dirid, ret);
1078 leaf = path.nodes[0];
1079 inode_item = btrfs_item_ptr(leaf, path.slots[0],
1080 struct btrfs_inode_item);
1082 key.objectid = root_objectid;
1083 key.offset = (u64)-1;
1084 key.type = BTRFS_ROOT_ITEM_KEY;
1086 memcpy(buf, base, len);
1087 for (i = 0; i < 1024; i++) {
1088 ret = btrfs_insert_dir_item(trans, root, buf, len,
1089 dirid, &key, BTRFS_FT_DIR, index);
1092 len = snprintf(buf, ARRAY_SIZE(buf), "%s%d", base, i);
1093 if (len < 1 || len > BTRFS_NAME_LEN) {
1101 btrfs_set_inode_size(leaf, inode_item, len * 2 +
1102 btrfs_inode_size(leaf, inode_item));
1103 btrfs_mark_buffer_dirty(leaf);
1104 btrfs_release_path(&path);
1106 /* add the backref first */
1107 ret = btrfs_add_root_ref(trans, tree_root, root_objectid,
1108 BTRFS_ROOT_BACKREF_KEY,
1109 root->root_key.objectid,
1110 dirid, index, buf, len);
1112 error("unable to add root backref for %llu: %d",
1113 root->root_key.objectid, ret);
1117 /* now add the forward ref */
1118 ret = btrfs_add_root_ref(trans, tree_root, root->root_key.objectid,
1119 BTRFS_ROOT_REF_KEY, root_objectid,
1120 dirid, index, buf, len);
1122 error("unable to add root ref for %llu: %d",
1123 root->root_key.objectid, ret);
1127 ret = btrfs_commit_transaction(trans, root);
1129 error("transaction commit failed: %d", ret);
1133 new_root = btrfs_read_fs_root(fs_info, &key);
1134 if (IS_ERR(new_root)) {
1135 error("unable to fs read root: %lu", PTR_ERR(new_root));
1139 btrfs_init_path(&path);
1143 static int create_subvol(struct btrfs_trans_handle *trans,
1144 struct btrfs_root *root, u64 root_objectid)
1146 struct extent_buffer *tmp;
1147 struct btrfs_root *new_root;
1148 struct btrfs_key key;
1149 struct btrfs_root_item root_item;
1152 ret = btrfs_copy_root(trans, root, root->node, &tmp,
1157 memcpy(&root_item, &root->root_item, sizeof(root_item));
1158 btrfs_set_root_bytenr(&root_item, tmp->start);
1159 btrfs_set_root_level(&root_item, btrfs_header_level(tmp));
1160 btrfs_set_root_generation(&root_item, trans->transid);
1161 free_extent_buffer(tmp);
1163 key.objectid = root_objectid;
1164 key.type = BTRFS_ROOT_ITEM_KEY;
1165 key.offset = trans->transid;
1166 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
1169 key.offset = (u64)-1;
1170 new_root = btrfs_read_fs_root(root->fs_info, &key);
1171 if (!new_root || IS_ERR(new_root)) {
1172 error("unable to fs read root: %lu", PTR_ERR(new_root));
1173 return PTR_ERR(new_root);
1176 ret = btrfs_make_root_dir(trans, new_root, BTRFS_FIRST_FREE_OBJECTID);
1182 * New make_btrfs() has handle system and meta chunks quite well.
1183 * So only need to add remaining data chunks.
1185 static int make_convert_data_block_groups(struct btrfs_trans_handle *trans,
1186 struct btrfs_fs_info *fs_info,
1187 struct btrfs_mkfs_config *cfg,
1188 struct btrfs_convert_context *cctx)
1190 struct btrfs_root *extent_root = fs_info->extent_root;
1191 struct cache_tree *data_chunks = &cctx->data_chunks;
1192 struct cache_extent *cache;
1197 * Don't create data chunk over 10% of the convert device
1198 * And for single chunk, don't create chunk larger than 1G.
1200 max_chunk_size = cfg->num_bytes / 10;
1201 max_chunk_size = min((u64)(1024 * 1024 * 1024), max_chunk_size);
1202 max_chunk_size = round_down(max_chunk_size, extent_root->sectorsize);
1204 for (cache = first_cache_extent(data_chunks); cache;
1205 cache = next_cache_extent(cache)) {
1206 u64 cur = cache->start;
1208 while (cur < cache->start + cache->size) {
1210 u64 cur_backup = cur;
1212 len = min(max_chunk_size,
1213 cache->start + cache->size - cur);
1214 ret = btrfs_alloc_data_chunk(trans, extent_root,
1216 BTRFS_BLOCK_GROUP_DATA, 1);
1219 ret = btrfs_make_block_group(trans, extent_root, 0,
1220 BTRFS_BLOCK_GROUP_DATA,
1221 BTRFS_FIRST_CHUNK_TREE_OBJECTID,
1232 * Init the temp btrfs to a operational status.
1234 * It will fix the extent usage accounting(XXX: Do we really need?) and
1235 * insert needed data chunks, to ensure all old fs data extents are covered
1236 * by DATA chunks, preventing wrong chunks are allocated.
1238 * And also create convert image subvolume and relocation tree.
1239 * (XXX: Not need again?)
1240 * But the convert image subvolume is *NOT* linked to fs tree yet.
1242 static int init_btrfs(struct btrfs_mkfs_config *cfg, struct btrfs_root *root,
1243 struct btrfs_convert_context *cctx, int datacsum,
1244 int packing, int noxattr)
1246 struct btrfs_key location;
1247 struct btrfs_trans_handle *trans;
1248 struct btrfs_fs_info *fs_info = root->fs_info;
1252 * Don't alloc any metadata/system chunk, as we don't want
1253 * any meta/sys chunk allcated before all data chunks are inserted.
1254 * Or we screw up the chunk layout just like the old implement.
1256 fs_info->avoid_sys_chunk_alloc = 1;
1257 fs_info->avoid_meta_chunk_alloc = 1;
1258 trans = btrfs_start_transaction(root, 1);
1260 error("unable to start transaction");
1264 ret = btrfs_fix_block_accounting(trans, root);
1267 ret = make_convert_data_block_groups(trans, fs_info, cfg, cctx);
1270 ret = btrfs_make_root_dir(trans, fs_info->tree_root,
1271 BTRFS_ROOT_TREE_DIR_OBJECTID);
1274 memcpy(&location, &root->root_key, sizeof(location));
1275 location.offset = (u64)-1;
1276 ret = btrfs_insert_dir_item(trans, fs_info->tree_root, "default", 7,
1277 btrfs_super_root_dir(fs_info->super_copy),
1278 &location, BTRFS_FT_DIR, 0);
1281 ret = btrfs_insert_inode_ref(trans, fs_info->tree_root, "default", 7,
1283 btrfs_super_root_dir(fs_info->super_copy), 0);
1286 btrfs_set_root_dirid(&fs_info->fs_root->root_item,
1287 BTRFS_FIRST_FREE_OBJECTID);
1289 /* subvol for fs image file */
1290 ret = create_subvol(trans, root, CONV_IMAGE_SUBVOL_OBJECTID);
1292 error("failed to create subvolume image root: %d", ret);
1295 /* subvol for data relocation tree */
1296 ret = create_subvol(trans, root, BTRFS_DATA_RELOC_TREE_OBJECTID);
1298 error("failed to create DATA_RELOC root: %d", ret);
1302 ret = btrfs_commit_transaction(trans, root);
1303 fs_info->avoid_sys_chunk_alloc = 0;
1304 fs_info->avoid_meta_chunk_alloc = 0;
1310 * Migrate super block to its default position and zero 0 ~ 16k
1312 static int migrate_super_block(int fd, u64 old_bytenr)
1315 struct extent_buffer *buf;
1316 struct btrfs_super_block *super;
1320 buf = malloc(sizeof(*buf) + BTRFS_SUPER_INFO_SIZE);
1324 buf->len = BTRFS_SUPER_INFO_SIZE;
1325 ret = pread(fd, buf->data, BTRFS_SUPER_INFO_SIZE, old_bytenr);
1326 if (ret != BTRFS_SUPER_INFO_SIZE)
1329 super = (struct btrfs_super_block *)buf->data;
1330 BUG_ON(btrfs_super_bytenr(super) != old_bytenr);
1331 btrfs_set_super_bytenr(super, BTRFS_SUPER_INFO_OFFSET);
1333 csum_tree_block_size(buf, BTRFS_CRC32_SIZE, 0);
1334 ret = pwrite(fd, buf->data, BTRFS_SUPER_INFO_SIZE,
1335 BTRFS_SUPER_INFO_OFFSET);
1336 if (ret != BTRFS_SUPER_INFO_SIZE)
1343 memset(buf->data, 0, BTRFS_SUPER_INFO_SIZE);
1344 for (bytenr = 0; bytenr < BTRFS_SUPER_INFO_OFFSET; ) {
1345 len = BTRFS_SUPER_INFO_OFFSET - bytenr;
1346 if (len > BTRFS_SUPER_INFO_SIZE)
1347 len = BTRFS_SUPER_INFO_SIZE;
1348 ret = pwrite(fd, buf->data, len, bytenr);
1350 fprintf(stderr, "unable to zero fill device\n");
1364 static int prepare_system_chunk_sb(struct btrfs_super_block *super)
1366 struct btrfs_chunk *chunk;
1367 struct btrfs_disk_key *key;
1368 u32 sectorsize = btrfs_super_sectorsize(super);
1370 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1371 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1372 sizeof(struct btrfs_disk_key));
1374 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1375 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1376 btrfs_set_disk_key_offset(key, 0);
1378 btrfs_set_stack_chunk_length(chunk, btrfs_super_total_bytes(super));
1379 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1380 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1381 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1382 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1383 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1384 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1385 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1386 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1387 chunk->stripe.devid = super->dev_item.devid;
1388 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1389 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1390 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1394 const struct btrfs_convert_operations ext2_convert_ops;
1396 static const struct btrfs_convert_operations *convert_operations[] = {
1397 #if BTRFSCONVERT_EXT2
1402 static int convert_open_fs(const char *devname,
1403 struct btrfs_convert_context *cctx)
1407 memset(cctx, 0, sizeof(*cctx));
1409 for (i = 0; i < ARRAY_SIZE(convert_operations); i++) {
1410 int ret = convert_operations[i]->open_fs(cctx, devname);
1413 cctx->convert_ops = convert_operations[i];
1418 error("no file system found to convert");
1422 static int do_convert(const char *devname, int datacsum, int packing,
1423 int noxattr, u32 nodesize, int copylabel, const char *fslabel,
1424 int progress, u64 features)
1430 struct btrfs_root *root;
1431 struct btrfs_root *image_root;
1432 struct btrfs_convert_context cctx;
1433 struct btrfs_key key;
1434 char *subvol_name = NULL;
1435 struct task_ctx ctx;
1436 char features_buf[64];
1437 struct btrfs_mkfs_config mkfs_cfg;
1439 init_convert_context(&cctx);
1440 ret = convert_open_fs(devname, &cctx);
1443 ret = convert_check_state(&cctx);
1446 "source filesystem is not clean, running filesystem check is recommended");
1447 ret = convert_read_used_space(&cctx);
1451 blocksize = cctx.blocksize;
1452 total_bytes = (u64)blocksize * (u64)cctx.block_count;
1453 if (blocksize < 4096) {
1454 error("block size is too small: %u < 4096", blocksize);
1457 if (btrfs_check_nodesize(nodesize, blocksize, features))
1459 fd = open(devname, O_RDWR);
1461 error("unable to open %s: %s", devname, strerror(errno));
1464 btrfs_parse_features_to_string(features_buf, features);
1465 if (features == BTRFS_MKFS_DEFAULT_FEATURES)
1466 strcat(features_buf, " (default)");
1468 printf("create btrfs filesystem:\n");
1469 printf("\tblocksize: %u\n", blocksize);
1470 printf("\tnodesize: %u\n", nodesize);
1471 printf("\tfeatures: %s\n", features_buf);
1473 mkfs_cfg.label = cctx.volume_name;
1474 mkfs_cfg.num_bytes = total_bytes;
1475 mkfs_cfg.nodesize = nodesize;
1476 mkfs_cfg.sectorsize = blocksize;
1477 mkfs_cfg.stripesize = blocksize;
1478 mkfs_cfg.features = features;
1479 /* New convert need these space */
1480 memset(mkfs_cfg.chunk_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
1481 memset(mkfs_cfg.fs_uuid, 0, BTRFS_UUID_UNPARSED_SIZE);
1483 ret = make_convert_btrfs(fd, &mkfs_cfg, &cctx);
1485 error("unable to create initial ctree: %s", strerror(-ret));
1489 root = open_ctree_fd(fd, devname, mkfs_cfg.super_bytenr,
1490 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1492 error("unable to open ctree");
1495 ret = init_btrfs(&mkfs_cfg, root, &cctx, datacsum, packing, noxattr);
1497 error("unable to setup the root tree: %d", ret);
1501 printf("creating %s image file\n", cctx.convert_ops->name);
1502 ret = asprintf(&subvol_name, "%s_saved", cctx.convert_ops->name);
1504 error("memory allocation failure for subvolume name: %s_saved",
1505 cctx.convert_ops->name);
1508 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1509 key.offset = (u64)-1;
1510 key.type = BTRFS_ROOT_ITEM_KEY;
1511 image_root = btrfs_read_fs_root(root->fs_info, &key);
1513 error("unable to create image subvolume");
1516 ret = create_image(image_root, &mkfs_cfg, &cctx, fd,
1517 mkfs_cfg.num_bytes, "image", datacsum);
1519 error("failed to create %s/image: %d", subvol_name, ret);
1523 printf("creating btrfs metadata");
1524 ctx.max_copy_inodes = (cctx.inodes_count - cctx.free_inodes_count);
1525 ctx.cur_copy_inodes = 0;
1528 ctx.info = task_init(print_copied_inodes, after_copied_inodes,
1530 task_start(ctx.info);
1532 ret = copy_inodes(&cctx, root, datacsum, packing, noxattr, &ctx);
1534 error("error during copy_inodes %d", ret);
1538 task_stop(ctx.info);
1539 task_deinit(ctx.info);
1542 image_root = link_subvol(root, subvol_name, CONV_IMAGE_SUBVOL_OBJECTID);
1544 error("unable to link subvolume %s", subvol_name);
1550 memset(root->fs_info->super_copy->label, 0, BTRFS_LABEL_SIZE);
1551 if (copylabel == 1) {
1552 __strncpy_null(root->fs_info->super_copy->label,
1553 cctx.volume_name, BTRFS_LABEL_SIZE - 1);
1554 printf("copy label '%s'\n", root->fs_info->super_copy->label);
1555 } else if (copylabel == -1) {
1556 strcpy(root->fs_info->super_copy->label, fslabel);
1557 printf("set label to '%s'\n", fslabel);
1560 ret = close_ctree(root);
1562 error("close_ctree failed: %d", ret);
1565 convert_close_fs(&cctx);
1566 clean_convert_context(&cctx);
1569 * If this step succeed, we get a mountable btrfs. Otherwise
1570 * the source fs is left unchanged.
1572 ret = migrate_super_block(fd, mkfs_cfg.super_bytenr);
1574 error("unable to migrate super block: %d", ret);
1578 root = open_ctree_fd(fd, devname, 0,
1579 OPEN_CTREE_WRITES | OPEN_CTREE_FS_PARTIAL);
1581 error("unable to open ctree for finalization");
1584 root->fs_info->finalize_on_close = 1;
1588 printf("conversion complete");
1591 clean_convert_context(&cctx);
1595 "an error occurred during conversion, filesystem is partially created but not finalized and not mountable");
1600 * Check if a non 1:1 mapped chunk can be rolled back.
1601 * For new convert, it's OK while for old convert it's not.
1603 static int may_rollback_chunk(struct btrfs_fs_info *fs_info, u64 bytenr)
1605 struct btrfs_block_group_cache *bg;
1606 struct btrfs_key key;
1607 struct btrfs_path path;
1608 struct btrfs_root *extent_root = fs_info->extent_root;
1613 bg = btrfs_lookup_first_block_group(fs_info, bytenr);
1616 bg_start = bg->key.objectid;
1617 bg_end = bg->key.objectid + bg->key.offset;
1619 key.objectid = bg_end;
1620 key.type = BTRFS_METADATA_ITEM_KEY;
1622 btrfs_init_path(&path);
1624 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
1629 struct btrfs_extent_item *ei;
1631 ret = btrfs_previous_extent_item(extent_root, &path, bg_start);
1639 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1640 if (key.type == BTRFS_METADATA_ITEM_KEY)
1642 /* Now it's EXTENT_ITEM_KEY only */
1643 ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
1644 struct btrfs_extent_item);
1646 * Found data extent, means this is old convert must follow 1:1
1649 if (btrfs_extent_flags(path.nodes[0], ei)
1650 & BTRFS_EXTENT_FLAG_DATA) {
1655 btrfs_release_path(&path);
1659 static int may_rollback(struct btrfs_root *root)
1661 struct btrfs_fs_info *info = root->fs_info;
1662 struct btrfs_multi_bio *multi = NULL;
1670 if (btrfs_super_num_devices(info->super_copy) != 1)
1673 bytenr = BTRFS_SUPER_INFO_OFFSET;
1674 total_bytes = btrfs_super_total_bytes(root->fs_info->super_copy);
1677 ret = btrfs_map_block(&info->mapping_tree, WRITE, bytenr,
1678 &length, &multi, 0, NULL);
1680 if (ret == -ENOENT) {
1681 /* removed block group at the tail */
1682 if (length == (u64)-1)
1685 /* removed block group in the middle */
1691 num_stripes = multi->num_stripes;
1692 physical = multi->stripes[0].physical;
1695 if (num_stripes != 1) {
1696 error("num stripes for bytenr %llu is not 1", bytenr);
1701 * Extra check for new convert, as metadata chunk from new
1702 * convert is much more free than old convert, it doesn't need
1703 * to do 1:1 mapping.
1705 if (physical != bytenr) {
1707 * Check if it's a metadata chunk and has only metadata
1710 ret = may_rollback_chunk(info, bytenr);
1716 if (bytenr >= total_bytes)
1724 static int do_rollback(const char *devname)
1729 struct btrfs_root *root;
1730 struct btrfs_root *image_root;
1731 struct btrfs_root *chunk_root;
1732 struct btrfs_dir_item *dir;
1733 struct btrfs_inode_item *inode;
1734 struct btrfs_file_extent_item *fi;
1735 struct btrfs_trans_handle *trans;
1736 struct extent_buffer *leaf;
1737 struct btrfs_block_group_cache *cache1;
1738 struct btrfs_block_group_cache *cache2;
1739 struct btrfs_key key;
1740 struct btrfs_path path;
1741 struct extent_io_tree io_tree;
1756 extent_io_tree_init(&io_tree);
1758 fd = open(devname, O_RDWR);
1760 error("unable to open %s: %s", devname, strerror(errno));
1763 root = open_ctree_fd(fd, devname, 0, OPEN_CTREE_WRITES);
1765 error("unable to open ctree");
1768 ret = may_rollback(root);
1770 error("unable to do rollback: %d", ret);
1774 sectorsize = root->sectorsize;
1775 buf = malloc(sectorsize);
1777 error("unable to allocate memory");
1781 btrfs_init_path(&path);
1783 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1784 key.type = BTRFS_ROOT_BACKREF_KEY;
1785 key.offset = BTRFS_FS_TREE_OBJECTID;
1786 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path, 0,
1788 btrfs_release_path(&path);
1790 error("unable to convert ext2 image subvolume, is it deleted?");
1792 } else if (ret < 0) {
1793 error("unable to open ext2_saved, id %llu: %s",
1794 (unsigned long long)key.objectid, strerror(-ret));
1798 key.objectid = CONV_IMAGE_SUBVOL_OBJECTID;
1799 key.type = BTRFS_ROOT_ITEM_KEY;
1800 key.offset = (u64)-1;
1801 image_root = btrfs_read_fs_root(root->fs_info, &key);
1802 if (!image_root || IS_ERR(image_root)) {
1803 error("unable to open subvolume %llu: %ld",
1804 (unsigned long long)key.objectid, PTR_ERR(image_root));
1809 root_dir = btrfs_root_dirid(&root->root_item);
1810 dir = btrfs_lookup_dir_item(NULL, image_root, &path,
1811 root_dir, name, strlen(name), 0);
1812 if (!dir || IS_ERR(dir)) {
1813 error("unable to find file %s: %ld", name, PTR_ERR(dir));
1816 leaf = path.nodes[0];
1817 btrfs_dir_item_key_to_cpu(leaf, dir, &key);
1818 btrfs_release_path(&path);
1820 objectid = key.objectid;
1822 ret = btrfs_lookup_inode(NULL, image_root, &path, &key, 0);
1824 error("unable to find inode item: %d", ret);
1827 leaf = path.nodes[0];
1828 inode = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_inode_item);
1829 total_bytes = btrfs_inode_size(leaf, inode);
1830 btrfs_release_path(&path);
1832 key.objectid = objectid;
1834 key.type = BTRFS_EXTENT_DATA_KEY;
1835 ret = btrfs_search_slot(NULL, image_root, &key, &path, 0, 0);
1837 error("unable to find first file extent: %d", ret);
1838 btrfs_release_path(&path);
1842 /* build mapping tree for the relocated blocks */
1843 for (offset = 0; offset < total_bytes; ) {
1844 leaf = path.nodes[0];
1845 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1846 ret = btrfs_next_leaf(root, &path);
1852 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1853 if (key.objectid != objectid || key.offset != offset ||
1854 key.type != BTRFS_EXTENT_DATA_KEY)
1857 fi = btrfs_item_ptr(leaf, path.slots[0],
1858 struct btrfs_file_extent_item);
1859 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
1861 if (btrfs_file_extent_compression(leaf, fi) ||
1862 btrfs_file_extent_encryption(leaf, fi) ||
1863 btrfs_file_extent_other_encoding(leaf, fi))
1866 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1867 /* skip holes and direct mapped extents */
1868 if (bytenr == 0 || bytenr == offset)
1871 bytenr += btrfs_file_extent_offset(leaf, fi);
1872 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
1874 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
1875 cache2 = btrfs_lookup_block_group(root->fs_info,
1876 offset + num_bytes - 1);
1878 * Here we must take consideration of old and new convert
1880 * For old convert case, sign, there is no consist chunk type
1881 * that will cover the extent. META/DATA/SYS are all possible.
1882 * Just ensure relocate one is in SYS chunk.
1883 * For new convert case, they are all covered by DATA chunk.
1885 * So, there is not valid chunk type check for it now.
1887 if (cache1 != cache2)
1890 set_extent_bits(&io_tree, offset, offset + num_bytes - 1,
1891 EXTENT_LOCKED, GFP_NOFS);
1892 set_state_private(&io_tree, offset, bytenr);
1894 offset += btrfs_file_extent_num_bytes(leaf, fi);
1897 btrfs_release_path(&path);
1899 if (offset < total_bytes) {
1900 error("unable to build extent mapping (offset %llu, total_bytes %llu)",
1901 (unsigned long long)offset,
1902 (unsigned long long)total_bytes);
1903 error("converted filesystem after balance is unable to rollback");
1907 first_free = BTRFS_SUPER_INFO_OFFSET + 2 * sectorsize - 1;
1908 first_free &= ~((u64)sectorsize - 1);
1909 /* backup for extent #0 should exist */
1910 if(!test_range_bit(&io_tree, 0, first_free - 1, EXTENT_LOCKED, 1)) {
1911 error("no backup for the first extent");
1914 /* force no allocation from system block group */
1915 root->fs_info->system_allocs = -1;
1916 trans = btrfs_start_transaction(root, 1);
1918 error("unable to start transaction");
1922 * recow the whole chunk tree, this will remove all chunk tree blocks
1923 * from system block group
1925 chunk_root = root->fs_info->chunk_root;
1926 memset(&key, 0, sizeof(key));
1928 ret = btrfs_search_slot(trans, chunk_root, &key, &path, 0, 1);
1932 ret = btrfs_next_leaf(chunk_root, &path);
1936 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
1937 btrfs_release_path(&path);
1939 btrfs_release_path(&path);
1944 cache1 = btrfs_lookup_block_group(root->fs_info, offset);
1948 if (cache1->flags & BTRFS_BLOCK_GROUP_SYSTEM)
1949 num_bytes += btrfs_block_group_used(&cache1->item);
1951 offset = cache1->key.objectid + cache1->key.offset;
1953 /* only extent #0 left in system block group? */
1954 if (num_bytes > first_free) {
1956 "unable to empty system block group (num_bytes %llu, first_free %llu",
1957 (unsigned long long)num_bytes,
1958 (unsigned long long)first_free);
1961 /* create a system chunk that maps the whole device */
1962 ret = prepare_system_chunk_sb(root->fs_info->super_copy);
1964 error("unable to update system chunk: %d", ret);
1968 ret = btrfs_commit_transaction(trans, root);
1970 error("transaction commit failed: %d", ret);
1974 ret = close_ctree(root);
1976 error("close_ctree failed: %d", ret);
1980 /* zero btrfs super block mirrors */
1981 memset(buf, 0, sectorsize);
1982 for (i = 1 ; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1983 bytenr = btrfs_sb_offset(i);
1984 if (bytenr >= total_bytes)
1986 ret = pwrite(fd, buf, sectorsize, bytenr);
1987 if (ret != sectorsize) {
1988 error("zeroing superblock mirror %d failed: %d",
1994 sb_bytenr = (u64)-1;
1995 /* copy all relocated blocks back */
1997 ret = find_first_extent_bit(&io_tree, 0, &start, &end,
2002 ret = get_state_private(&io_tree, start, &bytenr);
2005 clear_extent_bits(&io_tree, start, end, EXTENT_LOCKED,
2008 while (start <= end) {
2009 if (start == BTRFS_SUPER_INFO_OFFSET) {
2013 ret = pread(fd, buf, sectorsize, bytenr);
2015 error("reading superblock at %llu failed: %d",
2016 (unsigned long long)bytenr, ret);
2019 BUG_ON(ret != sectorsize);
2020 ret = pwrite(fd, buf, sectorsize, start);
2022 error("writing superblock at %llu failed: %d",
2023 (unsigned long long)start, ret);
2026 BUG_ON(ret != sectorsize);
2028 start += sectorsize;
2029 bytenr += sectorsize;
2035 error("fsync failed: %s", strerror(errno));
2039 * finally, overwrite btrfs super block.
2041 ret = pread(fd, buf, sectorsize, sb_bytenr);
2043 error("reading primary superblock failed: %s",
2047 BUG_ON(ret != sectorsize);
2048 ret = pwrite(fd, buf, sectorsize, BTRFS_SUPER_INFO_OFFSET);
2050 error("writing primary superblock failed: %s",
2054 BUG_ON(ret != sectorsize);
2057 error("fsync failed: %s", strerror(errno));
2063 extent_io_tree_cleanup(&io_tree);
2064 printf("rollback complete\n");
2071 error("rollback aborted");
2075 static void print_usage(void)
2077 printf("usage: btrfs-convert [options] device\n");
2078 printf("options:\n");
2079 printf("\t-d|--no-datasum disable data checksum, sets NODATASUM\n");
2080 printf("\t-i|--no-xattr ignore xattrs and ACLs\n");
2081 printf("\t-n|--no-inline disable inlining of small files to metadata\n");
2082 printf("\t-N|--nodesize SIZE set filesystem metadata nodesize\n");
2083 printf("\t-r|--rollback roll back to the original filesystem\n");
2084 printf("\t-l|--label LABEL set filesystem label\n");
2085 printf("\t-L|--copy-label use label from converted filesystem\n");
2086 printf("\t-p|--progress show converting progress (default)\n");
2087 printf("\t-O|--features LIST comma separated list of filesystem features\n");
2088 printf("\t--no-progress show only overview, not the detailed progress\n");
2090 printf("Supported filesystems:\n");
2091 printf("\text2/3/4: %s\n", BTRFSCONVERT_EXT2 ? "yes" : "no");
2094 int main(int argc, char *argv[])
2100 u32 nodesize = max_t(u32, sysconf(_SC_PAGESIZE),
2101 BTRFS_MKFS_DEFAULT_NODE_SIZE);
2104 int usage_error = 0;
2107 char fslabel[BTRFS_LABEL_SIZE];
2108 u64 features = BTRFS_MKFS_DEFAULT_FEATURES;
2111 enum { GETOPT_VAL_NO_PROGRESS = 256 };
2112 static const struct option long_options[] = {
2113 { "no-progress", no_argument, NULL,
2114 GETOPT_VAL_NO_PROGRESS },
2115 { "no-datasum", no_argument, NULL, 'd' },
2116 { "no-inline", no_argument, NULL, 'n' },
2117 { "no-xattr", no_argument, NULL, 'i' },
2118 { "rollback", no_argument, NULL, 'r' },
2119 { "features", required_argument, NULL, 'O' },
2120 { "progress", no_argument, NULL, 'p' },
2121 { "label", required_argument, NULL, 'l' },
2122 { "copy-label", no_argument, NULL, 'L' },
2123 { "nodesize", required_argument, NULL, 'N' },
2124 { "help", no_argument, NULL, GETOPT_VAL_HELP},
2125 { NULL, 0, NULL, 0 }
2127 int c = getopt_long(argc, argv, "dinN:rl:LpO:", long_options, NULL);
2142 nodesize = parse_size(optarg);
2149 if (strlen(optarg) >= BTRFS_LABEL_SIZE) {
2151 "label too long, trimmed to %d bytes",
2152 BTRFS_LABEL_SIZE - 1);
2154 __strncpy_null(fslabel, optarg, BTRFS_LABEL_SIZE - 1);
2163 char *orig = strdup(optarg);
2166 tmp = btrfs_parse_fs_features(tmp, &features);
2168 error("unrecognized filesystem feature: %s",
2174 if (features & BTRFS_FEATURE_LIST_ALL) {
2175 btrfs_list_all_fs_features(
2176 ~BTRFS_CONVERT_ALLOWED_FEATURES);
2179 if (features & ~BTRFS_CONVERT_ALLOWED_FEATURES) {
2182 btrfs_parse_features_to_string(buf,
2183 features & ~BTRFS_CONVERT_ALLOWED_FEATURES);
2184 error("features not allowed for convert: %s",
2191 case GETOPT_VAL_NO_PROGRESS:
2194 case GETOPT_VAL_HELP:
2197 return c != GETOPT_VAL_HELP;
2201 if (check_argc_exact(argc - optind, 1)) {
2206 if (rollback && (!datacsum || noxattr || !packing)) {
2208 "Usage error: -d, -i, -n options do not apply to rollback\n");
2217 file = argv[optind];
2218 ret = check_mounted(file);
2220 error("could not check mount status: %s", strerror(-ret));
2223 error("%s is mounted", file);
2228 ret = do_rollback(file);
2230 ret = do_convert(file, datacsum, packing, noxattr, nodesize,
2231 copylabel, fslabel, progress, features);