2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
23 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include "print-tree.h"
33 #include "transaction.h"
36 #include "free-space-cache.h"
38 #include "qgroup-verify.h"
39 #include "rbtree-utils.h"
43 static u64 bytes_used = 0;
44 static u64 total_csum_bytes = 0;
45 static u64 total_btree_bytes = 0;
46 static u64 total_fs_tree_bytes = 0;
47 static u64 total_extent_tree_bytes = 0;
48 static u64 btree_space_waste = 0;
49 static u64 data_bytes_allocated = 0;
50 static u64 data_bytes_referenced = 0;
51 static int found_old_backref = 0;
52 static LIST_HEAD(duplicate_extents);
53 static LIST_HEAD(delete_items);
54 static int repair = 0;
55 static int no_holes = 0;
56 static int init_extent_tree = 0;
57 static int check_data_csum = 0;
59 struct extent_backref {
60 struct list_head list;
61 unsigned int is_data:1;
62 unsigned int found_extent_tree:1;
63 unsigned int full_backref:1;
64 unsigned int found_ref:1;
65 unsigned int broken:1;
69 struct extent_backref node;
84 * Much like data_backref, just removed the undetermined members
85 * and change it to use list_head.
86 * During extent scan, it is stored in root->orphan_data_extent.
87 * During fs tree scan, it is then moved to inode_rec->orphan_data_extents.
89 struct orphan_data_extent {
90 struct list_head list;
99 struct extent_backref node;
106 struct extent_record {
107 struct list_head backrefs;
108 struct list_head dups;
109 struct list_head list;
110 struct cache_extent cache;
111 struct btrfs_disk_key parent_key;
116 u64 extent_item_refs;
118 u64 parent_generation;
122 unsigned int found_rec:1;
123 unsigned int content_checked:1;
124 unsigned int owner_ref_checked:1;
125 unsigned int is_root:1;
126 unsigned int metadata:1;
127 unsigned int flag_block_full_backref:1;
130 struct inode_backref {
131 struct list_head list;
132 unsigned int found_dir_item:1;
133 unsigned int found_dir_index:1;
134 unsigned int found_inode_ref:1;
135 unsigned int filetype:8;
137 unsigned int ref_type;
144 struct root_item_record {
145 struct list_head list;
151 struct btrfs_key drop_key;
154 #define REF_ERR_NO_DIR_ITEM (1 << 0)
155 #define REF_ERR_NO_DIR_INDEX (1 << 1)
156 #define REF_ERR_NO_INODE_REF (1 << 2)
157 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
158 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
159 #define REF_ERR_DUP_INODE_REF (1 << 5)
160 #define REF_ERR_INDEX_UNMATCH (1 << 6)
161 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
162 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
163 #define REF_ERR_NO_ROOT_REF (1 << 9)
164 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
165 #define REF_ERR_DUP_ROOT_REF (1 << 11)
166 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
168 struct file_extent_hole {
174 /* Compatible function to allow reuse of old codes */
175 static u64 first_extent_gap(struct rb_root *holes)
177 struct file_extent_hole *hole;
179 if (RB_EMPTY_ROOT(holes))
182 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
186 int compare_hole(struct rb_node *node1, struct rb_node *node2)
188 struct file_extent_hole *hole1;
189 struct file_extent_hole *hole2;
191 hole1 = rb_entry(node1, struct file_extent_hole, node);
192 hole2 = rb_entry(node2, struct file_extent_hole, node);
194 if (hole1->start > hole2->start)
196 if (hole1->start < hole2->start)
198 /* Now hole1->start == hole2->start */
199 if (hole1->len >= hole2->len)
201 * Hole 1 will be merge center
202 * Same hole will be merged later
205 /* Hole 2 will be merge center */
210 * Add a hole to the record
212 * This will do hole merge for copy_file_extent_holes(),
213 * which will ensure there won't be continuous holes.
215 static int add_file_extent_hole(struct rb_root *holes,
218 struct file_extent_hole *hole;
219 struct file_extent_hole *prev = NULL;
220 struct file_extent_hole *next = NULL;
222 hole = malloc(sizeof(*hole));
227 /* Since compare will not return 0, no -EEXIST will happen */
228 rb_insert(holes, &hole->node, compare_hole);
230 /* simple merge with previous hole */
231 if (rb_prev(&hole->node))
232 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
234 if (prev && prev->start + prev->len >= hole->start) {
235 hole->len = hole->start + hole->len - prev->start;
236 hole->start = prev->start;
237 rb_erase(&prev->node, holes);
242 /* iterate merge with next holes */
244 if (!rb_next(&hole->node))
246 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
248 if (hole->start + hole->len >= next->start) {
249 if (hole->start + hole->len <= next->start + next->len)
250 hole->len = next->start + next->len -
252 rb_erase(&next->node, holes);
261 static int compare_hole_range(struct rb_node *node, void *data)
263 struct file_extent_hole *hole;
266 hole = (struct file_extent_hole *)data;
269 hole = rb_entry(node, struct file_extent_hole, node);
270 if (start < hole->start)
272 if (start >= hole->start && start < hole->start + hole->len)
278 * Delete a hole in the record
280 * This will do the hole split and is much restrict than add.
282 static int del_file_extent_hole(struct rb_root *holes,
285 struct file_extent_hole *hole;
286 struct file_extent_hole tmp;
287 struct file_extent_hole prev;
288 struct file_extent_hole next;
289 struct rb_node *node;
296 node = rb_search(holes, &tmp, compare_hole_range, NULL);
299 hole = rb_entry(node, struct file_extent_hole, node);
300 if (start + len > hole->start + hole->len)
304 * Now there will be no overflap, delete the hole and re-add the
305 * split(s) if they exists.
307 if (start > hole->start) {
308 prev.start = hole->start;
309 prev.len = start - hole->start;
312 if (hole->start + hole->len > start + len) {
313 next.start = start + len;
314 next.len = hole->start + hole->len - start - len;
317 rb_erase(node, holes);
320 ret = add_file_extent_hole(holes, prev.start, prev.len);
325 ret = add_file_extent_hole(holes, next.start, next.len);
332 static int copy_file_extent_holes(struct rb_root *dst,
335 struct file_extent_hole *hole;
336 struct rb_node *node;
339 node = rb_first(src);
341 hole = rb_entry(node, struct file_extent_hole, node);
342 ret = add_file_extent_hole(dst, hole->start, hole->len);
345 node = rb_next(node);
350 static void free_file_extent_holes(struct rb_root *holes)
352 struct rb_node *node;
353 struct file_extent_hole *hole;
355 node = rb_first(holes);
357 hole = rb_entry(node, struct file_extent_hole, node);
358 rb_erase(node, holes);
360 node = rb_first(holes);
364 struct inode_record {
365 struct list_head backrefs;
366 unsigned int checked:1;
367 unsigned int merging:1;
368 unsigned int found_inode_item:1;
369 unsigned int found_dir_item:1;
370 unsigned int found_file_extent:1;
371 unsigned int found_csum_item:1;
372 unsigned int some_csum_missing:1;
373 unsigned int nodatasum:1;
386 struct rb_root holes;
387 struct list_head orphan_extents;
392 #define I_ERR_NO_INODE_ITEM (1 << 0)
393 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
394 #define I_ERR_DUP_INODE_ITEM (1 << 2)
395 #define I_ERR_DUP_DIR_INDEX (1 << 3)
396 #define I_ERR_ODD_DIR_ITEM (1 << 4)
397 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
398 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
399 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
400 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
401 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
402 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
403 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
404 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
405 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
406 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
408 struct root_backref {
409 struct list_head list;
410 unsigned int found_dir_item:1;
411 unsigned int found_dir_index:1;
412 unsigned int found_back_ref:1;
413 unsigned int found_forward_ref:1;
414 unsigned int reachable:1;
424 struct list_head backrefs;
425 struct cache_extent cache;
426 unsigned int found_root_item:1;
432 struct cache_extent cache;
437 struct cache_extent cache;
438 struct cache_tree root_cache;
439 struct cache_tree inode_cache;
440 struct inode_record *current;
449 struct walk_control {
450 struct cache_tree shared;
451 struct shared_node *nodes[BTRFS_MAX_LEVEL];
457 struct btrfs_key key;
459 struct list_head list;
462 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
464 static void record_root_in_trans(struct btrfs_trans_handle *trans,
465 struct btrfs_root *root)
467 if (root->last_trans != trans->transid) {
468 root->track_dirty = 1;
469 root->last_trans = trans->transid;
470 root->commit_root = root->node;
471 extent_buffer_get(root->node);
475 static u8 imode_to_type(u32 imode)
478 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
479 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
480 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
481 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
482 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
483 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
484 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
485 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
488 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
492 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
494 struct device_record *rec1;
495 struct device_record *rec2;
497 rec1 = rb_entry(node1, struct device_record, node);
498 rec2 = rb_entry(node2, struct device_record, node);
499 if (rec1->devid > rec2->devid)
501 else if (rec1->devid < rec2->devid)
507 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
509 struct inode_record *rec;
510 struct inode_backref *backref;
511 struct inode_backref *orig;
512 struct orphan_data_extent *src_orphan;
513 struct orphan_data_extent *dst_orphan;
516 rec = malloc(sizeof(*rec));
517 memcpy(rec, orig_rec, sizeof(*rec));
519 INIT_LIST_HEAD(&rec->backrefs);
520 INIT_LIST_HEAD(&rec->orphan_extents);
522 list_for_each_entry(orig, &orig_rec->backrefs, list) {
523 size = sizeof(*orig) + orig->namelen + 1;
524 backref = malloc(size);
525 memcpy(backref, orig, size);
526 list_add_tail(&backref->list, &rec->backrefs);
528 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
529 dst_orphan = malloc(sizeof(*dst_orphan));
530 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
532 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
533 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
538 static void print_orphan_data_extents(struct list_head *orphan_extents,
541 struct orphan_data_extent *orphan;
543 if (list_empty(orphan_extents))
545 printf("The following data extent is lost in tree %llu:\n",
547 list_for_each_entry(orphan, orphan_extents, list) {
548 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
549 orphan->objectid, orphan->offset, orphan->disk_bytenr,
554 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
556 u64 root_objectid = root->root_key.objectid;
557 int errors = rec->errors;
561 /* reloc root errors, we print its corresponding fs root objectid*/
562 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
563 root_objectid = root->root_key.offset;
564 fprintf(stderr, "reloc");
566 fprintf(stderr, "root %llu inode %llu errors %x",
567 (unsigned long long) root_objectid,
568 (unsigned long long) rec->ino, rec->errors);
570 if (errors & I_ERR_NO_INODE_ITEM)
571 fprintf(stderr, ", no inode item");
572 if (errors & I_ERR_NO_ORPHAN_ITEM)
573 fprintf(stderr, ", no orphan item");
574 if (errors & I_ERR_DUP_INODE_ITEM)
575 fprintf(stderr, ", dup inode item");
576 if (errors & I_ERR_DUP_DIR_INDEX)
577 fprintf(stderr, ", dup dir index");
578 if (errors & I_ERR_ODD_DIR_ITEM)
579 fprintf(stderr, ", odd dir item");
580 if (errors & I_ERR_ODD_FILE_EXTENT)
581 fprintf(stderr, ", odd file extent");
582 if (errors & I_ERR_BAD_FILE_EXTENT)
583 fprintf(stderr, ", bad file extent");
584 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
585 fprintf(stderr, ", file extent overlap");
586 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
587 fprintf(stderr, ", file extent discount");
588 if (errors & I_ERR_DIR_ISIZE_WRONG)
589 fprintf(stderr, ", dir isize wrong");
590 if (errors & I_ERR_FILE_NBYTES_WRONG)
591 fprintf(stderr, ", nbytes wrong");
592 if (errors & I_ERR_ODD_CSUM_ITEM)
593 fprintf(stderr, ", odd csum item");
594 if (errors & I_ERR_SOME_CSUM_MISSING)
595 fprintf(stderr, ", some csum missing");
596 if (errors & I_ERR_LINK_COUNT_WRONG)
597 fprintf(stderr, ", link count wrong");
598 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
599 fprintf(stderr, ", orphan file extent");
600 fprintf(stderr, "\n");
601 /* Print the orphan extents if needed */
602 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
603 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
605 /* Print the holes if needed */
606 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
607 struct file_extent_hole *hole;
608 struct rb_node *node;
610 node = rb_first(&rec->holes);
611 fprintf(stderr, "Found file extent holes:\n");
613 hole = rb_entry(node, struct file_extent_hole, node);
614 fprintf(stderr, "\tstart: %llu, len:%llu\n",
615 hole->start, hole->len);
616 node = rb_next(node);
621 static void print_ref_error(int errors)
623 if (errors & REF_ERR_NO_DIR_ITEM)
624 fprintf(stderr, ", no dir item");
625 if (errors & REF_ERR_NO_DIR_INDEX)
626 fprintf(stderr, ", no dir index");
627 if (errors & REF_ERR_NO_INODE_REF)
628 fprintf(stderr, ", no inode ref");
629 if (errors & REF_ERR_DUP_DIR_ITEM)
630 fprintf(stderr, ", dup dir item");
631 if (errors & REF_ERR_DUP_DIR_INDEX)
632 fprintf(stderr, ", dup dir index");
633 if (errors & REF_ERR_DUP_INODE_REF)
634 fprintf(stderr, ", dup inode ref");
635 if (errors & REF_ERR_INDEX_UNMATCH)
636 fprintf(stderr, ", index unmatch");
637 if (errors & REF_ERR_FILETYPE_UNMATCH)
638 fprintf(stderr, ", filetype unmatch");
639 if (errors & REF_ERR_NAME_TOO_LONG)
640 fprintf(stderr, ", name too long");
641 if (errors & REF_ERR_NO_ROOT_REF)
642 fprintf(stderr, ", no root ref");
643 if (errors & REF_ERR_NO_ROOT_BACKREF)
644 fprintf(stderr, ", no root backref");
645 if (errors & REF_ERR_DUP_ROOT_REF)
646 fprintf(stderr, ", dup root ref");
647 if (errors & REF_ERR_DUP_ROOT_BACKREF)
648 fprintf(stderr, ", dup root backref");
649 fprintf(stderr, "\n");
652 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
655 struct ptr_node *node;
656 struct cache_extent *cache;
657 struct inode_record *rec = NULL;
660 cache = lookup_cache_extent(inode_cache, ino, 1);
662 node = container_of(cache, struct ptr_node, cache);
664 if (mod && rec->refs > 1) {
665 node->data = clone_inode_rec(rec);
670 rec = calloc(1, sizeof(*rec));
672 rec->extent_start = (u64)-1;
674 INIT_LIST_HEAD(&rec->backrefs);
675 INIT_LIST_HEAD(&rec->orphan_extents);
676 rec->holes = RB_ROOT;
678 node = malloc(sizeof(*node));
679 node->cache.start = ino;
680 node->cache.size = 1;
683 if (ino == BTRFS_FREE_INO_OBJECTID)
686 ret = insert_cache_extent(inode_cache, &node->cache);
692 static void free_orphan_data_extents(struct list_head *orphan_extents)
694 struct orphan_data_extent *orphan;
696 while (!list_empty(orphan_extents)) {
697 orphan = list_entry(orphan_extents->next,
698 struct orphan_data_extent, list);
699 list_del(&orphan->list);
704 static void free_inode_rec(struct inode_record *rec)
706 struct inode_backref *backref;
711 while (!list_empty(&rec->backrefs)) {
712 backref = list_entry(rec->backrefs.next,
713 struct inode_backref, list);
714 list_del(&backref->list);
717 free_orphan_data_extents(&rec->orphan_extents);
718 free_file_extent_holes(&rec->holes);
722 static int can_free_inode_rec(struct inode_record *rec)
724 if (!rec->errors && rec->checked && rec->found_inode_item &&
725 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
730 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
731 struct inode_record *rec)
733 struct cache_extent *cache;
734 struct inode_backref *tmp, *backref;
735 struct ptr_node *node;
736 unsigned char filetype;
738 if (!rec->found_inode_item)
741 filetype = imode_to_type(rec->imode);
742 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
743 if (backref->found_dir_item && backref->found_dir_index) {
744 if (backref->filetype != filetype)
745 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
746 if (!backref->errors && backref->found_inode_ref) {
747 list_del(&backref->list);
753 if (!rec->checked || rec->merging)
756 if (S_ISDIR(rec->imode)) {
757 if (rec->found_size != rec->isize)
758 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
759 if (rec->found_file_extent)
760 rec->errors |= I_ERR_ODD_FILE_EXTENT;
761 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
762 if (rec->found_dir_item)
763 rec->errors |= I_ERR_ODD_DIR_ITEM;
764 if (rec->found_size != rec->nbytes)
765 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
766 if (rec->nlink > 0 && !no_holes &&
767 (rec->extent_end < rec->isize ||
768 first_extent_gap(&rec->holes) < rec->isize))
769 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
772 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
773 if (rec->found_csum_item && rec->nodatasum)
774 rec->errors |= I_ERR_ODD_CSUM_ITEM;
775 if (rec->some_csum_missing && !rec->nodatasum)
776 rec->errors |= I_ERR_SOME_CSUM_MISSING;
779 BUG_ON(rec->refs != 1);
780 if (can_free_inode_rec(rec)) {
781 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
782 node = container_of(cache, struct ptr_node, cache);
783 BUG_ON(node->data != rec);
784 remove_cache_extent(inode_cache, &node->cache);
790 static int check_orphan_item(struct btrfs_root *root, u64 ino)
792 struct btrfs_path path;
793 struct btrfs_key key;
796 key.objectid = BTRFS_ORPHAN_OBJECTID;
797 key.type = BTRFS_ORPHAN_ITEM_KEY;
800 btrfs_init_path(&path);
801 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
802 btrfs_release_path(&path);
808 static int process_inode_item(struct extent_buffer *eb,
809 int slot, struct btrfs_key *key,
810 struct shared_node *active_node)
812 struct inode_record *rec;
813 struct btrfs_inode_item *item;
815 rec = active_node->current;
816 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
817 if (rec->found_inode_item) {
818 rec->errors |= I_ERR_DUP_INODE_ITEM;
821 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
822 rec->nlink = btrfs_inode_nlink(eb, item);
823 rec->isize = btrfs_inode_size(eb, item);
824 rec->nbytes = btrfs_inode_nbytes(eb, item);
825 rec->imode = btrfs_inode_mode(eb, item);
826 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
828 rec->found_inode_item = 1;
830 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
831 maybe_free_inode_rec(&active_node->inode_cache, rec);
835 static struct inode_backref *get_inode_backref(struct inode_record *rec,
837 int namelen, u64 dir)
839 struct inode_backref *backref;
841 list_for_each_entry(backref, &rec->backrefs, list) {
842 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
844 if (backref->dir != dir || backref->namelen != namelen)
846 if (memcmp(name, backref->name, namelen))
851 backref = malloc(sizeof(*backref) + namelen + 1);
852 memset(backref, 0, sizeof(*backref));
854 backref->namelen = namelen;
855 memcpy(backref->name, name, namelen);
856 backref->name[namelen] = '\0';
857 list_add_tail(&backref->list, &rec->backrefs);
861 static int add_inode_backref(struct cache_tree *inode_cache,
862 u64 ino, u64 dir, u64 index,
863 const char *name, int namelen,
864 int filetype, int itemtype, int errors)
866 struct inode_record *rec;
867 struct inode_backref *backref;
869 rec = get_inode_rec(inode_cache, ino, 1);
870 backref = get_inode_backref(rec, name, namelen, dir);
872 backref->errors |= errors;
873 if (itemtype == BTRFS_DIR_INDEX_KEY) {
874 if (backref->found_dir_index)
875 backref->errors |= REF_ERR_DUP_DIR_INDEX;
876 if (backref->found_inode_ref && backref->index != index)
877 backref->errors |= REF_ERR_INDEX_UNMATCH;
878 if (backref->found_dir_item && backref->filetype != filetype)
879 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
881 backref->index = index;
882 backref->filetype = filetype;
883 backref->found_dir_index = 1;
884 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
886 if (backref->found_dir_item)
887 backref->errors |= REF_ERR_DUP_DIR_ITEM;
888 if (backref->found_dir_index && backref->filetype != filetype)
889 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
891 backref->filetype = filetype;
892 backref->found_dir_item = 1;
893 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
894 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
895 if (backref->found_inode_ref)
896 backref->errors |= REF_ERR_DUP_INODE_REF;
897 if (backref->found_dir_index && backref->index != index)
898 backref->errors |= REF_ERR_INDEX_UNMATCH;
900 backref->index = index;
902 backref->ref_type = itemtype;
903 backref->found_inode_ref = 1;
908 maybe_free_inode_rec(inode_cache, rec);
912 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
913 struct cache_tree *dst_cache)
915 struct inode_backref *backref;
920 list_for_each_entry(backref, &src->backrefs, list) {
921 if (backref->found_dir_index) {
922 add_inode_backref(dst_cache, dst->ino, backref->dir,
923 backref->index, backref->name,
924 backref->namelen, backref->filetype,
925 BTRFS_DIR_INDEX_KEY, backref->errors);
927 if (backref->found_dir_item) {
929 add_inode_backref(dst_cache, dst->ino,
930 backref->dir, 0, backref->name,
931 backref->namelen, backref->filetype,
932 BTRFS_DIR_ITEM_KEY, backref->errors);
934 if (backref->found_inode_ref) {
935 add_inode_backref(dst_cache, dst->ino,
936 backref->dir, backref->index,
937 backref->name, backref->namelen, 0,
938 backref->ref_type, backref->errors);
942 if (src->found_dir_item)
943 dst->found_dir_item = 1;
944 if (src->found_file_extent)
945 dst->found_file_extent = 1;
946 if (src->found_csum_item)
947 dst->found_csum_item = 1;
948 if (src->some_csum_missing)
949 dst->some_csum_missing = 1;
950 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
951 ret = copy_file_extent_holes(&dst->holes, &src->holes);
956 BUG_ON(src->found_link < dir_count);
957 dst->found_link += src->found_link - dir_count;
958 dst->found_size += src->found_size;
959 if (src->extent_start != (u64)-1) {
960 if (dst->extent_start == (u64)-1) {
961 dst->extent_start = src->extent_start;
962 dst->extent_end = src->extent_end;
964 if (dst->extent_end > src->extent_start)
965 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
966 else if (dst->extent_end < src->extent_start) {
967 ret = add_file_extent_hole(&dst->holes,
969 src->extent_start - dst->extent_end);
971 if (dst->extent_end < src->extent_end)
972 dst->extent_end = src->extent_end;
976 dst->errors |= src->errors;
977 if (src->found_inode_item) {
978 if (!dst->found_inode_item) {
979 dst->nlink = src->nlink;
980 dst->isize = src->isize;
981 dst->nbytes = src->nbytes;
982 dst->imode = src->imode;
983 dst->nodatasum = src->nodatasum;
984 dst->found_inode_item = 1;
986 dst->errors |= I_ERR_DUP_INODE_ITEM;
994 static int splice_shared_node(struct shared_node *src_node,
995 struct shared_node *dst_node)
997 struct cache_extent *cache;
998 struct ptr_node *node, *ins;
999 struct cache_tree *src, *dst;
1000 struct inode_record *rec, *conflict;
1001 u64 current_ino = 0;
1005 if (--src_node->refs == 0)
1007 if (src_node->current)
1008 current_ino = src_node->current->ino;
1010 src = &src_node->root_cache;
1011 dst = &dst_node->root_cache;
1013 cache = search_cache_extent(src, 0);
1015 node = container_of(cache, struct ptr_node, cache);
1017 cache = next_cache_extent(cache);
1020 remove_cache_extent(src, &node->cache);
1023 ins = malloc(sizeof(*ins));
1024 ins->cache.start = node->cache.start;
1025 ins->cache.size = node->cache.size;
1029 ret = insert_cache_extent(dst, &ins->cache);
1030 if (ret == -EEXIST) {
1031 conflict = get_inode_rec(dst, rec->ino, 1);
1032 merge_inode_recs(rec, conflict, dst);
1034 conflict->checked = 1;
1035 if (dst_node->current == conflict)
1036 dst_node->current = NULL;
1038 maybe_free_inode_rec(dst, conflict);
1039 free_inode_rec(rec);
1046 if (src == &src_node->root_cache) {
1047 src = &src_node->inode_cache;
1048 dst = &dst_node->inode_cache;
1052 if (current_ino > 0 && (!dst_node->current ||
1053 current_ino > dst_node->current->ino)) {
1054 if (dst_node->current) {
1055 dst_node->current->checked = 1;
1056 maybe_free_inode_rec(dst, dst_node->current);
1058 dst_node->current = get_inode_rec(dst, current_ino, 1);
1063 static void free_inode_ptr(struct cache_extent *cache)
1065 struct ptr_node *node;
1066 struct inode_record *rec;
1068 node = container_of(cache, struct ptr_node, cache);
1070 free_inode_rec(rec);
1074 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1076 static struct shared_node *find_shared_node(struct cache_tree *shared,
1079 struct cache_extent *cache;
1080 struct shared_node *node;
1082 cache = lookup_cache_extent(shared, bytenr, 1);
1084 node = container_of(cache, struct shared_node, cache);
1090 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1093 struct shared_node *node;
1095 node = calloc(1, sizeof(*node));
1096 node->cache.start = bytenr;
1097 node->cache.size = 1;
1098 cache_tree_init(&node->root_cache);
1099 cache_tree_init(&node->inode_cache);
1102 ret = insert_cache_extent(shared, &node->cache);
1107 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1108 struct walk_control *wc, int level)
1110 struct shared_node *node;
1111 struct shared_node *dest;
1113 if (level == wc->active_node)
1116 BUG_ON(wc->active_node <= level);
1117 node = find_shared_node(&wc->shared, bytenr);
1119 add_shared_node(&wc->shared, bytenr, refs);
1120 node = find_shared_node(&wc->shared, bytenr);
1121 wc->nodes[level] = node;
1122 wc->active_node = level;
1126 if (wc->root_level == wc->active_node &&
1127 btrfs_root_refs(&root->root_item) == 0) {
1128 if (--node->refs == 0) {
1129 free_inode_recs_tree(&node->root_cache);
1130 free_inode_recs_tree(&node->inode_cache);
1131 remove_cache_extent(&wc->shared, &node->cache);
1137 dest = wc->nodes[wc->active_node];
1138 splice_shared_node(node, dest);
1139 if (node->refs == 0) {
1140 remove_cache_extent(&wc->shared, &node->cache);
1146 static int leave_shared_node(struct btrfs_root *root,
1147 struct walk_control *wc, int level)
1149 struct shared_node *node;
1150 struct shared_node *dest;
1153 if (level == wc->root_level)
1156 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1160 BUG_ON(i >= BTRFS_MAX_LEVEL);
1162 node = wc->nodes[wc->active_node];
1163 wc->nodes[wc->active_node] = NULL;
1164 wc->active_node = i;
1166 dest = wc->nodes[wc->active_node];
1167 if (wc->active_node < wc->root_level ||
1168 btrfs_root_refs(&root->root_item) > 0) {
1169 BUG_ON(node->refs <= 1);
1170 splice_shared_node(node, dest);
1172 BUG_ON(node->refs < 2);
1181 * 1 - if the root with id child_root_id is a child of root parent_root_id
1182 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1183 * has other root(s) as parent(s)
1184 * 2 - if the root child_root_id doesn't have any parent roots
1186 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1189 struct btrfs_path path;
1190 struct btrfs_key key;
1191 struct extent_buffer *leaf;
1195 btrfs_init_path(&path);
1197 key.objectid = parent_root_id;
1198 key.type = BTRFS_ROOT_REF_KEY;
1199 key.offset = child_root_id;
1200 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1204 btrfs_release_path(&path);
1208 key.objectid = child_root_id;
1209 key.type = BTRFS_ROOT_BACKREF_KEY;
1211 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1217 leaf = path.nodes[0];
1218 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1219 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1222 leaf = path.nodes[0];
1225 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1226 if (key.objectid != child_root_id ||
1227 key.type != BTRFS_ROOT_BACKREF_KEY)
1232 if (key.offset == parent_root_id) {
1233 btrfs_release_path(&path);
1240 btrfs_release_path(&path);
1243 return has_parent ? 0 : 2;
1246 static int process_dir_item(struct btrfs_root *root,
1247 struct extent_buffer *eb,
1248 int slot, struct btrfs_key *key,
1249 struct shared_node *active_node)
1259 struct btrfs_dir_item *di;
1260 struct inode_record *rec;
1261 struct cache_tree *root_cache;
1262 struct cache_tree *inode_cache;
1263 struct btrfs_key location;
1264 char namebuf[BTRFS_NAME_LEN];
1266 root_cache = &active_node->root_cache;
1267 inode_cache = &active_node->inode_cache;
1268 rec = active_node->current;
1269 rec->found_dir_item = 1;
1271 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1272 total = btrfs_item_size_nr(eb, slot);
1273 while (cur < total) {
1275 btrfs_dir_item_key_to_cpu(eb, di, &location);
1276 name_len = btrfs_dir_name_len(eb, di);
1277 data_len = btrfs_dir_data_len(eb, di);
1278 filetype = btrfs_dir_type(eb, di);
1280 rec->found_size += name_len;
1281 if (name_len <= BTRFS_NAME_LEN) {
1285 len = BTRFS_NAME_LEN;
1286 error = REF_ERR_NAME_TOO_LONG;
1288 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1290 if (location.type == BTRFS_INODE_ITEM_KEY) {
1291 add_inode_backref(inode_cache, location.objectid,
1292 key->objectid, key->offset, namebuf,
1293 len, filetype, key->type, error);
1294 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1295 add_inode_backref(root_cache, location.objectid,
1296 key->objectid, key->offset,
1297 namebuf, len, filetype,
1300 fprintf(stderr, "invalid location in dir item %u\n",
1302 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1303 key->objectid, key->offset, namebuf,
1304 len, filetype, key->type, error);
1307 len = sizeof(*di) + name_len + data_len;
1308 di = (struct btrfs_dir_item *)((char *)di + len);
1311 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1312 rec->errors |= I_ERR_DUP_DIR_INDEX;
1317 static int process_inode_ref(struct extent_buffer *eb,
1318 int slot, struct btrfs_key *key,
1319 struct shared_node *active_node)
1327 struct cache_tree *inode_cache;
1328 struct btrfs_inode_ref *ref;
1329 char namebuf[BTRFS_NAME_LEN];
1331 inode_cache = &active_node->inode_cache;
1333 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1334 total = btrfs_item_size_nr(eb, slot);
1335 while (cur < total) {
1336 name_len = btrfs_inode_ref_name_len(eb, ref);
1337 index = btrfs_inode_ref_index(eb, ref);
1338 if (name_len <= BTRFS_NAME_LEN) {
1342 len = BTRFS_NAME_LEN;
1343 error = REF_ERR_NAME_TOO_LONG;
1345 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1346 add_inode_backref(inode_cache, key->objectid, key->offset,
1347 index, namebuf, len, 0, key->type, error);
1349 len = sizeof(*ref) + name_len;
1350 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1356 static int process_inode_extref(struct extent_buffer *eb,
1357 int slot, struct btrfs_key *key,
1358 struct shared_node *active_node)
1367 struct cache_tree *inode_cache;
1368 struct btrfs_inode_extref *extref;
1369 char namebuf[BTRFS_NAME_LEN];
1371 inode_cache = &active_node->inode_cache;
1373 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1374 total = btrfs_item_size_nr(eb, slot);
1375 while (cur < total) {
1376 name_len = btrfs_inode_extref_name_len(eb, extref);
1377 index = btrfs_inode_extref_index(eb, extref);
1378 parent = btrfs_inode_extref_parent(eb, extref);
1379 if (name_len <= BTRFS_NAME_LEN) {
1383 len = BTRFS_NAME_LEN;
1384 error = REF_ERR_NAME_TOO_LONG;
1386 read_extent_buffer(eb, namebuf,
1387 (unsigned long)(extref + 1), len);
1388 add_inode_backref(inode_cache, key->objectid, parent,
1389 index, namebuf, len, 0, key->type, error);
1391 len = sizeof(*extref) + name_len;
1392 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1399 static int count_csum_range(struct btrfs_root *root, u64 start,
1400 u64 len, u64 *found)
1402 struct btrfs_key key;
1403 struct btrfs_path path;
1404 struct extent_buffer *leaf;
1409 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1411 btrfs_init_path(&path);
1413 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1415 key.type = BTRFS_EXTENT_CSUM_KEY;
1417 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1421 if (ret > 0 && path.slots[0] > 0) {
1422 leaf = path.nodes[0];
1423 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1424 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1425 key.type == BTRFS_EXTENT_CSUM_KEY)
1430 leaf = path.nodes[0];
1431 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1432 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1437 leaf = path.nodes[0];
1440 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1441 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1442 key.type != BTRFS_EXTENT_CSUM_KEY)
1445 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1446 if (key.offset >= start + len)
1449 if (key.offset > start)
1452 size = btrfs_item_size_nr(leaf, path.slots[0]);
1453 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1454 if (csum_end > start) {
1455 size = min(csum_end - start, len);
1464 btrfs_release_path(&path);
1470 static int process_file_extent(struct btrfs_root *root,
1471 struct extent_buffer *eb,
1472 int slot, struct btrfs_key *key,
1473 struct shared_node *active_node)
1475 struct inode_record *rec;
1476 struct btrfs_file_extent_item *fi;
1478 u64 disk_bytenr = 0;
1479 u64 extent_offset = 0;
1480 u64 mask = root->sectorsize - 1;
1484 rec = active_node->current;
1485 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1486 rec->found_file_extent = 1;
1488 if (rec->extent_start == (u64)-1) {
1489 rec->extent_start = key->offset;
1490 rec->extent_end = key->offset;
1493 if (rec->extent_end > key->offset)
1494 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1495 else if (rec->extent_end < key->offset) {
1496 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1497 key->offset - rec->extent_end);
1502 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1503 extent_type = btrfs_file_extent_type(eb, fi);
1505 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1506 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1508 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1509 rec->found_size += num_bytes;
1510 num_bytes = (num_bytes + mask) & ~mask;
1511 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1512 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1513 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1514 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1515 extent_offset = btrfs_file_extent_offset(eb, fi);
1516 if (num_bytes == 0 || (num_bytes & mask))
1517 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1518 if (num_bytes + extent_offset >
1519 btrfs_file_extent_ram_bytes(eb, fi))
1520 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1521 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1522 (btrfs_file_extent_compression(eb, fi) ||
1523 btrfs_file_extent_encryption(eb, fi) ||
1524 btrfs_file_extent_other_encoding(eb, fi)))
1525 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1526 if (disk_bytenr > 0)
1527 rec->found_size += num_bytes;
1529 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1531 rec->extent_end = key->offset + num_bytes;
1534 * The data reloc tree will copy full extents into its inode and then
1535 * copy the corresponding csums. Because the extent it copied could be
1536 * a preallocated extent that hasn't been written to yet there may be no
1537 * csums to copy, ergo we won't have csums for our file extent. This is
1538 * ok so just don't bother checking csums if the inode belongs to the
1541 if (disk_bytenr > 0 &&
1542 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1544 if (btrfs_file_extent_compression(eb, fi))
1545 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1547 disk_bytenr += extent_offset;
1549 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1552 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1554 rec->found_csum_item = 1;
1555 if (found < num_bytes)
1556 rec->some_csum_missing = 1;
1557 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1559 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1565 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1566 struct walk_control *wc)
1568 struct btrfs_key key;
1572 struct cache_tree *inode_cache;
1573 struct shared_node *active_node;
1575 if (wc->root_level == wc->active_node &&
1576 btrfs_root_refs(&root->root_item) == 0)
1579 active_node = wc->nodes[wc->active_node];
1580 inode_cache = &active_node->inode_cache;
1581 nritems = btrfs_header_nritems(eb);
1582 for (i = 0; i < nritems; i++) {
1583 btrfs_item_key_to_cpu(eb, &key, i);
1585 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1587 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1590 if (active_node->current == NULL ||
1591 active_node->current->ino < key.objectid) {
1592 if (active_node->current) {
1593 active_node->current->checked = 1;
1594 maybe_free_inode_rec(inode_cache,
1595 active_node->current);
1597 active_node->current = get_inode_rec(inode_cache,
1601 case BTRFS_DIR_ITEM_KEY:
1602 case BTRFS_DIR_INDEX_KEY:
1603 ret = process_dir_item(root, eb, i, &key, active_node);
1605 case BTRFS_INODE_REF_KEY:
1606 ret = process_inode_ref(eb, i, &key, active_node);
1608 case BTRFS_INODE_EXTREF_KEY:
1609 ret = process_inode_extref(eb, i, &key, active_node);
1611 case BTRFS_INODE_ITEM_KEY:
1612 ret = process_inode_item(eb, i, &key, active_node);
1614 case BTRFS_EXTENT_DATA_KEY:
1615 ret = process_file_extent(root, eb, i, &key,
1625 static void reada_walk_down(struct btrfs_root *root,
1626 struct extent_buffer *node, int slot)
1635 level = btrfs_header_level(node);
1639 nritems = btrfs_header_nritems(node);
1640 blocksize = btrfs_level_size(root, level - 1);
1641 for (i = slot; i < nritems; i++) {
1642 bytenr = btrfs_node_blockptr(node, i);
1643 ptr_gen = btrfs_node_ptr_generation(node, i);
1644 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1649 * Check the child node/leaf by the following condition:
1650 * 1. the first item key of the node/leaf should be the same with the one
1652 * 2. block in parent node should match the child node/leaf.
1653 * 3. generation of parent node and child's header should be consistent.
1655 * Or the child node/leaf pointed by the key in parent is not valid.
1657 * We hope to check leaf owner too, but since subvol may share leaves,
1658 * which makes leaf owner check not so strong, key check should be
1659 * sufficient enough for that case.
1661 static int check_child_node(struct btrfs_root *root,
1662 struct extent_buffer *parent, int slot,
1663 struct extent_buffer *child)
1665 struct btrfs_key parent_key;
1666 struct btrfs_key child_key;
1669 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1670 if (btrfs_header_level(child) == 0)
1671 btrfs_item_key_to_cpu(child, &child_key, 0);
1673 btrfs_node_key_to_cpu(child, &child_key, 0);
1675 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1678 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1679 parent_key.objectid, parent_key.type, parent_key.offset,
1680 child_key.objectid, child_key.type, child_key.offset);
1682 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1684 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1685 btrfs_node_blockptr(parent, slot),
1686 btrfs_header_bytenr(child));
1688 if (btrfs_node_ptr_generation(parent, slot) !=
1689 btrfs_header_generation(child)) {
1691 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1692 btrfs_header_generation(child),
1693 btrfs_node_ptr_generation(parent, slot));
1698 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1699 struct walk_control *wc, int *level)
1701 enum btrfs_tree_block_status status;
1704 struct extent_buffer *next;
1705 struct extent_buffer *cur;
1710 WARN_ON(*level < 0);
1711 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1712 ret = btrfs_lookup_extent_info(NULL, root,
1713 path->nodes[*level]->start,
1714 *level, 1, &refs, NULL);
1721 ret = enter_shared_node(root, path->nodes[*level]->start,
1729 while (*level >= 0) {
1730 WARN_ON(*level < 0);
1731 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1732 cur = path->nodes[*level];
1734 if (btrfs_header_level(cur) != *level)
1737 if (path->slots[*level] >= btrfs_header_nritems(cur))
1740 ret = process_one_leaf(root, cur, wc);
1745 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1746 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1747 blocksize = btrfs_level_size(root, *level - 1);
1748 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1754 ret = enter_shared_node(root, bytenr, refs,
1757 path->slots[*level]++;
1762 next = btrfs_find_tree_block(root, bytenr, blocksize);
1763 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1764 free_extent_buffer(next);
1765 reada_walk_down(root, cur, path->slots[*level]);
1766 next = read_tree_block(root, bytenr, blocksize,
1768 if (!extent_buffer_uptodate(next)) {
1769 struct btrfs_key node_key;
1771 btrfs_node_key_to_cpu(path->nodes[*level],
1773 path->slots[*level]);
1774 btrfs_add_corrupt_extent_record(root->fs_info,
1776 path->nodes[*level]->start,
1777 root->leafsize, *level);
1783 ret = check_child_node(root, cur, path->slots[*level], next);
1789 if (btrfs_is_leaf(next))
1790 status = btrfs_check_leaf(root, NULL, next);
1792 status = btrfs_check_node(root, NULL, next);
1793 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1794 free_extent_buffer(next);
1799 *level = *level - 1;
1800 free_extent_buffer(path->nodes[*level]);
1801 path->nodes[*level] = next;
1802 path->slots[*level] = 0;
1805 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1809 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1810 struct walk_control *wc, int *level)
1813 struct extent_buffer *leaf;
1815 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1816 leaf = path->nodes[i];
1817 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1822 free_extent_buffer(path->nodes[*level]);
1823 path->nodes[*level] = NULL;
1824 BUG_ON(*level > wc->active_node);
1825 if (*level == wc->active_node)
1826 leave_shared_node(root, wc, *level);
1833 static int check_root_dir(struct inode_record *rec)
1835 struct inode_backref *backref;
1838 if (!rec->found_inode_item || rec->errors)
1840 if (rec->nlink != 1 || rec->found_link != 0)
1842 if (list_empty(&rec->backrefs))
1844 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1845 if (!backref->found_inode_ref)
1847 if (backref->index != 0 || backref->namelen != 2 ||
1848 memcmp(backref->name, "..", 2))
1850 if (backref->found_dir_index || backref->found_dir_item)
1857 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1858 struct btrfs_root *root, struct btrfs_path *path,
1859 struct inode_record *rec)
1861 struct btrfs_inode_item *ei;
1862 struct btrfs_key key;
1865 key.objectid = rec->ino;
1866 key.type = BTRFS_INODE_ITEM_KEY;
1867 key.offset = (u64)-1;
1869 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1873 if (!path->slots[0]) {
1880 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1881 if (key.objectid != rec->ino) {
1886 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1887 struct btrfs_inode_item);
1888 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1889 btrfs_mark_buffer_dirty(path->nodes[0]);
1890 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1891 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1892 root->root_key.objectid);
1894 btrfs_release_path(path);
1898 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1899 struct btrfs_root *root,
1900 struct btrfs_path *path,
1901 struct inode_record *rec)
1905 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1906 btrfs_release_path(path);
1908 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1912 static int add_missing_dir_index(struct btrfs_root *root,
1913 struct cache_tree *inode_cache,
1914 struct inode_record *rec,
1915 struct inode_backref *backref)
1917 struct btrfs_path *path;
1918 struct btrfs_trans_handle *trans;
1919 struct btrfs_dir_item *dir_item;
1920 struct extent_buffer *leaf;
1921 struct btrfs_key key;
1922 struct btrfs_disk_key disk_key;
1923 struct inode_record *dir_rec;
1924 unsigned long name_ptr;
1925 u32 data_size = sizeof(*dir_item) + backref->namelen;
1928 path = btrfs_alloc_path();
1932 trans = btrfs_start_transaction(root, 1);
1933 if (IS_ERR(trans)) {
1934 btrfs_free_path(path);
1935 return PTR_ERR(trans);
1938 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1939 (unsigned long long)rec->ino);
1940 key.objectid = backref->dir;
1941 key.type = BTRFS_DIR_INDEX_KEY;
1942 key.offset = backref->index;
1944 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1947 leaf = path->nodes[0];
1948 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
1950 disk_key.objectid = cpu_to_le64(rec->ino);
1951 disk_key.type = BTRFS_INODE_ITEM_KEY;
1952 disk_key.offset = 0;
1954 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
1955 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
1956 btrfs_set_dir_data_len(leaf, dir_item, 0);
1957 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
1958 name_ptr = (unsigned long)(dir_item + 1);
1959 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
1960 btrfs_mark_buffer_dirty(leaf);
1961 btrfs_free_path(path);
1962 btrfs_commit_transaction(trans, root);
1964 backref->found_dir_index = 1;
1965 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
1968 dir_rec->found_size += backref->namelen;
1969 if (dir_rec->found_size == dir_rec->isize &&
1970 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
1971 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1972 if (dir_rec->found_size != dir_rec->isize)
1973 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
1978 static int delete_dir_index(struct btrfs_root *root,
1979 struct cache_tree *inode_cache,
1980 struct inode_record *rec,
1981 struct inode_backref *backref)
1983 struct btrfs_trans_handle *trans;
1984 struct btrfs_dir_item *di;
1985 struct btrfs_path *path;
1988 path = btrfs_alloc_path();
1992 trans = btrfs_start_transaction(root, 1);
1993 if (IS_ERR(trans)) {
1994 btrfs_free_path(path);
1995 return PTR_ERR(trans);
1999 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2000 (unsigned long long)backref->dir,
2001 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2002 (unsigned long long)root->objectid);
2004 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2005 backref->name, backref->namelen,
2006 backref->index, -1);
2009 btrfs_free_path(path);
2010 btrfs_commit_transaction(trans, root);
2017 ret = btrfs_del_item(trans, root, path);
2019 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2021 btrfs_free_path(path);
2022 btrfs_commit_transaction(trans, root);
2026 static int create_inode_item(struct btrfs_root *root,
2027 struct inode_record *rec,
2028 struct inode_backref *backref, int root_dir)
2030 struct btrfs_trans_handle *trans;
2031 struct btrfs_inode_item inode_item;
2032 time_t now = time(NULL);
2035 trans = btrfs_start_transaction(root, 1);
2036 if (IS_ERR(trans)) {
2037 ret = PTR_ERR(trans);
2041 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2042 "be incomplete, please check permissions and content after "
2043 "the fsck completes.\n", (unsigned long long)root->objectid,
2044 (unsigned long long)rec->ino);
2046 memset(&inode_item, 0, sizeof(inode_item));
2047 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2049 btrfs_set_stack_inode_nlink(&inode_item, 1);
2051 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2052 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2053 if (rec->found_dir_item) {
2054 if (rec->found_file_extent)
2055 fprintf(stderr, "root %llu inode %llu has both a dir "
2056 "item and extents, unsure if it is a dir or a "
2057 "regular file so setting it as a directory\n",
2058 (unsigned long long)root->objectid,
2059 (unsigned long long)rec->ino);
2060 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2061 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2062 } else if (!rec->found_dir_item) {
2063 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2064 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2066 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2067 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2068 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2069 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2070 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2071 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2072 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2073 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2075 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2077 btrfs_commit_transaction(trans, root);
2081 static int repair_inode_backrefs(struct btrfs_root *root,
2082 struct inode_record *rec,
2083 struct cache_tree *inode_cache,
2086 struct inode_backref *tmp, *backref;
2087 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2091 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2092 if (!delete && rec->ino == root_dirid) {
2093 if (!rec->found_inode_item) {
2094 ret = create_inode_item(root, rec, backref, 1);
2101 /* Index 0 for root dir's are special, don't mess with it */
2102 if (rec->ino == root_dirid && backref->index == 0)
2106 ((backref->found_dir_index && !backref->found_inode_ref) ||
2107 (backref->found_dir_index && backref->found_inode_ref &&
2108 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2109 ret = delete_dir_index(root, inode_cache, rec, backref);
2113 list_del(&backref->list);
2117 if (!delete && !backref->found_dir_index &&
2118 backref->found_dir_item && backref->found_inode_ref) {
2119 ret = add_missing_dir_index(root, inode_cache, rec,
2124 if (backref->found_dir_item &&
2125 backref->found_dir_index &&
2126 backref->found_dir_index) {
2127 if (!backref->errors &&
2128 backref->found_inode_ref) {
2129 list_del(&backref->list);
2135 if (!delete && (!backref->found_dir_index &&
2136 !backref->found_dir_item &&
2137 backref->found_inode_ref)) {
2138 struct btrfs_trans_handle *trans;
2139 struct btrfs_key location;
2141 ret = check_dir_conflict(root, backref->name,
2147 * let nlink fixing routine to handle it,
2148 * which can do it better.
2153 location.objectid = rec->ino;
2154 location.type = BTRFS_INODE_ITEM_KEY;
2155 location.offset = 0;
2157 trans = btrfs_start_transaction(root, 1);
2158 if (IS_ERR(trans)) {
2159 ret = PTR_ERR(trans);
2162 fprintf(stderr, "adding missing dir index/item pair "
2164 (unsigned long long)rec->ino);
2165 ret = btrfs_insert_dir_item(trans, root, backref->name,
2167 backref->dir, &location,
2168 imode_to_type(rec->imode),
2171 btrfs_commit_transaction(trans, root);
2175 if (!delete && (backref->found_inode_ref &&
2176 backref->found_dir_index &&
2177 backref->found_dir_item &&
2178 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2179 !rec->found_inode_item)) {
2180 ret = create_inode_item(root, rec, backref, 0);
2187 return ret ? ret : repaired;
2191 * To determine the file type for nlink/inode_item repair
2193 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2194 * Return -ENOENT if file type is not found.
2196 static int find_file_type(struct inode_record *rec, u8 *type)
2198 struct inode_backref *backref;
2200 /* For inode item recovered case */
2201 if (rec->found_inode_item) {
2202 *type = imode_to_type(rec->imode);
2206 list_for_each_entry(backref, &rec->backrefs, list) {
2207 if (backref->found_dir_index || backref->found_dir_item) {
2208 *type = backref->filetype;
2216 * To determine the file name for nlink repair
2218 * Return 0 if file name is found, set name and namelen.
2219 * Return -ENOENT if file name is not found.
2221 static int find_file_name(struct inode_record *rec,
2222 char *name, int *namelen)
2224 struct inode_backref *backref;
2226 list_for_each_entry(backref, &rec->backrefs, list) {
2227 if (backref->found_dir_index || backref->found_dir_item ||
2228 backref->found_inode_ref) {
2229 memcpy(name, backref->name, backref->namelen);
2230 *namelen = backref->namelen;
2237 /* Reset the nlink of the inode to the correct one */
2238 static int reset_nlink(struct btrfs_trans_handle *trans,
2239 struct btrfs_root *root,
2240 struct btrfs_path *path,
2241 struct inode_record *rec)
2243 struct inode_backref *backref;
2244 struct inode_backref *tmp;
2245 struct btrfs_key key;
2246 struct btrfs_inode_item *inode_item;
2249 /* We don't believe this either, reset it and iterate backref */
2250 rec->found_link = 0;
2252 /* Remove all backref including the valid ones */
2253 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2254 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2255 backref->index, backref->name,
2256 backref->namelen, 0);
2260 /* remove invalid backref, so it won't be added back */
2261 if (!(backref->found_dir_index &&
2262 backref->found_dir_item &&
2263 backref->found_inode_ref)) {
2264 list_del(&backref->list);
2271 /* Set nlink to 0 */
2272 key.objectid = rec->ino;
2273 key.type = BTRFS_INODE_ITEM_KEY;
2275 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2282 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2283 struct btrfs_inode_item);
2284 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2285 btrfs_mark_buffer_dirty(path->nodes[0]);
2286 btrfs_release_path(path);
2289 * Add back valid inode_ref/dir_item/dir_index,
2290 * add_link() will handle the nlink inc, so new nlink must be correct
2292 list_for_each_entry(backref, &rec->backrefs, list) {
2293 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2294 backref->name, backref->namelen,
2295 backref->ref_type, &backref->index, 1);
2300 btrfs_release_path(path);
2304 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2305 struct btrfs_root *root,
2306 struct btrfs_path *path,
2307 struct inode_record *rec)
2309 char *dir_name = "lost+found";
2310 char namebuf[BTRFS_NAME_LEN] = {0};
2315 int name_recovered = 0;
2316 int type_recovered = 0;
2320 * Get file name and type first before these invalid inode ref
2321 * are deleted by remove_all_invalid_backref()
2323 name_recovered = !find_file_name(rec, namebuf, &namelen);
2324 type_recovered = !find_file_type(rec, &type);
2326 if (!name_recovered) {
2327 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2328 rec->ino, rec->ino);
2329 namelen = count_digits(rec->ino);
2330 sprintf(namebuf, "%llu", rec->ino);
2333 if (!type_recovered) {
2334 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2336 type = BTRFS_FT_REG_FILE;
2340 ret = reset_nlink(trans, root, path, rec);
2343 "Failed to reset nlink for inode %llu: %s\n",
2344 rec->ino, strerror(-ret));
2348 if (rec->found_link == 0) {
2349 lost_found_ino = root->highest_inode;
2350 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2355 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2356 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2359 fprintf(stderr, "Failed to create '%s' dir: %s",
2360 dir_name, strerror(-ret));
2363 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2364 namebuf, namelen, type, NULL, 1);
2365 if (ret == -EEXIST) {
2367 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2369 if (namelen + count_digits(rec->ino) + 1 >
2374 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2376 namelen += count_digits(rec->ino) + 1;
2377 ret = btrfs_add_link(trans, root, rec->ino,
2378 lost_found_ino, namebuf,
2379 namelen, type, NULL, 1);
2383 "Failed to link the inode %llu to %s dir: %s",
2384 rec->ino, dir_name, strerror(-ret));
2388 * Just increase the found_link, don't actually add the
2389 * backref. This will make things easier and this inode
2390 * record will be freed after the repair is done.
2391 * So fsck will not report problem about this inode.
2394 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2395 namelen, namebuf, dir_name);
2397 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2398 printf("Fixed the nlink of inode %llu\n", rec->ino);
2400 btrfs_release_path(path);
2405 * Check if there is any normal(reg or prealloc) file extent for given
2407 * This is used to determine the file type when neither its dir_index/item or
2408 * inode_item exists.
2410 * This will *NOT* report error, if any error happens, just consider it does
2411 * not have any normal file extent.
2413 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2415 struct btrfs_path *path;
2416 struct btrfs_key key;
2417 struct btrfs_key found_key;
2418 struct btrfs_file_extent_item *fi;
2422 path = btrfs_alloc_path();
2426 key.type = BTRFS_EXTENT_DATA_KEY;
2429 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2434 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2435 ret = btrfs_next_leaf(root, path);
2442 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2444 if (found_key.objectid != ino ||
2445 found_key.type != BTRFS_EXTENT_DATA_KEY)
2447 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2448 struct btrfs_file_extent_item);
2449 type = btrfs_file_extent_type(path->nodes[0], fi);
2450 if (type != BTRFS_FILE_EXTENT_INLINE) {
2456 btrfs_free_path(path);
2460 static u32 btrfs_type_to_imode(u8 type)
2462 static u32 imode_by_btrfs_type[] = {
2463 [BTRFS_FT_REG_FILE] = S_IFREG,
2464 [BTRFS_FT_DIR] = S_IFDIR,
2465 [BTRFS_FT_CHRDEV] = S_IFCHR,
2466 [BTRFS_FT_BLKDEV] = S_IFBLK,
2467 [BTRFS_FT_FIFO] = S_IFIFO,
2468 [BTRFS_FT_SOCK] = S_IFSOCK,
2469 [BTRFS_FT_SYMLINK] = S_IFLNK,
2472 return imode_by_btrfs_type[(type)];
2475 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2476 struct btrfs_root *root,
2477 struct btrfs_path *path,
2478 struct inode_record *rec)
2482 int type_recovered = 0;
2485 printf("Trying to rebuild inode:%llu\n", rec->ino);
2487 type_recovered = !find_file_type(rec, &filetype);
2490 * Try to determine inode type if type not found.
2492 * For found regular file extent, it must be FILE.
2493 * For found dir_item/index, it must be DIR.
2495 * For undetermined one, use FILE as fallback.
2498 * 1. If found backref(inode_index/item is already handled) to it,
2500 * Need new inode-inode ref structure to allow search for that.
2502 if (!type_recovered) {
2503 if (rec->found_file_extent &&
2504 find_normal_file_extent(root, rec->ino)) {
2506 filetype = BTRFS_FT_REG_FILE;
2507 } else if (rec->found_dir_item) {
2509 filetype = BTRFS_FT_DIR;
2510 } else if (!list_empty(&rec->orphan_extents)) {
2512 filetype = BTRFS_FT_REG_FILE;
2514 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2517 filetype = BTRFS_FT_REG_FILE;
2521 ret = btrfs_new_inode(trans, root, rec->ino,
2522 mode | btrfs_type_to_imode(filetype));
2527 * Here inode rebuild is done, we only rebuild the inode item,
2528 * don't repair the nlink(like move to lost+found).
2529 * That is the job of nlink repair.
2531 * We just fill the record and return
2533 rec->found_dir_item = 1;
2534 rec->imode = mode | btrfs_type_to_imode(filetype);
2536 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2537 /* Ensure the inode_nlinks repair function will be called */
2538 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2543 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2544 struct btrfs_root *root,
2545 struct btrfs_path *path,
2546 struct inode_record *rec)
2548 struct orphan_data_extent *orphan;
2549 struct orphan_data_extent *tmp;
2552 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2554 * Check for conflicting file extents
2556 * Here we don't know whether the extents is compressed or not,
2557 * so we can only assume it not compressed nor data offset,
2558 * and use its disk_len as extent length.
2560 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2561 orphan->offset, orphan->disk_len, 0);
2562 btrfs_release_path(path);
2567 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2568 orphan->disk_bytenr, orphan->disk_len);
2569 ret = btrfs_free_extent(trans,
2570 root->fs_info->extent_root,
2571 orphan->disk_bytenr, orphan->disk_len,
2572 0, root->objectid, orphan->objectid,
2577 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2578 orphan->offset, orphan->disk_bytenr,
2579 orphan->disk_len, orphan->disk_len);
2583 /* Update file size info */
2584 rec->found_size += orphan->disk_len;
2585 if (rec->found_size == rec->nbytes)
2586 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2588 /* Update the file extent hole info too */
2589 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2593 if (RB_EMPTY_ROOT(&rec->holes))
2594 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2596 list_del(&orphan->list);
2599 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2604 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2605 struct btrfs_root *root,
2606 struct btrfs_path *path,
2607 struct inode_record *rec)
2609 struct rb_node *node;
2610 struct file_extent_hole *hole;
2613 node = rb_first(&rec->holes);
2616 hole = rb_entry(node, struct file_extent_hole, node);
2617 ret = btrfs_punch_hole(trans, root, rec->ino,
2618 hole->start, hole->len);
2621 ret = del_file_extent_hole(&rec->holes, hole->start,
2625 if (RB_EMPTY_ROOT(&rec->holes))
2626 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2627 node = rb_first(&rec->holes);
2629 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2630 rec->ino, root->objectid);
2635 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2637 struct btrfs_trans_handle *trans;
2638 struct btrfs_path *path;
2641 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2642 I_ERR_NO_ORPHAN_ITEM |
2643 I_ERR_LINK_COUNT_WRONG |
2644 I_ERR_NO_INODE_ITEM |
2645 I_ERR_FILE_EXTENT_ORPHAN |
2646 I_ERR_FILE_EXTENT_DISCOUNT)))
2649 path = btrfs_alloc_path();
2654 * For nlink repair, it may create a dir and add link, so
2655 * 2 for parent(256)'s dir_index and dir_item
2656 * 2 for lost+found dir's inode_item and inode_ref
2657 * 1 for the new inode_ref of the file
2658 * 2 for lost+found dir's dir_index and dir_item for the file
2660 trans = btrfs_start_transaction(root, 7);
2661 if (IS_ERR(trans)) {
2662 btrfs_free_path(path);
2663 return PTR_ERR(trans);
2666 if (rec->errors & I_ERR_NO_INODE_ITEM)
2667 ret = repair_inode_no_item(trans, root, path, rec);
2668 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2669 ret = repair_inode_orphan_extent(trans, root, path, rec);
2670 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2671 ret = repair_inode_discount_extent(trans, root, path, rec);
2672 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2673 ret = repair_inode_isize(trans, root, path, rec);
2674 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2675 ret = repair_inode_orphan_item(trans, root, path, rec);
2676 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2677 ret = repair_inode_nlinks(trans, root, path, rec);
2678 btrfs_commit_transaction(trans, root);
2679 btrfs_free_path(path);
2683 static int check_inode_recs(struct btrfs_root *root,
2684 struct cache_tree *inode_cache)
2686 struct cache_extent *cache;
2687 struct ptr_node *node;
2688 struct inode_record *rec;
2689 struct inode_backref *backref;
2694 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2696 if (btrfs_root_refs(&root->root_item) == 0) {
2697 if (!cache_tree_empty(inode_cache))
2698 fprintf(stderr, "warning line %d\n", __LINE__);
2703 * We need to record the highest inode number for later 'lost+found'
2705 * We must select a ino not used/refered by any existing inode, or
2706 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2707 * this may cause 'lost+found' dir has wrong nlinks.
2709 cache = last_cache_extent(inode_cache);
2711 node = container_of(cache, struct ptr_node, cache);
2713 if (rec->ino > root->highest_inode)
2714 root->highest_inode = rec->ino;
2718 * We need to repair backrefs first because we could change some of the
2719 * errors in the inode recs.
2721 * We also need to go through and delete invalid backrefs first and then
2722 * add the correct ones second. We do this because we may get EEXIST
2723 * when adding back the correct index because we hadn't yet deleted the
2726 * For example, if we were missing a dir index then the directories
2727 * isize would be wrong, so if we fixed the isize to what we thought it
2728 * would be and then fixed the backref we'd still have a invalid fs, so
2729 * we need to add back the dir index and then check to see if the isize
2734 if (stage == 3 && !err)
2737 cache = search_cache_extent(inode_cache, 0);
2738 while (repair && cache) {
2739 node = container_of(cache, struct ptr_node, cache);
2741 cache = next_cache_extent(cache);
2743 /* Need to free everything up and rescan */
2745 remove_cache_extent(inode_cache, &node->cache);
2747 free_inode_rec(rec);
2751 if (list_empty(&rec->backrefs))
2754 ret = repair_inode_backrefs(root, rec, inode_cache,
2768 rec = get_inode_rec(inode_cache, root_dirid, 0);
2770 ret = check_root_dir(rec);
2772 fprintf(stderr, "root %llu root dir %llu error\n",
2773 (unsigned long long)root->root_key.objectid,
2774 (unsigned long long)root_dirid);
2775 print_inode_error(root, rec);
2780 struct btrfs_trans_handle *trans;
2782 trans = btrfs_start_transaction(root, 1);
2783 if (IS_ERR(trans)) {
2784 err = PTR_ERR(trans);
2789 "root %llu missing its root dir, recreating\n",
2790 (unsigned long long)root->objectid);
2792 ret = btrfs_make_root_dir(trans, root, root_dirid);
2795 btrfs_commit_transaction(trans, root);
2799 fprintf(stderr, "root %llu root dir %llu not found\n",
2800 (unsigned long long)root->root_key.objectid,
2801 (unsigned long long)root_dirid);
2805 cache = search_cache_extent(inode_cache, 0);
2808 node = container_of(cache, struct ptr_node, cache);
2810 remove_cache_extent(inode_cache, &node->cache);
2812 if (rec->ino == root_dirid ||
2813 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2814 free_inode_rec(rec);
2818 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2819 ret = check_orphan_item(root, rec->ino);
2821 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2822 if (can_free_inode_rec(rec)) {
2823 free_inode_rec(rec);
2828 if (!rec->found_inode_item)
2829 rec->errors |= I_ERR_NO_INODE_ITEM;
2830 if (rec->found_link != rec->nlink)
2831 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2833 ret = try_repair_inode(root, rec);
2834 if (ret == 0 && can_free_inode_rec(rec)) {
2835 free_inode_rec(rec);
2841 if (!(repair && ret == 0))
2843 print_inode_error(root, rec);
2844 list_for_each_entry(backref, &rec->backrefs, list) {
2845 if (!backref->found_dir_item)
2846 backref->errors |= REF_ERR_NO_DIR_ITEM;
2847 if (!backref->found_dir_index)
2848 backref->errors |= REF_ERR_NO_DIR_INDEX;
2849 if (!backref->found_inode_ref)
2850 backref->errors |= REF_ERR_NO_INODE_REF;
2851 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2852 " namelen %u name %s filetype %d errors %x",
2853 (unsigned long long)backref->dir,
2854 (unsigned long long)backref->index,
2855 backref->namelen, backref->name,
2856 backref->filetype, backref->errors);
2857 print_ref_error(backref->errors);
2859 free_inode_rec(rec);
2861 return (error > 0) ? -1 : 0;
2864 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2867 struct cache_extent *cache;
2868 struct root_record *rec = NULL;
2871 cache = lookup_cache_extent(root_cache, objectid, 1);
2873 rec = container_of(cache, struct root_record, cache);
2875 rec = calloc(1, sizeof(*rec));
2876 rec->objectid = objectid;
2877 INIT_LIST_HEAD(&rec->backrefs);
2878 rec->cache.start = objectid;
2879 rec->cache.size = 1;
2881 ret = insert_cache_extent(root_cache, &rec->cache);
2887 static struct root_backref *get_root_backref(struct root_record *rec,
2888 u64 ref_root, u64 dir, u64 index,
2889 const char *name, int namelen)
2891 struct root_backref *backref;
2893 list_for_each_entry(backref, &rec->backrefs, list) {
2894 if (backref->ref_root != ref_root || backref->dir != dir ||
2895 backref->namelen != namelen)
2897 if (memcmp(name, backref->name, namelen))
2902 backref = malloc(sizeof(*backref) + namelen + 1);
2903 memset(backref, 0, sizeof(*backref));
2904 backref->ref_root = ref_root;
2906 backref->index = index;
2907 backref->namelen = namelen;
2908 memcpy(backref->name, name, namelen);
2909 backref->name[namelen] = '\0';
2910 list_add_tail(&backref->list, &rec->backrefs);
2914 static void free_root_record(struct cache_extent *cache)
2916 struct root_record *rec;
2917 struct root_backref *backref;
2919 rec = container_of(cache, struct root_record, cache);
2920 while (!list_empty(&rec->backrefs)) {
2921 backref = list_entry(rec->backrefs.next,
2922 struct root_backref, list);
2923 list_del(&backref->list);
2930 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2932 static int add_root_backref(struct cache_tree *root_cache,
2933 u64 root_id, u64 ref_root, u64 dir, u64 index,
2934 const char *name, int namelen,
2935 int item_type, int errors)
2937 struct root_record *rec;
2938 struct root_backref *backref;
2940 rec = get_root_rec(root_cache, root_id);
2941 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2943 backref->errors |= errors;
2945 if (item_type != BTRFS_DIR_ITEM_KEY) {
2946 if (backref->found_dir_index || backref->found_back_ref ||
2947 backref->found_forward_ref) {
2948 if (backref->index != index)
2949 backref->errors |= REF_ERR_INDEX_UNMATCH;
2951 backref->index = index;
2955 if (item_type == BTRFS_DIR_ITEM_KEY) {
2956 if (backref->found_forward_ref)
2958 backref->found_dir_item = 1;
2959 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
2960 backref->found_dir_index = 1;
2961 } else if (item_type == BTRFS_ROOT_REF_KEY) {
2962 if (backref->found_forward_ref)
2963 backref->errors |= REF_ERR_DUP_ROOT_REF;
2964 else if (backref->found_dir_item)
2966 backref->found_forward_ref = 1;
2967 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
2968 if (backref->found_back_ref)
2969 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
2970 backref->found_back_ref = 1;
2975 if (backref->found_forward_ref && backref->found_dir_item)
2976 backref->reachable = 1;
2980 static int merge_root_recs(struct btrfs_root *root,
2981 struct cache_tree *src_cache,
2982 struct cache_tree *dst_cache)
2984 struct cache_extent *cache;
2985 struct ptr_node *node;
2986 struct inode_record *rec;
2987 struct inode_backref *backref;
2990 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
2991 free_inode_recs_tree(src_cache);
2996 cache = search_cache_extent(src_cache, 0);
2999 node = container_of(cache, struct ptr_node, cache);
3001 remove_cache_extent(src_cache, &node->cache);
3004 ret = is_child_root(root, root->objectid, rec->ino);
3010 list_for_each_entry(backref, &rec->backrefs, list) {
3011 BUG_ON(backref->found_inode_ref);
3012 if (backref->found_dir_item)
3013 add_root_backref(dst_cache, rec->ino,
3014 root->root_key.objectid, backref->dir,
3015 backref->index, backref->name,
3016 backref->namelen, BTRFS_DIR_ITEM_KEY,
3018 if (backref->found_dir_index)
3019 add_root_backref(dst_cache, rec->ino,
3020 root->root_key.objectid, backref->dir,
3021 backref->index, backref->name,
3022 backref->namelen, BTRFS_DIR_INDEX_KEY,
3026 free_inode_rec(rec);
3033 static int check_root_refs(struct btrfs_root *root,
3034 struct cache_tree *root_cache)
3036 struct root_record *rec;
3037 struct root_record *ref_root;
3038 struct root_backref *backref;
3039 struct cache_extent *cache;
3045 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3048 /* fixme: this can not detect circular references */
3051 cache = search_cache_extent(root_cache, 0);
3055 rec = container_of(cache, struct root_record, cache);
3056 cache = next_cache_extent(cache);
3058 if (rec->found_ref == 0)
3061 list_for_each_entry(backref, &rec->backrefs, list) {
3062 if (!backref->reachable)
3065 ref_root = get_root_rec(root_cache,
3067 if (ref_root->found_ref > 0)
3070 backref->reachable = 0;
3072 if (rec->found_ref == 0)
3078 cache = search_cache_extent(root_cache, 0);
3082 rec = container_of(cache, struct root_record, cache);
3083 cache = next_cache_extent(cache);
3085 if (rec->found_ref == 0 &&
3086 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3087 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3088 ret = check_orphan_item(root->fs_info->tree_root,
3094 * If we don't have a root item then we likely just have
3095 * a dir item in a snapshot for this root but no actual
3096 * ref key or anything so it's meaningless.
3098 if (!rec->found_root_item)
3101 fprintf(stderr, "fs tree %llu not referenced\n",
3102 (unsigned long long)rec->objectid);
3106 if (rec->found_ref > 0 && !rec->found_root_item)
3108 list_for_each_entry(backref, &rec->backrefs, list) {
3109 if (!backref->found_dir_item)
3110 backref->errors |= REF_ERR_NO_DIR_ITEM;
3111 if (!backref->found_dir_index)
3112 backref->errors |= REF_ERR_NO_DIR_INDEX;
3113 if (!backref->found_back_ref)
3114 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3115 if (!backref->found_forward_ref)
3116 backref->errors |= REF_ERR_NO_ROOT_REF;
3117 if (backref->reachable && backref->errors)
3124 fprintf(stderr, "fs tree %llu refs %u %s\n",
3125 (unsigned long long)rec->objectid, rec->found_ref,
3126 rec->found_root_item ? "" : "not found");
3128 list_for_each_entry(backref, &rec->backrefs, list) {
3129 if (!backref->reachable)
3131 if (!backref->errors && rec->found_root_item)
3133 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3134 " index %llu namelen %u name %s errors %x\n",
3135 (unsigned long long)backref->ref_root,
3136 (unsigned long long)backref->dir,
3137 (unsigned long long)backref->index,
3138 backref->namelen, backref->name,
3140 print_ref_error(backref->errors);
3143 return errors > 0 ? 1 : 0;
3146 static int process_root_ref(struct extent_buffer *eb, int slot,
3147 struct btrfs_key *key,
3148 struct cache_tree *root_cache)
3154 struct btrfs_root_ref *ref;
3155 char namebuf[BTRFS_NAME_LEN];
3158 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3160 dirid = btrfs_root_ref_dirid(eb, ref);
3161 index = btrfs_root_ref_sequence(eb, ref);
3162 name_len = btrfs_root_ref_name_len(eb, ref);
3164 if (name_len <= BTRFS_NAME_LEN) {
3168 len = BTRFS_NAME_LEN;
3169 error = REF_ERR_NAME_TOO_LONG;
3171 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3173 if (key->type == BTRFS_ROOT_REF_KEY) {
3174 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3175 index, namebuf, len, key->type, error);
3177 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3178 index, namebuf, len, key->type, error);
3183 static void free_corrupt_block(struct cache_extent *cache)
3185 struct btrfs_corrupt_block *corrupt;
3187 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3191 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3194 * Repair the btree of the given root.
3196 * The fix is to remove the node key in corrupt_blocks cache_tree.
3197 * and rebalance the tree.
3198 * After the fix, the btree should be writeable.
3200 static int repair_btree(struct btrfs_root *root,
3201 struct cache_tree *corrupt_blocks)
3203 struct btrfs_trans_handle *trans;
3204 struct btrfs_path *path;
3205 struct btrfs_corrupt_block *corrupt;
3206 struct cache_extent *cache;
3207 struct btrfs_key key;
3212 if (cache_tree_empty(corrupt_blocks))
3215 path = btrfs_alloc_path();
3219 trans = btrfs_start_transaction(root, 1);
3220 if (IS_ERR(trans)) {
3221 ret = PTR_ERR(trans);
3222 fprintf(stderr, "Error starting transaction: %s\n",
3226 cache = first_cache_extent(corrupt_blocks);
3228 corrupt = container_of(cache, struct btrfs_corrupt_block,
3230 level = corrupt->level;
3231 path->lowest_level = level;
3232 key.objectid = corrupt->key.objectid;
3233 key.type = corrupt->key.type;
3234 key.offset = corrupt->key.offset;
3237 * Here we don't want to do any tree balance, since it may
3238 * cause a balance with corrupted brother leaf/node,
3239 * so ins_len set to 0 here.
3240 * Balance will be done after all corrupt node/leaf is deleted.
3242 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3245 offset = btrfs_node_blockptr(path->nodes[level],
3246 path->slots[level]);
3248 /* Remove the ptr */
3249 ret = btrfs_del_ptr(trans, root, path, level,
3250 path->slots[level]);
3254 * Remove the corresponding extent
3255 * return value is not concerned.
3257 btrfs_release_path(path);
3258 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3259 0, root->root_key.objectid,
3261 cache = next_cache_extent(cache);
3264 /* Balance the btree using btrfs_search_slot() */
3265 cache = first_cache_extent(corrupt_blocks);
3267 corrupt = container_of(cache, struct btrfs_corrupt_block,
3269 memcpy(&key, &corrupt->key, sizeof(key));
3270 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3273 /* return will always >0 since it won't find the item */
3275 btrfs_release_path(path);
3276 cache = next_cache_extent(cache);
3279 btrfs_commit_transaction(trans, root);
3281 btrfs_free_path(path);
3285 static int check_fs_root(struct btrfs_root *root,
3286 struct cache_tree *root_cache,
3287 struct walk_control *wc)
3293 struct btrfs_path path;
3294 struct shared_node root_node;
3295 struct root_record *rec;
3296 struct btrfs_root_item *root_item = &root->root_item;
3297 struct cache_tree corrupt_blocks;
3298 struct orphan_data_extent *orphan;
3299 struct orphan_data_extent *tmp;
3300 enum btrfs_tree_block_status status;
3303 * Reuse the corrupt_block cache tree to record corrupted tree block
3305 * Unlike the usage in extent tree check, here we do it in a per
3306 * fs/subvol tree base.
3308 cache_tree_init(&corrupt_blocks);
3309 root->fs_info->corrupt_blocks = &corrupt_blocks;
3311 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3312 rec = get_root_rec(root_cache, root->root_key.objectid);
3313 if (btrfs_root_refs(root_item) > 0)
3314 rec->found_root_item = 1;
3317 btrfs_init_path(&path);
3318 memset(&root_node, 0, sizeof(root_node));
3319 cache_tree_init(&root_node.root_cache);
3320 cache_tree_init(&root_node.inode_cache);
3322 /* Move the orphan extent record to corresponding inode_record */
3323 list_for_each_entry_safe(orphan, tmp,
3324 &root->orphan_data_extents, list) {
3325 struct inode_record *inode;
3327 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3329 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3330 list_move(&orphan->list, &inode->orphan_extents);
3333 level = btrfs_header_level(root->node);
3334 memset(wc->nodes, 0, sizeof(wc->nodes));
3335 wc->nodes[level] = &root_node;
3336 wc->active_node = level;
3337 wc->root_level = level;
3339 /* We may not have checked the root block, lets do that now */
3340 if (btrfs_is_leaf(root->node))
3341 status = btrfs_check_leaf(root, NULL, root->node);
3343 status = btrfs_check_node(root, NULL, root->node);
3344 if (status != BTRFS_TREE_BLOCK_CLEAN)
3347 if (btrfs_root_refs(root_item) > 0 ||
3348 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3349 path.nodes[level] = root->node;
3350 extent_buffer_get(root->node);
3351 path.slots[level] = 0;
3353 struct btrfs_key key;
3354 struct btrfs_disk_key found_key;
3356 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3357 level = root_item->drop_level;
3358 path.lowest_level = level;
3359 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3362 btrfs_node_key(path.nodes[level], &found_key,
3364 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3365 sizeof(found_key)));
3369 wret = walk_down_tree(root, &path, wc, &level);
3375 wret = walk_up_tree(root, &path, wc, &level);
3382 btrfs_release_path(&path);
3384 if (!cache_tree_empty(&corrupt_blocks)) {
3385 struct cache_extent *cache;
3386 struct btrfs_corrupt_block *corrupt;
3388 printf("The following tree block(s) is corrupted in tree %llu:\n",
3389 root->root_key.objectid);
3390 cache = first_cache_extent(&corrupt_blocks);
3392 corrupt = container_of(cache,
3393 struct btrfs_corrupt_block,
3395 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3396 cache->start, corrupt->level,
3397 corrupt->key.objectid, corrupt->key.type,
3398 corrupt->key.offset);
3399 cache = next_cache_extent(cache);
3402 printf("Try to repair the btree for root %llu\n",
3403 root->root_key.objectid);
3404 ret = repair_btree(root, &corrupt_blocks);
3406 fprintf(stderr, "Failed to repair btree: %s\n",
3409 printf("Btree for root %llu is fixed\n",
3410 root->root_key.objectid);
3414 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3418 if (root_node.current) {
3419 root_node.current->checked = 1;
3420 maybe_free_inode_rec(&root_node.inode_cache,
3424 err = check_inode_recs(root, &root_node.inode_cache);
3428 free_corrupt_blocks_tree(&corrupt_blocks);
3429 root->fs_info->corrupt_blocks = NULL;
3430 free_orphan_data_extents(&root->orphan_data_extents);
3434 static int fs_root_objectid(u64 objectid)
3436 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3437 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3439 return is_fstree(objectid);
3442 static int check_fs_roots(struct btrfs_root *root,
3443 struct cache_tree *root_cache)
3445 struct btrfs_path path;
3446 struct btrfs_key key;
3447 struct walk_control wc;
3448 struct extent_buffer *leaf, *tree_node;
3449 struct btrfs_root *tmp_root;
3450 struct btrfs_root *tree_root = root->fs_info->tree_root;
3455 * Just in case we made any changes to the extent tree that weren't
3456 * reflected into the free space cache yet.
3459 reset_cached_block_groups(root->fs_info);
3460 memset(&wc, 0, sizeof(wc));
3461 cache_tree_init(&wc.shared);
3462 btrfs_init_path(&path);
3467 key.type = BTRFS_ROOT_ITEM_KEY;
3468 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3473 tree_node = tree_root->node;
3475 if (tree_node != tree_root->node) {
3476 free_root_recs_tree(root_cache);
3477 btrfs_release_path(&path);
3480 leaf = path.nodes[0];
3481 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3482 ret = btrfs_next_leaf(tree_root, &path);
3488 leaf = path.nodes[0];
3490 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3491 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3492 fs_root_objectid(key.objectid)) {
3493 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3494 tmp_root = btrfs_read_fs_root_no_cache(
3495 root->fs_info, &key);
3497 key.offset = (u64)-1;
3498 tmp_root = btrfs_read_fs_root(
3499 root->fs_info, &key);
3501 if (IS_ERR(tmp_root)) {
3505 ret = check_fs_root(tmp_root, root_cache, &wc);
3506 if (ret == -EAGAIN) {
3507 free_root_recs_tree(root_cache);
3508 btrfs_release_path(&path);
3513 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3514 btrfs_free_fs_root(tmp_root);
3515 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3516 key.type == BTRFS_ROOT_BACKREF_KEY) {
3517 process_root_ref(leaf, path.slots[0], &key,
3524 btrfs_release_path(&path);
3526 free_extent_cache_tree(&wc.shared);
3527 if (!cache_tree_empty(&wc.shared))
3528 fprintf(stderr, "warning line %d\n", __LINE__);
3533 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3535 struct list_head *cur = rec->backrefs.next;
3536 struct extent_backref *back;
3537 struct tree_backref *tback;
3538 struct data_backref *dback;
3542 while(cur != &rec->backrefs) {
3543 back = list_entry(cur, struct extent_backref, list);
3545 if (!back->found_extent_tree) {
3549 if (back->is_data) {
3550 dback = (struct data_backref *)back;
3551 fprintf(stderr, "Backref %llu %s %llu"
3552 " owner %llu offset %llu num_refs %lu"
3553 " not found in extent tree\n",
3554 (unsigned long long)rec->start,
3555 back->full_backref ?
3557 back->full_backref ?
3558 (unsigned long long)dback->parent:
3559 (unsigned long long)dback->root,
3560 (unsigned long long)dback->owner,
3561 (unsigned long long)dback->offset,
3562 (unsigned long)dback->num_refs);
3564 tback = (struct tree_backref *)back;
3565 fprintf(stderr, "Backref %llu parent %llu"
3566 " root %llu not found in extent tree\n",
3567 (unsigned long long)rec->start,
3568 (unsigned long long)tback->parent,
3569 (unsigned long long)tback->root);
3572 if (!back->is_data && !back->found_ref) {
3576 tback = (struct tree_backref *)back;
3577 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3578 (unsigned long long)rec->start,
3579 back->full_backref ? "parent" : "root",
3580 back->full_backref ?
3581 (unsigned long long)tback->parent :
3582 (unsigned long long)tback->root, back);
3584 if (back->is_data) {
3585 dback = (struct data_backref *)back;
3586 if (dback->found_ref != dback->num_refs) {
3590 fprintf(stderr, "Incorrect local backref count"
3591 " on %llu %s %llu owner %llu"
3592 " offset %llu found %u wanted %u back %p\n",
3593 (unsigned long long)rec->start,
3594 back->full_backref ?
3596 back->full_backref ?
3597 (unsigned long long)dback->parent:
3598 (unsigned long long)dback->root,
3599 (unsigned long long)dback->owner,
3600 (unsigned long long)dback->offset,
3601 dback->found_ref, dback->num_refs, back);
3603 if (dback->disk_bytenr != rec->start) {
3607 fprintf(stderr, "Backref disk bytenr does not"
3608 " match extent record, bytenr=%llu, "
3609 "ref bytenr=%llu\n",
3610 (unsigned long long)rec->start,
3611 (unsigned long long)dback->disk_bytenr);
3614 if (dback->bytes != rec->nr) {
3618 fprintf(stderr, "Backref bytes do not match "
3619 "extent backref, bytenr=%llu, ref "
3620 "bytes=%llu, backref bytes=%llu\n",
3621 (unsigned long long)rec->start,
3622 (unsigned long long)rec->nr,
3623 (unsigned long long)dback->bytes);
3626 if (!back->is_data) {
3629 dback = (struct data_backref *)back;
3630 found += dback->found_ref;
3633 if (found != rec->refs) {
3637 fprintf(stderr, "Incorrect global backref count "
3638 "on %llu found %llu wanted %llu\n",
3639 (unsigned long long)rec->start,
3640 (unsigned long long)found,
3641 (unsigned long long)rec->refs);
3647 static int free_all_extent_backrefs(struct extent_record *rec)
3649 struct extent_backref *back;
3650 struct list_head *cur;
3651 while (!list_empty(&rec->backrefs)) {
3652 cur = rec->backrefs.next;
3653 back = list_entry(cur, struct extent_backref, list);
3660 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3661 struct cache_tree *extent_cache)
3663 struct cache_extent *cache;
3664 struct extent_record *rec;
3667 cache = first_cache_extent(extent_cache);
3670 rec = container_of(cache, struct extent_record, cache);
3671 btrfs_unpin_extent(fs_info, rec->start, rec->max_size);
3672 remove_cache_extent(extent_cache, cache);
3673 free_all_extent_backrefs(rec);
3678 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3679 struct extent_record *rec)
3681 if (rec->content_checked && rec->owner_ref_checked &&
3682 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3683 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
3684 remove_cache_extent(extent_cache, &rec->cache);
3685 free_all_extent_backrefs(rec);
3686 list_del_init(&rec->list);
3692 static int check_owner_ref(struct btrfs_root *root,
3693 struct extent_record *rec,
3694 struct extent_buffer *buf)
3696 struct extent_backref *node;
3697 struct tree_backref *back;
3698 struct btrfs_root *ref_root;
3699 struct btrfs_key key;
3700 struct btrfs_path path;
3701 struct extent_buffer *parent;
3706 list_for_each_entry(node, &rec->backrefs, list) {
3709 if (!node->found_ref)
3711 if (node->full_backref)
3713 back = (struct tree_backref *)node;
3714 if (btrfs_header_owner(buf) == back->root)
3717 BUG_ON(rec->is_root);
3719 /* try to find the block by search corresponding fs tree */
3720 key.objectid = btrfs_header_owner(buf);
3721 key.type = BTRFS_ROOT_ITEM_KEY;
3722 key.offset = (u64)-1;
3724 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3725 if (IS_ERR(ref_root))
3728 level = btrfs_header_level(buf);
3730 btrfs_item_key_to_cpu(buf, &key, 0);
3732 btrfs_node_key_to_cpu(buf, &key, 0);
3734 btrfs_init_path(&path);
3735 path.lowest_level = level + 1;
3736 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3740 parent = path.nodes[level + 1];
3741 if (parent && buf->start == btrfs_node_blockptr(parent,
3742 path.slots[level + 1]))
3745 btrfs_release_path(&path);
3746 return found ? 0 : 1;
3749 static int is_extent_tree_record(struct extent_record *rec)
3751 struct list_head *cur = rec->backrefs.next;
3752 struct extent_backref *node;
3753 struct tree_backref *back;
3756 while(cur != &rec->backrefs) {
3757 node = list_entry(cur, struct extent_backref, list);
3761 back = (struct tree_backref *)node;
3762 if (node->full_backref)
3764 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3771 static int record_bad_block_io(struct btrfs_fs_info *info,
3772 struct cache_tree *extent_cache,
3775 struct extent_record *rec;
3776 struct cache_extent *cache;
3777 struct btrfs_key key;
3779 cache = lookup_cache_extent(extent_cache, start, len);
3783 rec = container_of(cache, struct extent_record, cache);
3784 if (!is_extent_tree_record(rec))
3787 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3788 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3791 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3792 struct extent_buffer *buf, int slot)
3794 if (btrfs_header_level(buf)) {
3795 struct btrfs_key_ptr ptr1, ptr2;
3797 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3798 sizeof(struct btrfs_key_ptr));
3799 read_extent_buffer(buf, &ptr2,
3800 btrfs_node_key_ptr_offset(slot + 1),
3801 sizeof(struct btrfs_key_ptr));
3802 write_extent_buffer(buf, &ptr1,
3803 btrfs_node_key_ptr_offset(slot + 1),
3804 sizeof(struct btrfs_key_ptr));
3805 write_extent_buffer(buf, &ptr2,
3806 btrfs_node_key_ptr_offset(slot),
3807 sizeof(struct btrfs_key_ptr));
3809 struct btrfs_disk_key key;
3810 btrfs_node_key(buf, &key, 0);
3811 btrfs_fixup_low_keys(root, path, &key,
3812 btrfs_header_level(buf) + 1);
3815 struct btrfs_item *item1, *item2;
3816 struct btrfs_key k1, k2;
3817 char *item1_data, *item2_data;
3818 u32 item1_offset, item2_offset, item1_size, item2_size;
3820 item1 = btrfs_item_nr(slot);
3821 item2 = btrfs_item_nr(slot + 1);
3822 btrfs_item_key_to_cpu(buf, &k1, slot);
3823 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3824 item1_offset = btrfs_item_offset(buf, item1);
3825 item2_offset = btrfs_item_offset(buf, item2);
3826 item1_size = btrfs_item_size(buf, item1);
3827 item2_size = btrfs_item_size(buf, item2);
3829 item1_data = malloc(item1_size);
3832 item2_data = malloc(item2_size);
3838 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3839 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3841 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3842 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3846 btrfs_set_item_offset(buf, item1, item2_offset);
3847 btrfs_set_item_offset(buf, item2, item1_offset);
3848 btrfs_set_item_size(buf, item1, item2_size);
3849 btrfs_set_item_size(buf, item2, item1_size);
3851 path->slots[0] = slot;
3852 btrfs_set_item_key_unsafe(root, path, &k2);
3853 path->slots[0] = slot + 1;
3854 btrfs_set_item_key_unsafe(root, path, &k1);
3859 static int fix_key_order(struct btrfs_trans_handle *trans,
3860 struct btrfs_root *root,
3861 struct btrfs_path *path)
3863 struct extent_buffer *buf;
3864 struct btrfs_key k1, k2;
3866 int level = path->lowest_level;
3869 buf = path->nodes[level];
3870 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3872 btrfs_node_key_to_cpu(buf, &k1, i);
3873 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3875 btrfs_item_key_to_cpu(buf, &k1, i);
3876 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3878 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3880 ret = swap_values(root, path, buf, i);
3883 btrfs_mark_buffer_dirty(buf);
3889 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3890 struct btrfs_root *root,
3891 struct btrfs_path *path,
3892 struct extent_buffer *buf, int slot)
3894 struct btrfs_key key;
3895 int nritems = btrfs_header_nritems(buf);
3897 btrfs_item_key_to_cpu(buf, &key, slot);
3899 /* These are all the keys we can deal with missing. */
3900 if (key.type != BTRFS_DIR_INDEX_KEY &&
3901 key.type != BTRFS_EXTENT_ITEM_KEY &&
3902 key.type != BTRFS_METADATA_ITEM_KEY &&
3903 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3904 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3907 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3908 (unsigned long long)key.objectid, key.type,
3909 (unsigned long long)key.offset, slot, buf->start);
3910 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3911 btrfs_item_nr_offset(slot + 1),
3912 sizeof(struct btrfs_item) *
3913 (nritems - slot - 1));
3914 btrfs_set_header_nritems(buf, nritems - 1);
3916 struct btrfs_disk_key disk_key;
3918 btrfs_item_key(buf, &disk_key, 0);
3919 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3921 btrfs_mark_buffer_dirty(buf);
3925 static int fix_item_offset(struct btrfs_trans_handle *trans,
3926 struct btrfs_root *root,
3927 struct btrfs_path *path)
3929 struct extent_buffer *buf;
3933 /* We should only get this for leaves */
3934 BUG_ON(path->lowest_level);
3935 buf = path->nodes[0];
3937 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3938 unsigned int shift = 0, offset;
3940 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3941 BTRFS_LEAF_DATA_SIZE(root)) {
3942 if (btrfs_item_end_nr(buf, i) >
3943 BTRFS_LEAF_DATA_SIZE(root)) {
3944 ret = delete_bogus_item(trans, root, path,
3948 fprintf(stderr, "item is off the end of the "
3949 "leaf, can't fix\n");
3953 shift = BTRFS_LEAF_DATA_SIZE(root) -
3954 btrfs_item_end_nr(buf, i);
3955 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
3956 btrfs_item_offset_nr(buf, i - 1)) {
3957 if (btrfs_item_end_nr(buf, i) >
3958 btrfs_item_offset_nr(buf, i - 1)) {
3959 ret = delete_bogus_item(trans, root, path,
3963 fprintf(stderr, "items overlap, can't fix\n");
3967 shift = btrfs_item_offset_nr(buf, i - 1) -
3968 btrfs_item_end_nr(buf, i);
3973 printf("Shifting item nr %d by %u bytes in block %llu\n",
3974 i, shift, (unsigned long long)buf->start);
3975 offset = btrfs_item_offset_nr(buf, i);
3976 memmove_extent_buffer(buf,
3977 btrfs_leaf_data(buf) + offset + shift,
3978 btrfs_leaf_data(buf) + offset,
3979 btrfs_item_size_nr(buf, i));
3980 btrfs_set_item_offset(buf, btrfs_item_nr(i),
3982 btrfs_mark_buffer_dirty(buf);
3986 * We may have moved things, in which case we want to exit so we don't
3987 * write those changes out. Once we have proper abort functionality in
3988 * progs this can be changed to something nicer.
3995 * Attempt to fix basic block failures. If we can't fix it for whatever reason
3996 * then just return -EIO.
3998 static int try_to_fix_bad_block(struct btrfs_trans_handle *trans,
3999 struct btrfs_root *root,
4000 struct extent_buffer *buf,
4001 enum btrfs_tree_block_status status)
4003 struct ulist *roots;
4004 struct ulist_node *node;
4005 struct btrfs_root *search_root;
4006 struct btrfs_path *path;
4007 struct ulist_iterator iter;
4008 struct btrfs_key root_key, key;
4011 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4012 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4015 path = btrfs_alloc_path();
4019 ret = btrfs_find_all_roots(trans, root->fs_info, buf->start,
4022 btrfs_free_path(path);
4026 ULIST_ITER_INIT(&iter);
4027 while ((node = ulist_next(roots, &iter))) {
4028 root_key.objectid = node->val;
4029 root_key.type = BTRFS_ROOT_ITEM_KEY;
4030 root_key.offset = (u64)-1;
4032 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4038 record_root_in_trans(trans, search_root);
4040 path->lowest_level = btrfs_header_level(buf);
4041 path->skip_check_block = 1;
4042 if (path->lowest_level)
4043 btrfs_node_key_to_cpu(buf, &key, 0);
4045 btrfs_item_key_to_cpu(buf, &key, 0);
4046 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4051 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4052 ret = fix_key_order(trans, search_root, path);
4053 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4054 ret = fix_item_offset(trans, search_root, path);
4057 btrfs_release_path(path);
4060 btrfs_free_path(path);
4064 static int check_block(struct btrfs_trans_handle *trans,
4065 struct btrfs_root *root,
4066 struct cache_tree *extent_cache,
4067 struct extent_buffer *buf, u64 flags)
4069 struct extent_record *rec;
4070 struct cache_extent *cache;
4071 struct btrfs_key key;
4072 enum btrfs_tree_block_status status;
4076 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4079 rec = container_of(cache, struct extent_record, cache);
4080 rec->generation = btrfs_header_generation(buf);
4082 level = btrfs_header_level(buf);
4083 if (btrfs_header_nritems(buf) > 0) {
4086 btrfs_item_key_to_cpu(buf, &key, 0);
4088 btrfs_node_key_to_cpu(buf, &key, 0);
4090 rec->info_objectid = key.objectid;
4092 rec->info_level = level;
4094 if (btrfs_is_leaf(buf))
4095 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4097 status = btrfs_check_node(root, &rec->parent_key, buf);
4099 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4101 status = try_to_fix_bad_block(trans, root, buf,
4103 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4105 fprintf(stderr, "bad block %llu\n",
4106 (unsigned long long)buf->start);
4109 * Signal to callers we need to start the scan over
4110 * again since we'll have cow'ed blocks.
4115 rec->content_checked = 1;
4116 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4117 rec->owner_ref_checked = 1;
4119 ret = check_owner_ref(root, rec, buf);
4121 rec->owner_ref_checked = 1;
4125 maybe_free_extent_rec(extent_cache, rec);
4129 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4130 u64 parent, u64 root)
4132 struct list_head *cur = rec->backrefs.next;
4133 struct extent_backref *node;
4134 struct tree_backref *back;
4136 while(cur != &rec->backrefs) {
4137 node = list_entry(cur, struct extent_backref, list);
4141 back = (struct tree_backref *)node;
4143 if (!node->full_backref)
4145 if (parent == back->parent)
4148 if (node->full_backref)
4150 if (back->root == root)
4157 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4158 u64 parent, u64 root)
4160 struct tree_backref *ref = malloc(sizeof(*ref));
4161 memset(&ref->node, 0, sizeof(ref->node));
4163 ref->parent = parent;
4164 ref->node.full_backref = 1;
4167 ref->node.full_backref = 0;
4169 list_add_tail(&ref->node.list, &rec->backrefs);
4174 static struct data_backref *find_data_backref(struct extent_record *rec,
4175 u64 parent, u64 root,
4176 u64 owner, u64 offset,
4178 u64 disk_bytenr, u64 bytes)
4180 struct list_head *cur = rec->backrefs.next;
4181 struct extent_backref *node;
4182 struct data_backref *back;
4184 while(cur != &rec->backrefs) {
4185 node = list_entry(cur, struct extent_backref, list);
4189 back = (struct data_backref *)node;
4191 if (!node->full_backref)
4193 if (parent == back->parent)
4196 if (node->full_backref)
4198 if (back->root == root && back->owner == owner &&
4199 back->offset == offset) {
4200 if (found_ref && node->found_ref &&
4201 (back->bytes != bytes ||
4202 back->disk_bytenr != disk_bytenr))
4211 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4212 u64 parent, u64 root,
4213 u64 owner, u64 offset,
4216 struct data_backref *ref = malloc(sizeof(*ref));
4217 memset(&ref->node, 0, sizeof(ref->node));
4218 ref->node.is_data = 1;
4221 ref->parent = parent;
4224 ref->node.full_backref = 1;
4228 ref->offset = offset;
4229 ref->node.full_backref = 0;
4231 ref->bytes = max_size;
4234 list_add_tail(&ref->node.list, &rec->backrefs);
4235 if (max_size > rec->max_size)
4236 rec->max_size = max_size;
4240 static int add_extent_rec(struct cache_tree *extent_cache,
4241 struct btrfs_key *parent_key, u64 parent_gen,
4242 u64 start, u64 nr, u64 extent_item_refs,
4243 int is_root, int inc_ref, int set_checked,
4244 int metadata, int extent_rec, u64 max_size)
4246 struct extent_record *rec;
4247 struct cache_extent *cache;
4251 cache = lookup_cache_extent(extent_cache, start, nr);
4253 rec = container_of(cache, struct extent_record, cache);
4257 rec->nr = max(nr, max_size);
4260 * We need to make sure to reset nr to whatever the extent
4261 * record says was the real size, this way we can compare it to
4265 if (start != rec->start || rec->found_rec) {
4266 struct extent_record *tmp;
4269 if (list_empty(&rec->list))
4270 list_add_tail(&rec->list,
4271 &duplicate_extents);
4274 * We have to do this song and dance in case we
4275 * find an extent record that falls inside of
4276 * our current extent record but does not have
4277 * the same objectid.
4279 tmp = malloc(sizeof(*tmp));
4283 tmp->max_size = max_size;
4286 tmp->metadata = metadata;
4287 tmp->extent_item_refs = extent_item_refs;
4288 INIT_LIST_HEAD(&tmp->list);
4289 list_add_tail(&tmp->list, &rec->dups);
4290 rec->num_duplicates++;
4297 if (extent_item_refs && !dup) {
4298 if (rec->extent_item_refs) {
4299 fprintf(stderr, "block %llu rec "
4300 "extent_item_refs %llu, passed %llu\n",
4301 (unsigned long long)start,
4302 (unsigned long long)
4303 rec->extent_item_refs,
4304 (unsigned long long)extent_item_refs);
4306 rec->extent_item_refs = extent_item_refs;
4311 rec->content_checked = 1;
4312 rec->owner_ref_checked = 1;
4316 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4318 rec->parent_generation = parent_gen;
4320 if (rec->max_size < max_size)
4321 rec->max_size = max_size;
4323 maybe_free_extent_rec(extent_cache, rec);
4326 rec = malloc(sizeof(*rec));
4328 rec->max_size = max_size;
4329 rec->nr = max(nr, max_size);
4330 rec->found_rec = !!extent_rec;
4331 rec->content_checked = 0;
4332 rec->owner_ref_checked = 0;
4333 rec->num_duplicates = 0;
4334 rec->metadata = metadata;
4335 INIT_LIST_HEAD(&rec->backrefs);
4336 INIT_LIST_HEAD(&rec->dups);
4337 INIT_LIST_HEAD(&rec->list);
4349 if (extent_item_refs)
4350 rec->extent_item_refs = extent_item_refs;
4352 rec->extent_item_refs = 0;
4355 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4357 memset(&rec->parent_key, 0, sizeof(*parent_key));
4360 rec->parent_generation = parent_gen;
4362 rec->parent_generation = 0;
4364 rec->cache.start = start;
4365 rec->cache.size = nr;
4366 ret = insert_cache_extent(extent_cache, &rec->cache);
4370 rec->content_checked = 1;
4371 rec->owner_ref_checked = 1;
4376 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4377 u64 parent, u64 root, int found_ref)
4379 struct extent_record *rec;
4380 struct tree_backref *back;
4381 struct cache_extent *cache;
4383 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4385 add_extent_rec(extent_cache, NULL, 0, bytenr,
4386 1, 0, 0, 0, 0, 1, 0, 0);
4387 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4392 rec = container_of(cache, struct extent_record, cache);
4393 if (rec->start != bytenr) {
4397 back = find_tree_backref(rec, parent, root);
4399 back = alloc_tree_backref(rec, parent, root);
4402 if (back->node.found_ref) {
4403 fprintf(stderr, "Extent back ref already exists "
4404 "for %llu parent %llu root %llu \n",
4405 (unsigned long long)bytenr,
4406 (unsigned long long)parent,
4407 (unsigned long long)root);
4409 back->node.found_ref = 1;
4411 if (back->node.found_extent_tree) {
4412 fprintf(stderr, "Extent back ref already exists "
4413 "for %llu parent %llu root %llu \n",
4414 (unsigned long long)bytenr,
4415 (unsigned long long)parent,
4416 (unsigned long long)root);
4418 back->node.found_extent_tree = 1;
4420 maybe_free_extent_rec(extent_cache, rec);
4424 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4425 u64 parent, u64 root, u64 owner, u64 offset,
4426 u32 num_refs, int found_ref, u64 max_size)
4428 struct extent_record *rec;
4429 struct data_backref *back;
4430 struct cache_extent *cache;
4432 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4434 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4436 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4441 rec = container_of(cache, struct extent_record, cache);
4442 if (rec->max_size < max_size)
4443 rec->max_size = max_size;
4446 * If found_ref is set then max_size is the real size and must match the
4447 * existing refs. So if we have already found a ref then we need to
4448 * make sure that this ref matches the existing one, otherwise we need
4449 * to add a new backref so we can notice that the backrefs don't match
4450 * and we need to figure out who is telling the truth. This is to
4451 * account for that awful fsync bug I introduced where we'd end up with
4452 * a btrfs_file_extent_item that would have its length include multiple
4453 * prealloc extents or point inside of a prealloc extent.
4455 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4458 back = alloc_data_backref(rec, parent, root, owner, offset,
4462 BUG_ON(num_refs != 1);
4463 if (back->node.found_ref)
4464 BUG_ON(back->bytes != max_size);
4465 back->node.found_ref = 1;
4466 back->found_ref += 1;
4467 back->bytes = max_size;
4468 back->disk_bytenr = bytenr;
4470 rec->content_checked = 1;
4471 rec->owner_ref_checked = 1;
4473 if (back->node.found_extent_tree) {
4474 fprintf(stderr, "Extent back ref already exists "
4475 "for %llu parent %llu root %llu "
4476 "owner %llu offset %llu num_refs %lu\n",
4477 (unsigned long long)bytenr,
4478 (unsigned long long)parent,
4479 (unsigned long long)root,
4480 (unsigned long long)owner,
4481 (unsigned long long)offset,
4482 (unsigned long)num_refs);
4484 back->num_refs = num_refs;
4485 back->node.found_extent_tree = 1;
4487 maybe_free_extent_rec(extent_cache, rec);
4491 static int add_pending(struct cache_tree *pending,
4492 struct cache_tree *seen, u64 bytenr, u32 size)
4495 ret = add_cache_extent(seen, bytenr, size);
4498 add_cache_extent(pending, bytenr, size);
4502 static int pick_next_pending(struct cache_tree *pending,
4503 struct cache_tree *reada,
4504 struct cache_tree *nodes,
4505 u64 last, struct block_info *bits, int bits_nr,
4508 unsigned long node_start = last;
4509 struct cache_extent *cache;
4512 cache = search_cache_extent(reada, 0);
4514 bits[0].start = cache->start;
4515 bits[0].size = cache->size;
4520 if (node_start > 32768)
4521 node_start -= 32768;
4523 cache = search_cache_extent(nodes, node_start);
4525 cache = search_cache_extent(nodes, 0);
4528 cache = search_cache_extent(pending, 0);
4533 bits[ret].start = cache->start;
4534 bits[ret].size = cache->size;
4535 cache = next_cache_extent(cache);
4537 } while (cache && ret < bits_nr);
4543 bits[ret].start = cache->start;
4544 bits[ret].size = cache->size;
4545 cache = next_cache_extent(cache);
4547 } while (cache && ret < bits_nr);
4549 if (bits_nr - ret > 8) {
4550 u64 lookup = bits[0].start + bits[0].size;
4551 struct cache_extent *next;
4552 next = search_cache_extent(pending, lookup);
4554 if (next->start - lookup > 32768)
4556 bits[ret].start = next->start;
4557 bits[ret].size = next->size;
4558 lookup = next->start + next->size;
4562 next = next_cache_extent(next);
4570 static void free_chunk_record(struct cache_extent *cache)
4572 struct chunk_record *rec;
4574 rec = container_of(cache, struct chunk_record, cache);
4575 list_del_init(&rec->list);
4576 list_del_init(&rec->dextents);
4580 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4582 cache_tree_free_extents(chunk_cache, free_chunk_record);
4585 static void free_device_record(struct rb_node *node)
4587 struct device_record *rec;
4589 rec = container_of(node, struct device_record, node);
4593 FREE_RB_BASED_TREE(device_cache, free_device_record);
4595 int insert_block_group_record(struct block_group_tree *tree,
4596 struct block_group_record *bg_rec)
4600 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4604 list_add_tail(&bg_rec->list, &tree->block_groups);
4608 static void free_block_group_record(struct cache_extent *cache)
4610 struct block_group_record *rec;
4612 rec = container_of(cache, struct block_group_record, cache);
4613 list_del_init(&rec->list);
4617 void free_block_group_tree(struct block_group_tree *tree)
4619 cache_tree_free_extents(&tree->tree, free_block_group_record);
4622 int insert_device_extent_record(struct device_extent_tree *tree,
4623 struct device_extent_record *de_rec)
4628 * Device extent is a bit different from the other extents, because
4629 * the extents which belong to the different devices may have the
4630 * same start and size, so we need use the special extent cache
4631 * search/insert functions.
4633 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4637 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4638 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4642 static void free_device_extent_record(struct cache_extent *cache)
4644 struct device_extent_record *rec;
4646 rec = container_of(cache, struct device_extent_record, cache);
4647 if (!list_empty(&rec->chunk_list))
4648 list_del_init(&rec->chunk_list);
4649 if (!list_empty(&rec->device_list))
4650 list_del_init(&rec->device_list);
4654 void free_device_extent_tree(struct device_extent_tree *tree)
4656 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4659 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4660 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4661 struct extent_buffer *leaf, int slot)
4663 struct btrfs_extent_ref_v0 *ref0;
4664 struct btrfs_key key;
4666 btrfs_item_key_to_cpu(leaf, &key, slot);
4667 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4668 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4669 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4671 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4672 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4678 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4679 struct btrfs_key *key,
4682 struct btrfs_chunk *ptr;
4683 struct chunk_record *rec;
4686 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4687 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4689 rec = malloc(btrfs_chunk_record_size(num_stripes));
4691 fprintf(stderr, "memory allocation failed\n");
4695 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4697 INIT_LIST_HEAD(&rec->list);
4698 INIT_LIST_HEAD(&rec->dextents);
4701 rec->cache.start = key->offset;
4702 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4704 rec->generation = btrfs_header_generation(leaf);
4706 rec->objectid = key->objectid;
4707 rec->type = key->type;
4708 rec->offset = key->offset;
4710 rec->length = rec->cache.size;
4711 rec->owner = btrfs_chunk_owner(leaf, ptr);
4712 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4713 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4714 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4715 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4716 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4717 rec->num_stripes = num_stripes;
4718 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4720 for (i = 0; i < rec->num_stripes; ++i) {
4721 rec->stripes[i].devid =
4722 btrfs_stripe_devid_nr(leaf, ptr, i);
4723 rec->stripes[i].offset =
4724 btrfs_stripe_offset_nr(leaf, ptr, i);
4725 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4726 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4733 static int process_chunk_item(struct cache_tree *chunk_cache,
4734 struct btrfs_key *key, struct extent_buffer *eb,
4737 struct chunk_record *rec;
4740 rec = btrfs_new_chunk_record(eb, key, slot);
4741 ret = insert_cache_extent(chunk_cache, &rec->cache);
4743 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4744 rec->offset, rec->length);
4751 static int process_device_item(struct rb_root *dev_cache,
4752 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4754 struct btrfs_dev_item *ptr;
4755 struct device_record *rec;
4758 ptr = btrfs_item_ptr(eb,
4759 slot, struct btrfs_dev_item);
4761 rec = malloc(sizeof(*rec));
4763 fprintf(stderr, "memory allocation failed\n");
4767 rec->devid = key->offset;
4768 rec->generation = btrfs_header_generation(eb);
4770 rec->objectid = key->objectid;
4771 rec->type = key->type;
4772 rec->offset = key->offset;
4774 rec->devid = btrfs_device_id(eb, ptr);
4775 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4776 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4778 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4780 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4787 struct block_group_record *
4788 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4791 struct btrfs_block_group_item *ptr;
4792 struct block_group_record *rec;
4794 rec = malloc(sizeof(*rec));
4796 fprintf(stderr, "memory allocation failed\n");
4799 memset(rec, 0, sizeof(*rec));
4801 rec->cache.start = key->objectid;
4802 rec->cache.size = key->offset;
4804 rec->generation = btrfs_header_generation(leaf);
4806 rec->objectid = key->objectid;
4807 rec->type = key->type;
4808 rec->offset = key->offset;
4810 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4811 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4813 INIT_LIST_HEAD(&rec->list);
4818 static int process_block_group_item(struct block_group_tree *block_group_cache,
4819 struct btrfs_key *key,
4820 struct extent_buffer *eb, int slot)
4822 struct block_group_record *rec;
4825 rec = btrfs_new_block_group_record(eb, key, slot);
4826 ret = insert_block_group_record(block_group_cache, rec);
4828 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4829 rec->objectid, rec->offset);
4836 struct device_extent_record *
4837 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4838 struct btrfs_key *key, int slot)
4840 struct device_extent_record *rec;
4841 struct btrfs_dev_extent *ptr;
4843 rec = malloc(sizeof(*rec));
4845 fprintf(stderr, "memory allocation failed\n");
4848 memset(rec, 0, sizeof(*rec));
4850 rec->cache.objectid = key->objectid;
4851 rec->cache.start = key->offset;
4853 rec->generation = btrfs_header_generation(leaf);
4855 rec->objectid = key->objectid;
4856 rec->type = key->type;
4857 rec->offset = key->offset;
4859 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4860 rec->chunk_objecteid =
4861 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4863 btrfs_dev_extent_chunk_offset(leaf, ptr);
4864 rec->length = btrfs_dev_extent_length(leaf, ptr);
4865 rec->cache.size = rec->length;
4867 INIT_LIST_HEAD(&rec->chunk_list);
4868 INIT_LIST_HEAD(&rec->device_list);
4874 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4875 struct btrfs_key *key, struct extent_buffer *eb,
4878 struct device_extent_record *rec;
4881 rec = btrfs_new_device_extent_record(eb, key, slot);
4882 ret = insert_device_extent_record(dev_extent_cache, rec);
4885 "Device extent[%llu, %llu, %llu] existed.\n",
4886 rec->objectid, rec->offset, rec->length);
4893 static int process_extent_item(struct btrfs_root *root,
4894 struct cache_tree *extent_cache,
4895 struct extent_buffer *eb, int slot)
4897 struct btrfs_extent_item *ei;
4898 struct btrfs_extent_inline_ref *iref;
4899 struct btrfs_extent_data_ref *dref;
4900 struct btrfs_shared_data_ref *sref;
4901 struct btrfs_key key;
4905 u32 item_size = btrfs_item_size_nr(eb, slot);
4911 btrfs_item_key_to_cpu(eb, &key, slot);
4913 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4915 num_bytes = root->leafsize;
4917 num_bytes = key.offset;
4920 if (item_size < sizeof(*ei)) {
4921 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4922 struct btrfs_extent_item_v0 *ei0;
4923 BUG_ON(item_size != sizeof(*ei0));
4924 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4925 refs = btrfs_extent_refs_v0(eb, ei0);
4929 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4930 num_bytes, refs, 0, 0, 0, metadata, 1,
4934 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4935 refs = btrfs_extent_refs(eb, ei);
4937 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
4938 refs, 0, 0, 0, metadata, 1, num_bytes);
4940 ptr = (unsigned long)(ei + 1);
4941 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
4942 key.type == BTRFS_EXTENT_ITEM_KEY)
4943 ptr += sizeof(struct btrfs_tree_block_info);
4945 end = (unsigned long)ei + item_size;
4947 iref = (struct btrfs_extent_inline_ref *)ptr;
4948 type = btrfs_extent_inline_ref_type(eb, iref);
4949 offset = btrfs_extent_inline_ref_offset(eb, iref);
4951 case BTRFS_TREE_BLOCK_REF_KEY:
4952 add_tree_backref(extent_cache, key.objectid,
4955 case BTRFS_SHARED_BLOCK_REF_KEY:
4956 add_tree_backref(extent_cache, key.objectid,
4959 case BTRFS_EXTENT_DATA_REF_KEY:
4960 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
4961 add_data_backref(extent_cache, key.objectid, 0,
4962 btrfs_extent_data_ref_root(eb, dref),
4963 btrfs_extent_data_ref_objectid(eb,
4965 btrfs_extent_data_ref_offset(eb, dref),
4966 btrfs_extent_data_ref_count(eb, dref),
4969 case BTRFS_SHARED_DATA_REF_KEY:
4970 sref = (struct btrfs_shared_data_ref *)(iref + 1);
4971 add_data_backref(extent_cache, key.objectid, offset,
4973 btrfs_shared_data_ref_count(eb, sref),
4977 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
4978 key.objectid, key.type, num_bytes);
4981 ptr += btrfs_extent_inline_ref_size(type);
4988 static int check_cache_range(struct btrfs_root *root,
4989 struct btrfs_block_group_cache *cache,
4990 u64 offset, u64 bytes)
4992 struct btrfs_free_space *entry;
4998 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
4999 bytenr = btrfs_sb_offset(i);
5000 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5001 cache->key.objectid, bytenr, 0,
5002 &logical, &nr, &stripe_len);
5007 if (logical[nr] + stripe_len <= offset)
5009 if (offset + bytes <= logical[nr])
5011 if (logical[nr] == offset) {
5012 if (stripe_len >= bytes) {
5016 bytes -= stripe_len;
5017 offset += stripe_len;
5018 } else if (logical[nr] < offset) {
5019 if (logical[nr] + stripe_len >=
5024 bytes = (offset + bytes) -
5025 (logical[nr] + stripe_len);
5026 offset = logical[nr] + stripe_len;
5029 * Could be tricky, the super may land in the
5030 * middle of the area we're checking. First
5031 * check the easiest case, it's at the end.
5033 if (logical[nr] + stripe_len >=
5035 bytes = logical[nr] - offset;
5039 /* Check the left side */
5040 ret = check_cache_range(root, cache,
5042 logical[nr] - offset);
5048 /* Now we continue with the right side */
5049 bytes = (offset + bytes) -
5050 (logical[nr] + stripe_len);
5051 offset = logical[nr] + stripe_len;
5058 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5060 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5061 offset, offset+bytes);
5065 if (entry->offset != offset) {
5066 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5071 if (entry->bytes != bytes) {
5072 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5073 bytes, entry->bytes, offset);
5077 unlink_free_space(cache->free_space_ctl, entry);
5082 static int verify_space_cache(struct btrfs_root *root,
5083 struct btrfs_block_group_cache *cache)
5085 struct btrfs_path *path;
5086 struct extent_buffer *leaf;
5087 struct btrfs_key key;
5091 path = btrfs_alloc_path();
5095 root = root->fs_info->extent_root;
5097 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5099 key.objectid = last;
5101 key.type = BTRFS_EXTENT_ITEM_KEY;
5103 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5108 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5109 ret = btrfs_next_leaf(root, path);
5117 leaf = path->nodes[0];
5118 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5119 if (key.objectid >= cache->key.offset + cache->key.objectid)
5121 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5122 key.type != BTRFS_METADATA_ITEM_KEY) {
5127 if (last == key.objectid) {
5128 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5129 last = key.objectid + key.offset;
5131 last = key.objectid + root->leafsize;
5136 ret = check_cache_range(root, cache, last,
5137 key.objectid - last);
5140 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5141 last = key.objectid + key.offset;
5143 last = key.objectid + root->leafsize;
5147 if (last < cache->key.objectid + cache->key.offset)
5148 ret = check_cache_range(root, cache, last,
5149 cache->key.objectid +
5150 cache->key.offset - last);
5153 btrfs_free_path(path);
5156 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5157 fprintf(stderr, "There are still entries left in the space "
5165 static int check_space_cache(struct btrfs_root *root)
5167 struct btrfs_block_group_cache *cache;
5168 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5172 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5173 btrfs_super_generation(root->fs_info->super_copy) !=
5174 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5175 printf("cache and super generation don't match, space cache "
5176 "will be invalidated\n");
5181 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5185 start = cache->key.objectid + cache->key.offset;
5186 if (!cache->free_space_ctl) {
5187 if (btrfs_init_free_space_ctl(cache,
5188 root->sectorsize)) {
5193 btrfs_remove_free_space_cache(cache);
5196 ret = load_free_space_cache(root->fs_info, cache);
5200 ret = verify_space_cache(root, cache);
5202 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5203 cache->key.objectid);
5208 return error ? -EINVAL : 0;
5211 static int read_extent_data(struct btrfs_root *root, char *data,
5212 u64 logical, u64 *len, int mirror)
5215 struct btrfs_multi_bio *multi = NULL;
5216 struct btrfs_fs_info *info = root->fs_info;
5217 struct btrfs_device *device;
5221 ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
5222 &multi, mirror, NULL);
5224 fprintf(stderr, "Couldn't map the block %llu\n",
5228 device = multi->stripes[0].dev;
5230 if (device->fd == 0)
5235 ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
5245 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5246 u64 num_bytes, unsigned long leaf_offset,
5247 struct extent_buffer *eb) {
5250 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5252 unsigned long csum_offset;
5256 u64 data_checked = 0;
5262 if (num_bytes % root->sectorsize)
5265 data = malloc(num_bytes);
5269 while (offset < num_bytes) {
5272 read_len = num_bytes - offset;
5273 /* read as much space once a time */
5274 ret = read_extent_data(root, data + offset,
5275 bytenr + offset, &read_len, mirror);
5279 /* verify every 4k data's checksum */
5280 while (data_checked < read_len) {
5282 tmp = offset + data_checked;
5284 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5285 csum, root->sectorsize);
5286 btrfs_csum_final(csum, (char *)&csum);
5288 csum_offset = leaf_offset +
5289 tmp / root->sectorsize * csum_size;
5290 read_extent_buffer(eb, (char *)&csum_expected,
5291 csum_offset, csum_size);
5292 /* try another mirror */
5293 if (csum != csum_expected) {
5294 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5295 mirror, bytenr + tmp,
5296 csum, csum_expected);
5297 num_copies = btrfs_num_copies(
5298 &root->fs_info->mapping_tree,
5300 if (mirror < num_copies - 1) {
5305 data_checked += root->sectorsize;
5314 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5317 struct btrfs_path *path;
5318 struct extent_buffer *leaf;
5319 struct btrfs_key key;
5322 path = btrfs_alloc_path();
5324 fprintf(stderr, "Error allocing path\n");
5328 key.objectid = bytenr;
5329 key.type = BTRFS_EXTENT_ITEM_KEY;
5330 key.offset = (u64)-1;
5333 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5336 fprintf(stderr, "Error looking up extent record %d\n", ret);
5337 btrfs_free_path(path);
5340 if (path->slots[0] > 0) {
5343 ret = btrfs_prev_leaf(root, path);
5346 } else if (ret > 0) {
5353 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5356 * Block group items come before extent items if they have the same
5357 * bytenr, so walk back one more just in case. Dear future traveler,
5358 * first congrats on mastering time travel. Now if it's not too much
5359 * trouble could you go back to 2006 and tell Chris to make the
5360 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5361 * EXTENT_ITEM_KEY please?
5363 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5364 if (path->slots[0] > 0) {
5367 ret = btrfs_prev_leaf(root, path);
5370 } else if (ret > 0) {
5375 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5379 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5380 ret = btrfs_next_leaf(root, path);
5382 fprintf(stderr, "Error going to next leaf "
5384 btrfs_free_path(path);
5390 leaf = path->nodes[0];
5391 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5392 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5396 if (key.objectid + key.offset < bytenr) {
5400 if (key.objectid > bytenr + num_bytes)
5403 if (key.objectid == bytenr) {
5404 if (key.offset >= num_bytes) {
5408 num_bytes -= key.offset;
5409 bytenr += key.offset;
5410 } else if (key.objectid < bytenr) {
5411 if (key.objectid + key.offset >= bytenr + num_bytes) {
5415 num_bytes = (bytenr + num_bytes) -
5416 (key.objectid + key.offset);
5417 bytenr = key.objectid + key.offset;
5419 if (key.objectid + key.offset < bytenr + num_bytes) {
5420 u64 new_start = key.objectid + key.offset;
5421 u64 new_bytes = bytenr + num_bytes - new_start;
5424 * Weird case, the extent is in the middle of
5425 * our range, we'll have to search one side
5426 * and then the other. Not sure if this happens
5427 * in real life, but no harm in coding it up
5428 * anyway just in case.
5430 btrfs_release_path(path);
5431 ret = check_extent_exists(root, new_start,
5434 fprintf(stderr, "Right section didn't "
5438 num_bytes = key.objectid - bytenr;
5441 num_bytes = key.objectid - bytenr;
5448 if (num_bytes && !ret) {
5449 fprintf(stderr, "There are no extents for csum range "
5450 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5454 btrfs_free_path(path);
5458 static int check_csums(struct btrfs_root *root)
5460 struct btrfs_path *path;
5461 struct extent_buffer *leaf;
5462 struct btrfs_key key;
5463 u64 offset = 0, num_bytes = 0;
5464 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5468 unsigned long leaf_offset;
5470 root = root->fs_info->csum_root;
5471 if (!extent_buffer_uptodate(root->node)) {
5472 fprintf(stderr, "No valid csum tree found\n");
5476 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5477 key.type = BTRFS_EXTENT_CSUM_KEY;
5480 path = btrfs_alloc_path();
5484 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5486 fprintf(stderr, "Error searching csum tree %d\n", ret);
5487 btrfs_free_path(path);
5491 if (ret > 0 && path->slots[0])
5496 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5497 ret = btrfs_next_leaf(root, path);
5499 fprintf(stderr, "Error going to next leaf "
5506 leaf = path->nodes[0];
5508 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5509 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5514 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5515 csum_size) * root->sectorsize;
5516 if (!check_data_csum)
5517 goto skip_csum_check;
5518 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5519 ret = check_extent_csums(root, key.offset, data_len,
5525 offset = key.offset;
5526 } else if (key.offset != offset + num_bytes) {
5527 ret = check_extent_exists(root, offset, num_bytes);
5529 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5530 "there is no extent record\n",
5531 offset, offset+num_bytes);
5534 offset = key.offset;
5537 num_bytes += data_len;
5541 btrfs_free_path(path);
5545 static int is_dropped_key(struct btrfs_key *key,
5546 struct btrfs_key *drop_key) {
5547 if (key->objectid < drop_key->objectid)
5549 else if (key->objectid == drop_key->objectid) {
5550 if (key->type < drop_key->type)
5552 else if (key->type == drop_key->type) {
5553 if (key->offset < drop_key->offset)
5560 static int calc_extent_flag(struct btrfs_root *root,
5561 struct cache_tree *extent_cache,
5562 struct extent_buffer *buf,
5563 struct root_item_record *ri,
5567 int nritems = btrfs_header_nritems(buf);
5568 struct btrfs_key key;
5569 struct extent_record *rec;
5570 struct cache_extent *cache;
5571 struct data_backref *dback;
5572 struct tree_backref *tback;
5573 struct extent_buffer *new_buf;
5583 * Except file/reloc tree, we can not have
5586 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5591 if (buf->start == ri->bytenr)
5593 if (btrfs_is_leaf(buf)) {
5595 * we are searching from original root, world
5596 * peace is achieved, we use normal backref.
5598 owner = btrfs_header_owner(buf);
5599 if (owner == ri->objectid)
5602 * we check every eb here, and if any of
5603 * eb dosen't have original root refers
5604 * to this eb, we set full backref flag for
5605 * this extent, otherwise normal backref.
5607 for (i = 0; i < nritems; i++) {
5608 struct btrfs_file_extent_item *fi;
5609 btrfs_item_key_to_cpu(buf, &key, i);
5611 if (key.type != BTRFS_EXTENT_DATA_KEY)
5613 fi = btrfs_item_ptr(buf, i,
5614 struct btrfs_file_extent_item);
5615 if (btrfs_file_extent_type(buf, fi) ==
5616 BTRFS_FILE_EXTENT_INLINE)
5618 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5620 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
5621 cache = lookup_cache_extent(extent_cache, bytenr, 1);
5624 offset = btrfs_file_extent_offset(buf, fi);
5625 rec = container_of(cache, struct extent_record, cache);
5626 dback = find_data_backref(rec, 0, ri->objectid, owner,
5627 key.offset - offset, 1, bytenr, bytenr);
5633 level = btrfs_header_level(buf);
5634 for (i = 0; i < nritems; i++) {
5635 ptr = btrfs_node_blockptr(buf, i);
5636 size = btrfs_level_size(root, level);
5638 new_buf = read_tree_block(root, ptr, size, 0);
5639 if (!extent_buffer_uptodate(new_buf)) {
5640 free_extent_buffer(new_buf);
5645 * we are searching from origin root, world
5646 * peace is achieved, we use normal backref.
5648 owner = btrfs_header_owner(new_buf);
5649 free_extent_buffer(new_buf);
5650 if (owner == ri->objectid)
5653 cache = lookup_cache_extent(extent_cache, ptr, size);
5656 rec = container_of(cache, struct extent_record, cache);
5657 tback = find_tree_backref(rec, 0, owner);
5665 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5666 /* we have added this extent before */
5668 rec = container_of(cache, struct extent_record, cache);
5669 rec->flag_block_full_backref = 0;
5672 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5673 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5674 /* we have added this extent before */
5676 rec = container_of(cache, struct extent_record, cache);
5677 rec->flag_block_full_backref = 1;
5681 static int run_next_block(struct btrfs_trans_handle *trans,
5682 struct btrfs_root *root,
5683 struct block_info *bits,
5686 struct cache_tree *pending,
5687 struct cache_tree *seen,
5688 struct cache_tree *reada,
5689 struct cache_tree *nodes,
5690 struct cache_tree *extent_cache,
5691 struct cache_tree *chunk_cache,
5692 struct rb_root *dev_cache,
5693 struct block_group_tree *block_group_cache,
5694 struct device_extent_tree *dev_extent_cache,
5695 struct root_item_record *ri)
5697 struct extent_buffer *buf;
5698 struct extent_record *rec = NULL;
5709 struct btrfs_key key;
5710 struct cache_extent *cache;
5713 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5714 bits_nr, &reada_bits);
5719 for(i = 0; i < nritems; i++) {
5720 ret = add_cache_extent(reada, bits[i].start,
5725 /* fixme, get the parent transid */
5726 readahead_tree_block(root, bits[i].start,
5730 *last = bits[0].start;
5731 bytenr = bits[0].start;
5732 size = bits[0].size;
5734 cache = lookup_cache_extent(pending, bytenr, size);
5736 remove_cache_extent(pending, cache);
5739 cache = lookup_cache_extent(reada, bytenr, size);
5741 remove_cache_extent(reada, cache);
5744 cache = lookup_cache_extent(nodes, bytenr, size);
5746 remove_cache_extent(nodes, cache);
5749 cache = lookup_cache_extent(extent_cache, bytenr, size);
5751 rec = container_of(cache, struct extent_record, cache);
5752 gen = rec->parent_generation;
5755 /* fixme, get the real parent transid */
5756 buf = read_tree_block(root, bytenr, size, gen);
5757 if (!extent_buffer_uptodate(buf)) {
5758 record_bad_block_io(root->fs_info,
5759 extent_cache, bytenr, size);
5763 nritems = btrfs_header_nritems(buf);
5766 * FIXME, this only works only if we don't have any full
5770 if (!init_extent_tree) {
5771 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5772 btrfs_header_level(buf), 1, NULL,
5775 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5777 fprintf(stderr, "Couldn't calc extent flags\n");
5778 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5783 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5785 fprintf(stderr, "Couldn't calc extent flags\n");
5786 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5790 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5792 rec->flag_block_full_backref = 1;
5797 owner = btrfs_header_owner(buf);
5800 ret = check_block(trans, root, extent_cache, buf, flags);
5804 if (btrfs_is_leaf(buf)) {
5805 btree_space_waste += btrfs_leaf_free_space(root, buf);
5806 for (i = 0; i < nritems; i++) {
5807 struct btrfs_file_extent_item *fi;
5808 btrfs_item_key_to_cpu(buf, &key, i);
5809 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5810 process_extent_item(root, extent_cache, buf,
5814 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5815 process_extent_item(root, extent_cache, buf,
5819 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5821 btrfs_item_size_nr(buf, i);
5824 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5825 process_chunk_item(chunk_cache, &key, buf, i);
5828 if (key.type == BTRFS_DEV_ITEM_KEY) {
5829 process_device_item(dev_cache, &key, buf, i);
5832 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5833 process_block_group_item(block_group_cache,
5837 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5838 process_device_extent_item(dev_extent_cache,
5843 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5844 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5845 process_extent_ref_v0(extent_cache, buf, i);
5852 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5853 add_tree_backref(extent_cache, key.objectid, 0,
5857 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5858 add_tree_backref(extent_cache, key.objectid,
5862 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5863 struct btrfs_extent_data_ref *ref;
5864 ref = btrfs_item_ptr(buf, i,
5865 struct btrfs_extent_data_ref);
5866 add_data_backref(extent_cache,
5868 btrfs_extent_data_ref_root(buf, ref),
5869 btrfs_extent_data_ref_objectid(buf,
5871 btrfs_extent_data_ref_offset(buf, ref),
5872 btrfs_extent_data_ref_count(buf, ref),
5873 0, root->sectorsize);
5876 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5877 struct btrfs_shared_data_ref *ref;
5878 ref = btrfs_item_ptr(buf, i,
5879 struct btrfs_shared_data_ref);
5880 add_data_backref(extent_cache,
5881 key.objectid, key.offset, 0, 0, 0,
5882 btrfs_shared_data_ref_count(buf, ref),
5883 0, root->sectorsize);
5886 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5887 struct bad_item *bad;
5889 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5893 bad = malloc(sizeof(struct bad_item));
5896 INIT_LIST_HEAD(&bad->list);
5897 memcpy(&bad->key, &key,
5898 sizeof(struct btrfs_key));
5899 bad->root_id = owner;
5900 list_add_tail(&bad->list, &delete_items);
5903 if (key.type != BTRFS_EXTENT_DATA_KEY)
5905 fi = btrfs_item_ptr(buf, i,
5906 struct btrfs_file_extent_item);
5907 if (btrfs_file_extent_type(buf, fi) ==
5908 BTRFS_FILE_EXTENT_INLINE)
5910 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5913 data_bytes_allocated +=
5914 btrfs_file_extent_disk_num_bytes(buf, fi);
5915 if (data_bytes_allocated < root->sectorsize) {
5918 data_bytes_referenced +=
5919 btrfs_file_extent_num_bytes(buf, fi);
5920 add_data_backref(extent_cache,
5921 btrfs_file_extent_disk_bytenr(buf, fi),
5922 parent, owner, key.objectid, key.offset -
5923 btrfs_file_extent_offset(buf, fi), 1, 1,
5924 btrfs_file_extent_disk_num_bytes(buf, fi));
5928 struct btrfs_key first_key;
5930 first_key.objectid = 0;
5933 btrfs_item_key_to_cpu(buf, &first_key, 0);
5934 level = btrfs_header_level(buf);
5935 for (i = 0; i < nritems; i++) {
5936 ptr = btrfs_node_blockptr(buf, i);
5937 size = btrfs_level_size(root, level - 1);
5938 btrfs_node_key_to_cpu(buf, &key, i);
5940 if ((level == ri->drop_level)
5941 && is_dropped_key(&key, &ri->drop_key)) {
5945 ret = add_extent_rec(extent_cache, &key,
5946 btrfs_node_ptr_generation(buf, i),
5947 ptr, size, 0, 0, 1, 0, 1, 0,
5951 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5954 add_pending(nodes, seen, ptr, size);
5956 add_pending(pending, seen, ptr, size);
5959 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5960 nritems) * sizeof(struct btrfs_key_ptr);
5962 total_btree_bytes += buf->len;
5963 if (fs_root_objectid(btrfs_header_owner(buf)))
5964 total_fs_tree_bytes += buf->len;
5965 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5966 total_extent_tree_bytes += buf->len;
5967 if (!found_old_backref &&
5968 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5969 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5970 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5971 found_old_backref = 1;
5973 free_extent_buffer(buf);
5977 static int add_root_to_pending(struct extent_buffer *buf,
5978 struct cache_tree *extent_cache,
5979 struct cache_tree *pending,
5980 struct cache_tree *seen,
5981 struct cache_tree *nodes,
5984 if (btrfs_header_level(buf) > 0)
5985 add_pending(nodes, seen, buf->start, buf->len);
5987 add_pending(pending, seen, buf->start, buf->len);
5988 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5989 0, 1, 1, 0, 1, 0, buf->len);
5991 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5992 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5993 add_tree_backref(extent_cache, buf->start, buf->start,
5996 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
6000 /* as we fix the tree, we might be deleting blocks that
6001 * we're tracking for repair. This hook makes sure we
6002 * remove any backrefs for blocks as we are fixing them.
6004 static int free_extent_hook(struct btrfs_trans_handle *trans,
6005 struct btrfs_root *root,
6006 u64 bytenr, u64 num_bytes, u64 parent,
6007 u64 root_objectid, u64 owner, u64 offset,
6010 struct extent_record *rec;
6011 struct cache_extent *cache;
6013 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6015 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6016 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6020 rec = container_of(cache, struct extent_record, cache);
6022 struct data_backref *back;
6023 back = find_data_backref(rec, parent, root_objectid, owner,
6024 offset, 1, bytenr, num_bytes);
6027 if (back->node.found_ref) {
6028 back->found_ref -= refs_to_drop;
6030 rec->refs -= refs_to_drop;
6032 if (back->node.found_extent_tree) {
6033 back->num_refs -= refs_to_drop;
6034 if (rec->extent_item_refs)
6035 rec->extent_item_refs -= refs_to_drop;
6037 if (back->found_ref == 0)
6038 back->node.found_ref = 0;
6039 if (back->num_refs == 0)
6040 back->node.found_extent_tree = 0;
6042 if (!back->node.found_extent_tree && back->node.found_ref) {
6043 list_del(&back->node.list);
6047 struct tree_backref *back;
6048 back = find_tree_backref(rec, parent, root_objectid);
6051 if (back->node.found_ref) {
6054 back->node.found_ref = 0;
6056 if (back->node.found_extent_tree) {
6057 if (rec->extent_item_refs)
6058 rec->extent_item_refs--;
6059 back->node.found_extent_tree = 0;
6061 if (!back->node.found_extent_tree && back->node.found_ref) {
6062 list_del(&back->node.list);
6066 maybe_free_extent_rec(extent_cache, rec);
6071 static int delete_extent_records(struct btrfs_trans_handle *trans,
6072 struct btrfs_root *root,
6073 struct btrfs_path *path,
6074 u64 bytenr, u64 new_len)
6076 struct btrfs_key key;
6077 struct btrfs_key found_key;
6078 struct extent_buffer *leaf;
6083 key.objectid = bytenr;
6085 key.offset = (u64)-1;
6088 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6095 if (path->slots[0] == 0)
6101 leaf = path->nodes[0];
6102 slot = path->slots[0];
6104 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6105 if (found_key.objectid != bytenr)
6108 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6109 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6110 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6111 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6112 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6113 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6114 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6115 btrfs_release_path(path);
6116 if (found_key.type == 0) {
6117 if (found_key.offset == 0)
6119 key.offset = found_key.offset - 1;
6120 key.type = found_key.type;
6122 key.type = found_key.type - 1;
6123 key.offset = (u64)-1;
6127 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6128 found_key.objectid, found_key.type, found_key.offset);
6130 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6133 btrfs_release_path(path);
6135 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6136 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6137 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6138 found_key.offset : root->leafsize;
6140 ret = btrfs_update_block_group(trans, root, bytenr,
6147 btrfs_release_path(path);
6152 * for a single backref, this will allocate a new extent
6153 * and add the backref to it.
6155 static int record_extent(struct btrfs_trans_handle *trans,
6156 struct btrfs_fs_info *info,
6157 struct btrfs_path *path,
6158 struct extent_record *rec,
6159 struct extent_backref *back,
6160 int allocated, u64 flags)
6163 struct btrfs_root *extent_root = info->extent_root;
6164 struct extent_buffer *leaf;
6165 struct btrfs_key ins_key;
6166 struct btrfs_extent_item *ei;
6167 struct tree_backref *tback;
6168 struct data_backref *dback;
6169 struct btrfs_tree_block_info *bi;
6172 rec->max_size = max_t(u64, rec->max_size,
6173 info->extent_root->leafsize);
6176 u32 item_size = sizeof(*ei);
6179 item_size += sizeof(*bi);
6181 ins_key.objectid = rec->start;
6182 ins_key.offset = rec->max_size;
6183 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6185 ret = btrfs_insert_empty_item(trans, extent_root, path,
6186 &ins_key, item_size);
6190 leaf = path->nodes[0];
6191 ei = btrfs_item_ptr(leaf, path->slots[0],
6192 struct btrfs_extent_item);
6194 btrfs_set_extent_refs(leaf, ei, 0);
6195 btrfs_set_extent_generation(leaf, ei, rec->generation);
6197 if (back->is_data) {
6198 btrfs_set_extent_flags(leaf, ei,
6199 BTRFS_EXTENT_FLAG_DATA);
6201 struct btrfs_disk_key copy_key;;
6203 tback = (struct tree_backref *)back;
6204 bi = (struct btrfs_tree_block_info *)(ei + 1);
6205 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6208 btrfs_set_disk_key_objectid(©_key,
6209 rec->info_objectid);
6210 btrfs_set_disk_key_type(©_key, 0);
6211 btrfs_set_disk_key_offset(©_key, 0);
6213 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6214 btrfs_set_tree_block_key(leaf, bi, ©_key);
6216 btrfs_set_extent_flags(leaf, ei,
6217 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6220 btrfs_mark_buffer_dirty(leaf);
6221 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6222 rec->max_size, 1, 0);
6225 btrfs_release_path(path);
6228 if (back->is_data) {
6232 dback = (struct data_backref *)back;
6233 if (back->full_backref)
6234 parent = dback->parent;
6238 for (i = 0; i < dback->found_ref; i++) {
6239 /* if parent != 0, we're doing a full backref
6240 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6241 * just makes the backref allocator create a data
6244 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6245 rec->start, rec->max_size,
6249 BTRFS_FIRST_FREE_OBJECTID :
6255 fprintf(stderr, "adding new data backref"
6256 " on %llu %s %llu owner %llu"
6257 " offset %llu found %d\n",
6258 (unsigned long long)rec->start,
6259 back->full_backref ?
6261 back->full_backref ?
6262 (unsigned long long)parent :
6263 (unsigned long long)dback->root,
6264 (unsigned long long)dback->owner,
6265 (unsigned long long)dback->offset,
6270 tback = (struct tree_backref *)back;
6271 if (back->full_backref)
6272 parent = tback->parent;
6276 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6277 rec->start, rec->max_size,
6278 parent, tback->root, 0, 0);
6279 fprintf(stderr, "adding new tree backref on "
6280 "start %llu len %llu parent %llu root %llu\n",
6281 rec->start, rec->max_size, tback->parent, tback->root);
6286 btrfs_release_path(path);
6290 struct extent_entry {
6295 struct list_head list;
6298 static struct extent_entry *find_entry(struct list_head *entries,
6299 u64 bytenr, u64 bytes)
6301 struct extent_entry *entry = NULL;
6303 list_for_each_entry(entry, entries, list) {
6304 if (entry->bytenr == bytenr && entry->bytes == bytes)
6311 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6313 struct extent_entry *entry, *best = NULL, *prev = NULL;
6315 list_for_each_entry(entry, entries, list) {
6322 * If there are as many broken entries as entries then we know
6323 * not to trust this particular entry.
6325 if (entry->broken == entry->count)
6329 * If our current entry == best then we can't be sure our best
6330 * is really the best, so we need to keep searching.
6332 if (best && best->count == entry->count) {
6338 /* Prev == entry, not good enough, have to keep searching */
6339 if (!prev->broken && prev->count == entry->count)
6343 best = (prev->count > entry->count) ? prev : entry;
6344 else if (best->count < entry->count)
6352 static int repair_ref(struct btrfs_trans_handle *trans,
6353 struct btrfs_fs_info *info, struct btrfs_path *path,
6354 struct data_backref *dback, struct extent_entry *entry)
6356 struct btrfs_root *root;
6357 struct btrfs_file_extent_item *fi;
6358 struct extent_buffer *leaf;
6359 struct btrfs_key key;
6363 key.objectid = dback->root;
6364 key.type = BTRFS_ROOT_ITEM_KEY;
6365 key.offset = (u64)-1;
6366 root = btrfs_read_fs_root(info, &key);
6368 fprintf(stderr, "Couldn't find root for our ref\n");
6373 * The backref points to the original offset of the extent if it was
6374 * split, so we need to search down to the offset we have and then walk
6375 * forward until we find the backref we're looking for.
6377 key.objectid = dback->owner;
6378 key.type = BTRFS_EXTENT_DATA_KEY;
6379 key.offset = dback->offset;
6380 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6382 fprintf(stderr, "Error looking up ref %d\n", ret);
6387 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6388 ret = btrfs_next_leaf(root, path);
6390 fprintf(stderr, "Couldn't find our ref, next\n");
6394 leaf = path->nodes[0];
6395 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6396 if (key.objectid != dback->owner ||
6397 key.type != BTRFS_EXTENT_DATA_KEY) {
6398 fprintf(stderr, "Couldn't find our ref, search\n");
6401 fi = btrfs_item_ptr(leaf, path->slots[0],
6402 struct btrfs_file_extent_item);
6403 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6404 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6406 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6411 btrfs_release_path(path);
6414 * Have to make sure that this root gets updated when we commit the
6417 record_root_in_trans(trans, root);
6420 * Ok we have the key of the file extent we want to fix, now we can cow
6421 * down to the thing and fix it.
6423 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6425 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6426 key.objectid, key.type, key.offset, ret);
6430 fprintf(stderr, "Well that's odd, we just found this key "
6431 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6435 leaf = path->nodes[0];
6436 fi = btrfs_item_ptr(leaf, path->slots[0],
6437 struct btrfs_file_extent_item);
6439 if (btrfs_file_extent_compression(leaf, fi) &&
6440 dback->disk_bytenr != entry->bytenr) {
6441 fprintf(stderr, "Ref doesn't match the record start and is "
6442 "compressed, please take a btrfs-image of this file "
6443 "system and send it to a btrfs developer so they can "
6444 "complete this functionality for bytenr %Lu\n",
6445 dback->disk_bytenr);
6449 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6450 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6451 } else if (dback->disk_bytenr > entry->bytenr) {
6452 u64 off_diff, offset;
6454 off_diff = dback->disk_bytenr - entry->bytenr;
6455 offset = btrfs_file_extent_offset(leaf, fi);
6456 if (dback->disk_bytenr + offset +
6457 btrfs_file_extent_num_bytes(leaf, fi) >
6458 entry->bytenr + entry->bytes) {
6459 fprintf(stderr, "Ref is past the entry end, please "
6460 "take a btrfs-image of this file system and "
6461 "send it to a btrfs developer, ref %Lu\n",
6462 dback->disk_bytenr);
6466 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6467 btrfs_set_file_extent_offset(leaf, fi, offset);
6468 } else if (dback->disk_bytenr < entry->bytenr) {
6471 offset = btrfs_file_extent_offset(leaf, fi);
6472 if (dback->disk_bytenr + offset < entry->bytenr) {
6473 fprintf(stderr, "Ref is before the entry start, please"
6474 " take a btrfs-image of this file system and "
6475 "send it to a btrfs developer, ref %Lu\n",
6476 dback->disk_bytenr);
6480 offset += dback->disk_bytenr;
6481 offset -= entry->bytenr;
6482 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6483 btrfs_set_file_extent_offset(leaf, fi, offset);
6486 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6489 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6490 * only do this if we aren't using compression, otherwise it's a
6493 if (!btrfs_file_extent_compression(leaf, fi))
6494 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6496 printf("ram bytes may be wrong?\n");
6497 btrfs_mark_buffer_dirty(leaf);
6498 btrfs_release_path(path);
6502 static int verify_backrefs(struct btrfs_trans_handle *trans,
6503 struct btrfs_fs_info *info, struct btrfs_path *path,
6504 struct extent_record *rec)
6506 struct extent_backref *back;
6507 struct data_backref *dback;
6508 struct extent_entry *entry, *best = NULL;
6511 int broken_entries = 0;
6516 * Metadata is easy and the backrefs should always agree on bytenr and
6517 * size, if not we've got bigger issues.
6522 list_for_each_entry(back, &rec->backrefs, list) {
6523 if (back->full_backref || !back->is_data)
6526 dback = (struct data_backref *)back;
6529 * We only pay attention to backrefs that we found a real
6532 if (dback->found_ref == 0)
6536 * For now we only catch when the bytes don't match, not the
6537 * bytenr. We can easily do this at the same time, but I want
6538 * to have a fs image to test on before we just add repair
6539 * functionality willy-nilly so we know we won't screw up the
6543 entry = find_entry(&entries, dback->disk_bytenr,
6546 entry = malloc(sizeof(struct extent_entry));
6551 memset(entry, 0, sizeof(*entry));
6552 entry->bytenr = dback->disk_bytenr;
6553 entry->bytes = dback->bytes;
6554 list_add_tail(&entry->list, &entries);
6559 * If we only have on entry we may think the entries agree when
6560 * in reality they don't so we have to do some extra checking.
6562 if (dback->disk_bytenr != rec->start ||
6563 dback->bytes != rec->nr || back->broken)
6574 /* Yay all the backrefs agree, carry on good sir */
6575 if (nr_entries <= 1 && !mismatch)
6578 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6579 "%Lu\n", rec->start);
6582 * First we want to see if the backrefs can agree amongst themselves who
6583 * is right, so figure out which one of the entries has the highest
6586 best = find_most_right_entry(&entries);
6589 * Ok so we may have an even split between what the backrefs think, so
6590 * this is where we use the extent ref to see what it thinks.
6593 entry = find_entry(&entries, rec->start, rec->nr);
6594 if (!entry && (!broken_entries || !rec->found_rec)) {
6595 fprintf(stderr, "Backrefs don't agree with each other "
6596 "and extent record doesn't agree with anybody,"
6597 " so we can't fix bytenr %Lu bytes %Lu\n",
6598 rec->start, rec->nr);
6601 } else if (!entry) {
6603 * Ok our backrefs were broken, we'll assume this is the
6604 * correct value and add an entry for this range.
6606 entry = malloc(sizeof(struct extent_entry));
6611 memset(entry, 0, sizeof(*entry));
6612 entry->bytenr = rec->start;
6613 entry->bytes = rec->nr;
6614 list_add_tail(&entry->list, &entries);
6618 best = find_most_right_entry(&entries);
6620 fprintf(stderr, "Backrefs and extent record evenly "
6621 "split on who is right, this is going to "
6622 "require user input to fix bytenr %Lu bytes "
6623 "%Lu\n", rec->start, rec->nr);
6630 * I don't think this can happen currently as we'll abort() if we catch
6631 * this case higher up, but in case somebody removes that we still can't
6632 * deal with it properly here yet, so just bail out of that's the case.
6634 if (best->bytenr != rec->start) {
6635 fprintf(stderr, "Extent start and backref starts don't match, "
6636 "please use btrfs-image on this file system and send "
6637 "it to a btrfs developer so they can make fsck fix "
6638 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6639 rec->start, rec->nr);
6645 * Ok great we all agreed on an extent record, let's go find the real
6646 * references and fix up the ones that don't match.
6648 list_for_each_entry(back, &rec->backrefs, list) {
6649 if (back->full_backref || !back->is_data)
6652 dback = (struct data_backref *)back;
6655 * Still ignoring backrefs that don't have a real ref attached
6658 if (dback->found_ref == 0)
6661 if (dback->bytes == best->bytes &&
6662 dback->disk_bytenr == best->bytenr)
6665 ret = repair_ref(trans, info, path, dback, best);
6671 * Ok we messed with the actual refs, which means we need to drop our
6672 * entire cache and go back and rescan. I know this is a huge pain and
6673 * adds a lot of extra work, but it's the only way to be safe. Once all
6674 * the backrefs agree we may not need to do anything to the extent
6679 while (!list_empty(&entries)) {
6680 entry = list_entry(entries.next, struct extent_entry, list);
6681 list_del_init(&entry->list);
6687 static int process_duplicates(struct btrfs_root *root,
6688 struct cache_tree *extent_cache,
6689 struct extent_record *rec)
6691 struct extent_record *good, *tmp;
6692 struct cache_extent *cache;
6696 * If we found a extent record for this extent then return, or if we
6697 * have more than one duplicate we are likely going to need to delete
6700 if (rec->found_rec || rec->num_duplicates > 1)
6703 /* Shouldn't happen but just in case */
6704 BUG_ON(!rec->num_duplicates);
6707 * So this happens if we end up with a backref that doesn't match the
6708 * actual extent entry. So either the backref is bad or the extent
6709 * entry is bad. Either way we want to have the extent_record actually
6710 * reflect what we found in the extent_tree, so we need to take the
6711 * duplicate out and use that as the extent_record since the only way we
6712 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6714 remove_cache_extent(extent_cache, &rec->cache);
6716 good = list_entry(rec->dups.next, struct extent_record, list);
6717 list_del_init(&good->list);
6718 INIT_LIST_HEAD(&good->backrefs);
6719 INIT_LIST_HEAD(&good->dups);
6720 good->cache.start = good->start;
6721 good->cache.size = good->nr;
6722 good->content_checked = 0;
6723 good->owner_ref_checked = 0;
6724 good->num_duplicates = 0;
6725 good->refs = rec->refs;
6726 list_splice_init(&rec->backrefs, &good->backrefs);
6728 cache = lookup_cache_extent(extent_cache, good->start,
6732 tmp = container_of(cache, struct extent_record, cache);
6735 * If we find another overlapping extent and it's found_rec is
6736 * set then it's a duplicate and we need to try and delete
6739 if (tmp->found_rec || tmp->num_duplicates > 0) {
6740 if (list_empty(&good->list))
6741 list_add_tail(&good->list,
6742 &duplicate_extents);
6743 good->num_duplicates += tmp->num_duplicates + 1;
6744 list_splice_init(&tmp->dups, &good->dups);
6745 list_del_init(&tmp->list);
6746 list_add_tail(&tmp->list, &good->dups);
6747 remove_cache_extent(extent_cache, &tmp->cache);
6752 * Ok we have another non extent item backed extent rec, so lets
6753 * just add it to this extent and carry on like we did above.
6755 good->refs += tmp->refs;
6756 list_splice_init(&tmp->backrefs, &good->backrefs);
6757 remove_cache_extent(extent_cache, &tmp->cache);
6760 ret = insert_cache_extent(extent_cache, &good->cache);
6763 return good->num_duplicates ? 0 : 1;
6766 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
6767 struct btrfs_root *root,
6768 struct extent_record *rec)
6770 LIST_HEAD(delete_list);
6771 struct btrfs_path *path;
6772 struct extent_record *tmp, *good, *n;
6775 struct btrfs_key key;
6777 path = btrfs_alloc_path();
6784 /* Find the record that covers all of the duplicates. */
6785 list_for_each_entry(tmp, &rec->dups, list) {
6786 if (good->start < tmp->start)
6788 if (good->nr > tmp->nr)
6791 if (tmp->start + tmp->nr < good->start + good->nr) {
6792 fprintf(stderr, "Ok we have overlapping extents that "
6793 "aren't completely covered by eachother, this "
6794 "is going to require more careful thought. "
6795 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6796 tmp->start, tmp->nr, good->start, good->nr);
6803 list_add_tail(&rec->list, &delete_list);
6805 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6808 list_move_tail(&tmp->list, &delete_list);
6811 root = root->fs_info->extent_root;
6812 list_for_each_entry(tmp, &delete_list, list) {
6813 if (tmp->found_rec == 0)
6815 key.objectid = tmp->start;
6816 key.type = BTRFS_EXTENT_ITEM_KEY;
6817 key.offset = tmp->nr;
6819 /* Shouldn't happen but just in case */
6820 if (tmp->metadata) {
6821 fprintf(stderr, "Well this shouldn't happen, extent "
6822 "record overlaps but is metadata? "
6823 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6827 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6833 ret = btrfs_del_item(trans, root, path);
6836 btrfs_release_path(path);
6841 while (!list_empty(&delete_list)) {
6842 tmp = list_entry(delete_list.next, struct extent_record, list);
6843 list_del_init(&tmp->list);
6849 while (!list_empty(&rec->dups)) {
6850 tmp = list_entry(rec->dups.next, struct extent_record, list);
6851 list_del_init(&tmp->list);
6855 btrfs_free_path(path);
6857 if (!ret && !nr_del)
6858 rec->num_duplicates = 0;
6860 return ret ? ret : nr_del;
6863 static int find_possible_backrefs(struct btrfs_trans_handle *trans,
6864 struct btrfs_fs_info *info,
6865 struct btrfs_path *path,
6866 struct cache_tree *extent_cache,
6867 struct extent_record *rec)
6869 struct btrfs_root *root;
6870 struct extent_backref *back;
6871 struct data_backref *dback;
6872 struct cache_extent *cache;
6873 struct btrfs_file_extent_item *fi;
6874 struct btrfs_key key;
6878 list_for_each_entry(back, &rec->backrefs, list) {
6879 /* Don't care about full backrefs (poor unloved backrefs) */
6880 if (back->full_backref || !back->is_data)
6883 dback = (struct data_backref *)back;
6885 /* We found this one, we don't need to do a lookup */
6886 if (dback->found_ref)
6889 key.objectid = dback->root;
6890 key.type = BTRFS_ROOT_ITEM_KEY;
6891 key.offset = (u64)-1;
6893 root = btrfs_read_fs_root(info, &key);
6895 /* No root, definitely a bad ref, skip */
6896 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6898 /* Other err, exit */
6900 return PTR_ERR(root);
6902 key.objectid = dback->owner;
6903 key.type = BTRFS_EXTENT_DATA_KEY;
6904 key.offset = dback->offset;
6905 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6907 btrfs_release_path(path);
6910 /* Didn't find it, we can carry on */
6915 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6916 struct btrfs_file_extent_item);
6917 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6918 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6919 btrfs_release_path(path);
6920 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6922 struct extent_record *tmp;
6923 tmp = container_of(cache, struct extent_record, cache);
6926 * If we found an extent record for the bytenr for this
6927 * particular backref then we can't add it to our
6928 * current extent record. We only want to add backrefs
6929 * that don't have a corresponding extent item in the
6930 * extent tree since they likely belong to this record
6931 * and we need to fix it if it doesn't match bytenrs.
6937 dback->found_ref += 1;
6938 dback->disk_bytenr = bytenr;
6939 dback->bytes = bytes;
6942 * Set this so the verify backref code knows not to trust the
6943 * values in this backref.
6952 * Record orphan data ref into corresponding root.
6954 * Return 0 if the extent item contains data ref and recorded.
6955 * Return 1 if the extent item contains no useful data ref
6956 * On that case, it may contains only shared_dataref or metadata backref
6957 * or the file extent exists(this should be handled by the extent bytenr
6959 * Return <0 if something goes wrong.
6961 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6962 struct extent_record *rec)
6964 struct btrfs_key key;
6965 struct btrfs_root *dest_root;
6966 struct extent_backref *back;
6967 struct data_backref *dback;
6968 struct orphan_data_extent *orphan;
6969 struct btrfs_path *path;
6970 int recorded_data_ref = 0;
6975 path = btrfs_alloc_path();
6978 list_for_each_entry(back, &rec->backrefs, list) {
6979 if (back->full_backref || !back->is_data ||
6980 !back->found_extent_tree)
6982 dback = (struct data_backref *)back;
6983 if (dback->found_ref)
6985 key.objectid = dback->root;
6986 key.type = BTRFS_ROOT_ITEM_KEY;
6987 key.offset = (u64)-1;
6989 dest_root = btrfs_read_fs_root(fs_info, &key);
6991 /* For non-exist root we just skip it */
6992 if (IS_ERR(dest_root) || !dest_root)
6995 key.objectid = dback->owner;
6996 key.type = BTRFS_EXTENT_DATA_KEY;
6997 key.offset = dback->offset;
6999 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7001 * For ret < 0, it's OK since the fs-tree may be corrupted,
7002 * we need to record it for inode/file extent rebuild.
7003 * For ret > 0, we record it only for file extent rebuild.
7004 * For ret == 0, the file extent exists but only bytenr
7005 * mismatch, let the original bytenr fix routine to handle,
7011 orphan = malloc(sizeof(*orphan));
7016 INIT_LIST_HEAD(&orphan->list);
7017 orphan->root = dback->root;
7018 orphan->objectid = dback->owner;
7019 orphan->offset = dback->offset;
7020 orphan->disk_bytenr = rec->cache.start;
7021 orphan->disk_len = rec->cache.size;
7022 list_add(&dest_root->orphan_data_extents, &orphan->list);
7023 recorded_data_ref = 1;
7026 btrfs_free_path(path);
7028 return !recorded_data_ref;
7034 * when an incorrect extent item is found, this will delete
7035 * all of the existing entries for it and recreate them
7036 * based on what the tree scan found.
7038 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
7039 struct btrfs_fs_info *info,
7040 struct cache_tree *extent_cache,
7041 struct extent_record *rec)
7044 struct btrfs_path *path;
7045 struct list_head *cur = rec->backrefs.next;
7046 struct cache_extent *cache;
7047 struct extent_backref *back;
7051 if (rec->flag_block_full_backref)
7052 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7054 path = btrfs_alloc_path();
7058 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7060 * Sometimes the backrefs themselves are so broken they don't
7061 * get attached to any meaningful rec, so first go back and
7062 * check any of our backrefs that we couldn't find and throw
7063 * them into the list if we find the backref so that
7064 * verify_backrefs can figure out what to do.
7066 ret = find_possible_backrefs(trans, info, path, extent_cache,
7072 /* step one, make sure all of the backrefs agree */
7073 ret = verify_backrefs(trans, info, path, rec);
7077 /* step two, delete all the existing records */
7078 ret = delete_extent_records(trans, info->extent_root, path,
7079 rec->start, rec->max_size);
7084 /* was this block corrupt? If so, don't add references to it */
7085 cache = lookup_cache_extent(info->corrupt_blocks,
7086 rec->start, rec->max_size);
7092 /* step three, recreate all the refs we did find */
7093 while(cur != &rec->backrefs) {
7094 back = list_entry(cur, struct extent_backref, list);
7098 * if we didn't find any references, don't create a
7101 if (!back->found_ref)
7104 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7111 btrfs_free_path(path);
7115 /* right now we only prune from the extent allocation tree */
7116 static int prune_one_block(struct btrfs_trans_handle *trans,
7117 struct btrfs_fs_info *info,
7118 struct btrfs_corrupt_block *corrupt)
7121 struct btrfs_path path;
7122 struct extent_buffer *eb;
7126 int level = corrupt->level + 1;
7128 btrfs_init_path(&path);
7130 /* we want to stop at the parent to our busted block */
7131 path.lowest_level = level;
7133 ret = btrfs_search_slot(trans, info->extent_root,
7134 &corrupt->key, &path, -1, 1);
7139 eb = path.nodes[level];
7146 * hopefully the search gave us the block we want to prune,
7147 * lets try that first
7149 slot = path.slots[level];
7150 found = btrfs_node_blockptr(eb, slot);
7151 if (found == corrupt->cache.start)
7154 nritems = btrfs_header_nritems(eb);
7156 /* the search failed, lets scan this node and hope we find it */
7157 for (slot = 0; slot < nritems; slot++) {
7158 found = btrfs_node_blockptr(eb, slot);
7159 if (found == corrupt->cache.start)
7163 * we couldn't find the bad block. TODO, search all the nodes for pointers
7166 if (eb == info->extent_root->node) {
7171 btrfs_release_path(&path);
7176 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7177 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7180 btrfs_release_path(&path);
7184 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
7185 struct btrfs_fs_info *info)
7187 struct cache_extent *cache;
7188 struct btrfs_corrupt_block *corrupt;
7190 cache = search_cache_extent(info->corrupt_blocks, 0);
7194 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7195 prune_one_block(trans, info, corrupt);
7196 cache = next_cache_extent(cache);
7201 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7203 struct btrfs_block_group_cache *cache;
7208 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7209 &start, &end, EXTENT_DIRTY);
7212 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7218 cache = btrfs_lookup_first_block_group(fs_info, start);
7223 start = cache->key.objectid + cache->key.offset;
7227 static int check_extent_refs(struct btrfs_trans_handle *trans,
7228 struct btrfs_root *root,
7229 struct cache_tree *extent_cache)
7231 struct extent_record *rec;
7232 struct cache_extent *cache;
7241 * if we're doing a repair, we have to make sure
7242 * we don't allocate from the problem extents.
7243 * In the worst case, this will be all the
7246 cache = search_cache_extent(extent_cache, 0);
7248 rec = container_of(cache, struct extent_record, cache);
7249 btrfs_pin_extent(root->fs_info,
7250 rec->start, rec->max_size);
7251 cache = next_cache_extent(cache);
7254 /* pin down all the corrupted blocks too */
7255 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7257 btrfs_pin_extent(root->fs_info,
7258 cache->start, cache->size);
7259 cache = next_cache_extent(cache);
7261 prune_corrupt_blocks(trans, root->fs_info);
7262 reset_cached_block_groups(root->fs_info);
7266 * We need to delete any duplicate entries we find first otherwise we
7267 * could mess up the extent tree when we have backrefs that actually
7268 * belong to a different extent item and not the weird duplicate one.
7270 while (repair && !list_empty(&duplicate_extents)) {
7271 rec = list_entry(duplicate_extents.next, struct extent_record,
7273 list_del_init(&rec->list);
7275 /* Sometimes we can find a backref before we find an actual
7276 * extent, so we need to process it a little bit to see if there
7277 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7278 * if this is a backref screwup. If we need to delete stuff
7279 * process_duplicates() will return 0, otherwise it will return
7282 if (process_duplicates(root, extent_cache, rec))
7284 ret = delete_duplicate_records(trans, root, rec);
7288 * delete_duplicate_records will return the number of entries
7289 * deleted, so if it's greater than 0 then we know we actually
7290 * did something and we need to remove.
7302 cache = search_cache_extent(extent_cache, 0);
7305 rec = container_of(cache, struct extent_record, cache);
7306 if (rec->num_duplicates) {
7307 fprintf(stderr, "extent item %llu has multiple extent "
7308 "items\n", (unsigned long long)rec->start);
7312 if (rec->refs != rec->extent_item_refs) {
7313 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7314 (unsigned long long)rec->start,
7315 (unsigned long long)rec->nr);
7316 fprintf(stderr, "extent item %llu, found %llu\n",
7317 (unsigned long long)rec->extent_item_refs,
7318 (unsigned long long)rec->refs);
7319 ret = record_orphan_data_extents(root->fs_info, rec);
7326 * we can't use the extent to repair file
7327 * extent, let the fallback method handle it.
7329 if (!fixed && repair) {
7330 ret = fixup_extent_refs(trans,
7341 if (all_backpointers_checked(rec, 1)) {
7342 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7343 (unsigned long long)rec->start,
7344 (unsigned long long)rec->nr);
7346 if (!fixed && !recorded && repair) {
7347 ret = fixup_extent_refs(trans, root->fs_info,
7355 if (!rec->owner_ref_checked) {
7356 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7357 (unsigned long long)rec->start,
7358 (unsigned long long)rec->nr);
7359 if (!fixed && !recorded && repair) {
7360 ret = fixup_extent_refs(trans, root->fs_info,
7369 remove_cache_extent(extent_cache, cache);
7370 free_all_extent_backrefs(rec);
7375 if (ret && ret != -EAGAIN) {
7376 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7379 btrfs_fix_block_accounting(trans, root);
7382 fprintf(stderr, "repaired damaged extent references\n");
7388 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7392 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7393 stripe_size = length;
7394 stripe_size /= num_stripes;
7395 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7396 stripe_size = length * 2;
7397 stripe_size /= num_stripes;
7398 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7399 stripe_size = length;
7400 stripe_size /= (num_stripes - 1);
7401 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7402 stripe_size = length;
7403 stripe_size /= (num_stripes - 2);
7405 stripe_size = length;
7411 * Check the chunk with its block group/dev list ref:
7412 * Return 0 if all refs seems valid.
7413 * Return 1 if part of refs seems valid, need later check for rebuild ref
7414 * like missing block group and needs to search extent tree to rebuild them.
7415 * Return -1 if essential refs are missing and unable to rebuild.
7417 static int check_chunk_refs(struct chunk_record *chunk_rec,
7418 struct block_group_tree *block_group_cache,
7419 struct device_extent_tree *dev_extent_cache,
7422 struct cache_extent *block_group_item;
7423 struct block_group_record *block_group_rec;
7424 struct cache_extent *dev_extent_item;
7425 struct device_extent_record *dev_extent_rec;
7429 int metadump_v2 = 0;
7433 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7436 if (block_group_item) {
7437 block_group_rec = container_of(block_group_item,
7438 struct block_group_record,
7440 if (chunk_rec->length != block_group_rec->offset ||
7441 chunk_rec->offset != block_group_rec->objectid ||
7443 chunk_rec->type_flags != block_group_rec->flags)) {
7446 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7447 chunk_rec->objectid,
7452 chunk_rec->type_flags,
7453 block_group_rec->objectid,
7454 block_group_rec->type,
7455 block_group_rec->offset,
7456 block_group_rec->offset,
7457 block_group_rec->objectid,
7458 block_group_rec->flags);
7461 list_del_init(&block_group_rec->list);
7462 chunk_rec->bg_rec = block_group_rec;
7467 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7468 chunk_rec->objectid,
7473 chunk_rec->type_flags);
7480 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7481 chunk_rec->num_stripes);
7482 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7483 devid = chunk_rec->stripes[i].devid;
7484 offset = chunk_rec->stripes[i].offset;
7485 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7486 devid, offset, length);
7487 if (dev_extent_item) {
7488 dev_extent_rec = container_of(dev_extent_item,
7489 struct device_extent_record,
7491 if (dev_extent_rec->objectid != devid ||
7492 dev_extent_rec->offset != offset ||
7493 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7494 dev_extent_rec->length != length) {
7497 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7498 chunk_rec->objectid,
7501 chunk_rec->stripes[i].devid,
7502 chunk_rec->stripes[i].offset,
7503 dev_extent_rec->objectid,
7504 dev_extent_rec->offset,
7505 dev_extent_rec->length);
7508 list_move(&dev_extent_rec->chunk_list,
7509 &chunk_rec->dextents);
7514 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7515 chunk_rec->objectid,
7518 chunk_rec->stripes[i].devid,
7519 chunk_rec->stripes[i].offset);
7526 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7527 int check_chunks(struct cache_tree *chunk_cache,
7528 struct block_group_tree *block_group_cache,
7529 struct device_extent_tree *dev_extent_cache,
7530 struct list_head *good, struct list_head *bad,
7531 struct list_head *rebuild, int silent)
7533 struct cache_extent *chunk_item;
7534 struct chunk_record *chunk_rec;
7535 struct block_group_record *bg_rec;
7536 struct device_extent_record *dext_rec;
7540 chunk_item = first_cache_extent(chunk_cache);
7541 while (chunk_item) {
7542 chunk_rec = container_of(chunk_item, struct chunk_record,
7544 err = check_chunk_refs(chunk_rec, block_group_cache,
7545 dev_extent_cache, silent);
7548 if (err == 0 && good)
7549 list_add_tail(&chunk_rec->list, good);
7550 if (err > 0 && rebuild)
7551 list_add_tail(&chunk_rec->list, rebuild);
7553 list_add_tail(&chunk_rec->list, bad);
7554 chunk_item = next_cache_extent(chunk_item);
7557 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7560 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7568 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7572 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7583 static int check_device_used(struct device_record *dev_rec,
7584 struct device_extent_tree *dext_cache)
7586 struct cache_extent *cache;
7587 struct device_extent_record *dev_extent_rec;
7590 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7592 dev_extent_rec = container_of(cache,
7593 struct device_extent_record,
7595 if (dev_extent_rec->objectid != dev_rec->devid)
7598 list_del_init(&dev_extent_rec->device_list);
7599 total_byte += dev_extent_rec->length;
7600 cache = next_cache_extent(cache);
7603 if (total_byte != dev_rec->byte_used) {
7605 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7606 total_byte, dev_rec->byte_used, dev_rec->objectid,
7607 dev_rec->type, dev_rec->offset);
7614 /* check btrfs_dev_item -> btrfs_dev_extent */
7615 static int check_devices(struct rb_root *dev_cache,
7616 struct device_extent_tree *dev_extent_cache)
7618 struct rb_node *dev_node;
7619 struct device_record *dev_rec;
7620 struct device_extent_record *dext_rec;
7624 dev_node = rb_first(dev_cache);
7626 dev_rec = container_of(dev_node, struct device_record, node);
7627 err = check_device_used(dev_rec, dev_extent_cache);
7631 dev_node = rb_next(dev_node);
7633 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7636 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7637 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7644 static int add_root_item_to_list(struct list_head *head,
7645 u64 objectid, u64 bytenr,
7646 u8 level, u8 drop_level,
7647 int level_size, struct btrfs_key *drop_key)
7650 struct root_item_record *ri_rec;
7651 ri_rec = malloc(sizeof(*ri_rec));
7654 ri_rec->bytenr = bytenr;
7655 ri_rec->objectid = objectid;
7656 ri_rec->level = level;
7657 ri_rec->level_size = level_size;
7658 ri_rec->drop_level = drop_level;
7660 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7661 list_add_tail(&ri_rec->list, head);
7666 static void free_root_item_list(struct list_head *list)
7668 struct root_item_record *ri_rec;
7670 while (!list_empty(list)) {
7671 ri_rec = list_first_entry(list, struct root_item_record,
7673 list_del_init(&ri_rec->list);
7678 static int deal_root_from_list(struct list_head *list,
7679 struct btrfs_trans_handle *trans,
7680 struct btrfs_root *root,
7681 struct block_info *bits,
7683 struct cache_tree *pending,
7684 struct cache_tree *seen,
7685 struct cache_tree *reada,
7686 struct cache_tree *nodes,
7687 struct cache_tree *extent_cache,
7688 struct cache_tree *chunk_cache,
7689 struct rb_root *dev_cache,
7690 struct block_group_tree *block_group_cache,
7691 struct device_extent_tree *dev_extent_cache)
7696 while (!list_empty(list)) {
7697 struct root_item_record *rec;
7698 struct extent_buffer *buf;
7699 rec = list_entry(list->next,
7700 struct root_item_record, list);
7702 buf = read_tree_block(root->fs_info->tree_root,
7703 rec->bytenr, rec->level_size, 0);
7704 if (!extent_buffer_uptodate(buf)) {
7705 free_extent_buffer(buf);
7709 add_root_to_pending(buf, extent_cache, pending,
7710 seen, nodes, rec->objectid);
7712 * To rebuild extent tree, we need deal with snapshot
7713 * one by one, otherwise we deal with node firstly which
7714 * can maximize readahead.
7717 ret = run_next_block(trans, root, bits, bits_nr, &last,
7718 pending, seen, reada,
7719 nodes, extent_cache,
7720 chunk_cache, dev_cache,
7722 dev_extent_cache, rec);
7726 free_extent_buffer(buf);
7727 list_del(&rec->list);
7733 ret = run_next_block(trans, root, bits, bits_nr, &last,
7734 pending, seen, reada,
7735 nodes, extent_cache,
7736 chunk_cache, dev_cache,
7738 dev_extent_cache, NULL);
7748 static int check_chunks_and_extents(struct btrfs_root *root)
7750 struct rb_root dev_cache;
7751 struct cache_tree chunk_cache;
7752 struct block_group_tree block_group_cache;
7753 struct device_extent_tree dev_extent_cache;
7754 struct cache_tree extent_cache;
7755 struct cache_tree seen;
7756 struct cache_tree pending;
7757 struct cache_tree reada;
7758 struct cache_tree nodes;
7759 struct cache_tree corrupt_blocks;
7760 struct btrfs_path path;
7761 struct btrfs_key key;
7762 struct btrfs_key found_key;
7764 struct block_info *bits;
7766 struct extent_buffer *leaf;
7767 struct btrfs_trans_handle *trans = NULL;
7769 struct btrfs_root_item ri;
7770 struct list_head dropping_trees;
7771 struct list_head normal_trees;
7772 struct btrfs_root *root1;
7777 dev_cache = RB_ROOT;
7778 cache_tree_init(&chunk_cache);
7779 block_group_tree_init(&block_group_cache);
7780 device_extent_tree_init(&dev_extent_cache);
7782 cache_tree_init(&extent_cache);
7783 cache_tree_init(&seen);
7784 cache_tree_init(&pending);
7785 cache_tree_init(&nodes);
7786 cache_tree_init(&reada);
7787 cache_tree_init(&corrupt_blocks);
7788 INIT_LIST_HEAD(&dropping_trees);
7789 INIT_LIST_HEAD(&normal_trees);
7792 trans = btrfs_start_transaction(root, 1);
7793 if (IS_ERR(trans)) {
7794 fprintf(stderr, "Error starting transaction\n");
7795 return PTR_ERR(trans);
7797 root->fs_info->fsck_extent_cache = &extent_cache;
7798 root->fs_info->free_extent_hook = free_extent_hook;
7799 root->fs_info->corrupt_blocks = &corrupt_blocks;
7803 bits = malloc(bits_nr * sizeof(struct block_info));
7810 root1 = root->fs_info->tree_root;
7811 level = btrfs_header_level(root1->node);
7812 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7813 root1->node->start, level, 0,
7814 btrfs_level_size(root1, level), NULL);
7817 root1 = root->fs_info->chunk_root;
7818 level = btrfs_header_level(root1->node);
7819 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7820 root1->node->start, level, 0,
7821 btrfs_level_size(root1, level), NULL);
7824 btrfs_init_path(&path);
7827 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7828 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7833 leaf = path.nodes[0];
7834 slot = path.slots[0];
7835 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7836 ret = btrfs_next_leaf(root, &path);
7839 leaf = path.nodes[0];
7840 slot = path.slots[0];
7842 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7843 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7844 unsigned long offset;
7846 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7847 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7848 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7849 level = btrfs_root_level(&ri);
7850 level_size = btrfs_level_size(root, level);
7851 ret = add_root_item_to_list(&normal_trees,
7853 btrfs_root_bytenr(&ri), level,
7854 0, level_size, NULL);
7858 level = btrfs_root_level(&ri);
7859 level_size = btrfs_level_size(root, level);
7860 objectid = found_key.objectid;
7861 btrfs_disk_key_to_cpu(&found_key,
7863 ret = add_root_item_to_list(&dropping_trees,
7865 btrfs_root_bytenr(&ri),
7866 level, ri.drop_level,
7867 level_size, &found_key);
7874 btrfs_release_path(&path);
7877 * check_block can return -EAGAIN if it fixes something, please keep
7878 * this in mind when dealing with return values from these functions, if
7879 * we get -EAGAIN we want to fall through and restart the loop.
7881 ret = deal_root_from_list(&normal_trees, trans, root,
7882 bits, bits_nr, &pending, &seen,
7883 &reada, &nodes, &extent_cache,
7884 &chunk_cache, &dev_cache, &block_group_cache,
7891 ret = deal_root_from_list(&dropping_trees, trans, root,
7892 bits, bits_nr, &pending, &seen,
7893 &reada, &nodes, &extent_cache,
7894 &chunk_cache, &dev_cache,
7903 err = check_chunks(&chunk_cache, &block_group_cache,
7904 &dev_extent_cache, NULL, NULL, NULL, 0);
7912 ret = check_extent_refs(trans, root, &extent_cache);
7919 err = check_devices(&dev_cache, &dev_extent_cache);
7925 err = btrfs_commit_transaction(trans, root);
7930 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
7931 root->fs_info->fsck_extent_cache = NULL;
7932 root->fs_info->free_extent_hook = NULL;
7933 root->fs_info->corrupt_blocks = NULL;
7936 free_chunk_cache_tree(&chunk_cache);
7937 free_device_cache_tree(&dev_cache);
7938 free_block_group_tree(&block_group_cache);
7939 free_device_extent_tree(&dev_extent_cache);
7940 free_extent_cache_tree(&seen);
7941 free_extent_cache_tree(&pending);
7942 free_extent_cache_tree(&reada);
7943 free_extent_cache_tree(&nodes);
7946 ret = btrfs_commit_transaction(trans, root);
7950 trans = btrfs_start_transaction(root, 1);
7951 if (IS_ERR(trans)) {
7952 ret = PTR_ERR(trans);
7956 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
7957 free_extent_cache_tree(&seen);
7958 free_extent_cache_tree(&pending);
7959 free_extent_cache_tree(&reada);
7960 free_extent_cache_tree(&nodes);
7961 free_chunk_cache_tree(&chunk_cache);
7962 free_block_group_tree(&block_group_cache);
7963 free_device_cache_tree(&dev_cache);
7964 free_device_extent_tree(&dev_extent_cache);
7965 free_extent_record_cache(root->fs_info, &extent_cache);
7966 free_root_item_list(&normal_trees);
7967 free_root_item_list(&dropping_trees);
7971 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
7972 struct btrfs_root *root, int overwrite)
7974 struct extent_buffer *c;
7975 struct extent_buffer *old = root->node;
7978 struct btrfs_disk_key disk_key = {0,0,0};
7984 extent_buffer_get(c);
7987 c = btrfs_alloc_free_block(trans, root,
7988 btrfs_level_size(root, 0),
7989 root->root_key.objectid,
7990 &disk_key, level, 0, 0);
7993 extent_buffer_get(c);
7997 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
7998 btrfs_set_header_level(c, level);
7999 btrfs_set_header_bytenr(c, c->start);
8000 btrfs_set_header_generation(c, trans->transid);
8001 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8002 btrfs_set_header_owner(c, root->root_key.objectid);
8004 write_extent_buffer(c, root->fs_info->fsid,
8005 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8007 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8008 btrfs_header_chunk_tree_uuid(c),
8011 btrfs_mark_buffer_dirty(c);
8013 * this case can happen in the following case:
8015 * 1.overwrite previous root.
8017 * 2.reinit reloc data root, this is because we skip pin
8018 * down reloc data tree before which means we can allocate
8019 * same block bytenr here.
8021 if (old->start == c->start) {
8022 btrfs_set_root_generation(&root->root_item,
8024 root->root_item.level = btrfs_header_level(root->node);
8025 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8026 &root->root_key, &root->root_item);
8028 free_extent_buffer(c);
8032 free_extent_buffer(old);
8034 add_root_to_dirty_list(root);
8038 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8039 struct extent_buffer *eb, int tree_root)
8041 struct extent_buffer *tmp;
8042 struct btrfs_root_item *ri;
8043 struct btrfs_key key;
8046 int level = btrfs_header_level(eb);
8052 * If we have pinned this block before, don't pin it again.
8053 * This can not only avoid forever loop with broken filesystem
8054 * but also give us some speedups.
8056 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8057 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8060 btrfs_pin_extent(fs_info, eb->start, eb->len);
8062 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8063 nritems = btrfs_header_nritems(eb);
8064 for (i = 0; i < nritems; i++) {
8066 btrfs_item_key_to_cpu(eb, &key, i);
8067 if (key.type != BTRFS_ROOT_ITEM_KEY)
8069 /* Skip the extent root and reloc roots */
8070 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8071 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8072 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8074 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8075 bytenr = btrfs_disk_root_bytenr(eb, ri);
8078 * If at any point we start needing the real root we
8079 * will have to build a stump root for the root we are
8080 * in, but for now this doesn't actually use the root so
8081 * just pass in extent_root.
8083 tmp = read_tree_block(fs_info->extent_root, bytenr,
8085 if (!extent_buffer_uptodate(tmp)) {
8086 fprintf(stderr, "Error reading root block\n");
8089 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8090 free_extent_buffer(tmp);
8094 bytenr = btrfs_node_blockptr(eb, i);
8096 /* If we aren't the tree root don't read the block */
8097 if (level == 1 && !tree_root) {
8098 btrfs_pin_extent(fs_info, bytenr, leafsize);
8102 tmp = read_tree_block(fs_info->extent_root, bytenr,
8104 if (!extent_buffer_uptodate(tmp)) {
8105 fprintf(stderr, "Error reading tree block\n");
8108 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8109 free_extent_buffer(tmp);
8118 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8122 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8126 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8129 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8131 struct btrfs_block_group_cache *cache;
8132 struct btrfs_path *path;
8133 struct extent_buffer *leaf;
8134 struct btrfs_chunk *chunk;
8135 struct btrfs_key key;
8139 path = btrfs_alloc_path();
8144 key.type = BTRFS_CHUNK_ITEM_KEY;
8147 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8149 btrfs_free_path(path);
8154 * We do this in case the block groups were screwed up and had alloc
8155 * bits that aren't actually set on the chunks. This happens with
8156 * restored images every time and could happen in real life I guess.
8158 fs_info->avail_data_alloc_bits = 0;
8159 fs_info->avail_metadata_alloc_bits = 0;
8160 fs_info->avail_system_alloc_bits = 0;
8162 /* First we need to create the in-memory block groups */
8164 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8165 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8167 btrfs_free_path(path);
8175 leaf = path->nodes[0];
8176 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8177 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8182 chunk = btrfs_item_ptr(leaf, path->slots[0],
8183 struct btrfs_chunk);
8184 btrfs_add_block_group(fs_info, 0,
8185 btrfs_chunk_type(leaf, chunk),
8186 key.objectid, key.offset,
8187 btrfs_chunk_length(leaf, chunk));
8188 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8189 key.offset + btrfs_chunk_length(leaf, chunk),
8195 cache = btrfs_lookup_first_block_group(fs_info, start);
8199 start = cache->key.objectid + cache->key.offset;
8202 btrfs_free_path(path);
8206 static int reset_balance(struct btrfs_trans_handle *trans,
8207 struct btrfs_fs_info *fs_info)
8209 struct btrfs_root *root = fs_info->tree_root;
8210 struct btrfs_path *path;
8211 struct extent_buffer *leaf;
8212 struct btrfs_key key;
8213 int del_slot, del_nr = 0;
8217 path = btrfs_alloc_path();
8221 key.objectid = BTRFS_BALANCE_OBJECTID;
8222 key.type = BTRFS_BALANCE_ITEM_KEY;
8225 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8230 goto reinit_data_reloc;
8235 ret = btrfs_del_item(trans, root, path);
8238 btrfs_release_path(path);
8240 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8241 key.type = BTRFS_ROOT_ITEM_KEY;
8244 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8248 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8253 ret = btrfs_del_items(trans, root, path,
8260 btrfs_release_path(path);
8263 ret = btrfs_search_slot(trans, root, &key, path,
8270 leaf = path->nodes[0];
8271 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8272 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8274 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8279 del_slot = path->slots[0];
8288 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8292 btrfs_release_path(path);
8295 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8296 key.type = BTRFS_ROOT_ITEM_KEY;
8297 key.offset = (u64)-1;
8298 root = btrfs_read_fs_root(fs_info, &key);
8300 fprintf(stderr, "Error reading data reloc tree\n");
8301 ret = PTR_ERR(root);
8304 record_root_in_trans(trans, root);
8305 ret = btrfs_fsck_reinit_root(trans, root, 0);
8308 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8310 btrfs_free_path(path);
8314 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8315 struct btrfs_fs_info *fs_info)
8321 * The only reason we don't do this is because right now we're just
8322 * walking the trees we find and pinning down their bytes, we don't look
8323 * at any of the leaves. In order to do mixed groups we'd have to check
8324 * the leaves of any fs roots and pin down the bytes for any file
8325 * extents we find. Not hard but why do it if we don't have to?
8327 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8328 fprintf(stderr, "We don't support re-initing the extent tree "
8329 "for mixed block groups yet, please notify a btrfs "
8330 "developer you want to do this so they can add this "
8331 "functionality.\n");
8336 * first we need to walk all of the trees except the extent tree and pin
8337 * down the bytes that are in use so we don't overwrite any existing
8340 ret = pin_metadata_blocks(fs_info);
8342 fprintf(stderr, "error pinning down used bytes\n");
8347 * Need to drop all the block groups since we're going to recreate all
8350 btrfs_free_block_groups(fs_info);
8351 ret = reset_block_groups(fs_info);
8353 fprintf(stderr, "error resetting the block groups\n");
8357 /* Ok we can allocate now, reinit the extent root */
8358 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8360 fprintf(stderr, "extent root initialization failed\n");
8362 * When the transaction code is updated we should end the
8363 * transaction, but for now progs only knows about commit so
8364 * just return an error.
8370 * Now we have all the in-memory block groups setup so we can make
8371 * allocations properly, and the metadata we care about is safe since we
8372 * pinned all of it above.
8375 struct btrfs_block_group_cache *cache;
8377 cache = btrfs_lookup_first_block_group(fs_info, start);
8380 start = cache->key.objectid + cache->key.offset;
8381 ret = btrfs_insert_item(trans, fs_info->extent_root,
8382 &cache->key, &cache->item,
8383 sizeof(cache->item));
8385 fprintf(stderr, "Error adding block group\n");
8388 btrfs_extent_post_op(trans, fs_info->extent_root);
8391 ret = reset_balance(trans, fs_info);
8393 fprintf(stderr, "error reseting the pending balance\n");
8398 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8400 struct btrfs_path *path;
8401 struct btrfs_trans_handle *trans;
8402 struct btrfs_key key;
8405 printf("Recowing metadata block %llu\n", eb->start);
8406 key.objectid = btrfs_header_owner(eb);
8407 key.type = BTRFS_ROOT_ITEM_KEY;
8408 key.offset = (u64)-1;
8410 root = btrfs_read_fs_root(root->fs_info, &key);
8412 fprintf(stderr, "Couldn't find owner root %llu\n",
8414 return PTR_ERR(root);
8417 path = btrfs_alloc_path();
8421 trans = btrfs_start_transaction(root, 1);
8422 if (IS_ERR(trans)) {
8423 btrfs_free_path(path);
8424 return PTR_ERR(trans);
8427 path->lowest_level = btrfs_header_level(eb);
8428 if (path->lowest_level)
8429 btrfs_node_key_to_cpu(eb, &key, 0);
8431 btrfs_item_key_to_cpu(eb, &key, 0);
8433 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8434 btrfs_commit_transaction(trans, root);
8435 btrfs_free_path(path);
8439 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8441 struct btrfs_path *path;
8442 struct btrfs_trans_handle *trans;
8443 struct btrfs_key key;
8446 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8447 bad->key.type, bad->key.offset);
8448 key.objectid = bad->root_id;
8449 key.type = BTRFS_ROOT_ITEM_KEY;
8450 key.offset = (u64)-1;
8452 root = btrfs_read_fs_root(root->fs_info, &key);
8454 fprintf(stderr, "Couldn't find owner root %llu\n",
8456 return PTR_ERR(root);
8459 path = btrfs_alloc_path();
8463 trans = btrfs_start_transaction(root, 1);
8464 if (IS_ERR(trans)) {
8465 btrfs_free_path(path);
8466 return PTR_ERR(trans);
8469 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8475 ret = btrfs_del_item(trans, root, path);
8477 btrfs_commit_transaction(trans, root);
8478 btrfs_free_path(path);
8482 static int zero_log_tree(struct btrfs_root *root)
8484 struct btrfs_trans_handle *trans;
8487 trans = btrfs_start_transaction(root, 1);
8488 if (IS_ERR(trans)) {
8489 ret = PTR_ERR(trans);
8492 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8493 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8494 ret = btrfs_commit_transaction(trans, root);
8498 static int populate_csum(struct btrfs_trans_handle *trans,
8499 struct btrfs_root *csum_root, char *buf, u64 start,
8506 while (offset < len) {
8507 sectorsize = csum_root->sectorsize;
8508 ret = read_extent_data(csum_root, buf, start + offset,
8512 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8513 start + offset, buf, sectorsize);
8516 offset += sectorsize;
8521 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8522 struct btrfs_root *csum_root)
8524 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8525 struct btrfs_path *path;
8526 struct btrfs_extent_item *ei;
8527 struct extent_buffer *leaf;
8529 struct btrfs_key key;
8532 path = btrfs_alloc_path();
8537 key.type = BTRFS_EXTENT_ITEM_KEY;
8540 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8542 btrfs_free_path(path);
8546 buf = malloc(csum_root->sectorsize);
8548 btrfs_free_path(path);
8553 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8554 ret = btrfs_next_leaf(extent_root, path);
8562 leaf = path->nodes[0];
8564 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8565 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8570 ei = btrfs_item_ptr(leaf, path->slots[0],
8571 struct btrfs_extent_item);
8572 if (!(btrfs_extent_flags(leaf, ei) &
8573 BTRFS_EXTENT_FLAG_DATA)) {
8578 ret = populate_csum(trans, csum_root, buf, key.objectid,
8585 btrfs_free_path(path);
8590 struct root_item_info {
8591 /* level of the root */
8593 /* number of nodes at this level, must be 1 for a root */
8597 struct cache_extent cache_extent;
8600 static struct cache_tree *roots_info_cache = NULL;
8602 static void free_roots_info_cache(void)
8604 if (!roots_info_cache)
8607 while (!cache_tree_empty(roots_info_cache)) {
8608 struct cache_extent *entry;
8609 struct root_item_info *rii;
8611 entry = first_cache_extent(roots_info_cache);
8614 remove_cache_extent(roots_info_cache, entry);
8615 rii = container_of(entry, struct root_item_info, cache_extent);
8619 free(roots_info_cache);
8620 roots_info_cache = NULL;
8623 static int build_roots_info_cache(struct btrfs_fs_info *info)
8626 struct btrfs_key key;
8627 struct extent_buffer *leaf;
8628 struct btrfs_path *path;
8630 if (!roots_info_cache) {
8631 roots_info_cache = malloc(sizeof(*roots_info_cache));
8632 if (!roots_info_cache)
8634 cache_tree_init(roots_info_cache);
8637 path = btrfs_alloc_path();
8642 key.type = BTRFS_EXTENT_ITEM_KEY;
8645 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8648 leaf = path->nodes[0];
8651 struct btrfs_key found_key;
8652 struct btrfs_extent_item *ei;
8653 struct btrfs_extent_inline_ref *iref;
8654 int slot = path->slots[0];
8659 struct cache_extent *entry;
8660 struct root_item_info *rii;
8662 if (slot >= btrfs_header_nritems(leaf)) {
8663 ret = btrfs_next_leaf(info->extent_root, path);
8670 leaf = path->nodes[0];
8671 slot = path->slots[0];
8674 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8676 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8677 found_key.type != BTRFS_METADATA_ITEM_KEY)
8680 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8681 flags = btrfs_extent_flags(leaf, ei);
8683 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8684 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8687 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8688 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8689 level = found_key.offset;
8691 struct btrfs_tree_block_info *info;
8693 info = (struct btrfs_tree_block_info *)(ei + 1);
8694 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8695 level = btrfs_tree_block_level(leaf, info);
8699 * For a root extent, it must be of the following type and the
8700 * first (and only one) iref in the item.
8702 type = btrfs_extent_inline_ref_type(leaf, iref);
8703 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8706 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8707 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8709 rii = malloc(sizeof(struct root_item_info));
8714 rii->cache_extent.start = root_id;
8715 rii->cache_extent.size = 1;
8716 rii->level = (u8)-1;
8717 entry = &rii->cache_extent;
8718 ret = insert_cache_extent(roots_info_cache, entry);
8721 rii = container_of(entry, struct root_item_info,
8725 ASSERT(rii->cache_extent.start == root_id);
8726 ASSERT(rii->cache_extent.size == 1);
8728 if (level > rii->level || rii->level == (u8)-1) {
8730 rii->bytenr = found_key.objectid;
8731 rii->gen = btrfs_extent_generation(leaf, ei);
8732 rii->node_count = 1;
8733 } else if (level == rii->level) {
8741 btrfs_free_path(path);
8746 static int maybe_repair_root_item(struct btrfs_fs_info *info,
8747 struct btrfs_path *path,
8748 const struct btrfs_key *root_key,
8749 const int read_only_mode)
8751 const u64 root_id = root_key->objectid;
8752 struct cache_extent *entry;
8753 struct root_item_info *rii;
8754 struct btrfs_root_item ri;
8755 unsigned long offset;
8757 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8760 "Error: could not find extent items for root %llu\n",
8761 root_key->objectid);
8765 rii = container_of(entry, struct root_item_info, cache_extent);
8766 ASSERT(rii->cache_extent.start == root_id);
8767 ASSERT(rii->cache_extent.size == 1);
8769 if (rii->node_count != 1) {
8771 "Error: could not find btree root extent for root %llu\n",
8776 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
8777 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
8779 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
8780 btrfs_root_level(&ri) != rii->level ||
8781 btrfs_root_generation(&ri) != rii->gen) {
8784 * If we're in repair mode but our caller told us to not update
8785 * the root item, i.e. just check if it needs to be updated, don't
8786 * print this message, since the caller will call us again shortly
8787 * for the same root item without read only mode (the caller will
8788 * open a transaction first).
8790 if (!(read_only_mode && repair))
8792 "%sroot item for root %llu,"
8793 " current bytenr %llu, current gen %llu, current level %u,"
8794 " new bytenr %llu, new gen %llu, new level %u\n",
8795 (read_only_mode ? "" : "fixing "),
8797 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
8798 btrfs_root_level(&ri),
8799 rii->bytenr, rii->gen, rii->level);
8801 if (btrfs_root_generation(&ri) > rii->gen) {
8803 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
8804 root_id, btrfs_root_generation(&ri), rii->gen);
8808 if (!read_only_mode) {
8809 btrfs_set_root_bytenr(&ri, rii->bytenr);
8810 btrfs_set_root_level(&ri, rii->level);
8811 btrfs_set_root_generation(&ri, rii->gen);
8812 write_extent_buffer(path->nodes[0], &ri,
8813 offset, sizeof(ri));
8823 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
8824 * caused read-only snapshots to be corrupted if they were created at a moment
8825 * when the source subvolume/snapshot had orphan items. The issue was that the
8826 * on-disk root items became incorrect, referring to the pre orphan cleanup root
8827 * node instead of the post orphan cleanup root node.
8828 * So this function, and its callees, just detects and fixes those cases. Even
8829 * though the regression was for read-only snapshots, this function applies to
8830 * any snapshot/subvolume root.
8831 * This must be run before any other repair code - not doing it so, makes other
8832 * repair code delete or modify backrefs in the extent tree for example, which
8833 * will result in an inconsistent fs after repairing the root items.
8835 static int repair_root_items(struct btrfs_fs_info *info)
8837 struct btrfs_path *path = NULL;
8838 struct btrfs_key key;
8839 struct extent_buffer *leaf;
8840 struct btrfs_trans_handle *trans = NULL;
8845 ret = build_roots_info_cache(info);
8849 path = btrfs_alloc_path();
8855 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
8856 key.type = BTRFS_ROOT_ITEM_KEY;
8861 * Avoid opening and committing transactions if a leaf doesn't have
8862 * any root items that need to be fixed, so that we avoid rotating
8863 * backup roots unnecessarily.
8866 trans = btrfs_start_transaction(info->tree_root, 1);
8867 if (IS_ERR(trans)) {
8868 ret = PTR_ERR(trans);
8873 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
8877 leaf = path->nodes[0];
8880 struct btrfs_key found_key;
8882 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
8883 int no_more_keys = find_next_key(path, &key);
8885 btrfs_release_path(path);
8887 ret = btrfs_commit_transaction(trans,
8899 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8901 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
8903 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
8906 ret = maybe_repair_root_item(info, path, &found_key,
8911 if (!trans && repair) {
8914 btrfs_release_path(path);
8924 free_roots_info_cache();
8926 btrfs_free_path(path);
8933 const char * const cmd_check_usage[] = {
8934 "btrfs check [options] <device>",
8935 "Check an unmounted btrfs filesystem.",
8937 "-s|--super <superblock> use this superblock copy",
8938 "-b|--backup use the backup root copy",
8939 "--repair try to repair the filesystem",
8940 "--init-csum-tree create a new CRC tree",
8941 "--init-extent-tree create a new extent tree",
8942 "--check-data-csum verify checkums of data blocks",
8943 "--qgroup-report print a report on qgroup consistency",
8944 "--subvol-extents <subvolid> print subvolume extents and sharing state",
8945 "--tree-root <bytenr> use the given bytenr for the tree root",
8949 int cmd_check(int argc, char **argv)
8951 struct cache_tree root_cache;
8952 struct btrfs_root *root;
8953 struct btrfs_fs_info *info;
8956 u64 tree_root_bytenr = 0;
8957 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
8960 int init_csum_tree = 0;
8962 int qgroup_report = 0;
8963 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
8967 int option_index = 0;
8968 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
8969 OPT_CHECK_CSUM, OPT_READONLY };
8970 static const struct option long_options[] = {
8971 { "super", 1, NULL, 's' },
8972 { "repair", 0, NULL, OPT_REPAIR },
8973 { "readonly", 0, NULL, OPT_READONLY },
8974 { "init-csum-tree", 0, NULL, OPT_INIT_CSUM },
8975 { "init-extent-tree", 0, NULL, OPT_INIT_EXTENT },
8976 { "check-data-csum", 0, NULL, OPT_CHECK_CSUM },
8977 { "backup", 0, NULL, 'b' },
8978 { "subvol-extents", 1, NULL, 'E' },
8979 { "qgroup-report", 0, NULL, 'Q' },
8980 { "tree-root", 1, NULL, 'r' },
8984 c = getopt_long(argc, argv, "as:br:", long_options,
8989 case 'a': /* ignored */ break;
8991 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
8994 num = arg_strtou64(optarg);
8995 if (num >= BTRFS_SUPER_MIRROR_MAX) {
8997 "ERROR: super mirror should be less than: %d\n",
8998 BTRFS_SUPER_MIRROR_MAX);
9001 bytenr = btrfs_sb_offset(((int)num));
9002 printf("using SB copy %llu, bytenr %llu\n", num,
9003 (unsigned long long)bytenr);
9009 subvolid = arg_strtou64(optarg);
9012 tree_root_bytenr = arg_strtou64(optarg);
9016 usage(cmd_check_usage);
9018 printf("enabling repair mode\n");
9020 ctree_flags |= OPEN_CTREE_WRITES;
9026 printf("Creating a new CRC tree\n");
9029 ctree_flags |= OPEN_CTREE_WRITES;
9031 case OPT_INIT_EXTENT:
9032 init_extent_tree = 1;
9033 ctree_flags |= (OPEN_CTREE_WRITES |
9034 OPEN_CTREE_NO_BLOCK_GROUPS);
9037 case OPT_CHECK_CSUM:
9038 check_data_csum = 1;
9042 argc = argc - optind;
9044 if (check_argc_exact(argc, 1))
9045 usage(cmd_check_usage);
9047 /* This check is the only reason for --readonly to exist */
9048 if (readonly && repair) {
9049 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9054 cache_tree_init(&root_cache);
9056 if((ret = check_mounted(argv[optind])) < 0) {
9057 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9060 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9065 /* only allow partial opening under repair mode */
9067 ctree_flags |= OPEN_CTREE_PARTIAL;
9069 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9072 fprintf(stderr, "Couldn't open file system\n");
9077 root = info->fs_root;
9080 * repair mode will force us to commit transaction which
9081 * will make us fail to load log tree when mounting.
9083 if (repair && btrfs_super_log_root(info->super_copy)) {
9084 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9089 ret = zero_log_tree(root);
9091 fprintf(stderr, "fail to zero log tree\n");
9096 uuid_unparse(info->super_copy->fsid, uuidbuf);
9097 if (qgroup_report) {
9098 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9100 ret = qgroup_verify_all(info);
9102 print_qgroup_report(1);
9106 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9107 subvolid, argv[optind], uuidbuf);
9108 ret = print_extent_state(info, subvolid);
9111 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9113 if (!extent_buffer_uptodate(info->tree_root->node) ||
9114 !extent_buffer_uptodate(info->dev_root->node) ||
9115 !extent_buffer_uptodate(info->chunk_root->node)) {
9116 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9121 if (init_extent_tree || init_csum_tree) {
9122 struct btrfs_trans_handle *trans;
9124 trans = btrfs_start_transaction(info->extent_root, 0);
9125 if (IS_ERR(trans)) {
9126 fprintf(stderr, "Error starting transaction\n");
9127 ret = PTR_ERR(trans);
9131 if (init_extent_tree) {
9132 printf("Creating a new extent tree\n");
9133 ret = reinit_extent_tree(trans, info);
9138 if (init_csum_tree) {
9139 fprintf(stderr, "Reinit crc root\n");
9140 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9142 fprintf(stderr, "crc root initialization failed\n");
9147 ret = fill_csum_tree(trans, info->csum_root);
9149 fprintf(stderr, "crc refilling failed\n");
9154 * Ok now we commit and run the normal fsck, which will add
9155 * extent entries for all of the items it finds.
9157 ret = btrfs_commit_transaction(trans, info->extent_root);
9161 if (!extent_buffer_uptodate(info->extent_root->node)) {
9162 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9166 if (!extent_buffer_uptodate(info->csum_root->node)) {
9167 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9172 fprintf(stderr, "checking extents\n");
9173 ret = check_chunks_and_extents(root);
9175 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9177 ret = repair_root_items(info);
9181 fprintf(stderr, "Fixed %d roots.\n", ret);
9183 } else if (ret > 0) {
9185 "Found %d roots with an outdated root item.\n",
9188 "Please run a filesystem check with the option --repair to fix them.\n");
9193 fprintf(stderr, "checking free space cache\n");
9194 ret = check_space_cache(root);
9199 * We used to have to have these hole extents in between our real
9200 * extents so if we don't have this flag set we need to make sure there
9201 * are no gaps in the file extents for inodes, otherwise we can just
9202 * ignore it when this happens.
9204 no_holes = btrfs_fs_incompat(root->fs_info,
9205 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9206 fprintf(stderr, "checking fs roots\n");
9207 ret = check_fs_roots(root, &root_cache);
9211 fprintf(stderr, "checking csums\n");
9212 ret = check_csums(root);
9216 fprintf(stderr, "checking root refs\n");
9217 ret = check_root_refs(root, &root_cache);
9221 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9222 struct extent_buffer *eb;
9224 eb = list_first_entry(&root->fs_info->recow_ebs,
9225 struct extent_buffer, recow);
9226 list_del_init(&eb->recow);
9227 ret = recow_extent_buffer(root, eb);
9232 while (!list_empty(&delete_items)) {
9233 struct bad_item *bad;
9235 bad = list_first_entry(&delete_items, struct bad_item, list);
9236 list_del_init(&bad->list);
9238 ret = delete_bad_item(root, bad);
9242 if (info->quota_enabled) {
9244 fprintf(stderr, "checking quota groups\n");
9245 err = qgroup_verify_all(info);
9250 if (!list_empty(&root->fs_info->recow_ebs)) {
9251 fprintf(stderr, "Transid errors in file system\n");
9255 print_qgroup_report(0);
9256 if (found_old_backref) { /*
9257 * there was a disk format change when mixed
9258 * backref was in testing tree. The old format
9259 * existed about one week.
9261 printf("\n * Found old mixed backref format. "
9262 "The old format is not supported! *"
9263 "\n * Please mount the FS in readonly mode, "
9264 "backup data and re-format the FS. *\n\n");
9267 printf("found %llu bytes used err is %d\n",
9268 (unsigned long long)bytes_used, ret);
9269 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9270 printf("total tree bytes: %llu\n",
9271 (unsigned long long)total_btree_bytes);
9272 printf("total fs tree bytes: %llu\n",
9273 (unsigned long long)total_fs_tree_bytes);
9274 printf("total extent tree bytes: %llu\n",
9275 (unsigned long long)total_extent_tree_bytes);
9276 printf("btree space waste bytes: %llu\n",
9277 (unsigned long long)btree_space_waste);
9278 printf("file data blocks allocated: %llu\n referenced %llu\n",
9279 (unsigned long long)data_bytes_allocated,
9280 (unsigned long long)data_bytes_referenced);
9281 printf("%s\n", PACKAGE_STRING);
9283 free_root_recs_tree(&root_cache);