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 remove_cache_extent(extent_cache, cache);
3672 free_all_extent_backrefs(rec);
3677 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3678 struct extent_record *rec)
3680 if (rec->content_checked && rec->owner_ref_checked &&
3681 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3682 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
3683 remove_cache_extent(extent_cache, &rec->cache);
3684 free_all_extent_backrefs(rec);
3685 list_del_init(&rec->list);
3691 static int check_owner_ref(struct btrfs_root *root,
3692 struct extent_record *rec,
3693 struct extent_buffer *buf)
3695 struct extent_backref *node;
3696 struct tree_backref *back;
3697 struct btrfs_root *ref_root;
3698 struct btrfs_key key;
3699 struct btrfs_path path;
3700 struct extent_buffer *parent;
3705 list_for_each_entry(node, &rec->backrefs, list) {
3708 if (!node->found_ref)
3710 if (node->full_backref)
3712 back = (struct tree_backref *)node;
3713 if (btrfs_header_owner(buf) == back->root)
3716 BUG_ON(rec->is_root);
3718 /* try to find the block by search corresponding fs tree */
3719 key.objectid = btrfs_header_owner(buf);
3720 key.type = BTRFS_ROOT_ITEM_KEY;
3721 key.offset = (u64)-1;
3723 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3724 if (IS_ERR(ref_root))
3727 level = btrfs_header_level(buf);
3729 btrfs_item_key_to_cpu(buf, &key, 0);
3731 btrfs_node_key_to_cpu(buf, &key, 0);
3733 btrfs_init_path(&path);
3734 path.lowest_level = level + 1;
3735 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3739 parent = path.nodes[level + 1];
3740 if (parent && buf->start == btrfs_node_blockptr(parent,
3741 path.slots[level + 1]))
3744 btrfs_release_path(&path);
3745 return found ? 0 : 1;
3748 static int is_extent_tree_record(struct extent_record *rec)
3750 struct list_head *cur = rec->backrefs.next;
3751 struct extent_backref *node;
3752 struct tree_backref *back;
3755 while(cur != &rec->backrefs) {
3756 node = list_entry(cur, struct extent_backref, list);
3760 back = (struct tree_backref *)node;
3761 if (node->full_backref)
3763 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3770 static int record_bad_block_io(struct btrfs_fs_info *info,
3771 struct cache_tree *extent_cache,
3774 struct extent_record *rec;
3775 struct cache_extent *cache;
3776 struct btrfs_key key;
3778 cache = lookup_cache_extent(extent_cache, start, len);
3782 rec = container_of(cache, struct extent_record, cache);
3783 if (!is_extent_tree_record(rec))
3786 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3787 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3790 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3791 struct extent_buffer *buf, int slot)
3793 if (btrfs_header_level(buf)) {
3794 struct btrfs_key_ptr ptr1, ptr2;
3796 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3797 sizeof(struct btrfs_key_ptr));
3798 read_extent_buffer(buf, &ptr2,
3799 btrfs_node_key_ptr_offset(slot + 1),
3800 sizeof(struct btrfs_key_ptr));
3801 write_extent_buffer(buf, &ptr1,
3802 btrfs_node_key_ptr_offset(slot + 1),
3803 sizeof(struct btrfs_key_ptr));
3804 write_extent_buffer(buf, &ptr2,
3805 btrfs_node_key_ptr_offset(slot),
3806 sizeof(struct btrfs_key_ptr));
3808 struct btrfs_disk_key key;
3809 btrfs_node_key(buf, &key, 0);
3810 btrfs_fixup_low_keys(root, path, &key,
3811 btrfs_header_level(buf) + 1);
3814 struct btrfs_item *item1, *item2;
3815 struct btrfs_key k1, k2;
3816 char *item1_data, *item2_data;
3817 u32 item1_offset, item2_offset, item1_size, item2_size;
3819 item1 = btrfs_item_nr(slot);
3820 item2 = btrfs_item_nr(slot + 1);
3821 btrfs_item_key_to_cpu(buf, &k1, slot);
3822 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3823 item1_offset = btrfs_item_offset(buf, item1);
3824 item2_offset = btrfs_item_offset(buf, item2);
3825 item1_size = btrfs_item_size(buf, item1);
3826 item2_size = btrfs_item_size(buf, item2);
3828 item1_data = malloc(item1_size);
3831 item2_data = malloc(item2_size);
3837 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3838 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3840 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3841 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3845 btrfs_set_item_offset(buf, item1, item2_offset);
3846 btrfs_set_item_offset(buf, item2, item1_offset);
3847 btrfs_set_item_size(buf, item1, item2_size);
3848 btrfs_set_item_size(buf, item2, item1_size);
3850 path->slots[0] = slot;
3851 btrfs_set_item_key_unsafe(root, path, &k2);
3852 path->slots[0] = slot + 1;
3853 btrfs_set_item_key_unsafe(root, path, &k1);
3858 static int fix_key_order(struct btrfs_trans_handle *trans,
3859 struct btrfs_root *root,
3860 struct btrfs_path *path)
3862 struct extent_buffer *buf;
3863 struct btrfs_key k1, k2;
3865 int level = path->lowest_level;
3868 buf = path->nodes[level];
3869 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3871 btrfs_node_key_to_cpu(buf, &k1, i);
3872 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3874 btrfs_item_key_to_cpu(buf, &k1, i);
3875 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3877 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3879 ret = swap_values(root, path, buf, i);
3882 btrfs_mark_buffer_dirty(buf);
3888 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3889 struct btrfs_root *root,
3890 struct btrfs_path *path,
3891 struct extent_buffer *buf, int slot)
3893 struct btrfs_key key;
3894 int nritems = btrfs_header_nritems(buf);
3896 btrfs_item_key_to_cpu(buf, &key, slot);
3898 /* These are all the keys we can deal with missing. */
3899 if (key.type != BTRFS_DIR_INDEX_KEY &&
3900 key.type != BTRFS_EXTENT_ITEM_KEY &&
3901 key.type != BTRFS_METADATA_ITEM_KEY &&
3902 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3903 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3906 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3907 (unsigned long long)key.objectid, key.type,
3908 (unsigned long long)key.offset, slot, buf->start);
3909 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3910 btrfs_item_nr_offset(slot + 1),
3911 sizeof(struct btrfs_item) *
3912 (nritems - slot - 1));
3913 btrfs_set_header_nritems(buf, nritems - 1);
3915 struct btrfs_disk_key disk_key;
3917 btrfs_item_key(buf, &disk_key, 0);
3918 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3920 btrfs_mark_buffer_dirty(buf);
3924 static int fix_item_offset(struct btrfs_trans_handle *trans,
3925 struct btrfs_root *root,
3926 struct btrfs_path *path)
3928 struct extent_buffer *buf;
3932 /* We should only get this for leaves */
3933 BUG_ON(path->lowest_level);
3934 buf = path->nodes[0];
3936 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3937 unsigned int shift = 0, offset;
3939 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3940 BTRFS_LEAF_DATA_SIZE(root)) {
3941 if (btrfs_item_end_nr(buf, i) >
3942 BTRFS_LEAF_DATA_SIZE(root)) {
3943 ret = delete_bogus_item(trans, root, path,
3947 fprintf(stderr, "item is off the end of the "
3948 "leaf, can't fix\n");
3952 shift = BTRFS_LEAF_DATA_SIZE(root) -
3953 btrfs_item_end_nr(buf, i);
3954 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
3955 btrfs_item_offset_nr(buf, i - 1)) {
3956 if (btrfs_item_end_nr(buf, i) >
3957 btrfs_item_offset_nr(buf, i - 1)) {
3958 ret = delete_bogus_item(trans, root, path,
3962 fprintf(stderr, "items overlap, can't fix\n");
3966 shift = btrfs_item_offset_nr(buf, i - 1) -
3967 btrfs_item_end_nr(buf, i);
3972 printf("Shifting item nr %d by %u bytes in block %llu\n",
3973 i, shift, (unsigned long long)buf->start);
3974 offset = btrfs_item_offset_nr(buf, i);
3975 memmove_extent_buffer(buf,
3976 btrfs_leaf_data(buf) + offset + shift,
3977 btrfs_leaf_data(buf) + offset,
3978 btrfs_item_size_nr(buf, i));
3979 btrfs_set_item_offset(buf, btrfs_item_nr(i),
3981 btrfs_mark_buffer_dirty(buf);
3985 * We may have moved things, in which case we want to exit so we don't
3986 * write those changes out. Once we have proper abort functionality in
3987 * progs this can be changed to something nicer.
3994 * Attempt to fix basic block failures. If we can't fix it for whatever reason
3995 * then just return -EIO.
3997 static int try_to_fix_bad_block(struct btrfs_root *root,
3998 struct extent_buffer *buf,
3999 enum btrfs_tree_block_status status)
4001 struct btrfs_trans_handle *trans;
4002 struct ulist *roots;
4003 struct ulist_node *node;
4004 struct btrfs_root *search_root;
4005 struct btrfs_path *path;
4006 struct ulist_iterator iter;
4007 struct btrfs_key root_key, key;
4010 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4011 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4014 path = btrfs_alloc_path();
4018 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4021 btrfs_free_path(path);
4025 ULIST_ITER_INIT(&iter);
4026 while ((node = ulist_next(roots, &iter))) {
4027 root_key.objectid = node->val;
4028 root_key.type = BTRFS_ROOT_ITEM_KEY;
4029 root_key.offset = (u64)-1;
4031 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4038 trans = btrfs_start_transaction(search_root, 0);
4039 if (IS_ERR(trans)) {
4040 ret = PTR_ERR(trans);
4044 path->lowest_level = btrfs_header_level(buf);
4045 path->skip_check_block = 1;
4046 if (path->lowest_level)
4047 btrfs_node_key_to_cpu(buf, &key, 0);
4049 btrfs_item_key_to_cpu(buf, &key, 0);
4050 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4053 btrfs_commit_transaction(trans, search_root);
4056 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4057 ret = fix_key_order(trans, search_root, path);
4058 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4059 ret = fix_item_offset(trans, search_root, path);
4061 btrfs_commit_transaction(trans, search_root);
4064 btrfs_release_path(path);
4065 btrfs_commit_transaction(trans, search_root);
4068 btrfs_free_path(path);
4072 static int check_block(struct btrfs_root *root,
4073 struct cache_tree *extent_cache,
4074 struct extent_buffer *buf, u64 flags)
4076 struct extent_record *rec;
4077 struct cache_extent *cache;
4078 struct btrfs_key key;
4079 enum btrfs_tree_block_status status;
4083 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4086 rec = container_of(cache, struct extent_record, cache);
4087 rec->generation = btrfs_header_generation(buf);
4089 level = btrfs_header_level(buf);
4090 if (btrfs_header_nritems(buf) > 0) {
4093 btrfs_item_key_to_cpu(buf, &key, 0);
4095 btrfs_node_key_to_cpu(buf, &key, 0);
4097 rec->info_objectid = key.objectid;
4099 rec->info_level = level;
4101 if (btrfs_is_leaf(buf))
4102 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4104 status = btrfs_check_node(root, &rec->parent_key, buf);
4106 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4108 status = try_to_fix_bad_block(root, buf, status);
4109 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4111 fprintf(stderr, "bad block %llu\n",
4112 (unsigned long long)buf->start);
4115 * Signal to callers we need to start the scan over
4116 * again since we'll have cow'ed blocks.
4121 rec->content_checked = 1;
4122 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4123 rec->owner_ref_checked = 1;
4125 ret = check_owner_ref(root, rec, buf);
4127 rec->owner_ref_checked = 1;
4131 maybe_free_extent_rec(extent_cache, rec);
4135 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4136 u64 parent, u64 root)
4138 struct list_head *cur = rec->backrefs.next;
4139 struct extent_backref *node;
4140 struct tree_backref *back;
4142 while(cur != &rec->backrefs) {
4143 node = list_entry(cur, struct extent_backref, list);
4147 back = (struct tree_backref *)node;
4149 if (!node->full_backref)
4151 if (parent == back->parent)
4154 if (node->full_backref)
4156 if (back->root == root)
4163 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4164 u64 parent, u64 root)
4166 struct tree_backref *ref = malloc(sizeof(*ref));
4167 memset(&ref->node, 0, sizeof(ref->node));
4169 ref->parent = parent;
4170 ref->node.full_backref = 1;
4173 ref->node.full_backref = 0;
4175 list_add_tail(&ref->node.list, &rec->backrefs);
4180 static struct data_backref *find_data_backref(struct extent_record *rec,
4181 u64 parent, u64 root,
4182 u64 owner, u64 offset,
4184 u64 disk_bytenr, u64 bytes)
4186 struct list_head *cur = rec->backrefs.next;
4187 struct extent_backref *node;
4188 struct data_backref *back;
4190 while(cur != &rec->backrefs) {
4191 node = list_entry(cur, struct extent_backref, list);
4195 back = (struct data_backref *)node;
4197 if (!node->full_backref)
4199 if (parent == back->parent)
4202 if (node->full_backref)
4204 if (back->root == root && back->owner == owner &&
4205 back->offset == offset) {
4206 if (found_ref && node->found_ref &&
4207 (back->bytes != bytes ||
4208 back->disk_bytenr != disk_bytenr))
4217 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4218 u64 parent, u64 root,
4219 u64 owner, u64 offset,
4222 struct data_backref *ref = malloc(sizeof(*ref));
4223 memset(&ref->node, 0, sizeof(ref->node));
4224 ref->node.is_data = 1;
4227 ref->parent = parent;
4230 ref->node.full_backref = 1;
4234 ref->offset = offset;
4235 ref->node.full_backref = 0;
4237 ref->bytes = max_size;
4240 list_add_tail(&ref->node.list, &rec->backrefs);
4241 if (max_size > rec->max_size)
4242 rec->max_size = max_size;
4246 static int add_extent_rec(struct cache_tree *extent_cache,
4247 struct btrfs_key *parent_key, u64 parent_gen,
4248 u64 start, u64 nr, u64 extent_item_refs,
4249 int is_root, int inc_ref, int set_checked,
4250 int metadata, int extent_rec, u64 max_size)
4252 struct extent_record *rec;
4253 struct cache_extent *cache;
4257 cache = lookup_cache_extent(extent_cache, start, nr);
4259 rec = container_of(cache, struct extent_record, cache);
4263 rec->nr = max(nr, max_size);
4266 * We need to make sure to reset nr to whatever the extent
4267 * record says was the real size, this way we can compare it to
4271 if (start != rec->start || rec->found_rec) {
4272 struct extent_record *tmp;
4275 if (list_empty(&rec->list))
4276 list_add_tail(&rec->list,
4277 &duplicate_extents);
4280 * We have to do this song and dance in case we
4281 * find an extent record that falls inside of
4282 * our current extent record but does not have
4283 * the same objectid.
4285 tmp = malloc(sizeof(*tmp));
4289 tmp->max_size = max_size;
4292 tmp->metadata = metadata;
4293 tmp->extent_item_refs = extent_item_refs;
4294 INIT_LIST_HEAD(&tmp->list);
4295 list_add_tail(&tmp->list, &rec->dups);
4296 rec->num_duplicates++;
4303 if (extent_item_refs && !dup) {
4304 if (rec->extent_item_refs) {
4305 fprintf(stderr, "block %llu rec "
4306 "extent_item_refs %llu, passed %llu\n",
4307 (unsigned long long)start,
4308 (unsigned long long)
4309 rec->extent_item_refs,
4310 (unsigned long long)extent_item_refs);
4312 rec->extent_item_refs = extent_item_refs;
4317 rec->content_checked = 1;
4318 rec->owner_ref_checked = 1;
4322 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4324 rec->parent_generation = parent_gen;
4326 if (rec->max_size < max_size)
4327 rec->max_size = max_size;
4329 maybe_free_extent_rec(extent_cache, rec);
4332 rec = malloc(sizeof(*rec));
4334 rec->max_size = max_size;
4335 rec->nr = max(nr, max_size);
4336 rec->found_rec = !!extent_rec;
4337 rec->content_checked = 0;
4338 rec->owner_ref_checked = 0;
4339 rec->num_duplicates = 0;
4340 rec->metadata = metadata;
4341 INIT_LIST_HEAD(&rec->backrefs);
4342 INIT_LIST_HEAD(&rec->dups);
4343 INIT_LIST_HEAD(&rec->list);
4355 if (extent_item_refs)
4356 rec->extent_item_refs = extent_item_refs;
4358 rec->extent_item_refs = 0;
4361 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4363 memset(&rec->parent_key, 0, sizeof(*parent_key));
4366 rec->parent_generation = parent_gen;
4368 rec->parent_generation = 0;
4370 rec->cache.start = start;
4371 rec->cache.size = nr;
4372 ret = insert_cache_extent(extent_cache, &rec->cache);
4376 rec->content_checked = 1;
4377 rec->owner_ref_checked = 1;
4382 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4383 u64 parent, u64 root, int found_ref)
4385 struct extent_record *rec;
4386 struct tree_backref *back;
4387 struct cache_extent *cache;
4389 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4391 add_extent_rec(extent_cache, NULL, 0, bytenr,
4392 1, 0, 0, 0, 0, 1, 0, 0);
4393 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4398 rec = container_of(cache, struct extent_record, cache);
4399 if (rec->start != bytenr) {
4403 back = find_tree_backref(rec, parent, root);
4405 back = alloc_tree_backref(rec, parent, root);
4408 if (back->node.found_ref) {
4409 fprintf(stderr, "Extent back ref already exists "
4410 "for %llu parent %llu root %llu \n",
4411 (unsigned long long)bytenr,
4412 (unsigned long long)parent,
4413 (unsigned long long)root);
4415 back->node.found_ref = 1;
4417 if (back->node.found_extent_tree) {
4418 fprintf(stderr, "Extent back ref already exists "
4419 "for %llu parent %llu root %llu \n",
4420 (unsigned long long)bytenr,
4421 (unsigned long long)parent,
4422 (unsigned long long)root);
4424 back->node.found_extent_tree = 1;
4426 maybe_free_extent_rec(extent_cache, rec);
4430 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4431 u64 parent, u64 root, u64 owner, u64 offset,
4432 u32 num_refs, int found_ref, u64 max_size)
4434 struct extent_record *rec;
4435 struct data_backref *back;
4436 struct cache_extent *cache;
4438 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4440 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4442 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4447 rec = container_of(cache, struct extent_record, cache);
4448 if (rec->max_size < max_size)
4449 rec->max_size = max_size;
4452 * If found_ref is set then max_size is the real size and must match the
4453 * existing refs. So if we have already found a ref then we need to
4454 * make sure that this ref matches the existing one, otherwise we need
4455 * to add a new backref so we can notice that the backrefs don't match
4456 * and we need to figure out who is telling the truth. This is to
4457 * account for that awful fsync bug I introduced where we'd end up with
4458 * a btrfs_file_extent_item that would have its length include multiple
4459 * prealloc extents or point inside of a prealloc extent.
4461 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4464 back = alloc_data_backref(rec, parent, root, owner, offset,
4468 BUG_ON(num_refs != 1);
4469 if (back->node.found_ref)
4470 BUG_ON(back->bytes != max_size);
4471 back->node.found_ref = 1;
4472 back->found_ref += 1;
4473 back->bytes = max_size;
4474 back->disk_bytenr = bytenr;
4476 rec->content_checked = 1;
4477 rec->owner_ref_checked = 1;
4479 if (back->node.found_extent_tree) {
4480 fprintf(stderr, "Extent back ref already exists "
4481 "for %llu parent %llu root %llu "
4482 "owner %llu offset %llu num_refs %lu\n",
4483 (unsigned long long)bytenr,
4484 (unsigned long long)parent,
4485 (unsigned long long)root,
4486 (unsigned long long)owner,
4487 (unsigned long long)offset,
4488 (unsigned long)num_refs);
4490 back->num_refs = num_refs;
4491 back->node.found_extent_tree = 1;
4493 maybe_free_extent_rec(extent_cache, rec);
4497 static int add_pending(struct cache_tree *pending,
4498 struct cache_tree *seen, u64 bytenr, u32 size)
4501 ret = add_cache_extent(seen, bytenr, size);
4504 add_cache_extent(pending, bytenr, size);
4508 static int pick_next_pending(struct cache_tree *pending,
4509 struct cache_tree *reada,
4510 struct cache_tree *nodes,
4511 u64 last, struct block_info *bits, int bits_nr,
4514 unsigned long node_start = last;
4515 struct cache_extent *cache;
4518 cache = search_cache_extent(reada, 0);
4520 bits[0].start = cache->start;
4521 bits[0].size = cache->size;
4526 if (node_start > 32768)
4527 node_start -= 32768;
4529 cache = search_cache_extent(nodes, node_start);
4531 cache = search_cache_extent(nodes, 0);
4534 cache = search_cache_extent(pending, 0);
4539 bits[ret].start = cache->start;
4540 bits[ret].size = cache->size;
4541 cache = next_cache_extent(cache);
4543 } while (cache && ret < bits_nr);
4549 bits[ret].start = cache->start;
4550 bits[ret].size = cache->size;
4551 cache = next_cache_extent(cache);
4553 } while (cache && ret < bits_nr);
4555 if (bits_nr - ret > 8) {
4556 u64 lookup = bits[0].start + bits[0].size;
4557 struct cache_extent *next;
4558 next = search_cache_extent(pending, lookup);
4560 if (next->start - lookup > 32768)
4562 bits[ret].start = next->start;
4563 bits[ret].size = next->size;
4564 lookup = next->start + next->size;
4568 next = next_cache_extent(next);
4576 static void free_chunk_record(struct cache_extent *cache)
4578 struct chunk_record *rec;
4580 rec = container_of(cache, struct chunk_record, cache);
4581 list_del_init(&rec->list);
4582 list_del_init(&rec->dextents);
4586 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4588 cache_tree_free_extents(chunk_cache, free_chunk_record);
4591 static void free_device_record(struct rb_node *node)
4593 struct device_record *rec;
4595 rec = container_of(node, struct device_record, node);
4599 FREE_RB_BASED_TREE(device_cache, free_device_record);
4601 int insert_block_group_record(struct block_group_tree *tree,
4602 struct block_group_record *bg_rec)
4606 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4610 list_add_tail(&bg_rec->list, &tree->block_groups);
4614 static void free_block_group_record(struct cache_extent *cache)
4616 struct block_group_record *rec;
4618 rec = container_of(cache, struct block_group_record, cache);
4619 list_del_init(&rec->list);
4623 void free_block_group_tree(struct block_group_tree *tree)
4625 cache_tree_free_extents(&tree->tree, free_block_group_record);
4628 int insert_device_extent_record(struct device_extent_tree *tree,
4629 struct device_extent_record *de_rec)
4634 * Device extent is a bit different from the other extents, because
4635 * the extents which belong to the different devices may have the
4636 * same start and size, so we need use the special extent cache
4637 * search/insert functions.
4639 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4643 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4644 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4648 static void free_device_extent_record(struct cache_extent *cache)
4650 struct device_extent_record *rec;
4652 rec = container_of(cache, struct device_extent_record, cache);
4653 if (!list_empty(&rec->chunk_list))
4654 list_del_init(&rec->chunk_list);
4655 if (!list_empty(&rec->device_list))
4656 list_del_init(&rec->device_list);
4660 void free_device_extent_tree(struct device_extent_tree *tree)
4662 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4665 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4666 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4667 struct extent_buffer *leaf, int slot)
4669 struct btrfs_extent_ref_v0 *ref0;
4670 struct btrfs_key key;
4672 btrfs_item_key_to_cpu(leaf, &key, slot);
4673 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4674 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4675 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4677 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4678 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4684 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4685 struct btrfs_key *key,
4688 struct btrfs_chunk *ptr;
4689 struct chunk_record *rec;
4692 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4693 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4695 rec = malloc(btrfs_chunk_record_size(num_stripes));
4697 fprintf(stderr, "memory allocation failed\n");
4701 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4703 INIT_LIST_HEAD(&rec->list);
4704 INIT_LIST_HEAD(&rec->dextents);
4707 rec->cache.start = key->offset;
4708 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4710 rec->generation = btrfs_header_generation(leaf);
4712 rec->objectid = key->objectid;
4713 rec->type = key->type;
4714 rec->offset = key->offset;
4716 rec->length = rec->cache.size;
4717 rec->owner = btrfs_chunk_owner(leaf, ptr);
4718 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4719 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4720 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4721 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4722 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4723 rec->num_stripes = num_stripes;
4724 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4726 for (i = 0; i < rec->num_stripes; ++i) {
4727 rec->stripes[i].devid =
4728 btrfs_stripe_devid_nr(leaf, ptr, i);
4729 rec->stripes[i].offset =
4730 btrfs_stripe_offset_nr(leaf, ptr, i);
4731 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4732 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4739 static int process_chunk_item(struct cache_tree *chunk_cache,
4740 struct btrfs_key *key, struct extent_buffer *eb,
4743 struct chunk_record *rec;
4746 rec = btrfs_new_chunk_record(eb, key, slot);
4747 ret = insert_cache_extent(chunk_cache, &rec->cache);
4749 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4750 rec->offset, rec->length);
4757 static int process_device_item(struct rb_root *dev_cache,
4758 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4760 struct btrfs_dev_item *ptr;
4761 struct device_record *rec;
4764 ptr = btrfs_item_ptr(eb,
4765 slot, struct btrfs_dev_item);
4767 rec = malloc(sizeof(*rec));
4769 fprintf(stderr, "memory allocation failed\n");
4773 rec->devid = key->offset;
4774 rec->generation = btrfs_header_generation(eb);
4776 rec->objectid = key->objectid;
4777 rec->type = key->type;
4778 rec->offset = key->offset;
4780 rec->devid = btrfs_device_id(eb, ptr);
4781 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4782 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4784 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4786 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4793 struct block_group_record *
4794 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4797 struct btrfs_block_group_item *ptr;
4798 struct block_group_record *rec;
4800 rec = malloc(sizeof(*rec));
4802 fprintf(stderr, "memory allocation failed\n");
4805 memset(rec, 0, sizeof(*rec));
4807 rec->cache.start = key->objectid;
4808 rec->cache.size = key->offset;
4810 rec->generation = btrfs_header_generation(leaf);
4812 rec->objectid = key->objectid;
4813 rec->type = key->type;
4814 rec->offset = key->offset;
4816 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4817 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4819 INIT_LIST_HEAD(&rec->list);
4824 static int process_block_group_item(struct block_group_tree *block_group_cache,
4825 struct btrfs_key *key,
4826 struct extent_buffer *eb, int slot)
4828 struct block_group_record *rec;
4831 rec = btrfs_new_block_group_record(eb, key, slot);
4832 ret = insert_block_group_record(block_group_cache, rec);
4834 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4835 rec->objectid, rec->offset);
4842 struct device_extent_record *
4843 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4844 struct btrfs_key *key, int slot)
4846 struct device_extent_record *rec;
4847 struct btrfs_dev_extent *ptr;
4849 rec = malloc(sizeof(*rec));
4851 fprintf(stderr, "memory allocation failed\n");
4854 memset(rec, 0, sizeof(*rec));
4856 rec->cache.objectid = key->objectid;
4857 rec->cache.start = key->offset;
4859 rec->generation = btrfs_header_generation(leaf);
4861 rec->objectid = key->objectid;
4862 rec->type = key->type;
4863 rec->offset = key->offset;
4865 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4866 rec->chunk_objecteid =
4867 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4869 btrfs_dev_extent_chunk_offset(leaf, ptr);
4870 rec->length = btrfs_dev_extent_length(leaf, ptr);
4871 rec->cache.size = rec->length;
4873 INIT_LIST_HEAD(&rec->chunk_list);
4874 INIT_LIST_HEAD(&rec->device_list);
4880 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4881 struct btrfs_key *key, struct extent_buffer *eb,
4884 struct device_extent_record *rec;
4887 rec = btrfs_new_device_extent_record(eb, key, slot);
4888 ret = insert_device_extent_record(dev_extent_cache, rec);
4891 "Device extent[%llu, %llu, %llu] existed.\n",
4892 rec->objectid, rec->offset, rec->length);
4899 static int process_extent_item(struct btrfs_root *root,
4900 struct cache_tree *extent_cache,
4901 struct extent_buffer *eb, int slot)
4903 struct btrfs_extent_item *ei;
4904 struct btrfs_extent_inline_ref *iref;
4905 struct btrfs_extent_data_ref *dref;
4906 struct btrfs_shared_data_ref *sref;
4907 struct btrfs_key key;
4911 u32 item_size = btrfs_item_size_nr(eb, slot);
4917 btrfs_item_key_to_cpu(eb, &key, slot);
4919 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4921 num_bytes = root->leafsize;
4923 num_bytes = key.offset;
4926 if (item_size < sizeof(*ei)) {
4927 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4928 struct btrfs_extent_item_v0 *ei0;
4929 BUG_ON(item_size != sizeof(*ei0));
4930 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4931 refs = btrfs_extent_refs_v0(eb, ei0);
4935 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4936 num_bytes, refs, 0, 0, 0, metadata, 1,
4940 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4941 refs = btrfs_extent_refs(eb, ei);
4943 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
4944 refs, 0, 0, 0, metadata, 1, num_bytes);
4946 ptr = (unsigned long)(ei + 1);
4947 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
4948 key.type == BTRFS_EXTENT_ITEM_KEY)
4949 ptr += sizeof(struct btrfs_tree_block_info);
4951 end = (unsigned long)ei + item_size;
4953 iref = (struct btrfs_extent_inline_ref *)ptr;
4954 type = btrfs_extent_inline_ref_type(eb, iref);
4955 offset = btrfs_extent_inline_ref_offset(eb, iref);
4957 case BTRFS_TREE_BLOCK_REF_KEY:
4958 add_tree_backref(extent_cache, key.objectid,
4961 case BTRFS_SHARED_BLOCK_REF_KEY:
4962 add_tree_backref(extent_cache, key.objectid,
4965 case BTRFS_EXTENT_DATA_REF_KEY:
4966 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
4967 add_data_backref(extent_cache, key.objectid, 0,
4968 btrfs_extent_data_ref_root(eb, dref),
4969 btrfs_extent_data_ref_objectid(eb,
4971 btrfs_extent_data_ref_offset(eb, dref),
4972 btrfs_extent_data_ref_count(eb, dref),
4975 case BTRFS_SHARED_DATA_REF_KEY:
4976 sref = (struct btrfs_shared_data_ref *)(iref + 1);
4977 add_data_backref(extent_cache, key.objectid, offset,
4979 btrfs_shared_data_ref_count(eb, sref),
4983 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
4984 key.objectid, key.type, num_bytes);
4987 ptr += btrfs_extent_inline_ref_size(type);
4994 static int check_cache_range(struct btrfs_root *root,
4995 struct btrfs_block_group_cache *cache,
4996 u64 offset, u64 bytes)
4998 struct btrfs_free_space *entry;
5004 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5005 bytenr = btrfs_sb_offset(i);
5006 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5007 cache->key.objectid, bytenr, 0,
5008 &logical, &nr, &stripe_len);
5013 if (logical[nr] + stripe_len <= offset)
5015 if (offset + bytes <= logical[nr])
5017 if (logical[nr] == offset) {
5018 if (stripe_len >= bytes) {
5022 bytes -= stripe_len;
5023 offset += stripe_len;
5024 } else if (logical[nr] < offset) {
5025 if (logical[nr] + stripe_len >=
5030 bytes = (offset + bytes) -
5031 (logical[nr] + stripe_len);
5032 offset = logical[nr] + stripe_len;
5035 * Could be tricky, the super may land in the
5036 * middle of the area we're checking. First
5037 * check the easiest case, it's at the end.
5039 if (logical[nr] + stripe_len >=
5041 bytes = logical[nr] - offset;
5045 /* Check the left side */
5046 ret = check_cache_range(root, cache,
5048 logical[nr] - offset);
5054 /* Now we continue with the right side */
5055 bytes = (offset + bytes) -
5056 (logical[nr] + stripe_len);
5057 offset = logical[nr] + stripe_len;
5064 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5066 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5067 offset, offset+bytes);
5071 if (entry->offset != offset) {
5072 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5077 if (entry->bytes != bytes) {
5078 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5079 bytes, entry->bytes, offset);
5083 unlink_free_space(cache->free_space_ctl, entry);
5088 static int verify_space_cache(struct btrfs_root *root,
5089 struct btrfs_block_group_cache *cache)
5091 struct btrfs_path *path;
5092 struct extent_buffer *leaf;
5093 struct btrfs_key key;
5097 path = btrfs_alloc_path();
5101 root = root->fs_info->extent_root;
5103 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5105 key.objectid = last;
5107 key.type = BTRFS_EXTENT_ITEM_KEY;
5109 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5114 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5115 ret = btrfs_next_leaf(root, path);
5123 leaf = path->nodes[0];
5124 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5125 if (key.objectid >= cache->key.offset + cache->key.objectid)
5127 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5128 key.type != BTRFS_METADATA_ITEM_KEY) {
5133 if (last == key.objectid) {
5134 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5135 last = key.objectid + key.offset;
5137 last = key.objectid + root->leafsize;
5142 ret = check_cache_range(root, cache, last,
5143 key.objectid - last);
5146 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5147 last = key.objectid + key.offset;
5149 last = key.objectid + root->leafsize;
5153 if (last < cache->key.objectid + cache->key.offset)
5154 ret = check_cache_range(root, cache, last,
5155 cache->key.objectid +
5156 cache->key.offset - last);
5159 btrfs_free_path(path);
5162 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5163 fprintf(stderr, "There are still entries left in the space "
5171 static int check_space_cache(struct btrfs_root *root)
5173 struct btrfs_block_group_cache *cache;
5174 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5178 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5179 btrfs_super_generation(root->fs_info->super_copy) !=
5180 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5181 printf("cache and super generation don't match, space cache "
5182 "will be invalidated\n");
5187 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5191 start = cache->key.objectid + cache->key.offset;
5192 if (!cache->free_space_ctl) {
5193 if (btrfs_init_free_space_ctl(cache,
5194 root->sectorsize)) {
5199 btrfs_remove_free_space_cache(cache);
5202 ret = load_free_space_cache(root->fs_info, cache);
5206 ret = verify_space_cache(root, cache);
5208 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5209 cache->key.objectid);
5214 return error ? -EINVAL : 0;
5217 static int read_extent_data(struct btrfs_root *root, char *data,
5218 u64 logical, u64 *len, int mirror)
5221 struct btrfs_multi_bio *multi = NULL;
5222 struct btrfs_fs_info *info = root->fs_info;
5223 struct btrfs_device *device;
5227 ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
5228 &multi, mirror, NULL);
5230 fprintf(stderr, "Couldn't map the block %llu\n",
5234 device = multi->stripes[0].dev;
5236 if (device->fd == 0)
5241 ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
5251 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5252 u64 num_bytes, unsigned long leaf_offset,
5253 struct extent_buffer *eb) {
5256 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5258 unsigned long csum_offset;
5262 u64 data_checked = 0;
5268 if (num_bytes % root->sectorsize)
5271 data = malloc(num_bytes);
5275 while (offset < num_bytes) {
5278 read_len = num_bytes - offset;
5279 /* read as much space once a time */
5280 ret = read_extent_data(root, data + offset,
5281 bytenr + offset, &read_len, mirror);
5285 /* verify every 4k data's checksum */
5286 while (data_checked < read_len) {
5288 tmp = offset + data_checked;
5290 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5291 csum, root->sectorsize);
5292 btrfs_csum_final(csum, (char *)&csum);
5294 csum_offset = leaf_offset +
5295 tmp / root->sectorsize * csum_size;
5296 read_extent_buffer(eb, (char *)&csum_expected,
5297 csum_offset, csum_size);
5298 /* try another mirror */
5299 if (csum != csum_expected) {
5300 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5301 mirror, bytenr + tmp,
5302 csum, csum_expected);
5303 num_copies = btrfs_num_copies(
5304 &root->fs_info->mapping_tree,
5306 if (mirror < num_copies - 1) {
5311 data_checked += root->sectorsize;
5320 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5323 struct btrfs_path *path;
5324 struct extent_buffer *leaf;
5325 struct btrfs_key key;
5328 path = btrfs_alloc_path();
5330 fprintf(stderr, "Error allocing path\n");
5334 key.objectid = bytenr;
5335 key.type = BTRFS_EXTENT_ITEM_KEY;
5336 key.offset = (u64)-1;
5339 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5342 fprintf(stderr, "Error looking up extent record %d\n", ret);
5343 btrfs_free_path(path);
5346 if (path->slots[0] > 0) {
5349 ret = btrfs_prev_leaf(root, path);
5352 } else if (ret > 0) {
5359 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5362 * Block group items come before extent items if they have the same
5363 * bytenr, so walk back one more just in case. Dear future traveler,
5364 * first congrats on mastering time travel. Now if it's not too much
5365 * trouble could you go back to 2006 and tell Chris to make the
5366 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5367 * EXTENT_ITEM_KEY please?
5369 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5370 if (path->slots[0] > 0) {
5373 ret = btrfs_prev_leaf(root, path);
5376 } else if (ret > 0) {
5381 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5385 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5386 ret = btrfs_next_leaf(root, path);
5388 fprintf(stderr, "Error going to next leaf "
5390 btrfs_free_path(path);
5396 leaf = path->nodes[0];
5397 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5398 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5402 if (key.objectid + key.offset < bytenr) {
5406 if (key.objectid > bytenr + num_bytes)
5409 if (key.objectid == bytenr) {
5410 if (key.offset >= num_bytes) {
5414 num_bytes -= key.offset;
5415 bytenr += key.offset;
5416 } else if (key.objectid < bytenr) {
5417 if (key.objectid + key.offset >= bytenr + num_bytes) {
5421 num_bytes = (bytenr + num_bytes) -
5422 (key.objectid + key.offset);
5423 bytenr = key.objectid + key.offset;
5425 if (key.objectid + key.offset < bytenr + num_bytes) {
5426 u64 new_start = key.objectid + key.offset;
5427 u64 new_bytes = bytenr + num_bytes - new_start;
5430 * Weird case, the extent is in the middle of
5431 * our range, we'll have to search one side
5432 * and then the other. Not sure if this happens
5433 * in real life, but no harm in coding it up
5434 * anyway just in case.
5436 btrfs_release_path(path);
5437 ret = check_extent_exists(root, new_start,
5440 fprintf(stderr, "Right section didn't "
5444 num_bytes = key.objectid - bytenr;
5447 num_bytes = key.objectid - bytenr;
5454 if (num_bytes && !ret) {
5455 fprintf(stderr, "There are no extents for csum range "
5456 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5460 btrfs_free_path(path);
5464 static int check_csums(struct btrfs_root *root)
5466 struct btrfs_path *path;
5467 struct extent_buffer *leaf;
5468 struct btrfs_key key;
5469 u64 offset = 0, num_bytes = 0;
5470 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5474 unsigned long leaf_offset;
5476 root = root->fs_info->csum_root;
5477 if (!extent_buffer_uptodate(root->node)) {
5478 fprintf(stderr, "No valid csum tree found\n");
5482 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5483 key.type = BTRFS_EXTENT_CSUM_KEY;
5486 path = btrfs_alloc_path();
5490 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5492 fprintf(stderr, "Error searching csum tree %d\n", ret);
5493 btrfs_free_path(path);
5497 if (ret > 0 && path->slots[0])
5502 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5503 ret = btrfs_next_leaf(root, path);
5505 fprintf(stderr, "Error going to next leaf "
5512 leaf = path->nodes[0];
5514 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5515 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5520 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5521 csum_size) * root->sectorsize;
5522 if (!check_data_csum)
5523 goto skip_csum_check;
5524 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5525 ret = check_extent_csums(root, key.offset, data_len,
5531 offset = key.offset;
5532 } else if (key.offset != offset + num_bytes) {
5533 ret = check_extent_exists(root, offset, num_bytes);
5535 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5536 "there is no extent record\n",
5537 offset, offset+num_bytes);
5540 offset = key.offset;
5543 num_bytes += data_len;
5547 btrfs_free_path(path);
5551 static int is_dropped_key(struct btrfs_key *key,
5552 struct btrfs_key *drop_key) {
5553 if (key->objectid < drop_key->objectid)
5555 else if (key->objectid == drop_key->objectid) {
5556 if (key->type < drop_key->type)
5558 else if (key->type == drop_key->type) {
5559 if (key->offset < drop_key->offset)
5566 static int calc_extent_flag(struct btrfs_root *root,
5567 struct cache_tree *extent_cache,
5568 struct extent_buffer *buf,
5569 struct root_item_record *ri,
5573 int nritems = btrfs_header_nritems(buf);
5574 struct btrfs_key key;
5575 struct extent_record *rec;
5576 struct cache_extent *cache;
5577 struct data_backref *dback;
5578 struct tree_backref *tback;
5579 struct extent_buffer *new_buf;
5589 * Except file/reloc tree, we can not have
5592 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5597 if (buf->start == ri->bytenr)
5599 if (btrfs_is_leaf(buf)) {
5601 * we are searching from original root, world
5602 * peace is achieved, we use normal backref.
5604 owner = btrfs_header_owner(buf);
5605 if (owner == ri->objectid)
5608 * we check every eb here, and if any of
5609 * eb dosen't have original root refers
5610 * to this eb, we set full backref flag for
5611 * this extent, otherwise normal backref.
5613 for (i = 0; i < nritems; i++) {
5614 struct btrfs_file_extent_item *fi;
5615 btrfs_item_key_to_cpu(buf, &key, i);
5617 if (key.type != BTRFS_EXTENT_DATA_KEY)
5619 fi = btrfs_item_ptr(buf, i,
5620 struct btrfs_file_extent_item);
5621 if (btrfs_file_extent_type(buf, fi) ==
5622 BTRFS_FILE_EXTENT_INLINE)
5624 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5626 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
5627 cache = lookup_cache_extent(extent_cache, bytenr, 1);
5630 offset = btrfs_file_extent_offset(buf, fi);
5631 rec = container_of(cache, struct extent_record, cache);
5632 dback = find_data_backref(rec, 0, ri->objectid, owner,
5633 key.offset - offset, 1, bytenr, bytenr);
5639 level = btrfs_header_level(buf);
5640 for (i = 0; i < nritems; i++) {
5641 ptr = btrfs_node_blockptr(buf, i);
5642 size = btrfs_level_size(root, level);
5644 new_buf = read_tree_block(root, ptr, size, 0);
5645 if (!extent_buffer_uptodate(new_buf)) {
5646 free_extent_buffer(new_buf);
5651 * we are searching from origin root, world
5652 * peace is achieved, we use normal backref.
5654 owner = btrfs_header_owner(new_buf);
5655 free_extent_buffer(new_buf);
5656 if (owner == ri->objectid)
5659 cache = lookup_cache_extent(extent_cache, ptr, size);
5662 rec = container_of(cache, struct extent_record, cache);
5663 tback = find_tree_backref(rec, 0, owner);
5671 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5672 /* we have added this extent before */
5674 rec = container_of(cache, struct extent_record, cache);
5675 rec->flag_block_full_backref = 0;
5678 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5679 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5680 /* we have added this extent before */
5682 rec = container_of(cache, struct extent_record, cache);
5683 rec->flag_block_full_backref = 1;
5687 static int run_next_block(struct btrfs_root *root,
5688 struct block_info *bits,
5691 struct cache_tree *pending,
5692 struct cache_tree *seen,
5693 struct cache_tree *reada,
5694 struct cache_tree *nodes,
5695 struct cache_tree *extent_cache,
5696 struct cache_tree *chunk_cache,
5697 struct rb_root *dev_cache,
5698 struct block_group_tree *block_group_cache,
5699 struct device_extent_tree *dev_extent_cache,
5700 struct root_item_record *ri)
5702 struct extent_buffer *buf;
5703 struct extent_record *rec = NULL;
5714 struct btrfs_key key;
5715 struct cache_extent *cache;
5718 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5719 bits_nr, &reada_bits);
5724 for(i = 0; i < nritems; i++) {
5725 ret = add_cache_extent(reada, bits[i].start,
5730 /* fixme, get the parent transid */
5731 readahead_tree_block(root, bits[i].start,
5735 *last = bits[0].start;
5736 bytenr = bits[0].start;
5737 size = bits[0].size;
5739 cache = lookup_cache_extent(pending, bytenr, size);
5741 remove_cache_extent(pending, cache);
5744 cache = lookup_cache_extent(reada, bytenr, size);
5746 remove_cache_extent(reada, cache);
5749 cache = lookup_cache_extent(nodes, bytenr, size);
5751 remove_cache_extent(nodes, cache);
5754 cache = lookup_cache_extent(extent_cache, bytenr, size);
5756 rec = container_of(cache, struct extent_record, cache);
5757 gen = rec->parent_generation;
5760 /* fixme, get the real parent transid */
5761 buf = read_tree_block(root, bytenr, size, gen);
5762 if (!extent_buffer_uptodate(buf)) {
5763 record_bad_block_io(root->fs_info,
5764 extent_cache, bytenr, size);
5768 nritems = btrfs_header_nritems(buf);
5771 * FIXME, this only works only if we don't have any full
5775 if (!init_extent_tree) {
5776 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5777 btrfs_header_level(buf), 1, NULL,
5780 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5782 fprintf(stderr, "Couldn't calc extent flags\n");
5783 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5788 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5790 fprintf(stderr, "Couldn't calc extent flags\n");
5791 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5795 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5797 rec->flag_block_full_backref = 1;
5802 owner = btrfs_header_owner(buf);
5805 ret = check_block(root, extent_cache, buf, flags);
5809 if (btrfs_is_leaf(buf)) {
5810 btree_space_waste += btrfs_leaf_free_space(root, buf);
5811 for (i = 0; i < nritems; i++) {
5812 struct btrfs_file_extent_item *fi;
5813 btrfs_item_key_to_cpu(buf, &key, i);
5814 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5815 process_extent_item(root, extent_cache, buf,
5819 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5820 process_extent_item(root, extent_cache, buf,
5824 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5826 btrfs_item_size_nr(buf, i);
5829 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5830 process_chunk_item(chunk_cache, &key, buf, i);
5833 if (key.type == BTRFS_DEV_ITEM_KEY) {
5834 process_device_item(dev_cache, &key, buf, i);
5837 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5838 process_block_group_item(block_group_cache,
5842 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5843 process_device_extent_item(dev_extent_cache,
5848 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5849 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5850 process_extent_ref_v0(extent_cache, buf, i);
5857 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5858 add_tree_backref(extent_cache, key.objectid, 0,
5862 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5863 add_tree_backref(extent_cache, key.objectid,
5867 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5868 struct btrfs_extent_data_ref *ref;
5869 ref = btrfs_item_ptr(buf, i,
5870 struct btrfs_extent_data_ref);
5871 add_data_backref(extent_cache,
5873 btrfs_extent_data_ref_root(buf, ref),
5874 btrfs_extent_data_ref_objectid(buf,
5876 btrfs_extent_data_ref_offset(buf, ref),
5877 btrfs_extent_data_ref_count(buf, ref),
5878 0, root->sectorsize);
5881 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5882 struct btrfs_shared_data_ref *ref;
5883 ref = btrfs_item_ptr(buf, i,
5884 struct btrfs_shared_data_ref);
5885 add_data_backref(extent_cache,
5886 key.objectid, key.offset, 0, 0, 0,
5887 btrfs_shared_data_ref_count(buf, ref),
5888 0, root->sectorsize);
5891 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5892 struct bad_item *bad;
5894 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5898 bad = malloc(sizeof(struct bad_item));
5901 INIT_LIST_HEAD(&bad->list);
5902 memcpy(&bad->key, &key,
5903 sizeof(struct btrfs_key));
5904 bad->root_id = owner;
5905 list_add_tail(&bad->list, &delete_items);
5908 if (key.type != BTRFS_EXTENT_DATA_KEY)
5910 fi = btrfs_item_ptr(buf, i,
5911 struct btrfs_file_extent_item);
5912 if (btrfs_file_extent_type(buf, fi) ==
5913 BTRFS_FILE_EXTENT_INLINE)
5915 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5918 data_bytes_allocated +=
5919 btrfs_file_extent_disk_num_bytes(buf, fi);
5920 if (data_bytes_allocated < root->sectorsize) {
5923 data_bytes_referenced +=
5924 btrfs_file_extent_num_bytes(buf, fi);
5925 add_data_backref(extent_cache,
5926 btrfs_file_extent_disk_bytenr(buf, fi),
5927 parent, owner, key.objectid, key.offset -
5928 btrfs_file_extent_offset(buf, fi), 1, 1,
5929 btrfs_file_extent_disk_num_bytes(buf, fi));
5933 struct btrfs_key first_key;
5935 first_key.objectid = 0;
5938 btrfs_item_key_to_cpu(buf, &first_key, 0);
5939 level = btrfs_header_level(buf);
5940 for (i = 0; i < nritems; i++) {
5941 ptr = btrfs_node_blockptr(buf, i);
5942 size = btrfs_level_size(root, level - 1);
5943 btrfs_node_key_to_cpu(buf, &key, i);
5945 if ((level == ri->drop_level)
5946 && is_dropped_key(&key, &ri->drop_key)) {
5950 ret = add_extent_rec(extent_cache, &key,
5951 btrfs_node_ptr_generation(buf, i),
5952 ptr, size, 0, 0, 1, 0, 1, 0,
5956 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5959 add_pending(nodes, seen, ptr, size);
5961 add_pending(pending, seen, ptr, size);
5964 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5965 nritems) * sizeof(struct btrfs_key_ptr);
5967 total_btree_bytes += buf->len;
5968 if (fs_root_objectid(btrfs_header_owner(buf)))
5969 total_fs_tree_bytes += buf->len;
5970 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5971 total_extent_tree_bytes += buf->len;
5972 if (!found_old_backref &&
5973 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5974 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5975 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5976 found_old_backref = 1;
5978 free_extent_buffer(buf);
5982 static int add_root_to_pending(struct extent_buffer *buf,
5983 struct cache_tree *extent_cache,
5984 struct cache_tree *pending,
5985 struct cache_tree *seen,
5986 struct cache_tree *nodes,
5989 if (btrfs_header_level(buf) > 0)
5990 add_pending(nodes, seen, buf->start, buf->len);
5992 add_pending(pending, seen, buf->start, buf->len);
5993 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5994 0, 1, 1, 0, 1, 0, buf->len);
5996 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5997 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5998 add_tree_backref(extent_cache, buf->start, buf->start,
6001 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
6005 /* as we fix the tree, we might be deleting blocks that
6006 * we're tracking for repair. This hook makes sure we
6007 * remove any backrefs for blocks as we are fixing them.
6009 static int free_extent_hook(struct btrfs_trans_handle *trans,
6010 struct btrfs_root *root,
6011 u64 bytenr, u64 num_bytes, u64 parent,
6012 u64 root_objectid, u64 owner, u64 offset,
6015 struct extent_record *rec;
6016 struct cache_extent *cache;
6018 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6020 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6021 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6025 rec = container_of(cache, struct extent_record, cache);
6027 struct data_backref *back;
6028 back = find_data_backref(rec, parent, root_objectid, owner,
6029 offset, 1, bytenr, num_bytes);
6032 if (back->node.found_ref) {
6033 back->found_ref -= refs_to_drop;
6035 rec->refs -= refs_to_drop;
6037 if (back->node.found_extent_tree) {
6038 back->num_refs -= refs_to_drop;
6039 if (rec->extent_item_refs)
6040 rec->extent_item_refs -= refs_to_drop;
6042 if (back->found_ref == 0)
6043 back->node.found_ref = 0;
6044 if (back->num_refs == 0)
6045 back->node.found_extent_tree = 0;
6047 if (!back->node.found_extent_tree && back->node.found_ref) {
6048 list_del(&back->node.list);
6052 struct tree_backref *back;
6053 back = find_tree_backref(rec, parent, root_objectid);
6056 if (back->node.found_ref) {
6059 back->node.found_ref = 0;
6061 if (back->node.found_extent_tree) {
6062 if (rec->extent_item_refs)
6063 rec->extent_item_refs--;
6064 back->node.found_extent_tree = 0;
6066 if (!back->node.found_extent_tree && back->node.found_ref) {
6067 list_del(&back->node.list);
6071 maybe_free_extent_rec(extent_cache, rec);
6076 static int delete_extent_records(struct btrfs_trans_handle *trans,
6077 struct btrfs_root *root,
6078 struct btrfs_path *path,
6079 u64 bytenr, u64 new_len)
6081 struct btrfs_key key;
6082 struct btrfs_key found_key;
6083 struct extent_buffer *leaf;
6088 key.objectid = bytenr;
6090 key.offset = (u64)-1;
6093 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6100 if (path->slots[0] == 0)
6106 leaf = path->nodes[0];
6107 slot = path->slots[0];
6109 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6110 if (found_key.objectid != bytenr)
6113 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6114 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6115 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6116 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6117 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6118 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6119 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6120 btrfs_release_path(path);
6121 if (found_key.type == 0) {
6122 if (found_key.offset == 0)
6124 key.offset = found_key.offset - 1;
6125 key.type = found_key.type;
6127 key.type = found_key.type - 1;
6128 key.offset = (u64)-1;
6132 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6133 found_key.objectid, found_key.type, found_key.offset);
6135 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6138 btrfs_release_path(path);
6140 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6141 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6142 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6143 found_key.offset : root->leafsize;
6145 ret = btrfs_update_block_group(trans, root, bytenr,
6152 btrfs_release_path(path);
6157 * for a single backref, this will allocate a new extent
6158 * and add the backref to it.
6160 static int record_extent(struct btrfs_trans_handle *trans,
6161 struct btrfs_fs_info *info,
6162 struct btrfs_path *path,
6163 struct extent_record *rec,
6164 struct extent_backref *back,
6165 int allocated, u64 flags)
6168 struct btrfs_root *extent_root = info->extent_root;
6169 struct extent_buffer *leaf;
6170 struct btrfs_key ins_key;
6171 struct btrfs_extent_item *ei;
6172 struct tree_backref *tback;
6173 struct data_backref *dback;
6174 struct btrfs_tree_block_info *bi;
6177 rec->max_size = max_t(u64, rec->max_size,
6178 info->extent_root->leafsize);
6181 u32 item_size = sizeof(*ei);
6184 item_size += sizeof(*bi);
6186 ins_key.objectid = rec->start;
6187 ins_key.offset = rec->max_size;
6188 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6190 ret = btrfs_insert_empty_item(trans, extent_root, path,
6191 &ins_key, item_size);
6195 leaf = path->nodes[0];
6196 ei = btrfs_item_ptr(leaf, path->slots[0],
6197 struct btrfs_extent_item);
6199 btrfs_set_extent_refs(leaf, ei, 0);
6200 btrfs_set_extent_generation(leaf, ei, rec->generation);
6202 if (back->is_data) {
6203 btrfs_set_extent_flags(leaf, ei,
6204 BTRFS_EXTENT_FLAG_DATA);
6206 struct btrfs_disk_key copy_key;;
6208 tback = (struct tree_backref *)back;
6209 bi = (struct btrfs_tree_block_info *)(ei + 1);
6210 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6213 btrfs_set_disk_key_objectid(©_key,
6214 rec->info_objectid);
6215 btrfs_set_disk_key_type(©_key, 0);
6216 btrfs_set_disk_key_offset(©_key, 0);
6218 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6219 btrfs_set_tree_block_key(leaf, bi, ©_key);
6221 btrfs_set_extent_flags(leaf, ei,
6222 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6225 btrfs_mark_buffer_dirty(leaf);
6226 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6227 rec->max_size, 1, 0);
6230 btrfs_release_path(path);
6233 if (back->is_data) {
6237 dback = (struct data_backref *)back;
6238 if (back->full_backref)
6239 parent = dback->parent;
6243 for (i = 0; i < dback->found_ref; i++) {
6244 /* if parent != 0, we're doing a full backref
6245 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6246 * just makes the backref allocator create a data
6249 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6250 rec->start, rec->max_size,
6254 BTRFS_FIRST_FREE_OBJECTID :
6260 fprintf(stderr, "adding new data backref"
6261 " on %llu %s %llu owner %llu"
6262 " offset %llu found %d\n",
6263 (unsigned long long)rec->start,
6264 back->full_backref ?
6266 back->full_backref ?
6267 (unsigned long long)parent :
6268 (unsigned long long)dback->root,
6269 (unsigned long long)dback->owner,
6270 (unsigned long long)dback->offset,
6275 tback = (struct tree_backref *)back;
6276 if (back->full_backref)
6277 parent = tback->parent;
6281 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6282 rec->start, rec->max_size,
6283 parent, tback->root, 0, 0);
6284 fprintf(stderr, "adding new tree backref on "
6285 "start %llu len %llu parent %llu root %llu\n",
6286 rec->start, rec->max_size, tback->parent, tback->root);
6291 btrfs_release_path(path);
6295 struct extent_entry {
6300 struct list_head list;
6303 static struct extent_entry *find_entry(struct list_head *entries,
6304 u64 bytenr, u64 bytes)
6306 struct extent_entry *entry = NULL;
6308 list_for_each_entry(entry, entries, list) {
6309 if (entry->bytenr == bytenr && entry->bytes == bytes)
6316 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6318 struct extent_entry *entry, *best = NULL, *prev = NULL;
6320 list_for_each_entry(entry, entries, list) {
6327 * If there are as many broken entries as entries then we know
6328 * not to trust this particular entry.
6330 if (entry->broken == entry->count)
6334 * If our current entry == best then we can't be sure our best
6335 * is really the best, so we need to keep searching.
6337 if (best && best->count == entry->count) {
6343 /* Prev == entry, not good enough, have to keep searching */
6344 if (!prev->broken && prev->count == entry->count)
6348 best = (prev->count > entry->count) ? prev : entry;
6349 else if (best->count < entry->count)
6357 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6358 struct data_backref *dback, struct extent_entry *entry)
6360 struct btrfs_trans_handle *trans;
6361 struct btrfs_root *root;
6362 struct btrfs_file_extent_item *fi;
6363 struct extent_buffer *leaf;
6364 struct btrfs_key key;
6368 key.objectid = dback->root;
6369 key.type = BTRFS_ROOT_ITEM_KEY;
6370 key.offset = (u64)-1;
6371 root = btrfs_read_fs_root(info, &key);
6373 fprintf(stderr, "Couldn't find root for our ref\n");
6378 * The backref points to the original offset of the extent if it was
6379 * split, so we need to search down to the offset we have and then walk
6380 * forward until we find the backref we're looking for.
6382 key.objectid = dback->owner;
6383 key.type = BTRFS_EXTENT_DATA_KEY;
6384 key.offset = dback->offset;
6385 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6387 fprintf(stderr, "Error looking up ref %d\n", ret);
6392 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6393 ret = btrfs_next_leaf(root, path);
6395 fprintf(stderr, "Couldn't find our ref, next\n");
6399 leaf = path->nodes[0];
6400 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6401 if (key.objectid != dback->owner ||
6402 key.type != BTRFS_EXTENT_DATA_KEY) {
6403 fprintf(stderr, "Couldn't find our ref, search\n");
6406 fi = btrfs_item_ptr(leaf, path->slots[0],
6407 struct btrfs_file_extent_item);
6408 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6409 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6411 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6416 btrfs_release_path(path);
6418 trans = btrfs_start_transaction(root, 1);
6420 return PTR_ERR(trans);
6423 * Ok we have the key of the file extent we want to fix, now we can cow
6424 * down to the thing and fix it.
6426 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6428 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6429 key.objectid, key.type, key.offset, ret);
6433 fprintf(stderr, "Well that's odd, we just found this key "
6434 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6439 leaf = path->nodes[0];
6440 fi = btrfs_item_ptr(leaf, path->slots[0],
6441 struct btrfs_file_extent_item);
6443 if (btrfs_file_extent_compression(leaf, fi) &&
6444 dback->disk_bytenr != entry->bytenr) {
6445 fprintf(stderr, "Ref doesn't match the record start and is "
6446 "compressed, please take a btrfs-image of this file "
6447 "system and send it to a btrfs developer so they can "
6448 "complete this functionality for bytenr %Lu\n",
6449 dback->disk_bytenr);
6454 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6455 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6456 } else if (dback->disk_bytenr > entry->bytenr) {
6457 u64 off_diff, offset;
6459 off_diff = dback->disk_bytenr - entry->bytenr;
6460 offset = btrfs_file_extent_offset(leaf, fi);
6461 if (dback->disk_bytenr + offset +
6462 btrfs_file_extent_num_bytes(leaf, fi) >
6463 entry->bytenr + entry->bytes) {
6464 fprintf(stderr, "Ref is past the entry end, please "
6465 "take a btrfs-image of this file system and "
6466 "send it to a btrfs developer, ref %Lu\n",
6467 dback->disk_bytenr);
6472 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6473 btrfs_set_file_extent_offset(leaf, fi, offset);
6474 } else if (dback->disk_bytenr < entry->bytenr) {
6477 offset = btrfs_file_extent_offset(leaf, fi);
6478 if (dback->disk_bytenr + offset < entry->bytenr) {
6479 fprintf(stderr, "Ref is before the entry start, please"
6480 " take a btrfs-image of this file system and "
6481 "send it to a btrfs developer, ref %Lu\n",
6482 dback->disk_bytenr);
6487 offset += dback->disk_bytenr;
6488 offset -= entry->bytenr;
6489 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6490 btrfs_set_file_extent_offset(leaf, fi, offset);
6493 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6496 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6497 * only do this if we aren't using compression, otherwise it's a
6500 if (!btrfs_file_extent_compression(leaf, fi))
6501 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6503 printf("ram bytes may be wrong?\n");
6504 btrfs_mark_buffer_dirty(leaf);
6506 err = btrfs_commit_transaction(trans, root);
6507 btrfs_release_path(path);
6508 return ret ? ret : err;
6511 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6512 struct extent_record *rec)
6514 struct extent_backref *back;
6515 struct data_backref *dback;
6516 struct extent_entry *entry, *best = NULL;
6519 int broken_entries = 0;
6524 * Metadata is easy and the backrefs should always agree on bytenr and
6525 * size, if not we've got bigger issues.
6530 list_for_each_entry(back, &rec->backrefs, list) {
6531 if (back->full_backref || !back->is_data)
6534 dback = (struct data_backref *)back;
6537 * We only pay attention to backrefs that we found a real
6540 if (dback->found_ref == 0)
6544 * For now we only catch when the bytes don't match, not the
6545 * bytenr. We can easily do this at the same time, but I want
6546 * to have a fs image to test on before we just add repair
6547 * functionality willy-nilly so we know we won't screw up the
6551 entry = find_entry(&entries, dback->disk_bytenr,
6554 entry = malloc(sizeof(struct extent_entry));
6559 memset(entry, 0, sizeof(*entry));
6560 entry->bytenr = dback->disk_bytenr;
6561 entry->bytes = dback->bytes;
6562 list_add_tail(&entry->list, &entries);
6567 * If we only have on entry we may think the entries agree when
6568 * in reality they don't so we have to do some extra checking.
6570 if (dback->disk_bytenr != rec->start ||
6571 dback->bytes != rec->nr || back->broken)
6582 /* Yay all the backrefs agree, carry on good sir */
6583 if (nr_entries <= 1 && !mismatch)
6586 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6587 "%Lu\n", rec->start);
6590 * First we want to see if the backrefs can agree amongst themselves who
6591 * is right, so figure out which one of the entries has the highest
6594 best = find_most_right_entry(&entries);
6597 * Ok so we may have an even split between what the backrefs think, so
6598 * this is where we use the extent ref to see what it thinks.
6601 entry = find_entry(&entries, rec->start, rec->nr);
6602 if (!entry && (!broken_entries || !rec->found_rec)) {
6603 fprintf(stderr, "Backrefs don't agree with each other "
6604 "and extent record doesn't agree with anybody,"
6605 " so we can't fix bytenr %Lu bytes %Lu\n",
6606 rec->start, rec->nr);
6609 } else if (!entry) {
6611 * Ok our backrefs were broken, we'll assume this is the
6612 * correct value and add an entry for this range.
6614 entry = malloc(sizeof(struct extent_entry));
6619 memset(entry, 0, sizeof(*entry));
6620 entry->bytenr = rec->start;
6621 entry->bytes = rec->nr;
6622 list_add_tail(&entry->list, &entries);
6626 best = find_most_right_entry(&entries);
6628 fprintf(stderr, "Backrefs and extent record evenly "
6629 "split on who is right, this is going to "
6630 "require user input to fix bytenr %Lu bytes "
6631 "%Lu\n", rec->start, rec->nr);
6638 * I don't think this can happen currently as we'll abort() if we catch
6639 * this case higher up, but in case somebody removes that we still can't
6640 * deal with it properly here yet, so just bail out of that's the case.
6642 if (best->bytenr != rec->start) {
6643 fprintf(stderr, "Extent start and backref starts don't match, "
6644 "please use btrfs-image on this file system and send "
6645 "it to a btrfs developer so they can make fsck fix "
6646 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6647 rec->start, rec->nr);
6653 * Ok great we all agreed on an extent record, let's go find the real
6654 * references and fix up the ones that don't match.
6656 list_for_each_entry(back, &rec->backrefs, list) {
6657 if (back->full_backref || !back->is_data)
6660 dback = (struct data_backref *)back;
6663 * Still ignoring backrefs that don't have a real ref attached
6666 if (dback->found_ref == 0)
6669 if (dback->bytes == best->bytes &&
6670 dback->disk_bytenr == best->bytenr)
6673 ret = repair_ref(info, path, dback, best);
6679 * Ok we messed with the actual refs, which means we need to drop our
6680 * entire cache and go back and rescan. I know this is a huge pain and
6681 * adds a lot of extra work, but it's the only way to be safe. Once all
6682 * the backrefs agree we may not need to do anything to the extent
6687 while (!list_empty(&entries)) {
6688 entry = list_entry(entries.next, struct extent_entry, list);
6689 list_del_init(&entry->list);
6695 static int process_duplicates(struct btrfs_root *root,
6696 struct cache_tree *extent_cache,
6697 struct extent_record *rec)
6699 struct extent_record *good, *tmp;
6700 struct cache_extent *cache;
6704 * If we found a extent record for this extent then return, or if we
6705 * have more than one duplicate we are likely going to need to delete
6708 if (rec->found_rec || rec->num_duplicates > 1)
6711 /* Shouldn't happen but just in case */
6712 BUG_ON(!rec->num_duplicates);
6715 * So this happens if we end up with a backref that doesn't match the
6716 * actual extent entry. So either the backref is bad or the extent
6717 * entry is bad. Either way we want to have the extent_record actually
6718 * reflect what we found in the extent_tree, so we need to take the
6719 * duplicate out and use that as the extent_record since the only way we
6720 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6722 remove_cache_extent(extent_cache, &rec->cache);
6724 good = list_entry(rec->dups.next, struct extent_record, list);
6725 list_del_init(&good->list);
6726 INIT_LIST_HEAD(&good->backrefs);
6727 INIT_LIST_HEAD(&good->dups);
6728 good->cache.start = good->start;
6729 good->cache.size = good->nr;
6730 good->content_checked = 0;
6731 good->owner_ref_checked = 0;
6732 good->num_duplicates = 0;
6733 good->refs = rec->refs;
6734 list_splice_init(&rec->backrefs, &good->backrefs);
6736 cache = lookup_cache_extent(extent_cache, good->start,
6740 tmp = container_of(cache, struct extent_record, cache);
6743 * If we find another overlapping extent and it's found_rec is
6744 * set then it's a duplicate and we need to try and delete
6747 if (tmp->found_rec || tmp->num_duplicates > 0) {
6748 if (list_empty(&good->list))
6749 list_add_tail(&good->list,
6750 &duplicate_extents);
6751 good->num_duplicates += tmp->num_duplicates + 1;
6752 list_splice_init(&tmp->dups, &good->dups);
6753 list_del_init(&tmp->list);
6754 list_add_tail(&tmp->list, &good->dups);
6755 remove_cache_extent(extent_cache, &tmp->cache);
6760 * Ok we have another non extent item backed extent rec, so lets
6761 * just add it to this extent and carry on like we did above.
6763 good->refs += tmp->refs;
6764 list_splice_init(&tmp->backrefs, &good->backrefs);
6765 remove_cache_extent(extent_cache, &tmp->cache);
6768 ret = insert_cache_extent(extent_cache, &good->cache);
6771 return good->num_duplicates ? 0 : 1;
6774 static int delete_duplicate_records(struct btrfs_root *root,
6775 struct extent_record *rec)
6777 struct btrfs_trans_handle *trans;
6778 LIST_HEAD(delete_list);
6779 struct btrfs_path *path;
6780 struct extent_record *tmp, *good, *n;
6783 struct btrfs_key key;
6785 path = btrfs_alloc_path();
6792 /* Find the record that covers all of the duplicates. */
6793 list_for_each_entry(tmp, &rec->dups, list) {
6794 if (good->start < tmp->start)
6796 if (good->nr > tmp->nr)
6799 if (tmp->start + tmp->nr < good->start + good->nr) {
6800 fprintf(stderr, "Ok we have overlapping extents that "
6801 "aren't completely covered by eachother, this "
6802 "is going to require more careful thought. "
6803 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6804 tmp->start, tmp->nr, good->start, good->nr);
6811 list_add_tail(&rec->list, &delete_list);
6813 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6816 list_move_tail(&tmp->list, &delete_list);
6819 root = root->fs_info->extent_root;
6820 trans = btrfs_start_transaction(root, 1);
6821 if (IS_ERR(trans)) {
6822 ret = PTR_ERR(trans);
6826 list_for_each_entry(tmp, &delete_list, list) {
6827 if (tmp->found_rec == 0)
6829 key.objectid = tmp->start;
6830 key.type = BTRFS_EXTENT_ITEM_KEY;
6831 key.offset = tmp->nr;
6833 /* Shouldn't happen but just in case */
6834 if (tmp->metadata) {
6835 fprintf(stderr, "Well this shouldn't happen, extent "
6836 "record overlaps but is metadata? "
6837 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6841 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6847 ret = btrfs_del_item(trans, root, path);
6850 btrfs_release_path(path);
6853 err = btrfs_commit_transaction(trans, root);
6857 while (!list_empty(&delete_list)) {
6858 tmp = list_entry(delete_list.next, struct extent_record, list);
6859 list_del_init(&tmp->list);
6865 while (!list_empty(&rec->dups)) {
6866 tmp = list_entry(rec->dups.next, struct extent_record, list);
6867 list_del_init(&tmp->list);
6871 btrfs_free_path(path);
6873 if (!ret && !nr_del)
6874 rec->num_duplicates = 0;
6876 return ret ? ret : nr_del;
6879 static int find_possible_backrefs(struct btrfs_fs_info *info,
6880 struct btrfs_path *path,
6881 struct cache_tree *extent_cache,
6882 struct extent_record *rec)
6884 struct btrfs_root *root;
6885 struct extent_backref *back;
6886 struct data_backref *dback;
6887 struct cache_extent *cache;
6888 struct btrfs_file_extent_item *fi;
6889 struct btrfs_key key;
6893 list_for_each_entry(back, &rec->backrefs, list) {
6894 /* Don't care about full backrefs (poor unloved backrefs) */
6895 if (back->full_backref || !back->is_data)
6898 dback = (struct data_backref *)back;
6900 /* We found this one, we don't need to do a lookup */
6901 if (dback->found_ref)
6904 key.objectid = dback->root;
6905 key.type = BTRFS_ROOT_ITEM_KEY;
6906 key.offset = (u64)-1;
6908 root = btrfs_read_fs_root(info, &key);
6910 /* No root, definitely a bad ref, skip */
6911 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6913 /* Other err, exit */
6915 return PTR_ERR(root);
6917 key.objectid = dback->owner;
6918 key.type = BTRFS_EXTENT_DATA_KEY;
6919 key.offset = dback->offset;
6920 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6922 btrfs_release_path(path);
6925 /* Didn't find it, we can carry on */
6930 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6931 struct btrfs_file_extent_item);
6932 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6933 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6934 btrfs_release_path(path);
6935 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6937 struct extent_record *tmp;
6938 tmp = container_of(cache, struct extent_record, cache);
6941 * If we found an extent record for the bytenr for this
6942 * particular backref then we can't add it to our
6943 * current extent record. We only want to add backrefs
6944 * that don't have a corresponding extent item in the
6945 * extent tree since they likely belong to this record
6946 * and we need to fix it if it doesn't match bytenrs.
6952 dback->found_ref += 1;
6953 dback->disk_bytenr = bytenr;
6954 dback->bytes = bytes;
6957 * Set this so the verify backref code knows not to trust the
6958 * values in this backref.
6967 * Record orphan data ref into corresponding root.
6969 * Return 0 if the extent item contains data ref and recorded.
6970 * Return 1 if the extent item contains no useful data ref
6971 * On that case, it may contains only shared_dataref or metadata backref
6972 * or the file extent exists(this should be handled by the extent bytenr
6974 * Return <0 if something goes wrong.
6976 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6977 struct extent_record *rec)
6979 struct btrfs_key key;
6980 struct btrfs_root *dest_root;
6981 struct extent_backref *back;
6982 struct data_backref *dback;
6983 struct orphan_data_extent *orphan;
6984 struct btrfs_path *path;
6985 int recorded_data_ref = 0;
6990 path = btrfs_alloc_path();
6993 list_for_each_entry(back, &rec->backrefs, list) {
6994 if (back->full_backref || !back->is_data ||
6995 !back->found_extent_tree)
6997 dback = (struct data_backref *)back;
6998 if (dback->found_ref)
7000 key.objectid = dback->root;
7001 key.type = BTRFS_ROOT_ITEM_KEY;
7002 key.offset = (u64)-1;
7004 dest_root = btrfs_read_fs_root(fs_info, &key);
7006 /* For non-exist root we just skip it */
7007 if (IS_ERR(dest_root) || !dest_root)
7010 key.objectid = dback->owner;
7011 key.type = BTRFS_EXTENT_DATA_KEY;
7012 key.offset = dback->offset;
7014 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7016 * For ret < 0, it's OK since the fs-tree may be corrupted,
7017 * we need to record it for inode/file extent rebuild.
7018 * For ret > 0, we record it only for file extent rebuild.
7019 * For ret == 0, the file extent exists but only bytenr
7020 * mismatch, let the original bytenr fix routine to handle,
7026 orphan = malloc(sizeof(*orphan));
7031 INIT_LIST_HEAD(&orphan->list);
7032 orphan->root = dback->root;
7033 orphan->objectid = dback->owner;
7034 orphan->offset = dback->offset;
7035 orphan->disk_bytenr = rec->cache.start;
7036 orphan->disk_len = rec->cache.size;
7037 list_add(&dest_root->orphan_data_extents, &orphan->list);
7038 recorded_data_ref = 1;
7041 btrfs_free_path(path);
7043 return !recorded_data_ref;
7049 * when an incorrect extent item is found, this will delete
7050 * all of the existing entries for it and recreate them
7051 * based on what the tree scan found.
7053 static int fixup_extent_refs(struct btrfs_fs_info *info,
7054 struct cache_tree *extent_cache,
7055 struct extent_record *rec)
7057 struct btrfs_trans_handle *trans = NULL;
7059 struct btrfs_path *path;
7060 struct list_head *cur = rec->backrefs.next;
7061 struct cache_extent *cache;
7062 struct extent_backref *back;
7066 if (rec->flag_block_full_backref)
7067 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7069 path = btrfs_alloc_path();
7073 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7075 * Sometimes the backrefs themselves are so broken they don't
7076 * get attached to any meaningful rec, so first go back and
7077 * check any of our backrefs that we couldn't find and throw
7078 * them into the list if we find the backref so that
7079 * verify_backrefs can figure out what to do.
7081 ret = find_possible_backrefs(info, path, extent_cache, rec);
7086 /* step one, make sure all of the backrefs agree */
7087 ret = verify_backrefs(info, path, rec);
7091 trans = btrfs_start_transaction(info->extent_root, 1);
7092 if (IS_ERR(trans)) {
7093 ret = PTR_ERR(trans);
7097 /* step two, delete all the existing records */
7098 ret = delete_extent_records(trans, info->extent_root, path,
7099 rec->start, rec->max_size);
7104 /* was this block corrupt? If so, don't add references to it */
7105 cache = lookup_cache_extent(info->corrupt_blocks,
7106 rec->start, rec->max_size);
7112 /* step three, recreate all the refs we did find */
7113 while(cur != &rec->backrefs) {
7114 back = list_entry(cur, struct extent_backref, list);
7118 * if we didn't find any references, don't create a
7121 if (!back->found_ref)
7124 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7132 int err = btrfs_commit_transaction(trans, info->extent_root);
7137 btrfs_free_path(path);
7141 /* right now we only prune from the extent allocation tree */
7142 static int prune_one_block(struct btrfs_trans_handle *trans,
7143 struct btrfs_fs_info *info,
7144 struct btrfs_corrupt_block *corrupt)
7147 struct btrfs_path path;
7148 struct extent_buffer *eb;
7152 int level = corrupt->level + 1;
7154 btrfs_init_path(&path);
7156 /* we want to stop at the parent to our busted block */
7157 path.lowest_level = level;
7159 ret = btrfs_search_slot(trans, info->extent_root,
7160 &corrupt->key, &path, -1, 1);
7165 eb = path.nodes[level];
7172 * hopefully the search gave us the block we want to prune,
7173 * lets try that first
7175 slot = path.slots[level];
7176 found = btrfs_node_blockptr(eb, slot);
7177 if (found == corrupt->cache.start)
7180 nritems = btrfs_header_nritems(eb);
7182 /* the search failed, lets scan this node and hope we find it */
7183 for (slot = 0; slot < nritems; slot++) {
7184 found = btrfs_node_blockptr(eb, slot);
7185 if (found == corrupt->cache.start)
7189 * we couldn't find the bad block. TODO, search all the nodes for pointers
7192 if (eb == info->extent_root->node) {
7197 btrfs_release_path(&path);
7202 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7203 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7206 btrfs_release_path(&path);
7210 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7212 struct btrfs_trans_handle *trans = NULL;
7213 struct cache_extent *cache;
7214 struct btrfs_corrupt_block *corrupt;
7217 cache = search_cache_extent(info->corrupt_blocks, 0);
7221 trans = btrfs_start_transaction(info->extent_root, 1);
7223 return PTR_ERR(trans);
7225 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7226 prune_one_block(trans, info, corrupt);
7227 remove_cache_extent(info->corrupt_blocks, cache);
7230 return btrfs_commit_transaction(trans, info->extent_root);
7234 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7236 struct btrfs_block_group_cache *cache;
7241 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7242 &start, &end, EXTENT_DIRTY);
7245 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7251 cache = btrfs_lookup_first_block_group(fs_info, start);
7256 start = cache->key.objectid + cache->key.offset;
7260 static int check_extent_refs(struct btrfs_root *root,
7261 struct cache_tree *extent_cache)
7263 struct extent_record *rec;
7264 struct cache_extent *cache;
7273 * if we're doing a repair, we have to make sure
7274 * we don't allocate from the problem extents.
7275 * In the worst case, this will be all the
7278 cache = search_cache_extent(extent_cache, 0);
7280 rec = container_of(cache, struct extent_record, cache);
7281 set_extent_dirty(root->fs_info->excluded_extents,
7283 rec->start + rec->max_size - 1,
7285 cache = next_cache_extent(cache);
7288 /* pin down all the corrupted blocks too */
7289 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7291 set_extent_dirty(root->fs_info->excluded_extents,
7293 cache->start + cache->size - 1,
7295 cache = next_cache_extent(cache);
7297 prune_corrupt_blocks(root->fs_info);
7298 reset_cached_block_groups(root->fs_info);
7301 reset_cached_block_groups(root->fs_info);
7304 * We need to delete any duplicate entries we find first otherwise we
7305 * could mess up the extent tree when we have backrefs that actually
7306 * belong to a different extent item and not the weird duplicate one.
7308 while (repair && !list_empty(&duplicate_extents)) {
7309 rec = list_entry(duplicate_extents.next, struct extent_record,
7311 list_del_init(&rec->list);
7313 /* Sometimes we can find a backref before we find an actual
7314 * extent, so we need to process it a little bit to see if there
7315 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7316 * if this is a backref screwup. If we need to delete stuff
7317 * process_duplicates() will return 0, otherwise it will return
7320 if (process_duplicates(root, extent_cache, rec))
7322 ret = delete_duplicate_records(root, rec);
7326 * delete_duplicate_records will return the number of entries
7327 * deleted, so if it's greater than 0 then we know we actually
7328 * did something and we need to remove.
7340 cache = search_cache_extent(extent_cache, 0);
7343 rec = container_of(cache, struct extent_record, cache);
7344 if (rec->num_duplicates) {
7345 fprintf(stderr, "extent item %llu has multiple extent "
7346 "items\n", (unsigned long long)rec->start);
7350 if (rec->refs != rec->extent_item_refs) {
7351 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7352 (unsigned long long)rec->start,
7353 (unsigned long long)rec->nr);
7354 fprintf(stderr, "extent item %llu, found %llu\n",
7355 (unsigned long long)rec->extent_item_refs,
7356 (unsigned long long)rec->refs);
7357 ret = record_orphan_data_extents(root->fs_info, rec);
7364 * we can't use the extent to repair file
7365 * extent, let the fallback method handle it.
7367 if (!fixed && repair) {
7368 ret = fixup_extent_refs(
7379 if (all_backpointers_checked(rec, 1)) {
7380 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7381 (unsigned long long)rec->start,
7382 (unsigned long long)rec->nr);
7384 if (!fixed && !recorded && repair) {
7385 ret = fixup_extent_refs(root->fs_info,
7393 if (!rec->owner_ref_checked) {
7394 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7395 (unsigned long long)rec->start,
7396 (unsigned long long)rec->nr);
7397 if (!fixed && !recorded && repair) {
7398 ret = fixup_extent_refs(root->fs_info,
7407 remove_cache_extent(extent_cache, cache);
7408 free_all_extent_backrefs(rec);
7413 if (ret && ret != -EAGAIN) {
7414 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7417 struct btrfs_trans_handle *trans;
7419 root = root->fs_info->extent_root;
7420 trans = btrfs_start_transaction(root, 1);
7421 if (IS_ERR(trans)) {
7422 ret = PTR_ERR(trans);
7426 btrfs_fix_block_accounting(trans, root);
7427 ret = btrfs_commit_transaction(trans, root);
7432 fprintf(stderr, "repaired damaged extent references\n");
7438 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7442 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7443 stripe_size = length;
7444 stripe_size /= num_stripes;
7445 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7446 stripe_size = length * 2;
7447 stripe_size /= num_stripes;
7448 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7449 stripe_size = length;
7450 stripe_size /= (num_stripes - 1);
7451 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7452 stripe_size = length;
7453 stripe_size /= (num_stripes - 2);
7455 stripe_size = length;
7461 * Check the chunk with its block group/dev list ref:
7462 * Return 0 if all refs seems valid.
7463 * Return 1 if part of refs seems valid, need later check for rebuild ref
7464 * like missing block group and needs to search extent tree to rebuild them.
7465 * Return -1 if essential refs are missing and unable to rebuild.
7467 static int check_chunk_refs(struct chunk_record *chunk_rec,
7468 struct block_group_tree *block_group_cache,
7469 struct device_extent_tree *dev_extent_cache,
7472 struct cache_extent *block_group_item;
7473 struct block_group_record *block_group_rec;
7474 struct cache_extent *dev_extent_item;
7475 struct device_extent_record *dev_extent_rec;
7479 int metadump_v2 = 0;
7483 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7486 if (block_group_item) {
7487 block_group_rec = container_of(block_group_item,
7488 struct block_group_record,
7490 if (chunk_rec->length != block_group_rec->offset ||
7491 chunk_rec->offset != block_group_rec->objectid ||
7493 chunk_rec->type_flags != block_group_rec->flags)) {
7496 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7497 chunk_rec->objectid,
7502 chunk_rec->type_flags,
7503 block_group_rec->objectid,
7504 block_group_rec->type,
7505 block_group_rec->offset,
7506 block_group_rec->offset,
7507 block_group_rec->objectid,
7508 block_group_rec->flags);
7511 list_del_init(&block_group_rec->list);
7512 chunk_rec->bg_rec = block_group_rec;
7517 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7518 chunk_rec->objectid,
7523 chunk_rec->type_flags);
7530 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7531 chunk_rec->num_stripes);
7532 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7533 devid = chunk_rec->stripes[i].devid;
7534 offset = chunk_rec->stripes[i].offset;
7535 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7536 devid, offset, length);
7537 if (dev_extent_item) {
7538 dev_extent_rec = container_of(dev_extent_item,
7539 struct device_extent_record,
7541 if (dev_extent_rec->objectid != devid ||
7542 dev_extent_rec->offset != offset ||
7543 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7544 dev_extent_rec->length != length) {
7547 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7548 chunk_rec->objectid,
7551 chunk_rec->stripes[i].devid,
7552 chunk_rec->stripes[i].offset,
7553 dev_extent_rec->objectid,
7554 dev_extent_rec->offset,
7555 dev_extent_rec->length);
7558 list_move(&dev_extent_rec->chunk_list,
7559 &chunk_rec->dextents);
7564 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7565 chunk_rec->objectid,
7568 chunk_rec->stripes[i].devid,
7569 chunk_rec->stripes[i].offset);
7576 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7577 int check_chunks(struct cache_tree *chunk_cache,
7578 struct block_group_tree *block_group_cache,
7579 struct device_extent_tree *dev_extent_cache,
7580 struct list_head *good, struct list_head *bad,
7581 struct list_head *rebuild, int silent)
7583 struct cache_extent *chunk_item;
7584 struct chunk_record *chunk_rec;
7585 struct block_group_record *bg_rec;
7586 struct device_extent_record *dext_rec;
7590 chunk_item = first_cache_extent(chunk_cache);
7591 while (chunk_item) {
7592 chunk_rec = container_of(chunk_item, struct chunk_record,
7594 err = check_chunk_refs(chunk_rec, block_group_cache,
7595 dev_extent_cache, silent);
7598 if (err == 0 && good)
7599 list_add_tail(&chunk_rec->list, good);
7600 if (err > 0 && rebuild)
7601 list_add_tail(&chunk_rec->list, rebuild);
7603 list_add_tail(&chunk_rec->list, bad);
7604 chunk_item = next_cache_extent(chunk_item);
7607 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7610 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7618 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7622 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7633 static int check_device_used(struct device_record *dev_rec,
7634 struct device_extent_tree *dext_cache)
7636 struct cache_extent *cache;
7637 struct device_extent_record *dev_extent_rec;
7640 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7642 dev_extent_rec = container_of(cache,
7643 struct device_extent_record,
7645 if (dev_extent_rec->objectid != dev_rec->devid)
7648 list_del_init(&dev_extent_rec->device_list);
7649 total_byte += dev_extent_rec->length;
7650 cache = next_cache_extent(cache);
7653 if (total_byte != dev_rec->byte_used) {
7655 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7656 total_byte, dev_rec->byte_used, dev_rec->objectid,
7657 dev_rec->type, dev_rec->offset);
7664 /* check btrfs_dev_item -> btrfs_dev_extent */
7665 static int check_devices(struct rb_root *dev_cache,
7666 struct device_extent_tree *dev_extent_cache)
7668 struct rb_node *dev_node;
7669 struct device_record *dev_rec;
7670 struct device_extent_record *dext_rec;
7674 dev_node = rb_first(dev_cache);
7676 dev_rec = container_of(dev_node, struct device_record, node);
7677 err = check_device_used(dev_rec, dev_extent_cache);
7681 dev_node = rb_next(dev_node);
7683 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7686 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7687 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7694 static int add_root_item_to_list(struct list_head *head,
7695 u64 objectid, u64 bytenr,
7696 u8 level, u8 drop_level,
7697 int level_size, struct btrfs_key *drop_key)
7700 struct root_item_record *ri_rec;
7701 ri_rec = malloc(sizeof(*ri_rec));
7704 ri_rec->bytenr = bytenr;
7705 ri_rec->objectid = objectid;
7706 ri_rec->level = level;
7707 ri_rec->level_size = level_size;
7708 ri_rec->drop_level = drop_level;
7710 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7711 list_add_tail(&ri_rec->list, head);
7716 static void free_root_item_list(struct list_head *list)
7718 struct root_item_record *ri_rec;
7720 while (!list_empty(list)) {
7721 ri_rec = list_first_entry(list, struct root_item_record,
7723 list_del_init(&ri_rec->list);
7728 static int deal_root_from_list(struct list_head *list,
7729 struct btrfs_root *root,
7730 struct block_info *bits,
7732 struct cache_tree *pending,
7733 struct cache_tree *seen,
7734 struct cache_tree *reada,
7735 struct cache_tree *nodes,
7736 struct cache_tree *extent_cache,
7737 struct cache_tree *chunk_cache,
7738 struct rb_root *dev_cache,
7739 struct block_group_tree *block_group_cache,
7740 struct device_extent_tree *dev_extent_cache)
7745 while (!list_empty(list)) {
7746 struct root_item_record *rec;
7747 struct extent_buffer *buf;
7748 rec = list_entry(list->next,
7749 struct root_item_record, list);
7751 buf = read_tree_block(root->fs_info->tree_root,
7752 rec->bytenr, rec->level_size, 0);
7753 if (!extent_buffer_uptodate(buf)) {
7754 free_extent_buffer(buf);
7758 add_root_to_pending(buf, extent_cache, pending,
7759 seen, nodes, rec->objectid);
7761 * To rebuild extent tree, we need deal with snapshot
7762 * one by one, otherwise we deal with node firstly which
7763 * can maximize readahead.
7766 ret = run_next_block(root, bits, bits_nr, &last,
7767 pending, seen, reada, nodes,
7768 extent_cache, chunk_cache,
7769 dev_cache, block_group_cache,
7770 dev_extent_cache, rec);
7774 free_extent_buffer(buf);
7775 list_del(&rec->list);
7781 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7782 reada, nodes, extent_cache, chunk_cache,
7783 dev_cache, block_group_cache,
7784 dev_extent_cache, NULL);
7794 static int check_chunks_and_extents(struct btrfs_root *root)
7796 struct rb_root dev_cache;
7797 struct cache_tree chunk_cache;
7798 struct block_group_tree block_group_cache;
7799 struct device_extent_tree dev_extent_cache;
7800 struct cache_tree extent_cache;
7801 struct cache_tree seen;
7802 struct cache_tree pending;
7803 struct cache_tree reada;
7804 struct cache_tree nodes;
7805 struct extent_io_tree excluded_extents;
7806 struct cache_tree corrupt_blocks;
7807 struct btrfs_path path;
7808 struct btrfs_key key;
7809 struct btrfs_key found_key;
7811 struct block_info *bits;
7813 struct extent_buffer *leaf;
7815 struct btrfs_root_item ri;
7816 struct list_head dropping_trees;
7817 struct list_head normal_trees;
7818 struct btrfs_root *root1;
7823 dev_cache = RB_ROOT;
7824 cache_tree_init(&chunk_cache);
7825 block_group_tree_init(&block_group_cache);
7826 device_extent_tree_init(&dev_extent_cache);
7828 cache_tree_init(&extent_cache);
7829 cache_tree_init(&seen);
7830 cache_tree_init(&pending);
7831 cache_tree_init(&nodes);
7832 cache_tree_init(&reada);
7833 cache_tree_init(&corrupt_blocks);
7834 extent_io_tree_init(&excluded_extents);
7835 INIT_LIST_HEAD(&dropping_trees);
7836 INIT_LIST_HEAD(&normal_trees);
7839 root->fs_info->excluded_extents = &excluded_extents;
7840 root->fs_info->fsck_extent_cache = &extent_cache;
7841 root->fs_info->free_extent_hook = free_extent_hook;
7842 root->fs_info->corrupt_blocks = &corrupt_blocks;
7846 bits = malloc(bits_nr * sizeof(struct block_info));
7853 root1 = root->fs_info->tree_root;
7854 level = btrfs_header_level(root1->node);
7855 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7856 root1->node->start, level, 0,
7857 btrfs_level_size(root1, level), NULL);
7860 root1 = root->fs_info->chunk_root;
7861 level = btrfs_header_level(root1->node);
7862 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7863 root1->node->start, level, 0,
7864 btrfs_level_size(root1, level), NULL);
7867 btrfs_init_path(&path);
7870 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7871 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7876 leaf = path.nodes[0];
7877 slot = path.slots[0];
7878 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7879 ret = btrfs_next_leaf(root, &path);
7882 leaf = path.nodes[0];
7883 slot = path.slots[0];
7885 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7886 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7887 unsigned long offset;
7889 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7890 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7891 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7892 level = btrfs_root_level(&ri);
7893 level_size = btrfs_level_size(root, level);
7894 ret = add_root_item_to_list(&normal_trees,
7896 btrfs_root_bytenr(&ri), level,
7897 0, level_size, NULL);
7901 level = btrfs_root_level(&ri);
7902 level_size = btrfs_level_size(root, level);
7903 objectid = found_key.objectid;
7904 btrfs_disk_key_to_cpu(&found_key,
7906 ret = add_root_item_to_list(&dropping_trees,
7908 btrfs_root_bytenr(&ri),
7909 level, ri.drop_level,
7910 level_size, &found_key);
7917 btrfs_release_path(&path);
7920 * check_block can return -EAGAIN if it fixes something, please keep
7921 * this in mind when dealing with return values from these functions, if
7922 * we get -EAGAIN we want to fall through and restart the loop.
7924 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
7925 &seen, &reada, &nodes, &extent_cache,
7926 &chunk_cache, &dev_cache, &block_group_cache,
7933 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
7934 &pending, &seen, &reada, &nodes,
7935 &extent_cache, &chunk_cache, &dev_cache,
7936 &block_group_cache, &dev_extent_cache);
7943 err = check_chunks(&chunk_cache, &block_group_cache,
7944 &dev_extent_cache, NULL, NULL, NULL, 0);
7952 ret = check_extent_refs(root, &extent_cache);
7959 err = check_devices(&dev_cache, &dev_extent_cache);
7965 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
7966 extent_io_tree_cleanup(&excluded_extents);
7967 root->fs_info->fsck_extent_cache = NULL;
7968 root->fs_info->free_extent_hook = NULL;
7969 root->fs_info->corrupt_blocks = NULL;
7970 root->fs_info->excluded_extents = NULL;
7973 free_chunk_cache_tree(&chunk_cache);
7974 free_device_cache_tree(&dev_cache);
7975 free_block_group_tree(&block_group_cache);
7976 free_device_extent_tree(&dev_extent_cache);
7977 free_extent_cache_tree(&seen);
7978 free_extent_cache_tree(&pending);
7979 free_extent_cache_tree(&reada);
7980 free_extent_cache_tree(&nodes);
7983 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
7984 free_extent_cache_tree(&seen);
7985 free_extent_cache_tree(&pending);
7986 free_extent_cache_tree(&reada);
7987 free_extent_cache_tree(&nodes);
7988 free_chunk_cache_tree(&chunk_cache);
7989 free_block_group_tree(&block_group_cache);
7990 free_device_cache_tree(&dev_cache);
7991 free_device_extent_tree(&dev_extent_cache);
7992 free_extent_record_cache(root->fs_info, &extent_cache);
7993 free_root_item_list(&normal_trees);
7994 free_root_item_list(&dropping_trees);
7995 extent_io_tree_cleanup(&excluded_extents);
7999 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8000 struct btrfs_root *root, int overwrite)
8002 struct extent_buffer *c;
8003 struct extent_buffer *old = root->node;
8006 struct btrfs_disk_key disk_key = {0,0,0};
8012 extent_buffer_get(c);
8015 c = btrfs_alloc_free_block(trans, root,
8016 btrfs_level_size(root, 0),
8017 root->root_key.objectid,
8018 &disk_key, level, 0, 0);
8021 extent_buffer_get(c);
8025 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8026 btrfs_set_header_level(c, level);
8027 btrfs_set_header_bytenr(c, c->start);
8028 btrfs_set_header_generation(c, trans->transid);
8029 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8030 btrfs_set_header_owner(c, root->root_key.objectid);
8032 write_extent_buffer(c, root->fs_info->fsid,
8033 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8035 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8036 btrfs_header_chunk_tree_uuid(c),
8039 btrfs_mark_buffer_dirty(c);
8041 * this case can happen in the following case:
8043 * 1.overwrite previous root.
8045 * 2.reinit reloc data root, this is because we skip pin
8046 * down reloc data tree before which means we can allocate
8047 * same block bytenr here.
8049 if (old->start == c->start) {
8050 btrfs_set_root_generation(&root->root_item,
8052 root->root_item.level = btrfs_header_level(root->node);
8053 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8054 &root->root_key, &root->root_item);
8056 free_extent_buffer(c);
8060 free_extent_buffer(old);
8062 add_root_to_dirty_list(root);
8066 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8067 struct extent_buffer *eb, int tree_root)
8069 struct extent_buffer *tmp;
8070 struct btrfs_root_item *ri;
8071 struct btrfs_key key;
8074 int level = btrfs_header_level(eb);
8080 * If we have pinned this block before, don't pin it again.
8081 * This can not only avoid forever loop with broken filesystem
8082 * but also give us some speedups.
8084 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8085 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8088 btrfs_pin_extent(fs_info, eb->start, eb->len);
8090 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8091 nritems = btrfs_header_nritems(eb);
8092 for (i = 0; i < nritems; i++) {
8094 btrfs_item_key_to_cpu(eb, &key, i);
8095 if (key.type != BTRFS_ROOT_ITEM_KEY)
8097 /* Skip the extent root and reloc roots */
8098 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8099 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8100 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8102 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8103 bytenr = btrfs_disk_root_bytenr(eb, ri);
8106 * If at any point we start needing the real root we
8107 * will have to build a stump root for the root we are
8108 * in, but for now this doesn't actually use the root so
8109 * just pass in extent_root.
8111 tmp = read_tree_block(fs_info->extent_root, bytenr,
8113 if (!extent_buffer_uptodate(tmp)) {
8114 fprintf(stderr, "Error reading root block\n");
8117 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8118 free_extent_buffer(tmp);
8122 bytenr = btrfs_node_blockptr(eb, i);
8124 /* If we aren't the tree root don't read the block */
8125 if (level == 1 && !tree_root) {
8126 btrfs_pin_extent(fs_info, bytenr, leafsize);
8130 tmp = read_tree_block(fs_info->extent_root, bytenr,
8132 if (!extent_buffer_uptodate(tmp)) {
8133 fprintf(stderr, "Error reading tree block\n");
8136 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8137 free_extent_buffer(tmp);
8146 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8150 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8154 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8157 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8159 struct btrfs_block_group_cache *cache;
8160 struct btrfs_path *path;
8161 struct extent_buffer *leaf;
8162 struct btrfs_chunk *chunk;
8163 struct btrfs_key key;
8167 path = btrfs_alloc_path();
8172 key.type = BTRFS_CHUNK_ITEM_KEY;
8175 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8177 btrfs_free_path(path);
8182 * We do this in case the block groups were screwed up and had alloc
8183 * bits that aren't actually set on the chunks. This happens with
8184 * restored images every time and could happen in real life I guess.
8186 fs_info->avail_data_alloc_bits = 0;
8187 fs_info->avail_metadata_alloc_bits = 0;
8188 fs_info->avail_system_alloc_bits = 0;
8190 /* First we need to create the in-memory block groups */
8192 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8193 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8195 btrfs_free_path(path);
8203 leaf = path->nodes[0];
8204 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8205 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8210 chunk = btrfs_item_ptr(leaf, path->slots[0],
8211 struct btrfs_chunk);
8212 btrfs_add_block_group(fs_info, 0,
8213 btrfs_chunk_type(leaf, chunk),
8214 key.objectid, key.offset,
8215 btrfs_chunk_length(leaf, chunk));
8216 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8217 key.offset + btrfs_chunk_length(leaf, chunk),
8223 cache = btrfs_lookup_first_block_group(fs_info, start);
8227 start = cache->key.objectid + cache->key.offset;
8230 btrfs_free_path(path);
8234 static int reset_balance(struct btrfs_trans_handle *trans,
8235 struct btrfs_fs_info *fs_info)
8237 struct btrfs_root *root = fs_info->tree_root;
8238 struct btrfs_path *path;
8239 struct extent_buffer *leaf;
8240 struct btrfs_key key;
8241 int del_slot, del_nr = 0;
8245 path = btrfs_alloc_path();
8249 key.objectid = BTRFS_BALANCE_OBJECTID;
8250 key.type = BTRFS_BALANCE_ITEM_KEY;
8253 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8258 goto reinit_data_reloc;
8263 ret = btrfs_del_item(trans, root, path);
8266 btrfs_release_path(path);
8268 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8269 key.type = BTRFS_ROOT_ITEM_KEY;
8272 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8276 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8281 ret = btrfs_del_items(trans, root, path,
8288 btrfs_release_path(path);
8291 ret = btrfs_search_slot(trans, root, &key, path,
8298 leaf = path->nodes[0];
8299 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8300 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8302 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8307 del_slot = path->slots[0];
8316 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8320 btrfs_release_path(path);
8323 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8324 key.type = BTRFS_ROOT_ITEM_KEY;
8325 key.offset = (u64)-1;
8326 root = btrfs_read_fs_root(fs_info, &key);
8328 fprintf(stderr, "Error reading data reloc tree\n");
8329 ret = PTR_ERR(root);
8332 record_root_in_trans(trans, root);
8333 ret = btrfs_fsck_reinit_root(trans, root, 0);
8336 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8338 btrfs_free_path(path);
8342 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8343 struct btrfs_fs_info *fs_info)
8349 * The only reason we don't do this is because right now we're just
8350 * walking the trees we find and pinning down their bytes, we don't look
8351 * at any of the leaves. In order to do mixed groups we'd have to check
8352 * the leaves of any fs roots and pin down the bytes for any file
8353 * extents we find. Not hard but why do it if we don't have to?
8355 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8356 fprintf(stderr, "We don't support re-initing the extent tree "
8357 "for mixed block groups yet, please notify a btrfs "
8358 "developer you want to do this so they can add this "
8359 "functionality.\n");
8364 * first we need to walk all of the trees except the extent tree and pin
8365 * down the bytes that are in use so we don't overwrite any existing
8368 ret = pin_metadata_blocks(fs_info);
8370 fprintf(stderr, "error pinning down used bytes\n");
8375 * Need to drop all the block groups since we're going to recreate all
8378 btrfs_free_block_groups(fs_info);
8379 ret = reset_block_groups(fs_info);
8381 fprintf(stderr, "error resetting the block groups\n");
8385 /* Ok we can allocate now, reinit the extent root */
8386 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8388 fprintf(stderr, "extent root initialization failed\n");
8390 * When the transaction code is updated we should end the
8391 * transaction, but for now progs only knows about commit so
8392 * just return an error.
8398 * Now we have all the in-memory block groups setup so we can make
8399 * allocations properly, and the metadata we care about is safe since we
8400 * pinned all of it above.
8403 struct btrfs_block_group_cache *cache;
8405 cache = btrfs_lookup_first_block_group(fs_info, start);
8408 start = cache->key.objectid + cache->key.offset;
8409 ret = btrfs_insert_item(trans, fs_info->extent_root,
8410 &cache->key, &cache->item,
8411 sizeof(cache->item));
8413 fprintf(stderr, "Error adding block group\n");
8416 btrfs_extent_post_op(trans, fs_info->extent_root);
8419 ret = reset_balance(trans, fs_info);
8421 fprintf(stderr, "error reseting the pending balance\n");
8426 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8428 struct btrfs_path *path;
8429 struct btrfs_trans_handle *trans;
8430 struct btrfs_key key;
8433 printf("Recowing metadata block %llu\n", eb->start);
8434 key.objectid = btrfs_header_owner(eb);
8435 key.type = BTRFS_ROOT_ITEM_KEY;
8436 key.offset = (u64)-1;
8438 root = btrfs_read_fs_root(root->fs_info, &key);
8440 fprintf(stderr, "Couldn't find owner root %llu\n",
8442 return PTR_ERR(root);
8445 path = btrfs_alloc_path();
8449 trans = btrfs_start_transaction(root, 1);
8450 if (IS_ERR(trans)) {
8451 btrfs_free_path(path);
8452 return PTR_ERR(trans);
8455 path->lowest_level = btrfs_header_level(eb);
8456 if (path->lowest_level)
8457 btrfs_node_key_to_cpu(eb, &key, 0);
8459 btrfs_item_key_to_cpu(eb, &key, 0);
8461 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8462 btrfs_commit_transaction(trans, root);
8463 btrfs_free_path(path);
8467 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8469 struct btrfs_path *path;
8470 struct btrfs_trans_handle *trans;
8471 struct btrfs_key key;
8474 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8475 bad->key.type, bad->key.offset);
8476 key.objectid = bad->root_id;
8477 key.type = BTRFS_ROOT_ITEM_KEY;
8478 key.offset = (u64)-1;
8480 root = btrfs_read_fs_root(root->fs_info, &key);
8482 fprintf(stderr, "Couldn't find owner root %llu\n",
8484 return PTR_ERR(root);
8487 path = btrfs_alloc_path();
8491 trans = btrfs_start_transaction(root, 1);
8492 if (IS_ERR(trans)) {
8493 btrfs_free_path(path);
8494 return PTR_ERR(trans);
8497 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8503 ret = btrfs_del_item(trans, root, path);
8505 btrfs_commit_transaction(trans, root);
8506 btrfs_free_path(path);
8510 static int zero_log_tree(struct btrfs_root *root)
8512 struct btrfs_trans_handle *trans;
8515 trans = btrfs_start_transaction(root, 1);
8516 if (IS_ERR(trans)) {
8517 ret = PTR_ERR(trans);
8520 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8521 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8522 ret = btrfs_commit_transaction(trans, root);
8526 static int populate_csum(struct btrfs_trans_handle *trans,
8527 struct btrfs_root *csum_root, char *buf, u64 start,
8534 while (offset < len) {
8535 sectorsize = csum_root->sectorsize;
8536 ret = read_extent_data(csum_root, buf, start + offset,
8540 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8541 start + offset, buf, sectorsize);
8544 offset += sectorsize;
8549 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8550 struct btrfs_root *csum_root)
8552 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8553 struct btrfs_path *path;
8554 struct btrfs_extent_item *ei;
8555 struct extent_buffer *leaf;
8557 struct btrfs_key key;
8560 path = btrfs_alloc_path();
8565 key.type = BTRFS_EXTENT_ITEM_KEY;
8568 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8570 btrfs_free_path(path);
8574 buf = malloc(csum_root->sectorsize);
8576 btrfs_free_path(path);
8581 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8582 ret = btrfs_next_leaf(extent_root, path);
8590 leaf = path->nodes[0];
8592 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8593 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8598 ei = btrfs_item_ptr(leaf, path->slots[0],
8599 struct btrfs_extent_item);
8600 if (!(btrfs_extent_flags(leaf, ei) &
8601 BTRFS_EXTENT_FLAG_DATA)) {
8606 ret = populate_csum(trans, csum_root, buf, key.objectid,
8613 btrfs_free_path(path);
8618 struct root_item_info {
8619 /* level of the root */
8621 /* number of nodes at this level, must be 1 for a root */
8625 struct cache_extent cache_extent;
8628 static struct cache_tree *roots_info_cache = NULL;
8630 static void free_roots_info_cache(void)
8632 if (!roots_info_cache)
8635 while (!cache_tree_empty(roots_info_cache)) {
8636 struct cache_extent *entry;
8637 struct root_item_info *rii;
8639 entry = first_cache_extent(roots_info_cache);
8642 remove_cache_extent(roots_info_cache, entry);
8643 rii = container_of(entry, struct root_item_info, cache_extent);
8647 free(roots_info_cache);
8648 roots_info_cache = NULL;
8651 static int build_roots_info_cache(struct btrfs_fs_info *info)
8654 struct btrfs_key key;
8655 struct extent_buffer *leaf;
8656 struct btrfs_path *path;
8658 if (!roots_info_cache) {
8659 roots_info_cache = malloc(sizeof(*roots_info_cache));
8660 if (!roots_info_cache)
8662 cache_tree_init(roots_info_cache);
8665 path = btrfs_alloc_path();
8670 key.type = BTRFS_EXTENT_ITEM_KEY;
8673 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8676 leaf = path->nodes[0];
8679 struct btrfs_key found_key;
8680 struct btrfs_extent_item *ei;
8681 struct btrfs_extent_inline_ref *iref;
8682 int slot = path->slots[0];
8687 struct cache_extent *entry;
8688 struct root_item_info *rii;
8690 if (slot >= btrfs_header_nritems(leaf)) {
8691 ret = btrfs_next_leaf(info->extent_root, path);
8698 leaf = path->nodes[0];
8699 slot = path->slots[0];
8702 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8704 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8705 found_key.type != BTRFS_METADATA_ITEM_KEY)
8708 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8709 flags = btrfs_extent_flags(leaf, ei);
8711 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8712 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8715 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8716 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8717 level = found_key.offset;
8719 struct btrfs_tree_block_info *info;
8721 info = (struct btrfs_tree_block_info *)(ei + 1);
8722 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8723 level = btrfs_tree_block_level(leaf, info);
8727 * For a root extent, it must be of the following type and the
8728 * first (and only one) iref in the item.
8730 type = btrfs_extent_inline_ref_type(leaf, iref);
8731 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8734 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8735 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8737 rii = malloc(sizeof(struct root_item_info));
8742 rii->cache_extent.start = root_id;
8743 rii->cache_extent.size = 1;
8744 rii->level = (u8)-1;
8745 entry = &rii->cache_extent;
8746 ret = insert_cache_extent(roots_info_cache, entry);
8749 rii = container_of(entry, struct root_item_info,
8753 ASSERT(rii->cache_extent.start == root_id);
8754 ASSERT(rii->cache_extent.size == 1);
8756 if (level > rii->level || rii->level == (u8)-1) {
8758 rii->bytenr = found_key.objectid;
8759 rii->gen = btrfs_extent_generation(leaf, ei);
8760 rii->node_count = 1;
8761 } else if (level == rii->level) {
8769 btrfs_free_path(path);
8774 static int maybe_repair_root_item(struct btrfs_fs_info *info,
8775 struct btrfs_path *path,
8776 const struct btrfs_key *root_key,
8777 const int read_only_mode)
8779 const u64 root_id = root_key->objectid;
8780 struct cache_extent *entry;
8781 struct root_item_info *rii;
8782 struct btrfs_root_item ri;
8783 unsigned long offset;
8785 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8788 "Error: could not find extent items for root %llu\n",
8789 root_key->objectid);
8793 rii = container_of(entry, struct root_item_info, cache_extent);
8794 ASSERT(rii->cache_extent.start == root_id);
8795 ASSERT(rii->cache_extent.size == 1);
8797 if (rii->node_count != 1) {
8799 "Error: could not find btree root extent for root %llu\n",
8804 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
8805 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
8807 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
8808 btrfs_root_level(&ri) != rii->level ||
8809 btrfs_root_generation(&ri) != rii->gen) {
8812 * If we're in repair mode but our caller told us to not update
8813 * the root item, i.e. just check if it needs to be updated, don't
8814 * print this message, since the caller will call us again shortly
8815 * for the same root item without read only mode (the caller will
8816 * open a transaction first).
8818 if (!(read_only_mode && repair))
8820 "%sroot item for root %llu,"
8821 " current bytenr %llu, current gen %llu, current level %u,"
8822 " new bytenr %llu, new gen %llu, new level %u\n",
8823 (read_only_mode ? "" : "fixing "),
8825 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
8826 btrfs_root_level(&ri),
8827 rii->bytenr, rii->gen, rii->level);
8829 if (btrfs_root_generation(&ri) > rii->gen) {
8831 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
8832 root_id, btrfs_root_generation(&ri), rii->gen);
8836 if (!read_only_mode) {
8837 btrfs_set_root_bytenr(&ri, rii->bytenr);
8838 btrfs_set_root_level(&ri, rii->level);
8839 btrfs_set_root_generation(&ri, rii->gen);
8840 write_extent_buffer(path->nodes[0], &ri,
8841 offset, sizeof(ri));
8851 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
8852 * caused read-only snapshots to be corrupted if they were created at a moment
8853 * when the source subvolume/snapshot had orphan items. The issue was that the
8854 * on-disk root items became incorrect, referring to the pre orphan cleanup root
8855 * node instead of the post orphan cleanup root node.
8856 * So this function, and its callees, just detects and fixes those cases. Even
8857 * though the regression was for read-only snapshots, this function applies to
8858 * any snapshot/subvolume root.
8859 * This must be run before any other repair code - not doing it so, makes other
8860 * repair code delete or modify backrefs in the extent tree for example, which
8861 * will result in an inconsistent fs after repairing the root items.
8863 static int repair_root_items(struct btrfs_fs_info *info)
8865 struct btrfs_path *path = NULL;
8866 struct btrfs_key key;
8867 struct extent_buffer *leaf;
8868 struct btrfs_trans_handle *trans = NULL;
8873 ret = build_roots_info_cache(info);
8877 path = btrfs_alloc_path();
8883 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
8884 key.type = BTRFS_ROOT_ITEM_KEY;
8889 * Avoid opening and committing transactions if a leaf doesn't have
8890 * any root items that need to be fixed, so that we avoid rotating
8891 * backup roots unnecessarily.
8894 trans = btrfs_start_transaction(info->tree_root, 1);
8895 if (IS_ERR(trans)) {
8896 ret = PTR_ERR(trans);
8901 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
8905 leaf = path->nodes[0];
8908 struct btrfs_key found_key;
8910 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
8911 int no_more_keys = find_next_key(path, &key);
8913 btrfs_release_path(path);
8915 ret = btrfs_commit_transaction(trans,
8927 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8929 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
8931 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
8934 ret = maybe_repair_root_item(info, path, &found_key,
8939 if (!trans && repair) {
8942 btrfs_release_path(path);
8952 free_roots_info_cache();
8954 btrfs_free_path(path);
8956 btrfs_commit_transaction(trans, info->tree_root);
8963 const char * const cmd_check_usage[] = {
8964 "btrfs check [options] <device>",
8965 "Check an unmounted btrfs filesystem.",
8967 "-s|--super <superblock> use this superblock copy",
8968 "-b|--backup use the backup root copy",
8969 "--repair try to repair the filesystem",
8970 "--init-csum-tree create a new CRC tree",
8971 "--init-extent-tree create a new extent tree",
8972 "--check-data-csum verify checkums of data blocks",
8973 "--qgroup-report print a report on qgroup consistency",
8974 "--subvol-extents <subvolid> print subvolume extents and sharing state",
8975 "--tree-root <bytenr> use the given bytenr for the tree root",
8979 int cmd_check(int argc, char **argv)
8981 struct cache_tree root_cache;
8982 struct btrfs_root *root;
8983 struct btrfs_fs_info *info;
8986 u64 tree_root_bytenr = 0;
8987 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
8990 int init_csum_tree = 0;
8992 int qgroup_report = 0;
8993 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
8997 int option_index = 0;
8998 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
8999 OPT_CHECK_CSUM, OPT_READONLY };
9000 static const struct option long_options[] = {
9001 { "super", 1, NULL, 's' },
9002 { "repair", 0, NULL, OPT_REPAIR },
9003 { "readonly", 0, NULL, OPT_READONLY },
9004 { "init-csum-tree", 0, NULL, OPT_INIT_CSUM },
9005 { "init-extent-tree", 0, NULL, OPT_INIT_EXTENT },
9006 { "check-data-csum", 0, NULL, OPT_CHECK_CSUM },
9007 { "backup", 0, NULL, 'b' },
9008 { "subvol-extents", 1, NULL, 'E' },
9009 { "qgroup-report", 0, NULL, 'Q' },
9010 { "tree-root", 1, NULL, 'r' },
9014 c = getopt_long(argc, argv, "as:br:", long_options,
9019 case 'a': /* ignored */ break;
9021 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9024 num = arg_strtou64(optarg);
9025 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9027 "ERROR: super mirror should be less than: %d\n",
9028 BTRFS_SUPER_MIRROR_MAX);
9031 bytenr = btrfs_sb_offset(((int)num));
9032 printf("using SB copy %llu, bytenr %llu\n", num,
9033 (unsigned long long)bytenr);
9039 subvolid = arg_strtou64(optarg);
9042 tree_root_bytenr = arg_strtou64(optarg);
9046 usage(cmd_check_usage);
9048 printf("enabling repair mode\n");
9050 ctree_flags |= OPEN_CTREE_WRITES;
9056 printf("Creating a new CRC tree\n");
9059 ctree_flags |= OPEN_CTREE_WRITES;
9061 case OPT_INIT_EXTENT:
9062 init_extent_tree = 1;
9063 ctree_flags |= (OPEN_CTREE_WRITES |
9064 OPEN_CTREE_NO_BLOCK_GROUPS);
9067 case OPT_CHECK_CSUM:
9068 check_data_csum = 1;
9072 argc = argc - optind;
9074 if (check_argc_exact(argc, 1))
9075 usage(cmd_check_usage);
9077 /* This check is the only reason for --readonly to exist */
9078 if (readonly && repair) {
9079 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9084 cache_tree_init(&root_cache);
9086 if((ret = check_mounted(argv[optind])) < 0) {
9087 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9090 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9095 /* only allow partial opening under repair mode */
9097 ctree_flags |= OPEN_CTREE_PARTIAL;
9099 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9102 fprintf(stderr, "Couldn't open file system\n");
9107 root = info->fs_root;
9110 * repair mode will force us to commit transaction which
9111 * will make us fail to load log tree when mounting.
9113 if (repair && btrfs_super_log_root(info->super_copy)) {
9114 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9119 ret = zero_log_tree(root);
9121 fprintf(stderr, "fail to zero log tree\n");
9126 uuid_unparse(info->super_copy->fsid, uuidbuf);
9127 if (qgroup_report) {
9128 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9130 ret = qgroup_verify_all(info);
9132 print_qgroup_report(1);
9136 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9137 subvolid, argv[optind], uuidbuf);
9138 ret = print_extent_state(info, subvolid);
9141 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9143 if (!extent_buffer_uptodate(info->tree_root->node) ||
9144 !extent_buffer_uptodate(info->dev_root->node) ||
9145 !extent_buffer_uptodate(info->chunk_root->node)) {
9146 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9151 if (init_extent_tree || init_csum_tree) {
9152 struct btrfs_trans_handle *trans;
9154 trans = btrfs_start_transaction(info->extent_root, 0);
9155 if (IS_ERR(trans)) {
9156 fprintf(stderr, "Error starting transaction\n");
9157 ret = PTR_ERR(trans);
9161 if (init_extent_tree) {
9162 printf("Creating a new extent tree\n");
9163 ret = reinit_extent_tree(trans, info);
9168 if (init_csum_tree) {
9169 fprintf(stderr, "Reinit crc root\n");
9170 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9172 fprintf(stderr, "crc root initialization failed\n");
9177 ret = fill_csum_tree(trans, info->csum_root);
9179 fprintf(stderr, "crc refilling failed\n");
9184 * Ok now we commit and run the normal fsck, which will add
9185 * extent entries for all of the items it finds.
9187 ret = btrfs_commit_transaction(trans, info->extent_root);
9191 if (!extent_buffer_uptodate(info->extent_root->node)) {
9192 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9196 if (!extent_buffer_uptodate(info->csum_root->node)) {
9197 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9202 fprintf(stderr, "checking extents\n");
9203 ret = check_chunks_and_extents(root);
9205 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9207 ret = repair_root_items(info);
9211 fprintf(stderr, "Fixed %d roots.\n", ret);
9213 } else if (ret > 0) {
9215 "Found %d roots with an outdated root item.\n",
9218 "Please run a filesystem check with the option --repair to fix them.\n");
9223 fprintf(stderr, "checking free space cache\n");
9224 ret = check_space_cache(root);
9229 * We used to have to have these hole extents in between our real
9230 * extents so if we don't have this flag set we need to make sure there
9231 * are no gaps in the file extents for inodes, otherwise we can just
9232 * ignore it when this happens.
9234 no_holes = btrfs_fs_incompat(root->fs_info,
9235 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9236 fprintf(stderr, "checking fs roots\n");
9237 ret = check_fs_roots(root, &root_cache);
9241 fprintf(stderr, "checking csums\n");
9242 ret = check_csums(root);
9246 fprintf(stderr, "checking root refs\n");
9247 ret = check_root_refs(root, &root_cache);
9251 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9252 struct extent_buffer *eb;
9254 eb = list_first_entry(&root->fs_info->recow_ebs,
9255 struct extent_buffer, recow);
9256 list_del_init(&eb->recow);
9257 ret = recow_extent_buffer(root, eb);
9262 while (!list_empty(&delete_items)) {
9263 struct bad_item *bad;
9265 bad = list_first_entry(&delete_items, struct bad_item, list);
9266 list_del_init(&bad->list);
9268 ret = delete_bad_item(root, bad);
9272 if (info->quota_enabled) {
9274 fprintf(stderr, "checking quota groups\n");
9275 err = qgroup_verify_all(info);
9280 if (!list_empty(&root->fs_info->recow_ebs)) {
9281 fprintf(stderr, "Transid errors in file system\n");
9285 print_qgroup_report(0);
9286 if (found_old_backref) { /*
9287 * there was a disk format change when mixed
9288 * backref was in testing tree. The old format
9289 * existed about one week.
9291 printf("\n * Found old mixed backref format. "
9292 "The old format is not supported! *"
9293 "\n * Please mount the FS in readonly mode, "
9294 "backup data and re-format the FS. *\n\n");
9297 printf("found %llu bytes used err is %d\n",
9298 (unsigned long long)bytes_used, ret);
9299 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9300 printf("total tree bytes: %llu\n",
9301 (unsigned long long)total_btree_bytes);
9302 printf("total fs tree bytes: %llu\n",
9303 (unsigned long long)total_fs_tree_bytes);
9304 printf("total extent tree bytes: %llu\n",
9305 (unsigned long long)total_extent_tree_bytes);
9306 printf("btree space waste bytes: %llu\n",
9307 (unsigned long long)btree_space_waste);
9308 printf("file data blocks allocated: %llu\n referenced %llu\n",
9309 (unsigned long long)data_bytes_allocated,
9310 (unsigned long long)data_bytes_referenced);
9311 printf("%s\n", PACKAGE_STRING);
9313 free_root_recs_tree(&root_cache);