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 int flag_block_full_backref;
123 unsigned int found_rec:1;
124 unsigned int content_checked:1;
125 unsigned int owner_ref_checked:1;
126 unsigned int is_root:1;
127 unsigned int metadata:1;
128 unsigned int bad_full_backref:1;
131 struct inode_backref {
132 struct list_head list;
133 unsigned int found_dir_item:1;
134 unsigned int found_dir_index:1;
135 unsigned int found_inode_ref:1;
136 unsigned int filetype:8;
138 unsigned int ref_type;
145 struct root_item_record {
146 struct list_head list;
153 struct btrfs_key drop_key;
156 #define REF_ERR_NO_DIR_ITEM (1 << 0)
157 #define REF_ERR_NO_DIR_INDEX (1 << 1)
158 #define REF_ERR_NO_INODE_REF (1 << 2)
159 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
160 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
161 #define REF_ERR_DUP_INODE_REF (1 << 5)
162 #define REF_ERR_INDEX_UNMATCH (1 << 6)
163 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
164 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
165 #define REF_ERR_NO_ROOT_REF (1 << 9)
166 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
167 #define REF_ERR_DUP_ROOT_REF (1 << 11)
168 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
170 struct file_extent_hole {
176 /* Compatible function to allow reuse of old codes */
177 static u64 first_extent_gap(struct rb_root *holes)
179 struct file_extent_hole *hole;
181 if (RB_EMPTY_ROOT(holes))
184 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
188 int compare_hole(struct rb_node *node1, struct rb_node *node2)
190 struct file_extent_hole *hole1;
191 struct file_extent_hole *hole2;
193 hole1 = rb_entry(node1, struct file_extent_hole, node);
194 hole2 = rb_entry(node2, struct file_extent_hole, node);
196 if (hole1->start > hole2->start)
198 if (hole1->start < hole2->start)
200 /* Now hole1->start == hole2->start */
201 if (hole1->len >= hole2->len)
203 * Hole 1 will be merge center
204 * Same hole will be merged later
207 /* Hole 2 will be merge center */
212 * Add a hole to the record
214 * This will do hole merge for copy_file_extent_holes(),
215 * which will ensure there won't be continuous holes.
217 static int add_file_extent_hole(struct rb_root *holes,
220 struct file_extent_hole *hole;
221 struct file_extent_hole *prev = NULL;
222 struct file_extent_hole *next = NULL;
224 hole = malloc(sizeof(*hole));
229 /* Since compare will not return 0, no -EEXIST will happen */
230 rb_insert(holes, &hole->node, compare_hole);
232 /* simple merge with previous hole */
233 if (rb_prev(&hole->node))
234 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
236 if (prev && prev->start + prev->len >= hole->start) {
237 hole->len = hole->start + hole->len - prev->start;
238 hole->start = prev->start;
239 rb_erase(&prev->node, holes);
244 /* iterate merge with next holes */
246 if (!rb_next(&hole->node))
248 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
250 if (hole->start + hole->len >= next->start) {
251 if (hole->start + hole->len <= next->start + next->len)
252 hole->len = next->start + next->len -
254 rb_erase(&next->node, holes);
263 static int compare_hole_range(struct rb_node *node, void *data)
265 struct file_extent_hole *hole;
268 hole = (struct file_extent_hole *)data;
271 hole = rb_entry(node, struct file_extent_hole, node);
272 if (start < hole->start)
274 if (start >= hole->start && start < hole->start + hole->len)
280 * Delete a hole in the record
282 * This will do the hole split and is much restrict than add.
284 static int del_file_extent_hole(struct rb_root *holes,
287 struct file_extent_hole *hole;
288 struct file_extent_hole tmp;
293 struct rb_node *node;
300 node = rb_search(holes, &tmp, compare_hole_range, NULL);
303 hole = rb_entry(node, struct file_extent_hole, node);
304 if (start + len > hole->start + hole->len)
308 * Now there will be no overflap, delete the hole and re-add the
309 * split(s) if they exists.
311 if (start > hole->start) {
312 prev_start = hole->start;
313 prev_len = start - hole->start;
316 if (hole->start + hole->len > start + len) {
317 next_start = start + len;
318 next_len = hole->start + hole->len - start - len;
321 rb_erase(node, holes);
324 ret = add_file_extent_hole(holes, prev_start, prev_len);
329 ret = add_file_extent_hole(holes, next_start, next_len);
336 static int copy_file_extent_holes(struct rb_root *dst,
339 struct file_extent_hole *hole;
340 struct rb_node *node;
343 node = rb_first(src);
345 hole = rb_entry(node, struct file_extent_hole, node);
346 ret = add_file_extent_hole(dst, hole->start, hole->len);
349 node = rb_next(node);
354 static void free_file_extent_holes(struct rb_root *holes)
356 struct rb_node *node;
357 struct file_extent_hole *hole;
359 node = rb_first(holes);
361 hole = rb_entry(node, struct file_extent_hole, node);
362 rb_erase(node, holes);
364 node = rb_first(holes);
368 struct inode_record {
369 struct list_head backrefs;
370 unsigned int checked:1;
371 unsigned int merging:1;
372 unsigned int found_inode_item:1;
373 unsigned int found_dir_item:1;
374 unsigned int found_file_extent:1;
375 unsigned int found_csum_item:1;
376 unsigned int some_csum_missing:1;
377 unsigned int nodatasum:1;
390 struct rb_root holes;
391 struct list_head orphan_extents;
396 #define I_ERR_NO_INODE_ITEM (1 << 0)
397 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
398 #define I_ERR_DUP_INODE_ITEM (1 << 2)
399 #define I_ERR_DUP_DIR_INDEX (1 << 3)
400 #define I_ERR_ODD_DIR_ITEM (1 << 4)
401 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
402 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
403 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
404 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
405 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
406 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
407 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
408 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
409 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
410 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
412 struct root_backref {
413 struct list_head list;
414 unsigned int found_dir_item:1;
415 unsigned int found_dir_index:1;
416 unsigned int found_back_ref:1;
417 unsigned int found_forward_ref:1;
418 unsigned int reachable:1;
428 struct list_head backrefs;
429 struct cache_extent cache;
430 unsigned int found_root_item:1;
436 struct cache_extent cache;
441 struct cache_extent cache;
442 struct cache_tree root_cache;
443 struct cache_tree inode_cache;
444 struct inode_record *current;
453 struct walk_control {
454 struct cache_tree shared;
455 struct shared_node *nodes[BTRFS_MAX_LEVEL];
461 struct btrfs_key key;
463 struct list_head list;
466 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
468 static void record_root_in_trans(struct btrfs_trans_handle *trans,
469 struct btrfs_root *root)
471 if (root->last_trans != trans->transid) {
472 root->track_dirty = 1;
473 root->last_trans = trans->transid;
474 root->commit_root = root->node;
475 extent_buffer_get(root->node);
479 static u8 imode_to_type(u32 imode)
482 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
483 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
484 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
485 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
486 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
487 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
488 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
489 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
492 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
496 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
498 struct device_record *rec1;
499 struct device_record *rec2;
501 rec1 = rb_entry(node1, struct device_record, node);
502 rec2 = rb_entry(node2, struct device_record, node);
503 if (rec1->devid > rec2->devid)
505 else if (rec1->devid < rec2->devid)
511 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
513 struct inode_record *rec;
514 struct inode_backref *backref;
515 struct inode_backref *orig;
516 struct orphan_data_extent *src_orphan;
517 struct orphan_data_extent *dst_orphan;
521 rec = malloc(sizeof(*rec));
522 memcpy(rec, orig_rec, sizeof(*rec));
524 INIT_LIST_HEAD(&rec->backrefs);
525 INIT_LIST_HEAD(&rec->orphan_extents);
526 rec->holes = RB_ROOT;
528 list_for_each_entry(orig, &orig_rec->backrefs, list) {
529 size = sizeof(*orig) + orig->namelen + 1;
530 backref = malloc(size);
531 memcpy(backref, orig, size);
532 list_add_tail(&backref->list, &rec->backrefs);
534 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
535 dst_orphan = malloc(sizeof(*dst_orphan));
536 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
538 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
539 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
541 ret = copy_file_extent_holes(&rec->holes, &orig_rec->holes);
547 static void print_orphan_data_extents(struct list_head *orphan_extents,
550 struct orphan_data_extent *orphan;
552 if (list_empty(orphan_extents))
554 printf("The following data extent is lost in tree %llu:\n",
556 list_for_each_entry(orphan, orphan_extents, list) {
557 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
558 orphan->objectid, orphan->offset, orphan->disk_bytenr,
563 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
565 u64 root_objectid = root->root_key.objectid;
566 int errors = rec->errors;
570 /* reloc root errors, we print its corresponding fs root objectid*/
571 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
572 root_objectid = root->root_key.offset;
573 fprintf(stderr, "reloc");
575 fprintf(stderr, "root %llu inode %llu errors %x",
576 (unsigned long long) root_objectid,
577 (unsigned long long) rec->ino, rec->errors);
579 if (errors & I_ERR_NO_INODE_ITEM)
580 fprintf(stderr, ", no inode item");
581 if (errors & I_ERR_NO_ORPHAN_ITEM)
582 fprintf(stderr, ", no orphan item");
583 if (errors & I_ERR_DUP_INODE_ITEM)
584 fprintf(stderr, ", dup inode item");
585 if (errors & I_ERR_DUP_DIR_INDEX)
586 fprintf(stderr, ", dup dir index");
587 if (errors & I_ERR_ODD_DIR_ITEM)
588 fprintf(stderr, ", odd dir item");
589 if (errors & I_ERR_ODD_FILE_EXTENT)
590 fprintf(stderr, ", odd file extent");
591 if (errors & I_ERR_BAD_FILE_EXTENT)
592 fprintf(stderr, ", bad file extent");
593 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
594 fprintf(stderr, ", file extent overlap");
595 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
596 fprintf(stderr, ", file extent discount");
597 if (errors & I_ERR_DIR_ISIZE_WRONG)
598 fprintf(stderr, ", dir isize wrong");
599 if (errors & I_ERR_FILE_NBYTES_WRONG)
600 fprintf(stderr, ", nbytes wrong");
601 if (errors & I_ERR_ODD_CSUM_ITEM)
602 fprintf(stderr, ", odd csum item");
603 if (errors & I_ERR_SOME_CSUM_MISSING)
604 fprintf(stderr, ", some csum missing");
605 if (errors & I_ERR_LINK_COUNT_WRONG)
606 fprintf(stderr, ", link count wrong");
607 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
608 fprintf(stderr, ", orphan file extent");
609 fprintf(stderr, "\n");
610 /* Print the orphan extents if needed */
611 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
612 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
614 /* Print the holes if needed */
615 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
616 struct file_extent_hole *hole;
617 struct rb_node *node;
619 node = rb_first(&rec->holes);
620 fprintf(stderr, "Found file extent holes:\n");
622 hole = rb_entry(node, struct file_extent_hole, node);
623 fprintf(stderr, "\tstart: %llu, len:%llu\n",
624 hole->start, hole->len);
625 node = rb_next(node);
630 static void print_ref_error(int errors)
632 if (errors & REF_ERR_NO_DIR_ITEM)
633 fprintf(stderr, ", no dir item");
634 if (errors & REF_ERR_NO_DIR_INDEX)
635 fprintf(stderr, ", no dir index");
636 if (errors & REF_ERR_NO_INODE_REF)
637 fprintf(stderr, ", no inode ref");
638 if (errors & REF_ERR_DUP_DIR_ITEM)
639 fprintf(stderr, ", dup dir item");
640 if (errors & REF_ERR_DUP_DIR_INDEX)
641 fprintf(stderr, ", dup dir index");
642 if (errors & REF_ERR_DUP_INODE_REF)
643 fprintf(stderr, ", dup inode ref");
644 if (errors & REF_ERR_INDEX_UNMATCH)
645 fprintf(stderr, ", index unmatch");
646 if (errors & REF_ERR_FILETYPE_UNMATCH)
647 fprintf(stderr, ", filetype unmatch");
648 if (errors & REF_ERR_NAME_TOO_LONG)
649 fprintf(stderr, ", name too long");
650 if (errors & REF_ERR_NO_ROOT_REF)
651 fprintf(stderr, ", no root ref");
652 if (errors & REF_ERR_NO_ROOT_BACKREF)
653 fprintf(stderr, ", no root backref");
654 if (errors & REF_ERR_DUP_ROOT_REF)
655 fprintf(stderr, ", dup root ref");
656 if (errors & REF_ERR_DUP_ROOT_BACKREF)
657 fprintf(stderr, ", dup root backref");
658 fprintf(stderr, "\n");
661 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
664 struct ptr_node *node;
665 struct cache_extent *cache;
666 struct inode_record *rec = NULL;
669 cache = lookup_cache_extent(inode_cache, ino, 1);
671 node = container_of(cache, struct ptr_node, cache);
673 if (mod && rec->refs > 1) {
674 node->data = clone_inode_rec(rec);
679 rec = calloc(1, sizeof(*rec));
681 rec->extent_start = (u64)-1;
683 INIT_LIST_HEAD(&rec->backrefs);
684 INIT_LIST_HEAD(&rec->orphan_extents);
685 rec->holes = RB_ROOT;
687 node = malloc(sizeof(*node));
688 node->cache.start = ino;
689 node->cache.size = 1;
692 if (ino == BTRFS_FREE_INO_OBJECTID)
695 ret = insert_cache_extent(inode_cache, &node->cache);
701 static void free_orphan_data_extents(struct list_head *orphan_extents)
703 struct orphan_data_extent *orphan;
705 while (!list_empty(orphan_extents)) {
706 orphan = list_entry(orphan_extents->next,
707 struct orphan_data_extent, list);
708 list_del(&orphan->list);
713 static void free_inode_rec(struct inode_record *rec)
715 struct inode_backref *backref;
720 while (!list_empty(&rec->backrefs)) {
721 backref = list_entry(rec->backrefs.next,
722 struct inode_backref, list);
723 list_del(&backref->list);
726 free_orphan_data_extents(&rec->orphan_extents);
727 free_file_extent_holes(&rec->holes);
731 static int can_free_inode_rec(struct inode_record *rec)
733 if (!rec->errors && rec->checked && rec->found_inode_item &&
734 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
739 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
740 struct inode_record *rec)
742 struct cache_extent *cache;
743 struct inode_backref *tmp, *backref;
744 struct ptr_node *node;
745 unsigned char filetype;
747 if (!rec->found_inode_item)
750 filetype = imode_to_type(rec->imode);
751 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
752 if (backref->found_dir_item && backref->found_dir_index) {
753 if (backref->filetype != filetype)
754 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
755 if (!backref->errors && backref->found_inode_ref) {
756 list_del(&backref->list);
762 if (!rec->checked || rec->merging)
765 if (S_ISDIR(rec->imode)) {
766 if (rec->found_size != rec->isize)
767 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
768 if (rec->found_file_extent)
769 rec->errors |= I_ERR_ODD_FILE_EXTENT;
770 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
771 if (rec->found_dir_item)
772 rec->errors |= I_ERR_ODD_DIR_ITEM;
773 if (rec->found_size != rec->nbytes)
774 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
775 if (rec->nlink > 0 && !no_holes &&
776 (rec->extent_end < rec->isize ||
777 first_extent_gap(&rec->holes) < rec->isize))
778 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
781 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
782 if (rec->found_csum_item && rec->nodatasum)
783 rec->errors |= I_ERR_ODD_CSUM_ITEM;
784 if (rec->some_csum_missing && !rec->nodatasum)
785 rec->errors |= I_ERR_SOME_CSUM_MISSING;
788 BUG_ON(rec->refs != 1);
789 if (can_free_inode_rec(rec)) {
790 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
791 node = container_of(cache, struct ptr_node, cache);
792 BUG_ON(node->data != rec);
793 remove_cache_extent(inode_cache, &node->cache);
799 static int check_orphan_item(struct btrfs_root *root, u64 ino)
801 struct btrfs_path path;
802 struct btrfs_key key;
805 key.objectid = BTRFS_ORPHAN_OBJECTID;
806 key.type = BTRFS_ORPHAN_ITEM_KEY;
809 btrfs_init_path(&path);
810 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
811 btrfs_release_path(&path);
817 static int process_inode_item(struct extent_buffer *eb,
818 int slot, struct btrfs_key *key,
819 struct shared_node *active_node)
821 struct inode_record *rec;
822 struct btrfs_inode_item *item;
824 rec = active_node->current;
825 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
826 if (rec->found_inode_item) {
827 rec->errors |= I_ERR_DUP_INODE_ITEM;
830 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
831 rec->nlink = btrfs_inode_nlink(eb, item);
832 rec->isize = btrfs_inode_size(eb, item);
833 rec->nbytes = btrfs_inode_nbytes(eb, item);
834 rec->imode = btrfs_inode_mode(eb, item);
835 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
837 rec->found_inode_item = 1;
839 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
840 maybe_free_inode_rec(&active_node->inode_cache, rec);
844 static struct inode_backref *get_inode_backref(struct inode_record *rec,
846 int namelen, u64 dir)
848 struct inode_backref *backref;
850 list_for_each_entry(backref, &rec->backrefs, list) {
851 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
853 if (backref->dir != dir || backref->namelen != namelen)
855 if (memcmp(name, backref->name, namelen))
860 backref = malloc(sizeof(*backref) + namelen + 1);
861 memset(backref, 0, sizeof(*backref));
863 backref->namelen = namelen;
864 memcpy(backref->name, name, namelen);
865 backref->name[namelen] = '\0';
866 list_add_tail(&backref->list, &rec->backrefs);
870 static int add_inode_backref(struct cache_tree *inode_cache,
871 u64 ino, u64 dir, u64 index,
872 const char *name, int namelen,
873 int filetype, int itemtype, int errors)
875 struct inode_record *rec;
876 struct inode_backref *backref;
878 rec = get_inode_rec(inode_cache, ino, 1);
879 backref = get_inode_backref(rec, name, namelen, dir);
881 backref->errors |= errors;
882 if (itemtype == BTRFS_DIR_INDEX_KEY) {
883 if (backref->found_dir_index)
884 backref->errors |= REF_ERR_DUP_DIR_INDEX;
885 if (backref->found_inode_ref && backref->index != index)
886 backref->errors |= REF_ERR_INDEX_UNMATCH;
887 if (backref->found_dir_item && backref->filetype != filetype)
888 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
890 backref->index = index;
891 backref->filetype = filetype;
892 backref->found_dir_index = 1;
893 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
895 if (backref->found_dir_item)
896 backref->errors |= REF_ERR_DUP_DIR_ITEM;
897 if (backref->found_dir_index && backref->filetype != filetype)
898 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
900 backref->filetype = filetype;
901 backref->found_dir_item = 1;
902 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
903 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
904 if (backref->found_inode_ref)
905 backref->errors |= REF_ERR_DUP_INODE_REF;
906 if (backref->found_dir_index && backref->index != index)
907 backref->errors |= REF_ERR_INDEX_UNMATCH;
909 backref->index = index;
911 backref->ref_type = itemtype;
912 backref->found_inode_ref = 1;
917 maybe_free_inode_rec(inode_cache, rec);
921 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
922 struct cache_tree *dst_cache)
924 struct inode_backref *backref;
929 list_for_each_entry(backref, &src->backrefs, list) {
930 if (backref->found_dir_index) {
931 add_inode_backref(dst_cache, dst->ino, backref->dir,
932 backref->index, backref->name,
933 backref->namelen, backref->filetype,
934 BTRFS_DIR_INDEX_KEY, backref->errors);
936 if (backref->found_dir_item) {
938 add_inode_backref(dst_cache, dst->ino,
939 backref->dir, 0, backref->name,
940 backref->namelen, backref->filetype,
941 BTRFS_DIR_ITEM_KEY, backref->errors);
943 if (backref->found_inode_ref) {
944 add_inode_backref(dst_cache, dst->ino,
945 backref->dir, backref->index,
946 backref->name, backref->namelen, 0,
947 backref->ref_type, backref->errors);
951 if (src->found_dir_item)
952 dst->found_dir_item = 1;
953 if (src->found_file_extent)
954 dst->found_file_extent = 1;
955 if (src->found_csum_item)
956 dst->found_csum_item = 1;
957 if (src->some_csum_missing)
958 dst->some_csum_missing = 1;
959 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
960 ret = copy_file_extent_holes(&dst->holes, &src->holes);
965 BUG_ON(src->found_link < dir_count);
966 dst->found_link += src->found_link - dir_count;
967 dst->found_size += src->found_size;
968 if (src->extent_start != (u64)-1) {
969 if (dst->extent_start == (u64)-1) {
970 dst->extent_start = src->extent_start;
971 dst->extent_end = src->extent_end;
973 if (dst->extent_end > src->extent_start)
974 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
975 else if (dst->extent_end < src->extent_start) {
976 ret = add_file_extent_hole(&dst->holes,
978 src->extent_start - dst->extent_end);
980 if (dst->extent_end < src->extent_end)
981 dst->extent_end = src->extent_end;
985 dst->errors |= src->errors;
986 if (src->found_inode_item) {
987 if (!dst->found_inode_item) {
988 dst->nlink = src->nlink;
989 dst->isize = src->isize;
990 dst->nbytes = src->nbytes;
991 dst->imode = src->imode;
992 dst->nodatasum = src->nodatasum;
993 dst->found_inode_item = 1;
995 dst->errors |= I_ERR_DUP_INODE_ITEM;
1003 static int splice_shared_node(struct shared_node *src_node,
1004 struct shared_node *dst_node)
1006 struct cache_extent *cache;
1007 struct ptr_node *node, *ins;
1008 struct cache_tree *src, *dst;
1009 struct inode_record *rec, *conflict;
1010 u64 current_ino = 0;
1014 if (--src_node->refs == 0)
1016 if (src_node->current)
1017 current_ino = src_node->current->ino;
1019 src = &src_node->root_cache;
1020 dst = &dst_node->root_cache;
1022 cache = search_cache_extent(src, 0);
1024 node = container_of(cache, struct ptr_node, cache);
1026 cache = next_cache_extent(cache);
1029 remove_cache_extent(src, &node->cache);
1032 ins = malloc(sizeof(*ins));
1033 ins->cache.start = node->cache.start;
1034 ins->cache.size = node->cache.size;
1038 ret = insert_cache_extent(dst, &ins->cache);
1039 if (ret == -EEXIST) {
1040 conflict = get_inode_rec(dst, rec->ino, 1);
1041 merge_inode_recs(rec, conflict, dst);
1043 conflict->checked = 1;
1044 if (dst_node->current == conflict)
1045 dst_node->current = NULL;
1047 maybe_free_inode_rec(dst, conflict);
1048 free_inode_rec(rec);
1055 if (src == &src_node->root_cache) {
1056 src = &src_node->inode_cache;
1057 dst = &dst_node->inode_cache;
1061 if (current_ino > 0 && (!dst_node->current ||
1062 current_ino > dst_node->current->ino)) {
1063 if (dst_node->current) {
1064 dst_node->current->checked = 1;
1065 maybe_free_inode_rec(dst, dst_node->current);
1067 dst_node->current = get_inode_rec(dst, current_ino, 1);
1072 static void free_inode_ptr(struct cache_extent *cache)
1074 struct ptr_node *node;
1075 struct inode_record *rec;
1077 node = container_of(cache, struct ptr_node, cache);
1079 free_inode_rec(rec);
1083 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1085 static struct shared_node *find_shared_node(struct cache_tree *shared,
1088 struct cache_extent *cache;
1089 struct shared_node *node;
1091 cache = lookup_cache_extent(shared, bytenr, 1);
1093 node = container_of(cache, struct shared_node, cache);
1099 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1102 struct shared_node *node;
1104 node = calloc(1, sizeof(*node));
1105 node->cache.start = bytenr;
1106 node->cache.size = 1;
1107 cache_tree_init(&node->root_cache);
1108 cache_tree_init(&node->inode_cache);
1111 ret = insert_cache_extent(shared, &node->cache);
1116 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1117 struct walk_control *wc, int level)
1119 struct shared_node *node;
1120 struct shared_node *dest;
1122 if (level == wc->active_node)
1125 BUG_ON(wc->active_node <= level);
1126 node = find_shared_node(&wc->shared, bytenr);
1128 add_shared_node(&wc->shared, bytenr, refs);
1129 node = find_shared_node(&wc->shared, bytenr);
1130 wc->nodes[level] = node;
1131 wc->active_node = level;
1135 if (wc->root_level == wc->active_node &&
1136 btrfs_root_refs(&root->root_item) == 0) {
1137 if (--node->refs == 0) {
1138 free_inode_recs_tree(&node->root_cache);
1139 free_inode_recs_tree(&node->inode_cache);
1140 remove_cache_extent(&wc->shared, &node->cache);
1146 dest = wc->nodes[wc->active_node];
1147 splice_shared_node(node, dest);
1148 if (node->refs == 0) {
1149 remove_cache_extent(&wc->shared, &node->cache);
1155 static int leave_shared_node(struct btrfs_root *root,
1156 struct walk_control *wc, int level)
1158 struct shared_node *node;
1159 struct shared_node *dest;
1162 if (level == wc->root_level)
1165 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1169 BUG_ON(i >= BTRFS_MAX_LEVEL);
1171 node = wc->nodes[wc->active_node];
1172 wc->nodes[wc->active_node] = NULL;
1173 wc->active_node = i;
1175 dest = wc->nodes[wc->active_node];
1176 if (wc->active_node < wc->root_level ||
1177 btrfs_root_refs(&root->root_item) > 0) {
1178 BUG_ON(node->refs <= 1);
1179 splice_shared_node(node, dest);
1181 BUG_ON(node->refs < 2);
1190 * 1 - if the root with id child_root_id is a child of root parent_root_id
1191 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1192 * has other root(s) as parent(s)
1193 * 2 - if the root child_root_id doesn't have any parent roots
1195 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1198 struct btrfs_path path;
1199 struct btrfs_key key;
1200 struct extent_buffer *leaf;
1204 btrfs_init_path(&path);
1206 key.objectid = parent_root_id;
1207 key.type = BTRFS_ROOT_REF_KEY;
1208 key.offset = child_root_id;
1209 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1213 btrfs_release_path(&path);
1217 key.objectid = child_root_id;
1218 key.type = BTRFS_ROOT_BACKREF_KEY;
1220 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1226 leaf = path.nodes[0];
1227 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1228 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1231 leaf = path.nodes[0];
1234 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1235 if (key.objectid != child_root_id ||
1236 key.type != BTRFS_ROOT_BACKREF_KEY)
1241 if (key.offset == parent_root_id) {
1242 btrfs_release_path(&path);
1249 btrfs_release_path(&path);
1252 return has_parent ? 0 : 2;
1255 static int process_dir_item(struct btrfs_root *root,
1256 struct extent_buffer *eb,
1257 int slot, struct btrfs_key *key,
1258 struct shared_node *active_node)
1268 struct btrfs_dir_item *di;
1269 struct inode_record *rec;
1270 struct cache_tree *root_cache;
1271 struct cache_tree *inode_cache;
1272 struct btrfs_key location;
1273 char namebuf[BTRFS_NAME_LEN];
1275 root_cache = &active_node->root_cache;
1276 inode_cache = &active_node->inode_cache;
1277 rec = active_node->current;
1278 rec->found_dir_item = 1;
1280 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1281 total = btrfs_item_size_nr(eb, slot);
1282 while (cur < total) {
1284 btrfs_dir_item_key_to_cpu(eb, di, &location);
1285 name_len = btrfs_dir_name_len(eb, di);
1286 data_len = btrfs_dir_data_len(eb, di);
1287 filetype = btrfs_dir_type(eb, di);
1289 rec->found_size += name_len;
1290 if (name_len <= BTRFS_NAME_LEN) {
1294 len = BTRFS_NAME_LEN;
1295 error = REF_ERR_NAME_TOO_LONG;
1297 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1299 if (location.type == BTRFS_INODE_ITEM_KEY) {
1300 add_inode_backref(inode_cache, location.objectid,
1301 key->objectid, key->offset, namebuf,
1302 len, filetype, key->type, error);
1303 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1304 add_inode_backref(root_cache, location.objectid,
1305 key->objectid, key->offset,
1306 namebuf, len, filetype,
1309 fprintf(stderr, "invalid location in dir item %u\n",
1311 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1312 key->objectid, key->offset, namebuf,
1313 len, filetype, key->type, error);
1316 len = sizeof(*di) + name_len + data_len;
1317 di = (struct btrfs_dir_item *)((char *)di + len);
1320 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1321 rec->errors |= I_ERR_DUP_DIR_INDEX;
1326 static int process_inode_ref(struct extent_buffer *eb,
1327 int slot, struct btrfs_key *key,
1328 struct shared_node *active_node)
1336 struct cache_tree *inode_cache;
1337 struct btrfs_inode_ref *ref;
1338 char namebuf[BTRFS_NAME_LEN];
1340 inode_cache = &active_node->inode_cache;
1342 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1343 total = btrfs_item_size_nr(eb, slot);
1344 while (cur < total) {
1345 name_len = btrfs_inode_ref_name_len(eb, ref);
1346 index = btrfs_inode_ref_index(eb, ref);
1347 if (name_len <= BTRFS_NAME_LEN) {
1351 len = BTRFS_NAME_LEN;
1352 error = REF_ERR_NAME_TOO_LONG;
1354 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1355 add_inode_backref(inode_cache, key->objectid, key->offset,
1356 index, namebuf, len, 0, key->type, error);
1358 len = sizeof(*ref) + name_len;
1359 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1365 static int process_inode_extref(struct extent_buffer *eb,
1366 int slot, struct btrfs_key *key,
1367 struct shared_node *active_node)
1376 struct cache_tree *inode_cache;
1377 struct btrfs_inode_extref *extref;
1378 char namebuf[BTRFS_NAME_LEN];
1380 inode_cache = &active_node->inode_cache;
1382 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1383 total = btrfs_item_size_nr(eb, slot);
1384 while (cur < total) {
1385 name_len = btrfs_inode_extref_name_len(eb, extref);
1386 index = btrfs_inode_extref_index(eb, extref);
1387 parent = btrfs_inode_extref_parent(eb, extref);
1388 if (name_len <= BTRFS_NAME_LEN) {
1392 len = BTRFS_NAME_LEN;
1393 error = REF_ERR_NAME_TOO_LONG;
1395 read_extent_buffer(eb, namebuf,
1396 (unsigned long)(extref + 1), len);
1397 add_inode_backref(inode_cache, key->objectid, parent,
1398 index, namebuf, len, 0, key->type, error);
1400 len = sizeof(*extref) + name_len;
1401 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1408 static int count_csum_range(struct btrfs_root *root, u64 start,
1409 u64 len, u64 *found)
1411 struct btrfs_key key;
1412 struct btrfs_path path;
1413 struct extent_buffer *leaf;
1418 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1420 btrfs_init_path(&path);
1422 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1424 key.type = BTRFS_EXTENT_CSUM_KEY;
1426 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1430 if (ret > 0 && path.slots[0] > 0) {
1431 leaf = path.nodes[0];
1432 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1433 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1434 key.type == BTRFS_EXTENT_CSUM_KEY)
1439 leaf = path.nodes[0];
1440 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1441 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1446 leaf = path.nodes[0];
1449 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1450 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1451 key.type != BTRFS_EXTENT_CSUM_KEY)
1454 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1455 if (key.offset >= start + len)
1458 if (key.offset > start)
1461 size = btrfs_item_size_nr(leaf, path.slots[0]);
1462 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1463 if (csum_end > start) {
1464 size = min(csum_end - start, len);
1473 btrfs_release_path(&path);
1479 static int process_file_extent(struct btrfs_root *root,
1480 struct extent_buffer *eb,
1481 int slot, struct btrfs_key *key,
1482 struct shared_node *active_node)
1484 struct inode_record *rec;
1485 struct btrfs_file_extent_item *fi;
1487 u64 disk_bytenr = 0;
1488 u64 extent_offset = 0;
1489 u64 mask = root->sectorsize - 1;
1493 rec = active_node->current;
1494 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1495 rec->found_file_extent = 1;
1497 if (rec->extent_start == (u64)-1) {
1498 rec->extent_start = key->offset;
1499 rec->extent_end = key->offset;
1502 if (rec->extent_end > key->offset)
1503 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1504 else if (rec->extent_end < key->offset) {
1505 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1506 key->offset - rec->extent_end);
1511 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1512 extent_type = btrfs_file_extent_type(eb, fi);
1514 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1515 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1517 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1518 rec->found_size += num_bytes;
1519 num_bytes = (num_bytes + mask) & ~mask;
1520 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1521 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1522 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1523 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1524 extent_offset = btrfs_file_extent_offset(eb, fi);
1525 if (num_bytes == 0 || (num_bytes & mask))
1526 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1527 if (num_bytes + extent_offset >
1528 btrfs_file_extent_ram_bytes(eb, fi))
1529 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1530 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1531 (btrfs_file_extent_compression(eb, fi) ||
1532 btrfs_file_extent_encryption(eb, fi) ||
1533 btrfs_file_extent_other_encoding(eb, fi)))
1534 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1535 if (disk_bytenr > 0)
1536 rec->found_size += num_bytes;
1538 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1540 rec->extent_end = key->offset + num_bytes;
1543 * The data reloc tree will copy full extents into its inode and then
1544 * copy the corresponding csums. Because the extent it copied could be
1545 * a preallocated extent that hasn't been written to yet there may be no
1546 * csums to copy, ergo we won't have csums for our file extent. This is
1547 * ok so just don't bother checking csums if the inode belongs to the
1550 if (disk_bytenr > 0 &&
1551 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1553 if (btrfs_file_extent_compression(eb, fi))
1554 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1556 disk_bytenr += extent_offset;
1558 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1561 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1563 rec->found_csum_item = 1;
1564 if (found < num_bytes)
1565 rec->some_csum_missing = 1;
1566 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1568 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1574 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1575 struct walk_control *wc)
1577 struct btrfs_key key;
1581 struct cache_tree *inode_cache;
1582 struct shared_node *active_node;
1584 if (wc->root_level == wc->active_node &&
1585 btrfs_root_refs(&root->root_item) == 0)
1588 active_node = wc->nodes[wc->active_node];
1589 inode_cache = &active_node->inode_cache;
1590 nritems = btrfs_header_nritems(eb);
1591 for (i = 0; i < nritems; i++) {
1592 btrfs_item_key_to_cpu(eb, &key, i);
1594 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1596 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1599 if (active_node->current == NULL ||
1600 active_node->current->ino < key.objectid) {
1601 if (active_node->current) {
1602 active_node->current->checked = 1;
1603 maybe_free_inode_rec(inode_cache,
1604 active_node->current);
1606 active_node->current = get_inode_rec(inode_cache,
1610 case BTRFS_DIR_ITEM_KEY:
1611 case BTRFS_DIR_INDEX_KEY:
1612 ret = process_dir_item(root, eb, i, &key, active_node);
1614 case BTRFS_INODE_REF_KEY:
1615 ret = process_inode_ref(eb, i, &key, active_node);
1617 case BTRFS_INODE_EXTREF_KEY:
1618 ret = process_inode_extref(eb, i, &key, active_node);
1620 case BTRFS_INODE_ITEM_KEY:
1621 ret = process_inode_item(eb, i, &key, active_node);
1623 case BTRFS_EXTENT_DATA_KEY:
1624 ret = process_file_extent(root, eb, i, &key,
1634 static void reada_walk_down(struct btrfs_root *root,
1635 struct extent_buffer *node, int slot)
1644 level = btrfs_header_level(node);
1648 nritems = btrfs_header_nritems(node);
1649 blocksize = btrfs_level_size(root, level - 1);
1650 for (i = slot; i < nritems; i++) {
1651 bytenr = btrfs_node_blockptr(node, i);
1652 ptr_gen = btrfs_node_ptr_generation(node, i);
1653 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1658 * Check the child node/leaf by the following condition:
1659 * 1. the first item key of the node/leaf should be the same with the one
1661 * 2. block in parent node should match the child node/leaf.
1662 * 3. generation of parent node and child's header should be consistent.
1664 * Or the child node/leaf pointed by the key in parent is not valid.
1666 * We hope to check leaf owner too, but since subvol may share leaves,
1667 * which makes leaf owner check not so strong, key check should be
1668 * sufficient enough for that case.
1670 static int check_child_node(struct btrfs_root *root,
1671 struct extent_buffer *parent, int slot,
1672 struct extent_buffer *child)
1674 struct btrfs_key parent_key;
1675 struct btrfs_key child_key;
1678 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1679 if (btrfs_header_level(child) == 0)
1680 btrfs_item_key_to_cpu(child, &child_key, 0);
1682 btrfs_node_key_to_cpu(child, &child_key, 0);
1684 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1687 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1688 parent_key.objectid, parent_key.type, parent_key.offset,
1689 child_key.objectid, child_key.type, child_key.offset);
1691 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1693 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1694 btrfs_node_blockptr(parent, slot),
1695 btrfs_header_bytenr(child));
1697 if (btrfs_node_ptr_generation(parent, slot) !=
1698 btrfs_header_generation(child)) {
1700 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1701 btrfs_header_generation(child),
1702 btrfs_node_ptr_generation(parent, slot));
1707 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1708 struct walk_control *wc, int *level)
1710 enum btrfs_tree_block_status status;
1713 struct extent_buffer *next;
1714 struct extent_buffer *cur;
1719 WARN_ON(*level < 0);
1720 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1721 ret = btrfs_lookup_extent_info(NULL, root,
1722 path->nodes[*level]->start,
1723 *level, 1, &refs, NULL);
1730 ret = enter_shared_node(root, path->nodes[*level]->start,
1738 while (*level >= 0) {
1739 WARN_ON(*level < 0);
1740 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1741 cur = path->nodes[*level];
1743 if (btrfs_header_level(cur) != *level)
1746 if (path->slots[*level] >= btrfs_header_nritems(cur))
1749 ret = process_one_leaf(root, cur, wc);
1754 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1755 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1756 blocksize = btrfs_level_size(root, *level - 1);
1757 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1763 ret = enter_shared_node(root, bytenr, refs,
1766 path->slots[*level]++;
1771 next = btrfs_find_tree_block(root, bytenr, blocksize);
1772 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1773 free_extent_buffer(next);
1774 reada_walk_down(root, cur, path->slots[*level]);
1775 next = read_tree_block(root, bytenr, blocksize,
1777 if (!extent_buffer_uptodate(next)) {
1778 struct btrfs_key node_key;
1780 btrfs_node_key_to_cpu(path->nodes[*level],
1782 path->slots[*level]);
1783 btrfs_add_corrupt_extent_record(root->fs_info,
1785 path->nodes[*level]->start,
1786 root->leafsize, *level);
1792 ret = check_child_node(root, cur, path->slots[*level], next);
1798 if (btrfs_is_leaf(next))
1799 status = btrfs_check_leaf(root, NULL, next);
1801 status = btrfs_check_node(root, NULL, next);
1802 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1803 free_extent_buffer(next);
1808 *level = *level - 1;
1809 free_extent_buffer(path->nodes[*level]);
1810 path->nodes[*level] = next;
1811 path->slots[*level] = 0;
1814 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1818 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1819 struct walk_control *wc, int *level)
1822 struct extent_buffer *leaf;
1824 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1825 leaf = path->nodes[i];
1826 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1831 free_extent_buffer(path->nodes[*level]);
1832 path->nodes[*level] = NULL;
1833 BUG_ON(*level > wc->active_node);
1834 if (*level == wc->active_node)
1835 leave_shared_node(root, wc, *level);
1842 static int check_root_dir(struct inode_record *rec)
1844 struct inode_backref *backref;
1847 if (!rec->found_inode_item || rec->errors)
1849 if (rec->nlink != 1 || rec->found_link != 0)
1851 if (list_empty(&rec->backrefs))
1853 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1854 if (!backref->found_inode_ref)
1856 if (backref->index != 0 || backref->namelen != 2 ||
1857 memcmp(backref->name, "..", 2))
1859 if (backref->found_dir_index || backref->found_dir_item)
1866 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1867 struct btrfs_root *root, struct btrfs_path *path,
1868 struct inode_record *rec)
1870 struct btrfs_inode_item *ei;
1871 struct btrfs_key key;
1874 key.objectid = rec->ino;
1875 key.type = BTRFS_INODE_ITEM_KEY;
1876 key.offset = (u64)-1;
1878 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1882 if (!path->slots[0]) {
1889 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1890 if (key.objectid != rec->ino) {
1895 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1896 struct btrfs_inode_item);
1897 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1898 btrfs_mark_buffer_dirty(path->nodes[0]);
1899 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1900 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1901 root->root_key.objectid);
1903 btrfs_release_path(path);
1907 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1908 struct btrfs_root *root,
1909 struct btrfs_path *path,
1910 struct inode_record *rec)
1914 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1915 btrfs_release_path(path);
1917 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1921 static int repair_inode_nbytes(struct btrfs_trans_handle *trans,
1922 struct btrfs_root *root,
1923 struct btrfs_path *path,
1924 struct inode_record *rec)
1926 struct btrfs_inode_item *ei;
1927 struct btrfs_key key;
1930 key.objectid = rec->ino;
1931 key.type = BTRFS_INODE_ITEM_KEY;
1934 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1941 /* Since ret == 0, no need to check anything */
1942 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1943 struct btrfs_inode_item);
1944 btrfs_set_inode_nbytes(path->nodes[0], ei, rec->found_size);
1945 btrfs_mark_buffer_dirty(path->nodes[0]);
1946 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
1947 printf("reset nbytes for ino %llu root %llu\n",
1948 rec->ino, root->root_key.objectid);
1950 btrfs_release_path(path);
1954 static int add_missing_dir_index(struct btrfs_root *root,
1955 struct cache_tree *inode_cache,
1956 struct inode_record *rec,
1957 struct inode_backref *backref)
1959 struct btrfs_path *path;
1960 struct btrfs_trans_handle *trans;
1961 struct btrfs_dir_item *dir_item;
1962 struct extent_buffer *leaf;
1963 struct btrfs_key key;
1964 struct btrfs_disk_key disk_key;
1965 struct inode_record *dir_rec;
1966 unsigned long name_ptr;
1967 u32 data_size = sizeof(*dir_item) + backref->namelen;
1970 path = btrfs_alloc_path();
1974 trans = btrfs_start_transaction(root, 1);
1975 if (IS_ERR(trans)) {
1976 btrfs_free_path(path);
1977 return PTR_ERR(trans);
1980 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1981 (unsigned long long)rec->ino);
1982 key.objectid = backref->dir;
1983 key.type = BTRFS_DIR_INDEX_KEY;
1984 key.offset = backref->index;
1986 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1989 leaf = path->nodes[0];
1990 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
1992 disk_key.objectid = cpu_to_le64(rec->ino);
1993 disk_key.type = BTRFS_INODE_ITEM_KEY;
1994 disk_key.offset = 0;
1996 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
1997 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
1998 btrfs_set_dir_data_len(leaf, dir_item, 0);
1999 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
2000 name_ptr = (unsigned long)(dir_item + 1);
2001 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
2002 btrfs_mark_buffer_dirty(leaf);
2003 btrfs_free_path(path);
2004 btrfs_commit_transaction(trans, root);
2006 backref->found_dir_index = 1;
2007 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
2010 dir_rec->found_size += backref->namelen;
2011 if (dir_rec->found_size == dir_rec->isize &&
2012 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
2013 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
2014 if (dir_rec->found_size != dir_rec->isize)
2015 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
2020 static int delete_dir_index(struct btrfs_root *root,
2021 struct cache_tree *inode_cache,
2022 struct inode_record *rec,
2023 struct inode_backref *backref)
2025 struct btrfs_trans_handle *trans;
2026 struct btrfs_dir_item *di;
2027 struct btrfs_path *path;
2030 path = btrfs_alloc_path();
2034 trans = btrfs_start_transaction(root, 1);
2035 if (IS_ERR(trans)) {
2036 btrfs_free_path(path);
2037 return PTR_ERR(trans);
2041 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2042 (unsigned long long)backref->dir,
2043 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2044 (unsigned long long)root->objectid);
2046 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2047 backref->name, backref->namelen,
2048 backref->index, -1);
2051 btrfs_free_path(path);
2052 btrfs_commit_transaction(trans, root);
2059 ret = btrfs_del_item(trans, root, path);
2061 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2063 btrfs_free_path(path);
2064 btrfs_commit_transaction(trans, root);
2068 static int create_inode_item(struct btrfs_root *root,
2069 struct inode_record *rec,
2070 struct inode_backref *backref, int root_dir)
2072 struct btrfs_trans_handle *trans;
2073 struct btrfs_inode_item inode_item;
2074 time_t now = time(NULL);
2077 trans = btrfs_start_transaction(root, 1);
2078 if (IS_ERR(trans)) {
2079 ret = PTR_ERR(trans);
2083 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2084 "be incomplete, please check permissions and content after "
2085 "the fsck completes.\n", (unsigned long long)root->objectid,
2086 (unsigned long long)rec->ino);
2088 memset(&inode_item, 0, sizeof(inode_item));
2089 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2091 btrfs_set_stack_inode_nlink(&inode_item, 1);
2093 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2094 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2095 if (rec->found_dir_item) {
2096 if (rec->found_file_extent)
2097 fprintf(stderr, "root %llu inode %llu has both a dir "
2098 "item and extents, unsure if it is a dir or a "
2099 "regular file so setting it as a directory\n",
2100 (unsigned long long)root->objectid,
2101 (unsigned long long)rec->ino);
2102 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2103 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2104 } else if (!rec->found_dir_item) {
2105 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2106 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2108 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2109 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2110 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2111 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2112 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2113 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2114 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2115 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2117 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2119 btrfs_commit_transaction(trans, root);
2123 static int repair_inode_backrefs(struct btrfs_root *root,
2124 struct inode_record *rec,
2125 struct cache_tree *inode_cache,
2128 struct inode_backref *tmp, *backref;
2129 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2133 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2134 if (!delete && rec->ino == root_dirid) {
2135 if (!rec->found_inode_item) {
2136 ret = create_inode_item(root, rec, backref, 1);
2143 /* Index 0 for root dir's are special, don't mess with it */
2144 if (rec->ino == root_dirid && backref->index == 0)
2148 ((backref->found_dir_index && !backref->found_inode_ref) ||
2149 (backref->found_dir_index && backref->found_inode_ref &&
2150 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2151 ret = delete_dir_index(root, inode_cache, rec, backref);
2155 list_del(&backref->list);
2159 if (!delete && !backref->found_dir_index &&
2160 backref->found_dir_item && backref->found_inode_ref) {
2161 ret = add_missing_dir_index(root, inode_cache, rec,
2166 if (backref->found_dir_item &&
2167 backref->found_dir_index &&
2168 backref->found_dir_index) {
2169 if (!backref->errors &&
2170 backref->found_inode_ref) {
2171 list_del(&backref->list);
2177 if (!delete && (!backref->found_dir_index &&
2178 !backref->found_dir_item &&
2179 backref->found_inode_ref)) {
2180 struct btrfs_trans_handle *trans;
2181 struct btrfs_key location;
2183 ret = check_dir_conflict(root, backref->name,
2189 * let nlink fixing routine to handle it,
2190 * which can do it better.
2195 location.objectid = rec->ino;
2196 location.type = BTRFS_INODE_ITEM_KEY;
2197 location.offset = 0;
2199 trans = btrfs_start_transaction(root, 1);
2200 if (IS_ERR(trans)) {
2201 ret = PTR_ERR(trans);
2204 fprintf(stderr, "adding missing dir index/item pair "
2206 (unsigned long long)rec->ino);
2207 ret = btrfs_insert_dir_item(trans, root, backref->name,
2209 backref->dir, &location,
2210 imode_to_type(rec->imode),
2213 btrfs_commit_transaction(trans, root);
2217 if (!delete && (backref->found_inode_ref &&
2218 backref->found_dir_index &&
2219 backref->found_dir_item &&
2220 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2221 !rec->found_inode_item)) {
2222 ret = create_inode_item(root, rec, backref, 0);
2229 return ret ? ret : repaired;
2233 * To determine the file type for nlink/inode_item repair
2235 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2236 * Return -ENOENT if file type is not found.
2238 static int find_file_type(struct inode_record *rec, u8 *type)
2240 struct inode_backref *backref;
2242 /* For inode item recovered case */
2243 if (rec->found_inode_item) {
2244 *type = imode_to_type(rec->imode);
2248 list_for_each_entry(backref, &rec->backrefs, list) {
2249 if (backref->found_dir_index || backref->found_dir_item) {
2250 *type = backref->filetype;
2258 * To determine the file name for nlink repair
2260 * Return 0 if file name is found, set name and namelen.
2261 * Return -ENOENT if file name is not found.
2263 static int find_file_name(struct inode_record *rec,
2264 char *name, int *namelen)
2266 struct inode_backref *backref;
2268 list_for_each_entry(backref, &rec->backrefs, list) {
2269 if (backref->found_dir_index || backref->found_dir_item ||
2270 backref->found_inode_ref) {
2271 memcpy(name, backref->name, backref->namelen);
2272 *namelen = backref->namelen;
2279 /* Reset the nlink of the inode to the correct one */
2280 static int reset_nlink(struct btrfs_trans_handle *trans,
2281 struct btrfs_root *root,
2282 struct btrfs_path *path,
2283 struct inode_record *rec)
2285 struct inode_backref *backref;
2286 struct inode_backref *tmp;
2287 struct btrfs_key key;
2288 struct btrfs_inode_item *inode_item;
2291 /* We don't believe this either, reset it and iterate backref */
2292 rec->found_link = 0;
2294 /* Remove all backref including the valid ones */
2295 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2296 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2297 backref->index, backref->name,
2298 backref->namelen, 0);
2302 /* remove invalid backref, so it won't be added back */
2303 if (!(backref->found_dir_index &&
2304 backref->found_dir_item &&
2305 backref->found_inode_ref)) {
2306 list_del(&backref->list);
2313 /* Set nlink to 0 */
2314 key.objectid = rec->ino;
2315 key.type = BTRFS_INODE_ITEM_KEY;
2317 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2324 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2325 struct btrfs_inode_item);
2326 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2327 btrfs_mark_buffer_dirty(path->nodes[0]);
2328 btrfs_release_path(path);
2331 * Add back valid inode_ref/dir_item/dir_index,
2332 * add_link() will handle the nlink inc, so new nlink must be correct
2334 list_for_each_entry(backref, &rec->backrefs, list) {
2335 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2336 backref->name, backref->namelen,
2337 backref->ref_type, &backref->index, 1);
2342 btrfs_release_path(path);
2346 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2347 struct btrfs_root *root,
2348 struct btrfs_path *path,
2349 struct inode_record *rec)
2351 char *dir_name = "lost+found";
2352 char namebuf[BTRFS_NAME_LEN] = {0};
2357 int name_recovered = 0;
2358 int type_recovered = 0;
2362 * Get file name and type first before these invalid inode ref
2363 * are deleted by remove_all_invalid_backref()
2365 name_recovered = !find_file_name(rec, namebuf, &namelen);
2366 type_recovered = !find_file_type(rec, &type);
2368 if (!name_recovered) {
2369 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2370 rec->ino, rec->ino);
2371 namelen = count_digits(rec->ino);
2372 sprintf(namebuf, "%llu", rec->ino);
2375 if (!type_recovered) {
2376 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2378 type = BTRFS_FT_REG_FILE;
2382 ret = reset_nlink(trans, root, path, rec);
2385 "Failed to reset nlink for inode %llu: %s\n",
2386 rec->ino, strerror(-ret));
2390 if (rec->found_link == 0) {
2391 lost_found_ino = root->highest_inode;
2392 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2397 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2398 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2401 fprintf(stderr, "Failed to create '%s' dir: %s",
2402 dir_name, strerror(-ret));
2405 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2406 namebuf, namelen, type, NULL, 1);
2408 * Add ".INO" suffix several times to handle case where
2409 * "FILENAME.INO" is already taken by another file.
2411 while (ret == -EEXIST) {
2413 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2415 if (namelen + count_digits(rec->ino) + 1 >
2420 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2422 namelen += count_digits(rec->ino) + 1;
2423 ret = btrfs_add_link(trans, root, rec->ino,
2424 lost_found_ino, namebuf,
2425 namelen, type, NULL, 1);
2429 "Failed to link the inode %llu to %s dir: %s",
2430 rec->ino, dir_name, strerror(-ret));
2434 * Just increase the found_link, don't actually add the
2435 * backref. This will make things easier and this inode
2436 * record will be freed after the repair is done.
2437 * So fsck will not report problem about this inode.
2440 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2441 namelen, namebuf, dir_name);
2443 printf("Fixed the nlink of inode %llu\n", rec->ino);
2446 * Clear the flag anyway, or we will loop forever for the same inode
2447 * as it will not be removed from the bad inode list and the dead loop
2450 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2451 btrfs_release_path(path);
2456 * Check if there is any normal(reg or prealloc) file extent for given
2458 * This is used to determine the file type when neither its dir_index/item or
2459 * inode_item exists.
2461 * This will *NOT* report error, if any error happens, just consider it does
2462 * not have any normal file extent.
2464 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2466 struct btrfs_path *path;
2467 struct btrfs_key key;
2468 struct btrfs_key found_key;
2469 struct btrfs_file_extent_item *fi;
2473 path = btrfs_alloc_path();
2477 key.type = BTRFS_EXTENT_DATA_KEY;
2480 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2485 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2486 ret = btrfs_next_leaf(root, path);
2493 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2495 if (found_key.objectid != ino ||
2496 found_key.type != BTRFS_EXTENT_DATA_KEY)
2498 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2499 struct btrfs_file_extent_item);
2500 type = btrfs_file_extent_type(path->nodes[0], fi);
2501 if (type != BTRFS_FILE_EXTENT_INLINE) {
2507 btrfs_free_path(path);
2511 static u32 btrfs_type_to_imode(u8 type)
2513 static u32 imode_by_btrfs_type[] = {
2514 [BTRFS_FT_REG_FILE] = S_IFREG,
2515 [BTRFS_FT_DIR] = S_IFDIR,
2516 [BTRFS_FT_CHRDEV] = S_IFCHR,
2517 [BTRFS_FT_BLKDEV] = S_IFBLK,
2518 [BTRFS_FT_FIFO] = S_IFIFO,
2519 [BTRFS_FT_SOCK] = S_IFSOCK,
2520 [BTRFS_FT_SYMLINK] = S_IFLNK,
2523 return imode_by_btrfs_type[(type)];
2526 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2527 struct btrfs_root *root,
2528 struct btrfs_path *path,
2529 struct inode_record *rec)
2533 int type_recovered = 0;
2536 printf("Trying to rebuild inode:%llu\n", rec->ino);
2538 type_recovered = !find_file_type(rec, &filetype);
2541 * Try to determine inode type if type not found.
2543 * For found regular file extent, it must be FILE.
2544 * For found dir_item/index, it must be DIR.
2546 * For undetermined one, use FILE as fallback.
2549 * 1. If found backref(inode_index/item is already handled) to it,
2551 * Need new inode-inode ref structure to allow search for that.
2553 if (!type_recovered) {
2554 if (rec->found_file_extent &&
2555 find_normal_file_extent(root, rec->ino)) {
2557 filetype = BTRFS_FT_REG_FILE;
2558 } else if (rec->found_dir_item) {
2560 filetype = BTRFS_FT_DIR;
2561 } else if (!list_empty(&rec->orphan_extents)) {
2563 filetype = BTRFS_FT_REG_FILE;
2565 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2568 filetype = BTRFS_FT_REG_FILE;
2572 ret = btrfs_new_inode(trans, root, rec->ino,
2573 mode | btrfs_type_to_imode(filetype));
2578 * Here inode rebuild is done, we only rebuild the inode item,
2579 * don't repair the nlink(like move to lost+found).
2580 * That is the job of nlink repair.
2582 * We just fill the record and return
2584 rec->found_dir_item = 1;
2585 rec->imode = mode | btrfs_type_to_imode(filetype);
2587 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2588 /* Ensure the inode_nlinks repair function will be called */
2589 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2594 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2595 struct btrfs_root *root,
2596 struct btrfs_path *path,
2597 struct inode_record *rec)
2599 struct orphan_data_extent *orphan;
2600 struct orphan_data_extent *tmp;
2603 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2605 * Check for conflicting file extents
2607 * Here we don't know whether the extents is compressed or not,
2608 * so we can only assume it not compressed nor data offset,
2609 * and use its disk_len as extent length.
2611 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2612 orphan->offset, orphan->disk_len, 0);
2613 btrfs_release_path(path);
2618 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2619 orphan->disk_bytenr, orphan->disk_len);
2620 ret = btrfs_free_extent(trans,
2621 root->fs_info->extent_root,
2622 orphan->disk_bytenr, orphan->disk_len,
2623 0, root->objectid, orphan->objectid,
2628 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2629 orphan->offset, orphan->disk_bytenr,
2630 orphan->disk_len, orphan->disk_len);
2634 /* Update file size info */
2635 rec->found_size += orphan->disk_len;
2636 if (rec->found_size == rec->nbytes)
2637 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2639 /* Update the file extent hole info too */
2640 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2644 if (RB_EMPTY_ROOT(&rec->holes))
2645 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2647 list_del(&orphan->list);
2650 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2655 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2656 struct btrfs_root *root,
2657 struct btrfs_path *path,
2658 struct inode_record *rec)
2660 struct rb_node *node;
2661 struct file_extent_hole *hole;
2664 node = rb_first(&rec->holes);
2667 hole = rb_entry(node, struct file_extent_hole, node);
2668 ret = btrfs_punch_hole(trans, root, rec->ino,
2669 hole->start, hole->len);
2672 ret = del_file_extent_hole(&rec->holes, hole->start,
2676 if (RB_EMPTY_ROOT(&rec->holes))
2677 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2678 node = rb_first(&rec->holes);
2680 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2681 rec->ino, root->objectid);
2686 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2688 struct btrfs_trans_handle *trans;
2689 struct btrfs_path *path;
2692 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2693 I_ERR_NO_ORPHAN_ITEM |
2694 I_ERR_LINK_COUNT_WRONG |
2695 I_ERR_NO_INODE_ITEM |
2696 I_ERR_FILE_EXTENT_ORPHAN |
2697 I_ERR_FILE_EXTENT_DISCOUNT|
2698 I_ERR_FILE_NBYTES_WRONG)))
2701 path = btrfs_alloc_path();
2706 * For nlink repair, it may create a dir and add link, so
2707 * 2 for parent(256)'s dir_index and dir_item
2708 * 2 for lost+found dir's inode_item and inode_ref
2709 * 1 for the new inode_ref of the file
2710 * 2 for lost+found dir's dir_index and dir_item for the file
2712 trans = btrfs_start_transaction(root, 7);
2713 if (IS_ERR(trans)) {
2714 btrfs_free_path(path);
2715 return PTR_ERR(trans);
2718 if (rec->errors & I_ERR_NO_INODE_ITEM)
2719 ret = repair_inode_no_item(trans, root, path, rec);
2720 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2721 ret = repair_inode_orphan_extent(trans, root, path, rec);
2722 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2723 ret = repair_inode_discount_extent(trans, root, path, rec);
2724 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2725 ret = repair_inode_isize(trans, root, path, rec);
2726 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2727 ret = repair_inode_orphan_item(trans, root, path, rec);
2728 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2729 ret = repair_inode_nlinks(trans, root, path, rec);
2730 if (!ret && rec->errors & I_ERR_FILE_NBYTES_WRONG)
2731 ret = repair_inode_nbytes(trans, root, path, rec);
2732 btrfs_commit_transaction(trans, root);
2733 btrfs_free_path(path);
2737 static int check_inode_recs(struct btrfs_root *root,
2738 struct cache_tree *inode_cache)
2740 struct cache_extent *cache;
2741 struct ptr_node *node;
2742 struct inode_record *rec;
2743 struct inode_backref *backref;
2748 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2750 if (btrfs_root_refs(&root->root_item) == 0) {
2751 if (!cache_tree_empty(inode_cache))
2752 fprintf(stderr, "warning line %d\n", __LINE__);
2757 * We need to record the highest inode number for later 'lost+found'
2759 * We must select a ino not used/refered by any existing inode, or
2760 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2761 * this may cause 'lost+found' dir has wrong nlinks.
2763 cache = last_cache_extent(inode_cache);
2765 node = container_of(cache, struct ptr_node, cache);
2767 if (rec->ino > root->highest_inode)
2768 root->highest_inode = rec->ino;
2772 * We need to repair backrefs first because we could change some of the
2773 * errors in the inode recs.
2775 * We also need to go through and delete invalid backrefs first and then
2776 * add the correct ones second. We do this because we may get EEXIST
2777 * when adding back the correct index because we hadn't yet deleted the
2780 * For example, if we were missing a dir index then the directories
2781 * isize would be wrong, so if we fixed the isize to what we thought it
2782 * would be and then fixed the backref we'd still have a invalid fs, so
2783 * we need to add back the dir index and then check to see if the isize
2788 if (stage == 3 && !err)
2791 cache = search_cache_extent(inode_cache, 0);
2792 while (repair && cache) {
2793 node = container_of(cache, struct ptr_node, cache);
2795 cache = next_cache_extent(cache);
2797 /* Need to free everything up and rescan */
2799 remove_cache_extent(inode_cache, &node->cache);
2801 free_inode_rec(rec);
2805 if (list_empty(&rec->backrefs))
2808 ret = repair_inode_backrefs(root, rec, inode_cache,
2822 rec = get_inode_rec(inode_cache, root_dirid, 0);
2824 ret = check_root_dir(rec);
2826 fprintf(stderr, "root %llu root dir %llu error\n",
2827 (unsigned long long)root->root_key.objectid,
2828 (unsigned long long)root_dirid);
2829 print_inode_error(root, rec);
2834 struct btrfs_trans_handle *trans;
2836 trans = btrfs_start_transaction(root, 1);
2837 if (IS_ERR(trans)) {
2838 err = PTR_ERR(trans);
2843 "root %llu missing its root dir, recreating\n",
2844 (unsigned long long)root->objectid);
2846 ret = btrfs_make_root_dir(trans, root, root_dirid);
2849 btrfs_commit_transaction(trans, root);
2853 fprintf(stderr, "root %llu root dir %llu not found\n",
2854 (unsigned long long)root->root_key.objectid,
2855 (unsigned long long)root_dirid);
2859 cache = search_cache_extent(inode_cache, 0);
2862 node = container_of(cache, struct ptr_node, cache);
2864 remove_cache_extent(inode_cache, &node->cache);
2866 if (rec->ino == root_dirid ||
2867 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2868 free_inode_rec(rec);
2872 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2873 ret = check_orphan_item(root, rec->ino);
2875 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2876 if (can_free_inode_rec(rec)) {
2877 free_inode_rec(rec);
2882 if (!rec->found_inode_item)
2883 rec->errors |= I_ERR_NO_INODE_ITEM;
2884 if (rec->found_link != rec->nlink)
2885 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2887 ret = try_repair_inode(root, rec);
2888 if (ret == 0 && can_free_inode_rec(rec)) {
2889 free_inode_rec(rec);
2895 if (!(repair && ret == 0))
2897 print_inode_error(root, rec);
2898 list_for_each_entry(backref, &rec->backrefs, list) {
2899 if (!backref->found_dir_item)
2900 backref->errors |= REF_ERR_NO_DIR_ITEM;
2901 if (!backref->found_dir_index)
2902 backref->errors |= REF_ERR_NO_DIR_INDEX;
2903 if (!backref->found_inode_ref)
2904 backref->errors |= REF_ERR_NO_INODE_REF;
2905 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2906 " namelen %u name %s filetype %d errors %x",
2907 (unsigned long long)backref->dir,
2908 (unsigned long long)backref->index,
2909 backref->namelen, backref->name,
2910 backref->filetype, backref->errors);
2911 print_ref_error(backref->errors);
2913 free_inode_rec(rec);
2915 return (error > 0) ? -1 : 0;
2918 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2921 struct cache_extent *cache;
2922 struct root_record *rec = NULL;
2925 cache = lookup_cache_extent(root_cache, objectid, 1);
2927 rec = container_of(cache, struct root_record, cache);
2929 rec = calloc(1, sizeof(*rec));
2930 rec->objectid = objectid;
2931 INIT_LIST_HEAD(&rec->backrefs);
2932 rec->cache.start = objectid;
2933 rec->cache.size = 1;
2935 ret = insert_cache_extent(root_cache, &rec->cache);
2941 static struct root_backref *get_root_backref(struct root_record *rec,
2942 u64 ref_root, u64 dir, u64 index,
2943 const char *name, int namelen)
2945 struct root_backref *backref;
2947 list_for_each_entry(backref, &rec->backrefs, list) {
2948 if (backref->ref_root != ref_root || backref->dir != dir ||
2949 backref->namelen != namelen)
2951 if (memcmp(name, backref->name, namelen))
2956 backref = malloc(sizeof(*backref) + namelen + 1);
2957 memset(backref, 0, sizeof(*backref));
2958 backref->ref_root = ref_root;
2960 backref->index = index;
2961 backref->namelen = namelen;
2962 memcpy(backref->name, name, namelen);
2963 backref->name[namelen] = '\0';
2964 list_add_tail(&backref->list, &rec->backrefs);
2968 static void free_root_record(struct cache_extent *cache)
2970 struct root_record *rec;
2971 struct root_backref *backref;
2973 rec = container_of(cache, struct root_record, cache);
2974 while (!list_empty(&rec->backrefs)) {
2975 backref = list_entry(rec->backrefs.next,
2976 struct root_backref, list);
2977 list_del(&backref->list);
2984 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2986 static int add_root_backref(struct cache_tree *root_cache,
2987 u64 root_id, u64 ref_root, u64 dir, u64 index,
2988 const char *name, int namelen,
2989 int item_type, int errors)
2991 struct root_record *rec;
2992 struct root_backref *backref;
2994 rec = get_root_rec(root_cache, root_id);
2995 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2997 backref->errors |= errors;
2999 if (item_type != BTRFS_DIR_ITEM_KEY) {
3000 if (backref->found_dir_index || backref->found_back_ref ||
3001 backref->found_forward_ref) {
3002 if (backref->index != index)
3003 backref->errors |= REF_ERR_INDEX_UNMATCH;
3005 backref->index = index;
3009 if (item_type == BTRFS_DIR_ITEM_KEY) {
3010 if (backref->found_forward_ref)
3012 backref->found_dir_item = 1;
3013 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
3014 backref->found_dir_index = 1;
3015 } else if (item_type == BTRFS_ROOT_REF_KEY) {
3016 if (backref->found_forward_ref)
3017 backref->errors |= REF_ERR_DUP_ROOT_REF;
3018 else if (backref->found_dir_item)
3020 backref->found_forward_ref = 1;
3021 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
3022 if (backref->found_back_ref)
3023 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
3024 backref->found_back_ref = 1;
3029 if (backref->found_forward_ref && backref->found_dir_item)
3030 backref->reachable = 1;
3034 static int merge_root_recs(struct btrfs_root *root,
3035 struct cache_tree *src_cache,
3036 struct cache_tree *dst_cache)
3038 struct cache_extent *cache;
3039 struct ptr_node *node;
3040 struct inode_record *rec;
3041 struct inode_backref *backref;
3044 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3045 free_inode_recs_tree(src_cache);
3050 cache = search_cache_extent(src_cache, 0);
3053 node = container_of(cache, struct ptr_node, cache);
3055 remove_cache_extent(src_cache, &node->cache);
3058 ret = is_child_root(root, root->objectid, rec->ino);
3064 list_for_each_entry(backref, &rec->backrefs, list) {
3065 BUG_ON(backref->found_inode_ref);
3066 if (backref->found_dir_item)
3067 add_root_backref(dst_cache, rec->ino,
3068 root->root_key.objectid, backref->dir,
3069 backref->index, backref->name,
3070 backref->namelen, BTRFS_DIR_ITEM_KEY,
3072 if (backref->found_dir_index)
3073 add_root_backref(dst_cache, rec->ino,
3074 root->root_key.objectid, backref->dir,
3075 backref->index, backref->name,
3076 backref->namelen, BTRFS_DIR_INDEX_KEY,
3080 free_inode_rec(rec);
3087 static int check_root_refs(struct btrfs_root *root,
3088 struct cache_tree *root_cache)
3090 struct root_record *rec;
3091 struct root_record *ref_root;
3092 struct root_backref *backref;
3093 struct cache_extent *cache;
3099 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3102 /* fixme: this can not detect circular references */
3105 cache = search_cache_extent(root_cache, 0);
3109 rec = container_of(cache, struct root_record, cache);
3110 cache = next_cache_extent(cache);
3112 if (rec->found_ref == 0)
3115 list_for_each_entry(backref, &rec->backrefs, list) {
3116 if (!backref->reachable)
3119 ref_root = get_root_rec(root_cache,
3121 if (ref_root->found_ref > 0)
3124 backref->reachable = 0;
3126 if (rec->found_ref == 0)
3132 cache = search_cache_extent(root_cache, 0);
3136 rec = container_of(cache, struct root_record, cache);
3137 cache = next_cache_extent(cache);
3139 if (rec->found_ref == 0 &&
3140 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3141 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3142 ret = check_orphan_item(root->fs_info->tree_root,
3148 * If we don't have a root item then we likely just have
3149 * a dir item in a snapshot for this root but no actual
3150 * ref key or anything so it's meaningless.
3152 if (!rec->found_root_item)
3155 fprintf(stderr, "fs tree %llu not referenced\n",
3156 (unsigned long long)rec->objectid);
3160 if (rec->found_ref > 0 && !rec->found_root_item)
3162 list_for_each_entry(backref, &rec->backrefs, list) {
3163 if (!backref->found_dir_item)
3164 backref->errors |= REF_ERR_NO_DIR_ITEM;
3165 if (!backref->found_dir_index)
3166 backref->errors |= REF_ERR_NO_DIR_INDEX;
3167 if (!backref->found_back_ref)
3168 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3169 if (!backref->found_forward_ref)
3170 backref->errors |= REF_ERR_NO_ROOT_REF;
3171 if (backref->reachable && backref->errors)
3178 fprintf(stderr, "fs tree %llu refs %u %s\n",
3179 (unsigned long long)rec->objectid, rec->found_ref,
3180 rec->found_root_item ? "" : "not found");
3182 list_for_each_entry(backref, &rec->backrefs, list) {
3183 if (!backref->reachable)
3185 if (!backref->errors && rec->found_root_item)
3187 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3188 " index %llu namelen %u name %s errors %x\n",
3189 (unsigned long long)backref->ref_root,
3190 (unsigned long long)backref->dir,
3191 (unsigned long long)backref->index,
3192 backref->namelen, backref->name,
3194 print_ref_error(backref->errors);
3197 return errors > 0 ? 1 : 0;
3200 static int process_root_ref(struct extent_buffer *eb, int slot,
3201 struct btrfs_key *key,
3202 struct cache_tree *root_cache)
3208 struct btrfs_root_ref *ref;
3209 char namebuf[BTRFS_NAME_LEN];
3212 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3214 dirid = btrfs_root_ref_dirid(eb, ref);
3215 index = btrfs_root_ref_sequence(eb, ref);
3216 name_len = btrfs_root_ref_name_len(eb, ref);
3218 if (name_len <= BTRFS_NAME_LEN) {
3222 len = BTRFS_NAME_LEN;
3223 error = REF_ERR_NAME_TOO_LONG;
3225 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3227 if (key->type == BTRFS_ROOT_REF_KEY) {
3228 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3229 index, namebuf, len, key->type, error);
3231 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3232 index, namebuf, len, key->type, error);
3237 static void free_corrupt_block(struct cache_extent *cache)
3239 struct btrfs_corrupt_block *corrupt;
3241 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3245 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3248 * Repair the btree of the given root.
3250 * The fix is to remove the node key in corrupt_blocks cache_tree.
3251 * and rebalance the tree.
3252 * After the fix, the btree should be writeable.
3254 static int repair_btree(struct btrfs_root *root,
3255 struct cache_tree *corrupt_blocks)
3257 struct btrfs_trans_handle *trans;
3258 struct btrfs_path *path;
3259 struct btrfs_corrupt_block *corrupt;
3260 struct cache_extent *cache;
3261 struct btrfs_key key;
3266 if (cache_tree_empty(corrupt_blocks))
3269 path = btrfs_alloc_path();
3273 trans = btrfs_start_transaction(root, 1);
3274 if (IS_ERR(trans)) {
3275 ret = PTR_ERR(trans);
3276 fprintf(stderr, "Error starting transaction: %s\n",
3280 cache = first_cache_extent(corrupt_blocks);
3282 corrupt = container_of(cache, struct btrfs_corrupt_block,
3284 level = corrupt->level;
3285 path->lowest_level = level;
3286 key.objectid = corrupt->key.objectid;
3287 key.type = corrupt->key.type;
3288 key.offset = corrupt->key.offset;
3291 * Here we don't want to do any tree balance, since it may
3292 * cause a balance with corrupted brother leaf/node,
3293 * so ins_len set to 0 here.
3294 * Balance will be done after all corrupt node/leaf is deleted.
3296 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3299 offset = btrfs_node_blockptr(path->nodes[level],
3300 path->slots[level]);
3302 /* Remove the ptr */
3303 ret = btrfs_del_ptr(trans, root, path, level,
3304 path->slots[level]);
3308 * Remove the corresponding extent
3309 * return value is not concerned.
3311 btrfs_release_path(path);
3312 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3313 0, root->root_key.objectid,
3315 cache = next_cache_extent(cache);
3318 /* Balance the btree using btrfs_search_slot() */
3319 cache = first_cache_extent(corrupt_blocks);
3321 corrupt = container_of(cache, struct btrfs_corrupt_block,
3323 memcpy(&key, &corrupt->key, sizeof(key));
3324 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3327 /* return will always >0 since it won't find the item */
3329 btrfs_release_path(path);
3330 cache = next_cache_extent(cache);
3333 btrfs_commit_transaction(trans, root);
3335 btrfs_free_path(path);
3339 static int check_fs_root(struct btrfs_root *root,
3340 struct cache_tree *root_cache,
3341 struct walk_control *wc)
3347 struct btrfs_path path;
3348 struct shared_node root_node;
3349 struct root_record *rec;
3350 struct btrfs_root_item *root_item = &root->root_item;
3351 struct cache_tree corrupt_blocks;
3352 struct orphan_data_extent *orphan;
3353 struct orphan_data_extent *tmp;
3354 enum btrfs_tree_block_status status;
3357 * Reuse the corrupt_block cache tree to record corrupted tree block
3359 * Unlike the usage in extent tree check, here we do it in a per
3360 * fs/subvol tree base.
3362 cache_tree_init(&corrupt_blocks);
3363 root->fs_info->corrupt_blocks = &corrupt_blocks;
3365 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3366 rec = get_root_rec(root_cache, root->root_key.objectid);
3367 if (btrfs_root_refs(root_item) > 0)
3368 rec->found_root_item = 1;
3371 btrfs_init_path(&path);
3372 memset(&root_node, 0, sizeof(root_node));
3373 cache_tree_init(&root_node.root_cache);
3374 cache_tree_init(&root_node.inode_cache);
3376 /* Move the orphan extent record to corresponding inode_record */
3377 list_for_each_entry_safe(orphan, tmp,
3378 &root->orphan_data_extents, list) {
3379 struct inode_record *inode;
3381 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3383 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3384 list_move(&orphan->list, &inode->orphan_extents);
3387 level = btrfs_header_level(root->node);
3388 memset(wc->nodes, 0, sizeof(wc->nodes));
3389 wc->nodes[level] = &root_node;
3390 wc->active_node = level;
3391 wc->root_level = level;
3393 /* We may not have checked the root block, lets do that now */
3394 if (btrfs_is_leaf(root->node))
3395 status = btrfs_check_leaf(root, NULL, root->node);
3397 status = btrfs_check_node(root, NULL, root->node);
3398 if (status != BTRFS_TREE_BLOCK_CLEAN)
3401 if (btrfs_root_refs(root_item) > 0 ||
3402 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3403 path.nodes[level] = root->node;
3404 extent_buffer_get(root->node);
3405 path.slots[level] = 0;
3407 struct btrfs_key key;
3408 struct btrfs_disk_key found_key;
3410 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3411 level = root_item->drop_level;
3412 path.lowest_level = level;
3413 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3416 btrfs_node_key(path.nodes[level], &found_key,
3418 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3419 sizeof(found_key)));
3423 wret = walk_down_tree(root, &path, wc, &level);
3429 wret = walk_up_tree(root, &path, wc, &level);
3436 btrfs_release_path(&path);
3438 if (!cache_tree_empty(&corrupt_blocks)) {
3439 struct cache_extent *cache;
3440 struct btrfs_corrupt_block *corrupt;
3442 printf("The following tree block(s) is corrupted in tree %llu:\n",
3443 root->root_key.objectid);
3444 cache = first_cache_extent(&corrupt_blocks);
3446 corrupt = container_of(cache,
3447 struct btrfs_corrupt_block,
3449 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3450 cache->start, corrupt->level,
3451 corrupt->key.objectid, corrupt->key.type,
3452 corrupt->key.offset);
3453 cache = next_cache_extent(cache);
3456 printf("Try to repair the btree for root %llu\n",
3457 root->root_key.objectid);
3458 ret = repair_btree(root, &corrupt_blocks);
3460 fprintf(stderr, "Failed to repair btree: %s\n",
3463 printf("Btree for root %llu is fixed\n",
3464 root->root_key.objectid);
3468 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3472 if (root_node.current) {
3473 root_node.current->checked = 1;
3474 maybe_free_inode_rec(&root_node.inode_cache,
3478 err = check_inode_recs(root, &root_node.inode_cache);
3482 free_corrupt_blocks_tree(&corrupt_blocks);
3483 root->fs_info->corrupt_blocks = NULL;
3484 free_orphan_data_extents(&root->orphan_data_extents);
3488 static int fs_root_objectid(u64 objectid)
3490 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3491 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3493 return is_fstree(objectid);
3496 static int check_fs_roots(struct btrfs_root *root,
3497 struct cache_tree *root_cache)
3499 struct btrfs_path path;
3500 struct btrfs_key key;
3501 struct walk_control wc;
3502 struct extent_buffer *leaf, *tree_node;
3503 struct btrfs_root *tmp_root;
3504 struct btrfs_root *tree_root = root->fs_info->tree_root;
3509 * Just in case we made any changes to the extent tree that weren't
3510 * reflected into the free space cache yet.
3513 reset_cached_block_groups(root->fs_info);
3514 memset(&wc, 0, sizeof(wc));
3515 cache_tree_init(&wc.shared);
3516 btrfs_init_path(&path);
3521 key.type = BTRFS_ROOT_ITEM_KEY;
3522 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3527 tree_node = tree_root->node;
3529 if (tree_node != tree_root->node) {
3530 free_root_recs_tree(root_cache);
3531 btrfs_release_path(&path);
3534 leaf = path.nodes[0];
3535 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3536 ret = btrfs_next_leaf(tree_root, &path);
3542 leaf = path.nodes[0];
3544 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3545 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3546 fs_root_objectid(key.objectid)) {
3547 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3548 tmp_root = btrfs_read_fs_root_no_cache(
3549 root->fs_info, &key);
3551 key.offset = (u64)-1;
3552 tmp_root = btrfs_read_fs_root(
3553 root->fs_info, &key);
3555 if (IS_ERR(tmp_root)) {
3559 ret = check_fs_root(tmp_root, root_cache, &wc);
3560 if (ret == -EAGAIN) {
3561 free_root_recs_tree(root_cache);
3562 btrfs_release_path(&path);
3567 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3568 btrfs_free_fs_root(tmp_root);
3569 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3570 key.type == BTRFS_ROOT_BACKREF_KEY) {
3571 process_root_ref(leaf, path.slots[0], &key,
3578 btrfs_release_path(&path);
3580 free_extent_cache_tree(&wc.shared);
3581 if (!cache_tree_empty(&wc.shared))
3582 fprintf(stderr, "warning line %d\n", __LINE__);
3587 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3589 struct list_head *cur = rec->backrefs.next;
3590 struct extent_backref *back;
3591 struct tree_backref *tback;
3592 struct data_backref *dback;
3596 while(cur != &rec->backrefs) {
3597 back = list_entry(cur, struct extent_backref, list);
3599 if (!back->found_extent_tree) {
3603 if (back->is_data) {
3604 dback = (struct data_backref *)back;
3605 fprintf(stderr, "Backref %llu %s %llu"
3606 " owner %llu offset %llu num_refs %lu"
3607 " not found in extent tree\n",
3608 (unsigned long long)rec->start,
3609 back->full_backref ?
3611 back->full_backref ?
3612 (unsigned long long)dback->parent:
3613 (unsigned long long)dback->root,
3614 (unsigned long long)dback->owner,
3615 (unsigned long long)dback->offset,
3616 (unsigned long)dback->num_refs);
3618 tback = (struct tree_backref *)back;
3619 fprintf(stderr, "Backref %llu parent %llu"
3620 " root %llu not found in extent tree\n",
3621 (unsigned long long)rec->start,
3622 (unsigned long long)tback->parent,
3623 (unsigned long long)tback->root);
3626 if (!back->is_data && !back->found_ref) {
3630 tback = (struct tree_backref *)back;
3631 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3632 (unsigned long long)rec->start,
3633 back->full_backref ? "parent" : "root",
3634 back->full_backref ?
3635 (unsigned long long)tback->parent :
3636 (unsigned long long)tback->root, back);
3638 if (back->is_data) {
3639 dback = (struct data_backref *)back;
3640 if (dback->found_ref != dback->num_refs) {
3644 fprintf(stderr, "Incorrect local backref count"
3645 " on %llu %s %llu owner %llu"
3646 " offset %llu found %u wanted %u back %p\n",
3647 (unsigned long long)rec->start,
3648 back->full_backref ?
3650 back->full_backref ?
3651 (unsigned long long)dback->parent:
3652 (unsigned long long)dback->root,
3653 (unsigned long long)dback->owner,
3654 (unsigned long long)dback->offset,
3655 dback->found_ref, dback->num_refs, back);
3657 if (dback->disk_bytenr != rec->start) {
3661 fprintf(stderr, "Backref disk bytenr does not"
3662 " match extent record, bytenr=%llu, "
3663 "ref bytenr=%llu\n",
3664 (unsigned long long)rec->start,
3665 (unsigned long long)dback->disk_bytenr);
3668 if (dback->bytes != rec->nr) {
3672 fprintf(stderr, "Backref bytes do not match "
3673 "extent backref, bytenr=%llu, ref "
3674 "bytes=%llu, backref bytes=%llu\n",
3675 (unsigned long long)rec->start,
3676 (unsigned long long)rec->nr,
3677 (unsigned long long)dback->bytes);
3680 if (!back->is_data) {
3683 dback = (struct data_backref *)back;
3684 found += dback->found_ref;
3687 if (found != rec->refs) {
3691 fprintf(stderr, "Incorrect global backref count "
3692 "on %llu found %llu wanted %llu\n",
3693 (unsigned long long)rec->start,
3694 (unsigned long long)found,
3695 (unsigned long long)rec->refs);
3701 static int free_all_extent_backrefs(struct extent_record *rec)
3703 struct extent_backref *back;
3704 struct list_head *cur;
3705 while (!list_empty(&rec->backrefs)) {
3706 cur = rec->backrefs.next;
3707 back = list_entry(cur, struct extent_backref, list);
3714 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3715 struct cache_tree *extent_cache)
3717 struct cache_extent *cache;
3718 struct extent_record *rec;
3721 cache = first_cache_extent(extent_cache);
3724 rec = container_of(cache, struct extent_record, cache);
3725 remove_cache_extent(extent_cache, cache);
3726 free_all_extent_backrefs(rec);
3731 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3732 struct extent_record *rec)
3734 if (rec->content_checked && rec->owner_ref_checked &&
3735 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3736 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3737 !rec->bad_full_backref) {
3738 remove_cache_extent(extent_cache, &rec->cache);
3739 free_all_extent_backrefs(rec);
3740 list_del_init(&rec->list);
3746 static int check_owner_ref(struct btrfs_root *root,
3747 struct extent_record *rec,
3748 struct extent_buffer *buf)
3750 struct extent_backref *node;
3751 struct tree_backref *back;
3752 struct btrfs_root *ref_root;
3753 struct btrfs_key key;
3754 struct btrfs_path path;
3755 struct extent_buffer *parent;
3760 list_for_each_entry(node, &rec->backrefs, list) {
3763 if (!node->found_ref)
3765 if (node->full_backref)
3767 back = (struct tree_backref *)node;
3768 if (btrfs_header_owner(buf) == back->root)
3771 BUG_ON(rec->is_root);
3773 /* try to find the block by search corresponding fs tree */
3774 key.objectid = btrfs_header_owner(buf);
3775 key.type = BTRFS_ROOT_ITEM_KEY;
3776 key.offset = (u64)-1;
3778 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3779 if (IS_ERR(ref_root))
3782 level = btrfs_header_level(buf);
3784 btrfs_item_key_to_cpu(buf, &key, 0);
3786 btrfs_node_key_to_cpu(buf, &key, 0);
3788 btrfs_init_path(&path);
3789 path.lowest_level = level + 1;
3790 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3794 parent = path.nodes[level + 1];
3795 if (parent && buf->start == btrfs_node_blockptr(parent,
3796 path.slots[level + 1]))
3799 btrfs_release_path(&path);
3800 return found ? 0 : 1;
3803 static int is_extent_tree_record(struct extent_record *rec)
3805 struct list_head *cur = rec->backrefs.next;
3806 struct extent_backref *node;
3807 struct tree_backref *back;
3810 while(cur != &rec->backrefs) {
3811 node = list_entry(cur, struct extent_backref, list);
3815 back = (struct tree_backref *)node;
3816 if (node->full_backref)
3818 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3825 static int record_bad_block_io(struct btrfs_fs_info *info,
3826 struct cache_tree *extent_cache,
3829 struct extent_record *rec;
3830 struct cache_extent *cache;
3831 struct btrfs_key key;
3833 cache = lookup_cache_extent(extent_cache, start, len);
3837 rec = container_of(cache, struct extent_record, cache);
3838 if (!is_extent_tree_record(rec))
3841 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3842 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3845 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3846 struct extent_buffer *buf, int slot)
3848 if (btrfs_header_level(buf)) {
3849 struct btrfs_key_ptr ptr1, ptr2;
3851 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3852 sizeof(struct btrfs_key_ptr));
3853 read_extent_buffer(buf, &ptr2,
3854 btrfs_node_key_ptr_offset(slot + 1),
3855 sizeof(struct btrfs_key_ptr));
3856 write_extent_buffer(buf, &ptr1,
3857 btrfs_node_key_ptr_offset(slot + 1),
3858 sizeof(struct btrfs_key_ptr));
3859 write_extent_buffer(buf, &ptr2,
3860 btrfs_node_key_ptr_offset(slot),
3861 sizeof(struct btrfs_key_ptr));
3863 struct btrfs_disk_key key;
3864 btrfs_node_key(buf, &key, 0);
3865 btrfs_fixup_low_keys(root, path, &key,
3866 btrfs_header_level(buf) + 1);
3869 struct btrfs_item *item1, *item2;
3870 struct btrfs_key k1, k2;
3871 char *item1_data, *item2_data;
3872 u32 item1_offset, item2_offset, item1_size, item2_size;
3874 item1 = btrfs_item_nr(slot);
3875 item2 = btrfs_item_nr(slot + 1);
3876 btrfs_item_key_to_cpu(buf, &k1, slot);
3877 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3878 item1_offset = btrfs_item_offset(buf, item1);
3879 item2_offset = btrfs_item_offset(buf, item2);
3880 item1_size = btrfs_item_size(buf, item1);
3881 item2_size = btrfs_item_size(buf, item2);
3883 item1_data = malloc(item1_size);
3886 item2_data = malloc(item2_size);
3892 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3893 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3895 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3896 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3900 btrfs_set_item_offset(buf, item1, item2_offset);
3901 btrfs_set_item_offset(buf, item2, item1_offset);
3902 btrfs_set_item_size(buf, item1, item2_size);
3903 btrfs_set_item_size(buf, item2, item1_size);
3905 path->slots[0] = slot;
3906 btrfs_set_item_key_unsafe(root, path, &k2);
3907 path->slots[0] = slot + 1;
3908 btrfs_set_item_key_unsafe(root, path, &k1);
3913 static int fix_key_order(struct btrfs_trans_handle *trans,
3914 struct btrfs_root *root,
3915 struct btrfs_path *path)
3917 struct extent_buffer *buf;
3918 struct btrfs_key k1, k2;
3920 int level = path->lowest_level;
3923 buf = path->nodes[level];
3924 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3926 btrfs_node_key_to_cpu(buf, &k1, i);
3927 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3929 btrfs_item_key_to_cpu(buf, &k1, i);
3930 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3932 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3934 ret = swap_values(root, path, buf, i);
3937 btrfs_mark_buffer_dirty(buf);
3943 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3944 struct btrfs_root *root,
3945 struct btrfs_path *path,
3946 struct extent_buffer *buf, int slot)
3948 struct btrfs_key key;
3949 int nritems = btrfs_header_nritems(buf);
3951 btrfs_item_key_to_cpu(buf, &key, slot);
3953 /* These are all the keys we can deal with missing. */
3954 if (key.type != BTRFS_DIR_INDEX_KEY &&
3955 key.type != BTRFS_EXTENT_ITEM_KEY &&
3956 key.type != BTRFS_METADATA_ITEM_KEY &&
3957 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3958 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3961 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3962 (unsigned long long)key.objectid, key.type,
3963 (unsigned long long)key.offset, slot, buf->start);
3964 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3965 btrfs_item_nr_offset(slot + 1),
3966 sizeof(struct btrfs_item) *
3967 (nritems - slot - 1));
3968 btrfs_set_header_nritems(buf, nritems - 1);
3970 struct btrfs_disk_key disk_key;
3972 btrfs_item_key(buf, &disk_key, 0);
3973 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3975 btrfs_mark_buffer_dirty(buf);
3979 static int fix_item_offset(struct btrfs_trans_handle *trans,
3980 struct btrfs_root *root,
3981 struct btrfs_path *path)
3983 struct extent_buffer *buf;
3987 /* We should only get this for leaves */
3988 BUG_ON(path->lowest_level);
3989 buf = path->nodes[0];
3991 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3992 unsigned int shift = 0, offset;
3994 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3995 BTRFS_LEAF_DATA_SIZE(root)) {
3996 if (btrfs_item_end_nr(buf, i) >
3997 BTRFS_LEAF_DATA_SIZE(root)) {
3998 ret = delete_bogus_item(trans, root, path,
4002 fprintf(stderr, "item is off the end of the "
4003 "leaf, can't fix\n");
4007 shift = BTRFS_LEAF_DATA_SIZE(root) -
4008 btrfs_item_end_nr(buf, i);
4009 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
4010 btrfs_item_offset_nr(buf, i - 1)) {
4011 if (btrfs_item_end_nr(buf, i) >
4012 btrfs_item_offset_nr(buf, i - 1)) {
4013 ret = delete_bogus_item(trans, root, path,
4017 fprintf(stderr, "items overlap, can't fix\n");
4021 shift = btrfs_item_offset_nr(buf, i - 1) -
4022 btrfs_item_end_nr(buf, i);
4027 printf("Shifting item nr %d by %u bytes in block %llu\n",
4028 i, shift, (unsigned long long)buf->start);
4029 offset = btrfs_item_offset_nr(buf, i);
4030 memmove_extent_buffer(buf,
4031 btrfs_leaf_data(buf) + offset + shift,
4032 btrfs_leaf_data(buf) + offset,
4033 btrfs_item_size_nr(buf, i));
4034 btrfs_set_item_offset(buf, btrfs_item_nr(i),
4036 btrfs_mark_buffer_dirty(buf);
4040 * We may have moved things, in which case we want to exit so we don't
4041 * write those changes out. Once we have proper abort functionality in
4042 * progs this can be changed to something nicer.
4049 * Attempt to fix basic block failures. If we can't fix it for whatever reason
4050 * then just return -EIO.
4052 static int try_to_fix_bad_block(struct btrfs_root *root,
4053 struct extent_buffer *buf,
4054 enum btrfs_tree_block_status status)
4056 struct btrfs_trans_handle *trans;
4057 struct ulist *roots;
4058 struct ulist_node *node;
4059 struct btrfs_root *search_root;
4060 struct btrfs_path *path;
4061 struct ulist_iterator iter;
4062 struct btrfs_key root_key, key;
4065 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4066 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4069 path = btrfs_alloc_path();
4073 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4076 btrfs_free_path(path);
4080 ULIST_ITER_INIT(&iter);
4081 while ((node = ulist_next(roots, &iter))) {
4082 root_key.objectid = node->val;
4083 root_key.type = BTRFS_ROOT_ITEM_KEY;
4084 root_key.offset = (u64)-1;
4086 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4093 trans = btrfs_start_transaction(search_root, 0);
4094 if (IS_ERR(trans)) {
4095 ret = PTR_ERR(trans);
4099 path->lowest_level = btrfs_header_level(buf);
4100 path->skip_check_block = 1;
4101 if (path->lowest_level)
4102 btrfs_node_key_to_cpu(buf, &key, 0);
4104 btrfs_item_key_to_cpu(buf, &key, 0);
4105 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4108 btrfs_commit_transaction(trans, search_root);
4111 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4112 ret = fix_key_order(trans, search_root, path);
4113 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4114 ret = fix_item_offset(trans, search_root, path);
4116 btrfs_commit_transaction(trans, search_root);
4119 btrfs_release_path(path);
4120 btrfs_commit_transaction(trans, search_root);
4123 btrfs_free_path(path);
4127 static int check_block(struct btrfs_root *root,
4128 struct cache_tree *extent_cache,
4129 struct extent_buffer *buf, u64 flags)
4131 struct extent_record *rec;
4132 struct cache_extent *cache;
4133 struct btrfs_key key;
4134 enum btrfs_tree_block_status status;
4138 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4141 rec = container_of(cache, struct extent_record, cache);
4142 rec->generation = btrfs_header_generation(buf);
4144 level = btrfs_header_level(buf);
4145 if (btrfs_header_nritems(buf) > 0) {
4148 btrfs_item_key_to_cpu(buf, &key, 0);
4150 btrfs_node_key_to_cpu(buf, &key, 0);
4152 rec->info_objectid = key.objectid;
4154 rec->info_level = level;
4156 if (btrfs_is_leaf(buf))
4157 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4159 status = btrfs_check_node(root, &rec->parent_key, buf);
4161 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4163 status = try_to_fix_bad_block(root, buf, status);
4164 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4166 fprintf(stderr, "bad block %llu\n",
4167 (unsigned long long)buf->start);
4170 * Signal to callers we need to start the scan over
4171 * again since we'll have cow'ed blocks.
4176 rec->content_checked = 1;
4177 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4178 rec->owner_ref_checked = 1;
4180 ret = check_owner_ref(root, rec, buf);
4182 rec->owner_ref_checked = 1;
4186 maybe_free_extent_rec(extent_cache, rec);
4190 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4191 u64 parent, u64 root)
4193 struct list_head *cur = rec->backrefs.next;
4194 struct extent_backref *node;
4195 struct tree_backref *back;
4197 while(cur != &rec->backrefs) {
4198 node = list_entry(cur, struct extent_backref, list);
4202 back = (struct tree_backref *)node;
4204 if (!node->full_backref)
4206 if (parent == back->parent)
4209 if (node->full_backref)
4211 if (back->root == root)
4218 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4219 u64 parent, u64 root)
4221 struct tree_backref *ref = malloc(sizeof(*ref));
4222 memset(&ref->node, 0, sizeof(ref->node));
4224 ref->parent = parent;
4225 ref->node.full_backref = 1;
4228 ref->node.full_backref = 0;
4230 list_add_tail(&ref->node.list, &rec->backrefs);
4235 static struct data_backref *find_data_backref(struct extent_record *rec,
4236 u64 parent, u64 root,
4237 u64 owner, u64 offset,
4239 u64 disk_bytenr, u64 bytes)
4241 struct list_head *cur = rec->backrefs.next;
4242 struct extent_backref *node;
4243 struct data_backref *back;
4245 while(cur != &rec->backrefs) {
4246 node = list_entry(cur, struct extent_backref, list);
4250 back = (struct data_backref *)node;
4252 if (!node->full_backref)
4254 if (parent == back->parent)
4257 if (node->full_backref)
4259 if (back->root == root && back->owner == owner &&
4260 back->offset == offset) {
4261 if (found_ref && node->found_ref &&
4262 (back->bytes != bytes ||
4263 back->disk_bytenr != disk_bytenr))
4272 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4273 u64 parent, u64 root,
4274 u64 owner, u64 offset,
4277 struct data_backref *ref = malloc(sizeof(*ref));
4278 memset(&ref->node, 0, sizeof(ref->node));
4279 ref->node.is_data = 1;
4282 ref->parent = parent;
4285 ref->node.full_backref = 1;
4289 ref->offset = offset;
4290 ref->node.full_backref = 0;
4292 ref->bytes = max_size;
4295 list_add_tail(&ref->node.list, &rec->backrefs);
4296 if (max_size > rec->max_size)
4297 rec->max_size = max_size;
4301 static int add_extent_rec(struct cache_tree *extent_cache,
4302 struct btrfs_key *parent_key, u64 parent_gen,
4303 u64 start, u64 nr, u64 extent_item_refs,
4304 int is_root, int inc_ref, int set_checked,
4305 int metadata, int extent_rec, u64 max_size)
4307 struct extent_record *rec;
4308 struct cache_extent *cache;
4312 cache = lookup_cache_extent(extent_cache, start, nr);
4314 rec = container_of(cache, struct extent_record, cache);
4318 rec->nr = max(nr, max_size);
4321 * We need to make sure to reset nr to whatever the extent
4322 * record says was the real size, this way we can compare it to
4326 if (start != rec->start || rec->found_rec) {
4327 struct extent_record *tmp;
4330 if (list_empty(&rec->list))
4331 list_add_tail(&rec->list,
4332 &duplicate_extents);
4335 * We have to do this song and dance in case we
4336 * find an extent record that falls inside of
4337 * our current extent record but does not have
4338 * the same objectid.
4340 tmp = malloc(sizeof(*tmp));
4344 tmp->max_size = max_size;
4347 tmp->metadata = metadata;
4348 tmp->extent_item_refs = extent_item_refs;
4349 INIT_LIST_HEAD(&tmp->list);
4350 list_add_tail(&tmp->list, &rec->dups);
4351 rec->num_duplicates++;
4358 if (extent_item_refs && !dup) {
4359 if (rec->extent_item_refs) {
4360 fprintf(stderr, "block %llu rec "
4361 "extent_item_refs %llu, passed %llu\n",
4362 (unsigned long long)start,
4363 (unsigned long long)
4364 rec->extent_item_refs,
4365 (unsigned long long)extent_item_refs);
4367 rec->extent_item_refs = extent_item_refs;
4372 rec->content_checked = 1;
4373 rec->owner_ref_checked = 1;
4377 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4379 rec->parent_generation = parent_gen;
4381 if (rec->max_size < max_size)
4382 rec->max_size = max_size;
4384 maybe_free_extent_rec(extent_cache, rec);
4387 rec = malloc(sizeof(*rec));
4389 rec->max_size = max_size;
4390 rec->nr = max(nr, max_size);
4391 rec->found_rec = !!extent_rec;
4392 rec->content_checked = 0;
4393 rec->owner_ref_checked = 0;
4394 rec->num_duplicates = 0;
4395 rec->metadata = metadata;
4396 rec->flag_block_full_backref = -1;
4397 rec->bad_full_backref = 0;
4398 INIT_LIST_HEAD(&rec->backrefs);
4399 INIT_LIST_HEAD(&rec->dups);
4400 INIT_LIST_HEAD(&rec->list);
4412 if (extent_item_refs)
4413 rec->extent_item_refs = extent_item_refs;
4415 rec->extent_item_refs = 0;
4418 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4420 memset(&rec->parent_key, 0, sizeof(*parent_key));
4423 rec->parent_generation = parent_gen;
4425 rec->parent_generation = 0;
4427 rec->cache.start = start;
4428 rec->cache.size = nr;
4429 ret = insert_cache_extent(extent_cache, &rec->cache);
4433 rec->content_checked = 1;
4434 rec->owner_ref_checked = 1;
4439 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4440 u64 parent, u64 root, int found_ref)
4442 struct extent_record *rec;
4443 struct tree_backref *back;
4444 struct cache_extent *cache;
4446 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4448 add_extent_rec(extent_cache, NULL, 0, bytenr,
4449 1, 0, 0, 0, 0, 1, 0, 0);
4450 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4455 rec = container_of(cache, struct extent_record, cache);
4456 if (rec->start != bytenr) {
4460 back = find_tree_backref(rec, parent, root);
4462 back = alloc_tree_backref(rec, parent, root);
4465 if (back->node.found_ref) {
4466 fprintf(stderr, "Extent back ref already exists "
4467 "for %llu parent %llu root %llu \n",
4468 (unsigned long long)bytenr,
4469 (unsigned long long)parent,
4470 (unsigned long long)root);
4472 back->node.found_ref = 1;
4474 if (back->node.found_extent_tree) {
4475 fprintf(stderr, "Extent back ref already exists "
4476 "for %llu parent %llu root %llu \n",
4477 (unsigned long long)bytenr,
4478 (unsigned long long)parent,
4479 (unsigned long long)root);
4481 back->node.found_extent_tree = 1;
4483 maybe_free_extent_rec(extent_cache, rec);
4487 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4488 u64 parent, u64 root, u64 owner, u64 offset,
4489 u32 num_refs, int found_ref, u64 max_size)
4491 struct extent_record *rec;
4492 struct data_backref *back;
4493 struct cache_extent *cache;
4495 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4497 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4499 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4504 rec = container_of(cache, struct extent_record, cache);
4505 if (rec->max_size < max_size)
4506 rec->max_size = max_size;
4509 * If found_ref is set then max_size is the real size and must match the
4510 * existing refs. So if we have already found a ref then we need to
4511 * make sure that this ref matches the existing one, otherwise we need
4512 * to add a new backref so we can notice that the backrefs don't match
4513 * and we need to figure out who is telling the truth. This is to
4514 * account for that awful fsync bug I introduced where we'd end up with
4515 * a btrfs_file_extent_item that would have its length include multiple
4516 * prealloc extents or point inside of a prealloc extent.
4518 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4521 back = alloc_data_backref(rec, parent, root, owner, offset,
4525 BUG_ON(num_refs != 1);
4526 if (back->node.found_ref)
4527 BUG_ON(back->bytes != max_size);
4528 back->node.found_ref = 1;
4529 back->found_ref += 1;
4530 back->bytes = max_size;
4531 back->disk_bytenr = bytenr;
4533 rec->content_checked = 1;
4534 rec->owner_ref_checked = 1;
4536 if (back->node.found_extent_tree) {
4537 fprintf(stderr, "Extent back ref already exists "
4538 "for %llu parent %llu root %llu "
4539 "owner %llu offset %llu num_refs %lu\n",
4540 (unsigned long long)bytenr,
4541 (unsigned long long)parent,
4542 (unsigned long long)root,
4543 (unsigned long long)owner,
4544 (unsigned long long)offset,
4545 (unsigned long)num_refs);
4547 back->num_refs = num_refs;
4548 back->node.found_extent_tree = 1;
4550 maybe_free_extent_rec(extent_cache, rec);
4554 static int add_pending(struct cache_tree *pending,
4555 struct cache_tree *seen, u64 bytenr, u32 size)
4558 ret = add_cache_extent(seen, bytenr, size);
4561 add_cache_extent(pending, bytenr, size);
4565 static int pick_next_pending(struct cache_tree *pending,
4566 struct cache_tree *reada,
4567 struct cache_tree *nodes,
4568 u64 last, struct block_info *bits, int bits_nr,
4571 unsigned long node_start = last;
4572 struct cache_extent *cache;
4575 cache = search_cache_extent(reada, 0);
4577 bits[0].start = cache->start;
4578 bits[0].size = cache->size;
4583 if (node_start > 32768)
4584 node_start -= 32768;
4586 cache = search_cache_extent(nodes, node_start);
4588 cache = search_cache_extent(nodes, 0);
4591 cache = search_cache_extent(pending, 0);
4596 bits[ret].start = cache->start;
4597 bits[ret].size = cache->size;
4598 cache = next_cache_extent(cache);
4600 } while (cache && ret < bits_nr);
4606 bits[ret].start = cache->start;
4607 bits[ret].size = cache->size;
4608 cache = next_cache_extent(cache);
4610 } while (cache && ret < bits_nr);
4612 if (bits_nr - ret > 8) {
4613 u64 lookup = bits[0].start + bits[0].size;
4614 struct cache_extent *next;
4615 next = search_cache_extent(pending, lookup);
4617 if (next->start - lookup > 32768)
4619 bits[ret].start = next->start;
4620 bits[ret].size = next->size;
4621 lookup = next->start + next->size;
4625 next = next_cache_extent(next);
4633 static void free_chunk_record(struct cache_extent *cache)
4635 struct chunk_record *rec;
4637 rec = container_of(cache, struct chunk_record, cache);
4638 list_del_init(&rec->list);
4639 list_del_init(&rec->dextents);
4643 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4645 cache_tree_free_extents(chunk_cache, free_chunk_record);
4648 static void free_device_record(struct rb_node *node)
4650 struct device_record *rec;
4652 rec = container_of(node, struct device_record, node);
4656 FREE_RB_BASED_TREE(device_cache, free_device_record);
4658 int insert_block_group_record(struct block_group_tree *tree,
4659 struct block_group_record *bg_rec)
4663 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4667 list_add_tail(&bg_rec->list, &tree->block_groups);
4671 static void free_block_group_record(struct cache_extent *cache)
4673 struct block_group_record *rec;
4675 rec = container_of(cache, struct block_group_record, cache);
4676 list_del_init(&rec->list);
4680 void free_block_group_tree(struct block_group_tree *tree)
4682 cache_tree_free_extents(&tree->tree, free_block_group_record);
4685 int insert_device_extent_record(struct device_extent_tree *tree,
4686 struct device_extent_record *de_rec)
4691 * Device extent is a bit different from the other extents, because
4692 * the extents which belong to the different devices may have the
4693 * same start and size, so we need use the special extent cache
4694 * search/insert functions.
4696 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4700 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4701 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4705 static void free_device_extent_record(struct cache_extent *cache)
4707 struct device_extent_record *rec;
4709 rec = container_of(cache, struct device_extent_record, cache);
4710 if (!list_empty(&rec->chunk_list))
4711 list_del_init(&rec->chunk_list);
4712 if (!list_empty(&rec->device_list))
4713 list_del_init(&rec->device_list);
4717 void free_device_extent_tree(struct device_extent_tree *tree)
4719 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4722 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4723 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4724 struct extent_buffer *leaf, int slot)
4726 struct btrfs_extent_ref_v0 *ref0;
4727 struct btrfs_key key;
4729 btrfs_item_key_to_cpu(leaf, &key, slot);
4730 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4731 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4732 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4734 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4735 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4741 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4742 struct btrfs_key *key,
4745 struct btrfs_chunk *ptr;
4746 struct chunk_record *rec;
4749 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4750 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4752 rec = malloc(btrfs_chunk_record_size(num_stripes));
4754 fprintf(stderr, "memory allocation failed\n");
4758 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4760 INIT_LIST_HEAD(&rec->list);
4761 INIT_LIST_HEAD(&rec->dextents);
4764 rec->cache.start = key->offset;
4765 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4767 rec->generation = btrfs_header_generation(leaf);
4769 rec->objectid = key->objectid;
4770 rec->type = key->type;
4771 rec->offset = key->offset;
4773 rec->length = rec->cache.size;
4774 rec->owner = btrfs_chunk_owner(leaf, ptr);
4775 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4776 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4777 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4778 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4779 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4780 rec->num_stripes = num_stripes;
4781 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4783 for (i = 0; i < rec->num_stripes; ++i) {
4784 rec->stripes[i].devid =
4785 btrfs_stripe_devid_nr(leaf, ptr, i);
4786 rec->stripes[i].offset =
4787 btrfs_stripe_offset_nr(leaf, ptr, i);
4788 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4789 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4796 static int process_chunk_item(struct cache_tree *chunk_cache,
4797 struct btrfs_key *key, struct extent_buffer *eb,
4800 struct chunk_record *rec;
4803 rec = btrfs_new_chunk_record(eb, key, slot);
4804 ret = insert_cache_extent(chunk_cache, &rec->cache);
4806 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4807 rec->offset, rec->length);
4814 static int process_device_item(struct rb_root *dev_cache,
4815 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4817 struct btrfs_dev_item *ptr;
4818 struct device_record *rec;
4821 ptr = btrfs_item_ptr(eb,
4822 slot, struct btrfs_dev_item);
4824 rec = malloc(sizeof(*rec));
4826 fprintf(stderr, "memory allocation failed\n");
4830 rec->devid = key->offset;
4831 rec->generation = btrfs_header_generation(eb);
4833 rec->objectid = key->objectid;
4834 rec->type = key->type;
4835 rec->offset = key->offset;
4837 rec->devid = btrfs_device_id(eb, ptr);
4838 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4839 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4841 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4843 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4850 struct block_group_record *
4851 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4854 struct btrfs_block_group_item *ptr;
4855 struct block_group_record *rec;
4857 rec = malloc(sizeof(*rec));
4859 fprintf(stderr, "memory allocation failed\n");
4862 memset(rec, 0, sizeof(*rec));
4864 rec->cache.start = key->objectid;
4865 rec->cache.size = key->offset;
4867 rec->generation = btrfs_header_generation(leaf);
4869 rec->objectid = key->objectid;
4870 rec->type = key->type;
4871 rec->offset = key->offset;
4873 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4874 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4876 INIT_LIST_HEAD(&rec->list);
4881 static int process_block_group_item(struct block_group_tree *block_group_cache,
4882 struct btrfs_key *key,
4883 struct extent_buffer *eb, int slot)
4885 struct block_group_record *rec;
4888 rec = btrfs_new_block_group_record(eb, key, slot);
4889 ret = insert_block_group_record(block_group_cache, rec);
4891 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4892 rec->objectid, rec->offset);
4899 struct device_extent_record *
4900 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4901 struct btrfs_key *key, int slot)
4903 struct device_extent_record *rec;
4904 struct btrfs_dev_extent *ptr;
4906 rec = malloc(sizeof(*rec));
4908 fprintf(stderr, "memory allocation failed\n");
4911 memset(rec, 0, sizeof(*rec));
4913 rec->cache.objectid = key->objectid;
4914 rec->cache.start = key->offset;
4916 rec->generation = btrfs_header_generation(leaf);
4918 rec->objectid = key->objectid;
4919 rec->type = key->type;
4920 rec->offset = key->offset;
4922 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4923 rec->chunk_objecteid =
4924 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4926 btrfs_dev_extent_chunk_offset(leaf, ptr);
4927 rec->length = btrfs_dev_extent_length(leaf, ptr);
4928 rec->cache.size = rec->length;
4930 INIT_LIST_HEAD(&rec->chunk_list);
4931 INIT_LIST_HEAD(&rec->device_list);
4937 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4938 struct btrfs_key *key, struct extent_buffer *eb,
4941 struct device_extent_record *rec;
4944 rec = btrfs_new_device_extent_record(eb, key, slot);
4945 ret = insert_device_extent_record(dev_extent_cache, rec);
4948 "Device extent[%llu, %llu, %llu] existed.\n",
4949 rec->objectid, rec->offset, rec->length);
4956 static int process_extent_item(struct btrfs_root *root,
4957 struct cache_tree *extent_cache,
4958 struct extent_buffer *eb, int slot)
4960 struct btrfs_extent_item *ei;
4961 struct btrfs_extent_inline_ref *iref;
4962 struct btrfs_extent_data_ref *dref;
4963 struct btrfs_shared_data_ref *sref;
4964 struct btrfs_key key;
4968 u32 item_size = btrfs_item_size_nr(eb, slot);
4974 btrfs_item_key_to_cpu(eb, &key, slot);
4976 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4978 num_bytes = root->leafsize;
4980 num_bytes = key.offset;
4983 if (item_size < sizeof(*ei)) {
4984 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4985 struct btrfs_extent_item_v0 *ei0;
4986 BUG_ON(item_size != sizeof(*ei0));
4987 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4988 refs = btrfs_extent_refs_v0(eb, ei0);
4992 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4993 num_bytes, refs, 0, 0, 0, metadata, 1,
4997 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4998 refs = btrfs_extent_refs(eb, ei);
5000 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
5001 refs, 0, 0, 0, metadata, 1, num_bytes);
5003 ptr = (unsigned long)(ei + 1);
5004 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
5005 key.type == BTRFS_EXTENT_ITEM_KEY)
5006 ptr += sizeof(struct btrfs_tree_block_info);
5008 end = (unsigned long)ei + item_size;
5010 iref = (struct btrfs_extent_inline_ref *)ptr;
5011 type = btrfs_extent_inline_ref_type(eb, iref);
5012 offset = btrfs_extent_inline_ref_offset(eb, iref);
5014 case BTRFS_TREE_BLOCK_REF_KEY:
5015 add_tree_backref(extent_cache, key.objectid,
5018 case BTRFS_SHARED_BLOCK_REF_KEY:
5019 add_tree_backref(extent_cache, key.objectid,
5022 case BTRFS_EXTENT_DATA_REF_KEY:
5023 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
5024 add_data_backref(extent_cache, key.objectid, 0,
5025 btrfs_extent_data_ref_root(eb, dref),
5026 btrfs_extent_data_ref_objectid(eb,
5028 btrfs_extent_data_ref_offset(eb, dref),
5029 btrfs_extent_data_ref_count(eb, dref),
5032 case BTRFS_SHARED_DATA_REF_KEY:
5033 sref = (struct btrfs_shared_data_ref *)(iref + 1);
5034 add_data_backref(extent_cache, key.objectid, offset,
5036 btrfs_shared_data_ref_count(eb, sref),
5040 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
5041 key.objectid, key.type, num_bytes);
5044 ptr += btrfs_extent_inline_ref_size(type);
5051 static int check_cache_range(struct btrfs_root *root,
5052 struct btrfs_block_group_cache *cache,
5053 u64 offset, u64 bytes)
5055 struct btrfs_free_space *entry;
5061 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5062 bytenr = btrfs_sb_offset(i);
5063 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5064 cache->key.objectid, bytenr, 0,
5065 &logical, &nr, &stripe_len);
5070 if (logical[nr] + stripe_len <= offset)
5072 if (offset + bytes <= logical[nr])
5074 if (logical[nr] == offset) {
5075 if (stripe_len >= bytes) {
5079 bytes -= stripe_len;
5080 offset += stripe_len;
5081 } else if (logical[nr] < offset) {
5082 if (logical[nr] + stripe_len >=
5087 bytes = (offset + bytes) -
5088 (logical[nr] + stripe_len);
5089 offset = logical[nr] + stripe_len;
5092 * Could be tricky, the super may land in the
5093 * middle of the area we're checking. First
5094 * check the easiest case, it's at the end.
5096 if (logical[nr] + stripe_len >=
5098 bytes = logical[nr] - offset;
5102 /* Check the left side */
5103 ret = check_cache_range(root, cache,
5105 logical[nr] - offset);
5111 /* Now we continue with the right side */
5112 bytes = (offset + bytes) -
5113 (logical[nr] + stripe_len);
5114 offset = logical[nr] + stripe_len;
5121 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5123 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5124 offset, offset+bytes);
5128 if (entry->offset != offset) {
5129 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5134 if (entry->bytes != bytes) {
5135 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5136 bytes, entry->bytes, offset);
5140 unlink_free_space(cache->free_space_ctl, entry);
5145 static int verify_space_cache(struct btrfs_root *root,
5146 struct btrfs_block_group_cache *cache)
5148 struct btrfs_path *path;
5149 struct extent_buffer *leaf;
5150 struct btrfs_key key;
5154 path = btrfs_alloc_path();
5158 root = root->fs_info->extent_root;
5160 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5162 key.objectid = last;
5164 key.type = BTRFS_EXTENT_ITEM_KEY;
5166 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5171 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5172 ret = btrfs_next_leaf(root, path);
5180 leaf = path->nodes[0];
5181 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5182 if (key.objectid >= cache->key.offset + cache->key.objectid)
5184 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5185 key.type != BTRFS_METADATA_ITEM_KEY) {
5190 if (last == key.objectid) {
5191 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5192 last = key.objectid + key.offset;
5194 last = key.objectid + root->leafsize;
5199 ret = check_cache_range(root, cache, last,
5200 key.objectid - last);
5203 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5204 last = key.objectid + key.offset;
5206 last = key.objectid + root->leafsize;
5210 if (last < cache->key.objectid + cache->key.offset)
5211 ret = check_cache_range(root, cache, last,
5212 cache->key.objectid +
5213 cache->key.offset - last);
5216 btrfs_free_path(path);
5219 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5220 fprintf(stderr, "There are still entries left in the space "
5228 static int check_space_cache(struct btrfs_root *root)
5230 struct btrfs_block_group_cache *cache;
5231 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5235 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5236 btrfs_super_generation(root->fs_info->super_copy) !=
5237 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5238 printf("cache and super generation don't match, space cache "
5239 "will be invalidated\n");
5244 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5248 start = cache->key.objectid + cache->key.offset;
5249 if (!cache->free_space_ctl) {
5250 if (btrfs_init_free_space_ctl(cache,
5251 root->sectorsize)) {
5256 btrfs_remove_free_space_cache(cache);
5259 ret = load_free_space_cache(root->fs_info, cache);
5263 ret = verify_space_cache(root, cache);
5265 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5266 cache->key.objectid);
5271 return error ? -EINVAL : 0;
5274 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5275 u64 num_bytes, unsigned long leaf_offset,
5276 struct extent_buffer *eb) {
5279 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5281 unsigned long csum_offset;
5285 u64 data_checked = 0;
5291 if (num_bytes % root->sectorsize)
5294 data = malloc(num_bytes);
5298 while (offset < num_bytes) {
5301 read_len = num_bytes - offset;
5302 /* read as much space once a time */
5303 ret = read_extent_data(root, data + offset,
5304 bytenr + offset, &read_len, mirror);
5308 /* verify every 4k data's checksum */
5309 while (data_checked < read_len) {
5311 tmp = offset + data_checked;
5313 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5314 csum, root->sectorsize);
5315 btrfs_csum_final(csum, (char *)&csum);
5317 csum_offset = leaf_offset +
5318 tmp / root->sectorsize * csum_size;
5319 read_extent_buffer(eb, (char *)&csum_expected,
5320 csum_offset, csum_size);
5321 /* try another mirror */
5322 if (csum != csum_expected) {
5323 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5324 mirror, bytenr + tmp,
5325 csum, csum_expected);
5326 num_copies = btrfs_num_copies(
5327 &root->fs_info->mapping_tree,
5329 if (mirror < num_copies - 1) {
5334 data_checked += root->sectorsize;
5343 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5346 struct btrfs_path *path;
5347 struct extent_buffer *leaf;
5348 struct btrfs_key key;
5351 path = btrfs_alloc_path();
5353 fprintf(stderr, "Error allocing path\n");
5357 key.objectid = bytenr;
5358 key.type = BTRFS_EXTENT_ITEM_KEY;
5359 key.offset = (u64)-1;
5362 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5365 fprintf(stderr, "Error looking up extent record %d\n", ret);
5366 btrfs_free_path(path);
5369 if (path->slots[0] > 0) {
5372 ret = btrfs_prev_leaf(root, path);
5375 } else if (ret > 0) {
5382 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5385 * Block group items come before extent items if they have the same
5386 * bytenr, so walk back one more just in case. Dear future traveler,
5387 * first congrats on mastering time travel. Now if it's not too much
5388 * trouble could you go back to 2006 and tell Chris to make the
5389 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5390 * EXTENT_ITEM_KEY please?
5392 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5393 if (path->slots[0] > 0) {
5396 ret = btrfs_prev_leaf(root, path);
5399 } else if (ret > 0) {
5404 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5408 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5409 ret = btrfs_next_leaf(root, path);
5411 fprintf(stderr, "Error going to next leaf "
5413 btrfs_free_path(path);
5419 leaf = path->nodes[0];
5420 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5421 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5425 if (key.objectid + key.offset < bytenr) {
5429 if (key.objectid > bytenr + num_bytes)
5432 if (key.objectid == bytenr) {
5433 if (key.offset >= num_bytes) {
5437 num_bytes -= key.offset;
5438 bytenr += key.offset;
5439 } else if (key.objectid < bytenr) {
5440 if (key.objectid + key.offset >= bytenr + num_bytes) {
5444 num_bytes = (bytenr + num_bytes) -
5445 (key.objectid + key.offset);
5446 bytenr = key.objectid + key.offset;
5448 if (key.objectid + key.offset < bytenr + num_bytes) {
5449 u64 new_start = key.objectid + key.offset;
5450 u64 new_bytes = bytenr + num_bytes - new_start;
5453 * Weird case, the extent is in the middle of
5454 * our range, we'll have to search one side
5455 * and then the other. Not sure if this happens
5456 * in real life, but no harm in coding it up
5457 * anyway just in case.
5459 btrfs_release_path(path);
5460 ret = check_extent_exists(root, new_start,
5463 fprintf(stderr, "Right section didn't "
5467 num_bytes = key.objectid - bytenr;
5470 num_bytes = key.objectid - bytenr;
5477 if (num_bytes && !ret) {
5478 fprintf(stderr, "There are no extents for csum range "
5479 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5483 btrfs_free_path(path);
5487 static int check_csums(struct btrfs_root *root)
5489 struct btrfs_path *path;
5490 struct extent_buffer *leaf;
5491 struct btrfs_key key;
5492 u64 offset = 0, num_bytes = 0;
5493 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5497 unsigned long leaf_offset;
5499 root = root->fs_info->csum_root;
5500 if (!extent_buffer_uptodate(root->node)) {
5501 fprintf(stderr, "No valid csum tree found\n");
5505 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5506 key.type = BTRFS_EXTENT_CSUM_KEY;
5509 path = btrfs_alloc_path();
5513 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5515 fprintf(stderr, "Error searching csum tree %d\n", ret);
5516 btrfs_free_path(path);
5520 if (ret > 0 && path->slots[0])
5525 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5526 ret = btrfs_next_leaf(root, path);
5528 fprintf(stderr, "Error going to next leaf "
5535 leaf = path->nodes[0];
5537 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5538 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5543 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5544 csum_size) * root->sectorsize;
5545 if (!check_data_csum)
5546 goto skip_csum_check;
5547 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5548 ret = check_extent_csums(root, key.offset, data_len,
5554 offset = key.offset;
5555 } else if (key.offset != offset + num_bytes) {
5556 ret = check_extent_exists(root, offset, num_bytes);
5558 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5559 "there is no extent record\n",
5560 offset, offset+num_bytes);
5563 offset = key.offset;
5566 num_bytes += data_len;
5570 btrfs_free_path(path);
5574 static int is_dropped_key(struct btrfs_key *key,
5575 struct btrfs_key *drop_key) {
5576 if (key->objectid < drop_key->objectid)
5578 else if (key->objectid == drop_key->objectid) {
5579 if (key->type < drop_key->type)
5581 else if (key->type == drop_key->type) {
5582 if (key->offset < drop_key->offset)
5590 * Here are the rules for FULL_BACKREF.
5592 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5593 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5595 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5596 * if it happened after the relocation occurred since we'll have dropped the
5597 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5598 * have no real way to know for sure.
5600 * We process the blocks one root at a time, and we start from the lowest root
5601 * objectid and go to the highest. So we can just lookup the owner backref for
5602 * the record and if we don't find it then we know it doesn't exist and we have
5605 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5606 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5607 * be set or not and then we can check later once we've gathered all the refs.
5609 static int calc_extent_flag(struct btrfs_root *root,
5610 struct cache_tree *extent_cache,
5611 struct extent_buffer *buf,
5612 struct root_item_record *ri,
5615 struct extent_record *rec;
5616 struct cache_extent *cache;
5617 struct tree_backref *tback;
5620 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5621 /* we have added this extent before */
5623 rec = container_of(cache, struct extent_record, cache);
5626 * Except file/reloc tree, we can not have
5629 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5634 if (buf->start == ri->bytenr)
5637 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5640 owner = btrfs_header_owner(buf);
5641 if (owner == ri->objectid)
5644 tback = find_tree_backref(rec, 0, owner);
5649 if (rec->flag_block_full_backref != -1 &&
5650 rec->flag_block_full_backref != 0)
5651 rec->bad_full_backref = 1;
5654 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5655 if (rec->flag_block_full_backref != -1 &&
5656 rec->flag_block_full_backref != 1)
5657 rec->bad_full_backref = 1;
5661 static int run_next_block(struct btrfs_root *root,
5662 struct block_info *bits,
5665 struct cache_tree *pending,
5666 struct cache_tree *seen,
5667 struct cache_tree *reada,
5668 struct cache_tree *nodes,
5669 struct cache_tree *extent_cache,
5670 struct cache_tree *chunk_cache,
5671 struct rb_root *dev_cache,
5672 struct block_group_tree *block_group_cache,
5673 struct device_extent_tree *dev_extent_cache,
5674 struct root_item_record *ri)
5676 struct extent_buffer *buf;
5677 struct extent_record *rec = NULL;
5688 struct btrfs_key key;
5689 struct cache_extent *cache;
5692 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5693 bits_nr, &reada_bits);
5698 for(i = 0; i < nritems; i++) {
5699 ret = add_cache_extent(reada, bits[i].start,
5704 /* fixme, get the parent transid */
5705 readahead_tree_block(root, bits[i].start,
5709 *last = bits[0].start;
5710 bytenr = bits[0].start;
5711 size = bits[0].size;
5713 cache = lookup_cache_extent(pending, bytenr, size);
5715 remove_cache_extent(pending, cache);
5718 cache = lookup_cache_extent(reada, bytenr, size);
5720 remove_cache_extent(reada, cache);
5723 cache = lookup_cache_extent(nodes, bytenr, size);
5725 remove_cache_extent(nodes, cache);
5728 cache = lookup_cache_extent(extent_cache, bytenr, size);
5730 rec = container_of(cache, struct extent_record, cache);
5731 gen = rec->parent_generation;
5734 /* fixme, get the real parent transid */
5735 buf = read_tree_block(root, bytenr, size, gen);
5736 if (!extent_buffer_uptodate(buf)) {
5737 record_bad_block_io(root->fs_info,
5738 extent_cache, bytenr, size);
5742 nritems = btrfs_header_nritems(buf);
5745 if (!init_extent_tree) {
5746 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5747 btrfs_header_level(buf), 1, NULL,
5750 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5752 fprintf(stderr, "Couldn't calc extent flags\n");
5753 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5758 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5760 fprintf(stderr, "Couldn't calc extent flags\n");
5761 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5765 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5767 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5768 ri->objectid == btrfs_header_owner(buf)) {
5770 * Ok we got to this block from it's original owner and
5771 * we have FULL_BACKREF set. Relocation can leave
5772 * converted blocks over so this is altogether possible,
5773 * however it's not possible if the generation > the
5774 * last snapshot, so check for this case.
5776 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5777 btrfs_header_generation(buf) > ri->last_snapshot) {
5778 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5779 rec->bad_full_backref = 1;
5784 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5785 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5786 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5787 rec->bad_full_backref = 1;
5791 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5792 rec->flag_block_full_backref = 1;
5796 rec->flag_block_full_backref = 0;
5798 owner = btrfs_header_owner(buf);
5801 ret = check_block(root, extent_cache, buf, flags);
5805 if (btrfs_is_leaf(buf)) {
5806 btree_space_waste += btrfs_leaf_free_space(root, buf);
5807 for (i = 0; i < nritems; i++) {
5808 struct btrfs_file_extent_item *fi;
5809 btrfs_item_key_to_cpu(buf, &key, i);
5810 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5811 process_extent_item(root, extent_cache, buf,
5815 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5816 process_extent_item(root, extent_cache, buf,
5820 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5822 btrfs_item_size_nr(buf, i);
5825 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5826 process_chunk_item(chunk_cache, &key, buf, i);
5829 if (key.type == BTRFS_DEV_ITEM_KEY) {
5830 process_device_item(dev_cache, &key, buf, i);
5833 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5834 process_block_group_item(block_group_cache,
5838 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5839 process_device_extent_item(dev_extent_cache,
5844 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5845 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5846 process_extent_ref_v0(extent_cache, buf, i);
5853 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5854 add_tree_backref(extent_cache, key.objectid, 0,
5858 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5859 add_tree_backref(extent_cache, key.objectid,
5863 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5864 struct btrfs_extent_data_ref *ref;
5865 ref = btrfs_item_ptr(buf, i,
5866 struct btrfs_extent_data_ref);
5867 add_data_backref(extent_cache,
5869 btrfs_extent_data_ref_root(buf, ref),
5870 btrfs_extent_data_ref_objectid(buf,
5872 btrfs_extent_data_ref_offset(buf, ref),
5873 btrfs_extent_data_ref_count(buf, ref),
5874 0, root->sectorsize);
5877 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5878 struct btrfs_shared_data_ref *ref;
5879 ref = btrfs_item_ptr(buf, i,
5880 struct btrfs_shared_data_ref);
5881 add_data_backref(extent_cache,
5882 key.objectid, key.offset, 0, 0, 0,
5883 btrfs_shared_data_ref_count(buf, ref),
5884 0, root->sectorsize);
5887 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5888 struct bad_item *bad;
5890 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5894 bad = malloc(sizeof(struct bad_item));
5897 INIT_LIST_HEAD(&bad->list);
5898 memcpy(&bad->key, &key,
5899 sizeof(struct btrfs_key));
5900 bad->root_id = owner;
5901 list_add_tail(&bad->list, &delete_items);
5904 if (key.type != BTRFS_EXTENT_DATA_KEY)
5906 fi = btrfs_item_ptr(buf, i,
5907 struct btrfs_file_extent_item);
5908 if (btrfs_file_extent_type(buf, fi) ==
5909 BTRFS_FILE_EXTENT_INLINE)
5911 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5914 data_bytes_allocated +=
5915 btrfs_file_extent_disk_num_bytes(buf, fi);
5916 if (data_bytes_allocated < root->sectorsize) {
5919 data_bytes_referenced +=
5920 btrfs_file_extent_num_bytes(buf, fi);
5921 add_data_backref(extent_cache,
5922 btrfs_file_extent_disk_bytenr(buf, fi),
5923 parent, owner, key.objectid, key.offset -
5924 btrfs_file_extent_offset(buf, fi), 1, 1,
5925 btrfs_file_extent_disk_num_bytes(buf, fi));
5929 struct btrfs_key first_key;
5931 first_key.objectid = 0;
5934 btrfs_item_key_to_cpu(buf, &first_key, 0);
5935 level = btrfs_header_level(buf);
5936 for (i = 0; i < nritems; i++) {
5937 ptr = btrfs_node_blockptr(buf, i);
5938 size = btrfs_level_size(root, level - 1);
5939 btrfs_node_key_to_cpu(buf, &key, i);
5941 if ((level == ri->drop_level)
5942 && is_dropped_key(&key, &ri->drop_key)) {
5946 ret = add_extent_rec(extent_cache, &key,
5947 btrfs_node_ptr_generation(buf, i),
5948 ptr, size, 0, 0, 1, 0, 1, 0,
5952 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5955 add_pending(nodes, seen, ptr, size);
5957 add_pending(pending, seen, ptr, size);
5960 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5961 nritems) * sizeof(struct btrfs_key_ptr);
5963 total_btree_bytes += buf->len;
5964 if (fs_root_objectid(btrfs_header_owner(buf)))
5965 total_fs_tree_bytes += buf->len;
5966 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5967 total_extent_tree_bytes += buf->len;
5968 if (!found_old_backref &&
5969 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5970 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5971 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5972 found_old_backref = 1;
5974 free_extent_buffer(buf);
5978 static int add_root_to_pending(struct extent_buffer *buf,
5979 struct cache_tree *extent_cache,
5980 struct cache_tree *pending,
5981 struct cache_tree *seen,
5982 struct cache_tree *nodes,
5985 if (btrfs_header_level(buf) > 0)
5986 add_pending(nodes, seen, buf->start, buf->len);
5988 add_pending(pending, seen, buf->start, buf->len);
5989 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5990 0, 1, 1, 0, 1, 0, buf->len);
5992 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5993 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5994 add_tree_backref(extent_cache, buf->start, buf->start,
5997 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
6001 /* as we fix the tree, we might be deleting blocks that
6002 * we're tracking for repair. This hook makes sure we
6003 * remove any backrefs for blocks as we are fixing them.
6005 static int free_extent_hook(struct btrfs_trans_handle *trans,
6006 struct btrfs_root *root,
6007 u64 bytenr, u64 num_bytes, u64 parent,
6008 u64 root_objectid, u64 owner, u64 offset,
6011 struct extent_record *rec;
6012 struct cache_extent *cache;
6014 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6016 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6017 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6021 rec = container_of(cache, struct extent_record, cache);
6023 struct data_backref *back;
6024 back = find_data_backref(rec, parent, root_objectid, owner,
6025 offset, 1, bytenr, num_bytes);
6028 if (back->node.found_ref) {
6029 back->found_ref -= refs_to_drop;
6031 rec->refs -= refs_to_drop;
6033 if (back->node.found_extent_tree) {
6034 back->num_refs -= refs_to_drop;
6035 if (rec->extent_item_refs)
6036 rec->extent_item_refs -= refs_to_drop;
6038 if (back->found_ref == 0)
6039 back->node.found_ref = 0;
6040 if (back->num_refs == 0)
6041 back->node.found_extent_tree = 0;
6043 if (!back->node.found_extent_tree && back->node.found_ref) {
6044 list_del(&back->node.list);
6048 struct tree_backref *back;
6049 back = find_tree_backref(rec, parent, root_objectid);
6052 if (back->node.found_ref) {
6055 back->node.found_ref = 0;
6057 if (back->node.found_extent_tree) {
6058 if (rec->extent_item_refs)
6059 rec->extent_item_refs--;
6060 back->node.found_extent_tree = 0;
6062 if (!back->node.found_extent_tree && back->node.found_ref) {
6063 list_del(&back->node.list);
6067 maybe_free_extent_rec(extent_cache, rec);
6072 static int delete_extent_records(struct btrfs_trans_handle *trans,
6073 struct btrfs_root *root,
6074 struct btrfs_path *path,
6075 u64 bytenr, u64 new_len)
6077 struct btrfs_key key;
6078 struct btrfs_key found_key;
6079 struct extent_buffer *leaf;
6084 key.objectid = bytenr;
6086 key.offset = (u64)-1;
6089 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6096 if (path->slots[0] == 0)
6102 leaf = path->nodes[0];
6103 slot = path->slots[0];
6105 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6106 if (found_key.objectid != bytenr)
6109 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6110 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6111 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6112 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6113 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6114 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6115 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6116 btrfs_release_path(path);
6117 if (found_key.type == 0) {
6118 if (found_key.offset == 0)
6120 key.offset = found_key.offset - 1;
6121 key.type = found_key.type;
6123 key.type = found_key.type - 1;
6124 key.offset = (u64)-1;
6128 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6129 found_key.objectid, found_key.type, found_key.offset);
6131 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6134 btrfs_release_path(path);
6136 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6137 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6138 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6139 found_key.offset : root->leafsize;
6141 ret = btrfs_update_block_group(trans, root, bytenr,
6148 btrfs_release_path(path);
6153 * for a single backref, this will allocate a new extent
6154 * and add the backref to it.
6156 static int record_extent(struct btrfs_trans_handle *trans,
6157 struct btrfs_fs_info *info,
6158 struct btrfs_path *path,
6159 struct extent_record *rec,
6160 struct extent_backref *back,
6161 int allocated, u64 flags)
6164 struct btrfs_root *extent_root = info->extent_root;
6165 struct extent_buffer *leaf;
6166 struct btrfs_key ins_key;
6167 struct btrfs_extent_item *ei;
6168 struct tree_backref *tback;
6169 struct data_backref *dback;
6170 struct btrfs_tree_block_info *bi;
6173 rec->max_size = max_t(u64, rec->max_size,
6174 info->extent_root->leafsize);
6177 u32 item_size = sizeof(*ei);
6180 item_size += sizeof(*bi);
6182 ins_key.objectid = rec->start;
6183 ins_key.offset = rec->max_size;
6184 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6186 ret = btrfs_insert_empty_item(trans, extent_root, path,
6187 &ins_key, item_size);
6191 leaf = path->nodes[0];
6192 ei = btrfs_item_ptr(leaf, path->slots[0],
6193 struct btrfs_extent_item);
6195 btrfs_set_extent_refs(leaf, ei, 0);
6196 btrfs_set_extent_generation(leaf, ei, rec->generation);
6198 if (back->is_data) {
6199 btrfs_set_extent_flags(leaf, ei,
6200 BTRFS_EXTENT_FLAG_DATA);
6202 struct btrfs_disk_key copy_key;;
6204 tback = (struct tree_backref *)back;
6205 bi = (struct btrfs_tree_block_info *)(ei + 1);
6206 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6209 btrfs_set_disk_key_objectid(©_key,
6210 rec->info_objectid);
6211 btrfs_set_disk_key_type(©_key, 0);
6212 btrfs_set_disk_key_offset(©_key, 0);
6214 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6215 btrfs_set_tree_block_key(leaf, bi, ©_key);
6217 btrfs_set_extent_flags(leaf, ei,
6218 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6221 btrfs_mark_buffer_dirty(leaf);
6222 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6223 rec->max_size, 1, 0);
6226 btrfs_release_path(path);
6229 if (back->is_data) {
6233 dback = (struct data_backref *)back;
6234 if (back->full_backref)
6235 parent = dback->parent;
6239 for (i = 0; i < dback->found_ref; i++) {
6240 /* if parent != 0, we're doing a full backref
6241 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6242 * just makes the backref allocator create a data
6245 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6246 rec->start, rec->max_size,
6250 BTRFS_FIRST_FREE_OBJECTID :
6256 fprintf(stderr, "adding new data backref"
6257 " on %llu %s %llu owner %llu"
6258 " offset %llu found %d\n",
6259 (unsigned long long)rec->start,
6260 back->full_backref ?
6262 back->full_backref ?
6263 (unsigned long long)parent :
6264 (unsigned long long)dback->root,
6265 (unsigned long long)dback->owner,
6266 (unsigned long long)dback->offset,
6271 tback = (struct tree_backref *)back;
6272 if (back->full_backref)
6273 parent = tback->parent;
6277 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6278 rec->start, rec->max_size,
6279 parent, tback->root, 0, 0);
6280 fprintf(stderr, "adding new tree backref on "
6281 "start %llu len %llu parent %llu root %llu\n",
6282 rec->start, rec->max_size, parent, tback->root);
6287 btrfs_release_path(path);
6291 struct extent_entry {
6296 struct list_head list;
6299 static struct extent_entry *find_entry(struct list_head *entries,
6300 u64 bytenr, u64 bytes)
6302 struct extent_entry *entry = NULL;
6304 list_for_each_entry(entry, entries, list) {
6305 if (entry->bytenr == bytenr && entry->bytes == bytes)
6312 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6314 struct extent_entry *entry, *best = NULL, *prev = NULL;
6316 list_for_each_entry(entry, entries, list) {
6323 * If there are as many broken entries as entries then we know
6324 * not to trust this particular entry.
6326 if (entry->broken == entry->count)
6330 * If our current entry == best then we can't be sure our best
6331 * is really the best, so we need to keep searching.
6333 if (best && best->count == entry->count) {
6339 /* Prev == entry, not good enough, have to keep searching */
6340 if (!prev->broken && prev->count == entry->count)
6344 best = (prev->count > entry->count) ? prev : entry;
6345 else if (best->count < entry->count)
6353 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6354 struct data_backref *dback, struct extent_entry *entry)
6356 struct btrfs_trans_handle *trans;
6357 struct btrfs_root *root;
6358 struct btrfs_file_extent_item *fi;
6359 struct extent_buffer *leaf;
6360 struct btrfs_key key;
6364 key.objectid = dback->root;
6365 key.type = BTRFS_ROOT_ITEM_KEY;
6366 key.offset = (u64)-1;
6367 root = btrfs_read_fs_root(info, &key);
6369 fprintf(stderr, "Couldn't find root for our ref\n");
6374 * The backref points to the original offset of the extent if it was
6375 * split, so we need to search down to the offset we have and then walk
6376 * forward until we find the backref we're looking for.
6378 key.objectid = dback->owner;
6379 key.type = BTRFS_EXTENT_DATA_KEY;
6380 key.offset = dback->offset;
6381 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6383 fprintf(stderr, "Error looking up ref %d\n", ret);
6388 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6389 ret = btrfs_next_leaf(root, path);
6391 fprintf(stderr, "Couldn't find our ref, next\n");
6395 leaf = path->nodes[0];
6396 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6397 if (key.objectid != dback->owner ||
6398 key.type != BTRFS_EXTENT_DATA_KEY) {
6399 fprintf(stderr, "Couldn't find our ref, search\n");
6402 fi = btrfs_item_ptr(leaf, path->slots[0],
6403 struct btrfs_file_extent_item);
6404 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6405 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6407 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6412 btrfs_release_path(path);
6414 trans = btrfs_start_transaction(root, 1);
6416 return PTR_ERR(trans);
6419 * Ok we have the key of the file extent we want to fix, now we can cow
6420 * down to the thing and fix it.
6422 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6424 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6425 key.objectid, key.type, key.offset, ret);
6429 fprintf(stderr, "Well that's odd, we just found this key "
6430 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6435 leaf = path->nodes[0];
6436 fi = btrfs_item_ptr(leaf, path->slots[0],
6437 struct btrfs_file_extent_item);
6439 if (btrfs_file_extent_compression(leaf, fi) &&
6440 dback->disk_bytenr != entry->bytenr) {
6441 fprintf(stderr, "Ref doesn't match the record start and is "
6442 "compressed, please take a btrfs-image of this file "
6443 "system and send it to a btrfs developer so they can "
6444 "complete this functionality for bytenr %Lu\n",
6445 dback->disk_bytenr);
6450 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6451 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6452 } else if (dback->disk_bytenr > entry->bytenr) {
6453 u64 off_diff, offset;
6455 off_diff = dback->disk_bytenr - entry->bytenr;
6456 offset = btrfs_file_extent_offset(leaf, fi);
6457 if (dback->disk_bytenr + offset +
6458 btrfs_file_extent_num_bytes(leaf, fi) >
6459 entry->bytenr + entry->bytes) {
6460 fprintf(stderr, "Ref is past the entry end, please "
6461 "take a btrfs-image of this file system and "
6462 "send it to a btrfs developer, ref %Lu\n",
6463 dback->disk_bytenr);
6468 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6469 btrfs_set_file_extent_offset(leaf, fi, offset);
6470 } else if (dback->disk_bytenr < entry->bytenr) {
6473 offset = btrfs_file_extent_offset(leaf, fi);
6474 if (dback->disk_bytenr + offset < entry->bytenr) {
6475 fprintf(stderr, "Ref is before the entry start, please"
6476 " take a btrfs-image of this file system and "
6477 "send it to a btrfs developer, ref %Lu\n",
6478 dback->disk_bytenr);
6483 offset += dback->disk_bytenr;
6484 offset -= entry->bytenr;
6485 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6486 btrfs_set_file_extent_offset(leaf, fi, offset);
6489 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6492 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6493 * only do this if we aren't using compression, otherwise it's a
6496 if (!btrfs_file_extent_compression(leaf, fi))
6497 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6499 printf("ram bytes may be wrong?\n");
6500 btrfs_mark_buffer_dirty(leaf);
6502 err = btrfs_commit_transaction(trans, root);
6503 btrfs_release_path(path);
6504 return ret ? ret : err;
6507 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6508 struct extent_record *rec)
6510 struct extent_backref *back;
6511 struct data_backref *dback;
6512 struct extent_entry *entry, *best = NULL;
6515 int broken_entries = 0;
6520 * Metadata is easy and the backrefs should always agree on bytenr and
6521 * size, if not we've got bigger issues.
6526 list_for_each_entry(back, &rec->backrefs, list) {
6527 if (back->full_backref || !back->is_data)
6530 dback = (struct data_backref *)back;
6533 * We only pay attention to backrefs that we found a real
6536 if (dback->found_ref == 0)
6540 * For now we only catch when the bytes don't match, not the
6541 * bytenr. We can easily do this at the same time, but I want
6542 * to have a fs image to test on before we just add repair
6543 * functionality willy-nilly so we know we won't screw up the
6547 entry = find_entry(&entries, dback->disk_bytenr,
6550 entry = malloc(sizeof(struct extent_entry));
6555 memset(entry, 0, sizeof(*entry));
6556 entry->bytenr = dback->disk_bytenr;
6557 entry->bytes = dback->bytes;
6558 list_add_tail(&entry->list, &entries);
6563 * If we only have on entry we may think the entries agree when
6564 * in reality they don't so we have to do some extra checking.
6566 if (dback->disk_bytenr != rec->start ||
6567 dback->bytes != rec->nr || back->broken)
6578 /* Yay all the backrefs agree, carry on good sir */
6579 if (nr_entries <= 1 && !mismatch)
6582 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6583 "%Lu\n", rec->start);
6586 * First we want to see if the backrefs can agree amongst themselves who
6587 * is right, so figure out which one of the entries has the highest
6590 best = find_most_right_entry(&entries);
6593 * Ok so we may have an even split between what the backrefs think, so
6594 * this is where we use the extent ref to see what it thinks.
6597 entry = find_entry(&entries, rec->start, rec->nr);
6598 if (!entry && (!broken_entries || !rec->found_rec)) {
6599 fprintf(stderr, "Backrefs don't agree with each other "
6600 "and extent record doesn't agree with anybody,"
6601 " so we can't fix bytenr %Lu bytes %Lu\n",
6602 rec->start, rec->nr);
6605 } else if (!entry) {
6607 * Ok our backrefs were broken, we'll assume this is the
6608 * correct value and add an entry for this range.
6610 entry = malloc(sizeof(struct extent_entry));
6615 memset(entry, 0, sizeof(*entry));
6616 entry->bytenr = rec->start;
6617 entry->bytes = rec->nr;
6618 list_add_tail(&entry->list, &entries);
6622 best = find_most_right_entry(&entries);
6624 fprintf(stderr, "Backrefs and extent record evenly "
6625 "split on who is right, this is going to "
6626 "require user input to fix bytenr %Lu bytes "
6627 "%Lu\n", rec->start, rec->nr);
6634 * I don't think this can happen currently as we'll abort() if we catch
6635 * this case higher up, but in case somebody removes that we still can't
6636 * deal with it properly here yet, so just bail out of that's the case.
6638 if (best->bytenr != rec->start) {
6639 fprintf(stderr, "Extent start and backref starts don't match, "
6640 "please use btrfs-image on this file system and send "
6641 "it to a btrfs developer so they can make fsck fix "
6642 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6643 rec->start, rec->nr);
6649 * Ok great we all agreed on an extent record, let's go find the real
6650 * references and fix up the ones that don't match.
6652 list_for_each_entry(back, &rec->backrefs, list) {
6653 if (back->full_backref || !back->is_data)
6656 dback = (struct data_backref *)back;
6659 * Still ignoring backrefs that don't have a real ref attached
6662 if (dback->found_ref == 0)
6665 if (dback->bytes == best->bytes &&
6666 dback->disk_bytenr == best->bytenr)
6669 ret = repair_ref(info, path, dback, best);
6675 * Ok we messed with the actual refs, which means we need to drop our
6676 * entire cache and go back and rescan. I know this is a huge pain and
6677 * adds a lot of extra work, but it's the only way to be safe. Once all
6678 * the backrefs agree we may not need to do anything to the extent
6683 while (!list_empty(&entries)) {
6684 entry = list_entry(entries.next, struct extent_entry, list);
6685 list_del_init(&entry->list);
6691 static int process_duplicates(struct btrfs_root *root,
6692 struct cache_tree *extent_cache,
6693 struct extent_record *rec)
6695 struct extent_record *good, *tmp;
6696 struct cache_extent *cache;
6700 * If we found a extent record for this extent then return, or if we
6701 * have more than one duplicate we are likely going to need to delete
6704 if (rec->found_rec || rec->num_duplicates > 1)
6707 /* Shouldn't happen but just in case */
6708 BUG_ON(!rec->num_duplicates);
6711 * So this happens if we end up with a backref that doesn't match the
6712 * actual extent entry. So either the backref is bad or the extent
6713 * entry is bad. Either way we want to have the extent_record actually
6714 * reflect what we found in the extent_tree, so we need to take the
6715 * duplicate out and use that as the extent_record since the only way we
6716 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6718 remove_cache_extent(extent_cache, &rec->cache);
6720 good = list_entry(rec->dups.next, struct extent_record, list);
6721 list_del_init(&good->list);
6722 INIT_LIST_HEAD(&good->backrefs);
6723 INIT_LIST_HEAD(&good->dups);
6724 good->cache.start = good->start;
6725 good->cache.size = good->nr;
6726 good->content_checked = 0;
6727 good->owner_ref_checked = 0;
6728 good->num_duplicates = 0;
6729 good->refs = rec->refs;
6730 list_splice_init(&rec->backrefs, &good->backrefs);
6732 cache = lookup_cache_extent(extent_cache, good->start,
6736 tmp = container_of(cache, struct extent_record, cache);
6739 * If we find another overlapping extent and it's found_rec is
6740 * set then it's a duplicate and we need to try and delete
6743 if (tmp->found_rec || tmp->num_duplicates > 0) {
6744 if (list_empty(&good->list))
6745 list_add_tail(&good->list,
6746 &duplicate_extents);
6747 good->num_duplicates += tmp->num_duplicates + 1;
6748 list_splice_init(&tmp->dups, &good->dups);
6749 list_del_init(&tmp->list);
6750 list_add_tail(&tmp->list, &good->dups);
6751 remove_cache_extent(extent_cache, &tmp->cache);
6756 * Ok we have another non extent item backed extent rec, so lets
6757 * just add it to this extent and carry on like we did above.
6759 good->refs += tmp->refs;
6760 list_splice_init(&tmp->backrefs, &good->backrefs);
6761 remove_cache_extent(extent_cache, &tmp->cache);
6764 ret = insert_cache_extent(extent_cache, &good->cache);
6767 return good->num_duplicates ? 0 : 1;
6770 static int delete_duplicate_records(struct btrfs_root *root,
6771 struct extent_record *rec)
6773 struct btrfs_trans_handle *trans;
6774 LIST_HEAD(delete_list);
6775 struct btrfs_path *path;
6776 struct extent_record *tmp, *good, *n;
6779 struct btrfs_key key;
6781 path = btrfs_alloc_path();
6788 /* Find the record that covers all of the duplicates. */
6789 list_for_each_entry(tmp, &rec->dups, list) {
6790 if (good->start < tmp->start)
6792 if (good->nr > tmp->nr)
6795 if (tmp->start + tmp->nr < good->start + good->nr) {
6796 fprintf(stderr, "Ok we have overlapping extents that "
6797 "aren't completely covered by eachother, this "
6798 "is going to require more careful thought. "
6799 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6800 tmp->start, tmp->nr, good->start, good->nr);
6807 list_add_tail(&rec->list, &delete_list);
6809 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6812 list_move_tail(&tmp->list, &delete_list);
6815 root = root->fs_info->extent_root;
6816 trans = btrfs_start_transaction(root, 1);
6817 if (IS_ERR(trans)) {
6818 ret = PTR_ERR(trans);
6822 list_for_each_entry(tmp, &delete_list, list) {
6823 if (tmp->found_rec == 0)
6825 key.objectid = tmp->start;
6826 key.type = BTRFS_EXTENT_ITEM_KEY;
6827 key.offset = tmp->nr;
6829 /* Shouldn't happen but just in case */
6830 if (tmp->metadata) {
6831 fprintf(stderr, "Well this shouldn't happen, extent "
6832 "record overlaps but is metadata? "
6833 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6837 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6843 ret = btrfs_del_item(trans, root, path);
6846 btrfs_release_path(path);
6849 err = btrfs_commit_transaction(trans, root);
6853 while (!list_empty(&delete_list)) {
6854 tmp = list_entry(delete_list.next, struct extent_record, list);
6855 list_del_init(&tmp->list);
6861 while (!list_empty(&rec->dups)) {
6862 tmp = list_entry(rec->dups.next, struct extent_record, list);
6863 list_del_init(&tmp->list);
6867 btrfs_free_path(path);
6869 if (!ret && !nr_del)
6870 rec->num_duplicates = 0;
6872 return ret ? ret : nr_del;
6875 static int find_possible_backrefs(struct btrfs_fs_info *info,
6876 struct btrfs_path *path,
6877 struct cache_tree *extent_cache,
6878 struct extent_record *rec)
6880 struct btrfs_root *root;
6881 struct extent_backref *back;
6882 struct data_backref *dback;
6883 struct cache_extent *cache;
6884 struct btrfs_file_extent_item *fi;
6885 struct btrfs_key key;
6889 list_for_each_entry(back, &rec->backrefs, list) {
6890 /* Don't care about full backrefs (poor unloved backrefs) */
6891 if (back->full_backref || !back->is_data)
6894 dback = (struct data_backref *)back;
6896 /* We found this one, we don't need to do a lookup */
6897 if (dback->found_ref)
6900 key.objectid = dback->root;
6901 key.type = BTRFS_ROOT_ITEM_KEY;
6902 key.offset = (u64)-1;
6904 root = btrfs_read_fs_root(info, &key);
6906 /* No root, definitely a bad ref, skip */
6907 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6909 /* Other err, exit */
6911 return PTR_ERR(root);
6913 key.objectid = dback->owner;
6914 key.type = BTRFS_EXTENT_DATA_KEY;
6915 key.offset = dback->offset;
6916 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6918 btrfs_release_path(path);
6921 /* Didn't find it, we can carry on */
6926 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6927 struct btrfs_file_extent_item);
6928 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6929 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6930 btrfs_release_path(path);
6931 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6933 struct extent_record *tmp;
6934 tmp = container_of(cache, struct extent_record, cache);
6937 * If we found an extent record for the bytenr for this
6938 * particular backref then we can't add it to our
6939 * current extent record. We only want to add backrefs
6940 * that don't have a corresponding extent item in the
6941 * extent tree since they likely belong to this record
6942 * and we need to fix it if it doesn't match bytenrs.
6948 dback->found_ref += 1;
6949 dback->disk_bytenr = bytenr;
6950 dback->bytes = bytes;
6953 * Set this so the verify backref code knows not to trust the
6954 * values in this backref.
6963 * Record orphan data ref into corresponding root.
6965 * Return 0 if the extent item contains data ref and recorded.
6966 * Return 1 if the extent item contains no useful data ref
6967 * On that case, it may contains only shared_dataref or metadata backref
6968 * or the file extent exists(this should be handled by the extent bytenr
6970 * Return <0 if something goes wrong.
6972 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6973 struct extent_record *rec)
6975 struct btrfs_key key;
6976 struct btrfs_root *dest_root;
6977 struct extent_backref *back;
6978 struct data_backref *dback;
6979 struct orphan_data_extent *orphan;
6980 struct btrfs_path *path;
6981 int recorded_data_ref = 0;
6986 path = btrfs_alloc_path();
6989 list_for_each_entry(back, &rec->backrefs, list) {
6990 if (back->full_backref || !back->is_data ||
6991 !back->found_extent_tree)
6993 dback = (struct data_backref *)back;
6994 if (dback->found_ref)
6996 key.objectid = dback->root;
6997 key.type = BTRFS_ROOT_ITEM_KEY;
6998 key.offset = (u64)-1;
7000 dest_root = btrfs_read_fs_root(fs_info, &key);
7002 /* For non-exist root we just skip it */
7003 if (IS_ERR(dest_root) || !dest_root)
7006 key.objectid = dback->owner;
7007 key.type = BTRFS_EXTENT_DATA_KEY;
7008 key.offset = dback->offset;
7010 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7012 * For ret < 0, it's OK since the fs-tree may be corrupted,
7013 * we need to record it for inode/file extent rebuild.
7014 * For ret > 0, we record it only for file extent rebuild.
7015 * For ret == 0, the file extent exists but only bytenr
7016 * mismatch, let the original bytenr fix routine to handle,
7022 orphan = malloc(sizeof(*orphan));
7027 INIT_LIST_HEAD(&orphan->list);
7028 orphan->root = dback->root;
7029 orphan->objectid = dback->owner;
7030 orphan->offset = dback->offset;
7031 orphan->disk_bytenr = rec->cache.start;
7032 orphan->disk_len = rec->cache.size;
7033 list_add(&dest_root->orphan_data_extents, &orphan->list);
7034 recorded_data_ref = 1;
7037 btrfs_free_path(path);
7039 return !recorded_data_ref;
7045 * when an incorrect extent item is found, this will delete
7046 * all of the existing entries for it and recreate them
7047 * based on what the tree scan found.
7049 static int fixup_extent_refs(struct btrfs_fs_info *info,
7050 struct cache_tree *extent_cache,
7051 struct extent_record *rec)
7053 struct btrfs_trans_handle *trans = NULL;
7055 struct btrfs_path *path;
7056 struct list_head *cur = rec->backrefs.next;
7057 struct cache_extent *cache;
7058 struct extent_backref *back;
7062 if (rec->flag_block_full_backref)
7063 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7065 path = btrfs_alloc_path();
7069 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7071 * Sometimes the backrefs themselves are so broken they don't
7072 * get attached to any meaningful rec, so first go back and
7073 * check any of our backrefs that we couldn't find and throw
7074 * them into the list if we find the backref so that
7075 * verify_backrefs can figure out what to do.
7077 ret = find_possible_backrefs(info, path, extent_cache, rec);
7082 /* step one, make sure all of the backrefs agree */
7083 ret = verify_backrefs(info, path, rec);
7087 trans = btrfs_start_transaction(info->extent_root, 1);
7088 if (IS_ERR(trans)) {
7089 ret = PTR_ERR(trans);
7093 /* step two, delete all the existing records */
7094 ret = delete_extent_records(trans, info->extent_root, path,
7095 rec->start, rec->max_size);
7100 /* was this block corrupt? If so, don't add references to it */
7101 cache = lookup_cache_extent(info->corrupt_blocks,
7102 rec->start, rec->max_size);
7108 /* step three, recreate all the refs we did find */
7109 while(cur != &rec->backrefs) {
7110 back = list_entry(cur, struct extent_backref, list);
7114 * if we didn't find any references, don't create a
7117 if (!back->found_ref)
7120 rec->bad_full_backref = 0;
7121 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7129 int err = btrfs_commit_transaction(trans, info->extent_root);
7134 btrfs_free_path(path);
7138 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7139 struct extent_record *rec)
7141 struct btrfs_trans_handle *trans;
7142 struct btrfs_root *root = fs_info->extent_root;
7143 struct btrfs_path *path;
7144 struct btrfs_extent_item *ei;
7145 struct btrfs_key key;
7149 key.objectid = rec->start;
7150 if (rec->metadata) {
7151 key.type = BTRFS_METADATA_ITEM_KEY;
7152 key.offset = rec->info_level;
7154 key.type = BTRFS_EXTENT_ITEM_KEY;
7155 key.offset = rec->max_size;
7158 path = btrfs_alloc_path();
7162 trans = btrfs_start_transaction(root, 0);
7163 if (IS_ERR(trans)) {
7164 btrfs_free_path(path);
7165 return PTR_ERR(trans);
7168 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7170 btrfs_free_path(path);
7171 btrfs_commit_transaction(trans, root);
7174 fprintf(stderr, "Didn't find extent for %llu\n",
7175 (unsigned long long)rec->start);
7176 btrfs_free_path(path);
7177 btrfs_commit_transaction(trans, root);
7181 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7182 struct btrfs_extent_item);
7183 flags = btrfs_extent_flags(path->nodes[0], ei);
7184 if (rec->flag_block_full_backref) {
7185 fprintf(stderr, "setting full backref on %llu\n",
7186 (unsigned long long)key.objectid);
7187 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7189 fprintf(stderr, "clearing full backref on %llu\n",
7190 (unsigned long long)key.objectid);
7191 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7193 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7194 btrfs_mark_buffer_dirty(path->nodes[0]);
7195 btrfs_free_path(path);
7196 return btrfs_commit_transaction(trans, root);
7199 /* right now we only prune from the extent allocation tree */
7200 static int prune_one_block(struct btrfs_trans_handle *trans,
7201 struct btrfs_fs_info *info,
7202 struct btrfs_corrupt_block *corrupt)
7205 struct btrfs_path path;
7206 struct extent_buffer *eb;
7210 int level = corrupt->level + 1;
7212 btrfs_init_path(&path);
7214 /* we want to stop at the parent to our busted block */
7215 path.lowest_level = level;
7217 ret = btrfs_search_slot(trans, info->extent_root,
7218 &corrupt->key, &path, -1, 1);
7223 eb = path.nodes[level];
7230 * hopefully the search gave us the block we want to prune,
7231 * lets try that first
7233 slot = path.slots[level];
7234 found = btrfs_node_blockptr(eb, slot);
7235 if (found == corrupt->cache.start)
7238 nritems = btrfs_header_nritems(eb);
7240 /* the search failed, lets scan this node and hope we find it */
7241 for (slot = 0; slot < nritems; slot++) {
7242 found = btrfs_node_blockptr(eb, slot);
7243 if (found == corrupt->cache.start)
7247 * we couldn't find the bad block. TODO, search all the nodes for pointers
7250 if (eb == info->extent_root->node) {
7255 btrfs_release_path(&path);
7260 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7261 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7264 btrfs_release_path(&path);
7268 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7270 struct btrfs_trans_handle *trans = NULL;
7271 struct cache_extent *cache;
7272 struct btrfs_corrupt_block *corrupt;
7275 cache = search_cache_extent(info->corrupt_blocks, 0);
7279 trans = btrfs_start_transaction(info->extent_root, 1);
7281 return PTR_ERR(trans);
7283 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7284 prune_one_block(trans, info, corrupt);
7285 remove_cache_extent(info->corrupt_blocks, cache);
7288 return btrfs_commit_transaction(trans, info->extent_root);
7292 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7294 struct btrfs_block_group_cache *cache;
7299 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7300 &start, &end, EXTENT_DIRTY);
7303 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7309 cache = btrfs_lookup_first_block_group(fs_info, start);
7314 start = cache->key.objectid + cache->key.offset;
7318 static int check_extent_refs(struct btrfs_root *root,
7319 struct cache_tree *extent_cache)
7321 struct extent_record *rec;
7322 struct cache_extent *cache;
7331 * if we're doing a repair, we have to make sure
7332 * we don't allocate from the problem extents.
7333 * In the worst case, this will be all the
7336 cache = search_cache_extent(extent_cache, 0);
7338 rec = container_of(cache, struct extent_record, cache);
7339 set_extent_dirty(root->fs_info->excluded_extents,
7341 rec->start + rec->max_size - 1,
7343 cache = next_cache_extent(cache);
7346 /* pin down all the corrupted blocks too */
7347 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7349 set_extent_dirty(root->fs_info->excluded_extents,
7351 cache->start + cache->size - 1,
7353 cache = next_cache_extent(cache);
7355 prune_corrupt_blocks(root->fs_info);
7356 reset_cached_block_groups(root->fs_info);
7359 reset_cached_block_groups(root->fs_info);
7362 * We need to delete any duplicate entries we find first otherwise we
7363 * could mess up the extent tree when we have backrefs that actually
7364 * belong to a different extent item and not the weird duplicate one.
7366 while (repair && !list_empty(&duplicate_extents)) {
7367 rec = list_entry(duplicate_extents.next, struct extent_record,
7369 list_del_init(&rec->list);
7371 /* Sometimes we can find a backref before we find an actual
7372 * extent, so we need to process it a little bit to see if there
7373 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7374 * if this is a backref screwup. If we need to delete stuff
7375 * process_duplicates() will return 0, otherwise it will return
7378 if (process_duplicates(root, extent_cache, rec))
7380 ret = delete_duplicate_records(root, rec);
7384 * delete_duplicate_records will return the number of entries
7385 * deleted, so if it's greater than 0 then we know we actually
7386 * did something and we need to remove.
7400 cache = search_cache_extent(extent_cache, 0);
7403 rec = container_of(cache, struct extent_record, cache);
7404 if (rec->num_duplicates) {
7405 fprintf(stderr, "extent item %llu has multiple extent "
7406 "items\n", (unsigned long long)rec->start);
7411 if (rec->refs != rec->extent_item_refs) {
7412 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7413 (unsigned long long)rec->start,
7414 (unsigned long long)rec->nr);
7415 fprintf(stderr, "extent item %llu, found %llu\n",
7416 (unsigned long long)rec->extent_item_refs,
7417 (unsigned long long)rec->refs);
7418 ret = record_orphan_data_extents(root->fs_info, rec);
7425 * we can't use the extent to repair file
7426 * extent, let the fallback method handle it.
7428 if (!fixed && repair) {
7429 ret = fixup_extent_refs(
7440 if (all_backpointers_checked(rec, 1)) {
7441 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7442 (unsigned long long)rec->start,
7443 (unsigned long long)rec->nr);
7445 if (!fixed && !recorded && repair) {
7446 ret = fixup_extent_refs(root->fs_info,
7455 if (!rec->owner_ref_checked) {
7456 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7457 (unsigned long long)rec->start,
7458 (unsigned long long)rec->nr);
7459 if (!fixed && !recorded && repair) {
7460 ret = fixup_extent_refs(root->fs_info,
7469 if (rec->bad_full_backref) {
7470 fprintf(stderr, "bad full backref, on [%llu]\n",
7471 (unsigned long long)rec->start);
7473 ret = fixup_extent_flags(root->fs_info, rec);
7482 remove_cache_extent(extent_cache, cache);
7483 free_all_extent_backrefs(rec);
7484 if (!init_extent_tree && repair && (!cur_err || fixed))
7485 clear_extent_dirty(root->fs_info->excluded_extents,
7487 rec->start + rec->max_size - 1,
7493 if (ret && ret != -EAGAIN) {
7494 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7497 struct btrfs_trans_handle *trans;
7499 root = root->fs_info->extent_root;
7500 trans = btrfs_start_transaction(root, 1);
7501 if (IS_ERR(trans)) {
7502 ret = PTR_ERR(trans);
7506 btrfs_fix_block_accounting(trans, root);
7507 ret = btrfs_commit_transaction(trans, root);
7512 fprintf(stderr, "repaired damaged extent references\n");
7518 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7522 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7523 stripe_size = length;
7524 stripe_size /= num_stripes;
7525 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7526 stripe_size = length * 2;
7527 stripe_size /= num_stripes;
7528 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7529 stripe_size = length;
7530 stripe_size /= (num_stripes - 1);
7531 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7532 stripe_size = length;
7533 stripe_size /= (num_stripes - 2);
7535 stripe_size = length;
7541 * Check the chunk with its block group/dev list ref:
7542 * Return 0 if all refs seems valid.
7543 * Return 1 if part of refs seems valid, need later check for rebuild ref
7544 * like missing block group and needs to search extent tree to rebuild them.
7545 * Return -1 if essential refs are missing and unable to rebuild.
7547 static int check_chunk_refs(struct chunk_record *chunk_rec,
7548 struct block_group_tree *block_group_cache,
7549 struct device_extent_tree *dev_extent_cache,
7552 struct cache_extent *block_group_item;
7553 struct block_group_record *block_group_rec;
7554 struct cache_extent *dev_extent_item;
7555 struct device_extent_record *dev_extent_rec;
7559 int metadump_v2 = 0;
7563 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7566 if (block_group_item) {
7567 block_group_rec = container_of(block_group_item,
7568 struct block_group_record,
7570 if (chunk_rec->length != block_group_rec->offset ||
7571 chunk_rec->offset != block_group_rec->objectid ||
7573 chunk_rec->type_flags != block_group_rec->flags)) {
7576 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7577 chunk_rec->objectid,
7582 chunk_rec->type_flags,
7583 block_group_rec->objectid,
7584 block_group_rec->type,
7585 block_group_rec->offset,
7586 block_group_rec->offset,
7587 block_group_rec->objectid,
7588 block_group_rec->flags);
7591 list_del_init(&block_group_rec->list);
7592 chunk_rec->bg_rec = block_group_rec;
7597 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7598 chunk_rec->objectid,
7603 chunk_rec->type_flags);
7610 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7611 chunk_rec->num_stripes);
7612 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7613 devid = chunk_rec->stripes[i].devid;
7614 offset = chunk_rec->stripes[i].offset;
7615 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7616 devid, offset, length);
7617 if (dev_extent_item) {
7618 dev_extent_rec = container_of(dev_extent_item,
7619 struct device_extent_record,
7621 if (dev_extent_rec->objectid != devid ||
7622 dev_extent_rec->offset != offset ||
7623 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7624 dev_extent_rec->length != length) {
7627 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7628 chunk_rec->objectid,
7631 chunk_rec->stripes[i].devid,
7632 chunk_rec->stripes[i].offset,
7633 dev_extent_rec->objectid,
7634 dev_extent_rec->offset,
7635 dev_extent_rec->length);
7638 list_move(&dev_extent_rec->chunk_list,
7639 &chunk_rec->dextents);
7644 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7645 chunk_rec->objectid,
7648 chunk_rec->stripes[i].devid,
7649 chunk_rec->stripes[i].offset);
7656 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7657 int check_chunks(struct cache_tree *chunk_cache,
7658 struct block_group_tree *block_group_cache,
7659 struct device_extent_tree *dev_extent_cache,
7660 struct list_head *good, struct list_head *bad,
7661 struct list_head *rebuild, int silent)
7663 struct cache_extent *chunk_item;
7664 struct chunk_record *chunk_rec;
7665 struct block_group_record *bg_rec;
7666 struct device_extent_record *dext_rec;
7670 chunk_item = first_cache_extent(chunk_cache);
7671 while (chunk_item) {
7672 chunk_rec = container_of(chunk_item, struct chunk_record,
7674 err = check_chunk_refs(chunk_rec, block_group_cache,
7675 dev_extent_cache, silent);
7678 if (err == 0 && good)
7679 list_add_tail(&chunk_rec->list, good);
7680 if (err > 0 && rebuild)
7681 list_add_tail(&chunk_rec->list, rebuild);
7683 list_add_tail(&chunk_rec->list, bad);
7684 chunk_item = next_cache_extent(chunk_item);
7687 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7690 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7698 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7702 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7713 static int check_device_used(struct device_record *dev_rec,
7714 struct device_extent_tree *dext_cache)
7716 struct cache_extent *cache;
7717 struct device_extent_record *dev_extent_rec;
7720 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7722 dev_extent_rec = container_of(cache,
7723 struct device_extent_record,
7725 if (dev_extent_rec->objectid != dev_rec->devid)
7728 list_del_init(&dev_extent_rec->device_list);
7729 total_byte += dev_extent_rec->length;
7730 cache = next_cache_extent(cache);
7733 if (total_byte != dev_rec->byte_used) {
7735 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7736 total_byte, dev_rec->byte_used, dev_rec->objectid,
7737 dev_rec->type, dev_rec->offset);
7744 /* check btrfs_dev_item -> btrfs_dev_extent */
7745 static int check_devices(struct rb_root *dev_cache,
7746 struct device_extent_tree *dev_extent_cache)
7748 struct rb_node *dev_node;
7749 struct device_record *dev_rec;
7750 struct device_extent_record *dext_rec;
7754 dev_node = rb_first(dev_cache);
7756 dev_rec = container_of(dev_node, struct device_record, node);
7757 err = check_device_used(dev_rec, dev_extent_cache);
7761 dev_node = rb_next(dev_node);
7763 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7766 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7767 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7774 static int add_root_item_to_list(struct list_head *head,
7775 u64 objectid, u64 bytenr, u64 last_snapshot,
7776 u8 level, u8 drop_level,
7777 int level_size, struct btrfs_key *drop_key)
7780 struct root_item_record *ri_rec;
7781 ri_rec = malloc(sizeof(*ri_rec));
7784 ri_rec->bytenr = bytenr;
7785 ri_rec->objectid = objectid;
7786 ri_rec->level = level;
7787 ri_rec->level_size = level_size;
7788 ri_rec->drop_level = drop_level;
7789 ri_rec->last_snapshot = last_snapshot;
7791 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7792 list_add_tail(&ri_rec->list, head);
7797 static void free_root_item_list(struct list_head *list)
7799 struct root_item_record *ri_rec;
7801 while (!list_empty(list)) {
7802 ri_rec = list_first_entry(list, struct root_item_record,
7804 list_del_init(&ri_rec->list);
7809 static int deal_root_from_list(struct list_head *list,
7810 struct btrfs_root *root,
7811 struct block_info *bits,
7813 struct cache_tree *pending,
7814 struct cache_tree *seen,
7815 struct cache_tree *reada,
7816 struct cache_tree *nodes,
7817 struct cache_tree *extent_cache,
7818 struct cache_tree *chunk_cache,
7819 struct rb_root *dev_cache,
7820 struct block_group_tree *block_group_cache,
7821 struct device_extent_tree *dev_extent_cache)
7826 while (!list_empty(list)) {
7827 struct root_item_record *rec;
7828 struct extent_buffer *buf;
7829 rec = list_entry(list->next,
7830 struct root_item_record, list);
7832 buf = read_tree_block(root->fs_info->tree_root,
7833 rec->bytenr, rec->level_size, 0);
7834 if (!extent_buffer_uptodate(buf)) {
7835 free_extent_buffer(buf);
7839 add_root_to_pending(buf, extent_cache, pending,
7840 seen, nodes, rec->objectid);
7842 * To rebuild extent tree, we need deal with snapshot
7843 * one by one, otherwise we deal with node firstly which
7844 * can maximize readahead.
7847 ret = run_next_block(root, bits, bits_nr, &last,
7848 pending, seen, reada, nodes,
7849 extent_cache, chunk_cache,
7850 dev_cache, block_group_cache,
7851 dev_extent_cache, rec);
7855 free_extent_buffer(buf);
7856 list_del(&rec->list);
7862 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7863 reada, nodes, extent_cache, chunk_cache,
7864 dev_cache, block_group_cache,
7865 dev_extent_cache, NULL);
7875 static int check_chunks_and_extents(struct btrfs_root *root)
7877 struct rb_root dev_cache;
7878 struct cache_tree chunk_cache;
7879 struct block_group_tree block_group_cache;
7880 struct device_extent_tree dev_extent_cache;
7881 struct cache_tree extent_cache;
7882 struct cache_tree seen;
7883 struct cache_tree pending;
7884 struct cache_tree reada;
7885 struct cache_tree nodes;
7886 struct extent_io_tree excluded_extents;
7887 struct cache_tree corrupt_blocks;
7888 struct btrfs_path path;
7889 struct btrfs_key key;
7890 struct btrfs_key found_key;
7892 struct block_info *bits;
7894 struct extent_buffer *leaf;
7896 struct btrfs_root_item ri;
7897 struct list_head dropping_trees;
7898 struct list_head normal_trees;
7899 struct btrfs_root *root1;
7904 dev_cache = RB_ROOT;
7905 cache_tree_init(&chunk_cache);
7906 block_group_tree_init(&block_group_cache);
7907 device_extent_tree_init(&dev_extent_cache);
7909 cache_tree_init(&extent_cache);
7910 cache_tree_init(&seen);
7911 cache_tree_init(&pending);
7912 cache_tree_init(&nodes);
7913 cache_tree_init(&reada);
7914 cache_tree_init(&corrupt_blocks);
7915 extent_io_tree_init(&excluded_extents);
7916 INIT_LIST_HEAD(&dropping_trees);
7917 INIT_LIST_HEAD(&normal_trees);
7920 root->fs_info->excluded_extents = &excluded_extents;
7921 root->fs_info->fsck_extent_cache = &extent_cache;
7922 root->fs_info->free_extent_hook = free_extent_hook;
7923 root->fs_info->corrupt_blocks = &corrupt_blocks;
7927 bits = malloc(bits_nr * sizeof(struct block_info));
7934 root1 = root->fs_info->tree_root;
7935 level = btrfs_header_level(root1->node);
7936 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7937 root1->node->start, 0, level, 0,
7938 btrfs_level_size(root1, level), NULL);
7941 root1 = root->fs_info->chunk_root;
7942 level = btrfs_header_level(root1->node);
7943 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7944 root1->node->start, 0, level, 0,
7945 btrfs_level_size(root1, level), NULL);
7948 btrfs_init_path(&path);
7951 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7952 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7957 leaf = path.nodes[0];
7958 slot = path.slots[0];
7959 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7960 ret = btrfs_next_leaf(root, &path);
7963 leaf = path.nodes[0];
7964 slot = path.slots[0];
7966 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7967 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7968 unsigned long offset;
7971 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7972 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7973 last_snapshot = btrfs_root_last_snapshot(&ri);
7974 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7975 level = btrfs_root_level(&ri);
7976 level_size = btrfs_level_size(root, level);
7977 ret = add_root_item_to_list(&normal_trees,
7979 btrfs_root_bytenr(&ri),
7980 last_snapshot, level,
7981 0, level_size, NULL);
7985 level = btrfs_root_level(&ri);
7986 level_size = btrfs_level_size(root, level);
7987 objectid = found_key.objectid;
7988 btrfs_disk_key_to_cpu(&found_key,
7990 ret = add_root_item_to_list(&dropping_trees,
7992 btrfs_root_bytenr(&ri),
7993 last_snapshot, level,
7995 level_size, &found_key);
8002 btrfs_release_path(&path);
8005 * check_block can return -EAGAIN if it fixes something, please keep
8006 * this in mind when dealing with return values from these functions, if
8007 * we get -EAGAIN we want to fall through and restart the loop.
8009 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8010 &seen, &reada, &nodes, &extent_cache,
8011 &chunk_cache, &dev_cache, &block_group_cache,
8018 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8019 &pending, &seen, &reada, &nodes,
8020 &extent_cache, &chunk_cache, &dev_cache,
8021 &block_group_cache, &dev_extent_cache);
8028 err = check_chunks(&chunk_cache, &block_group_cache,
8029 &dev_extent_cache, NULL, NULL, NULL, 0);
8037 ret = check_extent_refs(root, &extent_cache);
8044 err = check_devices(&dev_cache, &dev_extent_cache);
8050 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8051 extent_io_tree_cleanup(&excluded_extents);
8052 root->fs_info->fsck_extent_cache = NULL;
8053 root->fs_info->free_extent_hook = NULL;
8054 root->fs_info->corrupt_blocks = NULL;
8055 root->fs_info->excluded_extents = NULL;
8058 free_chunk_cache_tree(&chunk_cache);
8059 free_device_cache_tree(&dev_cache);
8060 free_block_group_tree(&block_group_cache);
8061 free_device_extent_tree(&dev_extent_cache);
8062 free_extent_cache_tree(&seen);
8063 free_extent_cache_tree(&pending);
8064 free_extent_cache_tree(&reada);
8065 free_extent_cache_tree(&nodes);
8068 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8069 free_extent_cache_tree(&seen);
8070 free_extent_cache_tree(&pending);
8071 free_extent_cache_tree(&reada);
8072 free_extent_cache_tree(&nodes);
8073 free_chunk_cache_tree(&chunk_cache);
8074 free_block_group_tree(&block_group_cache);
8075 free_device_cache_tree(&dev_cache);
8076 free_device_extent_tree(&dev_extent_cache);
8077 free_extent_record_cache(root->fs_info, &extent_cache);
8078 free_root_item_list(&normal_trees);
8079 free_root_item_list(&dropping_trees);
8080 extent_io_tree_cleanup(&excluded_extents);
8084 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8085 struct btrfs_root *root, int overwrite)
8087 struct extent_buffer *c;
8088 struct extent_buffer *old = root->node;
8091 struct btrfs_disk_key disk_key = {0,0,0};
8097 extent_buffer_get(c);
8100 c = btrfs_alloc_free_block(trans, root,
8101 btrfs_level_size(root, 0),
8102 root->root_key.objectid,
8103 &disk_key, level, 0, 0);
8106 extent_buffer_get(c);
8110 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8111 btrfs_set_header_level(c, level);
8112 btrfs_set_header_bytenr(c, c->start);
8113 btrfs_set_header_generation(c, trans->transid);
8114 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8115 btrfs_set_header_owner(c, root->root_key.objectid);
8117 write_extent_buffer(c, root->fs_info->fsid,
8118 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8120 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8121 btrfs_header_chunk_tree_uuid(c),
8124 btrfs_mark_buffer_dirty(c);
8126 * this case can happen in the following case:
8128 * 1.overwrite previous root.
8130 * 2.reinit reloc data root, this is because we skip pin
8131 * down reloc data tree before which means we can allocate
8132 * same block bytenr here.
8134 if (old->start == c->start) {
8135 btrfs_set_root_generation(&root->root_item,
8137 root->root_item.level = btrfs_header_level(root->node);
8138 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8139 &root->root_key, &root->root_item);
8141 free_extent_buffer(c);
8145 free_extent_buffer(old);
8147 add_root_to_dirty_list(root);
8151 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8152 struct extent_buffer *eb, int tree_root)
8154 struct extent_buffer *tmp;
8155 struct btrfs_root_item *ri;
8156 struct btrfs_key key;
8159 int level = btrfs_header_level(eb);
8165 * If we have pinned this block before, don't pin it again.
8166 * This can not only avoid forever loop with broken filesystem
8167 * but also give us some speedups.
8169 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8170 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8173 btrfs_pin_extent(fs_info, eb->start, eb->len);
8175 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8176 nritems = btrfs_header_nritems(eb);
8177 for (i = 0; i < nritems; i++) {
8179 btrfs_item_key_to_cpu(eb, &key, i);
8180 if (key.type != BTRFS_ROOT_ITEM_KEY)
8182 /* Skip the extent root and reloc roots */
8183 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8184 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8185 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8187 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8188 bytenr = btrfs_disk_root_bytenr(eb, ri);
8191 * If at any point we start needing the real root we
8192 * will have to build a stump root for the root we are
8193 * in, but for now this doesn't actually use the root so
8194 * just pass in extent_root.
8196 tmp = read_tree_block(fs_info->extent_root, bytenr,
8198 if (!extent_buffer_uptodate(tmp)) {
8199 fprintf(stderr, "Error reading root block\n");
8202 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8203 free_extent_buffer(tmp);
8207 bytenr = btrfs_node_blockptr(eb, i);
8209 /* If we aren't the tree root don't read the block */
8210 if (level == 1 && !tree_root) {
8211 btrfs_pin_extent(fs_info, bytenr, leafsize);
8215 tmp = read_tree_block(fs_info->extent_root, bytenr,
8217 if (!extent_buffer_uptodate(tmp)) {
8218 fprintf(stderr, "Error reading tree block\n");
8221 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8222 free_extent_buffer(tmp);
8231 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8235 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8239 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8242 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8244 struct btrfs_block_group_cache *cache;
8245 struct btrfs_path *path;
8246 struct extent_buffer *leaf;
8247 struct btrfs_chunk *chunk;
8248 struct btrfs_key key;
8252 path = btrfs_alloc_path();
8257 key.type = BTRFS_CHUNK_ITEM_KEY;
8260 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8262 btrfs_free_path(path);
8267 * We do this in case the block groups were screwed up and had alloc
8268 * bits that aren't actually set on the chunks. This happens with
8269 * restored images every time and could happen in real life I guess.
8271 fs_info->avail_data_alloc_bits = 0;
8272 fs_info->avail_metadata_alloc_bits = 0;
8273 fs_info->avail_system_alloc_bits = 0;
8275 /* First we need to create the in-memory block groups */
8277 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8278 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8280 btrfs_free_path(path);
8288 leaf = path->nodes[0];
8289 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8290 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8295 chunk = btrfs_item_ptr(leaf, path->slots[0],
8296 struct btrfs_chunk);
8297 btrfs_add_block_group(fs_info, 0,
8298 btrfs_chunk_type(leaf, chunk),
8299 key.objectid, key.offset,
8300 btrfs_chunk_length(leaf, chunk));
8301 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8302 key.offset + btrfs_chunk_length(leaf, chunk),
8308 cache = btrfs_lookup_first_block_group(fs_info, start);
8312 start = cache->key.objectid + cache->key.offset;
8315 btrfs_free_path(path);
8319 static int reset_balance(struct btrfs_trans_handle *trans,
8320 struct btrfs_fs_info *fs_info)
8322 struct btrfs_root *root = fs_info->tree_root;
8323 struct btrfs_path *path;
8324 struct extent_buffer *leaf;
8325 struct btrfs_key key;
8326 int del_slot, del_nr = 0;
8330 path = btrfs_alloc_path();
8334 key.objectid = BTRFS_BALANCE_OBJECTID;
8335 key.type = BTRFS_BALANCE_ITEM_KEY;
8338 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8343 goto reinit_data_reloc;
8348 ret = btrfs_del_item(trans, root, path);
8351 btrfs_release_path(path);
8353 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8354 key.type = BTRFS_ROOT_ITEM_KEY;
8357 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8361 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8366 ret = btrfs_del_items(trans, root, path,
8373 btrfs_release_path(path);
8376 ret = btrfs_search_slot(trans, root, &key, path,
8383 leaf = path->nodes[0];
8384 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8385 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8387 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8392 del_slot = path->slots[0];
8401 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8405 btrfs_release_path(path);
8408 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8409 key.type = BTRFS_ROOT_ITEM_KEY;
8410 key.offset = (u64)-1;
8411 root = btrfs_read_fs_root(fs_info, &key);
8413 fprintf(stderr, "Error reading data reloc tree\n");
8414 ret = PTR_ERR(root);
8417 record_root_in_trans(trans, root);
8418 ret = btrfs_fsck_reinit_root(trans, root, 0);
8421 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8423 btrfs_free_path(path);
8427 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8428 struct btrfs_fs_info *fs_info)
8434 * The only reason we don't do this is because right now we're just
8435 * walking the trees we find and pinning down their bytes, we don't look
8436 * at any of the leaves. In order to do mixed groups we'd have to check
8437 * the leaves of any fs roots and pin down the bytes for any file
8438 * extents we find. Not hard but why do it if we don't have to?
8440 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8441 fprintf(stderr, "We don't support re-initing the extent tree "
8442 "for mixed block groups yet, please notify a btrfs "
8443 "developer you want to do this so they can add this "
8444 "functionality.\n");
8449 * first we need to walk all of the trees except the extent tree and pin
8450 * down the bytes that are in use so we don't overwrite any existing
8453 ret = pin_metadata_blocks(fs_info);
8455 fprintf(stderr, "error pinning down used bytes\n");
8460 * Need to drop all the block groups since we're going to recreate all
8463 btrfs_free_block_groups(fs_info);
8464 ret = reset_block_groups(fs_info);
8466 fprintf(stderr, "error resetting the block groups\n");
8470 /* Ok we can allocate now, reinit the extent root */
8471 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8473 fprintf(stderr, "extent root initialization failed\n");
8475 * When the transaction code is updated we should end the
8476 * transaction, but for now progs only knows about commit so
8477 * just return an error.
8483 * Now we have all the in-memory block groups setup so we can make
8484 * allocations properly, and the metadata we care about is safe since we
8485 * pinned all of it above.
8488 struct btrfs_block_group_cache *cache;
8490 cache = btrfs_lookup_first_block_group(fs_info, start);
8493 start = cache->key.objectid + cache->key.offset;
8494 ret = btrfs_insert_item(trans, fs_info->extent_root,
8495 &cache->key, &cache->item,
8496 sizeof(cache->item));
8498 fprintf(stderr, "Error adding block group\n");
8501 btrfs_extent_post_op(trans, fs_info->extent_root);
8504 ret = reset_balance(trans, fs_info);
8506 fprintf(stderr, "error reseting the pending balance\n");
8511 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8513 struct btrfs_path *path;
8514 struct btrfs_trans_handle *trans;
8515 struct btrfs_key key;
8518 printf("Recowing metadata block %llu\n", eb->start);
8519 key.objectid = btrfs_header_owner(eb);
8520 key.type = BTRFS_ROOT_ITEM_KEY;
8521 key.offset = (u64)-1;
8523 root = btrfs_read_fs_root(root->fs_info, &key);
8525 fprintf(stderr, "Couldn't find owner root %llu\n",
8527 return PTR_ERR(root);
8530 path = btrfs_alloc_path();
8534 trans = btrfs_start_transaction(root, 1);
8535 if (IS_ERR(trans)) {
8536 btrfs_free_path(path);
8537 return PTR_ERR(trans);
8540 path->lowest_level = btrfs_header_level(eb);
8541 if (path->lowest_level)
8542 btrfs_node_key_to_cpu(eb, &key, 0);
8544 btrfs_item_key_to_cpu(eb, &key, 0);
8546 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8547 btrfs_commit_transaction(trans, root);
8548 btrfs_free_path(path);
8552 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8554 struct btrfs_path *path;
8555 struct btrfs_trans_handle *trans;
8556 struct btrfs_key key;
8559 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8560 bad->key.type, bad->key.offset);
8561 key.objectid = bad->root_id;
8562 key.type = BTRFS_ROOT_ITEM_KEY;
8563 key.offset = (u64)-1;
8565 root = btrfs_read_fs_root(root->fs_info, &key);
8567 fprintf(stderr, "Couldn't find owner root %llu\n",
8569 return PTR_ERR(root);
8572 path = btrfs_alloc_path();
8576 trans = btrfs_start_transaction(root, 1);
8577 if (IS_ERR(trans)) {
8578 btrfs_free_path(path);
8579 return PTR_ERR(trans);
8582 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8588 ret = btrfs_del_item(trans, root, path);
8590 btrfs_commit_transaction(trans, root);
8591 btrfs_free_path(path);
8595 static int zero_log_tree(struct btrfs_root *root)
8597 struct btrfs_trans_handle *trans;
8600 trans = btrfs_start_transaction(root, 1);
8601 if (IS_ERR(trans)) {
8602 ret = PTR_ERR(trans);
8605 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8606 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8607 ret = btrfs_commit_transaction(trans, root);
8611 static int populate_csum(struct btrfs_trans_handle *trans,
8612 struct btrfs_root *csum_root, char *buf, u64 start,
8619 while (offset < len) {
8620 sectorsize = csum_root->sectorsize;
8621 ret = read_extent_data(csum_root, buf, start + offset,
8625 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8626 start + offset, buf, sectorsize);
8629 offset += sectorsize;
8634 static int fill_csum_tree_from_one_fs_root(struct btrfs_trans_handle *trans,
8635 struct btrfs_root *csum_root,
8636 struct btrfs_root *cur_root)
8638 struct btrfs_path *path;
8639 struct btrfs_key key;
8640 struct extent_buffer *node;
8641 struct btrfs_file_extent_item *fi;
8648 path = btrfs_alloc_path();
8651 buf = malloc(cur_root->fs_info->csum_root->sectorsize);
8661 ret = btrfs_search_slot(NULL, cur_root, &key, path, 0, 0);
8664 /* Iterate all regular file extents and fill its csum */
8666 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
8668 if (key.type != BTRFS_EXTENT_DATA_KEY)
8670 node = path->nodes[0];
8671 slot = path->slots[0];
8672 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
8673 if (btrfs_file_extent_type(node, fi) != BTRFS_FILE_EXTENT_REG)
8675 start = btrfs_file_extent_disk_bytenr(node, fi);
8676 len = btrfs_file_extent_disk_num_bytes(node, fi);
8678 ret = populate_csum(trans, csum_root, buf, start, len);
8685 * TODO: if next leaf is corrupted, jump to nearest next valid
8688 ret = btrfs_next_item(cur_root, path);
8698 btrfs_free_path(path);
8703 static int fill_csum_tree_from_fs(struct btrfs_trans_handle *trans,
8704 struct btrfs_root *csum_root)
8706 struct btrfs_fs_info *fs_info = csum_root->fs_info;
8707 struct btrfs_path *path;
8708 struct btrfs_root *tree_root = fs_info->tree_root;
8709 struct btrfs_root *cur_root;
8710 struct extent_buffer *node;
8711 struct btrfs_key key;
8715 path = btrfs_alloc_path();
8719 key.objectid = BTRFS_FS_TREE_OBJECTID;
8721 key.type = BTRFS_ROOT_ITEM_KEY;
8723 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
8732 node = path->nodes[0];
8733 slot = path->slots[0];
8734 btrfs_item_key_to_cpu(node, &key, slot);
8735 if (key.objectid > BTRFS_LAST_FREE_OBJECTID)
8737 if (key.type != BTRFS_ROOT_ITEM_KEY)
8739 if (!is_fstree(key.objectid))
8741 key.offset = (u64)-1;
8743 cur_root = btrfs_read_fs_root(fs_info, &key);
8744 if (IS_ERR(cur_root) || !cur_root) {
8745 fprintf(stderr, "Fail to read fs/subvol tree: %lld\n",
8749 ret = fill_csum_tree_from_one_fs_root(trans, csum_root,
8754 ret = btrfs_next_item(tree_root, path);
8764 btrfs_free_path(path);
8768 static int fill_csum_tree_from_extent(struct btrfs_trans_handle *trans,
8769 struct btrfs_root *csum_root)
8771 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8772 struct btrfs_path *path;
8773 struct btrfs_extent_item *ei;
8774 struct extent_buffer *leaf;
8776 struct btrfs_key key;
8779 path = btrfs_alloc_path();
8784 key.type = BTRFS_EXTENT_ITEM_KEY;
8787 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8789 btrfs_free_path(path);
8793 buf = malloc(csum_root->sectorsize);
8795 btrfs_free_path(path);
8800 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8801 ret = btrfs_next_leaf(extent_root, path);
8809 leaf = path->nodes[0];
8811 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8812 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8817 ei = btrfs_item_ptr(leaf, path->slots[0],
8818 struct btrfs_extent_item);
8819 if (!(btrfs_extent_flags(leaf, ei) &
8820 BTRFS_EXTENT_FLAG_DATA)) {
8825 ret = populate_csum(trans, csum_root, buf, key.objectid,
8832 btrfs_free_path(path);
8838 * Recalculate the csum and put it into the csum tree.
8840 * Extent tree init will wipe out all the extent info, so in that case, we
8841 * can't depend on extent tree, but use fs tree. If search_fs_tree is set, we
8842 * will use fs/subvol trees to init the csum tree.
8844 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8845 struct btrfs_root *csum_root,
8849 return fill_csum_tree_from_fs(trans, csum_root);
8851 return fill_csum_tree_from_extent(trans, csum_root);
8854 struct root_item_info {
8855 /* level of the root */
8857 /* number of nodes at this level, must be 1 for a root */
8861 struct cache_extent cache_extent;
8864 static struct cache_tree *roots_info_cache = NULL;
8866 static void free_roots_info_cache(void)
8868 if (!roots_info_cache)
8871 while (!cache_tree_empty(roots_info_cache)) {
8872 struct cache_extent *entry;
8873 struct root_item_info *rii;
8875 entry = first_cache_extent(roots_info_cache);
8878 remove_cache_extent(roots_info_cache, entry);
8879 rii = container_of(entry, struct root_item_info, cache_extent);
8883 free(roots_info_cache);
8884 roots_info_cache = NULL;
8887 static int build_roots_info_cache(struct btrfs_fs_info *info)
8890 struct btrfs_key key;
8891 struct extent_buffer *leaf;
8892 struct btrfs_path *path;
8894 if (!roots_info_cache) {
8895 roots_info_cache = malloc(sizeof(*roots_info_cache));
8896 if (!roots_info_cache)
8898 cache_tree_init(roots_info_cache);
8901 path = btrfs_alloc_path();
8906 key.type = BTRFS_EXTENT_ITEM_KEY;
8909 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8912 leaf = path->nodes[0];
8915 struct btrfs_key found_key;
8916 struct btrfs_extent_item *ei;
8917 struct btrfs_extent_inline_ref *iref;
8918 int slot = path->slots[0];
8923 struct cache_extent *entry;
8924 struct root_item_info *rii;
8926 if (slot >= btrfs_header_nritems(leaf)) {
8927 ret = btrfs_next_leaf(info->extent_root, path);
8934 leaf = path->nodes[0];
8935 slot = path->slots[0];
8938 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8940 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8941 found_key.type != BTRFS_METADATA_ITEM_KEY)
8944 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8945 flags = btrfs_extent_flags(leaf, ei);
8947 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8948 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8951 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8952 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8953 level = found_key.offset;
8955 struct btrfs_tree_block_info *info;
8957 info = (struct btrfs_tree_block_info *)(ei + 1);
8958 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8959 level = btrfs_tree_block_level(leaf, info);
8963 * For a root extent, it must be of the following type and the
8964 * first (and only one) iref in the item.
8966 type = btrfs_extent_inline_ref_type(leaf, iref);
8967 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8970 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8971 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8973 rii = malloc(sizeof(struct root_item_info));
8978 rii->cache_extent.start = root_id;
8979 rii->cache_extent.size = 1;
8980 rii->level = (u8)-1;
8981 entry = &rii->cache_extent;
8982 ret = insert_cache_extent(roots_info_cache, entry);
8985 rii = container_of(entry, struct root_item_info,
8989 ASSERT(rii->cache_extent.start == root_id);
8990 ASSERT(rii->cache_extent.size == 1);
8992 if (level > rii->level || rii->level == (u8)-1) {
8994 rii->bytenr = found_key.objectid;
8995 rii->gen = btrfs_extent_generation(leaf, ei);
8996 rii->node_count = 1;
8997 } else if (level == rii->level) {
9005 btrfs_free_path(path);
9010 static int maybe_repair_root_item(struct btrfs_fs_info *info,
9011 struct btrfs_path *path,
9012 const struct btrfs_key *root_key,
9013 const int read_only_mode)
9015 const u64 root_id = root_key->objectid;
9016 struct cache_extent *entry;
9017 struct root_item_info *rii;
9018 struct btrfs_root_item ri;
9019 unsigned long offset;
9021 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9024 "Error: could not find extent items for root %llu\n",
9025 root_key->objectid);
9029 rii = container_of(entry, struct root_item_info, cache_extent);
9030 ASSERT(rii->cache_extent.start == root_id);
9031 ASSERT(rii->cache_extent.size == 1);
9033 if (rii->node_count != 1) {
9035 "Error: could not find btree root extent for root %llu\n",
9040 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
9041 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
9043 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
9044 btrfs_root_level(&ri) != rii->level ||
9045 btrfs_root_generation(&ri) != rii->gen) {
9048 * If we're in repair mode but our caller told us to not update
9049 * the root item, i.e. just check if it needs to be updated, don't
9050 * print this message, since the caller will call us again shortly
9051 * for the same root item without read only mode (the caller will
9052 * open a transaction first).
9054 if (!(read_only_mode && repair))
9056 "%sroot item for root %llu,"
9057 " current bytenr %llu, current gen %llu, current level %u,"
9058 " new bytenr %llu, new gen %llu, new level %u\n",
9059 (read_only_mode ? "" : "fixing "),
9061 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
9062 btrfs_root_level(&ri),
9063 rii->bytenr, rii->gen, rii->level);
9065 if (btrfs_root_generation(&ri) > rii->gen) {
9067 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
9068 root_id, btrfs_root_generation(&ri), rii->gen);
9072 if (!read_only_mode) {
9073 btrfs_set_root_bytenr(&ri, rii->bytenr);
9074 btrfs_set_root_level(&ri, rii->level);
9075 btrfs_set_root_generation(&ri, rii->gen);
9076 write_extent_buffer(path->nodes[0], &ri,
9077 offset, sizeof(ri));
9087 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
9088 * caused read-only snapshots to be corrupted if they were created at a moment
9089 * when the source subvolume/snapshot had orphan items. The issue was that the
9090 * on-disk root items became incorrect, referring to the pre orphan cleanup root
9091 * node instead of the post orphan cleanup root node.
9092 * So this function, and its callees, just detects and fixes those cases. Even
9093 * though the regression was for read-only snapshots, this function applies to
9094 * any snapshot/subvolume root.
9095 * This must be run before any other repair code - not doing it so, makes other
9096 * repair code delete or modify backrefs in the extent tree for example, which
9097 * will result in an inconsistent fs after repairing the root items.
9099 static int repair_root_items(struct btrfs_fs_info *info)
9101 struct btrfs_path *path = NULL;
9102 struct btrfs_key key;
9103 struct extent_buffer *leaf;
9104 struct btrfs_trans_handle *trans = NULL;
9109 ret = build_roots_info_cache(info);
9113 path = btrfs_alloc_path();
9119 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
9120 key.type = BTRFS_ROOT_ITEM_KEY;
9125 * Avoid opening and committing transactions if a leaf doesn't have
9126 * any root items that need to be fixed, so that we avoid rotating
9127 * backup roots unnecessarily.
9130 trans = btrfs_start_transaction(info->tree_root, 1);
9131 if (IS_ERR(trans)) {
9132 ret = PTR_ERR(trans);
9137 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
9141 leaf = path->nodes[0];
9144 struct btrfs_key found_key;
9146 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
9147 int no_more_keys = find_next_key(path, &key);
9149 btrfs_release_path(path);
9151 ret = btrfs_commit_transaction(trans,
9163 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9165 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
9167 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9170 ret = maybe_repair_root_item(info, path, &found_key,
9175 if (!trans && repair) {
9178 btrfs_release_path(path);
9188 free_roots_info_cache();
9190 btrfs_free_path(path);
9192 btrfs_commit_transaction(trans, info->tree_root);
9199 const char * const cmd_check_usage[] = {
9200 "btrfs check [options] <device>",
9201 "Check an unmounted btrfs filesystem.",
9203 "-s|--super <superblock> use this superblock copy",
9204 "-b|--backup use the backup root copy",
9205 "--repair try to repair the filesystem",
9206 "--init-csum-tree create a new CRC tree",
9207 "--init-extent-tree create a new extent tree",
9208 "--check-data-csum verify checkums of data blocks",
9209 "--qgroup-report print a report on qgroup consistency",
9210 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9211 "--tree-root <bytenr> use the given bytenr for the tree root",
9215 int cmd_check(int argc, char **argv)
9217 struct cache_tree root_cache;
9218 struct btrfs_root *root;
9219 struct btrfs_fs_info *info;
9222 u64 tree_root_bytenr = 0;
9223 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9226 int init_csum_tree = 0;
9228 int qgroup_report = 0;
9229 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9233 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9234 OPT_CHECK_CSUM, OPT_READONLY };
9235 static const struct option long_options[] = {
9236 { "super", required_argument, NULL, 's' },
9237 { "repair", no_argument, NULL, OPT_REPAIR },
9238 { "readonly", no_argument, NULL, OPT_READONLY },
9239 { "init-csum-tree", no_argument, NULL, OPT_INIT_CSUM },
9240 { "init-extent-tree", no_argument, NULL, OPT_INIT_EXTENT },
9241 { "check-data-csum", no_argument, NULL, OPT_CHECK_CSUM },
9242 { "backup", no_argument, NULL, 'b' },
9243 { "subvol-extents", required_argument, NULL, 'E' },
9244 { "qgroup-report", no_argument, NULL, 'Q' },
9245 { "tree-root", required_argument, NULL, 'r' },
9249 c = getopt_long(argc, argv, "as:br:", long_options, NULL);
9253 case 'a': /* ignored */ break;
9255 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9258 num = arg_strtou64(optarg);
9259 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9261 "ERROR: super mirror should be less than: %d\n",
9262 BTRFS_SUPER_MIRROR_MAX);
9265 bytenr = btrfs_sb_offset(((int)num));
9266 printf("using SB copy %llu, bytenr %llu\n", num,
9267 (unsigned long long)bytenr);
9273 subvolid = arg_strtou64(optarg);
9276 tree_root_bytenr = arg_strtou64(optarg);
9280 usage(cmd_check_usage);
9282 printf("enabling repair mode\n");
9284 ctree_flags |= OPEN_CTREE_WRITES;
9290 printf("Creating a new CRC tree\n");
9293 ctree_flags |= OPEN_CTREE_WRITES;
9295 case OPT_INIT_EXTENT:
9296 init_extent_tree = 1;
9297 ctree_flags |= (OPEN_CTREE_WRITES |
9298 OPEN_CTREE_NO_BLOCK_GROUPS);
9301 case OPT_CHECK_CSUM:
9302 check_data_csum = 1;
9306 argc = argc - optind;
9308 if (check_argc_exact(argc, 1))
9309 usage(cmd_check_usage);
9311 /* This check is the only reason for --readonly to exist */
9312 if (readonly && repair) {
9313 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9318 cache_tree_init(&root_cache);
9320 if((ret = check_mounted(argv[optind])) < 0) {
9321 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9324 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9329 /* only allow partial opening under repair mode */
9331 ctree_flags |= OPEN_CTREE_PARTIAL;
9333 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9336 fprintf(stderr, "Couldn't open file system\n");
9341 root = info->fs_root;
9344 * repair mode will force us to commit transaction which
9345 * will make us fail to load log tree when mounting.
9347 if (repair && btrfs_super_log_root(info->super_copy)) {
9348 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9353 ret = zero_log_tree(root);
9355 fprintf(stderr, "fail to zero log tree\n");
9360 uuid_unparse(info->super_copy->fsid, uuidbuf);
9361 if (qgroup_report) {
9362 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9364 ret = qgroup_verify_all(info);
9366 print_qgroup_report(1);
9370 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9371 subvolid, argv[optind], uuidbuf);
9372 ret = print_extent_state(info, subvolid);
9375 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9377 if (!extent_buffer_uptodate(info->tree_root->node) ||
9378 !extent_buffer_uptodate(info->dev_root->node) ||
9379 !extent_buffer_uptodate(info->chunk_root->node)) {
9380 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9385 if (init_extent_tree || init_csum_tree) {
9386 struct btrfs_trans_handle *trans;
9388 trans = btrfs_start_transaction(info->extent_root, 0);
9389 if (IS_ERR(trans)) {
9390 fprintf(stderr, "Error starting transaction\n");
9391 ret = PTR_ERR(trans);
9395 if (init_extent_tree) {
9396 printf("Creating a new extent tree\n");
9397 ret = reinit_extent_tree(trans, info);
9402 if (init_csum_tree) {
9403 fprintf(stderr, "Reinit crc root\n");
9404 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9406 fprintf(stderr, "crc root initialization failed\n");
9411 ret = fill_csum_tree(trans, info->csum_root,
9414 fprintf(stderr, "crc refilling failed\n");
9419 * Ok now we commit and run the normal fsck, which will add
9420 * extent entries for all of the items it finds.
9422 ret = btrfs_commit_transaction(trans, info->extent_root);
9426 if (!extent_buffer_uptodate(info->extent_root->node)) {
9427 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9431 if (!extent_buffer_uptodate(info->csum_root->node)) {
9432 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9437 fprintf(stderr, "checking extents\n");
9438 ret = check_chunks_and_extents(root);
9440 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9442 ret = repair_root_items(info);
9446 fprintf(stderr, "Fixed %d roots.\n", ret);
9448 } else if (ret > 0) {
9450 "Found %d roots with an outdated root item.\n",
9453 "Please run a filesystem check with the option --repair to fix them.\n");
9458 fprintf(stderr, "checking free space cache\n");
9459 ret = check_space_cache(root);
9464 * We used to have to have these hole extents in between our real
9465 * extents so if we don't have this flag set we need to make sure there
9466 * are no gaps in the file extents for inodes, otherwise we can just
9467 * ignore it when this happens.
9469 no_holes = btrfs_fs_incompat(root->fs_info,
9470 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9471 fprintf(stderr, "checking fs roots\n");
9472 ret = check_fs_roots(root, &root_cache);
9476 fprintf(stderr, "checking csums\n");
9477 ret = check_csums(root);
9481 fprintf(stderr, "checking root refs\n");
9482 ret = check_root_refs(root, &root_cache);
9486 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9487 struct extent_buffer *eb;
9489 eb = list_first_entry(&root->fs_info->recow_ebs,
9490 struct extent_buffer, recow);
9491 list_del_init(&eb->recow);
9492 ret = recow_extent_buffer(root, eb);
9497 while (!list_empty(&delete_items)) {
9498 struct bad_item *bad;
9500 bad = list_first_entry(&delete_items, struct bad_item, list);
9501 list_del_init(&bad->list);
9503 ret = delete_bad_item(root, bad);
9507 if (info->quota_enabled) {
9509 fprintf(stderr, "checking quota groups\n");
9510 err = qgroup_verify_all(info);
9515 if (!list_empty(&root->fs_info->recow_ebs)) {
9516 fprintf(stderr, "Transid errors in file system\n");
9520 print_qgroup_report(0);
9521 if (found_old_backref) { /*
9522 * there was a disk format change when mixed
9523 * backref was in testing tree. The old format
9524 * existed about one week.
9526 printf("\n * Found old mixed backref format. "
9527 "The old format is not supported! *"
9528 "\n * Please mount the FS in readonly mode, "
9529 "backup data and re-format the FS. *\n\n");
9532 printf("found %llu bytes used err is %d\n",
9533 (unsigned long long)bytes_used, ret);
9534 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9535 printf("total tree bytes: %llu\n",
9536 (unsigned long long)total_btree_bytes);
9537 printf("total fs tree bytes: %llu\n",
9538 (unsigned long long)total_fs_tree_bytes);
9539 printf("total extent tree bytes: %llu\n",
9540 (unsigned long long)total_extent_tree_bytes);
9541 printf("btree space waste bytes: %llu\n",
9542 (unsigned long long)btree_space_waste);
9543 printf("file data blocks allocated: %llu\n referenced %llu\n",
9544 (unsigned long long)data_bytes_allocated,
9545 (unsigned long long)data_bytes_referenced);
9546 printf("%s\n", PACKAGE_STRING);
9548 free_root_recs_tree(&root_cache);