2 * Copyright (C) 2013 Fujitsu. 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.
18 #define _XOPEN_SOURCE 500
22 #include <stdio_ext.h>
24 #include <sys/types.h>
28 #include <uuid/uuid.h>
30 #include "kerncompat.h"
32 #include "radix-tree.h"
34 #include "extent-cache.h"
37 #include "transaction.h"
44 #define BTRFS_STRIPE_LEN (64 * 1024)
45 #define BTRFS_NUM_MIRRORS 2
47 struct recover_control {
55 u64 chunk_root_generation;
57 struct btrfs_fs_devices *fs_devices;
59 struct cache_tree chunk;
60 struct block_group_tree bg;
61 struct device_extent_tree devext;
62 struct cache_tree eb_cache;
64 struct list_head good_chunks;
65 struct list_head bad_chunks;
66 struct list_head unrepaired_chunks;
69 struct extent_record {
70 struct cache_extent cache;
72 u8 csum[BTRFS_CSUM_SIZE];
73 struct btrfs_device *devices[BTRFS_NUM_MIRRORS];
74 u64 offsets[BTRFS_NUM_MIRRORS];
78 static struct extent_record *btrfs_new_extent_record(struct extent_buffer *eb)
80 struct extent_record *rec;
82 rec = malloc(sizeof(*rec));
84 fprintf(stderr, "Fail to allocate memory for extent record.\n");
88 memset(rec, 0, sizeof(*rec));
89 rec->cache.start = btrfs_header_bytenr(eb);
90 rec->cache.size = eb->len;
91 rec->generation = btrfs_header_generation(eb);
92 read_extent_buffer(eb, rec->csum, (unsigned long)btrfs_header_csum(eb),
97 static int process_extent_buffer(struct cache_tree *eb_cache,
98 struct extent_buffer *eb,
99 struct btrfs_device *device, u64 offset)
101 struct extent_record *rec;
102 struct extent_record *exist;
103 struct cache_extent *cache;
106 rec = btrfs_new_extent_record(eb);
107 if (!rec->cache.size)
110 cache = lookup_cache_extent(eb_cache,
114 exist = container_of(cache, struct extent_record, cache);
116 if (exist->generation > rec->generation)
118 if (exist->generation == rec->generation) {
119 if (exist->cache.start != rec->cache.start ||
120 exist->cache.size != rec->cache.size ||
121 memcmp(exist->csum, rec->csum, BTRFS_CSUM_SIZE)) {
124 BUG_ON(exist->nmirrors >= BTRFS_NUM_MIRRORS);
125 exist->devices[exist->nmirrors] = device;
126 exist->offsets[exist->nmirrors] = offset;
131 remove_cache_extent(eb_cache, cache);
136 rec->devices[0] = device;
137 rec->offsets[0] = offset;
139 ret = insert_cache_extent(eb_cache, &rec->cache);
148 static void free_extent_record(struct cache_extent *cache)
150 struct extent_record *er;
152 er = container_of(cache, struct extent_record, cache);
156 FREE_EXTENT_CACHE_BASED_TREE(extent_record, free_extent_record);
158 static struct btrfs_chunk *create_chunk_item(struct chunk_record *record)
160 struct btrfs_chunk *ret;
161 struct btrfs_stripe *chunk_stripe;
164 if (!record || record->num_stripes == 0)
166 ret = malloc(btrfs_chunk_item_size(record->num_stripes));
169 btrfs_set_stack_chunk_length(ret, record->length);
170 btrfs_set_stack_chunk_owner(ret, record->owner);
171 btrfs_set_stack_chunk_stripe_len(ret, record->stripe_len);
172 btrfs_set_stack_chunk_type(ret, record->type_flags);
173 btrfs_set_stack_chunk_io_align(ret, record->io_align);
174 btrfs_set_stack_chunk_io_width(ret, record->io_width);
175 btrfs_set_stack_chunk_sector_size(ret, record->sector_size);
176 btrfs_set_stack_chunk_num_stripes(ret, record->num_stripes);
177 btrfs_set_stack_chunk_sub_stripes(ret, record->sub_stripes);
178 for (i = 0, chunk_stripe = &ret->stripe; i < record->num_stripes;
179 i++, chunk_stripe++) {
180 btrfs_set_stack_stripe_devid(chunk_stripe,
181 record->stripes[i].devid);
182 btrfs_set_stack_stripe_offset(chunk_stripe,
183 record->stripes[i].offset);
184 memcpy(chunk_stripe->dev_uuid, record->stripes[i].dev_uuid,
190 static void init_recover_control(struct recover_control *rc, int verbose,
193 memset(rc, 0, sizeof(struct recover_control));
194 cache_tree_init(&rc->chunk);
195 cache_tree_init(&rc->eb_cache);
196 block_group_tree_init(&rc->bg);
197 device_extent_tree_init(&rc->devext);
199 INIT_LIST_HEAD(&rc->good_chunks);
200 INIT_LIST_HEAD(&rc->bad_chunks);
201 INIT_LIST_HEAD(&rc->unrepaired_chunks);
203 rc->verbose = verbose;
207 static void free_recover_control(struct recover_control *rc)
209 free_block_group_tree(&rc->bg);
210 free_chunk_cache_tree(&rc->chunk);
211 free_device_extent_tree(&rc->devext);
212 free_extent_record_tree(&rc->eb_cache);
215 static int process_block_group_item(struct block_group_tree *bg_cache,
216 struct extent_buffer *leaf,
217 struct btrfs_key *key, int slot)
219 struct block_group_record *rec;
220 struct block_group_record *exist;
221 struct cache_extent *cache;
224 rec = btrfs_new_block_group_record(leaf, key, slot);
225 if (!rec->cache.size)
228 cache = lookup_cache_extent(&bg_cache->tree,
232 exist = container_of(cache, struct block_group_record, cache);
234 /*check the generation and replace if needed*/
235 if (exist->generation > rec->generation)
237 if (exist->generation == rec->generation) {
238 int offset = offsetof(struct block_group_record,
241 * According to the current kernel code, the following
242 * case is impossble, or there is something wrong in
245 if (memcmp(((void *)exist) + offset,
246 ((void *)rec) + offset,
247 sizeof(*rec) - offset))
251 remove_cache_extent(&bg_cache->tree, cache);
252 list_del_init(&exist->list);
255 * We must do seach again to avoid the following cache.
256 * /--old bg 1--//--old bg 2--/
262 ret = insert_block_group_record(bg_cache, rec);
271 static int process_chunk_item(struct cache_tree *chunk_cache,
272 struct extent_buffer *leaf, struct btrfs_key *key,
275 struct chunk_record *rec;
276 struct chunk_record *exist;
277 struct cache_extent *cache;
280 rec = btrfs_new_chunk_record(leaf, key, slot);
281 if (!rec->cache.size)
284 cache = lookup_cache_extent(chunk_cache, rec->offset, rec->length);
286 exist = container_of(cache, struct chunk_record, cache);
288 if (exist->generation > rec->generation)
290 if (exist->generation == rec->generation) {
291 int num_stripes = rec->num_stripes;
292 int rec_size = btrfs_chunk_record_size(num_stripes);
293 int offset = offsetof(struct chunk_record, generation);
295 if (exist->num_stripes != rec->num_stripes ||
296 memcmp(((void *)exist) + offset,
297 ((void *)rec) + offset,
302 remove_cache_extent(chunk_cache, cache);
306 ret = insert_cache_extent(chunk_cache, &rec->cache);
315 static int process_device_extent_item(struct device_extent_tree *devext_cache,
316 struct extent_buffer *leaf,
317 struct btrfs_key *key, int slot)
319 struct device_extent_record *rec;
320 struct device_extent_record *exist;
321 struct cache_extent *cache;
324 rec = btrfs_new_device_extent_record(leaf, key, slot);
325 if (!rec->cache.size)
328 cache = lookup_cache_extent2(&devext_cache->tree,
333 exist = container_of(cache, struct device_extent_record, cache);
334 if (exist->generation > rec->generation)
336 if (exist->generation == rec->generation) {
337 int offset = offsetof(struct device_extent_record,
339 if (memcmp(((void *)exist) + offset,
340 ((void *)rec) + offset,
341 sizeof(*rec) - offset))
345 remove_cache_extent(&devext_cache->tree, cache);
346 list_del_init(&exist->chunk_list);
347 list_del_init(&exist->device_list);
352 ret = insert_device_extent_record(devext_cache, rec);
361 static void print_block_group_info(struct block_group_record *rec, char *prefix)
364 printf("%s", prefix);
365 printf("Block Group: start = %llu, len = %llu, flag = %llx\n",
366 rec->objectid, rec->offset, rec->flags);
369 static void print_block_group_tree(struct block_group_tree *tree)
371 struct cache_extent *cache;
372 struct block_group_record *rec;
374 printf("All Block Groups:\n");
375 for (cache = first_cache_extent(&tree->tree); cache;
376 cache = next_cache_extent(cache)) {
377 rec = container_of(cache, struct block_group_record, cache);
378 print_block_group_info(rec, "\t");
383 static void print_stripe_info(struct stripe *data, char *prefix1, char *prefix2,
387 printf("%s", prefix1);
389 printf("%s", prefix2);
390 printf("[%2d] Stripe: devid = %llu, offset = %llu\n",
391 index, data->devid, data->offset);
394 static void print_chunk_self_info(struct chunk_record *rec, char *prefix)
399 printf("%s", prefix);
400 printf("Chunk: start = %llu, len = %llu, type = %llx, num_stripes = %u\n",
401 rec->offset, rec->length, rec->type_flags, rec->num_stripes);
403 printf("%s", prefix);
404 printf(" Stripes list:\n");
405 for (i = 0; i < rec->num_stripes; i++)
406 print_stripe_info(&rec->stripes[i], prefix, " ", i);
409 static void print_chunk_tree(struct cache_tree *tree)
411 struct cache_extent *n;
412 struct chunk_record *entry;
414 printf("All Chunks:\n");
415 for (n = first_cache_extent(tree); n;
416 n = next_cache_extent(n)) {
417 entry = container_of(n, struct chunk_record, cache);
418 print_chunk_self_info(entry, "\t");
423 static void print_device_extent_info(struct device_extent_record *rec,
427 printf("%s", prefix);
428 printf("Device extent: devid = %llu, start = %llu, len = %llu, chunk offset = %llu\n",
429 rec->objectid, rec->offset, rec->length, rec->chunk_offset);
432 static void print_device_extent_tree(struct device_extent_tree *tree)
434 struct cache_extent *n;
435 struct device_extent_record *entry;
437 printf("All Device Extents:\n");
438 for (n = first_cache_extent(&tree->tree); n;
439 n = next_cache_extent(n)) {
440 entry = container_of(n, struct device_extent_record, cache);
441 print_device_extent_info(entry, "\t");
446 static void print_device_info(struct btrfs_device *device, char *prefix)
449 printf("%s", prefix);
450 printf("Device: id = %llu, name = %s\n",
451 device->devid, device->name);
454 static void print_all_devices(struct list_head *devices)
456 struct btrfs_device *dev;
458 printf("All Devices:\n");
459 list_for_each_entry(dev, devices, dev_list)
460 print_device_info(dev, "\t");
464 static void print_scan_result(struct recover_control *rc)
469 printf("DEVICE SCAN RESULT:\n");
470 printf("Filesystem Information:\n");
471 printf("\tsectorsize: %d\n", rc->sectorsize);
472 printf("\tleafsize: %d\n", rc->leafsize);
473 printf("\ttree root generation: %llu\n", rc->generation);
474 printf("\tchunk root generation: %llu\n", rc->chunk_root_generation);
477 print_all_devices(&rc->fs_devices->devices);
478 print_block_group_tree(&rc->bg);
479 print_chunk_tree(&rc->chunk);
480 print_device_extent_tree(&rc->devext);
483 static void print_chunk_info(struct chunk_record *chunk, char *prefix)
485 struct device_extent_record *devext;
488 print_chunk_self_info(chunk, prefix);
490 printf("%s", prefix);
492 print_block_group_info(chunk->bg_rec, " ");
494 printf(" No block group.\n");
496 printf("%s", prefix);
497 if (list_empty(&chunk->dextents)) {
498 printf(" No device extent.\n");
500 printf(" Device extent list:\n");
502 list_for_each_entry(devext, &chunk->dextents, chunk_list) {
504 printf("%s", prefix);
505 printf("%s[%2d]", " ", i);
506 print_device_extent_info(devext, NULL);
512 static void print_check_result(struct recover_control *rc)
514 struct chunk_record *chunk;
515 struct block_group_record *bg;
516 struct device_extent_record *devext;
524 printf("CHECK RESULT:\n");
525 printf("Healthy Chunks:\n");
526 list_for_each_entry(chunk, &rc->good_chunks, list) {
527 print_chunk_info(chunk, " ");
531 printf("Bad Chunks:\n");
532 list_for_each_entry(chunk, &rc->bad_chunks, list) {
533 print_chunk_info(chunk, " ");
538 printf("Total Chunks:\t%d\n", total);
539 printf(" Heathy:\t%d\n", good);
540 printf(" Bad:\t%d\n", bad);
543 printf("Orphan Block Groups:\n");
544 list_for_each_entry(bg, &rc->bg.block_groups, list)
545 print_block_group_info(bg, " ");
548 printf("Orphan Device Extents:\n");
549 list_for_each_entry(devext, &rc->devext.no_chunk_orphans, chunk_list)
550 print_device_extent_info(devext, " ");
553 static int check_chunk_by_metadata(struct recover_control *rc,
554 struct btrfs_root *root,
555 struct chunk_record *chunk, int bg_only)
560 struct btrfs_path path;
561 struct btrfs_key key;
562 struct btrfs_root *dev_root;
563 struct stripe *stripe;
564 struct btrfs_dev_extent *dev_extent;
565 struct btrfs_block_group_item *bg_ptr;
566 struct extent_buffer *l;
568 btrfs_init_path(&path);
573 dev_root = root->fs_info->dev_root;
574 for (i = 0; i < chunk->num_stripes; i++) {
575 stripe = &chunk->stripes[i];
577 key.objectid = stripe->devid;
578 key.offset = stripe->offset;
579 key.type = BTRFS_DEV_EXTENT_KEY;
581 ret = btrfs_search_slot(NULL, dev_root, &key, &path, 0, 0);
583 fprintf(stderr, "Search device extent failed(%d)\n",
585 btrfs_release_path(&path);
587 } else if (ret > 0) {
590 "No device extent[%llu, %llu]\n",
591 stripe->devid, stripe->offset);
592 btrfs_release_path(&path);
596 slot = path.slots[0];
597 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
599 btrfs_dev_extent_chunk_offset(l, dev_extent)) {
602 "Device tree unmatch with chunks dev_extent[%llu, %llu], chunk[%llu, %llu]\n",
603 btrfs_dev_extent_chunk_offset(l,
605 btrfs_dev_extent_length(l, dev_extent),
606 chunk->offset, chunk->length);
607 btrfs_release_path(&path);
610 btrfs_release_path(&path);
614 key.objectid = chunk->offset;
615 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
616 key.offset = chunk->length;
618 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, &path,
621 fprintf(stderr, "Search block group failed(%d)\n", ret);
622 btrfs_release_path(&path);
624 } else if (ret > 0) {
626 fprintf(stderr, "No block group[%llu, %llu]\n",
627 key.objectid, key.offset);
628 btrfs_release_path(&path);
633 slot = path.slots[0];
634 bg_ptr = btrfs_item_ptr(l, slot, struct btrfs_block_group_item);
635 if (chunk->type_flags != btrfs_disk_block_group_flags(l, bg_ptr)) {
638 "Chunk[%llu, %llu]'s type(%llu) is differemt with Block Group's type(%llu)\n",
639 chunk->offset, chunk->length, chunk->type_flags,
640 btrfs_disk_block_group_flags(l, bg_ptr));
641 btrfs_release_path(&path);
644 btrfs_release_path(&path);
648 static int check_all_chunks_by_metadata(struct recover_control *rc,
649 struct btrfs_root *root)
651 struct chunk_record *chunk;
652 struct chunk_record *next;
653 LIST_HEAD(orphan_chunks);
657 list_for_each_entry_safe(chunk, next, &rc->good_chunks, list) {
658 err = check_chunk_by_metadata(rc, root, chunk, 0);
661 list_move_tail(&chunk->list, &orphan_chunks);
662 else if (err && !ret)
667 list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
668 err = check_chunk_by_metadata(rc, root, chunk, 1);
670 list_move_tail(&chunk->list, &orphan_chunks);
671 else if (err && !ret)
675 list_for_each_entry(chunk, &rc->bad_chunks, list) {
676 err = check_chunk_by_metadata(rc, root, chunk, 1);
677 if (err != -ENOENT && !ret)
678 ret = err ? err : -EINVAL;
680 list_splice(&orphan_chunks, &rc->bad_chunks);
684 static int extract_metadata_record(struct recover_control *rc,
685 struct extent_buffer *leaf)
687 struct btrfs_key key;
692 nritems = btrfs_header_nritems(leaf);
693 for (i = 0; i < nritems; i++) {
694 btrfs_item_key_to_cpu(leaf, &key, i);
696 case BTRFS_BLOCK_GROUP_ITEM_KEY:
697 ret = process_block_group_item(&rc->bg, leaf, &key, i);
699 case BTRFS_CHUNK_ITEM_KEY:
700 ret = process_chunk_item(&rc->chunk, leaf, &key, i);
702 case BTRFS_DEV_EXTENT_KEY:
703 ret = process_device_extent_item(&rc->devext, leaf,
713 static inline int is_super_block_address(u64 offset)
717 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
718 if (offset == btrfs_sb_offset(i))
724 static int scan_one_device(struct recover_control *rc, int fd,
725 struct btrfs_device *device)
727 struct extent_buffer *buf;
731 buf = malloc(sizeof(*buf) + rc->leafsize);
734 buf->len = rc->leafsize;
738 if (is_super_block_address(bytenr))
739 bytenr += rc->sectorsize;
741 if (pread64(fd, buf->data, rc->leafsize, bytenr) <
745 if (memcmp_extent_buffer(buf, rc->fs_devices->fsid,
746 (unsigned long)btrfs_header_fsid(buf),
748 bytenr += rc->sectorsize;
752 if (verify_tree_block_csum_silent(buf, rc->csum_size)) {
753 bytenr += rc->sectorsize;
757 ret = process_extent_buffer(&rc->eb_cache, buf, device, bytenr);
761 if (btrfs_header_level(buf) != 0)
764 switch (btrfs_header_owner(buf)) {
765 case BTRFS_EXTENT_TREE_OBJECTID:
766 case BTRFS_DEV_TREE_OBJECTID:
767 /* different tree use different generation */
768 if (btrfs_header_generation(buf) > rc->generation)
770 ret = extract_metadata_record(rc, buf);
774 case BTRFS_CHUNK_TREE_OBJECTID:
775 if (btrfs_header_generation(buf) >
776 rc->chunk_root_generation)
778 ret = extract_metadata_record(rc, buf);
784 bytenr += rc->leafsize;
791 static int scan_devices(struct recover_control *rc)
795 struct btrfs_device *dev;
797 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
798 fd = open(dev->name, O_RDONLY);
800 fprintf(stderr, "Failed to open device %s\n",
804 ret = scan_one_device(rc, fd, dev);
812 static int build_device_map_by_chunk_record(struct btrfs_root *root,
813 struct chunk_record *chunk)
818 u8 uuid[BTRFS_UUID_SIZE];
820 struct btrfs_mapping_tree *map_tree;
821 struct map_lookup *map;
822 struct stripe *stripe;
824 map_tree = &root->fs_info->mapping_tree;
825 num_stripes = chunk->num_stripes;
826 map = malloc(btrfs_map_lookup_size(num_stripes));
829 map->ce.start = chunk->offset;
830 map->ce.size = chunk->length;
831 map->num_stripes = num_stripes;
832 map->io_width = chunk->io_width;
833 map->io_align = chunk->io_align;
834 map->sector_size = chunk->sector_size;
835 map->stripe_len = chunk->stripe_len;
836 map->type = chunk->type_flags;
837 map->sub_stripes = chunk->sub_stripes;
839 for (i = 0, stripe = chunk->stripes; i < num_stripes; i++, stripe++) {
840 devid = stripe->devid;
841 memcpy(uuid, stripe->dev_uuid, BTRFS_UUID_SIZE);
842 map->stripes[i].physical = stripe->offset;
843 map->stripes[i].dev = btrfs_find_device(root, devid,
845 if (!map->stripes[i].dev) {
851 ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
855 static int build_device_maps_by_chunk_records(struct recover_control *rc,
856 struct btrfs_root *root)
859 struct chunk_record *chunk;
861 list_for_each_entry(chunk, &rc->good_chunks, list) {
862 ret = build_device_map_by_chunk_record(root, chunk);
869 static int block_group_remove_all_extent_items(struct btrfs_trans_handle *trans,
870 struct btrfs_root *root,
871 struct block_group_record *bg)
873 struct btrfs_fs_info *fs_info = root->fs_info;
874 struct btrfs_key key;
875 struct btrfs_path path;
876 struct extent_buffer *leaf;
877 u64 start = bg->objectid;
878 u64 end = bg->objectid + bg->offset;
885 btrfs_init_path(&path);
886 root = root->fs_info->extent_root;
888 key.objectid = start;
890 key.type = BTRFS_EXTENT_ITEM_KEY;
892 ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
898 leaf = path.nodes[0];
899 nitems = btrfs_header_nritems(leaf);
901 /* The tree is empty. */
906 if (path.slots[0] >= nitems) {
907 ret = btrfs_next_leaf(root, &path);
914 leaf = path.nodes[0];
915 btrfs_item_key_to_cpu(leaf, &key, 0);
916 if (key.objectid >= end)
918 btrfs_release_path(&path);
924 for (i = path.slots[0]; i < nitems; i++) {
925 btrfs_item_key_to_cpu(leaf, &key, i);
926 if (key.objectid >= end)
929 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
939 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
940 key.type == BTRFS_METADATA_ITEM_KEY) {
941 old_val = btrfs_super_bytes_used(fs_info->super_copy);
942 if (key.type == BTRFS_METADATA_ITEM_KEY)
943 old_val += root->leafsize;
945 old_val += key.offset;
946 btrfs_set_super_bytes_used(fs_info->super_copy,
952 ret = btrfs_del_items(trans, root, &path, del_s, del_nr);
957 if (key.objectid < end) {
958 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
959 key.objectid += root->sectorsize;
960 key.type = BTRFS_EXTENT_ITEM_KEY;
963 btrfs_release_path(&path);
967 btrfs_release_path(&path);
971 static int block_group_free_all_extent(struct btrfs_trans_handle *trans,
972 struct btrfs_root *root,
973 struct block_group_record *bg)
975 struct btrfs_block_group_cache *cache;
976 struct btrfs_fs_info *info;
980 info = root->fs_info;
981 cache = btrfs_lookup_block_group(info, bg->objectid);
985 start = cache->key.objectid;
986 end = start + cache->key.offset - 1;
988 set_extent_bits(&info->block_group_cache, start, end,
989 BLOCK_GROUP_DIRTY, GFP_NOFS);
990 set_extent_dirty(&info->free_space_cache, start, end, GFP_NOFS);
992 btrfs_set_block_group_used(&cache->item, 0);
997 static int remove_chunk_extent_item(struct btrfs_trans_handle *trans,
998 struct recover_control *rc,
999 struct btrfs_root *root)
1001 struct chunk_record *chunk;
1004 list_for_each_entry(chunk, &rc->good_chunks, list) {
1005 if (!(chunk->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1007 ret = block_group_remove_all_extent_items(trans, root,
1012 ret = block_group_free_all_extent(trans, root, chunk->bg_rec);
1019 static int __rebuild_chunk_root(struct btrfs_trans_handle *trans,
1020 struct recover_control *rc,
1021 struct btrfs_root *root)
1024 struct btrfs_device *dev;
1025 struct extent_buffer *cow;
1026 struct btrfs_disk_key disk_key;
1029 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1030 if (min_devid > dev->devid)
1031 min_devid = dev->devid;
1033 disk_key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1034 disk_key.type = BTRFS_DEV_ITEM_KEY;
1035 disk_key.offset = min_devid;
1037 cow = btrfs_alloc_free_block(trans, root, root->sectorsize,
1038 BTRFS_CHUNK_TREE_OBJECTID,
1039 &disk_key, 0, 0, 0);
1040 btrfs_set_header_bytenr(cow, cow->start);
1041 btrfs_set_header_generation(cow, trans->transid);
1042 btrfs_set_header_nritems(cow, 0);
1043 btrfs_set_header_level(cow, 0);
1044 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1045 btrfs_set_header_owner(cow, BTRFS_CHUNK_TREE_OBJECTID);
1046 write_extent_buffer(cow, root->fs_info->fsid,
1047 (unsigned long)btrfs_header_fsid(cow),
1050 write_extent_buffer(cow, root->fs_info->chunk_tree_uuid,
1051 (unsigned long)btrfs_header_chunk_tree_uuid(cow),
1055 btrfs_mark_buffer_dirty(cow);
1060 static int __rebuild_device_items(struct btrfs_trans_handle *trans,
1061 struct recover_control *rc,
1062 struct btrfs_root *root)
1064 struct btrfs_device *dev;
1065 struct btrfs_key key;
1066 struct btrfs_dev_item *dev_item;
1069 dev_item = malloc(sizeof(struct btrfs_dev_item));
1073 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1074 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1075 key.type = BTRFS_DEV_ITEM_KEY;
1076 key.offset = dev->devid;
1078 btrfs_set_stack_device_generation(dev_item, 0);
1079 btrfs_set_stack_device_type(dev_item, dev->type);
1080 btrfs_set_stack_device_id(dev_item, dev->devid);
1081 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1082 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1083 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1084 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1085 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1086 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1087 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1089 ret = btrfs_insert_item(trans, root, &key,
1090 dev_item, sizeof(*dev_item));
1097 static int __rebuild_chunk_items(struct btrfs_trans_handle *trans,
1098 struct recover_control *rc,
1099 struct btrfs_root *root)
1101 struct btrfs_key key;
1102 struct btrfs_chunk *chunk = NULL;
1103 struct btrfs_root *chunk_root;
1104 struct chunk_record *chunk_rec;
1107 chunk_root = root->fs_info->chunk_root;
1109 list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1110 chunk = create_chunk_item(chunk_rec);
1114 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1115 key.type = BTRFS_CHUNK_ITEM_KEY;
1116 key.offset = chunk_rec->offset;
1118 ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1119 btrfs_chunk_item_size(chunk->num_stripes));
1127 static int rebuild_chunk_tree(struct btrfs_trans_handle *trans,
1128 struct recover_control *rc,
1129 struct btrfs_root *root)
1133 root = root->fs_info->chunk_root;
1135 ret = __rebuild_chunk_root(trans, rc, root);
1139 ret = __rebuild_device_items(trans, rc, root);
1143 ret = __rebuild_chunk_items(trans, rc, root);
1148 static int rebuild_sys_array(struct recover_control *rc,
1149 struct btrfs_root *root)
1151 struct btrfs_chunk *chunk;
1152 struct btrfs_key key;
1153 struct chunk_record *chunk_rec;
1157 btrfs_set_super_sys_array_size(root->fs_info->super_copy, 0);
1159 list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1160 if (!(chunk_rec->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1163 num_stripes = chunk_rec->num_stripes;
1164 chunk = create_chunk_item(chunk_rec);
1170 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1171 key.type = BTRFS_CHUNK_ITEM_KEY;
1172 key.offset = chunk_rec->offset;
1174 ret = btrfs_add_system_chunk(NULL, root, &key, chunk,
1175 btrfs_chunk_item_size(num_stripes));
1184 static struct btrfs_root *
1185 open_ctree_with_broken_chunk(struct recover_control *rc)
1187 struct btrfs_fs_info *fs_info;
1188 struct btrfs_super_block *disk_super;
1189 struct extent_buffer *eb;
1196 fs_info = btrfs_new_fs_info(1, BTRFS_SUPER_INFO_OFFSET);
1198 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1199 return ERR_PTR(-ENOMEM);
1202 fs_info->fs_devices = rc->fs_devices;
1203 ret = btrfs_open_devices(fs_info->fs_devices, O_RDWR);
1207 disk_super = fs_info->super_copy;
1208 ret = btrfs_read_dev_super(fs_info->fs_devices->latest_bdev,
1209 disk_super, fs_info->super_bytenr);
1211 fprintf(stderr, "No valid btrfs found\n");
1215 memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1217 ret = btrfs_check_fs_compatibility(disk_super, 1);
1221 nodesize = btrfs_super_nodesize(disk_super);
1222 leafsize = btrfs_super_leafsize(disk_super);
1223 sectorsize = btrfs_super_sectorsize(disk_super);
1224 stripesize = btrfs_super_stripesize(disk_super);
1226 __setup_root(nodesize, leafsize, sectorsize, stripesize,
1227 fs_info->chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1229 ret = build_device_maps_by_chunk_records(rc, fs_info->chunk_root);
1233 ret = btrfs_setup_all_roots(fs_info, 0, 0);
1237 eb = fs_info->tree_root->node;
1238 read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1239 (unsigned long)btrfs_header_chunk_tree_uuid(eb),
1242 return fs_info->fs_root;
1244 btrfs_release_all_roots(fs_info);
1246 btrfs_cleanup_all_caches(fs_info);
1248 btrfs_close_devices(fs_info->fs_devices);
1250 btrfs_free_fs_info(fs_info);
1251 return ERR_PTR(ret);
1254 static int recover_prepare(struct recover_control *rc, char *path)
1258 struct btrfs_super_block *sb;
1259 struct btrfs_fs_devices *fs_devices;
1262 fd = open(path, O_RDONLY);
1264 fprintf(stderr, "open %s\n error.\n", path);
1268 sb = malloc(sizeof(struct btrfs_super_block));
1270 fprintf(stderr, "allocating memory for sb failed.\n");
1275 ret = btrfs_read_dev_super(fd, sb, BTRFS_SUPER_INFO_OFFSET);
1277 fprintf(stderr, "read super block error\n");
1281 rc->sectorsize = btrfs_super_sectorsize(sb);
1282 rc->leafsize = btrfs_super_leafsize(sb);
1283 rc->generation = btrfs_super_generation(sb);
1284 rc->chunk_root_generation = btrfs_super_chunk_root_generation(sb);
1285 rc->csum_size = btrfs_super_csum_size(sb);
1287 /* if seed, the result of scanning below will be partial */
1288 if (btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_SEEDING) {
1289 fprintf(stderr, "this device is seed device\n");
1294 ret = btrfs_scan_fs_devices(fd, path, &fs_devices, 0, 1);
1298 rc->fs_devices = fs_devices;
1301 print_all_devices(&rc->fs_devices->devices);
1311 * This reads a line from the stdin and only returns non-zero if the
1312 * first whitespace delimited token is a case insensitive match with yes
1315 static int ask_user(char *question)
1317 char buf[30] = {0,};
1318 char *saveptr = NULL;
1321 printf("%s [y/N]: ", question);
1323 return fgets(buf, sizeof(buf) - 1, stdin) &&
1324 (answer = strtok_r(buf, " \t\n\r", &saveptr)) &&
1325 (!strcasecmp(answer, "yes") || !strcasecmp(answer, "y"));
1328 static int btrfs_get_device_extents(u64 chunk_object,
1329 struct list_head *orphan_devexts,
1330 struct list_head *ret_list)
1332 struct device_extent_record *devext;
1333 struct device_extent_record *next;
1336 list_for_each_entry_safe(devext, next, orphan_devexts, chunk_list) {
1337 if (devext->chunk_offset == chunk_object) {
1338 list_move_tail(&devext->chunk_list, ret_list);
1345 static int calc_num_stripes(u64 type)
1347 if (type & (BTRFS_BLOCK_GROUP_RAID0 |
1348 BTRFS_BLOCK_GROUP_RAID10 |
1349 BTRFS_BLOCK_GROUP_RAID5 |
1350 BTRFS_BLOCK_GROUP_RAID6))
1352 else if (type & (BTRFS_BLOCK_GROUP_RAID1 |
1353 BTRFS_BLOCK_GROUP_DUP))
1359 static inline int calc_sub_nstripes(u64 type)
1361 if (type & BTRFS_BLOCK_GROUP_RAID10)
1367 static int btrfs_verify_device_extents(struct block_group_record *bg,
1368 struct list_head *devexts, int ndevexts)
1370 struct device_extent_record *devext;
1372 int expected_num_stripes;
1374 expected_num_stripes = calc_num_stripes(bg->flags);
1375 if (expected_num_stripes && expected_num_stripes != ndevexts)
1378 strpie_length = calc_stripe_length(bg->flags, bg->offset, ndevexts);
1379 list_for_each_entry(devext, devexts, chunk_list) {
1380 if (devext->length != strpie_length)
1386 static int btrfs_rebuild_unordered_chunk_stripes(struct recover_control *rc,
1387 struct chunk_record *chunk)
1389 struct device_extent_record *devext;
1390 struct btrfs_device *device;
1393 devext = list_first_entry(&chunk->dextents, struct device_extent_record,
1395 for (i = 0; i < chunk->num_stripes; i++) {
1396 chunk->stripes[i].devid = devext->objectid;
1397 chunk->stripes[i].offset = devext->offset;
1398 device = btrfs_find_device_by_devid(rc->fs_devices,
1403 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1406 memcpy(chunk->stripes[i].dev_uuid, device->uuid,
1408 devext = list_next_entry(devext, chunk_list);
1413 static int btrfs_calc_stripe_index(struct chunk_record *chunk, u64 logical)
1415 u64 offset = logical - chunk->offset;
1417 int nr_data_stripes;
1420 stripe_nr = offset / chunk->stripe_len;
1421 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
1422 index = stripe_nr % chunk->num_stripes;
1423 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
1424 index = stripe_nr % (chunk->num_stripes / chunk->sub_stripes);
1425 index *= chunk->sub_stripes;
1426 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
1427 nr_data_stripes = chunk->num_stripes - 1;
1428 index = stripe_nr % nr_data_stripes;
1429 stripe_nr /= nr_data_stripes;
1430 index = (index + stripe_nr) % chunk->num_stripes;
1431 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
1432 nr_data_stripes = chunk->num_stripes - 2;
1433 index = stripe_nr % nr_data_stripes;
1434 stripe_nr /= nr_data_stripes;
1435 index = (index + stripe_nr) % chunk->num_stripes;
1442 /* calc the logical offset which is the start of the next stripe. */
1443 static inline u64 btrfs_next_stripe_logical_offset(struct chunk_record *chunk,
1446 u64 offset = logical - chunk->offset;
1448 offset /= chunk->stripe_len;
1449 offset *= chunk->stripe_len;
1450 offset += chunk->stripe_len;
1452 return offset + chunk->offset;
1455 static int is_extent_record_in_device_extent(struct extent_record *er,
1456 struct device_extent_record *dext,
1461 for (i = 0; i < er->nmirrors; i++) {
1462 if (er->devices[i]->devid == dext->objectid &&
1463 er->offsets[i] >= dext->offset &&
1464 er->offsets[i] < dext->offset + dext->length) {
1473 btrfs_rebuild_ordered_meta_chunk_stripes(struct recover_control *rc,
1474 struct chunk_record *chunk)
1476 u64 start = chunk->offset;
1477 u64 end = chunk->offset + chunk->length;
1478 struct cache_extent *cache;
1479 struct extent_record *er;
1480 struct device_extent_record *devext;
1481 struct device_extent_record *next;
1482 struct btrfs_device *device;
1488 cache = lookup_cache_extent(&rc->eb_cache,
1489 start, chunk->length);
1491 /* No used space, we can reorder the stripes freely. */
1492 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1496 list_splice_init(&chunk->dextents, &devexts);
1498 er = container_of(cache, struct extent_record, cache);
1499 index = btrfs_calc_stripe_index(chunk, er->cache.start);
1500 if (chunk->stripes[index].devid)
1502 list_for_each_entry_safe(devext, next, &devexts, chunk_list) {
1503 if (is_extent_record_in_device_extent(er, devext, &mirror)) {
1504 chunk->stripes[index].devid = devext->objectid;
1505 chunk->stripes[index].offset = devext->offset;
1506 memcpy(chunk->stripes[index].dev_uuid,
1507 er->devices[mirror]->uuid,
1510 list_move(&devext->chunk_list, &chunk->dextents);
1514 start = btrfs_next_stripe_logical_offset(chunk, er->cache.start);
1516 goto no_extent_record;
1518 cache = lookup_cache_extent(&rc->eb_cache, start, end - start);
1522 if (list_empty(&devexts))
1525 if (chunk->type_flags & (BTRFS_BLOCK_GROUP_RAID5 |
1526 BTRFS_BLOCK_GROUP_RAID6)) {
1527 /* Fixme: try to recover the order by the parity block. */
1528 list_splice_tail(&devexts, &chunk->dextents);
1532 /* There is no data on the lost stripes, we can reorder them freely. */
1533 for (index = 0; index < chunk->num_stripes; index++) {
1534 if (chunk->stripes[index].devid)
1537 devext = list_first_entry(&devexts,
1538 struct device_extent_record,
1540 list_move(&devext->chunk_list, &chunk->dextents);
1542 chunk->stripes[index].devid = devext->objectid;
1543 chunk->stripes[index].offset = devext->offset;
1544 device = btrfs_find_device_by_devid(rc->fs_devices,
1548 list_splice_tail(&devexts, &chunk->dextents);
1551 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1554 memcpy(chunk->stripes[index].dev_uuid, device->uuid,
1560 #define BTRFS_ORDERED_RAID (BTRFS_BLOCK_GROUP_RAID0 | \
1561 BTRFS_BLOCK_GROUP_RAID10 | \
1562 BTRFS_BLOCK_GROUP_RAID5 | \
1563 BTRFS_BLOCK_GROUP_RAID6)
1565 static int btrfs_rebuild_chunk_stripes(struct recover_control *rc,
1566 struct chunk_record *chunk)
1571 * All the data in the system metadata chunk will be dropped,
1572 * so we need not guarantee that the data is right or not, that
1573 * is we can reorder the stripes in the system metadata chunk.
1575 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_METADATA) &&
1576 (chunk->type_flags & BTRFS_ORDERED_RAID))
1577 ret =btrfs_rebuild_ordered_meta_chunk_stripes(rc, chunk);
1578 else if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA) &&
1579 (chunk->type_flags & BTRFS_ORDERED_RAID))
1580 ret = 1; /* Be handled after the fs is opened. */
1582 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1587 static int btrfs_recover_chunks(struct recover_control *rc)
1589 struct chunk_record *chunk;
1590 struct block_group_record *bg;
1591 struct block_group_record *next;
1592 LIST_HEAD(new_chunks);
1597 /* create the chunk by block group */
1598 list_for_each_entry_safe(bg, next, &rc->bg.block_groups, list) {
1599 nstripes = btrfs_get_device_extents(bg->objectid,
1600 &rc->devext.no_chunk_orphans,
1602 chunk = malloc(btrfs_chunk_record_size(nstripes));
1605 memset(chunk, 0, btrfs_chunk_record_size(nstripes));
1606 INIT_LIST_HEAD(&chunk->dextents);
1608 chunk->cache.start = bg->objectid;
1609 chunk->cache.size = bg->offset;
1610 chunk->objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1611 chunk->type = BTRFS_CHUNK_ITEM_KEY;
1612 chunk->offset = bg->objectid;
1613 chunk->generation = bg->generation;
1614 chunk->length = bg->offset;
1615 chunk->owner = BTRFS_CHUNK_TREE_OBJECTID;
1616 chunk->stripe_len = BTRFS_STRIPE_LEN;
1617 chunk->type_flags = bg->flags;
1618 chunk->io_width = BTRFS_STRIPE_LEN;
1619 chunk->io_align = BTRFS_STRIPE_LEN;
1620 chunk->sector_size = rc->sectorsize;
1621 chunk->sub_stripes = calc_sub_nstripes(bg->flags);
1623 ret = insert_cache_extent(&rc->chunk, &chunk->cache);
1627 list_add_tail(&chunk->list, &rc->bad_chunks);
1631 list_splice_init(&devexts, &chunk->dextents);
1633 ret = btrfs_verify_device_extents(bg, &devexts, nstripes);
1635 list_add_tail(&chunk->list, &rc->bad_chunks);
1639 chunk->num_stripes = nstripes;
1640 ret = btrfs_rebuild_chunk_stripes(rc, chunk);
1642 list_add_tail(&chunk->list, &rc->unrepaired_chunks);
1644 list_add_tail(&chunk->list, &rc->bad_chunks);
1646 list_add_tail(&chunk->list, &rc->good_chunks);
1649 * Don't worry about the lost orphan device extents, they don't
1650 * have its chunk and block group, they must be the old ones that
1657 * Return 0 when succesful, < 0 on error and > 0 if aborted by user
1659 int btrfs_recover_chunk_tree(char *path, int verbose, int yes)
1662 struct btrfs_root *root = NULL;
1663 struct btrfs_trans_handle *trans;
1664 struct recover_control rc;
1666 init_recover_control(&rc, verbose, yes);
1668 ret = recover_prepare(&rc, path);
1670 fprintf(stderr, "recover prepare error\n");
1674 ret = scan_devices(&rc);
1676 fprintf(stderr, "scan chunk headers error\n");
1680 if (cache_tree_empty(&rc.chunk) &&
1681 cache_tree_empty(&rc.bg.tree) &&
1682 cache_tree_empty(&rc.devext.tree)) {
1683 fprintf(stderr, "no recoverable chunk\n");
1687 print_scan_result(&rc);
1689 ret = check_chunks(&rc.chunk, &rc.bg, &rc.devext, &rc.good_chunks,
1691 print_check_result(&rc);
1693 if (!list_empty(&rc.bg.block_groups) ||
1694 !list_empty(&rc.devext.no_chunk_orphans)) {
1695 ret = btrfs_recover_chunks(&rc);
1700 * If the chunk is healthy, its block group item and device
1701 * extent item should be written on the disks. So, it is very
1702 * likely that the bad chunk is a old one that has been
1703 * droppped from the fs. Don't deal with them now, we will
1704 * check it after the fs is opened.
1708 root = open_ctree_with_broken_chunk(&rc);
1710 fprintf(stderr, "open with broken chunk error\n");
1711 ret = PTR_ERR(root);
1715 ret = check_all_chunks_by_metadata(&rc, root);
1717 fprintf(stderr, "The chunks in memory can not match the metadata of the fs. Repair failed.\n");
1718 goto fail_close_ctree;
1722 ret = ask_user("We are going to rebuild the chunk tree on disk, it might destroy the old metadata on the disk, Are you sure?");
1725 goto fail_close_ctree;
1729 trans = btrfs_start_transaction(root, 1);
1730 ret = remove_chunk_extent_item(trans, &rc, root);
1733 ret = rebuild_chunk_tree(trans, &rc, root);
1736 ret = rebuild_sys_array(&rc, root);
1739 btrfs_commit_transaction(trans, root);
1743 free_recover_control(&rc);