2 * Copyright (C) 2008 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.
22 #include <sys/types.h>
30 #include "kerncompat.h"
34 #include "transaction.h"
37 #include "extent_io.h"
39 #define HEADER_MAGIC 0xbd5c25e27295668bULL
40 #define MAX_PENDING_SIZE (256 * 1024)
41 #define BLOCK_SIZE 1024
42 #define BLOCK_MASK (BLOCK_SIZE - 1)
44 #define COMPRESS_NONE 0
45 #define COMPRESS_ZLIB 1
47 struct meta_cluster_item {
50 } __attribute__ ((__packed__));
52 struct meta_cluster_header {
57 } __attribute__ ((__packed__));
59 /* cluster header + index items + buffers */
61 struct meta_cluster_header header;
62 struct meta_cluster_item items[];
63 } __attribute__ ((__packed__));
65 #define ITEMS_PER_CLUSTER ((BLOCK_SIZE - sizeof(struct meta_cluster)) / \
66 sizeof(struct meta_cluster_item))
74 struct list_head list;
78 struct list_head list;
79 struct list_head ordered;
87 struct metadump_struct {
88 struct btrfs_root *root;
91 struct meta_cluster *cluster;
95 pthread_mutex_t mutex;
97 struct rb_root name_tree;
99 struct list_head list;
100 struct list_head ordered;
122 struct mdrestore_struct {
128 pthread_mutex_t mutex;
131 struct rb_root chunk_tree;
132 struct rb_root physical_tree;
133 struct list_head list;
134 struct list_head overlapping_chunks;
139 u64 last_physical_offset;
140 u8 uuid[BTRFS_UUID_SIZE];
141 u8 fsid[BTRFS_FSID_SIZE];
149 int clear_space_cache;
150 struct btrfs_fs_info *info;
153 static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
154 u64 search, u64 cluster_bytenr);
155 static struct extent_buffer *alloc_dummy_eb(u64 bytenr, u32 size);
157 static void csum_block(u8 *buf, size_t len)
159 char result[BTRFS_CRC32_SIZE];
161 crc = crc32c(crc, buf + BTRFS_CSUM_SIZE, len - BTRFS_CSUM_SIZE);
162 btrfs_csum_final(crc, result);
163 memcpy(buf, result, BTRFS_CRC32_SIZE);
166 static int has_name(struct btrfs_key *key)
169 case BTRFS_DIR_ITEM_KEY:
170 case BTRFS_DIR_INDEX_KEY:
171 case BTRFS_INODE_REF_KEY:
172 case BTRFS_INODE_EXTREF_KEY:
173 case BTRFS_XATTR_ITEM_KEY:
182 static char *generate_garbage(u32 name_len)
184 char *buf = malloc(name_len);
190 for (i = 0; i < name_len; i++) {
191 char c = rand() % 94 + 33;
201 static int name_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
203 struct name *entry = rb_entry(a, struct name, n);
204 struct name *ins = rb_entry(b, struct name, n);
207 len = min(ins->len, entry->len);
208 return memcmp(ins->val, entry->val, len);
211 static int chunk_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
213 struct fs_chunk *entry = rb_entry(a, struct fs_chunk, l);
214 struct fs_chunk *ins = rb_entry(b, struct fs_chunk, l);
216 if (fuzz && ins->logical >= entry->logical &&
217 ins->logical < entry->logical + entry->bytes)
220 if (ins->logical < entry->logical)
222 else if (ins->logical > entry->logical)
227 static int physical_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
229 struct fs_chunk *entry = rb_entry(a, struct fs_chunk, p);
230 struct fs_chunk *ins = rb_entry(b, struct fs_chunk, p);
232 if (fuzz && ins->physical >= entry->physical &&
233 ins->physical < entry->physical + entry->bytes)
236 if (fuzz && entry->physical >= ins->physical &&
237 entry->physical < ins->physical + ins->bytes)
240 if (ins->physical < entry->physical)
242 else if (ins->physical > entry->physical)
247 static void tree_insert(struct rb_root *root, struct rb_node *ins,
248 int (*cmp)(struct rb_node *a, struct rb_node *b,
251 struct rb_node ** p = &root->rb_node;
252 struct rb_node * parent = NULL;
258 dir = cmp(*p, ins, 1);
267 rb_link_node(ins, parent, p);
268 rb_insert_color(ins, root);
271 static struct rb_node *tree_search(struct rb_root *root,
272 struct rb_node *search,
273 int (*cmp)(struct rb_node *a,
274 struct rb_node *b, int fuzz),
277 struct rb_node *n = root->rb_node;
281 dir = cmp(n, search, fuzz);
293 static u64 logical_to_physical(struct mdrestore_struct *mdres, u64 logical, u64 *size)
295 struct fs_chunk *fs_chunk;
296 struct rb_node *entry;
297 struct fs_chunk search;
300 if (logical == BTRFS_SUPER_INFO_OFFSET)
303 search.logical = logical;
304 entry = tree_search(&mdres->chunk_tree, &search.l, chunk_cmp, 1);
306 if (mdres->in != stdin)
307 printf("Couldn't find a chunk, using logical\n");
310 fs_chunk = rb_entry(entry, struct fs_chunk, l);
311 if (fs_chunk->logical > logical || fs_chunk->logical + fs_chunk->bytes < logical)
313 offset = search.logical - fs_chunk->logical;
315 *size = min(*size, fs_chunk->bytes + fs_chunk->logical - logical);
316 return fs_chunk->physical + offset;
320 static char *find_collision(struct metadump_struct *md, char *name,
324 struct rb_node *entry;
326 unsigned long checksum;
332 entry = tree_search(&md->name_tree, &tmp.n, name_cmp, 0);
334 val = rb_entry(entry, struct name, n);
339 val = malloc(sizeof(struct name));
341 fprintf(stderr, "Couldn't sanitize name, enomem\n");
346 memset(val, 0, sizeof(*val));
350 val->sub = malloc(name_len);
352 fprintf(stderr, "Couldn't sanitize name, enomem\n");
358 checksum = crc32c(~1, val->val, name_len);
359 memset(val->sub, ' ', name_len);
362 if (crc32c(~1, val->sub, name_len) == checksum &&
363 memcmp(val->sub, val->val, val->len)) {
368 if (val->sub[i] == 127) {
373 } while (val->sub[i] == 127);
378 if (val->sub[i] == '/')
380 memset(val->sub, ' ', i);
385 if (val->sub[i] == '/')
391 fprintf(stderr, "Couldn't find a collision for '%.*s', "
392 "generating normal garbage, it won't match indexes\n",
394 for (i = 0; i < name_len; i++) {
395 char c = rand() % 94 + 33;
403 tree_insert(&md->name_tree, &val->n, name_cmp);
407 static void sanitize_dir_item(struct metadump_struct *md, struct extent_buffer *eb,
410 struct btrfs_dir_item *dir_item;
413 unsigned long name_ptr;
418 int free_garbage = (md->sanitize_names == 1);
420 dir_item = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
421 total_len = btrfs_item_size_nr(eb, slot);
422 while (cur < total_len) {
423 this_len = sizeof(*dir_item) +
424 btrfs_dir_name_len(eb, dir_item) +
425 btrfs_dir_data_len(eb, dir_item);
426 name_ptr = (unsigned long)(dir_item + 1);
427 name_len = btrfs_dir_name_len(eb, dir_item);
429 if (md->sanitize_names > 1) {
430 buf = malloc(name_len);
432 fprintf(stderr, "Couldn't sanitize name, "
436 read_extent_buffer(eb, buf, name_ptr, name_len);
437 garbage = find_collision(md, buf, name_len);
439 garbage = generate_garbage(name_len);
442 fprintf(stderr, "Couldn't sanitize name, enomem\n");
445 write_extent_buffer(eb, garbage, name_ptr, name_len);
447 dir_item = (struct btrfs_dir_item *)((char *)dir_item +
454 static void sanitize_inode_ref(struct metadump_struct *md,
455 struct extent_buffer *eb, int slot, int ext)
457 struct btrfs_inode_extref *extref;
458 struct btrfs_inode_ref *ref;
461 unsigned long name_ptr;
465 int free_garbage = (md->sanitize_names == 1);
467 item_size = btrfs_item_size_nr(eb, slot);
468 ptr = btrfs_item_ptr_offset(eb, slot);
469 while (cur_offset < item_size) {
471 extref = (struct btrfs_inode_extref *)(ptr +
473 name_ptr = (unsigned long)(&extref->name);
474 len = btrfs_inode_extref_name_len(eb, extref);
475 cur_offset += sizeof(*extref);
477 ref = (struct btrfs_inode_ref *)(ptr + cur_offset);
478 len = btrfs_inode_ref_name_len(eb, ref);
479 name_ptr = (unsigned long)(ref + 1);
480 cur_offset += sizeof(*ref);
484 if (md->sanitize_names > 1) {
487 fprintf(stderr, "Couldn't sanitize name, "
491 read_extent_buffer(eb, buf, name_ptr, len);
492 garbage = find_collision(md, buf, len);
494 garbage = generate_garbage(len);
498 fprintf(stderr, "Couldn't sanitize name, enomem\n");
501 write_extent_buffer(eb, garbage, name_ptr, len);
507 static void sanitize_xattr(struct metadump_struct *md,
508 struct extent_buffer *eb, int slot)
510 struct btrfs_dir_item *dir_item;
511 unsigned long data_ptr;
514 dir_item = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
515 data_len = btrfs_dir_data_len(eb, dir_item);
517 data_ptr = (unsigned long)((char *)(dir_item + 1) +
518 btrfs_dir_name_len(eb, dir_item));
519 memset_extent_buffer(eb, 0, data_ptr, data_len);
522 static void sanitize_name(struct metadump_struct *md, u8 *dst,
523 struct extent_buffer *src, struct btrfs_key *key,
526 struct extent_buffer *eb;
528 eb = alloc_dummy_eb(src->start, src->len);
530 fprintf(stderr, "Couldn't sanitize name, no memory\n");
534 memcpy(eb->data, dst, eb->len);
537 case BTRFS_DIR_ITEM_KEY:
538 case BTRFS_DIR_INDEX_KEY:
539 sanitize_dir_item(md, eb, slot);
541 case BTRFS_INODE_REF_KEY:
542 sanitize_inode_ref(md, eb, slot, 0);
544 case BTRFS_INODE_EXTREF_KEY:
545 sanitize_inode_ref(md, eb, slot, 1);
547 case BTRFS_XATTR_ITEM_KEY:
548 sanitize_xattr(md, eb, slot);
554 memcpy(dst, eb->data, eb->len);
559 * zero inline extents and csum items
561 static void zero_items(struct metadump_struct *md, u8 *dst,
562 struct extent_buffer *src)
564 struct btrfs_file_extent_item *fi;
565 struct btrfs_item *item;
566 struct btrfs_key key;
567 u32 nritems = btrfs_header_nritems(src);
572 for (i = 0; i < nritems; i++) {
573 item = btrfs_item_nr(i);
574 btrfs_item_key_to_cpu(src, &key, i);
575 if (key.type == BTRFS_CSUM_ITEM_KEY) {
576 size = btrfs_item_size_nr(src, i);
577 memset(dst + btrfs_leaf_data(src) +
578 btrfs_item_offset_nr(src, i), 0, size);
582 if (md->sanitize_names && has_name(&key)) {
583 sanitize_name(md, dst, src, &key, i);
587 if (key.type != BTRFS_EXTENT_DATA_KEY)
590 fi = btrfs_item_ptr(src, i, struct btrfs_file_extent_item);
591 extent_type = btrfs_file_extent_type(src, fi);
592 if (extent_type != BTRFS_FILE_EXTENT_INLINE)
595 ptr = btrfs_file_extent_inline_start(fi);
596 size = btrfs_file_extent_inline_item_len(src, item);
597 memset(dst + ptr, 0, size);
602 * copy buffer and zero useless data in the buffer
604 static void copy_buffer(struct metadump_struct *md, u8 *dst,
605 struct extent_buffer *src)
611 memcpy(dst, src->data, src->len);
612 if (src->start == BTRFS_SUPER_INFO_OFFSET)
615 level = btrfs_header_level(src);
616 nritems = btrfs_header_nritems(src);
619 size = sizeof(struct btrfs_header);
620 memset(dst + size, 0, src->len - size);
621 } else if (level == 0) {
622 size = btrfs_leaf_data(src) +
623 btrfs_item_offset_nr(src, nritems - 1) -
624 btrfs_item_nr_offset(nritems);
625 memset(dst + btrfs_item_nr_offset(nritems), 0, size);
626 zero_items(md, dst, src);
628 size = offsetof(struct btrfs_node, ptrs) +
629 sizeof(struct btrfs_key_ptr) * nritems;
630 memset(dst + size, 0, src->len - size);
632 csum_block(dst, src->len);
635 static void *dump_worker(void *data)
637 struct metadump_struct *md = (struct metadump_struct *)data;
638 struct async_work *async;
642 pthread_mutex_lock(&md->mutex);
643 while (list_empty(&md->list)) {
645 pthread_mutex_unlock(&md->mutex);
648 pthread_cond_wait(&md->cond, &md->mutex);
650 async = list_entry(md->list.next, struct async_work, list);
651 list_del_init(&async->list);
652 pthread_mutex_unlock(&md->mutex);
654 if (md->compress_level > 0) {
655 u8 *orig = async->buffer;
657 async->bufsize = compressBound(async->size);
658 async->buffer = malloc(async->bufsize);
659 if (!async->buffer) {
660 fprintf(stderr, "Error allocing buffer\n");
661 pthread_mutex_lock(&md->mutex);
664 pthread_mutex_unlock(&md->mutex);
668 ret = compress2(async->buffer,
669 (unsigned long *)&async->bufsize,
670 orig, async->size, md->compress_level);
678 pthread_mutex_lock(&md->mutex);
680 pthread_mutex_unlock(&md->mutex);
686 static void meta_cluster_init(struct metadump_struct *md, u64 start)
688 struct meta_cluster_header *header;
692 header = &md->cluster->header;
693 header->magic = cpu_to_le64(HEADER_MAGIC);
694 header->bytenr = cpu_to_le64(start);
695 header->nritems = cpu_to_le32(0);
696 header->compress = md->compress_level > 0 ?
697 COMPRESS_ZLIB : COMPRESS_NONE;
700 static void metadump_destroy(struct metadump_struct *md, int num_threads)
705 pthread_mutex_lock(&md->mutex);
707 pthread_cond_broadcast(&md->cond);
708 pthread_mutex_unlock(&md->mutex);
710 for (i = 0; i < num_threads; i++)
711 pthread_join(md->threads[i], NULL);
713 pthread_cond_destroy(&md->cond);
714 pthread_mutex_destroy(&md->mutex);
716 while ((n = rb_first(&md->name_tree))) {
719 name = rb_entry(n, struct name, n);
720 rb_erase(n, &md->name_tree);
729 static int metadump_init(struct metadump_struct *md, struct btrfs_root *root,
730 FILE *out, int num_threads, int compress_level,
735 memset(md, 0, sizeof(*md));
736 md->cluster = calloc(1, BLOCK_SIZE);
739 md->threads = calloc(num_threads, sizeof(pthread_t));
744 INIT_LIST_HEAD(&md->list);
745 INIT_LIST_HEAD(&md->ordered);
748 md->pending_start = (u64)-1;
749 md->compress_level = compress_level;
750 md->sanitize_names = sanitize_names;
751 if (sanitize_names > 1)
752 crc32c_optimization_init();
754 md->name_tree.rb_node = NULL;
755 md->num_threads = num_threads;
756 pthread_cond_init(&md->cond, NULL);
757 pthread_mutex_init(&md->mutex, NULL);
758 meta_cluster_init(md, 0);
763 for (i = 0; i < num_threads; i++) {
764 ret = pthread_create(md->threads + i, NULL, dump_worker, md);
770 metadump_destroy(md, i + 1);
775 static int write_zero(FILE *out, size_t size)
777 static char zero[BLOCK_SIZE];
778 return fwrite(zero, size, 1, out);
781 static int write_buffers(struct metadump_struct *md, u64 *next)
783 struct meta_cluster_header *header = &md->cluster->header;
784 struct meta_cluster_item *item;
785 struct async_work *async;
791 if (list_empty(&md->ordered))
794 /* wait until all buffers are compressed */
795 while (!err && md->num_items > md->num_ready) {
796 struct timespec ts = {
800 pthread_mutex_unlock(&md->mutex);
801 nanosleep(&ts, NULL);
802 pthread_mutex_lock(&md->mutex);
807 fprintf(stderr, "One of the threads errored out %s\n",
812 /* setup and write index block */
813 list_for_each_entry(async, &md->ordered, ordered) {
814 item = md->cluster->items + nritems;
815 item->bytenr = cpu_to_le64(async->start);
816 item->size = cpu_to_le32(async->bufsize);
819 header->nritems = cpu_to_le32(nritems);
821 ret = fwrite(md->cluster, BLOCK_SIZE, 1, md->out);
823 fprintf(stderr, "Error writing out cluster: %d\n", errno);
828 bytenr += le64_to_cpu(header->bytenr) + BLOCK_SIZE;
829 while (!list_empty(&md->ordered)) {
830 async = list_entry(md->ordered.next, struct async_work,
832 list_del_init(&async->ordered);
834 bytenr += async->bufsize;
836 ret = fwrite(async->buffer, async->bufsize, 1,
841 fprintf(stderr, "Error writing out cluster: %d\n",
849 /* zero unused space in the last block */
850 if (!err && bytenr & BLOCK_MASK) {
851 size_t size = BLOCK_SIZE - (bytenr & BLOCK_MASK);
854 ret = write_zero(md->out, size);
856 fprintf(stderr, "Error zeroing out buffer: %d\n",
866 static int read_data_extent(struct metadump_struct *md,
867 struct async_work *async)
869 struct btrfs_root *root = md->root;
870 u64 bytes_left = async->size;
871 u64 logical = async->start;
878 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree, logical,
881 /* Try our best to read data, just like read_tree_block() */
882 for (cur_mirror = 0; cur_mirror < num_copies; cur_mirror++) {
884 read_len = bytes_left;
885 ret = read_extent_data(root,
886 (char *)(async->buffer + offset),
887 logical, &read_len, cur_mirror);
892 bytes_left -= read_len;
900 static int get_dev_fd(struct btrfs_root *root)
902 struct btrfs_device *dev;
904 dev = list_first_entry(&root->fs_info->fs_devices->devices,
905 struct btrfs_device, dev_list);
909 static int flush_pending(struct metadump_struct *md, int done)
911 struct async_work *async = NULL;
912 struct extent_buffer *eb;
913 u64 blocksize = md->root->nodesize;
919 if (md->pending_size) {
920 async = calloc(1, sizeof(*async));
924 async->start = md->pending_start;
925 async->size = md->pending_size;
926 async->bufsize = async->size;
927 async->buffer = malloc(async->bufsize);
928 if (!async->buffer) {
933 start = async->start;
937 ret = read_data_extent(md, async);
946 * Balance can make the mapping not cover the super block, so
947 * just copy directly from one of the devices.
949 if (start == BTRFS_SUPER_INFO_OFFSET) {
950 int fd = get_dev_fd(md->root);
952 ret = pread64(fd, async->buffer, size, start);
956 fprintf(stderr, "Error reading superblock\n");
963 while (!md->data && size > 0) {
964 u64 this_read = min(blocksize, size);
965 eb = read_tree_block(md->root, start, this_read, 0);
966 if (!extent_buffer_uptodate(eb)) {
970 "Error reading metadata block\n");
973 copy_buffer(md, async->buffer + offset, eb);
974 free_extent_buffer(eb);
980 md->pending_start = (u64)-1;
981 md->pending_size = 0;
986 pthread_mutex_lock(&md->mutex);
988 list_add_tail(&async->ordered, &md->ordered);
990 if (md->compress_level > 0) {
991 list_add_tail(&async->list, &md->list);
992 pthread_cond_signal(&md->cond);
997 if (md->num_items >= ITEMS_PER_CLUSTER || done) {
998 ret = write_buffers(md, &start);
1000 fprintf(stderr, "Error writing buffers %d\n",
1003 meta_cluster_init(md, start);
1005 pthread_mutex_unlock(&md->mutex);
1009 static int add_extent(u64 start, u64 size, struct metadump_struct *md,
1013 if (md->data != data ||
1014 md->pending_size + size > MAX_PENDING_SIZE ||
1015 md->pending_start + md->pending_size != start) {
1016 ret = flush_pending(md, 0);
1019 md->pending_start = start;
1021 readahead_tree_block(md->root, start, size, 0);
1022 md->pending_size += size;
1027 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1028 static int is_tree_block(struct btrfs_root *extent_root,
1029 struct btrfs_path *path, u64 bytenr)
1031 struct extent_buffer *leaf;
1032 struct btrfs_key key;
1036 leaf = path->nodes[0];
1038 struct btrfs_extent_ref_v0 *ref_item;
1040 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1041 ret = btrfs_next_leaf(extent_root, path);
1046 leaf = path->nodes[0];
1048 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1049 if (key.objectid != bytenr)
1051 if (key.type != BTRFS_EXTENT_REF_V0_KEY)
1053 ref_item = btrfs_item_ptr(leaf, path->slots[0],
1054 struct btrfs_extent_ref_v0);
1055 ref_objectid = btrfs_ref_objectid_v0(leaf, ref_item);
1056 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID)
1064 static int copy_tree_blocks(struct btrfs_root *root, struct extent_buffer *eb,
1065 struct metadump_struct *metadump, int root_tree)
1067 struct extent_buffer *tmp;
1068 struct btrfs_root_item *ri;
1069 struct btrfs_key key;
1076 ret = add_extent(btrfs_header_bytenr(eb), root->leafsize, metadump, 0);
1078 fprintf(stderr, "Error adding metadata block\n");
1082 if (btrfs_header_level(eb) == 0 && !root_tree)
1085 level = btrfs_header_level(eb);
1086 nritems = btrfs_header_nritems(eb);
1087 for (i = 0; i < nritems; i++) {
1089 btrfs_item_key_to_cpu(eb, &key, i);
1090 if (key.type != BTRFS_ROOT_ITEM_KEY)
1092 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
1093 bytenr = btrfs_disk_root_bytenr(eb, ri);
1094 tmp = read_tree_block(root, bytenr, root->leafsize, 0);
1095 if (!extent_buffer_uptodate(tmp)) {
1097 "Error reading log root block\n");
1100 ret = copy_tree_blocks(root, tmp, metadump, 0);
1101 free_extent_buffer(tmp);
1105 bytenr = btrfs_node_blockptr(eb, i);
1106 tmp = read_tree_block(root, bytenr, root->leafsize, 0);
1107 if (!extent_buffer_uptodate(tmp)) {
1108 fprintf(stderr, "Error reading log block\n");
1111 ret = copy_tree_blocks(root, tmp, metadump, root_tree);
1112 free_extent_buffer(tmp);
1121 static int copy_log_trees(struct btrfs_root *root,
1122 struct metadump_struct *metadump,
1123 struct btrfs_path *path)
1125 u64 blocknr = btrfs_super_log_root(root->fs_info->super_copy);
1130 if (!root->fs_info->log_root_tree ||
1131 !root->fs_info->log_root_tree->node) {
1132 fprintf(stderr, "Error copying tree log, it wasn't setup\n");
1136 return copy_tree_blocks(root, root->fs_info->log_root_tree->node,
1140 static int copy_space_cache(struct btrfs_root *root,
1141 struct metadump_struct *metadump,
1142 struct btrfs_path *path)
1144 struct extent_buffer *leaf;
1145 struct btrfs_file_extent_item *fi;
1146 struct btrfs_key key;
1147 u64 bytenr, num_bytes;
1150 root = root->fs_info->tree_root;
1153 key.type = BTRFS_EXTENT_DATA_KEY;
1156 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1158 fprintf(stderr, "Error searching for free space inode %d\n",
1163 leaf = path->nodes[0];
1166 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1167 ret = btrfs_next_leaf(root, path);
1169 fprintf(stderr, "Error going to next leaf "
1175 leaf = path->nodes[0];
1178 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1179 if (key.type != BTRFS_EXTENT_DATA_KEY) {
1184 fi = btrfs_item_ptr(leaf, path->slots[0],
1185 struct btrfs_file_extent_item);
1186 if (btrfs_file_extent_type(leaf, fi) !=
1187 BTRFS_FILE_EXTENT_REG) {
1192 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1193 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1194 ret = add_extent(bytenr, num_bytes, metadump, 1);
1196 fprintf(stderr, "Error adding space cache blocks %d\n",
1198 btrfs_release_path(path);
1207 static int copy_from_extent_tree(struct metadump_struct *metadump,
1208 struct btrfs_path *path)
1210 struct btrfs_root *extent_root;
1211 struct extent_buffer *leaf;
1212 struct btrfs_extent_item *ei;
1213 struct btrfs_key key;
1218 extent_root = metadump->root->fs_info->extent_root;
1219 bytenr = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
1220 key.objectid = bytenr;
1221 key.type = BTRFS_EXTENT_ITEM_KEY;
1224 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1226 fprintf(stderr, "Error searching extent root %d\n", ret);
1231 leaf = path->nodes[0];
1234 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1235 ret = btrfs_next_leaf(extent_root, path);
1237 fprintf(stderr, "Error going to next leaf %d"
1245 leaf = path->nodes[0];
1248 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1249 if (key.objectid < bytenr ||
1250 (key.type != BTRFS_EXTENT_ITEM_KEY &&
1251 key.type != BTRFS_METADATA_ITEM_KEY)) {
1256 bytenr = key.objectid;
1257 if (key.type == BTRFS_METADATA_ITEM_KEY)
1258 num_bytes = extent_root->leafsize;
1260 num_bytes = key.offset;
1262 if (btrfs_item_size_nr(leaf, path->slots[0]) > sizeof(*ei)) {
1263 ei = btrfs_item_ptr(leaf, path->slots[0],
1264 struct btrfs_extent_item);
1265 if (btrfs_extent_flags(leaf, ei) &
1266 BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1267 ret = add_extent(bytenr, num_bytes, metadump,
1270 fprintf(stderr, "Error adding block "
1276 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1277 ret = is_tree_block(extent_root, path, bytenr);
1279 fprintf(stderr, "Error checking tree block "
1285 ret = add_extent(bytenr, num_bytes, metadump,
1288 fprintf(stderr, "Error adding block "
1295 fprintf(stderr, "Either extent tree corruption or "
1296 "you haven't built with V0 support\n");
1301 bytenr += num_bytes;
1304 btrfs_release_path(path);
1309 static int create_metadump(const char *input, FILE *out, int num_threads,
1310 int compress_level, int sanitize, int walk_trees)
1312 struct btrfs_root *root;
1313 struct btrfs_path *path = NULL;
1314 struct metadump_struct metadump;
1318 root = open_ctree(input, 0, 0);
1320 fprintf(stderr, "Open ctree failed\n");
1324 BUG_ON(root->nodesize != root->leafsize);
1326 ret = metadump_init(&metadump, root, out, num_threads,
1327 compress_level, sanitize);
1329 fprintf(stderr, "Error initing metadump %d\n", ret);
1334 ret = add_extent(BTRFS_SUPER_INFO_OFFSET, BTRFS_SUPER_INFO_SIZE,
1337 fprintf(stderr, "Error adding metadata %d\n", ret);
1342 path = btrfs_alloc_path();
1344 fprintf(stderr, "Out of memory allocing path\n");
1350 ret = copy_tree_blocks(root, root->fs_info->chunk_root->node,
1357 ret = copy_tree_blocks(root, root->fs_info->tree_root->node,
1364 ret = copy_from_extent_tree(&metadump, path);
1371 ret = copy_log_trees(root, &metadump, path);
1377 ret = copy_space_cache(root, &metadump, path);
1379 ret = flush_pending(&metadump, 1);
1383 fprintf(stderr, "Error flushing pending %d\n", ret);
1386 metadump_destroy(&metadump, num_threads);
1388 btrfs_free_path(path);
1389 ret = close_ctree(root);
1390 return err ? err : ret;
1393 static void update_super_old(u8 *buffer)
1395 struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
1396 struct btrfs_chunk *chunk;
1397 struct btrfs_disk_key *key;
1398 u32 sectorsize = btrfs_super_sectorsize(super);
1399 u64 flags = btrfs_super_flags(super);
1401 flags |= BTRFS_SUPER_FLAG_METADUMP;
1402 btrfs_set_super_flags(super, flags);
1404 key = (struct btrfs_disk_key *)(super->sys_chunk_array);
1405 chunk = (struct btrfs_chunk *)(super->sys_chunk_array +
1406 sizeof(struct btrfs_disk_key));
1408 btrfs_set_disk_key_objectid(key, BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1409 btrfs_set_disk_key_type(key, BTRFS_CHUNK_ITEM_KEY);
1410 btrfs_set_disk_key_offset(key, 0);
1412 btrfs_set_stack_chunk_length(chunk, (u64)-1);
1413 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
1414 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
1415 btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
1416 btrfs_set_stack_chunk_io_align(chunk, sectorsize);
1417 btrfs_set_stack_chunk_io_width(chunk, sectorsize);
1418 btrfs_set_stack_chunk_sector_size(chunk, sectorsize);
1419 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1420 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1421 chunk->stripe.devid = super->dev_item.devid;
1422 btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
1423 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
1424 btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
1425 csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
1428 static int update_super(struct mdrestore_struct *mdres, u8 *buffer)
1430 struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
1431 struct btrfs_chunk *chunk;
1432 struct btrfs_disk_key *disk_key;
1433 struct btrfs_key key;
1434 u64 flags = btrfs_super_flags(super);
1435 u32 new_array_size = 0;
1438 u8 *ptr, *write_ptr;
1439 int old_num_stripes;
1441 write_ptr = ptr = super->sys_chunk_array;
1442 array_size = btrfs_super_sys_array_size(super);
1444 while (cur < array_size) {
1445 disk_key = (struct btrfs_disk_key *)ptr;
1446 btrfs_disk_key_to_cpu(&key, disk_key);
1448 new_array_size += sizeof(*disk_key);
1449 memmove(write_ptr, ptr, sizeof(*disk_key));
1451 write_ptr += sizeof(*disk_key);
1452 ptr += sizeof(*disk_key);
1453 cur += sizeof(*disk_key);
1455 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
1456 u64 physical, size = 0;
1458 chunk = (struct btrfs_chunk *)ptr;
1459 old_num_stripes = btrfs_stack_chunk_num_stripes(chunk);
1460 chunk = (struct btrfs_chunk *)write_ptr;
1462 memmove(write_ptr, ptr, sizeof(*chunk));
1463 btrfs_set_stack_chunk_num_stripes(chunk, 1);
1464 btrfs_set_stack_chunk_sub_stripes(chunk, 0);
1465 btrfs_set_stack_chunk_type(chunk,
1466 BTRFS_BLOCK_GROUP_SYSTEM);
1467 chunk->stripe.devid = super->dev_item.devid;
1468 physical = logical_to_physical(mdres, key.offset,
1470 if (size != (u64)-1)
1471 btrfs_set_stack_stripe_offset(&chunk->stripe,
1473 memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid,
1475 new_array_size += sizeof(*chunk);
1477 fprintf(stderr, "Bogus key in the sys chunk array "
1481 write_ptr += sizeof(*chunk);
1482 ptr += btrfs_chunk_item_size(old_num_stripes);
1483 cur += btrfs_chunk_item_size(old_num_stripes);
1486 if (mdres->clear_space_cache)
1487 btrfs_set_super_cache_generation(super, 0);
1489 flags |= BTRFS_SUPER_FLAG_METADUMP_V2;
1490 btrfs_set_super_flags(super, flags);
1491 btrfs_set_super_sys_array_size(super, new_array_size);
1492 csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
1497 static struct extent_buffer *alloc_dummy_eb(u64 bytenr, u32 size)
1499 struct extent_buffer *eb;
1501 eb = calloc(1, sizeof(struct extent_buffer) + size);
1510 static void truncate_item(struct extent_buffer *eb, int slot, u32 new_size)
1512 struct btrfs_item *item;
1520 old_size = btrfs_item_size_nr(eb, slot);
1521 if (old_size == new_size)
1524 nritems = btrfs_header_nritems(eb);
1525 data_end = btrfs_item_offset_nr(eb, nritems - 1);
1527 old_data_start = btrfs_item_offset_nr(eb, slot);
1528 size_diff = old_size - new_size;
1530 for (i = slot; i < nritems; i++) {
1532 item = btrfs_item_nr(i);
1533 ioff = btrfs_item_offset(eb, item);
1534 btrfs_set_item_offset(eb, item, ioff + size_diff);
1537 memmove_extent_buffer(eb, btrfs_leaf_data(eb) + data_end + size_diff,
1538 btrfs_leaf_data(eb) + data_end,
1539 old_data_start + new_size - data_end);
1540 item = btrfs_item_nr(slot);
1541 btrfs_set_item_size(eb, item, new_size);
1544 static int fixup_chunk_tree_block(struct mdrestore_struct *mdres,
1545 struct async_work *async, u8 *buffer,
1548 struct extent_buffer *eb;
1549 size_t size_left = size;
1550 u64 bytenr = async->start;
1553 if (size_left % mdres->leafsize)
1556 eb = alloc_dummy_eb(bytenr, mdres->leafsize);
1562 memcpy(eb->data, buffer, mdres->leafsize);
1564 if (btrfs_header_bytenr(eb) != bytenr)
1566 if (memcmp(mdres->fsid,
1567 eb->data + offsetof(struct btrfs_header, fsid),
1571 if (btrfs_header_owner(eb) != BTRFS_CHUNK_TREE_OBJECTID)
1574 if (btrfs_header_level(eb) != 0)
1577 for (i = 0; i < btrfs_header_nritems(eb); i++) {
1578 struct btrfs_chunk chunk;
1579 struct btrfs_key key;
1580 u64 type, physical, size = (u64)-1;
1582 btrfs_item_key_to_cpu(eb, &key, i);
1583 if (key.type != BTRFS_CHUNK_ITEM_KEY)
1585 truncate_item(eb, i, sizeof(chunk));
1586 read_extent_buffer(eb, &chunk,
1587 btrfs_item_ptr_offset(eb, i),
1591 physical = logical_to_physical(mdres, key.offset,
1594 /* Zero out the RAID profile */
1595 type = btrfs_stack_chunk_type(&chunk);
1596 type &= (BTRFS_BLOCK_GROUP_DATA |
1597 BTRFS_BLOCK_GROUP_SYSTEM |
1598 BTRFS_BLOCK_GROUP_METADATA |
1599 BTRFS_BLOCK_GROUP_DUP);
1600 btrfs_set_stack_chunk_type(&chunk, type);
1602 btrfs_set_stack_chunk_num_stripes(&chunk, 1);
1603 btrfs_set_stack_chunk_sub_stripes(&chunk, 0);
1604 btrfs_set_stack_stripe_devid(&chunk.stripe, mdres->devid);
1605 if (size != (u64)-1)
1606 btrfs_set_stack_stripe_offset(&chunk.stripe,
1608 memcpy(chunk.stripe.dev_uuid, mdres->uuid,
1610 write_extent_buffer(eb, &chunk,
1611 btrfs_item_ptr_offset(eb, i),
1614 memcpy(buffer, eb->data, eb->len);
1615 csum_block(buffer, eb->len);
1617 size_left -= mdres->leafsize;
1618 buffer += mdres->leafsize;
1619 bytenr += mdres->leafsize;
1626 static void write_backup_supers(int fd, u8 *buf)
1628 struct btrfs_super_block *super = (struct btrfs_super_block *)buf;
1635 if (fstat(fd, &st)) {
1636 fprintf(stderr, "Couldn't stat restore point, won't be able "
1637 "to write backup supers: %d\n", errno);
1641 size = btrfs_device_size(fd, &st);
1643 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1644 bytenr = btrfs_sb_offset(i);
1645 if (bytenr + BTRFS_SUPER_INFO_SIZE > size)
1647 btrfs_set_super_bytenr(super, bytenr);
1648 csum_block(buf, BTRFS_SUPER_INFO_SIZE);
1649 ret = pwrite64(fd, buf, BTRFS_SUPER_INFO_SIZE, bytenr);
1650 if (ret < BTRFS_SUPER_INFO_SIZE) {
1652 fprintf(stderr, "Problem writing out backup "
1653 "super block %d, err %d\n", i, errno);
1655 fprintf(stderr, "Short write writing out "
1656 "backup super block\n");
1662 static void *restore_worker(void *data)
1664 struct mdrestore_struct *mdres = (struct mdrestore_struct *)data;
1665 struct async_work *async;
1671 int compress_size = MAX_PENDING_SIZE * 4;
1673 outfd = fileno(mdres->out);
1674 buffer = malloc(compress_size);
1676 fprintf(stderr, "Error allocing buffer\n");
1677 pthread_mutex_lock(&mdres->mutex);
1679 mdres->error = -ENOMEM;
1680 pthread_mutex_unlock(&mdres->mutex);
1689 pthread_mutex_lock(&mdres->mutex);
1690 while (!mdres->leafsize || list_empty(&mdres->list)) {
1692 pthread_mutex_unlock(&mdres->mutex);
1695 pthread_cond_wait(&mdres->cond, &mdres->mutex);
1697 async = list_entry(mdres->list.next, struct async_work, list);
1698 list_del_init(&async->list);
1699 pthread_mutex_unlock(&mdres->mutex);
1701 if (mdres->compress_method == COMPRESS_ZLIB) {
1702 size = compress_size;
1703 ret = uncompress(buffer, (unsigned long *)&size,
1704 async->buffer, async->bufsize);
1706 fprintf(stderr, "Error decompressing %d\n",
1712 outbuf = async->buffer;
1713 size = async->bufsize;
1716 if (!mdres->multi_devices) {
1717 if (async->start == BTRFS_SUPER_INFO_OFFSET) {
1718 if (mdres->old_restore) {
1719 update_super_old(outbuf);
1721 ret = update_super(mdres, outbuf);
1725 } else if (!mdres->old_restore) {
1726 ret = fixup_chunk_tree_block(mdres, async, outbuf, size);
1732 if (!mdres->fixup_offset) {
1734 u64 chunk_size = size;
1735 if (!mdres->multi_devices && !mdres->old_restore)
1736 bytenr = logical_to_physical(mdres,
1737 async->start + offset,
1740 bytenr = async->start + offset;
1742 ret = pwrite64(outfd, outbuf+offset, chunk_size,
1744 if (ret != chunk_size) {
1746 fprintf(stderr, "Error writing to "
1747 "device %d\n", errno);
1751 fprintf(stderr, "Short write\n");
1757 offset += chunk_size;
1759 } else if (async->start != BTRFS_SUPER_INFO_OFFSET) {
1760 ret = write_data_to_disk(mdres->info, outbuf, async->start, size, 0);
1762 printk("Error write data\n");
1768 /* backup super blocks are already there at fixup_offset stage */
1769 if (!mdres->multi_devices && async->start == BTRFS_SUPER_INFO_OFFSET)
1770 write_backup_supers(outfd, outbuf);
1772 pthread_mutex_lock(&mdres->mutex);
1773 if (err && !mdres->error)
1776 pthread_mutex_unlock(&mdres->mutex);
1778 free(async->buffer);
1786 static void mdrestore_destroy(struct mdrestore_struct *mdres, int num_threads)
1791 while ((n = rb_first(&mdres->chunk_tree))) {
1792 struct fs_chunk *entry;
1794 entry = rb_entry(n, struct fs_chunk, l);
1795 rb_erase(n, &mdres->chunk_tree);
1796 rb_erase(&entry->p, &mdres->physical_tree);
1799 pthread_mutex_lock(&mdres->mutex);
1801 pthread_cond_broadcast(&mdres->cond);
1802 pthread_mutex_unlock(&mdres->mutex);
1804 for (i = 0; i < num_threads; i++)
1805 pthread_join(mdres->threads[i], NULL);
1807 pthread_cond_destroy(&mdres->cond);
1808 pthread_mutex_destroy(&mdres->mutex);
1809 free(mdres->threads);
1812 static int mdrestore_init(struct mdrestore_struct *mdres,
1813 FILE *in, FILE *out, int old_restore,
1814 int num_threads, int fixup_offset,
1815 struct btrfs_fs_info *info, int multi_devices)
1819 memset(mdres, 0, sizeof(*mdres));
1820 pthread_cond_init(&mdres->cond, NULL);
1821 pthread_mutex_init(&mdres->mutex, NULL);
1822 INIT_LIST_HEAD(&mdres->list);
1823 INIT_LIST_HEAD(&mdres->overlapping_chunks);
1826 mdres->old_restore = old_restore;
1827 mdres->chunk_tree.rb_node = NULL;
1828 mdres->fixup_offset = fixup_offset;
1830 mdres->multi_devices = multi_devices;
1831 mdres->clear_space_cache = 0;
1832 mdres->last_physical_offset = 0;
1833 mdres->alloced_chunks = 0;
1838 mdres->num_threads = num_threads;
1839 mdres->threads = calloc(num_threads, sizeof(pthread_t));
1840 if (!mdres->threads)
1842 for (i = 0; i < num_threads; i++) {
1843 ret = pthread_create(mdres->threads + i, NULL, restore_worker,
1849 mdrestore_destroy(mdres, i + 1);
1853 static int fill_mdres_info(struct mdrestore_struct *mdres,
1854 struct async_work *async)
1856 struct btrfs_super_block *super;
1861 /* We've already been initialized */
1862 if (mdres->leafsize)
1865 if (mdres->compress_method == COMPRESS_ZLIB) {
1866 size_t size = MAX_PENDING_SIZE * 2;
1868 buffer = malloc(MAX_PENDING_SIZE * 2);
1871 ret = uncompress(buffer, (unsigned long *)&size,
1872 async->buffer, async->bufsize);
1874 fprintf(stderr, "Error decompressing %d\n", ret);
1880 outbuf = async->buffer;
1883 super = (struct btrfs_super_block *)outbuf;
1884 mdres->leafsize = btrfs_super_leafsize(super);
1885 memcpy(mdres->fsid, super->fsid, BTRFS_FSID_SIZE);
1886 memcpy(mdres->uuid, super->dev_item.uuid,
1888 mdres->devid = le64_to_cpu(super->dev_item.devid);
1893 static int add_cluster(struct meta_cluster *cluster,
1894 struct mdrestore_struct *mdres, u64 *next)
1896 struct meta_cluster_item *item;
1897 struct meta_cluster_header *header = &cluster->header;
1898 struct async_work *async;
1903 mdres->compress_method = header->compress;
1905 bytenr = le64_to_cpu(header->bytenr) + BLOCK_SIZE;
1906 nritems = le32_to_cpu(header->nritems);
1907 for (i = 0; i < nritems; i++) {
1908 item = &cluster->items[i];
1909 async = calloc(1, sizeof(*async));
1911 fprintf(stderr, "Error allocating async\n");
1914 async->start = le64_to_cpu(item->bytenr);
1915 async->bufsize = le32_to_cpu(item->size);
1916 async->buffer = malloc(async->bufsize);
1917 if (!async->buffer) {
1918 fprintf(stderr, "Error allocing async buffer\n");
1922 ret = fread(async->buffer, async->bufsize, 1, mdres->in);
1924 fprintf(stderr, "Error reading buffer %d\n", errno);
1925 free(async->buffer);
1929 bytenr += async->bufsize;
1931 pthread_mutex_lock(&mdres->mutex);
1932 if (async->start == BTRFS_SUPER_INFO_OFFSET) {
1933 ret = fill_mdres_info(mdres, async);
1935 fprintf(stderr, "Error setting up restore\n");
1936 pthread_mutex_unlock(&mdres->mutex);
1937 free(async->buffer);
1942 list_add_tail(&async->list, &mdres->list);
1944 pthread_cond_signal(&mdres->cond);
1945 pthread_mutex_unlock(&mdres->mutex);
1947 if (bytenr & BLOCK_MASK) {
1948 char buffer[BLOCK_MASK];
1949 size_t size = BLOCK_SIZE - (bytenr & BLOCK_MASK);
1952 ret = fread(buffer, size, 1, mdres->in);
1954 fprintf(stderr, "Error reading in buffer %d\n", errno);
1962 static int wait_for_worker(struct mdrestore_struct *mdres)
1966 pthread_mutex_lock(&mdres->mutex);
1968 while (!ret && mdres->num_items > 0) {
1969 struct timespec ts = {
1971 .tv_nsec = 10000000,
1973 pthread_mutex_unlock(&mdres->mutex);
1974 nanosleep(&ts, NULL);
1975 pthread_mutex_lock(&mdres->mutex);
1978 pthread_mutex_unlock(&mdres->mutex);
1982 static int read_chunk_block(struct mdrestore_struct *mdres, u8 *buffer,
1983 u64 bytenr, u64 item_bytenr, u32 bufsize,
1986 struct extent_buffer *eb;
1990 eb = alloc_dummy_eb(bytenr, mdres->leafsize);
1996 while (item_bytenr != bytenr) {
1997 buffer += mdres->leafsize;
1998 item_bytenr += mdres->leafsize;
2001 memcpy(eb->data, buffer, mdres->leafsize);
2002 if (btrfs_header_bytenr(eb) != bytenr) {
2003 fprintf(stderr, "Eb bytenr doesn't match found bytenr\n");
2008 if (memcmp(mdres->fsid, eb->data + offsetof(struct btrfs_header, fsid),
2010 fprintf(stderr, "Fsid doesn't match\n");
2015 if (btrfs_header_owner(eb) != BTRFS_CHUNK_TREE_OBJECTID) {
2016 fprintf(stderr, "Does not belong to the chunk tree\n");
2021 for (i = 0; i < btrfs_header_nritems(eb); i++) {
2022 struct btrfs_chunk chunk;
2023 struct fs_chunk *fs_chunk;
2024 struct btrfs_key key;
2026 if (btrfs_header_level(eb)) {
2027 u64 blockptr = btrfs_node_blockptr(eb, i);
2029 ret = search_for_chunk_blocks(mdres, blockptr,
2036 /* Yay a leaf! We loves leafs! */
2037 btrfs_item_key_to_cpu(eb, &key, i);
2038 if (key.type != BTRFS_CHUNK_ITEM_KEY)
2041 fs_chunk = malloc(sizeof(struct fs_chunk));
2043 fprintf(stderr, "Erorr allocating chunk\n");
2047 memset(fs_chunk, 0, sizeof(*fs_chunk));
2048 read_extent_buffer(eb, &chunk, btrfs_item_ptr_offset(eb, i),
2051 fs_chunk->logical = key.offset;
2052 fs_chunk->physical = btrfs_stack_stripe_offset(&chunk.stripe);
2053 fs_chunk->bytes = btrfs_stack_chunk_length(&chunk);
2054 INIT_LIST_HEAD(&fs_chunk->list);
2055 if (tree_search(&mdres->physical_tree, &fs_chunk->p,
2056 physical_cmp, 1) != NULL)
2057 list_add(&fs_chunk->list, &mdres->overlapping_chunks);
2059 tree_insert(&mdres->physical_tree, &fs_chunk->p,
2061 if (fs_chunk->physical + fs_chunk->bytes >
2062 mdres->last_physical_offset)
2063 mdres->last_physical_offset = fs_chunk->physical +
2065 mdres->alloced_chunks += fs_chunk->bytes;
2066 tree_insert(&mdres->chunk_tree, &fs_chunk->l, chunk_cmp);
2073 /* If you have to ask you aren't worthy */
2074 static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
2075 u64 search, u64 cluster_bytenr)
2077 struct meta_cluster *cluster;
2078 struct meta_cluster_header *header;
2079 struct meta_cluster_item *item;
2080 u64 current_cluster = cluster_bytenr, bytenr;
2082 u32 bufsize, nritems, i;
2083 u32 max_size = MAX_PENDING_SIZE * 2;
2084 u8 *buffer, *tmp = NULL;
2087 cluster = malloc(BLOCK_SIZE);
2089 fprintf(stderr, "Error allocating cluster\n");
2093 buffer = malloc(max_size);
2095 fprintf(stderr, "Error allocing buffer\n");
2100 if (mdres->compress_method == COMPRESS_ZLIB) {
2101 tmp = malloc(max_size);
2103 fprintf(stderr, "Error allocing tmp buffer\n");
2110 bytenr = current_cluster;
2112 if (fseek(mdres->in, current_cluster, SEEK_SET)) {
2113 fprintf(stderr, "Error seeking: %d\n", errno);
2118 ret = fread(cluster, BLOCK_SIZE, 1, mdres->in);
2120 if (cluster_bytenr != 0) {
2122 current_cluster = 0;
2126 printf("ok this is where we screwed up?\n");
2129 } else if (ret < 0) {
2130 fprintf(stderr, "Error reading image\n");
2135 header = &cluster->header;
2136 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2137 le64_to_cpu(header->bytenr) != current_cluster) {
2138 fprintf(stderr, "bad header in metadump image\n");
2143 bytenr += BLOCK_SIZE;
2144 nritems = le32_to_cpu(header->nritems);
2145 for (i = 0; i < nritems; i++) {
2148 item = &cluster->items[i];
2149 bufsize = le32_to_cpu(item->size);
2150 item_bytenr = le64_to_cpu(item->bytenr);
2152 if (bufsize > max_size) {
2153 fprintf(stderr, "item %u size %u too big\n",
2159 if (mdres->compress_method == COMPRESS_ZLIB) {
2160 ret = fread(tmp, bufsize, 1, mdres->in);
2162 fprintf(stderr, "Error reading: %d\n",
2169 ret = uncompress(buffer,
2170 (unsigned long *)&size, tmp,
2173 fprintf(stderr, "Error decompressing "
2179 ret = fread(buffer, bufsize, 1, mdres->in);
2181 fprintf(stderr, "Error reading: %d\n",
2190 if (item_bytenr <= search &&
2191 item_bytenr + size > search) {
2192 ret = read_chunk_block(mdres, buffer, search,
2206 if (bytenr & BLOCK_MASK)
2207 bytenr += BLOCK_SIZE - (bytenr & BLOCK_MASK);
2208 current_cluster = bytenr;
2217 static int build_chunk_tree(struct mdrestore_struct *mdres,
2218 struct meta_cluster *cluster)
2220 struct btrfs_super_block *super;
2221 struct meta_cluster_header *header;
2222 struct meta_cluster_item *item = NULL;
2223 u64 chunk_root_bytenr = 0;
2229 /* We can't seek with stdin so don't bother doing this */
2230 if (mdres->in == stdin)
2233 ret = fread(cluster, BLOCK_SIZE, 1, mdres->in);
2235 fprintf(stderr, "Error reading in cluster: %d\n", errno);
2240 header = &cluster->header;
2241 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2242 le64_to_cpu(header->bytenr) != 0) {
2243 fprintf(stderr, "bad header in metadump image\n");
2247 bytenr += BLOCK_SIZE;
2248 mdres->compress_method = header->compress;
2249 nritems = le32_to_cpu(header->nritems);
2250 for (i = 0; i < nritems; i++) {
2251 item = &cluster->items[i];
2253 if (le64_to_cpu(item->bytenr) == BTRFS_SUPER_INFO_OFFSET)
2255 bytenr += le32_to_cpu(item->size);
2256 if (fseek(mdres->in, le32_to_cpu(item->size), SEEK_CUR)) {
2257 fprintf(stderr, "Error seeking: %d\n", errno);
2262 if (!item || le64_to_cpu(item->bytenr) != BTRFS_SUPER_INFO_OFFSET) {
2263 fprintf(stderr, "Huh, didn't find the super?\n");
2267 buffer = malloc(le32_to_cpu(item->size));
2269 fprintf(stderr, "Error allocing buffer\n");
2273 ret = fread(buffer, le32_to_cpu(item->size), 1, mdres->in);
2275 fprintf(stderr, "Error reading buffer: %d\n", errno);
2280 if (mdres->compress_method == COMPRESS_ZLIB) {
2281 size_t size = MAX_PENDING_SIZE * 2;
2284 tmp = malloc(MAX_PENDING_SIZE * 2);
2289 ret = uncompress(tmp, (unsigned long *)&size,
2290 buffer, le32_to_cpu(item->size));
2292 fprintf(stderr, "Error decompressing %d\n", ret);
2301 pthread_mutex_lock(&mdres->mutex);
2302 super = (struct btrfs_super_block *)buffer;
2303 chunk_root_bytenr = btrfs_super_chunk_root(super);
2304 mdres->leafsize = btrfs_super_leafsize(super);
2305 memcpy(mdres->fsid, super->fsid, BTRFS_FSID_SIZE);
2306 memcpy(mdres->uuid, super->dev_item.uuid,
2308 mdres->devid = le64_to_cpu(super->dev_item.devid);
2310 pthread_mutex_unlock(&mdres->mutex);
2312 return search_for_chunk_blocks(mdres, chunk_root_bytenr, 0);
2315 static int range_contains_super(u64 physical, u64 bytes)
2320 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2321 super_bytenr = btrfs_sb_offset(i);
2322 if (super_bytenr >= physical &&
2323 super_bytenr < physical + bytes)
2330 static void remap_overlapping_chunks(struct mdrestore_struct *mdres)
2332 struct fs_chunk *fs_chunk;
2334 while (!list_empty(&mdres->overlapping_chunks)) {
2335 fs_chunk = list_first_entry(&mdres->overlapping_chunks,
2336 struct fs_chunk, list);
2337 list_del_init(&fs_chunk->list);
2338 if (range_contains_super(fs_chunk->physical,
2340 fprintf(stderr, "Remapping a chunk that had a super "
2341 "mirror inside of it, clearing space cache "
2342 "so we don't end up with corruption\n");
2343 mdres->clear_space_cache = 1;
2345 fs_chunk->physical = mdres->last_physical_offset;
2346 tree_insert(&mdres->physical_tree, &fs_chunk->p, physical_cmp);
2347 mdres->last_physical_offset += fs_chunk->bytes;
2351 static int fixup_devices(struct btrfs_fs_info *fs_info,
2352 struct mdrestore_struct *mdres, off_t dev_size)
2354 struct btrfs_trans_handle *trans;
2355 struct btrfs_dev_item *dev_item;
2356 struct btrfs_path *path;
2357 struct extent_buffer *leaf;
2358 struct btrfs_root *root = fs_info->chunk_root;
2359 struct btrfs_key key;
2360 u64 devid, cur_devid;
2363 path = btrfs_alloc_path();
2365 fprintf(stderr, "Error alloc'ing path\n");
2369 trans = btrfs_start_transaction(fs_info->tree_root, 1);
2370 if (IS_ERR(trans)) {
2371 fprintf(stderr, "Error starting transaction %ld\n",
2373 btrfs_free_path(path);
2374 return PTR_ERR(trans);
2377 dev_item = &fs_info->super_copy->dev_item;
2379 devid = btrfs_stack_device_id(dev_item);
2381 btrfs_set_stack_device_total_bytes(dev_item, dev_size);
2382 btrfs_set_stack_device_bytes_used(dev_item, mdres->alloced_chunks);
2384 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2385 key.type = BTRFS_DEV_ITEM_KEY;
2389 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2391 fprintf(stderr, "search failed %d\n", ret);
2396 leaf = path->nodes[0];
2397 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2398 ret = btrfs_next_leaf(root, path);
2400 fprintf(stderr, "Error going to next leaf "
2408 leaf = path->nodes[0];
2411 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2412 if (key.type > BTRFS_DEV_ITEM_KEY)
2414 if (key.type != BTRFS_DEV_ITEM_KEY) {
2419 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2420 struct btrfs_dev_item);
2421 cur_devid = btrfs_device_id(leaf, dev_item);
2422 if (devid != cur_devid) {
2423 ret = btrfs_del_item(trans, root, path);
2425 fprintf(stderr, "Error deleting item %d\n",
2429 btrfs_release_path(path);
2433 btrfs_set_device_total_bytes(leaf, dev_item, dev_size);
2434 btrfs_set_device_bytes_used(leaf, dev_item,
2435 mdres->alloced_chunks);
2436 btrfs_mark_buffer_dirty(leaf);
2440 btrfs_free_path(path);
2441 ret = btrfs_commit_transaction(trans, fs_info->tree_root);
2443 fprintf(stderr, "Commit failed %d\n", ret);
2449 static int restore_metadump(const char *input, FILE *out, int old_restore,
2450 int num_threads, int fixup_offset,
2451 const char *target, int multi_devices)
2453 struct meta_cluster *cluster = NULL;
2454 struct meta_cluster_header *header;
2455 struct mdrestore_struct mdrestore;
2456 struct btrfs_fs_info *info = NULL;
2461 if (!strcmp(input, "-")) {
2464 in = fopen(input, "r");
2466 perror("unable to open metadump image");
2471 /* NOTE: open with write mode */
2474 info = open_ctree_fs_info(target, 0, 0, 0,
2476 OPEN_CTREE_RESTORE |
2477 OPEN_CTREE_PARTIAL);
2479 fprintf(stderr, "%s: open ctree failed\n", __func__);
2485 cluster = malloc(BLOCK_SIZE);
2487 fprintf(stderr, "Error allocating cluster\n");
2492 ret = mdrestore_init(&mdrestore, in, out, old_restore, num_threads,
2493 fixup_offset, info, multi_devices);
2495 fprintf(stderr, "Error initing mdrestore %d\n", ret);
2496 goto failed_cluster;
2499 if (!multi_devices && !old_restore) {
2500 ret = build_chunk_tree(&mdrestore, cluster);
2503 if (!list_empty(&mdrestore.overlapping_chunks))
2504 remap_overlapping_chunks(&mdrestore);
2507 if (in != stdin && fseek(in, 0, SEEK_SET)) {
2508 fprintf(stderr, "Error seeking %d\n", errno);
2512 while (!mdrestore.error) {
2513 ret = fread(cluster, BLOCK_SIZE, 1, in);
2517 header = &cluster->header;
2518 if (le64_to_cpu(header->magic) != HEADER_MAGIC ||
2519 le64_to_cpu(header->bytenr) != bytenr) {
2520 fprintf(stderr, "bad header in metadump image\n");
2524 ret = add_cluster(cluster, &mdrestore, &bytenr);
2526 fprintf(stderr, "Error adding cluster\n");
2530 ret = wait_for_worker(&mdrestore);
2532 if (!ret && !multi_devices && !old_restore) {
2533 struct btrfs_root *root;
2536 root = open_ctree_fd(fileno(out), target, 0,
2537 OPEN_CTREE_PARTIAL |
2539 OPEN_CTREE_NO_DEVICES);
2541 fprintf(stderr, "unable to open %s\n", target);
2545 info = root->fs_info;
2547 if (stat(target, &st)) {
2548 fprintf(stderr, "statting %s failed\n", target);
2549 close_ctree(info->chunk_root);
2553 ret = fixup_devices(info, &mdrestore, st.st_size);
2554 close_ctree(info->chunk_root);
2559 mdrestore_destroy(&mdrestore, num_threads);
2563 if (fixup_offset && info)
2564 close_ctree(info->chunk_root);
2571 static int update_disk_super_on_device(struct btrfs_fs_info *info,
2572 const char *other_dev, u64 cur_devid)
2574 struct btrfs_key key;
2575 struct extent_buffer *leaf;
2576 struct btrfs_path path;
2577 struct btrfs_dev_item *dev_item;
2578 struct btrfs_super_block *disk_super;
2579 char dev_uuid[BTRFS_UUID_SIZE];
2580 char fs_uuid[BTRFS_UUID_SIZE];
2581 u64 devid, type, io_align, io_width;
2582 u64 sector_size, total_bytes, bytes_used;
2583 char buf[BTRFS_SUPER_INFO_SIZE];
2587 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2588 key.type = BTRFS_DEV_ITEM_KEY;
2589 key.offset = cur_devid;
2591 btrfs_init_path(&path);
2592 ret = btrfs_search_slot(NULL, info->chunk_root, &key, &path, 0, 0);
2594 fprintf(stderr, "ERROR: search key failed\n");
2599 leaf = path.nodes[0];
2600 dev_item = btrfs_item_ptr(leaf, path.slots[0],
2601 struct btrfs_dev_item);
2603 devid = btrfs_device_id(leaf, dev_item);
2604 if (devid != cur_devid) {
2605 printk("ERROR: devid %llu mismatch with %llu\n", devid, cur_devid);
2610 type = btrfs_device_type(leaf, dev_item);
2611 io_align = btrfs_device_io_align(leaf, dev_item);
2612 io_width = btrfs_device_io_width(leaf, dev_item);
2613 sector_size = btrfs_device_sector_size(leaf, dev_item);
2614 total_bytes = btrfs_device_total_bytes(leaf, dev_item);
2615 bytes_used = btrfs_device_bytes_used(leaf, dev_item);
2616 read_extent_buffer(leaf, dev_uuid, (unsigned long)btrfs_device_uuid(dev_item), BTRFS_UUID_SIZE);
2617 read_extent_buffer(leaf, fs_uuid, (unsigned long)btrfs_device_fsid(dev_item), BTRFS_UUID_SIZE);
2619 btrfs_release_path(&path);
2621 printk("update disk super on %s devid=%llu\n", other_dev, devid);
2623 /* update other devices' super block */
2624 fp = open(other_dev, O_CREAT | O_RDWR, 0600);
2626 fprintf(stderr, "ERROR: could not open %s\n", other_dev);
2631 memcpy(buf, info->super_copy, BTRFS_SUPER_INFO_SIZE);
2633 disk_super = (struct btrfs_super_block *)buf;
2634 dev_item = &disk_super->dev_item;
2636 btrfs_set_stack_device_type(dev_item, type);
2637 btrfs_set_stack_device_id(dev_item, devid);
2638 btrfs_set_stack_device_total_bytes(dev_item, total_bytes);
2639 btrfs_set_stack_device_bytes_used(dev_item, bytes_used);
2640 btrfs_set_stack_device_io_align(dev_item, io_align);
2641 btrfs_set_stack_device_io_width(dev_item, io_width);
2642 btrfs_set_stack_device_sector_size(dev_item, sector_size);
2643 memcpy(dev_item->uuid, dev_uuid, BTRFS_UUID_SIZE);
2644 memcpy(dev_item->fsid, fs_uuid, BTRFS_UUID_SIZE);
2645 csum_block((u8 *)buf, BTRFS_SUPER_INFO_SIZE);
2647 ret = pwrite64(fp, buf, BTRFS_SUPER_INFO_SIZE, BTRFS_SUPER_INFO_OFFSET);
2648 if (ret != BTRFS_SUPER_INFO_SIZE) {
2650 fprintf(stderr, "ERROR: cannot write superblock: %s\n", strerror(ret));
2652 fprintf(stderr, "ERROR: cannot write superblock\n");
2657 write_backup_supers(fp, (u8 *)buf);
2665 static void print_usage(int ret)
2667 fprintf(stderr, "usage: btrfs-image [options] source target\n");
2668 fprintf(stderr, "\t-r \trestore metadump image\n");
2669 fprintf(stderr, "\t-c value\tcompression level (0 ~ 9)\n");
2670 fprintf(stderr, "\t-t value\tnumber of threads (1 ~ 32)\n");
2671 fprintf(stderr, "\t-o \tdon't mess with the chunk tree when restoring\n");
2672 fprintf(stderr, "\t-s \tsanitize file names, use once to just use garbage, use twice if you want crc collisions\n");
2673 fprintf(stderr, "\t-w \twalk all trees instead of using extent tree, do this if your extent tree is broken\n");
2674 fprintf(stderr, "\t-m \trestore for multiple devices\n");
2675 fprintf(stderr, "\n");
2676 fprintf(stderr, "\tIn the dump mode, source is the btrfs device and target is the output file (use '-' for stdout).\n");
2677 fprintf(stderr, "\tIn the restore mode, source is the dumped image and target is the btrfs device/file.\n");
2681 int main(int argc, char *argv[])
2685 u64 num_threads = 0;
2686 u64 compress_level = 0;
2688 int old_restore = 0;
2690 int multi_devices = 0;
2694 int usage_error = 0;
2698 static const struct option long_options[] = {
2699 { "help", no_argument, NULL, GETOPT_VAL_HELP},
2700 { NULL, 0, NULL, 0 }
2702 int c = getopt_long(argc, argv, "rc:t:oswm", long_options, NULL);
2710 num_threads = arg_strtou64(optarg);
2711 if (num_threads > 32)
2715 compress_level = arg_strtou64(optarg);
2716 if (compress_level > 9)
2732 case GETOPT_VAL_HELP:
2734 print_usage(c != GETOPT_VAL_HELP);
2739 if (check_argc_min(argc - optind, 2))
2742 dev_cnt = argc - optind - 1;
2746 fprintf(stderr, "Usage error: create and restore cannot be used at the same time\n");
2750 if (walk_trees || sanitize || compress_level) {
2751 fprintf(stderr, "Usage error: use -w, -s, -c options for restore makes no sense\n");
2754 if (multi_devices && dev_cnt < 2) {
2755 fprintf(stderr, "Usage error: not enough devices specified for -m option\n");
2758 if (!multi_devices && dev_cnt != 1) {
2759 fprintf(stderr, "Usage error: accepts only 1 device without -m option\n");
2767 source = argv[optind];
2768 target = argv[optind + 1];
2770 if (create && !strcmp(target, "-")) {
2773 out = fopen(target, "w+");
2775 perror("unable to create target file");
2780 if (compress_level > 0 || create == 0) {
2781 if (num_threads == 0) {
2782 long tmp = sysconf(_SC_NPROCESSORS_ONLN);
2793 ret = check_mounted(source);
2795 fprintf(stderr, "Could not check mount status: %s\n",
2800 "WARNING: The device is mounted. Make sure the filesystem is quiescent.\n");
2802 ret = create_metadump(source, out, num_threads,
2803 compress_level, sanitize, walk_trees);
2805 ret = restore_metadump(source, out, old_restore, num_threads,
2806 0, target, multi_devices);
2809 printk("%s failed (%s)\n", (create) ? "create" : "restore",
2814 /* extended support for multiple devices */
2815 if (!create && multi_devices) {
2816 struct btrfs_fs_info *info;
2820 info = open_ctree_fs_info(target, 0, 0, 0,
2821 OPEN_CTREE_PARTIAL |
2822 OPEN_CTREE_RESTORE);
2824 fprintf(stderr, "unable to open %s error = %s\n",
2825 target, strerror(errno));
2829 total_devs = btrfs_super_num_devices(info->super_copy);
2830 if (total_devs != dev_cnt) {
2831 printk("it needs %llu devices but has only %d\n",
2832 total_devs, dev_cnt);
2833 close_ctree(info->chunk_root);
2837 /* update super block on other disks */
2838 for (i = 2; i <= dev_cnt; i++) {
2839 ret = update_disk_super_on_device(info,
2840 argv[optind + i], (u64)i);
2842 printk("update disk super failed devid=%d (error=%d)\n",
2844 close_ctree(info->chunk_root);
2849 close_ctree(info->chunk_root);
2851 /* fix metadata block to map correct chunk */
2852 ret = restore_metadump(source, out, 0, num_threads, 1,
2855 fprintf(stderr, "fix metadump failed (error=%d)\n",
2861 if (out == stdout) {
2865 if (ret && create) {
2868 unlink_ret = unlink(target);
2871 "unlink output file failed : %s\n",
2876 btrfs_close_all_devices();