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.
19 #include "kerncompat.h"
20 #include "androidcompat.h"
23 #include <stdio_ext.h>
25 #include <sys/types.h>
29 #include <uuid/uuid.h>
33 #include "radix-tree.h"
35 #include "extent-cache.h"
38 #include "transaction.h"
44 struct recover_control {
52 u64 chunk_root_generation;
54 struct btrfs_fs_devices *fs_devices;
56 struct cache_tree chunk;
57 struct block_group_tree bg;
58 struct device_extent_tree devext;
59 struct cache_tree eb_cache;
61 struct list_head good_chunks;
62 struct list_head bad_chunks;
63 struct list_head rebuild_chunks;
64 struct list_head unrepaired_chunks;
65 pthread_mutex_t rc_lock;
68 struct extent_record {
69 struct cache_extent cache;
71 u8 csum[BTRFS_CSUM_SIZE];
72 struct btrfs_device *devices[BTRFS_MAX_MIRRORS];
73 u64 offsets[BTRFS_MAX_MIRRORS];
78 struct recover_control *rc;
79 struct btrfs_device *dev;
84 static struct extent_record *btrfs_new_extent_record(struct extent_buffer *eb)
86 struct extent_record *rec;
88 rec = malloc(sizeof(*rec));
90 fprintf(stderr, "Fail to allocate memory for extent record.\n");
94 memset(rec, 0, sizeof(*rec));
95 rec->cache.start = btrfs_header_bytenr(eb);
96 rec->cache.size = eb->len;
97 rec->generation = btrfs_header_generation(eb);
98 read_extent_buffer(eb, rec->csum, (unsigned long)btrfs_header_csum(eb),
103 static int process_extent_buffer(struct cache_tree *eb_cache,
104 struct extent_buffer *eb,
105 struct btrfs_device *device, u64 offset)
107 struct extent_record *rec;
108 struct extent_record *exist;
109 struct cache_extent *cache;
112 rec = btrfs_new_extent_record(eb);
113 if (!rec->cache.size)
116 cache = lookup_cache_extent(eb_cache,
120 exist = container_of(cache, struct extent_record, cache);
122 if (exist->generation > rec->generation)
124 if (exist->generation == rec->generation) {
125 if (exist->cache.start != rec->cache.start ||
126 exist->cache.size != rec->cache.size ||
127 memcmp(exist->csum, rec->csum, BTRFS_CSUM_SIZE)) {
130 BUG_ON(exist->nmirrors >= BTRFS_MAX_MIRRORS);
131 exist->devices[exist->nmirrors] = device;
132 exist->offsets[exist->nmirrors] = offset;
137 remove_cache_extent(eb_cache, cache);
142 rec->devices[0] = device;
143 rec->offsets[0] = offset;
145 ret = insert_cache_extent(eb_cache, &rec->cache);
154 static void free_extent_record(struct cache_extent *cache)
156 struct extent_record *er;
158 er = container_of(cache, struct extent_record, cache);
162 FREE_EXTENT_CACHE_BASED_TREE(extent_record, free_extent_record);
164 static struct btrfs_chunk *create_chunk_item(struct chunk_record *record)
166 struct btrfs_chunk *ret;
167 struct btrfs_stripe *chunk_stripe;
170 if (!record || record->num_stripes == 0)
172 ret = malloc(btrfs_chunk_item_size(record->num_stripes));
175 btrfs_set_stack_chunk_length(ret, record->length);
176 btrfs_set_stack_chunk_owner(ret, record->owner);
177 btrfs_set_stack_chunk_stripe_len(ret, record->stripe_len);
178 btrfs_set_stack_chunk_type(ret, record->type_flags);
179 btrfs_set_stack_chunk_io_align(ret, record->io_align);
180 btrfs_set_stack_chunk_io_width(ret, record->io_width);
181 btrfs_set_stack_chunk_sector_size(ret, record->sector_size);
182 btrfs_set_stack_chunk_num_stripes(ret, record->num_stripes);
183 btrfs_set_stack_chunk_sub_stripes(ret, record->sub_stripes);
184 for (i = 0, chunk_stripe = &ret->stripe; i < record->num_stripes;
185 i++, chunk_stripe++) {
186 btrfs_set_stack_stripe_devid(chunk_stripe,
187 record->stripes[i].devid);
188 btrfs_set_stack_stripe_offset(chunk_stripe,
189 record->stripes[i].offset);
190 memcpy(chunk_stripe->dev_uuid, record->stripes[i].dev_uuid,
196 static void init_recover_control(struct recover_control *rc, int verbose,
199 memset(rc, 0, sizeof(struct recover_control));
200 cache_tree_init(&rc->chunk);
201 cache_tree_init(&rc->eb_cache);
202 block_group_tree_init(&rc->bg);
203 device_extent_tree_init(&rc->devext);
205 INIT_LIST_HEAD(&rc->good_chunks);
206 INIT_LIST_HEAD(&rc->bad_chunks);
207 INIT_LIST_HEAD(&rc->rebuild_chunks);
208 INIT_LIST_HEAD(&rc->unrepaired_chunks);
210 rc->verbose = verbose;
212 pthread_mutex_init(&rc->rc_lock, NULL);
215 static void free_recover_control(struct recover_control *rc)
217 free_block_group_tree(&rc->bg);
218 free_chunk_cache_tree(&rc->chunk);
219 free_device_extent_tree(&rc->devext);
220 free_extent_record_tree(&rc->eb_cache);
221 pthread_mutex_destroy(&rc->rc_lock);
224 static int process_block_group_item(struct block_group_tree *bg_cache,
225 struct extent_buffer *leaf,
226 struct btrfs_key *key, int slot)
228 struct block_group_record *rec;
229 struct block_group_record *exist;
230 struct cache_extent *cache;
233 rec = btrfs_new_block_group_record(leaf, key, slot);
234 if (!rec->cache.size)
237 cache = lookup_cache_extent(&bg_cache->tree,
241 exist = container_of(cache, struct block_group_record, cache);
243 /*check the generation and replace if needed*/
244 if (exist->generation > rec->generation)
246 if (exist->generation == rec->generation) {
247 int offset = offsetof(struct block_group_record,
250 * According to the current kernel code, the following
251 * case is impossble, or there is something wrong in
254 if (memcmp(((void *)exist) + offset,
255 ((void *)rec) + offset,
256 sizeof(*rec) - offset))
260 remove_cache_extent(&bg_cache->tree, cache);
261 list_del_init(&exist->list);
264 * We must do search again to avoid the following cache.
265 * /--old bg 1--//--old bg 2--/
271 ret = insert_block_group_record(bg_cache, rec);
280 static int process_chunk_item(struct cache_tree *chunk_cache,
281 struct extent_buffer *leaf, struct btrfs_key *key,
284 struct chunk_record *rec;
285 struct chunk_record *exist;
286 struct cache_extent *cache;
289 rec = btrfs_new_chunk_record(leaf, key, slot);
290 if (!rec->cache.size)
293 cache = lookup_cache_extent(chunk_cache, rec->offset, rec->length);
295 exist = container_of(cache, struct chunk_record, cache);
297 if (exist->generation > rec->generation)
299 if (exist->generation == rec->generation) {
300 int num_stripes = rec->num_stripes;
301 int rec_size = btrfs_chunk_record_size(num_stripes);
302 int offset = offsetof(struct chunk_record, generation);
304 if (exist->num_stripes != rec->num_stripes ||
305 memcmp(((void *)exist) + offset,
306 ((void *)rec) + offset,
311 remove_cache_extent(chunk_cache, cache);
315 ret = insert_cache_extent(chunk_cache, &rec->cache);
324 static int process_device_extent_item(struct device_extent_tree *devext_cache,
325 struct extent_buffer *leaf,
326 struct btrfs_key *key, int slot)
328 struct device_extent_record *rec;
329 struct device_extent_record *exist;
330 struct cache_extent *cache;
333 rec = btrfs_new_device_extent_record(leaf, key, slot);
334 if (!rec->cache.size)
337 cache = lookup_cache_extent2(&devext_cache->tree,
342 exist = container_of(cache, struct device_extent_record, cache);
343 if (exist->generation > rec->generation)
345 if (exist->generation == rec->generation) {
346 int offset = offsetof(struct device_extent_record,
348 if (memcmp(((void *)exist) + offset,
349 ((void *)rec) + offset,
350 sizeof(*rec) - offset))
354 remove_cache_extent(&devext_cache->tree, cache);
355 list_del_init(&exist->chunk_list);
356 list_del_init(&exist->device_list);
361 ret = insert_device_extent_record(devext_cache, rec);
370 static void print_block_group_info(struct block_group_record *rec, char *prefix)
373 printf("%s", prefix);
374 printf("Block Group: start = %llu, len = %llu, flag = %llx\n",
375 rec->objectid, rec->offset, rec->flags);
378 static void print_block_group_tree(struct block_group_tree *tree)
380 struct cache_extent *cache;
381 struct block_group_record *rec;
383 printf("All Block Groups:\n");
384 for (cache = first_cache_extent(&tree->tree); cache;
385 cache = next_cache_extent(cache)) {
386 rec = container_of(cache, struct block_group_record, cache);
387 print_block_group_info(rec, "\t");
392 static void print_stripe_info(struct stripe *data, char *prefix1, char *prefix2,
396 printf("%s", prefix1);
398 printf("%s", prefix2);
399 printf("[%2d] Stripe: devid = %llu, offset = %llu\n",
400 index, data->devid, data->offset);
403 static void print_chunk_self_info(struct chunk_record *rec, char *prefix)
408 printf("%s", prefix);
409 printf("Chunk: start = %llu, len = %llu, type = %llx, num_stripes = %u\n",
410 rec->offset, rec->length, rec->type_flags, rec->num_stripes);
412 printf("%s", prefix);
413 printf(" Stripes list:\n");
414 for (i = 0; i < rec->num_stripes; i++)
415 print_stripe_info(&rec->stripes[i], prefix, " ", i);
418 static void print_chunk_tree(struct cache_tree *tree)
420 struct cache_extent *n;
421 struct chunk_record *entry;
423 printf("All Chunks:\n");
424 for (n = first_cache_extent(tree); n;
425 n = next_cache_extent(n)) {
426 entry = container_of(n, struct chunk_record, cache);
427 print_chunk_self_info(entry, "\t");
432 static void print_device_extent_info(struct device_extent_record *rec,
436 printf("%s", prefix);
437 printf("Device extent: devid = %llu, start = %llu, len = %llu, chunk offset = %llu\n",
438 rec->objectid, rec->offset, rec->length, rec->chunk_offset);
441 static void print_device_extent_tree(struct device_extent_tree *tree)
443 struct cache_extent *n;
444 struct device_extent_record *entry;
446 printf("All Device Extents:\n");
447 for (n = first_cache_extent(&tree->tree); n;
448 n = next_cache_extent(n)) {
449 entry = container_of(n, struct device_extent_record, cache);
450 print_device_extent_info(entry, "\t");
455 static void print_device_info(struct btrfs_device *device, char *prefix)
458 printf("%s", prefix);
459 printf("Device: id = %llu, name = %s\n",
460 device->devid, device->name);
463 static void print_all_devices(struct list_head *devices)
465 struct btrfs_device *dev;
467 printf("All Devices:\n");
468 list_for_each_entry(dev, devices, dev_list)
469 print_device_info(dev, "\t");
473 static void print_scan_result(struct recover_control *rc)
478 printf("DEVICE SCAN RESULT:\n");
479 printf("Filesystem Information:\n");
480 printf("\tsectorsize: %d\n", rc->sectorsize);
481 printf("\tleafsize: %d\n", rc->leafsize);
482 printf("\ttree root generation: %llu\n", rc->generation);
483 printf("\tchunk root generation: %llu\n", rc->chunk_root_generation);
486 print_all_devices(&rc->fs_devices->devices);
487 print_block_group_tree(&rc->bg);
488 print_chunk_tree(&rc->chunk);
489 print_device_extent_tree(&rc->devext);
492 static void print_chunk_info(struct chunk_record *chunk, char *prefix)
494 struct device_extent_record *devext;
497 print_chunk_self_info(chunk, prefix);
499 printf("%s", prefix);
501 print_block_group_info(chunk->bg_rec, " ");
503 printf(" No block group.\n");
505 printf("%s", prefix);
506 if (list_empty(&chunk->dextents)) {
507 printf(" No device extent.\n");
509 printf(" Device extent list:\n");
511 list_for_each_entry(devext, &chunk->dextents, chunk_list) {
513 printf("%s", prefix);
514 printf("%s[%2d]", " ", i);
515 print_device_extent_info(devext, NULL);
521 static void print_check_result(struct recover_control *rc)
523 struct chunk_record *chunk;
524 struct block_group_record *bg;
525 struct device_extent_record *devext;
533 printf("CHECK RESULT:\n");
534 printf("Recoverable Chunks:\n");
535 list_for_each_entry(chunk, &rc->good_chunks, list) {
536 print_chunk_info(chunk, " ");
540 list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
541 print_chunk_info(chunk, " ");
545 list_for_each_entry(chunk, &rc->unrepaired_chunks, list) {
546 print_chunk_info(chunk, " ");
550 printf("Unrecoverable Chunks:\n");
551 list_for_each_entry(chunk, &rc->bad_chunks, list) {
552 print_chunk_info(chunk, " ");
557 printf("Total Chunks:\t\t%d\n", total);
558 printf(" Recoverable:\t\t%d\n", good);
559 printf(" Unrecoverable:\t%d\n", bad);
562 printf("Orphan Block Groups:\n");
563 list_for_each_entry(bg, &rc->bg.block_groups, list)
564 print_block_group_info(bg, " ");
567 printf("Orphan Device Extents:\n");
568 list_for_each_entry(devext, &rc->devext.no_chunk_orphans, chunk_list)
569 print_device_extent_info(devext, " ");
573 static int check_chunk_by_metadata(struct recover_control *rc,
574 struct btrfs_root *root,
575 struct chunk_record *chunk, int bg_only)
580 struct btrfs_path path;
581 struct btrfs_key key;
582 struct btrfs_root *dev_root;
583 struct stripe *stripe;
584 struct btrfs_dev_extent *dev_extent;
585 struct btrfs_block_group_item *bg_ptr;
586 struct extent_buffer *l;
588 btrfs_init_path(&path);
593 dev_root = root->fs_info->dev_root;
594 for (i = 0; i < chunk->num_stripes; i++) {
595 stripe = &chunk->stripes[i];
597 key.objectid = stripe->devid;
598 key.offset = stripe->offset;
599 key.type = BTRFS_DEV_EXTENT_KEY;
601 ret = btrfs_search_slot(NULL, dev_root, &key, &path, 0, 0);
603 fprintf(stderr, "Search device extent failed(%d)\n",
605 btrfs_release_path(&path);
607 } else if (ret > 0) {
610 "No device extent[%llu, %llu]\n",
611 stripe->devid, stripe->offset);
612 btrfs_release_path(&path);
616 slot = path.slots[0];
617 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
619 btrfs_dev_extent_chunk_offset(l, dev_extent)) {
622 "Device tree unmatch with chunks dev_extent[%llu, %llu], chunk[%llu, %llu]\n",
623 btrfs_dev_extent_chunk_offset(l,
625 btrfs_dev_extent_length(l, dev_extent),
626 chunk->offset, chunk->length);
627 btrfs_release_path(&path);
630 btrfs_release_path(&path);
634 key.objectid = chunk->offset;
635 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
636 key.offset = chunk->length;
638 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, &path,
641 fprintf(stderr, "Search block group failed(%d)\n", ret);
642 btrfs_release_path(&path);
644 } else if (ret > 0) {
646 fprintf(stderr, "No block group[%llu, %llu]\n",
647 key.objectid, key.offset);
648 btrfs_release_path(&path);
653 slot = path.slots[0];
654 bg_ptr = btrfs_item_ptr(l, slot, struct btrfs_block_group_item);
655 if (chunk->type_flags != btrfs_disk_block_group_flags(l, bg_ptr)) {
658 "Chunk[%llu, %llu]'s type(%llu) is differemt with Block Group's type(%llu)\n",
659 chunk->offset, chunk->length, chunk->type_flags,
660 btrfs_disk_block_group_flags(l, bg_ptr));
661 btrfs_release_path(&path);
664 btrfs_release_path(&path);
668 static int check_all_chunks_by_metadata(struct recover_control *rc,
669 struct btrfs_root *root)
671 struct chunk_record *chunk;
672 struct chunk_record *next;
673 LIST_HEAD(orphan_chunks);
677 list_for_each_entry_safe(chunk, next, &rc->good_chunks, list) {
678 err = check_chunk_by_metadata(rc, root, chunk, 0);
681 list_move_tail(&chunk->list, &orphan_chunks);
682 else if (err && !ret)
687 list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
688 err = check_chunk_by_metadata(rc, root, chunk, 1);
690 list_move_tail(&chunk->list, &orphan_chunks);
691 else if (err && !ret)
695 list_for_each_entry(chunk, &rc->bad_chunks, list) {
696 err = check_chunk_by_metadata(rc, root, chunk, 1);
697 if (err != -ENOENT && !ret)
698 ret = err ? err : -EINVAL;
700 list_splice(&orphan_chunks, &rc->bad_chunks);
704 static int extract_metadata_record(struct recover_control *rc,
705 struct extent_buffer *leaf)
707 struct btrfs_key key;
712 nritems = btrfs_header_nritems(leaf);
713 for (i = 0; i < nritems; i++) {
714 btrfs_item_key_to_cpu(leaf, &key, i);
716 case BTRFS_BLOCK_GROUP_ITEM_KEY:
717 pthread_mutex_lock(&rc->rc_lock);
718 ret = process_block_group_item(&rc->bg, leaf, &key, i);
719 pthread_mutex_unlock(&rc->rc_lock);
721 case BTRFS_CHUNK_ITEM_KEY:
722 pthread_mutex_lock(&rc->rc_lock);
723 ret = process_chunk_item(&rc->chunk, leaf, &key, i);
724 pthread_mutex_unlock(&rc->rc_lock);
726 case BTRFS_DEV_EXTENT_KEY:
727 pthread_mutex_lock(&rc->rc_lock);
728 ret = process_device_extent_item(&rc->devext, leaf,
730 pthread_mutex_unlock(&rc->rc_lock);
739 static inline int is_super_block_address(u64 offset)
743 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
744 if (offset == btrfs_sb_offset(i))
750 static int scan_one_device(void *dev_scan_struct)
752 struct extent_buffer *buf;
755 struct device_scan *dev_scan = (struct device_scan *)dev_scan_struct;
756 struct recover_control *rc = dev_scan->rc;
757 struct btrfs_device *device = dev_scan->dev;
758 int fd = dev_scan->fd;
761 ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
765 buf = malloc(sizeof(*buf) + rc->leafsize);
768 buf->len = rc->leafsize;
772 dev_scan->bytenr = bytenr;
774 if (is_super_block_address(bytenr))
775 bytenr += rc->sectorsize;
777 if (pread64(fd, buf->data, rc->leafsize, bytenr) <
781 if (memcmp_extent_buffer(buf, rc->fs_devices->fsid,
784 bytenr += rc->sectorsize;
788 if (verify_tree_block_csum_silent(buf, rc->csum_size)) {
789 bytenr += rc->sectorsize;
793 pthread_mutex_lock(&rc->rc_lock);
794 ret = process_extent_buffer(&rc->eb_cache, buf, device, bytenr);
795 pthread_mutex_unlock(&rc->rc_lock);
799 if (btrfs_header_level(buf) != 0)
802 switch (btrfs_header_owner(buf)) {
803 case BTRFS_EXTENT_TREE_OBJECTID:
804 case BTRFS_DEV_TREE_OBJECTID:
805 /* different tree use different generation */
806 if (btrfs_header_generation(buf) > rc->generation)
808 ret = extract_metadata_record(rc, buf);
812 case BTRFS_CHUNK_TREE_OBJECTID:
813 if (btrfs_header_generation(buf) >
814 rc->chunk_root_generation)
816 ret = extract_metadata_record(rc, buf);
822 bytenr += rc->leafsize;
830 static int scan_devices(struct recover_control *rc)
834 struct btrfs_device *dev;
835 struct device_scan *dev_scans;
843 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list)
845 dev_scans = (struct device_scan *)malloc(sizeof(struct device_scan)
849 t_scans = (pthread_t *)malloc(sizeof(pthread_t) * devnr);
852 t_rets = (long *)malloc(sizeof(long) * devnr);
856 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
857 fd = open(dev->name, O_RDONLY);
859 fprintf(stderr, "Failed to open device %s\n",
864 dev_scans[devidx].rc = rc;
865 dev_scans[devidx].dev = dev;
866 dev_scans[devidx].fd = fd;
867 dev_scans[devidx].bytenr = -1;
871 for (i = 0; i < devidx; i++) {
872 ret = pthread_create(&t_scans[i], NULL,
873 (void *)scan_one_device,
874 (void *)&dev_scans[i]);
878 dev_scans[i].bytenr = 0;
883 for (i = 0; i < devidx; i++) {
884 if (dev_scans[i].bytenr == -1)
886 ret = pthread_tryjoin_np(t_scans[i],
887 (void **)&t_rets[i]);
892 if (ret || t_rets[i]) {
896 dev_scans[i].bytenr = -1;
899 printf("\rScanning: ");
900 for (i = 0; i < devidx; i++) {
901 if (dev_scans[i].bytenr == -1)
902 printf("%sDONE in dev%d",
905 printf("%s%llu in dev%d",
906 i ? ", " : "", dev_scans[i].bytenr, i);
908 /* clear chars if exist in tail */
910 printf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
921 for (i = 0; i < devidx; i++) {
922 if (dev_scans[i].bytenr == -1)
924 pthread_cancel(t_scans[i]);
933 static int build_device_map_by_chunk_record(struct btrfs_root *root,
934 struct chunk_record *chunk)
939 u8 uuid[BTRFS_UUID_SIZE];
941 struct btrfs_mapping_tree *map_tree;
942 struct map_lookup *map;
943 struct stripe *stripe;
945 map_tree = &root->fs_info->mapping_tree;
946 num_stripes = chunk->num_stripes;
947 map = malloc(btrfs_map_lookup_size(num_stripes));
950 map->ce.start = chunk->offset;
951 map->ce.size = chunk->length;
952 map->num_stripes = num_stripes;
953 map->io_width = chunk->io_width;
954 map->io_align = chunk->io_align;
955 map->sector_size = chunk->sector_size;
956 map->stripe_len = chunk->stripe_len;
957 map->type = chunk->type_flags;
958 map->sub_stripes = chunk->sub_stripes;
960 for (i = 0, stripe = chunk->stripes; i < num_stripes; i++, stripe++) {
961 devid = stripe->devid;
962 memcpy(uuid, stripe->dev_uuid, BTRFS_UUID_SIZE);
963 map->stripes[i].physical = stripe->offset;
964 map->stripes[i].dev = btrfs_find_device(root, devid,
966 if (!map->stripes[i].dev) {
972 ret = insert_cache_extent(&map_tree->cache_tree, &map->ce);
976 static int build_device_maps_by_chunk_records(struct recover_control *rc,
977 struct btrfs_root *root)
980 struct chunk_record *chunk;
982 list_for_each_entry(chunk, &rc->good_chunks, list) {
983 ret = build_device_map_by_chunk_record(root, chunk);
987 list_for_each_entry(chunk, &rc->rebuild_chunks, list) {
988 ret = build_device_map_by_chunk_record(root, chunk);
995 static int block_group_remove_all_extent_items(struct btrfs_trans_handle *trans,
996 struct btrfs_root *root,
997 struct block_group_record *bg)
999 struct btrfs_fs_info *fs_info = root->fs_info;
1000 struct btrfs_key key;
1001 struct btrfs_path path;
1002 struct extent_buffer *leaf;
1003 u64 start = bg->objectid;
1004 u64 end = bg->objectid + bg->offset;
1011 btrfs_init_path(&path);
1012 root = root->fs_info->extent_root;
1014 key.objectid = start;
1016 key.type = BTRFS_EXTENT_ITEM_KEY;
1018 ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
1024 leaf = path.nodes[0];
1025 nitems = btrfs_header_nritems(leaf);
1027 /* The tree is empty. */
1032 if (path.slots[0] >= nitems) {
1033 ret = btrfs_next_leaf(root, &path);
1040 leaf = path.nodes[0];
1041 btrfs_item_key_to_cpu(leaf, &key, 0);
1042 if (key.objectid >= end)
1044 btrfs_release_path(&path);
1050 for (i = path.slots[0]; i < nitems; i++) {
1051 btrfs_item_key_to_cpu(leaf, &key, i);
1052 if (key.objectid >= end)
1055 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1065 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
1066 key.type == BTRFS_METADATA_ITEM_KEY) {
1067 old_val = btrfs_super_bytes_used(fs_info->super_copy);
1068 if (key.type == BTRFS_METADATA_ITEM_KEY)
1069 old_val += root->leafsize;
1071 old_val += key.offset;
1072 btrfs_set_super_bytes_used(fs_info->super_copy,
1078 ret = btrfs_del_items(trans, root, &path, del_s, del_nr);
1083 if (key.objectid < end) {
1084 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1085 key.objectid += root->sectorsize;
1086 key.type = BTRFS_EXTENT_ITEM_KEY;
1089 btrfs_release_path(&path);
1093 btrfs_release_path(&path);
1097 static int block_group_free_all_extent(struct btrfs_root *root,
1098 struct block_group_record *bg)
1100 struct btrfs_block_group_cache *cache;
1101 struct btrfs_fs_info *info;
1105 info = root->fs_info;
1106 cache = btrfs_lookup_block_group(info, bg->objectid);
1110 start = cache->key.objectid;
1111 end = start + cache->key.offset - 1;
1113 set_extent_bits(&info->block_group_cache, start, end,
1114 BLOCK_GROUP_DIRTY, GFP_NOFS);
1115 set_extent_dirty(&info->free_space_cache, start, end, GFP_NOFS);
1117 btrfs_set_block_group_used(&cache->item, 0);
1122 static int remove_chunk_extent_item(struct btrfs_trans_handle *trans,
1123 struct recover_control *rc,
1124 struct btrfs_root *root)
1126 struct chunk_record *chunk;
1129 list_for_each_entry(chunk, &rc->good_chunks, list) {
1130 if (!(chunk->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1132 ret = block_group_remove_all_extent_items(trans, root,
1137 ret = block_group_free_all_extent(root, chunk->bg_rec);
1144 static int __rebuild_chunk_root(struct btrfs_trans_handle *trans,
1145 struct recover_control *rc,
1146 struct btrfs_root *root)
1149 struct btrfs_device *dev;
1150 struct extent_buffer *cow;
1151 struct btrfs_disk_key disk_key;
1154 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1155 if (min_devid > dev->devid)
1156 min_devid = dev->devid;
1158 disk_key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1159 disk_key.type = BTRFS_DEV_ITEM_KEY;
1160 disk_key.offset = min_devid;
1162 cow = btrfs_alloc_free_block(trans, root, root->nodesize,
1163 BTRFS_CHUNK_TREE_OBJECTID,
1164 &disk_key, 0, 0, 0);
1165 btrfs_set_header_bytenr(cow, cow->start);
1166 btrfs_set_header_generation(cow, trans->transid);
1167 btrfs_set_header_nritems(cow, 0);
1168 btrfs_set_header_level(cow, 0);
1169 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1170 btrfs_set_header_owner(cow, BTRFS_CHUNK_TREE_OBJECTID);
1171 write_extent_buffer(cow, root->fs_info->fsid,
1172 btrfs_header_fsid(), BTRFS_FSID_SIZE);
1174 write_extent_buffer(cow, root->fs_info->chunk_tree_uuid,
1175 btrfs_header_chunk_tree_uuid(cow),
1179 btrfs_mark_buffer_dirty(cow);
1184 static int __rebuild_device_items(struct btrfs_trans_handle *trans,
1185 struct recover_control *rc,
1186 struct btrfs_root *root)
1188 struct btrfs_device *dev;
1189 struct btrfs_key key;
1190 struct btrfs_dev_item *dev_item;
1193 dev_item = malloc(sizeof(struct btrfs_dev_item));
1197 list_for_each_entry(dev, &rc->fs_devices->devices, dev_list) {
1198 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1199 key.type = BTRFS_DEV_ITEM_KEY;
1200 key.offset = dev->devid;
1202 btrfs_set_stack_device_generation(dev_item, 0);
1203 btrfs_set_stack_device_type(dev_item, dev->type);
1204 btrfs_set_stack_device_id(dev_item, dev->devid);
1205 btrfs_set_stack_device_total_bytes(dev_item, dev->total_bytes);
1206 btrfs_set_stack_device_bytes_used(dev_item, dev->bytes_used);
1207 btrfs_set_stack_device_io_align(dev_item, dev->io_align);
1208 btrfs_set_stack_device_io_width(dev_item, dev->io_width);
1209 btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
1210 memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
1211 memcpy(dev_item->fsid, dev->fs_devices->fsid, BTRFS_UUID_SIZE);
1213 ret = btrfs_insert_item(trans, root, &key,
1214 dev_item, sizeof(*dev_item));
1221 static int __insert_chunk_item(struct btrfs_trans_handle *trans,
1222 struct chunk_record *chunk_rec,
1223 struct btrfs_root *chunk_root)
1225 struct btrfs_key key;
1226 struct btrfs_chunk *chunk = NULL;
1229 chunk = create_chunk_item(chunk_rec);
1232 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1233 key.type = BTRFS_CHUNK_ITEM_KEY;
1234 key.offset = chunk_rec->offset;
1236 ret = btrfs_insert_item(trans, chunk_root, &key, chunk,
1237 btrfs_chunk_item_size(chunk->num_stripes));
1242 static int __rebuild_chunk_items(struct btrfs_trans_handle *trans,
1243 struct recover_control *rc,
1244 struct btrfs_root *root)
1246 struct btrfs_root *chunk_root;
1247 struct chunk_record *chunk_rec;
1250 chunk_root = root->fs_info->chunk_root;
1252 list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1253 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1257 list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1258 ret = __insert_chunk_item(trans, chunk_rec, chunk_root);
1265 static int rebuild_chunk_tree(struct btrfs_trans_handle *trans,
1266 struct recover_control *rc,
1267 struct btrfs_root *root)
1271 root = root->fs_info->chunk_root;
1273 ret = __rebuild_chunk_root(trans, rc, root);
1277 ret = __rebuild_device_items(trans, rc, root);
1281 ret = __rebuild_chunk_items(trans, rc, root);
1286 static int rebuild_sys_array(struct recover_control *rc,
1287 struct btrfs_root *root)
1289 struct btrfs_chunk *chunk;
1290 struct btrfs_key key;
1291 struct chunk_record *chunk_rec;
1295 btrfs_set_super_sys_array_size(root->fs_info->super_copy, 0);
1297 list_for_each_entry(chunk_rec, &rc->good_chunks, list) {
1298 if (!(chunk_rec->type_flags & BTRFS_BLOCK_GROUP_SYSTEM))
1301 num_stripes = chunk_rec->num_stripes;
1302 chunk = create_chunk_item(chunk_rec);
1308 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
1309 key.type = BTRFS_CHUNK_ITEM_KEY;
1310 key.offset = chunk_rec->offset;
1312 ret = btrfs_add_system_chunk(NULL, root, &key, chunk,
1313 btrfs_chunk_item_size(num_stripes));
1322 static int calculate_bg_used(struct btrfs_root *extent_root,
1323 struct chunk_record *chunk_rec,
1324 struct btrfs_path *path,
1327 struct extent_buffer *node;
1328 struct btrfs_key found_key;
1334 node = path->nodes[0];
1335 slot = path->slots[0];
1336 btrfs_item_key_to_cpu(node, &found_key, slot);
1337 if (found_key.objectid >= chunk_rec->offset + chunk_rec->length)
1339 if (found_key.type != BTRFS_METADATA_ITEM_KEY &&
1340 found_key.type != BTRFS_EXTENT_DATA_KEY)
1342 if (found_key.type == BTRFS_METADATA_ITEM_KEY)
1343 used_ret += extent_root->nodesize;
1345 used_ret += found_key.offset;
1347 if (slot + 1 < btrfs_header_nritems(node)) {
1350 ret = btrfs_next_leaf(extent_root, path);
1364 static int __insert_block_group(struct btrfs_trans_handle *trans,
1365 struct chunk_record *chunk_rec,
1366 struct btrfs_root *extent_root,
1369 struct btrfs_block_group_item bg_item;
1370 struct btrfs_key key;
1373 btrfs_set_block_group_used(&bg_item, used);
1374 btrfs_set_block_group_chunk_objectid(&bg_item, used);
1375 btrfs_set_block_group_flags(&bg_item, chunk_rec->type_flags);
1376 key.objectid = chunk_rec->offset;
1377 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1378 key.offset = chunk_rec->length;
1380 ret = btrfs_insert_item(trans, extent_root, &key, &bg_item,
1386 * Search through the extent tree to rebuild the 'used' member of the block
1388 * However, since block group and extent item shares the extent tree,
1389 * the extent item may also missing.
1390 * In that case, we fill the 'used' with the length of the block group to
1391 * ensure no write into the block group.
1392 * Btrfsck will hate it but we will inform user to call '--init-extent-tree'
1393 * if possible, or just salvage as much data as possible from the fs.
1395 static int rebuild_block_group(struct btrfs_trans_handle *trans,
1396 struct recover_control *rc,
1397 struct btrfs_root *root)
1399 struct chunk_record *chunk_rec;
1400 struct btrfs_key search_key;
1401 struct btrfs_path *path;
1405 if (list_empty(&rc->rebuild_chunks))
1408 path = btrfs_alloc_path();
1411 list_for_each_entry(chunk_rec, &rc->rebuild_chunks, list) {
1412 search_key.objectid = chunk_rec->offset;
1413 search_key.type = BTRFS_EXTENT_ITEM_KEY;
1414 search_key.offset = 0;
1415 ret = btrfs_search_slot(NULL, root->fs_info->extent_root,
1416 &search_key, path, 0, 0);
1419 ret = calculate_bg_used(root->fs_info->extent_root,
1420 chunk_rec, path, &used);
1422 * Extent tree is damaged, better to rebuild the whole extent
1423 * tree. Currently, change the used to chunk's len to prevent
1424 * write/block reserve happening in that block group.
1428 "Fail to search extent tree for block group: [%llu,%llu]\n",
1430 chunk_rec->offset + chunk_rec->length);
1432 "Mark the block group full to prevent block rsv problems\n");
1433 used = chunk_rec->length;
1435 btrfs_release_path(path);
1436 ret = __insert_block_group(trans, chunk_rec,
1437 root->fs_info->extent_root,
1443 btrfs_free_path(path);
1447 static struct btrfs_root *
1448 open_ctree_with_broken_chunk(struct recover_control *rc)
1450 struct btrfs_fs_info *fs_info;
1451 struct btrfs_super_block *disk_super;
1452 struct extent_buffer *eb;
1459 fs_info = btrfs_new_fs_info(1, BTRFS_SUPER_INFO_OFFSET);
1461 fprintf(stderr, "Failed to allocate memory for fs_info\n");
1462 return ERR_PTR(-ENOMEM);
1464 fs_info->is_chunk_recover = 1;
1466 fs_info->fs_devices = rc->fs_devices;
1467 ret = btrfs_open_devices(fs_info->fs_devices, O_RDWR);
1471 disk_super = fs_info->super_copy;
1472 ret = btrfs_read_dev_super(fs_info->fs_devices->latest_bdev,
1473 disk_super, fs_info->super_bytenr, 1);
1475 fprintf(stderr, "No valid btrfs found\n");
1479 memcpy(fs_info->fsid, &disk_super->fsid, BTRFS_FSID_SIZE);
1481 ret = btrfs_check_fs_compatibility(disk_super, 1);
1485 nodesize = btrfs_super_nodesize(disk_super);
1486 leafsize = btrfs_super_leafsize(disk_super);
1487 sectorsize = btrfs_super_sectorsize(disk_super);
1488 stripesize = btrfs_super_stripesize(disk_super);
1490 __setup_root(nodesize, leafsize, sectorsize, stripesize,
1491 fs_info->chunk_root, fs_info, BTRFS_CHUNK_TREE_OBJECTID);
1493 ret = build_device_maps_by_chunk_records(rc, fs_info->chunk_root);
1497 ret = btrfs_setup_all_roots(fs_info, 0, 0);
1501 eb = fs_info->tree_root->node;
1502 read_extent_buffer(eb, fs_info->chunk_tree_uuid,
1503 btrfs_header_chunk_tree_uuid(eb),
1506 return fs_info->fs_root;
1508 btrfs_release_all_roots(fs_info);
1510 btrfs_cleanup_all_caches(fs_info);
1512 btrfs_close_devices(fs_info->fs_devices);
1514 btrfs_free_fs_info(fs_info);
1515 return ERR_PTR(ret);
1518 static int recover_prepare(struct recover_control *rc, char *path)
1522 struct btrfs_super_block *sb;
1523 struct btrfs_fs_devices *fs_devices;
1526 fd = open(path, O_RDONLY);
1528 fprintf(stderr, "open %s\n error.\n", path);
1532 sb = malloc(BTRFS_SUPER_INFO_SIZE);
1534 fprintf(stderr, "allocating memory for sb failed.\n");
1539 ret = btrfs_read_dev_super(fd, sb, BTRFS_SUPER_INFO_OFFSET, 1);
1541 fprintf(stderr, "read super block error\n");
1545 rc->sectorsize = btrfs_super_sectorsize(sb);
1546 rc->leafsize = btrfs_super_leafsize(sb);
1547 rc->generation = btrfs_super_generation(sb);
1548 rc->chunk_root_generation = btrfs_super_chunk_root_generation(sb);
1549 rc->csum_size = btrfs_super_csum_size(sb);
1551 /* if seed, the result of scanning below will be partial */
1552 if (btrfs_super_flags(sb) & BTRFS_SUPER_FLAG_SEEDING) {
1553 fprintf(stderr, "this device is seed device\n");
1558 ret = btrfs_scan_fs_devices(fd, path, &fs_devices, 0, 1, 0);
1562 rc->fs_devices = fs_devices;
1565 print_all_devices(&rc->fs_devices->devices);
1574 static int btrfs_get_device_extents(u64 chunk_object,
1575 struct list_head *orphan_devexts,
1576 struct list_head *ret_list)
1578 struct device_extent_record *devext;
1579 struct device_extent_record *next;
1582 list_for_each_entry_safe(devext, next, orphan_devexts, chunk_list) {
1583 if (devext->chunk_offset == chunk_object) {
1584 list_move_tail(&devext->chunk_list, ret_list);
1591 static int calc_num_stripes(u64 type)
1593 if (type & (BTRFS_BLOCK_GROUP_RAID0 |
1594 BTRFS_BLOCK_GROUP_RAID10 |
1595 BTRFS_BLOCK_GROUP_RAID5 |
1596 BTRFS_BLOCK_GROUP_RAID6))
1598 else if (type & (BTRFS_BLOCK_GROUP_RAID1 |
1599 BTRFS_BLOCK_GROUP_DUP))
1605 static inline int calc_sub_nstripes(u64 type)
1607 if (type & BTRFS_BLOCK_GROUP_RAID10)
1613 static int btrfs_verify_device_extents(struct block_group_record *bg,
1614 struct list_head *devexts, int ndevexts)
1616 struct device_extent_record *devext;
1618 int expected_num_stripes;
1620 expected_num_stripes = calc_num_stripes(bg->flags);
1621 if (expected_num_stripes && expected_num_stripes != ndevexts)
1624 strpie_length = calc_stripe_length(bg->flags, bg->offset, ndevexts);
1625 list_for_each_entry(devext, devexts, chunk_list) {
1626 if (devext->length != strpie_length)
1632 static int btrfs_rebuild_unordered_chunk_stripes(struct recover_control *rc,
1633 struct chunk_record *chunk)
1635 struct device_extent_record *devext;
1636 struct btrfs_device *device;
1639 devext = list_first_entry(&chunk->dextents, struct device_extent_record,
1641 for (i = 0; i < chunk->num_stripes; i++) {
1642 chunk->stripes[i].devid = devext->objectid;
1643 chunk->stripes[i].offset = devext->offset;
1644 device = btrfs_find_device_by_devid(rc->fs_devices,
1649 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1652 memcpy(chunk->stripes[i].dev_uuid, device->uuid,
1654 devext = list_next_entry(devext, chunk_list);
1659 static int btrfs_calc_stripe_index(struct chunk_record *chunk, u64 logical)
1661 u64 offset = logical - chunk->offset;
1663 int nr_data_stripes;
1666 stripe_nr = offset / chunk->stripe_len;
1667 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
1668 index = stripe_nr % chunk->num_stripes;
1669 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
1670 index = stripe_nr % (chunk->num_stripes / chunk->sub_stripes);
1671 index *= chunk->sub_stripes;
1672 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
1673 nr_data_stripes = chunk->num_stripes - 1;
1674 index = stripe_nr % nr_data_stripes;
1675 stripe_nr /= nr_data_stripes;
1676 index = (index + stripe_nr) % chunk->num_stripes;
1677 } else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
1678 nr_data_stripes = chunk->num_stripes - 2;
1679 index = stripe_nr % nr_data_stripes;
1680 stripe_nr /= nr_data_stripes;
1681 index = (index + stripe_nr) % chunk->num_stripes;
1688 /* calc the logical offset which is the start of the next stripe. */
1689 static inline u64 btrfs_next_stripe_logical_offset(struct chunk_record *chunk,
1692 u64 offset = logical - chunk->offset;
1694 offset /= chunk->stripe_len;
1695 offset *= chunk->stripe_len;
1696 offset += chunk->stripe_len;
1698 return offset + chunk->offset;
1701 static int is_extent_record_in_device_extent(struct extent_record *er,
1702 struct device_extent_record *dext,
1707 for (i = 0; i < er->nmirrors; i++) {
1708 if (er->devices[i]->devid == dext->objectid &&
1709 er->offsets[i] >= dext->offset &&
1710 er->offsets[i] < dext->offset + dext->length) {
1719 btrfs_rebuild_ordered_meta_chunk_stripes(struct recover_control *rc,
1720 struct chunk_record *chunk)
1722 u64 start = chunk->offset;
1723 u64 end = chunk->offset + chunk->length;
1724 struct cache_extent *cache;
1725 struct extent_record *er;
1726 struct device_extent_record *devext;
1727 struct device_extent_record *next;
1728 struct btrfs_device *device;
1734 cache = lookup_cache_extent(&rc->eb_cache,
1735 start, chunk->length);
1737 /* No used space, we can reorder the stripes freely. */
1738 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1742 list_splice_init(&chunk->dextents, &devexts);
1744 er = container_of(cache, struct extent_record, cache);
1745 index = btrfs_calc_stripe_index(chunk, er->cache.start);
1746 BUG_ON(index == -1);
1747 if (chunk->stripes[index].devid)
1749 list_for_each_entry_safe(devext, next, &devexts, chunk_list) {
1750 if (is_extent_record_in_device_extent(er, devext, &mirror)) {
1751 chunk->stripes[index].devid = devext->objectid;
1752 chunk->stripes[index].offset = devext->offset;
1753 memcpy(chunk->stripes[index].dev_uuid,
1754 er->devices[mirror]->uuid,
1757 list_move(&devext->chunk_list, &chunk->dextents);
1761 start = btrfs_next_stripe_logical_offset(chunk, er->cache.start);
1763 goto no_extent_record;
1765 cache = lookup_cache_extent(&rc->eb_cache, start, end - start);
1769 if (list_empty(&devexts))
1772 if (chunk->type_flags & (BTRFS_BLOCK_GROUP_RAID5 |
1773 BTRFS_BLOCK_GROUP_RAID6)) {
1774 /* Fixme: try to recover the order by the parity block. */
1775 list_splice_tail(&devexts, &chunk->dextents);
1779 /* There is no data on the lost stripes, we can reorder them freely. */
1780 for (index = 0; index < chunk->num_stripes; index++) {
1781 if (chunk->stripes[index].devid)
1784 devext = list_first_entry(&devexts,
1785 struct device_extent_record,
1787 list_move(&devext->chunk_list, &chunk->dextents);
1789 chunk->stripes[index].devid = devext->objectid;
1790 chunk->stripes[index].offset = devext->offset;
1791 device = btrfs_find_device_by_devid(rc->fs_devices,
1795 list_splice_tail(&devexts, &chunk->dextents);
1798 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
1801 memcpy(chunk->stripes[index].dev_uuid, device->uuid,
1807 #define BTRFS_ORDERED_RAID (BTRFS_BLOCK_GROUP_RAID0 | \
1808 BTRFS_BLOCK_GROUP_RAID10 | \
1809 BTRFS_BLOCK_GROUP_RAID5 | \
1810 BTRFS_BLOCK_GROUP_RAID6)
1812 static int btrfs_rebuild_chunk_stripes(struct recover_control *rc,
1813 struct chunk_record *chunk)
1818 * All the data in the system metadata chunk will be dropped,
1819 * so we need not guarantee that the data is right or not, that
1820 * is we can reorder the stripes in the system metadata chunk.
1822 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_METADATA) &&
1823 (chunk->type_flags & BTRFS_ORDERED_RAID))
1824 ret =btrfs_rebuild_ordered_meta_chunk_stripes(rc, chunk);
1825 else if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA) &&
1826 (chunk->type_flags & BTRFS_ORDERED_RAID))
1827 ret = 1; /* Be handled after the fs is opened. */
1829 ret = btrfs_rebuild_unordered_chunk_stripes(rc, chunk);
1834 static int next_csum(struct btrfs_root *root,
1835 struct extent_buffer **leaf,
1836 struct btrfs_path *path,
1841 struct btrfs_key *key)
1844 struct btrfs_root *csum_root = root->fs_info->csum_root;
1845 struct btrfs_csum_item *csum_item;
1846 u32 blocksize = root->sectorsize;
1847 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1848 int csums_in_item = btrfs_item_size_nr(*leaf, *slot) / csum_size;
1850 if (*csum_offset >= csums_in_item) {
1853 if (*slot >= btrfs_header_nritems(*leaf)) {
1854 ret = btrfs_next_leaf(csum_root, path);
1859 *leaf = path->nodes[0];
1860 *slot = path->slots[0];
1862 btrfs_item_key_to_cpu(*leaf, key, *slot);
1865 if (key->offset + (*csum_offset) * blocksize >= end)
1867 csum_item = btrfs_item_ptr(*leaf, *slot, struct btrfs_csum_item);
1868 csum_item = (struct btrfs_csum_item *)((unsigned char *)csum_item
1869 + (*csum_offset) * csum_size);
1870 read_extent_buffer(*leaf, tree_csum,
1871 (unsigned long)csum_item, csum_size);
1875 static u64 calc_data_offset(struct btrfs_key *key,
1876 struct chunk_record *chunk,
1882 int logical_stripe_nr;
1884 int nr_data_stripes;
1886 data_offset = key->offset + csum_offset * blocksize - chunk->offset;
1887 nr_data_stripes = chunk->num_stripes;
1889 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID5)
1890 nr_data_stripes -= 1;
1891 else if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6)
1892 nr_data_stripes -= 2;
1894 logical_stripe_nr = data_offset / chunk->stripe_len;
1895 dev_stripe_nr = logical_stripe_nr / nr_data_stripes;
1897 data_offset -= logical_stripe_nr * chunk->stripe_len;
1898 data_offset += dev_stripe_nr * chunk->stripe_len;
1900 return dev_offset + data_offset;
1903 static int check_one_csum(int fd, u64 start, u32 len, u32 tree_csum)
1907 u32 csum_result = ~(u32)0;
1912 ret = pread64(fd, data, len, start);
1913 if (ret < 0 || ret != len) {
1918 csum_result = btrfs_csum_data(NULL, data, csum_result, len);
1919 btrfs_csum_final(csum_result, (char *)&csum_result);
1920 if (csum_result != tree_csum)
1927 static u64 item_end_offset(struct btrfs_root *root, struct btrfs_key *key,
1928 struct extent_buffer *leaf, int slot) {
1929 u32 blocksize = root->sectorsize;
1930 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1932 u64 offset = btrfs_item_size_nr(leaf, slot);
1933 offset /= csum_size;
1934 offset *= blocksize;
1935 offset += key->offset;
1940 static int insert_stripe(struct list_head *devexts,
1941 struct recover_control *rc,
1942 struct chunk_record *chunk,
1944 struct device_extent_record *devext;
1945 struct btrfs_device *dev;
1947 devext = list_entry(devexts->next, struct device_extent_record,
1949 dev = btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1953 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices, devext->objectid,
1956 chunk->stripes[index].devid = devext->objectid;
1957 chunk->stripes[index].offset = devext->offset;
1958 memcpy(chunk->stripes[index].dev_uuid, dev->uuid, BTRFS_UUID_SIZE);
1960 list_move(&devext->chunk_list, &chunk->dextents);
1965 static inline int count_devext_records(struct list_head *record_list)
1967 int num_of_records = 0;
1968 struct device_extent_record *devext;
1970 list_for_each_entry(devext, record_list, chunk_list)
1973 return num_of_records;
1976 static int fill_chunk_up(struct chunk_record *chunk, struct list_head *devexts,
1977 struct recover_control *rc)
1982 for (i = 0; i < chunk->num_stripes; i++) {
1983 if (!chunk->stripes[i].devid) {
1984 ret = insert_stripe(devexts, rc, chunk, i);
1993 #define EQUAL_STRIPE (1 << 0)
1995 static int rebuild_raid_data_chunk_stripes(struct recover_control *rc,
1996 struct btrfs_root *root,
1997 struct chunk_record *chunk,
2003 struct btrfs_path path;
2004 struct btrfs_key prev_key;
2005 struct btrfs_key key;
2006 struct btrfs_root *csum_root;
2007 struct extent_buffer *leaf;
2008 struct device_extent_record *devext;
2009 struct device_extent_record *next;
2010 struct btrfs_device *dev;
2011 u64 start = chunk->offset;
2012 u64 end = start + chunk->stripe_len;
2013 u64 chunk_end = chunk->offset + chunk->length;
2014 u64 csum_offset = 0;
2016 u32 blocksize = root->sectorsize;
2019 int num_unordered = 0;
2020 LIST_HEAD(unordered);
2021 LIST_HEAD(candidates);
2023 csum_root = root->fs_info->csum_root;
2024 btrfs_init_path(&path);
2025 list_splice_init(&chunk->dextents, &candidates);
2027 if (list_is_last(candidates.next, &candidates))
2030 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
2031 key.type = BTRFS_EXTENT_CSUM_KEY;
2034 ret = btrfs_search_slot(NULL, csum_root, &key, &path, 0, 0);
2036 fprintf(stderr, "Search csum failed(%d)\n", ret);
2039 leaf = path.nodes[0];
2040 slot = path.slots[0];
2042 if (slot >= btrfs_header_nritems(leaf)) {
2043 ret = btrfs_next_leaf(csum_root, &path);
2046 "Walk tree failed(%d)\n", ret);
2048 } else if (ret > 0) {
2049 slot = btrfs_header_nritems(leaf) - 1;
2050 btrfs_item_key_to_cpu(leaf, &key, slot);
2051 if (item_end_offset(root, &key, leaf, slot)
2053 csum_offset = start - key.offset;
2054 csum_offset /= blocksize;
2059 leaf = path.nodes[0];
2060 slot = path.slots[0];
2062 btrfs_item_key_to_cpu(leaf, &key, slot);
2063 ret = btrfs_previous_item(csum_root, &path, 0,
2064 BTRFS_EXTENT_CSUM_KEY);
2068 if (key.offset >= end)
2073 leaf = path.nodes[0];
2074 slot = path.slots[0];
2076 btrfs_item_key_to_cpu(leaf, &prev_key, slot);
2077 if (item_end_offset(root, &prev_key, leaf, slot) > start) {
2078 csum_offset = start - prev_key.offset;
2079 csum_offset /= blocksize;
2080 btrfs_item_key_to_cpu(leaf, &key, slot);
2082 if (key.offset >= end)
2086 if (key.offset + csum_offset * blocksize > chunk_end)
2090 ret = next_csum(root, &leaf, &path, &slot, &csum_offset, &tree_csum,
2093 fprintf(stderr, "Fetch csum failed\n");
2095 } else if (ret == 1) {
2096 if (!(*flags & EQUAL_STRIPE))
2097 *flags |= EQUAL_STRIPE;
2099 } else if (ret == 2)
2102 list_for_each_entry_safe(devext, next, &candidates, chunk_list) {
2103 data_offset = calc_data_offset(&key, chunk, devext->offset,
2104 csum_offset, blocksize);
2105 dev = btrfs_find_device_by_devid(rc->fs_devices,
2106 devext->objectid, 0);
2111 BUG_ON(btrfs_find_device_by_devid(rc->fs_devices,
2112 devext->objectid, 1));
2114 ret = check_one_csum(dev->fd, data_offset, blocksize,
2119 list_move(&devext->chunk_list, &unordered);
2122 if (list_empty(&candidates)) {
2123 num_unordered = count_devext_records(&unordered);
2124 if (chunk->type_flags & BTRFS_BLOCK_GROUP_RAID6
2125 && num_unordered == 2) {
2126 btrfs_release_path(&path);
2127 ret = fill_chunk_up(chunk, &unordered, rc);
2134 if (list_is_last(candidates.next, &candidates)) {
2135 index = btrfs_calc_stripe_index(chunk,
2136 key.offset + csum_offset * blocksize);
2137 BUG_ON(index == -1);
2138 if (chunk->stripes[index].devid)
2140 ret = insert_stripe(&candidates, rc, chunk, index);
2148 start = btrfs_next_stripe_logical_offset(chunk, start);
2149 end = min(start + chunk->stripe_len, chunk_end);
2150 list_splice_init(&unordered, &candidates);
2151 btrfs_release_path(&path);
2153 if (end < chunk_end)
2157 list_splice_init(&candidates, &unordered);
2158 num_unordered = count_devext_records(&unordered);
2159 if (num_unordered == 1) {
2160 for (i = 0; i < chunk->num_stripes; i++) {
2161 if (!chunk->stripes[i].devid) {
2166 ret = insert_stripe(&unordered, rc, chunk, index);
2170 if ((num_unordered == 2 && chunk->type_flags
2171 & BTRFS_BLOCK_GROUP_RAID5)
2172 || (num_unordered == 3 && chunk->type_flags
2173 & BTRFS_BLOCK_GROUP_RAID6)) {
2174 ret = fill_chunk_up(chunk, &unordered, rc);
2178 ret = !!ret || (list_empty(&unordered) ? 0 : 1);
2179 list_splice_init(&candidates, &chunk->dextents);
2180 list_splice_init(&unordered, &chunk->dextents);
2181 btrfs_release_path(&path);
2186 static int btrfs_rebuild_ordered_data_chunk_stripes(struct recover_control *rc,
2187 struct btrfs_root *root)
2189 struct chunk_record *chunk;
2190 struct chunk_record *next;
2195 list_for_each_entry_safe(chunk, next, &rc->unrepaired_chunks, list) {
2196 if ((chunk->type_flags & BTRFS_BLOCK_GROUP_DATA)
2197 && (chunk->type_flags & BTRFS_ORDERED_RAID)) {
2199 err = rebuild_raid_data_chunk_stripes(rc, root, chunk,
2202 list_move(&chunk->list, &rc->bad_chunks);
2203 if (flags & EQUAL_STRIPE)
2205 "Failure: too many equal stripes in chunk[%llu %llu]\n",
2206 chunk->offset, chunk->length);
2210 list_move(&chunk->list, &rc->good_chunks);
2216 static int btrfs_recover_chunks(struct recover_control *rc)
2218 struct chunk_record *chunk;
2219 struct block_group_record *bg;
2220 struct block_group_record *next;
2221 LIST_HEAD(new_chunks);
2226 /* create the chunk by block group */
2227 list_for_each_entry_safe(bg, next, &rc->bg.block_groups, list) {
2228 nstripes = btrfs_get_device_extents(bg->objectid,
2229 &rc->devext.no_chunk_orphans,
2231 chunk = malloc(btrfs_chunk_record_size(nstripes));
2234 memset(chunk, 0, btrfs_chunk_record_size(nstripes));
2235 INIT_LIST_HEAD(&chunk->dextents);
2237 chunk->cache.start = bg->objectid;
2238 chunk->cache.size = bg->offset;
2239 chunk->objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2240 chunk->type = BTRFS_CHUNK_ITEM_KEY;
2241 chunk->offset = bg->objectid;
2242 chunk->generation = bg->generation;
2243 chunk->length = bg->offset;
2244 chunk->owner = BTRFS_CHUNK_TREE_OBJECTID;
2245 chunk->stripe_len = BTRFS_STRIPE_LEN;
2246 chunk->type_flags = bg->flags;
2247 chunk->io_width = BTRFS_STRIPE_LEN;
2248 chunk->io_align = BTRFS_STRIPE_LEN;
2249 chunk->sector_size = rc->sectorsize;
2250 chunk->sub_stripes = calc_sub_nstripes(bg->flags);
2252 ret = insert_cache_extent(&rc->chunk, &chunk->cache);
2255 list_del_init(&bg->list);
2257 list_add_tail(&chunk->list, &rc->bad_chunks);
2261 list_splice_init(&devexts, &chunk->dextents);
2263 ret = btrfs_verify_device_extents(bg, &devexts, nstripes);
2265 list_add_tail(&chunk->list, &rc->bad_chunks);
2269 chunk->num_stripes = nstripes;
2270 ret = btrfs_rebuild_chunk_stripes(rc, chunk);
2272 list_add_tail(&chunk->list, &rc->unrepaired_chunks);
2274 list_add_tail(&chunk->list, &rc->bad_chunks);
2276 list_add_tail(&chunk->list, &rc->good_chunks);
2279 * Don't worry about the lost orphan device extents, they don't
2280 * have its chunk and block group, they must be the old ones that
2286 static inline int is_chunk_overlap(struct chunk_record *chunk1,
2287 struct chunk_record *chunk2)
2289 if (chunk1->offset >= chunk2->offset + chunk2->length ||
2290 chunk1->offset + chunk1->length <= chunk2->offset)
2295 /* Move invalid(overlap with good chunks) rebuild chunks to bad chunk list */
2296 static void validate_rebuild_chunks(struct recover_control *rc)
2298 struct chunk_record *good;
2299 struct chunk_record *rebuild;
2300 struct chunk_record *tmp;
2302 list_for_each_entry_safe(rebuild, tmp, &rc->rebuild_chunks, list) {
2303 list_for_each_entry(good, &rc->good_chunks, list) {
2304 if (is_chunk_overlap(rebuild, good)) {
2305 list_move_tail(&rebuild->list,
2314 * Return 0 when successful, < 0 on error and > 0 if aborted by user
2316 int btrfs_recover_chunk_tree(char *path, int verbose, int yes)
2319 struct btrfs_root *root = NULL;
2320 struct btrfs_trans_handle *trans;
2321 struct recover_control rc;
2323 init_recover_control(&rc, verbose, yes);
2325 ret = recover_prepare(&rc, path);
2327 fprintf(stderr, "recover prepare error\n");
2331 ret = scan_devices(&rc);
2333 fprintf(stderr, "scan chunk headers error\n");
2337 if (cache_tree_empty(&rc.chunk) &&
2338 cache_tree_empty(&rc.bg.tree) &&
2339 cache_tree_empty(&rc.devext.tree)) {
2340 fprintf(stderr, "no recoverable chunk\n");
2344 print_scan_result(&rc);
2346 ret = check_chunks(&rc.chunk, &rc.bg, &rc.devext, &rc.good_chunks,
2347 &rc.bad_chunks, &rc.rebuild_chunks, 1);
2349 if (!list_empty(&rc.bg.block_groups) ||
2350 !list_empty(&rc.devext.no_chunk_orphans)) {
2351 ret = btrfs_recover_chunks(&rc);
2356 print_check_result(&rc);
2357 printf("Check chunks successfully with no orphans\n");
2360 validate_rebuild_chunks(&rc);
2361 print_check_result(&rc);
2363 root = open_ctree_with_broken_chunk(&rc);
2365 fprintf(stderr, "open with broken chunk error\n");
2366 ret = PTR_ERR(root);
2370 ret = check_all_chunks_by_metadata(&rc, root);
2372 fprintf(stderr, "The chunks in memory can not match the metadata of the fs. Repair failed.\n");
2373 goto fail_close_ctree;
2376 ret = btrfs_rebuild_ordered_data_chunk_stripes(&rc, root);
2378 fprintf(stderr, "Failed to rebuild ordered chunk stripes.\n");
2379 goto fail_close_ctree;
2383 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?");
2386 goto fail_close_ctree;
2390 trans = btrfs_start_transaction(root, 1);
2391 ret = remove_chunk_extent_item(trans, &rc, root);
2394 ret = rebuild_chunk_tree(trans, &rc, root);
2397 ret = rebuild_sys_array(&rc, root);
2400 ret = rebuild_block_group(trans, &rc, root);
2402 printf("Fail to rebuild block groups.\n");
2403 printf("Recommend to run 'btrfs check --init-extent-tree <dev>' after recovery\n");
2406 btrfs_commit_transaction(trans, root);
2410 free_recover_control(&rc);