2 * Copyright (C) 2013 FUJITSU LIMITED. 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.
20 #include <stdio_ext.h>
22 #include <sys/types.h>
26 #include <uuid/uuid.h>
29 #include "kerncompat.h"
31 #include "radix-tree.h"
33 #include "extent-cache.h"
36 #include "transaction.h"
43 struct recover_control {
51 u64 chunk_root_generation;
53 struct btrfs_fs_devices *fs_devices;
55 struct cache_tree chunk;
56 struct block_group_tree bg;
57 struct device_extent_tree devext;
58 struct cache_tree eb_cache;
60 struct list_head good_chunks;
61 struct list_head bad_chunks;
62 struct list_head rebuild_chunks;
63 struct list_head unrepaired_chunks;
64 pthread_mutex_t rc_lock;
67 struct extent_record {
68 struct cache_extent cache;
70 u8 csum[BTRFS_CSUM_SIZE];
71 struct btrfs_device *devices[BTRFS_MAX_MIRRORS];
72 u64 offsets[BTRFS_MAX_MIRRORS];
77 struct recover_control *rc;
78 struct btrfs_device *dev;
82 static struct extent_record *btrfs_new_extent_record(struct extent_buffer *eb)
84 struct extent_record *rec;
86 rec = malloc(sizeof(*rec));
88 fprintf(stderr, "Fail to allocate memory for extent record.\n");
92 memset(rec, 0, sizeof(*rec));
93 rec->cache.start = btrfs_header_bytenr(eb);
94 rec->cache.size = eb->len;
95 rec->generation = btrfs_header_generation(eb);
96 read_extent_buffer(eb, rec->csum, (unsigned long)btrfs_header_csum(eb),
101 static int process_extent_buffer(struct cache_tree *eb_cache,
102 struct extent_buffer *eb,
103 struct btrfs_device *device, u64 offset)
105 struct extent_record *rec;
106 struct extent_record *exist;
107 struct cache_extent *cache;
110 rec = btrfs_new_extent_record(eb);
111 if (!rec->cache.size)
114 cache = lookup_cache_extent(eb_cache,
118 exist = container_of(cache, struct extent_record, cache);
120 if (exist->generation > rec->generation)
122 if (exist->generation == rec->generation) {
123 if (exist->cache.start != rec->cache.start ||
124 exist->cache.size != rec->cache.size ||
125 memcmp(exist->csum, rec->csum, BTRFS_CSUM_SIZE)) {
128 BUG_ON(exist->nmirrors >= BTRFS_MAX_MIRRORS);
129 exist->devices[exist->nmirrors] = device;
130 exist->offsets[exist->nmirrors] = offset;
135 remove_cache_extent(eb_cache, cache);
140 rec->devices[0] = device;
141 rec->offsets[0] = offset;
143 ret = insert_cache_extent(eb_cache, &rec->cache);
152 static void free_extent_record(struct cache_extent *cache)
154 struct extent_record *er;
156 er = container_of(cache, struct extent_record, cache);
160 FREE_EXTENT_CACHE_BASED_TREE(extent_record, free_extent_record);
162 static struct btrfs_chunk *create_chunk_item(struct chunk_record *record)
164 struct btrfs_chunk *ret;
165 struct btrfs_stripe *chunk_stripe;
168 if (!record || record->num_stripes == 0)
170 ret = malloc(btrfs_chunk_item_size(record->num_stripes));
173 btrfs_set_stack_chunk_length(ret, record->length);
174 btrfs_set_stack_chunk_owner(ret, record->owner);
175 btrfs_set_stack_chunk_stripe_len(ret, record->stripe_len);
176 btrfs_set_stack_chunk_type(ret, record->type_flags);
177 btrfs_set_stack_chunk_io_align(ret, record->io_align);
178 btrfs_set_stack_chunk_io_width(ret, record->io_width);
179 btrfs_set_stack_chunk_sector_size(ret, record->sector_size);
180 btrfs_set_stack_chunk_num_stripes(ret, record->num_stripes);
181 btrfs_set_stack_chunk_sub_stripes(ret, record->sub_stripes);
182 for (i = 0, chunk_stripe = &ret->stripe; i < record->num_stripes;
183 i++, chunk_stripe++) {
184 btrfs_set_stack_stripe_devid(chunk_stripe,
185 record->stripes[i].devid);
186 btrfs_set_stack_stripe_offset(chunk_stripe,
187 record->stripes[i].offset);
188 memcpy(chunk_stripe->dev_uuid, record->stripes[i].dev_uuid,
194 static void init_recover_control(struct recover_control *rc, int verbose,
197 memset(rc, 0, sizeof(struct recover_control));
198 cache_tree_init(&rc->chunk);
199 cache_tree_init(&rc->eb_cache);
200 block_group_tree_init(&rc->bg);
201 device_extent_tree_init(&rc->devext);
203 INIT_LIST_HEAD(&rc->good_chunks);
204 INIT_LIST_HEAD(&rc->bad_chunks);
205 INIT_LIST_HEAD(&rc->rebuild_chunks);
206 INIT_LIST_HEAD(&rc->unrepaired_chunks);
208 rc->verbose = verbose;
210 pthread_mutex_init(&rc->rc_lock, NULL);
213 static void free_recover_control(struct recover_control *rc)
215 free_block_group_tree(&rc->bg);
216 free_chunk_cache_tree(&rc->chunk);
217 free_device_extent_tree(&rc->devext);
218 free_extent_record_tree(&rc->eb_cache);
219 pthread_mutex_destroy(&rc->rc_lock);
222 static int process_block_group_item(struct block_group_tree *bg_cache,
223 struct extent_buffer *leaf,
224 struct btrfs_key *key, int slot)
226 struct block_group_record *rec;
227 struct block_group_record *exist;
228 struct cache_extent *cache;
231 rec = btrfs_new_block_group_record(leaf, key, slot);
232 if (!rec->cache.size)
235 cache = lookup_cache_extent(&bg_cache->tree,
239 exist = container_of(cache, struct block_group_record, cache);
241 /*check the generation and replace if needed*/
242 if (exist->generation > rec->generation)
244 if (exist->generation == rec->generation) {
245 int offset = offsetof(struct block_group_record,
248 * According to the current kernel code, the following
249 * case is impossble, or there is something wrong in
252 if (memcmp(((void *)exist) + offset,
253 ((void *)rec) + offset,
254 sizeof(*rec) - offset))
258 remove_cache_extent(&bg_cache->tree, cache);
259 list_del_init(&exist->list);
262 * We must do seach again to avoid the following cache.
263 * /--old bg 1--//--old bg 2--/
269 ret = insert_block_group_record(bg_cache, rec);
278 static int process_chunk_item(struct cache_tree *chunk_cache,
279 struct extent_buffer *leaf, struct btrfs_key *key,
282 struct chunk_record *rec;
283 struct chunk_record *exist;
284 struct cache_extent *cache;
287 rec = btrfs_new_chunk_record(leaf, key, slot);
288 if (!rec->cache.size)
291 cache = lookup_cache_extent(chunk_cache, rec->offset, rec->length);
293 exist = container_of(cache, struct chunk_record, cache);
295 if (exist->generation > rec->generation)
297 if (exist->generation == rec->generation) {
298 int num_stripes = rec->num_stripes;
299 int rec_size = btrfs_chunk_record_size(num_stripes);
300 int offset = offsetof(struct chunk_record, generation);
302 if (exist->num_stripes != rec->num_stripes ||
303 memcmp(((void *)exist) + offset,
304 ((void *)rec) + offset,
309 remove_cache_extent(chunk_cache, cache);
313 ret = insert_cache_extent(chunk_cache, &rec->cache);
322 static int process_device_extent_item(struct device_extent_tree *devext_cache,
323 struct extent_buffer *leaf,
324 struct btrfs_key *key, int slot)
326 struct device_extent_record *rec;
327 struct device_extent_record *exist;
328 struct cache_extent *cache;
331 rec = btrfs_new_device_extent_record(leaf, key, slot);
332 if (!rec->cache.size)
335 cache = lookup_cache_extent2(&devext_cache->tree,
340 exist = container_of(cache, struct device_extent_record, cache);
341 if (exist->generation > rec->generation)
343 if (exist->generation == rec->generation) {
344 int offset = offsetof(struct device_extent_record,
346 if (memcmp(((void *)exist) + offset,
347 ((void *)rec) + offset,
348 sizeof(*rec) - offset))
352 remove_cache_extent(&devext_cache->tree, cache);
353 list_del_init(&exist->chunk_list);
354 list_del_init(&exist->device_list);
359 ret = insert_device_extent_record(devext_cache, rec);
368 static void print_block_group_info(struct block_group_record *rec, char *prefix)
371 printf("%s", prefix);
372 printf("Block Group: start = %llu, len = %llu, flag = %llx\n",
373 rec->objectid, rec->offset, rec->flags);
376 static void print_block_group_tree(struct block_group_tree *tree)
378 struct cache_extent *cache;
379 struct block_group_record *rec;
381 printf("All Block Groups:\n");
382 for (cache = first_cache_extent(&tree->tree); cache;
383 cache = next_cache_extent(cache)) {
384 rec = container_of(cache, struct block_group_record, cache);
385 print_block_group_info(rec, "\t");
390 static void print_stripe_info(struct stripe *data, char *prefix1, char *prefix2,
394 printf("%s", prefix1);
396 printf("%s", prefix2);
397 printf("[%2d] Stripe: devid = %llu, offset = %llu\n",
398 index, data->devid, data->offset);
401 static void print_chunk_self_info(struct chunk_record *rec, char *prefix)
406 printf("%s", prefix);
407 printf("Chunk: start = %llu, len = %llu, type = %llx, num_stripes = %u\n",
408 rec->offset, rec->length, rec->type_flags, rec->num_stripes);
410 printf("%s", prefix);
411 printf(" Stripes list:\n");
412 for (i = 0; i < rec->num_stripes; i++)
413 print_stripe_info(&rec->stripes[i], prefix, " ", i);
416 static void print_chunk_tree(struct cache_tree *tree)
418 struct cache_extent *n;
419 struct chunk_record *entry;
421 printf("All Chunks:\n");
422 for (n = first_cache_extent(tree); n;
423 n = next_cache_extent(n)) {
424 entry = container_of(n, struct chunk_record, cache);
425 print_chunk_self_info(entry, "\t");
430 static void print_device_extent_info(struct device_extent_record *rec,
434 printf("%s", prefix);
435 printf("Device extent: devid = %llu, start = %llu, len = %llu, chunk offset = %llu\n",
436 rec->objectid, rec->offset, rec->length, rec->chunk_offset);
439 static void print_device_extent_tree(struct device_extent_tree *tree)
441 struct cache_extent *n;
442 struct device_extent_record *entry;
444 printf("All Device Extents:\n");
445 for (n = first_cache_extent(&tree->tree); n;
446 n = next_cache_extent(n)) {
447 entry = container_of(n, struct device_extent_record, cache);
448 print_device_extent_info(entry, "\t");
453 static void print_device_info(struct btrfs_device *device, char *prefix)
456 printf("%s", prefix);
457 printf("Device: id = %llu, name = %s\n",
458 device->devid, device->name);
461 static void print_all_devices(struct list_head *devices)
463 struct btrfs_device *dev;
465 printf("All Devices:\n");
466 list_for_each_entry(dev, devices, dev_list)
467 print_device_info(dev, "\t");
471 static void print_scan_result(struct recover_control *rc)
476 printf("DEVICE SCAN RESULT:\n");
477 printf("Filesystem Information:\n");
478 printf("\tsectorsize: %d\n", rc->sectorsize);
479 printf("\tleafsize: %d\n", rc->leafsize);
480 printf("\ttree root generation: %llu\n", rc->generation);
481 printf("\tchunk root generation: %llu\n", rc->chunk_root_generation);
484 print_all_devices(&rc->fs_devices->devices);
485 print_block_group_tree(&rc->bg);
486 print_chunk_tree(&rc->chunk);
487 print_device_extent_tree(&rc->devext);
490 static void print_chunk_info(struct chunk_record *chunk, char *prefix)
492 struct device_extent_record *devext;
495 print_chunk_self_info(chunk, prefix);
497 printf("%s", prefix);
499 print_block_group_info(chunk->bg_rec, " ");
501 printf(" No block group.\n");
503 printf("%s", prefix);
504 if (list_empty(&chunk->dextents)) {
505 printf(" No device extent.\n");
507 printf(" Device extent list:\n");
509 list_for_each_entry(devext, &chunk->dextents, chunk_list) {
511 printf("%s", prefix);
512 printf("%s[%2d]", " ", i);
513 print_device_extent_info(devext, NULL);
519 static void print_check_result(struct recover_control *rc)
521 struct chunk_record *chunk;
522 struct block_group_record *bg;
523 struct device_extent_record *devext;
531 printf("CHECK RESULT:\n");
532 printf("Recoverable Chunks:\n");
533 list_for_each_entry(chunk, &rc->good_chunks, list) {
534 print_chunk_info(chunk, " ");
538 list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
539 print_chunk_info(chunk, " ");
543 list_for_each_entry(chunk, &rc->unrepaired_chunks, list) {
544 print_chunk_info(chunk, " ");
548 printf("Unrecoverable Chunks:\n");
549 list_for_each_entry(chunk, &rc->bad_chunks, list) {
550 print_chunk_info(chunk, " ");
555 printf("Total Chunks:\t\t%d\n", total);
556 printf(" Recoverable:\t\t%d\n", good);
557 printf(" Unrecoverable:\t%d\n", bad);
560 printf("Orphan Block Groups:\n");
561 list_for_each_entry(bg, &rc->bg.block_groups, list)
562 print_block_group_info(bg, " ");
565 printf("Orphan Device Extents:\n");
566 list_for_each_entry(devext, &rc->devext.no_chunk_orphans, chunk_list)
567 print_device_extent_info(devext, " ");
571 static int check_chunk_by_metadata(struct recover_control *rc,
572 struct btrfs_root *root,
573 struct chunk_record *chunk, int bg_only)
578 struct btrfs_path path;
579 struct btrfs_key key;
580 struct btrfs_root *dev_root;
581 struct stripe *stripe;
582 struct btrfs_dev_extent *dev_extent;
583 struct btrfs_block_group_item *bg_ptr;
584 struct extent_buffer *l;
586 btrfs_init_path(&path);
591 dev_root = root->fs_info->dev_root;
592 for (i = 0; i < chunk->num_stripes; i++) {
593 stripe = &chunk->stripes[i];
595 key.objectid = stripe->devid;
596 key.offset = stripe->offset;
597 key.type = BTRFS_DEV_EXTENT_KEY;
599 ret = btrfs_search_slot(NULL, dev_root, &key, &path, 0, 0);
601 fprintf(stderr, "Search device extent failed(%d)\n",
603 btrfs_release_path(&path);
605 } else if (ret > 0) {
608 "No device extent[%llu, %llu]\n",
609 stripe->devid, stripe->offset);
610 btrfs_release_path(&path);
614 slot = path.slots[0];
615 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
617 btrfs_dev_extent_chunk_offset(l, dev_extent)) {
620 "Device tree unmatch with chunks dev_extent[%llu, %llu], chunk[%llu, %llu]\n",
621 btrfs_dev_extent_chunk_offset(l,
623 btrfs_dev_extent_length(l, dev_extent),
624 chunk->offset, chunk->length);
625 btrfs_release_path(&path);
628 btrfs_release_path(&path);
632 key.objectid = chunk->offset;
633 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
634 key.offset = chunk->length;
636 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, &path,
639 fprintf(stderr, "Search block group failed(%d)\n", ret);
640 btrfs_release_path(&path);
642 } else if (ret > 0) {
644 fprintf(stderr, "No block group[%llu, %llu]\n",
645 key.objectid, key.offset);
646 btrfs_release_path(&path);
651 slot = path.slots[0];
652 bg_ptr = btrfs_item_ptr(l, slot, struct btrfs_block_group_item);
653 if (chunk->type_flags != btrfs_disk_block_group_flags(l, bg_ptr)) {
656 "Chunk[%llu, %llu]'s type(%llu) is differemt with Block Group's type(%llu)\n",
657 chunk->offset, chunk->length, chunk->type_flags,
658 btrfs_disk_block_group_flags(l, bg_ptr));
659 btrfs_release_path(&path);
662 btrfs_release_path(&path);
666 static int check_all_chunks_by_metadata(struct recover_control *rc,
667 struct btrfs_root *root)
669 struct chunk_record *chunk;
670 struct chunk_record *next;
671 LIST_HEAD(orphan_chunks);
675 list_for_each_entry_safe(chunk, next, &rc->good_chunks, list) {
676 err = check_chunk_by_metadata(rc, root, chunk, 0);
679 list_move_tail(&chunk->list, &orphan_chunks);
680 else if (err && !ret)
685 list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
686 err = check_chunk_by_metadata(rc, root, chunk, 1);
688 list_move_tail(&chunk->list, &orphan_chunks);
689 else if (err && !ret)
693 list_for_each_entry(chunk, &rc->bad_chunks, list) {
694 err = check_chunk_by_metadata(rc, root, chunk, 1);
695 if (err != -ENOENT && !ret)
696 ret = err ? err : -EINVAL;
698 list_splice(&orphan_chunks, &rc->bad_chunks);
702 static int extract_metadata_record(struct recover_control *rc,
703 struct extent_buffer *leaf)
705 struct btrfs_key key;
710 nritems = btrfs_header_nritems(leaf);
711 for (i = 0; i < nritems; i++) {
712 btrfs_item_key_to_cpu(leaf, &key, i);
714 case BTRFS_BLOCK_GROUP_ITEM_KEY:
715 pthread_mutex_lock(&rc->rc_lock);
716 ret = process_block_group_item(&rc->bg, leaf, &key, i);
717 pthread_mutex_unlock(&rc->rc_lock);
719 case BTRFS_CHUNK_ITEM_KEY:
720 pthread_mutex_lock(&rc->rc_lock);
721 ret = process_chunk_item(&rc->chunk, leaf, &key, i);
722 pthread_mutex_unlock(&rc->rc_lock);
724 case BTRFS_DEV_EXTENT_KEY:
725 pthread_mutex_lock(&rc->rc_lock);
726 ret = process_device_extent_item(&rc->devext, leaf,
728 pthread_mutex_unlock(&rc->rc_lock);
737 static inline int is_super_block_address(u64 offset)
741 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
742 if (offset == btrfs_sb_offset(i))
748 static int scan_one_device(void *dev_scan_struct)
750 struct extent_buffer *buf;
753 struct device_scan *dev_scan = (struct device_scan *)dev_scan_struct;
754 struct recover_control *rc = dev_scan->rc;
755 struct btrfs_device *device = dev_scan->dev;
756 int fd = dev_scan->fd;
759 ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
763 buf = malloc(sizeof(*buf) + rc->leafsize);
766 buf->len = rc->leafsize;
770 if (is_super_block_address(bytenr))
771 bytenr += rc->sectorsize;
773 if (pread64(fd, buf->data, rc->leafsize, bytenr) <
777 if (memcmp_extent_buffer(buf, rc->fs_devices->fsid,
780 bytenr += rc->sectorsize;
784 if (verify_tree_block_csum_silent(buf, rc->csum_size)) {
785 bytenr += rc->sectorsize;
789 pthread_mutex_lock(&rc->rc_lock);
790 ret = process_extent_buffer(&rc->eb_cache, buf, device, bytenr);
791 pthread_mutex_unlock(&rc->rc_lock);
795 if (btrfs_header_level(buf) != 0)
798 switch (btrfs_header_owner(buf)) {
799 case BTRFS_EXTENT_TREE_OBJECTID:
800 case BTRFS_DEV_TREE_OBJECTID:
801 /* different tree use different generation */
802 if (btrfs_header_generation(buf) > rc->generation)
804 ret = extract_metadata_record(rc, buf);
808 case BTRFS_CHUNK_TREE_OBJECTID:
809 if (btrfs_header_generation(buf) >
810 rc->chunk_root_generation)
812 ret = extract_metadata_record(rc, buf);
818 bytenr += rc->leafsize;
826 static int scan_devices(struct recover_control *rc)
830 struct btrfs_device *dev;
831 struct device_scan *dev_scans;
840 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list)
842 dev_scans = (struct device_scan *)malloc(sizeof(struct device_scan)
846 t_scans = (pthread_t *)malloc(sizeof(pthread_t) * devnr);
849 t_rets = (int *)malloc(sizeof(int) * devnr);
853 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
854 fd = open(dev->name, O_RDONLY);
856 fprintf(stderr, "Failed to open device %s\n",
861 dev_scans[devidx].rc = rc;
862 dev_scans[devidx].dev = dev;
863 dev_scans[devidx].fd = fd;
864 ret = pthread_create(&t_scans[devidx], NULL,
865 (void *)scan_one_device,
866 (void *)&dev_scans[devidx]);
869 cancel_to = devidx - 1;
877 ret = pthread_join(t_scans[i], (void **)&t_rets[i]);
878 if (ret || t_rets[i]) {
881 cancel_to = devnr - 1;
887 while (ret && (cancel_from <= cancel_to)) {
888 pthread_cancel(t_scans[cancel_from]);
898 static int build_device_map_by_chunk_record(struct btrfs_root *root,
899 struct chunk_record *chunk)
904 u8 uuid[BTRFS_UUID_SIZE];
906 struct btrfs_mapping_tree *map_tree;
907 struct map_lookup *map;
908 struct stripe *stripe;
910 map_tree = &root->fs_info->mapping_tree;
911 num_stripes = chunk->num_stripes;
912 map = malloc(btrfs_map_lookup_size(num_stripes));
915 map->ce.start = chunk->offset;
916 map->ce.size = chunk->length;
917 map->num_stripes = num_stripes;
918 map->io_width = chunk->io_width;
919 map->io_align = chunk->io_align;
920 map->sector_size = chunk->sector_size;
921 map->stripe_len = chunk->stripe_len;
922 map->type = chunk->type_flags;
923 map->sub_stripes = chunk->sub_stripes;
925 for (i = 0, stripe = chunk->stripes; i < num_stripes; i++, stripe++) {
926 devid = stripe->devid;
927 memcpy(uuid, stripe->dev_uuid, BTRFS_UUID_SIZE);
928 map->stripes[i].physical = stripe->offset;
929 map->stripes[i].dev = btrfs_find_device(root, devid,
931 if (!map->stripes[i].dev) {
937 ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
941 static int build_device_maps_by_chunk_records(struct recover_control *rc,
942 struct btrfs_root *root)
945 struct chunk_record *chunk;
947 list_for_each_entry(chunk, &rc->good_chunks, list) {
948 ret = build_device_map_by_chunk_record(root, chunk);
952 list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
953 ret = build_device_map_by_chunk_record(root, chunk);
960 static int block_group_remove_all_extent_items(struct btrfs_trans_handle *trans,
961 struct btrfs_root *root,
962 struct block_group_record *bg)
964 struct btrfs_fs_info *fs_info = root->fs_info;
965 struct btrfs_key key;
966 struct btrfs_path path;
967 struct extent_buffer *leaf;
968 u64 start = bg->objectid;
969 u64 end = bg->objectid + bg->offset;
976 btrfs_init_path(&path);
977 root = root->fs_info->extent_root;
979 key.objectid = start;
981 key.type = BTRFS_EXTENT_ITEM_KEY;
983 ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
989 leaf = path.nodes[0];
990 nitems = btrfs_header_nritems(leaf);
992 /* The tree is empty. */
997 if (path.slots[0] >= nitems) {
998 ret = btrfs_next_leaf(root, &path);
1005 leaf = path.nodes[0];
1006 btrfs_item_key_to_cpu(leaf, &key, 0);
1007 if (key.objectid >= end)
1009 btrfs_release_path(&path);
1015 for (i = path.slots[0]; i < nitems; i++) {
1016 btrfs_item_key_to_cpu(leaf, &key, i);
1017 if (key.objectid >= end)
1020 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1030 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
1031 key.type == BTRFS_METADATA_ITEM_KEY) {
1032 old_val = btrfs_super_bytes_used(fs_info->super_copy);
1033 if (key.type == BTRFS_METADATA_ITEM_KEY)
1034 old_val += root->leafsize;
1036 old_val += key.offset;
1037 btrfs_set_super_bytes_used(fs_info->super_copy,
1043 ret = btrfs_del_items(trans, root, &path, del_s, del_nr);
1048 if (key.objectid < end) {
1049 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1050 key.objectid += root->sectorsize;
1051 key.type = BTRFS_EXTENT_ITEM_KEY;
1054 btrfs_release_path(&path);
1058 btrfs_release_path(&path);
1062 static int block_group_free_all_extent(struct btrfs_trans_handle *trans,
1063 struct btrfs_root *root,
1064 struct block_group_record *bg)
1066 struct btrfs_block_group_cache *cache;
1067 struct btrfs_fs_info *info;
1071 info = root->fs_info;
1072 cache = btrfs_lookup_block_group(info, bg->objectid);
1076 start = cache->key.objectid;
1077 end = start + cache->key.offset - 1;
1079 set_extent_bits(&info->block_group_cache, start, end,
1080 BLOCK_GROUP_DIRTY, GFP_NOFS);
1081 set_extent_dirty(&info->free_space_cache, start, end, GFP_NOFS);
1083 btrfs_set_block_group_used(&cache->item, 0);
1088 static int remove_chunk_extent_item(struct btrfs_trans_handle *trans,
1089 struct recover_control *rc,
1090 struct btrfs_root *root)
1092 struct chunk_record *chunk;
1095 list_for_each_entry(chunk, &rc->good_chunks, list) {
1096 if (!(chunk->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1098 ret = block_group_remove_all_extent_items(trans, root,
1103 ret = block_group_free_all_extent(trans, root, chunk->bg_rec);
1110 static int __rebuild_chunk_root(struct btrfs_trans_handle *trans,
1111 struct recover_control *rc,
1112 struct btrfs_root *root)
1115 struct btrfs_device *dev;
1116 struct extent_buffer *cow;
1117 struct btrfs_disk_key disk_key;
1120 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1121 if (min_devid > dev->devid)
1122 min_devid = dev->devid;
1124 disk_key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1125 disk_key.type = BTRFS_DEV_ITEM_KEY;
1126 disk_key.offset = min_devid;
1128 cow = btrfs_alloc_free_block(trans, root, root->nodesize,
1129 BTRFS_CHUNK_TREE_OBJECTID,
1130 &disk_key, 0, 0, 0);
1131 btrfs_set_header_bytenr(cow, cow->start);
1132 btrfs_set_header_generation(cow, trans->transid);
1133 btrfs_set_header_nritems(cow, 0);
1134 btrfs_set_header_level(cow, 0);
1135 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1136 btrfs_set_header_owner(cow, BTRFS_CHUNK_TREE_OBJECTID);
1137 write_extent_buffer(cow, root->fs_info->fsid,
1138 btrfs_header_fsid(), BTRFS_FSID_SIZE);
1140 write_extent_buffer(cow, root->fs_info->chunk_tree_uuid,
1141 btrfs_header_chunk_tree_uuid(cow),
1145 btrfs_mark_buffer_dirty(cow);
1150 static int __rebuild_device_items(struct btrfs_trans_handle *trans,
1151 struct recover_control *rc,
1152 struct btrfs_root *root)
1154 struct btrfs_device *dev;
1155 struct btrfs_key key;
1156 struct btrfs_dev_item *dev_item;
1159 dev_item = malloc(sizeof(struct btrfs_dev_item));
1163 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1164 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1165 key.type = BTRFS_DEV_ITEM_KEY;
1166 key.offset = dev->devid;
1168 btrfs_set_stack_device_generation(dev_item, 0);
1169 btrfs_set_stack_device_type(dev_item, dev->type);
1170 btrfs_set_stack_device_id(dev_item, dev->devid);
1171 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1172 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1173 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1174 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1175 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1176 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1177 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1179 ret = btrfs_insert_item(trans, root, &key,
1180 dev_item, sizeof(*dev_item));
1187 static int __insert_chunk_item(struct btrfs_trans_handle *trans,
1188 struct chunk_record *chunk_rec,
1189 struct btrfs_root *chunk_root)
1191 struct btrfs_key key;
1192 struct btrfs_chunk *chunk = NULL;
1195 chunk = create_chunk_item(chunk_rec);
1198 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1199 key.type = BTRFS_CHUNK_ITEM_KEY;
1200 key.offset = chunk_rec->offset;
1202 ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1203 btrfs_chunk_item_size(chunk->num_stripes));
1208 static int __rebuild_chunk_items(struct btrfs_trans_handle *trans,
1209 struct recover_control *rc,
1210 struct btrfs_root *root)
1212 struct btrfs_root *chunk_root;
1213 struct chunk_record *chunk_rec;
1216 chunk_root = root->fs_info->chunk_root;
1218 list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1219 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1223 list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1224 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1231 static int rebuild_chunk_tree(struct btrfs_trans_handle *trans,
1232 struct recover_control *rc,
1233 struct btrfs_root *root)
1237 root = root->fs_info->chunk_root;
1239 ret = __rebuild_chunk_root(trans, rc, root);
1243 ret = __rebuild_device_items(trans, rc, root);
1247 ret = __rebuild_chunk_items(trans, rc, root);
1252 static int rebuild_sys_array(struct recover_control *rc,
1253 struct btrfs_root *root)
1255 struct btrfs_chunk *chunk;
1256 struct btrfs_key key;
1257 struct chunk_record *chunk_rec;
1261 btrfs_set_super_sys_array_size(root->fs_info->super_copy, 0);
1263 list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1264 if (!(chunk_rec->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1267 num_stripes = chunk_rec->num_stripes;
1268 chunk = create_chunk_item(chunk_rec);
1274 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1275 key.type = BTRFS_CHUNK_ITEM_KEY;
1276 key.offset = chunk_rec->offset;
1278 ret = btrfs_add_system_chunk(NULL, root, &key, chunk,
1279 btrfs_chunk_item_size(num_stripes));
1288 static int calculate_bg_used(struct btrfs_root *extent_root,
1289 struct chunk_record *chunk_rec,
1290 struct btrfs_path *path,
1293 struct extent_buffer *node;
1294 struct btrfs_key found_key;
1300 node = path->nodes[0];
1301 slot = path->slots[0];
1302 btrfs_item_key_to_cpu(node, &found_key, slot);
1303 if (found_key.objectid >= chunk_rec->offset + chunk_rec->length)
1305 if (found_key.type != BTRFS_METADATA_ITEM_KEY &&
1306 found_key.type != BTRFS_EXTENT_DATA_KEY)
1308 if (found_key.type == BTRFS_METADATA_ITEM_KEY)
1309 used_ret += extent_root->nodesize;
1311 used_ret += found_key.offset;
1313 if (slot + 1 < btrfs_header_nritems(node)) {
1316 ret = btrfs_next_leaf(extent_root, path);
1330 static int __insert_block_group(struct btrfs_trans_handle *trans,
1331 struct chunk_record *chunk_rec,
1332 struct btrfs_root *extent_root,
1335 struct btrfs_block_group_item bg_item;
1336 struct btrfs_key key;
1339 btrfs_set_block_group_used(&bg_item, used);
1340 btrfs_set_block_group_chunk_objectid(&bg_item, used);
1341 btrfs_set_block_group_flags(&bg_item, chunk_rec->type_flags);
1342 key.objectid = chunk_rec->offset;
1343 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1344 key.offset = chunk_rec->length;
1346 ret = btrfs_insert_item(trans, extent_root, &key, &bg_item,
1352 * Search through the extent tree to rebuild the 'used' member of the block
1354 * However, since block group and extent item shares the extent tree,
1355 * the extent item may also missing.
1356 * In that case, we fill the 'used' with the length of the block group to
1357 * ensure no write into the block group.
1358 * Btrfsck will hate it but we will inform user to call '--init-extent-tree'
1359 * if possible, or just salvage as much data as possible from the fs.
1361 static int rebuild_block_group(struct btrfs_trans_handle *trans,
1362 struct recover_control *rc,
1363 struct btrfs_root *root)
1365 struct chunk_record *chunk_rec;
1366 struct btrfs_key search_key;
1367 struct btrfs_path *path;
1371 if (list_empty(&rc->rebuild_chunks))
1374 path = btrfs_alloc_path();
1377 list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1378 search_key.objectid = chunk_rec->offset;
1379 search_key.type = BTRFS_EXTENT_ITEM_KEY;
1380 search_key.offset = 0;
1381 ret = btrfs_search_slot(NULL, root->fs_info->extent_root,
1382 &search_key, path, 0, 0);
1385 ret = calculate_bg_used(root->fs_info->extent_root,
1386 chunk_rec, path, &used);
1388 * Extent tree is damaged, better to rebuild the whole extent
1389 * tree. Currently, change the used to chunk's len to prevent
1390 * write/block reserve happening in that block group.
1394 "Fail to search extent tree for block group: [%llu,%llu]\n",
1396 chunk_rec->offset + chunk_rec->length);
1398 "Mark the block group full to prevent block rsv problems\n");
1399 used = chunk_rec->length;
1401 btrfs_release_path(path);
1402 ret = __insert_block_group(trans, chunk_rec,
1403 root->fs_info->extent_root,
1409 btrfs_free_path(path);
1413 static struct btrfs_root *
1414 open_ctree_with_broken_chunk(struct recover_control *rc)
1416 struct btrfs_fs_info *fs_info;
1417 struct btrfs_super_block *disk_super;
1418 struct extent_buffer *eb;
1425 fs_info = btrfs_new_fs_info(1, BTRFS_SUPER_INFO_OFFSET);
1427 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1428 return ERR_PTR(-ENOMEM);
1430 fs_info->is_chunk_recover = 1;
1432 fs_info->fs_devices = rc->fs_devices;
1433 ret = btrfs_open_devices(fs_info->fs_devices, O_RDWR);
1437 disk_super = fs_info->super_copy;
1438 ret = btrfs_read_dev_super(fs_info->fs_devices->latest_bdev,
1439 disk_super, fs_info->super_bytenr, 1);
1441 fprintf(stderr, "No valid btrfs found\n");
1445 memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1447 ret = btrfs_check_fs_compatibility(disk_super, 1);
1451 nodesize = btrfs_super_nodesize(disk_super);
1452 leafsize = btrfs_super_leafsize(disk_super);
1453 sectorsize = btrfs_super_sectorsize(disk_super);
1454 stripesize = btrfs_super_stripesize(disk_super);
1456 __setup_root(nodesize, leafsize, sectorsize, stripesize,
1457 fs_info->chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1459 ret = build_device_maps_by_chunk_records(rc, fs_info->chunk_root);
1463 ret = btrfs_setup_all_roots(fs_info, 0, 0);
1467 eb = fs_info->tree_root->node;
1468 read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1469 btrfs_header_chunk_tree_uuid(eb),
1472 return fs_info->fs_root;
1474 btrfs_release_all_roots(fs_info);
1476 btrfs_cleanup_all_caches(fs_info);
1478 btrfs_close_devices(fs_info->fs_devices);
1480 btrfs_free_fs_info(fs_info);
1481 return ERR_PTR(ret);
1484 static int recover_prepare(struct recover_control *rc, char *path)
1488 struct btrfs_super_block *sb;
1489 struct btrfs_fs_devices *fs_devices;
1492 fd = open(path, O_RDONLY);
1494 fprintf(stderr, "open %s\n error.\n", path);
1498 sb = malloc(BTRFS_SUPER_INFO_SIZE);
1500 fprintf(stderr, "allocating memory for sb failed.\n");
1505 ret = btrfs_read_dev_super(fd, sb, BTRFS_SUPER_INFO_OFFSET, 1);
1507 fprintf(stderr, "read super block error\n");
1511 rc->sectorsize = btrfs_super_sectorsize(sb);
1512 rc->leafsize = btrfs_super_leafsize(sb);
1513 rc->generation = btrfs_super_generation(sb);
1514 rc->chunk_root_generation = btrfs_super_chunk_root_generation(sb);
1515 rc->csum_size = btrfs_super_csum_size(sb);
1517 /* if seed, the result of scanning below will be partial */
1518 if (btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_SEEDING) {
1519 fprintf(stderr, "this device is seed device\n");
1524 ret = btrfs_scan_fs_devices(fd, path, &fs_devices, 0, 1);
1528 rc->fs_devices = fs_devices;
1531 print_all_devices(&rc->fs_devices->devices);
1540 static int btrfs_get_device_extents(u64 chunk_object,
1541 struct list_head *orphan_devexts,
1542 struct list_head *ret_list)
1544 struct device_extent_record *devext;
1545 struct device_extent_record *next;
1548 list_for_each_entry_safe(devext, next, orphan_devexts, chunk_list) {
1549 if (devext->chunk_offset == chunk_object) {
1550 list_move_tail(&devext->chunk_list, ret_list);
1557 static int calc_num_stripes(u64 type)
1559 if (type & (BTRFS_BLOCK_GROUP_RAID0 |
1560 BTRFS_BLOCK_GROUP_RAID10 |
1561 BTRFS_BLOCK_GROUP_RAID5 |
1562 BTRFS_BLOCK_GROUP_RAID6))
1564 else if (type & (BTRFS_BLOCK_GROUP_RAID1 |
1565 BTRFS_BLOCK_GROUP_DUP))
1571 static inline int calc_sub_nstripes(u64 type)
1573 if (type & BTRFS_BLOCK_GROUP_RAID10)
1579 static int btrfs_verify_device_extents(struct block_group_record *bg,
1580 struct list_head *devexts, int ndevexts)
1582 struct device_extent_record *devext;
1584 int expected_num_stripes;
1586 expected_num_stripes = calc_num_stripes(bg->flags);
1587 if (expected_num_stripes && expected_num_stripes != ndevexts)
1590 strpie_length = calc_stripe_length(bg->flags, bg->offset, ndevexts);
1591 list_for_each_entry(devext, devexts, chunk_list) {
1592 if (devext->length != strpie_length)
1598 static int btrfs_rebuild_unordered_chunk_stripes(struct recover_control *rc,
1599 struct chunk_record *chunk)
1601 struct device_extent_record *devext;
1602 struct btrfs_device *device;
1605 devext = list_first_entry(&chunk->dextents, struct device_extent_record,
1607 for (i = 0; i < chunk->num_stripes; i++) {
1608 chunk->stripes[i].devid = devext->objectid;
1609 chunk->stripes[i].offset = devext->offset;
1610 device = btrfs_find_device_by_devid(rc->fs_devices,
1615 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1618 memcpy(chunk->stripes[i].dev_uuid, device->uuid,
1620 devext = list_next_entry(devext, chunk_list);
1625 static int btrfs_calc_stripe_index(struct chunk_record *chunk, u64 logical)
1627 u64 offset = logical - chunk->offset;
1629 int nr_data_stripes;
1632 stripe_nr = offset / chunk->stripe_len;
1633 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
1634 index = stripe_nr % chunk->num_stripes;
1635 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
1636 index = stripe_nr % (chunk->num_stripes / chunk->sub_stripes);
1637 index *= chunk->sub_stripes;
1638 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
1639 nr_data_stripes = chunk->num_stripes - 1;
1640 index = stripe_nr % nr_data_stripes;
1641 stripe_nr /= nr_data_stripes;
1642 index = (index + stripe_nr) % chunk->num_stripes;
1643 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
1644 nr_data_stripes = chunk->num_stripes - 2;
1645 index = stripe_nr % nr_data_stripes;
1646 stripe_nr /= nr_data_stripes;
1647 index = (index + stripe_nr) % chunk->num_stripes;
1654 /* calc the logical offset which is the start of the next stripe. */
1655 static inline u64 btrfs_next_stripe_logical_offset(struct chunk_record *chunk,
1658 u64 offset = logical - chunk->offset;
1660 offset /= chunk->stripe_len;
1661 offset *= chunk->stripe_len;
1662 offset += chunk->stripe_len;
1664 return offset + chunk->offset;
1667 static int is_extent_record_in_device_extent(struct extent_record *er,
1668 struct device_extent_record *dext,
1673 for (i = 0; i < er->nmirrors; i++) {
1674 if (er->devices[i]->devid == dext->objectid &&
1675 er->offsets[i] >= dext->offset &&
1676 er->offsets[i] < dext->offset + dext->length) {
1685 btrfs_rebuild_ordered_meta_chunk_stripes(struct recover_control *rc,
1686 struct chunk_record *chunk)
1688 u64 start = chunk->offset;
1689 u64 end = chunk->offset + chunk->length;
1690 struct cache_extent *cache;
1691 struct extent_record *er;
1692 struct device_extent_record *devext;
1693 struct device_extent_record *next;
1694 struct btrfs_device *device;
1700 cache = lookup_cache_extent(&rc->eb_cache,
1701 start, chunk->length);
1703 /* No used space, we can reorder the stripes freely. */
1704 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1708 list_splice_init(&chunk->dextents, &devexts);
1710 er = container_of(cache, struct extent_record, cache);
1711 index = btrfs_calc_stripe_index(chunk, er->cache.start);
1712 BUG_ON(index == -1);
1713 if (chunk->stripes[index].devid)
1715 list_for_each_entry_safe(devext, next, &devexts, chunk_list) {
1716 if (is_extent_record_in_device_extent(er, devext, &mirror)) {
1717 chunk->stripes[index].devid = devext->objectid;
1718 chunk->stripes[index].offset = devext->offset;
1719 memcpy(chunk->stripes[index].dev_uuid,
1720 er->devices[mirror]->uuid,
1723 list_move(&devext->chunk_list, &chunk->dextents);
1727 start = btrfs_next_stripe_logical_offset(chunk, er->cache.start);
1729 goto no_extent_record;
1731 cache = lookup_cache_extent(&rc->eb_cache, start, end - start);
1735 if (list_empty(&devexts))
1738 if (chunk->type_flags & (BTRFS_BLOCK_GROUP_RAID5 |
1739 BTRFS_BLOCK_GROUP_RAID6)) {
1740 /* Fixme: try to recover the order by the parity block. */
1741 list_splice_tail(&devexts, &chunk->dextents);
1745 /* There is no data on the lost stripes, we can reorder them freely. */
1746 for (index = 0; index < chunk->num_stripes; index++) {
1747 if (chunk->stripes[index].devid)
1750 devext = list_first_entry(&devexts,
1751 struct device_extent_record,
1753 list_move(&devext->chunk_list, &chunk->dextents);
1755 chunk->stripes[index].devid = devext->objectid;
1756 chunk->stripes[index].offset = devext->offset;
1757 device = btrfs_find_device_by_devid(rc->fs_devices,
1761 list_splice_tail(&devexts, &chunk->dextents);
1764 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1767 memcpy(chunk->stripes[index].dev_uuid, device->uuid,
1773 #define BTRFS_ORDERED_RAID (BTRFS_BLOCK_GROUP_RAID0 | \
1774 BTRFS_BLOCK_GROUP_RAID10 | \
1775 BTRFS_BLOCK_GROUP_RAID5 | \
1776 BTRFS_BLOCK_GROUP_RAID6)
1778 static int btrfs_rebuild_chunk_stripes(struct recover_control *rc,
1779 struct chunk_record *chunk)
1784 * All the data in the system metadata chunk will be dropped,
1785 * so we need not guarantee that the data is right or not, that
1786 * is we can reorder the stripes in the system metadata chunk.
1788 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_METADATA) &&
1789 (chunk->type_flags & BTRFS_ORDERED_RAID))
1790 ret =btrfs_rebuild_ordered_meta_chunk_stripes(rc, chunk);
1791 else if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA) &&
1792 (chunk->type_flags & BTRFS_ORDERED_RAID))
1793 ret = 1; /* Be handled after the fs is opened. */
1795 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1800 static int next_csum(struct btrfs_root *root,
1801 struct extent_buffer **leaf,
1802 struct btrfs_path *path,
1807 struct btrfs_key *key)
1810 struct btrfs_root *csum_root = root->fs_info->csum_root;
1811 struct btrfs_csum_item *csum_item;
1812 u32 blocksize = root->sectorsize;
1813 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1814 int csums_in_item = btrfs_item_size_nr(*leaf, *slot) / csum_size;
1816 if (*csum_offset >= csums_in_item) {
1819 if (*slot >= btrfs_header_nritems(*leaf)) {
1820 ret = btrfs_next_leaf(csum_root, path);
1825 *leaf = path->nodes[0];
1826 *slot = path->slots[0];
1828 btrfs_item_key_to_cpu(*leaf, key, *slot);
1831 if (key->offset + (*csum_offset) * blocksize >= end)
1833 csum_item = btrfs_item_ptr(*leaf, *slot, struct btrfs_csum_item);
1834 csum_item = (struct btrfs_csum_item *)((unsigned char *)csum_item
1835 + (*csum_offset) * csum_size);
1836 read_extent_buffer(*leaf, tree_csum,
1837 (unsigned long)csum_item, csum_size);
1841 static u64 calc_data_offset(struct btrfs_key *key,
1842 struct chunk_record *chunk,
1848 int logical_stripe_nr;
1850 int nr_data_stripes;
1852 data_offset = key->offset + csum_offset * blocksize - chunk->offset;
1853 nr_data_stripes = chunk->num_stripes;
1855 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5)
1856 nr_data_stripes -= 1;
1857 else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6)
1858 nr_data_stripes -= 2;
1860 logical_stripe_nr = data_offset / chunk->stripe_len;
1861 dev_stripe_nr = logical_stripe_nr / nr_data_stripes;
1863 data_offset -= logical_stripe_nr * chunk->stripe_len;
1864 data_offset += dev_stripe_nr * chunk->stripe_len;
1866 return dev_offset + data_offset;
1869 static int check_one_csum(int fd, u64 start, u32 len, u32 tree_csum)
1873 u32 csum_result = ~(u32)0;
1878 ret = pread64(fd, data, len, start);
1879 if (ret < 0 || ret != len) {
1884 csum_result = btrfs_csum_data(NULL, data, csum_result, len);
1885 btrfs_csum_final(csum_result, (char *)&csum_result);
1886 if (csum_result != tree_csum)
1893 static u64 item_end_offset(struct btrfs_root *root, struct btrfs_key *key,
1894 struct extent_buffer *leaf, int slot) {
1895 u32 blocksize = root->sectorsize;
1896 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1898 u64 offset = btrfs_item_size_nr(leaf, slot);
1899 offset /= csum_size;
1900 offset *= blocksize;
1901 offset += key->offset;
1906 static int insert_stripe(struct list_head *devexts,
1907 struct recover_control *rc,
1908 struct chunk_record *chunk,
1910 struct device_extent_record *devext;
1911 struct btrfs_device *dev;
1913 devext = list_entry(devexts->next, struct device_extent_record,
1915 dev = btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1919 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1922 chunk->stripes[index].devid = devext->objectid;
1923 chunk->stripes[index].offset = devext->offset;
1924 memcpy(chunk->stripes[index].dev_uuid, dev->uuid, BTRFS_UUID_SIZE);
1926 list_move(&devext->chunk_list, &chunk->dextents);
1931 static inline int count_devext_records(struct list_head *record_list)
1933 int num_of_records = 0;
1934 struct device_extent_record *devext;
1936 list_for_each_entry(devext, record_list, chunk_list)
1939 return num_of_records;
1942 static int fill_chunk_up(struct chunk_record *chunk, struct list_head *devexts,
1943 struct recover_control *rc)
1948 for (i = 0; i < chunk->num_stripes; i++) {
1949 if (!chunk->stripes[i].devid) {
1950 ret = insert_stripe(devexts, rc, chunk, i);
1959 #define EQUAL_STRIPE (1 << 0)
1961 static int rebuild_raid_data_chunk_stripes(struct recover_control *rc,
1962 struct btrfs_root *root,
1963 struct chunk_record *chunk,
1969 struct btrfs_path path;
1970 struct btrfs_key prev_key;
1971 struct btrfs_key key;
1972 struct btrfs_root *csum_root;
1973 struct extent_buffer *leaf;
1974 struct device_extent_record *devext;
1975 struct device_extent_record *next;
1976 struct btrfs_device *dev;
1977 u64 start = chunk->offset;
1978 u64 end = start + chunk->stripe_len;
1979 u64 chunk_end = chunk->offset + chunk->length;
1980 u64 csum_offset = 0;
1982 u32 blocksize = root->sectorsize;
1985 int num_unordered = 0;
1986 LIST_HEAD(unordered);
1987 LIST_HEAD(candidates);
1989 csum_root = root->fs_info->csum_root;
1990 btrfs_init_path(&path);
1991 list_splice_init(&chunk->dextents, &candidates);
1993 if (list_is_last(candidates.next, &candidates))
1996 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1997 key.type = BTRFS_EXTENT_CSUM_KEY;
2000 ret = btrfs_search_slot(NULL, csum_root, &key, &path, 0, 0);
2002 fprintf(stderr, "Search csum failed(%d)\n", ret);
2005 leaf = path.nodes[0];
2006 slot = path.slots[0];
2008 if (slot >= btrfs_header_nritems(leaf)) {
2009 ret = btrfs_next_leaf(csum_root, &path);
2012 "Walk tree failed(%d)\n", ret);
2014 } else if (ret > 0) {
2015 slot = btrfs_header_nritems(leaf) - 1;
2016 btrfs_item_key_to_cpu(leaf, &key, slot);
2017 if (item_end_offset(root, &key, leaf, slot)
2019 csum_offset = start - key.offset;
2020 csum_offset /= blocksize;
2025 leaf = path.nodes[0];
2026 slot = path.slots[0];
2028 btrfs_item_key_to_cpu(leaf, &key, slot);
2029 ret = btrfs_previous_item(csum_root, &path, 0,
2030 BTRFS_EXTENT_CSUM_KEY);
2034 if (key.offset >= end)
2039 leaf = path.nodes[0];
2040 slot = path.slots[0];
2042 btrfs_item_key_to_cpu(leaf, &prev_key, slot);
2043 if (item_end_offset(root, &prev_key, leaf, slot) > start) {
2044 csum_offset = start - prev_key.offset;
2045 csum_offset /= blocksize;
2046 btrfs_item_key_to_cpu(leaf, &key, slot);
2048 if (key.offset >= end)
2052 if (key.offset + csum_offset * blocksize > chunk_end)
2056 ret = next_csum(root, &leaf, &path, &slot, &csum_offset, &tree_csum,
2059 fprintf(stderr, "Fetch csum failed\n");
2061 } else if (ret == 1) {
2062 if (!(*flags & EQUAL_STRIPE))
2063 *flags |= EQUAL_STRIPE;
2065 } else if (ret == 2)
2068 list_for_each_entry_safe(devext, next, &candidates, chunk_list) {
2069 data_offset = calc_data_offset(&key, chunk, devext->offset,
2070 csum_offset, blocksize);
2071 dev = btrfs_find_device_by_devid(rc->fs_devices,
2072 devext->objectid, 0);
2077 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
2078 devext->objectid, 1));
2080 ret = check_one_csum(dev->fd, data_offset, blocksize,
2085 list_move(&devext->chunk_list, &unordered);
2088 if (list_empty(&candidates)) {
2089 num_unordered = count_devext_records(&unordered);
2090 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6
2091 && num_unordered == 2) {
2092 btrfs_release_path(&path);
2093 ret = fill_chunk_up(chunk, &unordered, rc);
2100 if (list_is_last(candidates.next, &candidates)) {
2101 index = btrfs_calc_stripe_index(chunk,
2102 key.offset + csum_offset * blocksize);
2103 BUG_ON(index == -1);
2104 if (chunk->stripes[index].devid)
2106 ret = insert_stripe(&candidates, rc, chunk, index);
2114 start = btrfs_next_stripe_logical_offset(chunk, start);
2115 end = min(start + chunk->stripe_len, chunk_end);
2116 list_splice_init(&unordered, &candidates);
2117 btrfs_release_path(&path);
2119 if (end < chunk_end)
2123 list_splice_init(&candidates, &unordered);
2124 num_unordered = count_devext_records(&unordered);
2125 if (num_unordered == 1) {
2126 for (i = 0; i < chunk->num_stripes; i++) {
2127 if (!chunk->stripes[i].devid) {
2132 ret = insert_stripe(&unordered, rc, chunk, index);
2136 if ((num_unordered == 2 && chunk->type_flags
2137 & BTRFS_BLOCK_GROUP_RAID5)
2138 || (num_unordered == 3 && chunk->type_flags
2139 & BTRFS_BLOCK_GROUP_RAID6)) {
2140 ret = fill_chunk_up(chunk, &unordered, rc);
2144 ret = !!ret || (list_empty(&unordered) ? 0 : 1);
2145 list_splice_init(&candidates, &chunk->dextents);
2146 list_splice_init(&unordered, &chunk->dextents);
2147 btrfs_release_path(&path);
2152 static int btrfs_rebuild_ordered_data_chunk_stripes(struct recover_control *rc,
2153 struct btrfs_root *root)
2155 struct chunk_record *chunk;
2156 struct chunk_record *next;
2161 list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
2162 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA)
2163 && (chunk->type_flags & BTRFS_ORDERED_RAID)) {
2165 err = rebuild_raid_data_chunk_stripes(rc, root, chunk,
2168 list_move(&chunk->list, &rc->bad_chunks);
2169 if (flags & EQUAL_STRIPE)
2171 "Failure: too many equal stripes in chunk[%llu %llu]\n",
2172 chunk->offset, chunk->length);
2176 list_move(&chunk->list, &rc->good_chunks);
2182 static int btrfs_recover_chunks(struct recover_control *rc)
2184 struct chunk_record *chunk;
2185 struct block_group_record *bg;
2186 struct block_group_record *next;
2187 LIST_HEAD(new_chunks);
2192 /* create the chunk by block group */
2193 list_for_each_entry_safe(bg, next, &rc->bg.block_groups, list) {
2194 nstripes = btrfs_get_device_extents(bg->objectid,
2195 &rc->devext.no_chunk_orphans,
2197 chunk = malloc(btrfs_chunk_record_size(nstripes));
2200 memset(chunk, 0, btrfs_chunk_record_size(nstripes));
2201 INIT_LIST_HEAD(&chunk->dextents);
2203 chunk->cache.start = bg->objectid;
2204 chunk->cache.size = bg->offset;
2205 chunk->objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2206 chunk->type = BTRFS_CHUNK_ITEM_KEY;
2207 chunk->offset = bg->objectid;
2208 chunk->generation = bg->generation;
2209 chunk->length = bg->offset;
2210 chunk->owner = BTRFS_CHUNK_TREE_OBJECTID;
2211 chunk->stripe_len = BTRFS_STRIPE_LEN;
2212 chunk->type_flags = bg->flags;
2213 chunk->io_width = BTRFS_STRIPE_LEN;
2214 chunk->io_align = BTRFS_STRIPE_LEN;
2215 chunk->sector_size = rc->sectorsize;
2216 chunk->sub_stripes = calc_sub_nstripes(bg->flags);
2218 ret = insert_cache_extent(&rc->chunk, &chunk->cache);
2221 list_del_init(&bg->list);
2223 list_add_tail(&chunk->list, &rc->bad_chunks);
2227 list_splice_init(&devexts, &chunk->dextents);
2229 ret = btrfs_verify_device_extents(bg, &devexts, nstripes);
2231 list_add_tail(&chunk->list, &rc->bad_chunks);
2235 chunk->num_stripes = nstripes;
2236 ret = btrfs_rebuild_chunk_stripes(rc, chunk);
2238 list_add_tail(&chunk->list, &rc->unrepaired_chunks);
2240 list_add_tail(&chunk->list, &rc->bad_chunks);
2242 list_add_tail(&chunk->list, &rc->good_chunks);
2245 * Don't worry about the lost orphan device extents, they don't
2246 * have its chunk and block group, they must be the old ones that
2252 static inline int is_chunk_overlap(struct chunk_record *chunk1,
2253 struct chunk_record *chunk2)
2255 if (chunk1->offset >= chunk2->offset + chunk2->length ||
2256 chunk1->offset + chunk1->length <= chunk2->offset)
2261 /* Move invalid(overlap with good chunks) rebuild chunks to bad chunk list */
2262 static void validate_rebuild_chunks(struct recover_control *rc)
2264 struct chunk_record *good;
2265 struct chunk_record *rebuild;
2266 struct chunk_record *tmp;
2268 list_for_each_entry_safe(rebuild, tmp, &rc->rebuild_chunks, list) {
2269 list_for_each_entry(good, &rc->good_chunks, list) {
2270 if (is_chunk_overlap(rebuild, good)) {
2271 list_move_tail(&rebuild->list,
2280 * Return 0 when succesful, < 0 on error and > 0 if aborted by user
2282 int btrfs_recover_chunk_tree(char *path, int verbose, int yes)
2285 struct btrfs_root *root = NULL;
2286 struct btrfs_trans_handle *trans;
2287 struct recover_control rc;
2289 init_recover_control(&rc, verbose, yes);
2291 ret = recover_prepare(&rc, path);
2293 fprintf(stderr, "recover prepare error\n");
2297 ret = scan_devices(&rc);
2299 fprintf(stderr, "scan chunk headers error\n");
2303 if (cache_tree_empty(&rc.chunk) &&
2304 cache_tree_empty(&rc.bg.tree) &&
2305 cache_tree_empty(&rc.devext.tree)) {
2306 fprintf(stderr, "no recoverable chunk\n");
2310 print_scan_result(&rc);
2312 ret = check_chunks(&rc.chunk, &rc.bg, &rc.devext, &rc.good_chunks,
2313 &rc.bad_chunks, &rc.rebuild_chunks, 1);
2315 if (!list_empty(&rc.bg.block_groups) ||
2316 !list_empty(&rc.devext.no_chunk_orphans)) {
2317 ret = btrfs_recover_chunks(&rc);
2322 print_check_result(&rc);
2323 printf("Check chunks successfully with no orphans\n");
2326 validate_rebuild_chunks(&rc);
2327 print_check_result(&rc);
2329 root = open_ctree_with_broken_chunk(&rc);
2331 fprintf(stderr, "open with broken chunk error\n");
2332 ret = PTR_ERR(root);
2336 ret = check_all_chunks_by_metadata(&rc, root);
2338 fprintf(stderr, "The chunks in memory can not match the metadata of the fs. Repair failed.\n");
2339 goto fail_close_ctree;
2342 ret = btrfs_rebuild_ordered_data_chunk_stripes(&rc, root);
2344 fprintf(stderr, "Failed to rebuild ordered chunk stripes.\n");
2345 goto fail_close_ctree;
2349 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?");
2352 goto fail_close_ctree;
2356 trans = btrfs_start_transaction(root, 1);
2357 ret = remove_chunk_extent_item(trans, &rc, root);
2360 ret = rebuild_chunk_tree(trans, &rc, root);
2363 ret = rebuild_sys_array(&rc, root);
2366 ret = rebuild_block_group(trans, &rc, root);
2368 printf("Fail to rebuild block groups.\n");
2369 printf("Recommend to run 'btrfs check --init-extent-tree <dev>' after recovery\n");
2372 btrfs_commit_transaction(trans, root);
2376 free_recover_control(&rc);