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;
129 unsigned int crossing_stripes:1;
132 struct inode_backref {
133 struct list_head list;
134 unsigned int found_dir_item:1;
135 unsigned int found_dir_index:1;
136 unsigned int found_inode_ref:1;
137 unsigned int filetype:8;
139 unsigned int ref_type;
146 struct root_item_record {
147 struct list_head list;
154 struct btrfs_key drop_key;
157 #define REF_ERR_NO_DIR_ITEM (1 << 0)
158 #define REF_ERR_NO_DIR_INDEX (1 << 1)
159 #define REF_ERR_NO_INODE_REF (1 << 2)
160 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
161 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
162 #define REF_ERR_DUP_INODE_REF (1 << 5)
163 #define REF_ERR_INDEX_UNMATCH (1 << 6)
164 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
165 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
166 #define REF_ERR_NO_ROOT_REF (1 << 9)
167 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
168 #define REF_ERR_DUP_ROOT_REF (1 << 11)
169 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
171 struct file_extent_hole {
177 /* Compatible function to allow reuse of old codes */
178 static u64 first_extent_gap(struct rb_root *holes)
180 struct file_extent_hole *hole;
182 if (RB_EMPTY_ROOT(holes))
185 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
189 int compare_hole(struct rb_node *node1, struct rb_node *node2)
191 struct file_extent_hole *hole1;
192 struct file_extent_hole *hole2;
194 hole1 = rb_entry(node1, struct file_extent_hole, node);
195 hole2 = rb_entry(node2, struct file_extent_hole, node);
197 if (hole1->start > hole2->start)
199 if (hole1->start < hole2->start)
201 /* Now hole1->start == hole2->start */
202 if (hole1->len >= hole2->len)
204 * Hole 1 will be merge center
205 * Same hole will be merged later
208 /* Hole 2 will be merge center */
213 * Add a hole to the record
215 * This will do hole merge for copy_file_extent_holes(),
216 * which will ensure there won't be continuous holes.
218 static int add_file_extent_hole(struct rb_root *holes,
221 struct file_extent_hole *hole;
222 struct file_extent_hole *prev = NULL;
223 struct file_extent_hole *next = NULL;
225 hole = malloc(sizeof(*hole));
230 /* Since compare will not return 0, no -EEXIST will happen */
231 rb_insert(holes, &hole->node, compare_hole);
233 /* simple merge with previous hole */
234 if (rb_prev(&hole->node))
235 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
237 if (prev && prev->start + prev->len >= hole->start) {
238 hole->len = hole->start + hole->len - prev->start;
239 hole->start = prev->start;
240 rb_erase(&prev->node, holes);
245 /* iterate merge with next holes */
247 if (!rb_next(&hole->node))
249 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
251 if (hole->start + hole->len >= next->start) {
252 if (hole->start + hole->len <= next->start + next->len)
253 hole->len = next->start + next->len -
255 rb_erase(&next->node, holes);
264 static int compare_hole_range(struct rb_node *node, void *data)
266 struct file_extent_hole *hole;
269 hole = (struct file_extent_hole *)data;
272 hole = rb_entry(node, struct file_extent_hole, node);
273 if (start < hole->start)
275 if (start >= hole->start && start < hole->start + hole->len)
281 * Delete a hole in the record
283 * This will do the hole split and is much restrict than add.
285 static int del_file_extent_hole(struct rb_root *holes,
288 struct file_extent_hole *hole;
289 struct file_extent_hole tmp;
294 struct rb_node *node;
301 node = rb_search(holes, &tmp, compare_hole_range, NULL);
304 hole = rb_entry(node, struct file_extent_hole, node);
305 if (start + len > hole->start + hole->len)
309 * Now there will be no overflap, delete the hole and re-add the
310 * split(s) if they exists.
312 if (start > hole->start) {
313 prev_start = hole->start;
314 prev_len = start - hole->start;
317 if (hole->start + hole->len > start + len) {
318 next_start = start + len;
319 next_len = hole->start + hole->len - start - len;
322 rb_erase(node, holes);
325 ret = add_file_extent_hole(holes, prev_start, prev_len);
330 ret = add_file_extent_hole(holes, next_start, next_len);
337 static int copy_file_extent_holes(struct rb_root *dst,
340 struct file_extent_hole *hole;
341 struct rb_node *node;
344 node = rb_first(src);
346 hole = rb_entry(node, struct file_extent_hole, node);
347 ret = add_file_extent_hole(dst, hole->start, hole->len);
350 node = rb_next(node);
355 static void free_file_extent_holes(struct rb_root *holes)
357 struct rb_node *node;
358 struct file_extent_hole *hole;
360 node = rb_first(holes);
362 hole = rb_entry(node, struct file_extent_hole, node);
363 rb_erase(node, holes);
365 node = rb_first(holes);
369 struct inode_record {
370 struct list_head backrefs;
371 unsigned int checked:1;
372 unsigned int merging:1;
373 unsigned int found_inode_item:1;
374 unsigned int found_dir_item:1;
375 unsigned int found_file_extent:1;
376 unsigned int found_csum_item:1;
377 unsigned int some_csum_missing:1;
378 unsigned int nodatasum:1;
391 struct rb_root holes;
392 struct list_head orphan_extents;
397 #define I_ERR_NO_INODE_ITEM (1 << 0)
398 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
399 #define I_ERR_DUP_INODE_ITEM (1 << 2)
400 #define I_ERR_DUP_DIR_INDEX (1 << 3)
401 #define I_ERR_ODD_DIR_ITEM (1 << 4)
402 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
403 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
404 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
405 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
406 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
407 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
408 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
409 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
410 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
411 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
413 struct root_backref {
414 struct list_head list;
415 unsigned int found_dir_item:1;
416 unsigned int found_dir_index:1;
417 unsigned int found_back_ref:1;
418 unsigned int found_forward_ref:1;
419 unsigned int reachable:1;
429 struct list_head backrefs;
430 struct cache_extent cache;
431 unsigned int found_root_item:1;
437 struct cache_extent cache;
442 struct cache_extent cache;
443 struct cache_tree root_cache;
444 struct cache_tree inode_cache;
445 struct inode_record *current;
454 struct walk_control {
455 struct cache_tree shared;
456 struct shared_node *nodes[BTRFS_MAX_LEVEL];
462 struct btrfs_key key;
464 struct list_head list;
467 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
469 static void record_root_in_trans(struct btrfs_trans_handle *trans,
470 struct btrfs_root *root)
472 if (root->last_trans != trans->transid) {
473 root->track_dirty = 1;
474 root->last_trans = trans->transid;
475 root->commit_root = root->node;
476 extent_buffer_get(root->node);
480 static u8 imode_to_type(u32 imode)
483 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
484 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
485 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
486 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
487 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
488 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
489 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
490 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
493 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
497 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
499 struct device_record *rec1;
500 struct device_record *rec2;
502 rec1 = rb_entry(node1, struct device_record, node);
503 rec2 = rb_entry(node2, struct device_record, node);
504 if (rec1->devid > rec2->devid)
506 else if (rec1->devid < rec2->devid)
512 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
514 struct inode_record *rec;
515 struct inode_backref *backref;
516 struct inode_backref *orig;
517 struct orphan_data_extent *src_orphan;
518 struct orphan_data_extent *dst_orphan;
522 rec = malloc(sizeof(*rec));
523 memcpy(rec, orig_rec, sizeof(*rec));
525 INIT_LIST_HEAD(&rec->backrefs);
526 INIT_LIST_HEAD(&rec->orphan_extents);
527 rec->holes = RB_ROOT;
529 list_for_each_entry(orig, &orig_rec->backrefs, list) {
530 size = sizeof(*orig) + orig->namelen + 1;
531 backref = malloc(size);
532 memcpy(backref, orig, size);
533 list_add_tail(&backref->list, &rec->backrefs);
535 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
536 dst_orphan = malloc(sizeof(*dst_orphan));
537 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
539 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
540 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
542 ret = copy_file_extent_holes(&rec->holes, &orig_rec->holes);
548 static void print_orphan_data_extents(struct list_head *orphan_extents,
551 struct orphan_data_extent *orphan;
553 if (list_empty(orphan_extents))
555 printf("The following data extent is lost in tree %llu:\n",
557 list_for_each_entry(orphan, orphan_extents, list) {
558 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
559 orphan->objectid, orphan->offset, orphan->disk_bytenr,
564 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
566 u64 root_objectid = root->root_key.objectid;
567 int errors = rec->errors;
571 /* reloc root errors, we print its corresponding fs root objectid*/
572 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
573 root_objectid = root->root_key.offset;
574 fprintf(stderr, "reloc");
576 fprintf(stderr, "root %llu inode %llu errors %x",
577 (unsigned long long) root_objectid,
578 (unsigned long long) rec->ino, rec->errors);
580 if (errors & I_ERR_NO_INODE_ITEM)
581 fprintf(stderr, ", no inode item");
582 if (errors & I_ERR_NO_ORPHAN_ITEM)
583 fprintf(stderr, ", no orphan item");
584 if (errors & I_ERR_DUP_INODE_ITEM)
585 fprintf(stderr, ", dup inode item");
586 if (errors & I_ERR_DUP_DIR_INDEX)
587 fprintf(stderr, ", dup dir index");
588 if (errors & I_ERR_ODD_DIR_ITEM)
589 fprintf(stderr, ", odd dir item");
590 if (errors & I_ERR_ODD_FILE_EXTENT)
591 fprintf(stderr, ", odd file extent");
592 if (errors & I_ERR_BAD_FILE_EXTENT)
593 fprintf(stderr, ", bad file extent");
594 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
595 fprintf(stderr, ", file extent overlap");
596 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
597 fprintf(stderr, ", file extent discount");
598 if (errors & I_ERR_DIR_ISIZE_WRONG)
599 fprintf(stderr, ", dir isize wrong");
600 if (errors & I_ERR_FILE_NBYTES_WRONG)
601 fprintf(stderr, ", nbytes wrong");
602 if (errors & I_ERR_ODD_CSUM_ITEM)
603 fprintf(stderr, ", odd csum item");
604 if (errors & I_ERR_SOME_CSUM_MISSING)
605 fprintf(stderr, ", some csum missing");
606 if (errors & I_ERR_LINK_COUNT_WRONG)
607 fprintf(stderr, ", link count wrong");
608 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
609 fprintf(stderr, ", orphan file extent");
610 fprintf(stderr, "\n");
611 /* Print the orphan extents if needed */
612 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
613 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
615 /* Print the holes if needed */
616 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
617 struct file_extent_hole *hole;
618 struct rb_node *node;
620 node = rb_first(&rec->holes);
621 fprintf(stderr, "Found file extent holes:\n");
623 hole = rb_entry(node, struct file_extent_hole, node);
624 fprintf(stderr, "\tstart: %llu, len:%llu\n",
625 hole->start, hole->len);
626 node = rb_next(node);
631 static void print_ref_error(int errors)
633 if (errors & REF_ERR_NO_DIR_ITEM)
634 fprintf(stderr, ", no dir item");
635 if (errors & REF_ERR_NO_DIR_INDEX)
636 fprintf(stderr, ", no dir index");
637 if (errors & REF_ERR_NO_INODE_REF)
638 fprintf(stderr, ", no inode ref");
639 if (errors & REF_ERR_DUP_DIR_ITEM)
640 fprintf(stderr, ", dup dir item");
641 if (errors & REF_ERR_DUP_DIR_INDEX)
642 fprintf(stderr, ", dup dir index");
643 if (errors & REF_ERR_DUP_INODE_REF)
644 fprintf(stderr, ", dup inode ref");
645 if (errors & REF_ERR_INDEX_UNMATCH)
646 fprintf(stderr, ", index unmatch");
647 if (errors & REF_ERR_FILETYPE_UNMATCH)
648 fprintf(stderr, ", filetype unmatch");
649 if (errors & REF_ERR_NAME_TOO_LONG)
650 fprintf(stderr, ", name too long");
651 if (errors & REF_ERR_NO_ROOT_REF)
652 fprintf(stderr, ", no root ref");
653 if (errors & REF_ERR_NO_ROOT_BACKREF)
654 fprintf(stderr, ", no root backref");
655 if (errors & REF_ERR_DUP_ROOT_REF)
656 fprintf(stderr, ", dup root ref");
657 if (errors & REF_ERR_DUP_ROOT_BACKREF)
658 fprintf(stderr, ", dup root backref");
659 fprintf(stderr, "\n");
662 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
665 struct ptr_node *node;
666 struct cache_extent *cache;
667 struct inode_record *rec = NULL;
670 cache = lookup_cache_extent(inode_cache, ino, 1);
672 node = container_of(cache, struct ptr_node, cache);
674 if (mod && rec->refs > 1) {
675 node->data = clone_inode_rec(rec);
680 rec = calloc(1, sizeof(*rec));
682 rec->extent_start = (u64)-1;
684 INIT_LIST_HEAD(&rec->backrefs);
685 INIT_LIST_HEAD(&rec->orphan_extents);
686 rec->holes = RB_ROOT;
688 node = malloc(sizeof(*node));
689 node->cache.start = ino;
690 node->cache.size = 1;
693 if (ino == BTRFS_FREE_INO_OBJECTID)
696 ret = insert_cache_extent(inode_cache, &node->cache);
702 static void free_orphan_data_extents(struct list_head *orphan_extents)
704 struct orphan_data_extent *orphan;
706 while (!list_empty(orphan_extents)) {
707 orphan = list_entry(orphan_extents->next,
708 struct orphan_data_extent, list);
709 list_del(&orphan->list);
714 static void free_inode_rec(struct inode_record *rec)
716 struct inode_backref *backref;
721 while (!list_empty(&rec->backrefs)) {
722 backref = list_entry(rec->backrefs.next,
723 struct inode_backref, list);
724 list_del(&backref->list);
727 free_orphan_data_extents(&rec->orphan_extents);
728 free_file_extent_holes(&rec->holes);
732 static int can_free_inode_rec(struct inode_record *rec)
734 if (!rec->errors && rec->checked && rec->found_inode_item &&
735 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
740 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
741 struct inode_record *rec)
743 struct cache_extent *cache;
744 struct inode_backref *tmp, *backref;
745 struct ptr_node *node;
746 unsigned char filetype;
748 if (!rec->found_inode_item)
751 filetype = imode_to_type(rec->imode);
752 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
753 if (backref->found_dir_item && backref->found_dir_index) {
754 if (backref->filetype != filetype)
755 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
756 if (!backref->errors && backref->found_inode_ref) {
757 list_del(&backref->list);
763 if (!rec->checked || rec->merging)
766 if (S_ISDIR(rec->imode)) {
767 if (rec->found_size != rec->isize)
768 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
769 if (rec->found_file_extent)
770 rec->errors |= I_ERR_ODD_FILE_EXTENT;
771 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
772 if (rec->found_dir_item)
773 rec->errors |= I_ERR_ODD_DIR_ITEM;
774 if (rec->found_size != rec->nbytes)
775 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
776 if (rec->nlink > 0 && !no_holes &&
777 (rec->extent_end < rec->isize ||
778 first_extent_gap(&rec->holes) < rec->isize))
779 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
782 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
783 if (rec->found_csum_item && rec->nodatasum)
784 rec->errors |= I_ERR_ODD_CSUM_ITEM;
785 if (rec->some_csum_missing && !rec->nodatasum)
786 rec->errors |= I_ERR_SOME_CSUM_MISSING;
789 BUG_ON(rec->refs != 1);
790 if (can_free_inode_rec(rec)) {
791 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
792 node = container_of(cache, struct ptr_node, cache);
793 BUG_ON(node->data != rec);
794 remove_cache_extent(inode_cache, &node->cache);
800 static int check_orphan_item(struct btrfs_root *root, u64 ino)
802 struct btrfs_path path;
803 struct btrfs_key key;
806 key.objectid = BTRFS_ORPHAN_OBJECTID;
807 key.type = BTRFS_ORPHAN_ITEM_KEY;
810 btrfs_init_path(&path);
811 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
812 btrfs_release_path(&path);
818 static int process_inode_item(struct extent_buffer *eb,
819 int slot, struct btrfs_key *key,
820 struct shared_node *active_node)
822 struct inode_record *rec;
823 struct btrfs_inode_item *item;
825 rec = active_node->current;
826 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
827 if (rec->found_inode_item) {
828 rec->errors |= I_ERR_DUP_INODE_ITEM;
831 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
832 rec->nlink = btrfs_inode_nlink(eb, item);
833 rec->isize = btrfs_inode_size(eb, item);
834 rec->nbytes = btrfs_inode_nbytes(eb, item);
835 rec->imode = btrfs_inode_mode(eb, item);
836 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
838 rec->found_inode_item = 1;
840 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
841 maybe_free_inode_rec(&active_node->inode_cache, rec);
845 static struct inode_backref *get_inode_backref(struct inode_record *rec,
847 int namelen, u64 dir)
849 struct inode_backref *backref;
851 list_for_each_entry(backref, &rec->backrefs, list) {
852 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
854 if (backref->dir != dir || backref->namelen != namelen)
856 if (memcmp(name, backref->name, namelen))
861 backref = malloc(sizeof(*backref) + namelen + 1);
862 memset(backref, 0, sizeof(*backref));
864 backref->namelen = namelen;
865 memcpy(backref->name, name, namelen);
866 backref->name[namelen] = '\0';
867 list_add_tail(&backref->list, &rec->backrefs);
871 static int add_inode_backref(struct cache_tree *inode_cache,
872 u64 ino, u64 dir, u64 index,
873 const char *name, int namelen,
874 int filetype, int itemtype, int errors)
876 struct inode_record *rec;
877 struct inode_backref *backref;
879 rec = get_inode_rec(inode_cache, ino, 1);
880 backref = get_inode_backref(rec, name, namelen, dir);
882 backref->errors |= errors;
883 if (itemtype == BTRFS_DIR_INDEX_KEY) {
884 if (backref->found_dir_index)
885 backref->errors |= REF_ERR_DUP_DIR_INDEX;
886 if (backref->found_inode_ref && backref->index != index)
887 backref->errors |= REF_ERR_INDEX_UNMATCH;
888 if (backref->found_dir_item && backref->filetype != filetype)
889 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
891 backref->index = index;
892 backref->filetype = filetype;
893 backref->found_dir_index = 1;
894 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
896 if (backref->found_dir_item)
897 backref->errors |= REF_ERR_DUP_DIR_ITEM;
898 if (backref->found_dir_index && backref->filetype != filetype)
899 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
901 backref->filetype = filetype;
902 backref->found_dir_item = 1;
903 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
904 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
905 if (backref->found_inode_ref)
906 backref->errors |= REF_ERR_DUP_INODE_REF;
907 if (backref->found_dir_index && backref->index != index)
908 backref->errors |= REF_ERR_INDEX_UNMATCH;
910 backref->index = index;
912 backref->ref_type = itemtype;
913 backref->found_inode_ref = 1;
918 maybe_free_inode_rec(inode_cache, rec);
922 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
923 struct cache_tree *dst_cache)
925 struct inode_backref *backref;
930 list_for_each_entry(backref, &src->backrefs, list) {
931 if (backref->found_dir_index) {
932 add_inode_backref(dst_cache, dst->ino, backref->dir,
933 backref->index, backref->name,
934 backref->namelen, backref->filetype,
935 BTRFS_DIR_INDEX_KEY, backref->errors);
937 if (backref->found_dir_item) {
939 add_inode_backref(dst_cache, dst->ino,
940 backref->dir, 0, backref->name,
941 backref->namelen, backref->filetype,
942 BTRFS_DIR_ITEM_KEY, backref->errors);
944 if (backref->found_inode_ref) {
945 add_inode_backref(dst_cache, dst->ino,
946 backref->dir, backref->index,
947 backref->name, backref->namelen, 0,
948 backref->ref_type, backref->errors);
952 if (src->found_dir_item)
953 dst->found_dir_item = 1;
954 if (src->found_file_extent)
955 dst->found_file_extent = 1;
956 if (src->found_csum_item)
957 dst->found_csum_item = 1;
958 if (src->some_csum_missing)
959 dst->some_csum_missing = 1;
960 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
961 ret = copy_file_extent_holes(&dst->holes, &src->holes);
966 BUG_ON(src->found_link < dir_count);
967 dst->found_link += src->found_link - dir_count;
968 dst->found_size += src->found_size;
969 if (src->extent_start != (u64)-1) {
970 if (dst->extent_start == (u64)-1) {
971 dst->extent_start = src->extent_start;
972 dst->extent_end = src->extent_end;
974 if (dst->extent_end > src->extent_start)
975 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
976 else if (dst->extent_end < src->extent_start) {
977 ret = add_file_extent_hole(&dst->holes,
979 src->extent_start - dst->extent_end);
981 if (dst->extent_end < src->extent_end)
982 dst->extent_end = src->extent_end;
986 dst->errors |= src->errors;
987 if (src->found_inode_item) {
988 if (!dst->found_inode_item) {
989 dst->nlink = src->nlink;
990 dst->isize = src->isize;
991 dst->nbytes = src->nbytes;
992 dst->imode = src->imode;
993 dst->nodatasum = src->nodatasum;
994 dst->found_inode_item = 1;
996 dst->errors |= I_ERR_DUP_INODE_ITEM;
1004 static int splice_shared_node(struct shared_node *src_node,
1005 struct shared_node *dst_node)
1007 struct cache_extent *cache;
1008 struct ptr_node *node, *ins;
1009 struct cache_tree *src, *dst;
1010 struct inode_record *rec, *conflict;
1011 u64 current_ino = 0;
1015 if (--src_node->refs == 0)
1017 if (src_node->current)
1018 current_ino = src_node->current->ino;
1020 src = &src_node->root_cache;
1021 dst = &dst_node->root_cache;
1023 cache = search_cache_extent(src, 0);
1025 node = container_of(cache, struct ptr_node, cache);
1027 cache = next_cache_extent(cache);
1030 remove_cache_extent(src, &node->cache);
1033 ins = malloc(sizeof(*ins));
1034 ins->cache.start = node->cache.start;
1035 ins->cache.size = node->cache.size;
1039 ret = insert_cache_extent(dst, &ins->cache);
1040 if (ret == -EEXIST) {
1041 conflict = get_inode_rec(dst, rec->ino, 1);
1042 merge_inode_recs(rec, conflict, dst);
1044 conflict->checked = 1;
1045 if (dst_node->current == conflict)
1046 dst_node->current = NULL;
1048 maybe_free_inode_rec(dst, conflict);
1049 free_inode_rec(rec);
1056 if (src == &src_node->root_cache) {
1057 src = &src_node->inode_cache;
1058 dst = &dst_node->inode_cache;
1062 if (current_ino > 0 && (!dst_node->current ||
1063 current_ino > dst_node->current->ino)) {
1064 if (dst_node->current) {
1065 dst_node->current->checked = 1;
1066 maybe_free_inode_rec(dst, dst_node->current);
1068 dst_node->current = get_inode_rec(dst, current_ino, 1);
1073 static void free_inode_ptr(struct cache_extent *cache)
1075 struct ptr_node *node;
1076 struct inode_record *rec;
1078 node = container_of(cache, struct ptr_node, cache);
1080 free_inode_rec(rec);
1084 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1086 static struct shared_node *find_shared_node(struct cache_tree *shared,
1089 struct cache_extent *cache;
1090 struct shared_node *node;
1092 cache = lookup_cache_extent(shared, bytenr, 1);
1094 node = container_of(cache, struct shared_node, cache);
1100 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1103 struct shared_node *node;
1105 node = calloc(1, sizeof(*node));
1106 node->cache.start = bytenr;
1107 node->cache.size = 1;
1108 cache_tree_init(&node->root_cache);
1109 cache_tree_init(&node->inode_cache);
1112 ret = insert_cache_extent(shared, &node->cache);
1117 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1118 struct walk_control *wc, int level)
1120 struct shared_node *node;
1121 struct shared_node *dest;
1123 if (level == wc->active_node)
1126 BUG_ON(wc->active_node <= level);
1127 node = find_shared_node(&wc->shared, bytenr);
1129 add_shared_node(&wc->shared, bytenr, refs);
1130 node = find_shared_node(&wc->shared, bytenr);
1131 wc->nodes[level] = node;
1132 wc->active_node = level;
1136 if (wc->root_level == wc->active_node &&
1137 btrfs_root_refs(&root->root_item) == 0) {
1138 if (--node->refs == 0) {
1139 free_inode_recs_tree(&node->root_cache);
1140 free_inode_recs_tree(&node->inode_cache);
1141 remove_cache_extent(&wc->shared, &node->cache);
1147 dest = wc->nodes[wc->active_node];
1148 splice_shared_node(node, dest);
1149 if (node->refs == 0) {
1150 remove_cache_extent(&wc->shared, &node->cache);
1156 static int leave_shared_node(struct btrfs_root *root,
1157 struct walk_control *wc, int level)
1159 struct shared_node *node;
1160 struct shared_node *dest;
1163 if (level == wc->root_level)
1166 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1170 BUG_ON(i >= BTRFS_MAX_LEVEL);
1172 node = wc->nodes[wc->active_node];
1173 wc->nodes[wc->active_node] = NULL;
1174 wc->active_node = i;
1176 dest = wc->nodes[wc->active_node];
1177 if (wc->active_node < wc->root_level ||
1178 btrfs_root_refs(&root->root_item) > 0) {
1179 BUG_ON(node->refs <= 1);
1180 splice_shared_node(node, dest);
1182 BUG_ON(node->refs < 2);
1191 * 1 - if the root with id child_root_id is a child of root parent_root_id
1192 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1193 * has other root(s) as parent(s)
1194 * 2 - if the root child_root_id doesn't have any parent roots
1196 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1199 struct btrfs_path path;
1200 struct btrfs_key key;
1201 struct extent_buffer *leaf;
1205 btrfs_init_path(&path);
1207 key.objectid = parent_root_id;
1208 key.type = BTRFS_ROOT_REF_KEY;
1209 key.offset = child_root_id;
1210 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1214 btrfs_release_path(&path);
1218 key.objectid = child_root_id;
1219 key.type = BTRFS_ROOT_BACKREF_KEY;
1221 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1227 leaf = path.nodes[0];
1228 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1229 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1232 leaf = path.nodes[0];
1235 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1236 if (key.objectid != child_root_id ||
1237 key.type != BTRFS_ROOT_BACKREF_KEY)
1242 if (key.offset == parent_root_id) {
1243 btrfs_release_path(&path);
1250 btrfs_release_path(&path);
1253 return has_parent ? 0 : 2;
1256 static int process_dir_item(struct btrfs_root *root,
1257 struct extent_buffer *eb,
1258 int slot, struct btrfs_key *key,
1259 struct shared_node *active_node)
1269 struct btrfs_dir_item *di;
1270 struct inode_record *rec;
1271 struct cache_tree *root_cache;
1272 struct cache_tree *inode_cache;
1273 struct btrfs_key location;
1274 char namebuf[BTRFS_NAME_LEN];
1276 root_cache = &active_node->root_cache;
1277 inode_cache = &active_node->inode_cache;
1278 rec = active_node->current;
1279 rec->found_dir_item = 1;
1281 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1282 total = btrfs_item_size_nr(eb, slot);
1283 while (cur < total) {
1285 btrfs_dir_item_key_to_cpu(eb, di, &location);
1286 name_len = btrfs_dir_name_len(eb, di);
1287 data_len = btrfs_dir_data_len(eb, di);
1288 filetype = btrfs_dir_type(eb, di);
1290 rec->found_size += name_len;
1291 if (name_len <= BTRFS_NAME_LEN) {
1295 len = BTRFS_NAME_LEN;
1296 error = REF_ERR_NAME_TOO_LONG;
1298 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1300 if (location.type == BTRFS_INODE_ITEM_KEY) {
1301 add_inode_backref(inode_cache, location.objectid,
1302 key->objectid, key->offset, namebuf,
1303 len, filetype, key->type, error);
1304 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1305 add_inode_backref(root_cache, location.objectid,
1306 key->objectid, key->offset,
1307 namebuf, len, filetype,
1310 fprintf(stderr, "invalid location in dir item %u\n",
1312 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1313 key->objectid, key->offset, namebuf,
1314 len, filetype, key->type, error);
1317 len = sizeof(*di) + name_len + data_len;
1318 di = (struct btrfs_dir_item *)((char *)di + len);
1321 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1322 rec->errors |= I_ERR_DUP_DIR_INDEX;
1327 static int process_inode_ref(struct extent_buffer *eb,
1328 int slot, struct btrfs_key *key,
1329 struct shared_node *active_node)
1337 struct cache_tree *inode_cache;
1338 struct btrfs_inode_ref *ref;
1339 char namebuf[BTRFS_NAME_LEN];
1341 inode_cache = &active_node->inode_cache;
1343 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1344 total = btrfs_item_size_nr(eb, slot);
1345 while (cur < total) {
1346 name_len = btrfs_inode_ref_name_len(eb, ref);
1347 index = btrfs_inode_ref_index(eb, ref);
1348 if (name_len <= BTRFS_NAME_LEN) {
1352 len = BTRFS_NAME_LEN;
1353 error = REF_ERR_NAME_TOO_LONG;
1355 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1356 add_inode_backref(inode_cache, key->objectid, key->offset,
1357 index, namebuf, len, 0, key->type, error);
1359 len = sizeof(*ref) + name_len;
1360 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1366 static int process_inode_extref(struct extent_buffer *eb,
1367 int slot, struct btrfs_key *key,
1368 struct shared_node *active_node)
1377 struct cache_tree *inode_cache;
1378 struct btrfs_inode_extref *extref;
1379 char namebuf[BTRFS_NAME_LEN];
1381 inode_cache = &active_node->inode_cache;
1383 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1384 total = btrfs_item_size_nr(eb, slot);
1385 while (cur < total) {
1386 name_len = btrfs_inode_extref_name_len(eb, extref);
1387 index = btrfs_inode_extref_index(eb, extref);
1388 parent = btrfs_inode_extref_parent(eb, extref);
1389 if (name_len <= BTRFS_NAME_LEN) {
1393 len = BTRFS_NAME_LEN;
1394 error = REF_ERR_NAME_TOO_LONG;
1396 read_extent_buffer(eb, namebuf,
1397 (unsigned long)(extref + 1), len);
1398 add_inode_backref(inode_cache, key->objectid, parent,
1399 index, namebuf, len, 0, key->type, error);
1401 len = sizeof(*extref) + name_len;
1402 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1409 static int count_csum_range(struct btrfs_root *root, u64 start,
1410 u64 len, u64 *found)
1412 struct btrfs_key key;
1413 struct btrfs_path path;
1414 struct extent_buffer *leaf;
1419 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1421 btrfs_init_path(&path);
1423 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1425 key.type = BTRFS_EXTENT_CSUM_KEY;
1427 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1431 if (ret > 0 && path.slots[0] > 0) {
1432 leaf = path.nodes[0];
1433 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1434 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1435 key.type == BTRFS_EXTENT_CSUM_KEY)
1440 leaf = path.nodes[0];
1441 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1442 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1447 leaf = path.nodes[0];
1450 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1451 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1452 key.type != BTRFS_EXTENT_CSUM_KEY)
1455 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1456 if (key.offset >= start + len)
1459 if (key.offset > start)
1462 size = btrfs_item_size_nr(leaf, path.slots[0]);
1463 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1464 if (csum_end > start) {
1465 size = min(csum_end - start, len);
1474 btrfs_release_path(&path);
1480 static int process_file_extent(struct btrfs_root *root,
1481 struct extent_buffer *eb,
1482 int slot, struct btrfs_key *key,
1483 struct shared_node *active_node)
1485 struct inode_record *rec;
1486 struct btrfs_file_extent_item *fi;
1488 u64 disk_bytenr = 0;
1489 u64 extent_offset = 0;
1490 u64 mask = root->sectorsize - 1;
1494 rec = active_node->current;
1495 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1496 rec->found_file_extent = 1;
1498 if (rec->extent_start == (u64)-1) {
1499 rec->extent_start = key->offset;
1500 rec->extent_end = key->offset;
1503 if (rec->extent_end > key->offset)
1504 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1505 else if (rec->extent_end < key->offset) {
1506 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1507 key->offset - rec->extent_end);
1512 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1513 extent_type = btrfs_file_extent_type(eb, fi);
1515 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1516 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1518 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1519 rec->found_size += num_bytes;
1520 num_bytes = (num_bytes + mask) & ~mask;
1521 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1522 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1523 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1524 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1525 extent_offset = btrfs_file_extent_offset(eb, fi);
1526 if (num_bytes == 0 || (num_bytes & mask))
1527 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1528 if (num_bytes + extent_offset >
1529 btrfs_file_extent_ram_bytes(eb, fi))
1530 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1531 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1532 (btrfs_file_extent_compression(eb, fi) ||
1533 btrfs_file_extent_encryption(eb, fi) ||
1534 btrfs_file_extent_other_encoding(eb, fi)))
1535 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1536 if (disk_bytenr > 0)
1537 rec->found_size += num_bytes;
1539 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1541 rec->extent_end = key->offset + num_bytes;
1544 * The data reloc tree will copy full extents into its inode and then
1545 * copy the corresponding csums. Because the extent it copied could be
1546 * a preallocated extent that hasn't been written to yet there may be no
1547 * csums to copy, ergo we won't have csums for our file extent. This is
1548 * ok so just don't bother checking csums if the inode belongs to the
1551 if (disk_bytenr > 0 &&
1552 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1554 if (btrfs_file_extent_compression(eb, fi))
1555 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1557 disk_bytenr += extent_offset;
1559 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1562 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1564 rec->found_csum_item = 1;
1565 if (found < num_bytes)
1566 rec->some_csum_missing = 1;
1567 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1569 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1575 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1576 struct walk_control *wc)
1578 struct btrfs_key key;
1582 struct cache_tree *inode_cache;
1583 struct shared_node *active_node;
1585 if (wc->root_level == wc->active_node &&
1586 btrfs_root_refs(&root->root_item) == 0)
1589 active_node = wc->nodes[wc->active_node];
1590 inode_cache = &active_node->inode_cache;
1591 nritems = btrfs_header_nritems(eb);
1592 for (i = 0; i < nritems; i++) {
1593 btrfs_item_key_to_cpu(eb, &key, i);
1595 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1597 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1600 if (active_node->current == NULL ||
1601 active_node->current->ino < key.objectid) {
1602 if (active_node->current) {
1603 active_node->current->checked = 1;
1604 maybe_free_inode_rec(inode_cache,
1605 active_node->current);
1607 active_node->current = get_inode_rec(inode_cache,
1611 case BTRFS_DIR_ITEM_KEY:
1612 case BTRFS_DIR_INDEX_KEY:
1613 ret = process_dir_item(root, eb, i, &key, active_node);
1615 case BTRFS_INODE_REF_KEY:
1616 ret = process_inode_ref(eb, i, &key, active_node);
1618 case BTRFS_INODE_EXTREF_KEY:
1619 ret = process_inode_extref(eb, i, &key, active_node);
1621 case BTRFS_INODE_ITEM_KEY:
1622 ret = process_inode_item(eb, i, &key, active_node);
1624 case BTRFS_EXTENT_DATA_KEY:
1625 ret = process_file_extent(root, eb, i, &key,
1635 static void reada_walk_down(struct btrfs_root *root,
1636 struct extent_buffer *node, int slot)
1645 level = btrfs_header_level(node);
1649 nritems = btrfs_header_nritems(node);
1650 blocksize = btrfs_level_size(root, level - 1);
1651 for (i = slot; i < nritems; i++) {
1652 bytenr = btrfs_node_blockptr(node, i);
1653 ptr_gen = btrfs_node_ptr_generation(node, i);
1654 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1659 * Check the child node/leaf by the following condition:
1660 * 1. the first item key of the node/leaf should be the same with the one
1662 * 2. block in parent node should match the child node/leaf.
1663 * 3. generation of parent node and child's header should be consistent.
1665 * Or the child node/leaf pointed by the key in parent is not valid.
1667 * We hope to check leaf owner too, but since subvol may share leaves,
1668 * which makes leaf owner check not so strong, key check should be
1669 * sufficient enough for that case.
1671 static int check_child_node(struct btrfs_root *root,
1672 struct extent_buffer *parent, int slot,
1673 struct extent_buffer *child)
1675 struct btrfs_key parent_key;
1676 struct btrfs_key child_key;
1679 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1680 if (btrfs_header_level(child) == 0)
1681 btrfs_item_key_to_cpu(child, &child_key, 0);
1683 btrfs_node_key_to_cpu(child, &child_key, 0);
1685 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1688 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1689 parent_key.objectid, parent_key.type, parent_key.offset,
1690 child_key.objectid, child_key.type, child_key.offset);
1692 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1694 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1695 btrfs_node_blockptr(parent, slot),
1696 btrfs_header_bytenr(child));
1698 if (btrfs_node_ptr_generation(parent, slot) !=
1699 btrfs_header_generation(child)) {
1701 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1702 btrfs_header_generation(child),
1703 btrfs_node_ptr_generation(parent, slot));
1708 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1709 struct walk_control *wc, int *level)
1711 enum btrfs_tree_block_status status;
1714 struct extent_buffer *next;
1715 struct extent_buffer *cur;
1720 WARN_ON(*level < 0);
1721 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1722 ret = btrfs_lookup_extent_info(NULL, root,
1723 path->nodes[*level]->start,
1724 *level, 1, &refs, NULL);
1731 ret = enter_shared_node(root, path->nodes[*level]->start,
1739 while (*level >= 0) {
1740 WARN_ON(*level < 0);
1741 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1742 cur = path->nodes[*level];
1744 if (btrfs_header_level(cur) != *level)
1747 if (path->slots[*level] >= btrfs_header_nritems(cur))
1750 ret = process_one_leaf(root, cur, wc);
1755 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1756 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1757 blocksize = btrfs_level_size(root, *level - 1);
1758 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1764 ret = enter_shared_node(root, bytenr, refs,
1767 path->slots[*level]++;
1772 next = btrfs_find_tree_block(root, bytenr, blocksize);
1773 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1774 free_extent_buffer(next);
1775 reada_walk_down(root, cur, path->slots[*level]);
1776 next = read_tree_block(root, bytenr, blocksize,
1778 if (!extent_buffer_uptodate(next)) {
1779 struct btrfs_key node_key;
1781 btrfs_node_key_to_cpu(path->nodes[*level],
1783 path->slots[*level]);
1784 btrfs_add_corrupt_extent_record(root->fs_info,
1786 path->nodes[*level]->start,
1787 root->leafsize, *level);
1793 ret = check_child_node(root, cur, path->slots[*level], next);
1799 if (btrfs_is_leaf(next))
1800 status = btrfs_check_leaf(root, NULL, next);
1802 status = btrfs_check_node(root, NULL, next);
1803 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1804 free_extent_buffer(next);
1809 *level = *level - 1;
1810 free_extent_buffer(path->nodes[*level]);
1811 path->nodes[*level] = next;
1812 path->slots[*level] = 0;
1815 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1819 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1820 struct walk_control *wc, int *level)
1823 struct extent_buffer *leaf;
1825 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1826 leaf = path->nodes[i];
1827 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1832 free_extent_buffer(path->nodes[*level]);
1833 path->nodes[*level] = NULL;
1834 BUG_ON(*level > wc->active_node);
1835 if (*level == wc->active_node)
1836 leave_shared_node(root, wc, *level);
1843 static int check_root_dir(struct inode_record *rec)
1845 struct inode_backref *backref;
1848 if (!rec->found_inode_item || rec->errors)
1850 if (rec->nlink != 1 || rec->found_link != 0)
1852 if (list_empty(&rec->backrefs))
1854 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1855 if (!backref->found_inode_ref)
1857 if (backref->index != 0 || backref->namelen != 2 ||
1858 memcmp(backref->name, "..", 2))
1860 if (backref->found_dir_index || backref->found_dir_item)
1867 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1868 struct btrfs_root *root, struct btrfs_path *path,
1869 struct inode_record *rec)
1871 struct btrfs_inode_item *ei;
1872 struct btrfs_key key;
1875 key.objectid = rec->ino;
1876 key.type = BTRFS_INODE_ITEM_KEY;
1877 key.offset = (u64)-1;
1879 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1883 if (!path->slots[0]) {
1890 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1891 if (key.objectid != rec->ino) {
1896 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1897 struct btrfs_inode_item);
1898 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1899 btrfs_mark_buffer_dirty(path->nodes[0]);
1900 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1901 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1902 root->root_key.objectid);
1904 btrfs_release_path(path);
1908 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1909 struct btrfs_root *root,
1910 struct btrfs_path *path,
1911 struct inode_record *rec)
1915 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1916 btrfs_release_path(path);
1918 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1922 static int repair_inode_nbytes(struct btrfs_trans_handle *trans,
1923 struct btrfs_root *root,
1924 struct btrfs_path *path,
1925 struct inode_record *rec)
1927 struct btrfs_inode_item *ei;
1928 struct btrfs_key key;
1931 key.objectid = rec->ino;
1932 key.type = BTRFS_INODE_ITEM_KEY;
1935 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1942 /* Since ret == 0, no need to check anything */
1943 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1944 struct btrfs_inode_item);
1945 btrfs_set_inode_nbytes(path->nodes[0], ei, rec->found_size);
1946 btrfs_mark_buffer_dirty(path->nodes[0]);
1947 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
1948 printf("reset nbytes for ino %llu root %llu\n",
1949 rec->ino, root->root_key.objectid);
1951 btrfs_release_path(path);
1955 static int add_missing_dir_index(struct btrfs_root *root,
1956 struct cache_tree *inode_cache,
1957 struct inode_record *rec,
1958 struct inode_backref *backref)
1960 struct btrfs_path *path;
1961 struct btrfs_trans_handle *trans;
1962 struct btrfs_dir_item *dir_item;
1963 struct extent_buffer *leaf;
1964 struct btrfs_key key;
1965 struct btrfs_disk_key disk_key;
1966 struct inode_record *dir_rec;
1967 unsigned long name_ptr;
1968 u32 data_size = sizeof(*dir_item) + backref->namelen;
1971 path = btrfs_alloc_path();
1975 trans = btrfs_start_transaction(root, 1);
1976 if (IS_ERR(trans)) {
1977 btrfs_free_path(path);
1978 return PTR_ERR(trans);
1981 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1982 (unsigned long long)rec->ino);
1983 key.objectid = backref->dir;
1984 key.type = BTRFS_DIR_INDEX_KEY;
1985 key.offset = backref->index;
1987 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1990 leaf = path->nodes[0];
1991 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
1993 disk_key.objectid = cpu_to_le64(rec->ino);
1994 disk_key.type = BTRFS_INODE_ITEM_KEY;
1995 disk_key.offset = 0;
1997 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
1998 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
1999 btrfs_set_dir_data_len(leaf, dir_item, 0);
2000 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
2001 name_ptr = (unsigned long)(dir_item + 1);
2002 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
2003 btrfs_mark_buffer_dirty(leaf);
2004 btrfs_free_path(path);
2005 btrfs_commit_transaction(trans, root);
2007 backref->found_dir_index = 1;
2008 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
2011 dir_rec->found_size += backref->namelen;
2012 if (dir_rec->found_size == dir_rec->isize &&
2013 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
2014 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
2015 if (dir_rec->found_size != dir_rec->isize)
2016 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
2021 static int delete_dir_index(struct btrfs_root *root,
2022 struct cache_tree *inode_cache,
2023 struct inode_record *rec,
2024 struct inode_backref *backref)
2026 struct btrfs_trans_handle *trans;
2027 struct btrfs_dir_item *di;
2028 struct btrfs_path *path;
2031 path = btrfs_alloc_path();
2035 trans = btrfs_start_transaction(root, 1);
2036 if (IS_ERR(trans)) {
2037 btrfs_free_path(path);
2038 return PTR_ERR(trans);
2042 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2043 (unsigned long long)backref->dir,
2044 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2045 (unsigned long long)root->objectid);
2047 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2048 backref->name, backref->namelen,
2049 backref->index, -1);
2052 btrfs_free_path(path);
2053 btrfs_commit_transaction(trans, root);
2060 ret = btrfs_del_item(trans, root, path);
2062 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2064 btrfs_free_path(path);
2065 btrfs_commit_transaction(trans, root);
2069 static int create_inode_item(struct btrfs_root *root,
2070 struct inode_record *rec,
2071 struct inode_backref *backref, int root_dir)
2073 struct btrfs_trans_handle *trans;
2074 struct btrfs_inode_item inode_item;
2075 time_t now = time(NULL);
2078 trans = btrfs_start_transaction(root, 1);
2079 if (IS_ERR(trans)) {
2080 ret = PTR_ERR(trans);
2084 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2085 "be incomplete, please check permissions and content after "
2086 "the fsck completes.\n", (unsigned long long)root->objectid,
2087 (unsigned long long)rec->ino);
2089 memset(&inode_item, 0, sizeof(inode_item));
2090 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2092 btrfs_set_stack_inode_nlink(&inode_item, 1);
2094 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2095 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2096 if (rec->found_dir_item) {
2097 if (rec->found_file_extent)
2098 fprintf(stderr, "root %llu inode %llu has both a dir "
2099 "item and extents, unsure if it is a dir or a "
2100 "regular file so setting it as a directory\n",
2101 (unsigned long long)root->objectid,
2102 (unsigned long long)rec->ino);
2103 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2104 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2105 } else if (!rec->found_dir_item) {
2106 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2107 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2109 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2110 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2111 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2112 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2113 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2114 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2115 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2116 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2118 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2120 btrfs_commit_transaction(trans, root);
2124 static int repair_inode_backrefs(struct btrfs_root *root,
2125 struct inode_record *rec,
2126 struct cache_tree *inode_cache,
2129 struct inode_backref *tmp, *backref;
2130 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2134 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2135 if (!delete && rec->ino == root_dirid) {
2136 if (!rec->found_inode_item) {
2137 ret = create_inode_item(root, rec, backref, 1);
2144 /* Index 0 for root dir's are special, don't mess with it */
2145 if (rec->ino == root_dirid && backref->index == 0)
2149 ((backref->found_dir_index && !backref->found_inode_ref) ||
2150 (backref->found_dir_index && backref->found_inode_ref &&
2151 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2152 ret = delete_dir_index(root, inode_cache, rec, backref);
2156 list_del(&backref->list);
2160 if (!delete && !backref->found_dir_index &&
2161 backref->found_dir_item && backref->found_inode_ref) {
2162 ret = add_missing_dir_index(root, inode_cache, rec,
2167 if (backref->found_dir_item &&
2168 backref->found_dir_index &&
2169 backref->found_dir_index) {
2170 if (!backref->errors &&
2171 backref->found_inode_ref) {
2172 list_del(&backref->list);
2178 if (!delete && (!backref->found_dir_index &&
2179 !backref->found_dir_item &&
2180 backref->found_inode_ref)) {
2181 struct btrfs_trans_handle *trans;
2182 struct btrfs_key location;
2184 ret = check_dir_conflict(root, backref->name,
2190 * let nlink fixing routine to handle it,
2191 * which can do it better.
2196 location.objectid = rec->ino;
2197 location.type = BTRFS_INODE_ITEM_KEY;
2198 location.offset = 0;
2200 trans = btrfs_start_transaction(root, 1);
2201 if (IS_ERR(trans)) {
2202 ret = PTR_ERR(trans);
2205 fprintf(stderr, "adding missing dir index/item pair "
2207 (unsigned long long)rec->ino);
2208 ret = btrfs_insert_dir_item(trans, root, backref->name,
2210 backref->dir, &location,
2211 imode_to_type(rec->imode),
2214 btrfs_commit_transaction(trans, root);
2218 if (!delete && (backref->found_inode_ref &&
2219 backref->found_dir_index &&
2220 backref->found_dir_item &&
2221 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2222 !rec->found_inode_item)) {
2223 ret = create_inode_item(root, rec, backref, 0);
2230 return ret ? ret : repaired;
2234 * To determine the file type for nlink/inode_item repair
2236 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2237 * Return -ENOENT if file type is not found.
2239 static int find_file_type(struct inode_record *rec, u8 *type)
2241 struct inode_backref *backref;
2243 /* For inode item recovered case */
2244 if (rec->found_inode_item) {
2245 *type = imode_to_type(rec->imode);
2249 list_for_each_entry(backref, &rec->backrefs, list) {
2250 if (backref->found_dir_index || backref->found_dir_item) {
2251 *type = backref->filetype;
2259 * To determine the file name for nlink repair
2261 * Return 0 if file name is found, set name and namelen.
2262 * Return -ENOENT if file name is not found.
2264 static int find_file_name(struct inode_record *rec,
2265 char *name, int *namelen)
2267 struct inode_backref *backref;
2269 list_for_each_entry(backref, &rec->backrefs, list) {
2270 if (backref->found_dir_index || backref->found_dir_item ||
2271 backref->found_inode_ref) {
2272 memcpy(name, backref->name, backref->namelen);
2273 *namelen = backref->namelen;
2280 /* Reset the nlink of the inode to the correct one */
2281 static int reset_nlink(struct btrfs_trans_handle *trans,
2282 struct btrfs_root *root,
2283 struct btrfs_path *path,
2284 struct inode_record *rec)
2286 struct inode_backref *backref;
2287 struct inode_backref *tmp;
2288 struct btrfs_key key;
2289 struct btrfs_inode_item *inode_item;
2292 /* We don't believe this either, reset it and iterate backref */
2293 rec->found_link = 0;
2295 /* Remove all backref including the valid ones */
2296 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2297 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2298 backref->index, backref->name,
2299 backref->namelen, 0);
2303 /* remove invalid backref, so it won't be added back */
2304 if (!(backref->found_dir_index &&
2305 backref->found_dir_item &&
2306 backref->found_inode_ref)) {
2307 list_del(&backref->list);
2314 /* Set nlink to 0 */
2315 key.objectid = rec->ino;
2316 key.type = BTRFS_INODE_ITEM_KEY;
2318 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2325 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2326 struct btrfs_inode_item);
2327 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2328 btrfs_mark_buffer_dirty(path->nodes[0]);
2329 btrfs_release_path(path);
2332 * Add back valid inode_ref/dir_item/dir_index,
2333 * add_link() will handle the nlink inc, so new nlink must be correct
2335 list_for_each_entry(backref, &rec->backrefs, list) {
2336 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2337 backref->name, backref->namelen,
2338 backref->ref_type, &backref->index, 1);
2343 btrfs_release_path(path);
2347 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2348 struct btrfs_root *root,
2349 struct btrfs_path *path,
2350 struct inode_record *rec)
2352 char *dir_name = "lost+found";
2353 char namebuf[BTRFS_NAME_LEN] = {0};
2358 int name_recovered = 0;
2359 int type_recovered = 0;
2363 * Get file name and type first before these invalid inode ref
2364 * are deleted by remove_all_invalid_backref()
2366 name_recovered = !find_file_name(rec, namebuf, &namelen);
2367 type_recovered = !find_file_type(rec, &type);
2369 if (!name_recovered) {
2370 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2371 rec->ino, rec->ino);
2372 namelen = count_digits(rec->ino);
2373 sprintf(namebuf, "%llu", rec->ino);
2376 if (!type_recovered) {
2377 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2379 type = BTRFS_FT_REG_FILE;
2383 ret = reset_nlink(trans, root, path, rec);
2386 "Failed to reset nlink for inode %llu: %s\n",
2387 rec->ino, strerror(-ret));
2391 if (rec->found_link == 0) {
2392 lost_found_ino = root->highest_inode;
2393 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2398 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2399 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2402 fprintf(stderr, "Failed to create '%s' dir: %s",
2403 dir_name, strerror(-ret));
2406 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2407 namebuf, namelen, type, NULL, 1);
2409 * Add ".INO" suffix several times to handle case where
2410 * "FILENAME.INO" is already taken by another file.
2412 while (ret == -EEXIST) {
2414 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2416 if (namelen + count_digits(rec->ino) + 1 >
2421 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2423 namelen += count_digits(rec->ino) + 1;
2424 ret = btrfs_add_link(trans, root, rec->ino,
2425 lost_found_ino, namebuf,
2426 namelen, type, NULL, 1);
2430 "Failed to link the inode %llu to %s dir: %s",
2431 rec->ino, dir_name, strerror(-ret));
2435 * Just increase the found_link, don't actually add the
2436 * backref. This will make things easier and this inode
2437 * record will be freed after the repair is done.
2438 * So fsck will not report problem about this inode.
2441 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2442 namelen, namebuf, dir_name);
2444 printf("Fixed the nlink of inode %llu\n", rec->ino);
2447 * Clear the flag anyway, or we will loop forever for the same inode
2448 * as it will not be removed from the bad inode list and the dead loop
2451 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2452 btrfs_release_path(path);
2457 * Check if there is any normal(reg or prealloc) file extent for given
2459 * This is used to determine the file type when neither its dir_index/item or
2460 * inode_item exists.
2462 * This will *NOT* report error, if any error happens, just consider it does
2463 * not have any normal file extent.
2465 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2467 struct btrfs_path *path;
2468 struct btrfs_key key;
2469 struct btrfs_key found_key;
2470 struct btrfs_file_extent_item *fi;
2474 path = btrfs_alloc_path();
2478 key.type = BTRFS_EXTENT_DATA_KEY;
2481 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2486 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2487 ret = btrfs_next_leaf(root, path);
2494 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2496 if (found_key.objectid != ino ||
2497 found_key.type != BTRFS_EXTENT_DATA_KEY)
2499 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2500 struct btrfs_file_extent_item);
2501 type = btrfs_file_extent_type(path->nodes[0], fi);
2502 if (type != BTRFS_FILE_EXTENT_INLINE) {
2508 btrfs_free_path(path);
2512 static u32 btrfs_type_to_imode(u8 type)
2514 static u32 imode_by_btrfs_type[] = {
2515 [BTRFS_FT_REG_FILE] = S_IFREG,
2516 [BTRFS_FT_DIR] = S_IFDIR,
2517 [BTRFS_FT_CHRDEV] = S_IFCHR,
2518 [BTRFS_FT_BLKDEV] = S_IFBLK,
2519 [BTRFS_FT_FIFO] = S_IFIFO,
2520 [BTRFS_FT_SOCK] = S_IFSOCK,
2521 [BTRFS_FT_SYMLINK] = S_IFLNK,
2524 return imode_by_btrfs_type[(type)];
2527 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2528 struct btrfs_root *root,
2529 struct btrfs_path *path,
2530 struct inode_record *rec)
2534 int type_recovered = 0;
2537 printf("Trying to rebuild inode:%llu\n", rec->ino);
2539 type_recovered = !find_file_type(rec, &filetype);
2542 * Try to determine inode type if type not found.
2544 * For found regular file extent, it must be FILE.
2545 * For found dir_item/index, it must be DIR.
2547 * For undetermined one, use FILE as fallback.
2550 * 1. If found backref(inode_index/item is already handled) to it,
2552 * Need new inode-inode ref structure to allow search for that.
2554 if (!type_recovered) {
2555 if (rec->found_file_extent &&
2556 find_normal_file_extent(root, rec->ino)) {
2558 filetype = BTRFS_FT_REG_FILE;
2559 } else if (rec->found_dir_item) {
2561 filetype = BTRFS_FT_DIR;
2562 } else if (!list_empty(&rec->orphan_extents)) {
2564 filetype = BTRFS_FT_REG_FILE;
2566 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2569 filetype = BTRFS_FT_REG_FILE;
2573 ret = btrfs_new_inode(trans, root, rec->ino,
2574 mode | btrfs_type_to_imode(filetype));
2579 * Here inode rebuild is done, we only rebuild the inode item,
2580 * don't repair the nlink(like move to lost+found).
2581 * That is the job of nlink repair.
2583 * We just fill the record and return
2585 rec->found_dir_item = 1;
2586 rec->imode = mode | btrfs_type_to_imode(filetype);
2588 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2589 /* Ensure the inode_nlinks repair function will be called */
2590 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2595 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2596 struct btrfs_root *root,
2597 struct btrfs_path *path,
2598 struct inode_record *rec)
2600 struct orphan_data_extent *orphan;
2601 struct orphan_data_extent *tmp;
2604 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2606 * Check for conflicting file extents
2608 * Here we don't know whether the extents is compressed or not,
2609 * so we can only assume it not compressed nor data offset,
2610 * and use its disk_len as extent length.
2612 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2613 orphan->offset, orphan->disk_len, 0);
2614 btrfs_release_path(path);
2619 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2620 orphan->disk_bytenr, orphan->disk_len);
2621 ret = btrfs_free_extent(trans,
2622 root->fs_info->extent_root,
2623 orphan->disk_bytenr, orphan->disk_len,
2624 0, root->objectid, orphan->objectid,
2629 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2630 orphan->offset, orphan->disk_bytenr,
2631 orphan->disk_len, orphan->disk_len);
2635 /* Update file size info */
2636 rec->found_size += orphan->disk_len;
2637 if (rec->found_size == rec->nbytes)
2638 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2640 /* Update the file extent hole info too */
2641 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2645 if (RB_EMPTY_ROOT(&rec->holes))
2646 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2648 list_del(&orphan->list);
2651 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2656 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2657 struct btrfs_root *root,
2658 struct btrfs_path *path,
2659 struct inode_record *rec)
2661 struct rb_node *node;
2662 struct file_extent_hole *hole;
2665 node = rb_first(&rec->holes);
2668 hole = rb_entry(node, struct file_extent_hole, node);
2669 ret = btrfs_punch_hole(trans, root, rec->ino,
2670 hole->start, hole->len);
2673 ret = del_file_extent_hole(&rec->holes, hole->start,
2677 if (RB_EMPTY_ROOT(&rec->holes))
2678 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2679 node = rb_first(&rec->holes);
2681 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2682 rec->ino, root->objectid);
2687 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2689 struct btrfs_trans_handle *trans;
2690 struct btrfs_path *path;
2693 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2694 I_ERR_NO_ORPHAN_ITEM |
2695 I_ERR_LINK_COUNT_WRONG |
2696 I_ERR_NO_INODE_ITEM |
2697 I_ERR_FILE_EXTENT_ORPHAN |
2698 I_ERR_FILE_EXTENT_DISCOUNT|
2699 I_ERR_FILE_NBYTES_WRONG)))
2702 path = btrfs_alloc_path();
2707 * For nlink repair, it may create a dir and add link, so
2708 * 2 for parent(256)'s dir_index and dir_item
2709 * 2 for lost+found dir's inode_item and inode_ref
2710 * 1 for the new inode_ref of the file
2711 * 2 for lost+found dir's dir_index and dir_item for the file
2713 trans = btrfs_start_transaction(root, 7);
2714 if (IS_ERR(trans)) {
2715 btrfs_free_path(path);
2716 return PTR_ERR(trans);
2719 if (rec->errors & I_ERR_NO_INODE_ITEM)
2720 ret = repair_inode_no_item(trans, root, path, rec);
2721 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2722 ret = repair_inode_orphan_extent(trans, root, path, rec);
2723 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2724 ret = repair_inode_discount_extent(trans, root, path, rec);
2725 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2726 ret = repair_inode_isize(trans, root, path, rec);
2727 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2728 ret = repair_inode_orphan_item(trans, root, path, rec);
2729 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2730 ret = repair_inode_nlinks(trans, root, path, rec);
2731 if (!ret && rec->errors & I_ERR_FILE_NBYTES_WRONG)
2732 ret = repair_inode_nbytes(trans, root, path, rec);
2733 btrfs_commit_transaction(trans, root);
2734 btrfs_free_path(path);
2738 static int check_inode_recs(struct btrfs_root *root,
2739 struct cache_tree *inode_cache)
2741 struct cache_extent *cache;
2742 struct ptr_node *node;
2743 struct inode_record *rec;
2744 struct inode_backref *backref;
2749 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2751 if (btrfs_root_refs(&root->root_item) == 0) {
2752 if (!cache_tree_empty(inode_cache))
2753 fprintf(stderr, "warning line %d\n", __LINE__);
2758 * We need to record the highest inode number for later 'lost+found'
2760 * We must select a ino not used/refered by any existing inode, or
2761 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2762 * this may cause 'lost+found' dir has wrong nlinks.
2764 cache = last_cache_extent(inode_cache);
2766 node = container_of(cache, struct ptr_node, cache);
2768 if (rec->ino > root->highest_inode)
2769 root->highest_inode = rec->ino;
2773 * We need to repair backrefs first because we could change some of the
2774 * errors in the inode recs.
2776 * We also need to go through and delete invalid backrefs first and then
2777 * add the correct ones second. We do this because we may get EEXIST
2778 * when adding back the correct index because we hadn't yet deleted the
2781 * For example, if we were missing a dir index then the directories
2782 * isize would be wrong, so if we fixed the isize to what we thought it
2783 * would be and then fixed the backref we'd still have a invalid fs, so
2784 * we need to add back the dir index and then check to see if the isize
2789 if (stage == 3 && !err)
2792 cache = search_cache_extent(inode_cache, 0);
2793 while (repair && cache) {
2794 node = container_of(cache, struct ptr_node, cache);
2796 cache = next_cache_extent(cache);
2798 /* Need to free everything up and rescan */
2800 remove_cache_extent(inode_cache, &node->cache);
2802 free_inode_rec(rec);
2806 if (list_empty(&rec->backrefs))
2809 ret = repair_inode_backrefs(root, rec, inode_cache,
2823 rec = get_inode_rec(inode_cache, root_dirid, 0);
2825 ret = check_root_dir(rec);
2827 fprintf(stderr, "root %llu root dir %llu error\n",
2828 (unsigned long long)root->root_key.objectid,
2829 (unsigned long long)root_dirid);
2830 print_inode_error(root, rec);
2835 struct btrfs_trans_handle *trans;
2837 trans = btrfs_start_transaction(root, 1);
2838 if (IS_ERR(trans)) {
2839 err = PTR_ERR(trans);
2844 "root %llu missing its root dir, recreating\n",
2845 (unsigned long long)root->objectid);
2847 ret = btrfs_make_root_dir(trans, root, root_dirid);
2850 btrfs_commit_transaction(trans, root);
2854 fprintf(stderr, "root %llu root dir %llu not found\n",
2855 (unsigned long long)root->root_key.objectid,
2856 (unsigned long long)root_dirid);
2860 cache = search_cache_extent(inode_cache, 0);
2863 node = container_of(cache, struct ptr_node, cache);
2865 remove_cache_extent(inode_cache, &node->cache);
2867 if (rec->ino == root_dirid ||
2868 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2869 free_inode_rec(rec);
2873 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2874 ret = check_orphan_item(root, rec->ino);
2876 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2877 if (can_free_inode_rec(rec)) {
2878 free_inode_rec(rec);
2883 if (!rec->found_inode_item)
2884 rec->errors |= I_ERR_NO_INODE_ITEM;
2885 if (rec->found_link != rec->nlink)
2886 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2888 ret = try_repair_inode(root, rec);
2889 if (ret == 0 && can_free_inode_rec(rec)) {
2890 free_inode_rec(rec);
2896 if (!(repair && ret == 0))
2898 print_inode_error(root, rec);
2899 list_for_each_entry(backref, &rec->backrefs, list) {
2900 if (!backref->found_dir_item)
2901 backref->errors |= REF_ERR_NO_DIR_ITEM;
2902 if (!backref->found_dir_index)
2903 backref->errors |= REF_ERR_NO_DIR_INDEX;
2904 if (!backref->found_inode_ref)
2905 backref->errors |= REF_ERR_NO_INODE_REF;
2906 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2907 " namelen %u name %s filetype %d errors %x",
2908 (unsigned long long)backref->dir,
2909 (unsigned long long)backref->index,
2910 backref->namelen, backref->name,
2911 backref->filetype, backref->errors);
2912 print_ref_error(backref->errors);
2914 free_inode_rec(rec);
2916 return (error > 0) ? -1 : 0;
2919 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2922 struct cache_extent *cache;
2923 struct root_record *rec = NULL;
2926 cache = lookup_cache_extent(root_cache, objectid, 1);
2928 rec = container_of(cache, struct root_record, cache);
2930 rec = calloc(1, sizeof(*rec));
2931 rec->objectid = objectid;
2932 INIT_LIST_HEAD(&rec->backrefs);
2933 rec->cache.start = objectid;
2934 rec->cache.size = 1;
2936 ret = insert_cache_extent(root_cache, &rec->cache);
2942 static struct root_backref *get_root_backref(struct root_record *rec,
2943 u64 ref_root, u64 dir, u64 index,
2944 const char *name, int namelen)
2946 struct root_backref *backref;
2948 list_for_each_entry(backref, &rec->backrefs, list) {
2949 if (backref->ref_root != ref_root || backref->dir != dir ||
2950 backref->namelen != namelen)
2952 if (memcmp(name, backref->name, namelen))
2957 backref = malloc(sizeof(*backref) + namelen + 1);
2958 memset(backref, 0, sizeof(*backref));
2959 backref->ref_root = ref_root;
2961 backref->index = index;
2962 backref->namelen = namelen;
2963 memcpy(backref->name, name, namelen);
2964 backref->name[namelen] = '\0';
2965 list_add_tail(&backref->list, &rec->backrefs);
2969 static void free_root_record(struct cache_extent *cache)
2971 struct root_record *rec;
2972 struct root_backref *backref;
2974 rec = container_of(cache, struct root_record, cache);
2975 while (!list_empty(&rec->backrefs)) {
2976 backref = list_entry(rec->backrefs.next,
2977 struct root_backref, list);
2978 list_del(&backref->list);
2985 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2987 static int add_root_backref(struct cache_tree *root_cache,
2988 u64 root_id, u64 ref_root, u64 dir, u64 index,
2989 const char *name, int namelen,
2990 int item_type, int errors)
2992 struct root_record *rec;
2993 struct root_backref *backref;
2995 rec = get_root_rec(root_cache, root_id);
2996 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2998 backref->errors |= errors;
3000 if (item_type != BTRFS_DIR_ITEM_KEY) {
3001 if (backref->found_dir_index || backref->found_back_ref ||
3002 backref->found_forward_ref) {
3003 if (backref->index != index)
3004 backref->errors |= REF_ERR_INDEX_UNMATCH;
3006 backref->index = index;
3010 if (item_type == BTRFS_DIR_ITEM_KEY) {
3011 if (backref->found_forward_ref)
3013 backref->found_dir_item = 1;
3014 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
3015 backref->found_dir_index = 1;
3016 } else if (item_type == BTRFS_ROOT_REF_KEY) {
3017 if (backref->found_forward_ref)
3018 backref->errors |= REF_ERR_DUP_ROOT_REF;
3019 else if (backref->found_dir_item)
3021 backref->found_forward_ref = 1;
3022 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
3023 if (backref->found_back_ref)
3024 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
3025 backref->found_back_ref = 1;
3030 if (backref->found_forward_ref && backref->found_dir_item)
3031 backref->reachable = 1;
3035 static int merge_root_recs(struct btrfs_root *root,
3036 struct cache_tree *src_cache,
3037 struct cache_tree *dst_cache)
3039 struct cache_extent *cache;
3040 struct ptr_node *node;
3041 struct inode_record *rec;
3042 struct inode_backref *backref;
3045 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3046 free_inode_recs_tree(src_cache);
3051 cache = search_cache_extent(src_cache, 0);
3054 node = container_of(cache, struct ptr_node, cache);
3056 remove_cache_extent(src_cache, &node->cache);
3059 ret = is_child_root(root, root->objectid, rec->ino);
3065 list_for_each_entry(backref, &rec->backrefs, list) {
3066 BUG_ON(backref->found_inode_ref);
3067 if (backref->found_dir_item)
3068 add_root_backref(dst_cache, rec->ino,
3069 root->root_key.objectid, backref->dir,
3070 backref->index, backref->name,
3071 backref->namelen, BTRFS_DIR_ITEM_KEY,
3073 if (backref->found_dir_index)
3074 add_root_backref(dst_cache, rec->ino,
3075 root->root_key.objectid, backref->dir,
3076 backref->index, backref->name,
3077 backref->namelen, BTRFS_DIR_INDEX_KEY,
3081 free_inode_rec(rec);
3088 static int check_root_refs(struct btrfs_root *root,
3089 struct cache_tree *root_cache)
3091 struct root_record *rec;
3092 struct root_record *ref_root;
3093 struct root_backref *backref;
3094 struct cache_extent *cache;
3100 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3103 /* fixme: this can not detect circular references */
3106 cache = search_cache_extent(root_cache, 0);
3110 rec = container_of(cache, struct root_record, cache);
3111 cache = next_cache_extent(cache);
3113 if (rec->found_ref == 0)
3116 list_for_each_entry(backref, &rec->backrefs, list) {
3117 if (!backref->reachable)
3120 ref_root = get_root_rec(root_cache,
3122 if (ref_root->found_ref > 0)
3125 backref->reachable = 0;
3127 if (rec->found_ref == 0)
3133 cache = search_cache_extent(root_cache, 0);
3137 rec = container_of(cache, struct root_record, cache);
3138 cache = next_cache_extent(cache);
3140 if (rec->found_ref == 0 &&
3141 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3142 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3143 ret = check_orphan_item(root->fs_info->tree_root,
3149 * If we don't have a root item then we likely just have
3150 * a dir item in a snapshot for this root but no actual
3151 * ref key or anything so it's meaningless.
3153 if (!rec->found_root_item)
3156 fprintf(stderr, "fs tree %llu not referenced\n",
3157 (unsigned long long)rec->objectid);
3161 if (rec->found_ref > 0 && !rec->found_root_item)
3163 list_for_each_entry(backref, &rec->backrefs, list) {
3164 if (!backref->found_dir_item)
3165 backref->errors |= REF_ERR_NO_DIR_ITEM;
3166 if (!backref->found_dir_index)
3167 backref->errors |= REF_ERR_NO_DIR_INDEX;
3168 if (!backref->found_back_ref)
3169 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3170 if (!backref->found_forward_ref)
3171 backref->errors |= REF_ERR_NO_ROOT_REF;
3172 if (backref->reachable && backref->errors)
3179 fprintf(stderr, "fs tree %llu refs %u %s\n",
3180 (unsigned long long)rec->objectid, rec->found_ref,
3181 rec->found_root_item ? "" : "not found");
3183 list_for_each_entry(backref, &rec->backrefs, list) {
3184 if (!backref->reachable)
3186 if (!backref->errors && rec->found_root_item)
3188 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3189 " index %llu namelen %u name %s errors %x\n",
3190 (unsigned long long)backref->ref_root,
3191 (unsigned long long)backref->dir,
3192 (unsigned long long)backref->index,
3193 backref->namelen, backref->name,
3195 print_ref_error(backref->errors);
3198 return errors > 0 ? 1 : 0;
3201 static int process_root_ref(struct extent_buffer *eb, int slot,
3202 struct btrfs_key *key,
3203 struct cache_tree *root_cache)
3209 struct btrfs_root_ref *ref;
3210 char namebuf[BTRFS_NAME_LEN];
3213 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3215 dirid = btrfs_root_ref_dirid(eb, ref);
3216 index = btrfs_root_ref_sequence(eb, ref);
3217 name_len = btrfs_root_ref_name_len(eb, ref);
3219 if (name_len <= BTRFS_NAME_LEN) {
3223 len = BTRFS_NAME_LEN;
3224 error = REF_ERR_NAME_TOO_LONG;
3226 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3228 if (key->type == BTRFS_ROOT_REF_KEY) {
3229 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3230 index, namebuf, len, key->type, error);
3232 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3233 index, namebuf, len, key->type, error);
3238 static void free_corrupt_block(struct cache_extent *cache)
3240 struct btrfs_corrupt_block *corrupt;
3242 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3246 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3249 * Repair the btree of the given root.
3251 * The fix is to remove the node key in corrupt_blocks cache_tree.
3252 * and rebalance the tree.
3253 * After the fix, the btree should be writeable.
3255 static int repair_btree(struct btrfs_root *root,
3256 struct cache_tree *corrupt_blocks)
3258 struct btrfs_trans_handle *trans;
3259 struct btrfs_path *path;
3260 struct btrfs_corrupt_block *corrupt;
3261 struct cache_extent *cache;
3262 struct btrfs_key key;
3267 if (cache_tree_empty(corrupt_blocks))
3270 path = btrfs_alloc_path();
3274 trans = btrfs_start_transaction(root, 1);
3275 if (IS_ERR(trans)) {
3276 ret = PTR_ERR(trans);
3277 fprintf(stderr, "Error starting transaction: %s\n",
3281 cache = first_cache_extent(corrupt_blocks);
3283 corrupt = container_of(cache, struct btrfs_corrupt_block,
3285 level = corrupt->level;
3286 path->lowest_level = level;
3287 key.objectid = corrupt->key.objectid;
3288 key.type = corrupt->key.type;
3289 key.offset = corrupt->key.offset;
3292 * Here we don't want to do any tree balance, since it may
3293 * cause a balance with corrupted brother leaf/node,
3294 * so ins_len set to 0 here.
3295 * Balance will be done after all corrupt node/leaf is deleted.
3297 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3300 offset = btrfs_node_blockptr(path->nodes[level],
3301 path->slots[level]);
3303 /* Remove the ptr */
3304 ret = btrfs_del_ptr(trans, root, path, level,
3305 path->slots[level]);
3309 * Remove the corresponding extent
3310 * return value is not concerned.
3312 btrfs_release_path(path);
3313 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3314 0, root->root_key.objectid,
3316 cache = next_cache_extent(cache);
3319 /* Balance the btree using btrfs_search_slot() */
3320 cache = first_cache_extent(corrupt_blocks);
3322 corrupt = container_of(cache, struct btrfs_corrupt_block,
3324 memcpy(&key, &corrupt->key, sizeof(key));
3325 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3328 /* return will always >0 since it won't find the item */
3330 btrfs_release_path(path);
3331 cache = next_cache_extent(cache);
3334 btrfs_commit_transaction(trans, root);
3336 btrfs_free_path(path);
3340 static int check_fs_root(struct btrfs_root *root,
3341 struct cache_tree *root_cache,
3342 struct walk_control *wc)
3348 struct btrfs_path path;
3349 struct shared_node root_node;
3350 struct root_record *rec;
3351 struct btrfs_root_item *root_item = &root->root_item;
3352 struct cache_tree corrupt_blocks;
3353 struct orphan_data_extent *orphan;
3354 struct orphan_data_extent *tmp;
3355 enum btrfs_tree_block_status status;
3358 * Reuse the corrupt_block cache tree to record corrupted tree block
3360 * Unlike the usage in extent tree check, here we do it in a per
3361 * fs/subvol tree base.
3363 cache_tree_init(&corrupt_blocks);
3364 root->fs_info->corrupt_blocks = &corrupt_blocks;
3366 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3367 rec = get_root_rec(root_cache, root->root_key.objectid);
3368 if (btrfs_root_refs(root_item) > 0)
3369 rec->found_root_item = 1;
3372 btrfs_init_path(&path);
3373 memset(&root_node, 0, sizeof(root_node));
3374 cache_tree_init(&root_node.root_cache);
3375 cache_tree_init(&root_node.inode_cache);
3377 /* Move the orphan extent record to corresponding inode_record */
3378 list_for_each_entry_safe(orphan, tmp,
3379 &root->orphan_data_extents, list) {
3380 struct inode_record *inode;
3382 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3384 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3385 list_move(&orphan->list, &inode->orphan_extents);
3388 level = btrfs_header_level(root->node);
3389 memset(wc->nodes, 0, sizeof(wc->nodes));
3390 wc->nodes[level] = &root_node;
3391 wc->active_node = level;
3392 wc->root_level = level;
3394 /* We may not have checked the root block, lets do that now */
3395 if (btrfs_is_leaf(root->node))
3396 status = btrfs_check_leaf(root, NULL, root->node);
3398 status = btrfs_check_node(root, NULL, root->node);
3399 if (status != BTRFS_TREE_BLOCK_CLEAN)
3402 if (btrfs_root_refs(root_item) > 0 ||
3403 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3404 path.nodes[level] = root->node;
3405 extent_buffer_get(root->node);
3406 path.slots[level] = 0;
3408 struct btrfs_key key;
3409 struct btrfs_disk_key found_key;
3411 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3412 level = root_item->drop_level;
3413 path.lowest_level = level;
3414 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3417 btrfs_node_key(path.nodes[level], &found_key,
3419 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3420 sizeof(found_key)));
3424 wret = walk_down_tree(root, &path, wc, &level);
3430 wret = walk_up_tree(root, &path, wc, &level);
3437 btrfs_release_path(&path);
3439 if (!cache_tree_empty(&corrupt_blocks)) {
3440 struct cache_extent *cache;
3441 struct btrfs_corrupt_block *corrupt;
3443 printf("The following tree block(s) is corrupted in tree %llu:\n",
3444 root->root_key.objectid);
3445 cache = first_cache_extent(&corrupt_blocks);
3447 corrupt = container_of(cache,
3448 struct btrfs_corrupt_block,
3450 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3451 cache->start, corrupt->level,
3452 corrupt->key.objectid, corrupt->key.type,
3453 corrupt->key.offset);
3454 cache = next_cache_extent(cache);
3457 printf("Try to repair the btree for root %llu\n",
3458 root->root_key.objectid);
3459 ret = repair_btree(root, &corrupt_blocks);
3461 fprintf(stderr, "Failed to repair btree: %s\n",
3464 printf("Btree for root %llu is fixed\n",
3465 root->root_key.objectid);
3469 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3473 if (root_node.current) {
3474 root_node.current->checked = 1;
3475 maybe_free_inode_rec(&root_node.inode_cache,
3479 err = check_inode_recs(root, &root_node.inode_cache);
3483 free_corrupt_blocks_tree(&corrupt_blocks);
3484 root->fs_info->corrupt_blocks = NULL;
3485 free_orphan_data_extents(&root->orphan_data_extents);
3489 static int fs_root_objectid(u64 objectid)
3491 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3492 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3494 return is_fstree(objectid);
3497 static int check_fs_roots(struct btrfs_root *root,
3498 struct cache_tree *root_cache)
3500 struct btrfs_path path;
3501 struct btrfs_key key;
3502 struct walk_control wc;
3503 struct extent_buffer *leaf, *tree_node;
3504 struct btrfs_root *tmp_root;
3505 struct btrfs_root *tree_root = root->fs_info->tree_root;
3510 * Just in case we made any changes to the extent tree that weren't
3511 * reflected into the free space cache yet.
3514 reset_cached_block_groups(root->fs_info);
3515 memset(&wc, 0, sizeof(wc));
3516 cache_tree_init(&wc.shared);
3517 btrfs_init_path(&path);
3522 key.type = BTRFS_ROOT_ITEM_KEY;
3523 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3528 tree_node = tree_root->node;
3530 if (tree_node != tree_root->node) {
3531 free_root_recs_tree(root_cache);
3532 btrfs_release_path(&path);
3535 leaf = path.nodes[0];
3536 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3537 ret = btrfs_next_leaf(tree_root, &path);
3543 leaf = path.nodes[0];
3545 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3546 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3547 fs_root_objectid(key.objectid)) {
3548 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3549 tmp_root = btrfs_read_fs_root_no_cache(
3550 root->fs_info, &key);
3552 key.offset = (u64)-1;
3553 tmp_root = btrfs_read_fs_root(
3554 root->fs_info, &key);
3556 if (IS_ERR(tmp_root)) {
3560 ret = check_fs_root(tmp_root, root_cache, &wc);
3561 if (ret == -EAGAIN) {
3562 free_root_recs_tree(root_cache);
3563 btrfs_release_path(&path);
3568 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3569 btrfs_free_fs_root(tmp_root);
3570 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3571 key.type == BTRFS_ROOT_BACKREF_KEY) {
3572 process_root_ref(leaf, path.slots[0], &key,
3579 btrfs_release_path(&path);
3581 free_extent_cache_tree(&wc.shared);
3582 if (!cache_tree_empty(&wc.shared))
3583 fprintf(stderr, "warning line %d\n", __LINE__);
3588 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3590 struct list_head *cur = rec->backrefs.next;
3591 struct extent_backref *back;
3592 struct tree_backref *tback;
3593 struct data_backref *dback;
3597 while(cur != &rec->backrefs) {
3598 back = list_entry(cur, struct extent_backref, list);
3600 if (!back->found_extent_tree) {
3604 if (back->is_data) {
3605 dback = (struct data_backref *)back;
3606 fprintf(stderr, "Backref %llu %s %llu"
3607 " owner %llu offset %llu num_refs %lu"
3608 " not found in extent tree\n",
3609 (unsigned long long)rec->start,
3610 back->full_backref ?
3612 back->full_backref ?
3613 (unsigned long long)dback->parent:
3614 (unsigned long long)dback->root,
3615 (unsigned long long)dback->owner,
3616 (unsigned long long)dback->offset,
3617 (unsigned long)dback->num_refs);
3619 tback = (struct tree_backref *)back;
3620 fprintf(stderr, "Backref %llu parent %llu"
3621 " root %llu not found in extent tree\n",
3622 (unsigned long long)rec->start,
3623 (unsigned long long)tback->parent,
3624 (unsigned long long)tback->root);
3627 if (!back->is_data && !back->found_ref) {
3631 tback = (struct tree_backref *)back;
3632 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3633 (unsigned long long)rec->start,
3634 back->full_backref ? "parent" : "root",
3635 back->full_backref ?
3636 (unsigned long long)tback->parent :
3637 (unsigned long long)tback->root, back);
3639 if (back->is_data) {
3640 dback = (struct data_backref *)back;
3641 if (dback->found_ref != dback->num_refs) {
3645 fprintf(stderr, "Incorrect local backref count"
3646 " on %llu %s %llu owner %llu"
3647 " offset %llu found %u wanted %u back %p\n",
3648 (unsigned long long)rec->start,
3649 back->full_backref ?
3651 back->full_backref ?
3652 (unsigned long long)dback->parent:
3653 (unsigned long long)dback->root,
3654 (unsigned long long)dback->owner,
3655 (unsigned long long)dback->offset,
3656 dback->found_ref, dback->num_refs, back);
3658 if (dback->disk_bytenr != rec->start) {
3662 fprintf(stderr, "Backref disk bytenr does not"
3663 " match extent record, bytenr=%llu, "
3664 "ref bytenr=%llu\n",
3665 (unsigned long long)rec->start,
3666 (unsigned long long)dback->disk_bytenr);
3669 if (dback->bytes != rec->nr) {
3673 fprintf(stderr, "Backref bytes do not match "
3674 "extent backref, bytenr=%llu, ref "
3675 "bytes=%llu, backref bytes=%llu\n",
3676 (unsigned long long)rec->start,
3677 (unsigned long long)rec->nr,
3678 (unsigned long long)dback->bytes);
3681 if (!back->is_data) {
3684 dback = (struct data_backref *)back;
3685 found += dback->found_ref;
3688 if (found != rec->refs) {
3692 fprintf(stderr, "Incorrect global backref count "
3693 "on %llu found %llu wanted %llu\n",
3694 (unsigned long long)rec->start,
3695 (unsigned long long)found,
3696 (unsigned long long)rec->refs);
3702 static int free_all_extent_backrefs(struct extent_record *rec)
3704 struct extent_backref *back;
3705 struct list_head *cur;
3706 while (!list_empty(&rec->backrefs)) {
3707 cur = rec->backrefs.next;
3708 back = list_entry(cur, struct extent_backref, list);
3715 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3716 struct cache_tree *extent_cache)
3718 struct cache_extent *cache;
3719 struct extent_record *rec;
3722 cache = first_cache_extent(extent_cache);
3725 rec = container_of(cache, struct extent_record, cache);
3726 remove_cache_extent(extent_cache, cache);
3727 free_all_extent_backrefs(rec);
3732 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3733 struct extent_record *rec)
3735 if (rec->content_checked && rec->owner_ref_checked &&
3736 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3737 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3738 !rec->bad_full_backref && !rec->crossing_stripes) {
3739 remove_cache_extent(extent_cache, &rec->cache);
3740 free_all_extent_backrefs(rec);
3741 list_del_init(&rec->list);
3747 static int check_owner_ref(struct btrfs_root *root,
3748 struct extent_record *rec,
3749 struct extent_buffer *buf)
3751 struct extent_backref *node;
3752 struct tree_backref *back;
3753 struct btrfs_root *ref_root;
3754 struct btrfs_key key;
3755 struct btrfs_path path;
3756 struct extent_buffer *parent;
3761 list_for_each_entry(node, &rec->backrefs, list) {
3764 if (!node->found_ref)
3766 if (node->full_backref)
3768 back = (struct tree_backref *)node;
3769 if (btrfs_header_owner(buf) == back->root)
3772 BUG_ON(rec->is_root);
3774 /* try to find the block by search corresponding fs tree */
3775 key.objectid = btrfs_header_owner(buf);
3776 key.type = BTRFS_ROOT_ITEM_KEY;
3777 key.offset = (u64)-1;
3779 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3780 if (IS_ERR(ref_root))
3783 level = btrfs_header_level(buf);
3785 btrfs_item_key_to_cpu(buf, &key, 0);
3787 btrfs_node_key_to_cpu(buf, &key, 0);
3789 btrfs_init_path(&path);
3790 path.lowest_level = level + 1;
3791 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3795 parent = path.nodes[level + 1];
3796 if (parent && buf->start == btrfs_node_blockptr(parent,
3797 path.slots[level + 1]))
3800 btrfs_release_path(&path);
3801 return found ? 0 : 1;
3804 static int is_extent_tree_record(struct extent_record *rec)
3806 struct list_head *cur = rec->backrefs.next;
3807 struct extent_backref *node;
3808 struct tree_backref *back;
3811 while(cur != &rec->backrefs) {
3812 node = list_entry(cur, struct extent_backref, list);
3816 back = (struct tree_backref *)node;
3817 if (node->full_backref)
3819 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3826 static int record_bad_block_io(struct btrfs_fs_info *info,
3827 struct cache_tree *extent_cache,
3830 struct extent_record *rec;
3831 struct cache_extent *cache;
3832 struct btrfs_key key;
3834 cache = lookup_cache_extent(extent_cache, start, len);
3838 rec = container_of(cache, struct extent_record, cache);
3839 if (!is_extent_tree_record(rec))
3842 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3843 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3846 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3847 struct extent_buffer *buf, int slot)
3849 if (btrfs_header_level(buf)) {
3850 struct btrfs_key_ptr ptr1, ptr2;
3852 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3853 sizeof(struct btrfs_key_ptr));
3854 read_extent_buffer(buf, &ptr2,
3855 btrfs_node_key_ptr_offset(slot + 1),
3856 sizeof(struct btrfs_key_ptr));
3857 write_extent_buffer(buf, &ptr1,
3858 btrfs_node_key_ptr_offset(slot + 1),
3859 sizeof(struct btrfs_key_ptr));
3860 write_extent_buffer(buf, &ptr2,
3861 btrfs_node_key_ptr_offset(slot),
3862 sizeof(struct btrfs_key_ptr));
3864 struct btrfs_disk_key key;
3865 btrfs_node_key(buf, &key, 0);
3866 btrfs_fixup_low_keys(root, path, &key,
3867 btrfs_header_level(buf) + 1);
3870 struct btrfs_item *item1, *item2;
3871 struct btrfs_key k1, k2;
3872 char *item1_data, *item2_data;
3873 u32 item1_offset, item2_offset, item1_size, item2_size;
3875 item1 = btrfs_item_nr(slot);
3876 item2 = btrfs_item_nr(slot + 1);
3877 btrfs_item_key_to_cpu(buf, &k1, slot);
3878 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3879 item1_offset = btrfs_item_offset(buf, item1);
3880 item2_offset = btrfs_item_offset(buf, item2);
3881 item1_size = btrfs_item_size(buf, item1);
3882 item2_size = btrfs_item_size(buf, item2);
3884 item1_data = malloc(item1_size);
3887 item2_data = malloc(item2_size);
3893 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3894 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3896 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3897 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3901 btrfs_set_item_offset(buf, item1, item2_offset);
3902 btrfs_set_item_offset(buf, item2, item1_offset);
3903 btrfs_set_item_size(buf, item1, item2_size);
3904 btrfs_set_item_size(buf, item2, item1_size);
3906 path->slots[0] = slot;
3907 btrfs_set_item_key_unsafe(root, path, &k2);
3908 path->slots[0] = slot + 1;
3909 btrfs_set_item_key_unsafe(root, path, &k1);
3914 static int fix_key_order(struct btrfs_trans_handle *trans,
3915 struct btrfs_root *root,
3916 struct btrfs_path *path)
3918 struct extent_buffer *buf;
3919 struct btrfs_key k1, k2;
3921 int level = path->lowest_level;
3924 buf = path->nodes[level];
3925 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3927 btrfs_node_key_to_cpu(buf, &k1, i);
3928 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3930 btrfs_item_key_to_cpu(buf, &k1, i);
3931 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3933 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3935 ret = swap_values(root, path, buf, i);
3938 btrfs_mark_buffer_dirty(buf);
3944 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3945 struct btrfs_root *root,
3946 struct btrfs_path *path,
3947 struct extent_buffer *buf, int slot)
3949 struct btrfs_key key;
3950 int nritems = btrfs_header_nritems(buf);
3952 btrfs_item_key_to_cpu(buf, &key, slot);
3954 /* These are all the keys we can deal with missing. */
3955 if (key.type != BTRFS_DIR_INDEX_KEY &&
3956 key.type != BTRFS_EXTENT_ITEM_KEY &&
3957 key.type != BTRFS_METADATA_ITEM_KEY &&
3958 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3959 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3962 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3963 (unsigned long long)key.objectid, key.type,
3964 (unsigned long long)key.offset, slot, buf->start);
3965 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3966 btrfs_item_nr_offset(slot + 1),
3967 sizeof(struct btrfs_item) *
3968 (nritems - slot - 1));
3969 btrfs_set_header_nritems(buf, nritems - 1);
3971 struct btrfs_disk_key disk_key;
3973 btrfs_item_key(buf, &disk_key, 0);
3974 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3976 btrfs_mark_buffer_dirty(buf);
3980 static int fix_item_offset(struct btrfs_trans_handle *trans,
3981 struct btrfs_root *root,
3982 struct btrfs_path *path)
3984 struct extent_buffer *buf;
3988 /* We should only get this for leaves */
3989 BUG_ON(path->lowest_level);
3990 buf = path->nodes[0];
3992 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3993 unsigned int shift = 0, offset;
3995 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3996 BTRFS_LEAF_DATA_SIZE(root)) {
3997 if (btrfs_item_end_nr(buf, i) >
3998 BTRFS_LEAF_DATA_SIZE(root)) {
3999 ret = delete_bogus_item(trans, root, path,
4003 fprintf(stderr, "item is off the end of the "
4004 "leaf, can't fix\n");
4008 shift = BTRFS_LEAF_DATA_SIZE(root) -
4009 btrfs_item_end_nr(buf, i);
4010 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
4011 btrfs_item_offset_nr(buf, i - 1)) {
4012 if (btrfs_item_end_nr(buf, i) >
4013 btrfs_item_offset_nr(buf, i - 1)) {
4014 ret = delete_bogus_item(trans, root, path,
4018 fprintf(stderr, "items overlap, can't fix\n");
4022 shift = btrfs_item_offset_nr(buf, i - 1) -
4023 btrfs_item_end_nr(buf, i);
4028 printf("Shifting item nr %d by %u bytes in block %llu\n",
4029 i, shift, (unsigned long long)buf->start);
4030 offset = btrfs_item_offset_nr(buf, i);
4031 memmove_extent_buffer(buf,
4032 btrfs_leaf_data(buf) + offset + shift,
4033 btrfs_leaf_data(buf) + offset,
4034 btrfs_item_size_nr(buf, i));
4035 btrfs_set_item_offset(buf, btrfs_item_nr(i),
4037 btrfs_mark_buffer_dirty(buf);
4041 * We may have moved things, in which case we want to exit so we don't
4042 * write those changes out. Once we have proper abort functionality in
4043 * progs this can be changed to something nicer.
4050 * Attempt to fix basic block failures. If we can't fix it for whatever reason
4051 * then just return -EIO.
4053 static int try_to_fix_bad_block(struct btrfs_root *root,
4054 struct extent_buffer *buf,
4055 enum btrfs_tree_block_status status)
4057 struct btrfs_trans_handle *trans;
4058 struct ulist *roots;
4059 struct ulist_node *node;
4060 struct btrfs_root *search_root;
4061 struct btrfs_path *path;
4062 struct ulist_iterator iter;
4063 struct btrfs_key root_key, key;
4066 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4067 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4070 path = btrfs_alloc_path();
4074 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4077 btrfs_free_path(path);
4081 ULIST_ITER_INIT(&iter);
4082 while ((node = ulist_next(roots, &iter))) {
4083 root_key.objectid = node->val;
4084 root_key.type = BTRFS_ROOT_ITEM_KEY;
4085 root_key.offset = (u64)-1;
4087 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4094 trans = btrfs_start_transaction(search_root, 0);
4095 if (IS_ERR(trans)) {
4096 ret = PTR_ERR(trans);
4100 path->lowest_level = btrfs_header_level(buf);
4101 path->skip_check_block = 1;
4102 if (path->lowest_level)
4103 btrfs_node_key_to_cpu(buf, &key, 0);
4105 btrfs_item_key_to_cpu(buf, &key, 0);
4106 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4109 btrfs_commit_transaction(trans, search_root);
4112 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4113 ret = fix_key_order(trans, search_root, path);
4114 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4115 ret = fix_item_offset(trans, search_root, path);
4117 btrfs_commit_transaction(trans, search_root);
4120 btrfs_release_path(path);
4121 btrfs_commit_transaction(trans, search_root);
4124 btrfs_free_path(path);
4128 static int check_block(struct btrfs_root *root,
4129 struct cache_tree *extent_cache,
4130 struct extent_buffer *buf, u64 flags)
4132 struct extent_record *rec;
4133 struct cache_extent *cache;
4134 struct btrfs_key key;
4135 enum btrfs_tree_block_status status;
4139 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4142 rec = container_of(cache, struct extent_record, cache);
4143 rec->generation = btrfs_header_generation(buf);
4145 level = btrfs_header_level(buf);
4146 if (btrfs_header_nritems(buf) > 0) {
4149 btrfs_item_key_to_cpu(buf, &key, 0);
4151 btrfs_node_key_to_cpu(buf, &key, 0);
4153 rec->info_objectid = key.objectid;
4155 rec->info_level = level;
4157 if (btrfs_is_leaf(buf))
4158 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4160 status = btrfs_check_node(root, &rec->parent_key, buf);
4162 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4164 status = try_to_fix_bad_block(root, buf, status);
4165 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4167 fprintf(stderr, "bad block %llu\n",
4168 (unsigned long long)buf->start);
4171 * Signal to callers we need to start the scan over
4172 * again since we'll have cow'ed blocks.
4177 rec->content_checked = 1;
4178 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4179 rec->owner_ref_checked = 1;
4181 ret = check_owner_ref(root, rec, buf);
4183 rec->owner_ref_checked = 1;
4187 maybe_free_extent_rec(extent_cache, rec);
4191 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4192 u64 parent, u64 root)
4194 struct list_head *cur = rec->backrefs.next;
4195 struct extent_backref *node;
4196 struct tree_backref *back;
4198 while(cur != &rec->backrefs) {
4199 node = list_entry(cur, struct extent_backref, list);
4203 back = (struct tree_backref *)node;
4205 if (!node->full_backref)
4207 if (parent == back->parent)
4210 if (node->full_backref)
4212 if (back->root == root)
4219 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4220 u64 parent, u64 root)
4222 struct tree_backref *ref = malloc(sizeof(*ref));
4223 memset(&ref->node, 0, sizeof(ref->node));
4225 ref->parent = parent;
4226 ref->node.full_backref = 1;
4229 ref->node.full_backref = 0;
4231 list_add_tail(&ref->node.list, &rec->backrefs);
4236 static struct data_backref *find_data_backref(struct extent_record *rec,
4237 u64 parent, u64 root,
4238 u64 owner, u64 offset,
4240 u64 disk_bytenr, u64 bytes)
4242 struct list_head *cur = rec->backrefs.next;
4243 struct extent_backref *node;
4244 struct data_backref *back;
4246 while(cur != &rec->backrefs) {
4247 node = list_entry(cur, struct extent_backref, list);
4251 back = (struct data_backref *)node;
4253 if (!node->full_backref)
4255 if (parent == back->parent)
4258 if (node->full_backref)
4260 if (back->root == root && back->owner == owner &&
4261 back->offset == offset) {
4262 if (found_ref && node->found_ref &&
4263 (back->bytes != bytes ||
4264 back->disk_bytenr != disk_bytenr))
4273 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4274 u64 parent, u64 root,
4275 u64 owner, u64 offset,
4278 struct data_backref *ref = malloc(sizeof(*ref));
4279 memset(&ref->node, 0, sizeof(ref->node));
4280 ref->node.is_data = 1;
4283 ref->parent = parent;
4286 ref->node.full_backref = 1;
4290 ref->offset = offset;
4291 ref->node.full_backref = 0;
4293 ref->bytes = max_size;
4296 list_add_tail(&ref->node.list, &rec->backrefs);
4297 if (max_size > rec->max_size)
4298 rec->max_size = max_size;
4302 static int add_extent_rec(struct cache_tree *extent_cache,
4303 struct btrfs_key *parent_key, u64 parent_gen,
4304 u64 start, u64 nr, u64 extent_item_refs,
4305 int is_root, int inc_ref, int set_checked,
4306 int metadata, int extent_rec, u64 max_size)
4308 struct extent_record *rec;
4309 struct cache_extent *cache;
4313 cache = lookup_cache_extent(extent_cache, start, nr);
4315 rec = container_of(cache, struct extent_record, cache);
4319 rec->nr = max(nr, max_size);
4322 * We need to make sure to reset nr to whatever the extent
4323 * record says was the real size, this way we can compare it to
4327 if (start != rec->start || rec->found_rec) {
4328 struct extent_record *tmp;
4331 if (list_empty(&rec->list))
4332 list_add_tail(&rec->list,
4333 &duplicate_extents);
4336 * We have to do this song and dance in case we
4337 * find an extent record that falls inside of
4338 * our current extent record but does not have
4339 * the same objectid.
4341 tmp = malloc(sizeof(*tmp));
4345 tmp->max_size = max_size;
4348 tmp->metadata = metadata;
4349 tmp->extent_item_refs = extent_item_refs;
4350 INIT_LIST_HEAD(&tmp->list);
4351 list_add_tail(&tmp->list, &rec->dups);
4352 rec->num_duplicates++;
4359 if (extent_item_refs && !dup) {
4360 if (rec->extent_item_refs) {
4361 fprintf(stderr, "block %llu rec "
4362 "extent_item_refs %llu, passed %llu\n",
4363 (unsigned long long)start,
4364 (unsigned long long)
4365 rec->extent_item_refs,
4366 (unsigned long long)extent_item_refs);
4368 rec->extent_item_refs = extent_item_refs;
4373 rec->content_checked = 1;
4374 rec->owner_ref_checked = 1;
4378 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4380 rec->parent_generation = parent_gen;
4382 if (rec->max_size < max_size)
4383 rec->max_size = max_size;
4386 * A metadata extent can't cross stripe_len boundary, otherwise
4387 * kernel scrub won't be able to handle it.
4388 * As now stripe_len is fixed to BTRFS_STRIPE_LEN, just check
4391 if (metadata && check_crossing_stripes(rec->start,
4393 rec->crossing_stripes = 1;
4394 maybe_free_extent_rec(extent_cache, rec);
4397 rec = malloc(sizeof(*rec));
4399 rec->max_size = max_size;
4400 rec->nr = max(nr, max_size);
4401 rec->found_rec = !!extent_rec;
4402 rec->content_checked = 0;
4403 rec->owner_ref_checked = 0;
4404 rec->num_duplicates = 0;
4405 rec->metadata = metadata;
4406 rec->flag_block_full_backref = -1;
4407 rec->bad_full_backref = 0;
4408 INIT_LIST_HEAD(&rec->backrefs);
4409 INIT_LIST_HEAD(&rec->dups);
4410 INIT_LIST_HEAD(&rec->list);
4422 if (extent_item_refs)
4423 rec->extent_item_refs = extent_item_refs;
4425 rec->extent_item_refs = 0;
4428 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4430 memset(&rec->parent_key, 0, sizeof(*parent_key));
4433 rec->parent_generation = parent_gen;
4435 rec->parent_generation = 0;
4437 rec->cache.start = start;
4438 rec->cache.size = nr;
4439 ret = insert_cache_extent(extent_cache, &rec->cache);
4443 rec->content_checked = 1;
4444 rec->owner_ref_checked = 1;
4448 if (check_crossing_stripes(rec->start, rec->max_size))
4449 rec->crossing_stripes = 1;
4453 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4454 u64 parent, u64 root, int found_ref)
4456 struct extent_record *rec;
4457 struct tree_backref *back;
4458 struct cache_extent *cache;
4460 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4462 add_extent_rec(extent_cache, NULL, 0, bytenr,
4463 1, 0, 0, 0, 0, 1, 0, 0);
4464 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4469 rec = container_of(cache, struct extent_record, cache);
4470 if (rec->start != bytenr) {
4474 back = find_tree_backref(rec, parent, root);
4476 back = alloc_tree_backref(rec, parent, root);
4479 if (back->node.found_ref) {
4480 fprintf(stderr, "Extent back ref already exists "
4481 "for %llu parent %llu root %llu \n",
4482 (unsigned long long)bytenr,
4483 (unsigned long long)parent,
4484 (unsigned long long)root);
4486 back->node.found_ref = 1;
4488 if (back->node.found_extent_tree) {
4489 fprintf(stderr, "Extent back ref already exists "
4490 "for %llu parent %llu root %llu \n",
4491 (unsigned long long)bytenr,
4492 (unsigned long long)parent,
4493 (unsigned long long)root);
4495 back->node.found_extent_tree = 1;
4497 maybe_free_extent_rec(extent_cache, rec);
4501 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4502 u64 parent, u64 root, u64 owner, u64 offset,
4503 u32 num_refs, int found_ref, u64 max_size)
4505 struct extent_record *rec;
4506 struct data_backref *back;
4507 struct cache_extent *cache;
4509 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4511 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4513 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4518 rec = container_of(cache, struct extent_record, cache);
4519 if (rec->max_size < max_size)
4520 rec->max_size = max_size;
4523 * If found_ref is set then max_size is the real size and must match the
4524 * existing refs. So if we have already found a ref then we need to
4525 * make sure that this ref matches the existing one, otherwise we need
4526 * to add a new backref so we can notice that the backrefs don't match
4527 * and we need to figure out who is telling the truth. This is to
4528 * account for that awful fsync bug I introduced where we'd end up with
4529 * a btrfs_file_extent_item that would have its length include multiple
4530 * prealloc extents or point inside of a prealloc extent.
4532 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4535 back = alloc_data_backref(rec, parent, root, owner, offset,
4539 BUG_ON(num_refs != 1);
4540 if (back->node.found_ref)
4541 BUG_ON(back->bytes != max_size);
4542 back->node.found_ref = 1;
4543 back->found_ref += 1;
4544 back->bytes = max_size;
4545 back->disk_bytenr = bytenr;
4547 rec->content_checked = 1;
4548 rec->owner_ref_checked = 1;
4550 if (back->node.found_extent_tree) {
4551 fprintf(stderr, "Extent back ref already exists "
4552 "for %llu parent %llu root %llu "
4553 "owner %llu offset %llu num_refs %lu\n",
4554 (unsigned long long)bytenr,
4555 (unsigned long long)parent,
4556 (unsigned long long)root,
4557 (unsigned long long)owner,
4558 (unsigned long long)offset,
4559 (unsigned long)num_refs);
4561 back->num_refs = num_refs;
4562 back->node.found_extent_tree = 1;
4564 maybe_free_extent_rec(extent_cache, rec);
4568 static int add_pending(struct cache_tree *pending,
4569 struct cache_tree *seen, u64 bytenr, u32 size)
4572 ret = add_cache_extent(seen, bytenr, size);
4575 add_cache_extent(pending, bytenr, size);
4579 static int pick_next_pending(struct cache_tree *pending,
4580 struct cache_tree *reada,
4581 struct cache_tree *nodes,
4582 u64 last, struct block_info *bits, int bits_nr,
4585 unsigned long node_start = last;
4586 struct cache_extent *cache;
4589 cache = search_cache_extent(reada, 0);
4591 bits[0].start = cache->start;
4592 bits[0].size = cache->size;
4597 if (node_start > 32768)
4598 node_start -= 32768;
4600 cache = search_cache_extent(nodes, node_start);
4602 cache = search_cache_extent(nodes, 0);
4605 cache = search_cache_extent(pending, 0);
4610 bits[ret].start = cache->start;
4611 bits[ret].size = cache->size;
4612 cache = next_cache_extent(cache);
4614 } while (cache && ret < bits_nr);
4620 bits[ret].start = cache->start;
4621 bits[ret].size = cache->size;
4622 cache = next_cache_extent(cache);
4624 } while (cache && ret < bits_nr);
4626 if (bits_nr - ret > 8) {
4627 u64 lookup = bits[0].start + bits[0].size;
4628 struct cache_extent *next;
4629 next = search_cache_extent(pending, lookup);
4631 if (next->start - lookup > 32768)
4633 bits[ret].start = next->start;
4634 bits[ret].size = next->size;
4635 lookup = next->start + next->size;
4639 next = next_cache_extent(next);
4647 static void free_chunk_record(struct cache_extent *cache)
4649 struct chunk_record *rec;
4651 rec = container_of(cache, struct chunk_record, cache);
4652 list_del_init(&rec->list);
4653 list_del_init(&rec->dextents);
4657 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4659 cache_tree_free_extents(chunk_cache, free_chunk_record);
4662 static void free_device_record(struct rb_node *node)
4664 struct device_record *rec;
4666 rec = container_of(node, struct device_record, node);
4670 FREE_RB_BASED_TREE(device_cache, free_device_record);
4672 int insert_block_group_record(struct block_group_tree *tree,
4673 struct block_group_record *bg_rec)
4677 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4681 list_add_tail(&bg_rec->list, &tree->block_groups);
4685 static void free_block_group_record(struct cache_extent *cache)
4687 struct block_group_record *rec;
4689 rec = container_of(cache, struct block_group_record, cache);
4690 list_del_init(&rec->list);
4694 void free_block_group_tree(struct block_group_tree *tree)
4696 cache_tree_free_extents(&tree->tree, free_block_group_record);
4699 int insert_device_extent_record(struct device_extent_tree *tree,
4700 struct device_extent_record *de_rec)
4705 * Device extent is a bit different from the other extents, because
4706 * the extents which belong to the different devices may have the
4707 * same start and size, so we need use the special extent cache
4708 * search/insert functions.
4710 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4714 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4715 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4719 static void free_device_extent_record(struct cache_extent *cache)
4721 struct device_extent_record *rec;
4723 rec = container_of(cache, struct device_extent_record, cache);
4724 if (!list_empty(&rec->chunk_list))
4725 list_del_init(&rec->chunk_list);
4726 if (!list_empty(&rec->device_list))
4727 list_del_init(&rec->device_list);
4731 void free_device_extent_tree(struct device_extent_tree *tree)
4733 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4736 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4737 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4738 struct extent_buffer *leaf, int slot)
4740 struct btrfs_extent_ref_v0 *ref0;
4741 struct btrfs_key key;
4743 btrfs_item_key_to_cpu(leaf, &key, slot);
4744 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4745 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4746 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4748 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4749 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4755 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4756 struct btrfs_key *key,
4759 struct btrfs_chunk *ptr;
4760 struct chunk_record *rec;
4763 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4764 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4766 rec = malloc(btrfs_chunk_record_size(num_stripes));
4768 fprintf(stderr, "memory allocation failed\n");
4772 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4774 INIT_LIST_HEAD(&rec->list);
4775 INIT_LIST_HEAD(&rec->dextents);
4778 rec->cache.start = key->offset;
4779 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4781 rec->generation = btrfs_header_generation(leaf);
4783 rec->objectid = key->objectid;
4784 rec->type = key->type;
4785 rec->offset = key->offset;
4787 rec->length = rec->cache.size;
4788 rec->owner = btrfs_chunk_owner(leaf, ptr);
4789 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4790 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4791 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4792 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4793 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4794 rec->num_stripes = num_stripes;
4795 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4797 for (i = 0; i < rec->num_stripes; ++i) {
4798 rec->stripes[i].devid =
4799 btrfs_stripe_devid_nr(leaf, ptr, i);
4800 rec->stripes[i].offset =
4801 btrfs_stripe_offset_nr(leaf, ptr, i);
4802 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4803 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4810 static int process_chunk_item(struct cache_tree *chunk_cache,
4811 struct btrfs_key *key, struct extent_buffer *eb,
4814 struct chunk_record *rec;
4817 rec = btrfs_new_chunk_record(eb, key, slot);
4818 ret = insert_cache_extent(chunk_cache, &rec->cache);
4820 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4821 rec->offset, rec->length);
4828 static int process_device_item(struct rb_root *dev_cache,
4829 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4831 struct btrfs_dev_item *ptr;
4832 struct device_record *rec;
4835 ptr = btrfs_item_ptr(eb,
4836 slot, struct btrfs_dev_item);
4838 rec = malloc(sizeof(*rec));
4840 fprintf(stderr, "memory allocation failed\n");
4844 rec->devid = key->offset;
4845 rec->generation = btrfs_header_generation(eb);
4847 rec->objectid = key->objectid;
4848 rec->type = key->type;
4849 rec->offset = key->offset;
4851 rec->devid = btrfs_device_id(eb, ptr);
4852 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4853 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4855 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4857 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4864 struct block_group_record *
4865 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4868 struct btrfs_block_group_item *ptr;
4869 struct block_group_record *rec;
4871 rec = malloc(sizeof(*rec));
4873 fprintf(stderr, "memory allocation failed\n");
4876 memset(rec, 0, sizeof(*rec));
4878 rec->cache.start = key->objectid;
4879 rec->cache.size = key->offset;
4881 rec->generation = btrfs_header_generation(leaf);
4883 rec->objectid = key->objectid;
4884 rec->type = key->type;
4885 rec->offset = key->offset;
4887 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4888 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4890 INIT_LIST_HEAD(&rec->list);
4895 static int process_block_group_item(struct block_group_tree *block_group_cache,
4896 struct btrfs_key *key,
4897 struct extent_buffer *eb, int slot)
4899 struct block_group_record *rec;
4902 rec = btrfs_new_block_group_record(eb, key, slot);
4903 ret = insert_block_group_record(block_group_cache, rec);
4905 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4906 rec->objectid, rec->offset);
4913 struct device_extent_record *
4914 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4915 struct btrfs_key *key, int slot)
4917 struct device_extent_record *rec;
4918 struct btrfs_dev_extent *ptr;
4920 rec = malloc(sizeof(*rec));
4922 fprintf(stderr, "memory allocation failed\n");
4925 memset(rec, 0, sizeof(*rec));
4927 rec->cache.objectid = key->objectid;
4928 rec->cache.start = key->offset;
4930 rec->generation = btrfs_header_generation(leaf);
4932 rec->objectid = key->objectid;
4933 rec->type = key->type;
4934 rec->offset = key->offset;
4936 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4937 rec->chunk_objecteid =
4938 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4940 btrfs_dev_extent_chunk_offset(leaf, ptr);
4941 rec->length = btrfs_dev_extent_length(leaf, ptr);
4942 rec->cache.size = rec->length;
4944 INIT_LIST_HEAD(&rec->chunk_list);
4945 INIT_LIST_HEAD(&rec->device_list);
4951 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4952 struct btrfs_key *key, struct extent_buffer *eb,
4955 struct device_extent_record *rec;
4958 rec = btrfs_new_device_extent_record(eb, key, slot);
4959 ret = insert_device_extent_record(dev_extent_cache, rec);
4962 "Device extent[%llu, %llu, %llu] existed.\n",
4963 rec->objectid, rec->offset, rec->length);
4970 static int process_extent_item(struct btrfs_root *root,
4971 struct cache_tree *extent_cache,
4972 struct extent_buffer *eb, int slot)
4974 struct btrfs_extent_item *ei;
4975 struct btrfs_extent_inline_ref *iref;
4976 struct btrfs_extent_data_ref *dref;
4977 struct btrfs_shared_data_ref *sref;
4978 struct btrfs_key key;
4982 u32 item_size = btrfs_item_size_nr(eb, slot);
4988 btrfs_item_key_to_cpu(eb, &key, slot);
4990 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4992 num_bytes = root->leafsize;
4994 num_bytes = key.offset;
4997 if (item_size < sizeof(*ei)) {
4998 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4999 struct btrfs_extent_item_v0 *ei0;
5000 BUG_ON(item_size != sizeof(*ei0));
5001 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
5002 refs = btrfs_extent_refs_v0(eb, ei0);
5006 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
5007 num_bytes, refs, 0, 0, 0, metadata, 1,
5011 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
5012 refs = btrfs_extent_refs(eb, ei);
5014 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
5015 refs, 0, 0, 0, metadata, 1, num_bytes);
5017 ptr = (unsigned long)(ei + 1);
5018 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
5019 key.type == BTRFS_EXTENT_ITEM_KEY)
5020 ptr += sizeof(struct btrfs_tree_block_info);
5022 end = (unsigned long)ei + item_size;
5024 iref = (struct btrfs_extent_inline_ref *)ptr;
5025 type = btrfs_extent_inline_ref_type(eb, iref);
5026 offset = btrfs_extent_inline_ref_offset(eb, iref);
5028 case BTRFS_TREE_BLOCK_REF_KEY:
5029 add_tree_backref(extent_cache, key.objectid,
5032 case BTRFS_SHARED_BLOCK_REF_KEY:
5033 add_tree_backref(extent_cache, key.objectid,
5036 case BTRFS_EXTENT_DATA_REF_KEY:
5037 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
5038 add_data_backref(extent_cache, key.objectid, 0,
5039 btrfs_extent_data_ref_root(eb, dref),
5040 btrfs_extent_data_ref_objectid(eb,
5042 btrfs_extent_data_ref_offset(eb, dref),
5043 btrfs_extent_data_ref_count(eb, dref),
5046 case BTRFS_SHARED_DATA_REF_KEY:
5047 sref = (struct btrfs_shared_data_ref *)(iref + 1);
5048 add_data_backref(extent_cache, key.objectid, offset,
5050 btrfs_shared_data_ref_count(eb, sref),
5054 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
5055 key.objectid, key.type, num_bytes);
5058 ptr += btrfs_extent_inline_ref_size(type);
5065 static int check_cache_range(struct btrfs_root *root,
5066 struct btrfs_block_group_cache *cache,
5067 u64 offset, u64 bytes)
5069 struct btrfs_free_space *entry;
5075 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5076 bytenr = btrfs_sb_offset(i);
5077 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5078 cache->key.objectid, bytenr, 0,
5079 &logical, &nr, &stripe_len);
5084 if (logical[nr] + stripe_len <= offset)
5086 if (offset + bytes <= logical[nr])
5088 if (logical[nr] == offset) {
5089 if (stripe_len >= bytes) {
5093 bytes -= stripe_len;
5094 offset += stripe_len;
5095 } else if (logical[nr] < offset) {
5096 if (logical[nr] + stripe_len >=
5101 bytes = (offset + bytes) -
5102 (logical[nr] + stripe_len);
5103 offset = logical[nr] + stripe_len;
5106 * Could be tricky, the super may land in the
5107 * middle of the area we're checking. First
5108 * check the easiest case, it's at the end.
5110 if (logical[nr] + stripe_len >=
5112 bytes = logical[nr] - offset;
5116 /* Check the left side */
5117 ret = check_cache_range(root, cache,
5119 logical[nr] - offset);
5125 /* Now we continue with the right side */
5126 bytes = (offset + bytes) -
5127 (logical[nr] + stripe_len);
5128 offset = logical[nr] + stripe_len;
5135 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5137 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5138 offset, offset+bytes);
5142 if (entry->offset != offset) {
5143 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5148 if (entry->bytes != bytes) {
5149 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5150 bytes, entry->bytes, offset);
5154 unlink_free_space(cache->free_space_ctl, entry);
5159 static int verify_space_cache(struct btrfs_root *root,
5160 struct btrfs_block_group_cache *cache)
5162 struct btrfs_path *path;
5163 struct extent_buffer *leaf;
5164 struct btrfs_key key;
5168 path = btrfs_alloc_path();
5172 root = root->fs_info->extent_root;
5174 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5176 key.objectid = last;
5178 key.type = BTRFS_EXTENT_ITEM_KEY;
5180 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5185 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5186 ret = btrfs_next_leaf(root, path);
5194 leaf = path->nodes[0];
5195 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5196 if (key.objectid >= cache->key.offset + cache->key.objectid)
5198 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5199 key.type != BTRFS_METADATA_ITEM_KEY) {
5204 if (last == key.objectid) {
5205 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5206 last = key.objectid + key.offset;
5208 last = key.objectid + root->leafsize;
5213 ret = check_cache_range(root, cache, last,
5214 key.objectid - last);
5217 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5218 last = key.objectid + key.offset;
5220 last = key.objectid + root->leafsize;
5224 if (last < cache->key.objectid + cache->key.offset)
5225 ret = check_cache_range(root, cache, last,
5226 cache->key.objectid +
5227 cache->key.offset - last);
5230 btrfs_free_path(path);
5233 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5234 fprintf(stderr, "There are still entries left in the space "
5242 static int check_space_cache(struct btrfs_root *root)
5244 struct btrfs_block_group_cache *cache;
5245 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5249 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5250 btrfs_super_generation(root->fs_info->super_copy) !=
5251 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5252 printf("cache and super generation don't match, space cache "
5253 "will be invalidated\n");
5258 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5262 start = cache->key.objectid + cache->key.offset;
5263 if (!cache->free_space_ctl) {
5264 if (btrfs_init_free_space_ctl(cache,
5265 root->sectorsize)) {
5270 btrfs_remove_free_space_cache(cache);
5273 ret = load_free_space_cache(root->fs_info, cache);
5277 ret = verify_space_cache(root, cache);
5279 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5280 cache->key.objectid);
5285 return error ? -EINVAL : 0;
5288 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5289 u64 num_bytes, unsigned long leaf_offset,
5290 struct extent_buffer *eb) {
5293 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5295 unsigned long csum_offset;
5299 u64 data_checked = 0;
5305 if (num_bytes % root->sectorsize)
5308 data = malloc(num_bytes);
5312 while (offset < num_bytes) {
5315 read_len = num_bytes - offset;
5316 /* read as much space once a time */
5317 ret = read_extent_data(root, data + offset,
5318 bytenr + offset, &read_len, mirror);
5322 /* verify every 4k data's checksum */
5323 while (data_checked < read_len) {
5325 tmp = offset + data_checked;
5327 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5328 csum, root->sectorsize);
5329 btrfs_csum_final(csum, (char *)&csum);
5331 csum_offset = leaf_offset +
5332 tmp / root->sectorsize * csum_size;
5333 read_extent_buffer(eb, (char *)&csum_expected,
5334 csum_offset, csum_size);
5335 /* try another mirror */
5336 if (csum != csum_expected) {
5337 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5338 mirror, bytenr + tmp,
5339 csum, csum_expected);
5340 num_copies = btrfs_num_copies(
5341 &root->fs_info->mapping_tree,
5343 if (mirror < num_copies - 1) {
5348 data_checked += root->sectorsize;
5357 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5360 struct btrfs_path *path;
5361 struct extent_buffer *leaf;
5362 struct btrfs_key key;
5365 path = btrfs_alloc_path();
5367 fprintf(stderr, "Error allocing path\n");
5371 key.objectid = bytenr;
5372 key.type = BTRFS_EXTENT_ITEM_KEY;
5373 key.offset = (u64)-1;
5376 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5379 fprintf(stderr, "Error looking up extent record %d\n", ret);
5380 btrfs_free_path(path);
5383 if (path->slots[0] > 0) {
5386 ret = btrfs_prev_leaf(root, path);
5389 } else if (ret > 0) {
5396 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5399 * Block group items come before extent items if they have the same
5400 * bytenr, so walk back one more just in case. Dear future traveler,
5401 * first congrats on mastering time travel. Now if it's not too much
5402 * trouble could you go back to 2006 and tell Chris to make the
5403 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5404 * EXTENT_ITEM_KEY please?
5406 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5407 if (path->slots[0] > 0) {
5410 ret = btrfs_prev_leaf(root, path);
5413 } else if (ret > 0) {
5418 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5422 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5423 ret = btrfs_next_leaf(root, path);
5425 fprintf(stderr, "Error going to next leaf "
5427 btrfs_free_path(path);
5433 leaf = path->nodes[0];
5434 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5435 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5439 if (key.objectid + key.offset < bytenr) {
5443 if (key.objectid > bytenr + num_bytes)
5446 if (key.objectid == bytenr) {
5447 if (key.offset >= num_bytes) {
5451 num_bytes -= key.offset;
5452 bytenr += key.offset;
5453 } else if (key.objectid < bytenr) {
5454 if (key.objectid + key.offset >= bytenr + num_bytes) {
5458 num_bytes = (bytenr + num_bytes) -
5459 (key.objectid + key.offset);
5460 bytenr = key.objectid + key.offset;
5462 if (key.objectid + key.offset < bytenr + num_bytes) {
5463 u64 new_start = key.objectid + key.offset;
5464 u64 new_bytes = bytenr + num_bytes - new_start;
5467 * Weird case, the extent is in the middle of
5468 * our range, we'll have to search one side
5469 * and then the other. Not sure if this happens
5470 * in real life, but no harm in coding it up
5471 * anyway just in case.
5473 btrfs_release_path(path);
5474 ret = check_extent_exists(root, new_start,
5477 fprintf(stderr, "Right section didn't "
5481 num_bytes = key.objectid - bytenr;
5484 num_bytes = key.objectid - bytenr;
5491 if (num_bytes && !ret) {
5492 fprintf(stderr, "There are no extents for csum range "
5493 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5497 btrfs_free_path(path);
5501 static int check_csums(struct btrfs_root *root)
5503 struct btrfs_path *path;
5504 struct extent_buffer *leaf;
5505 struct btrfs_key key;
5506 u64 offset = 0, num_bytes = 0;
5507 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5511 unsigned long leaf_offset;
5513 root = root->fs_info->csum_root;
5514 if (!extent_buffer_uptodate(root->node)) {
5515 fprintf(stderr, "No valid csum tree found\n");
5519 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5520 key.type = BTRFS_EXTENT_CSUM_KEY;
5523 path = btrfs_alloc_path();
5527 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5529 fprintf(stderr, "Error searching csum tree %d\n", ret);
5530 btrfs_free_path(path);
5534 if (ret > 0 && path->slots[0])
5539 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5540 ret = btrfs_next_leaf(root, path);
5542 fprintf(stderr, "Error going to next leaf "
5549 leaf = path->nodes[0];
5551 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5552 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5557 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5558 csum_size) * root->sectorsize;
5559 if (!check_data_csum)
5560 goto skip_csum_check;
5561 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5562 ret = check_extent_csums(root, key.offset, data_len,
5568 offset = key.offset;
5569 } else if (key.offset != offset + num_bytes) {
5570 ret = check_extent_exists(root, offset, num_bytes);
5572 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5573 "there is no extent record\n",
5574 offset, offset+num_bytes);
5577 offset = key.offset;
5580 num_bytes += data_len;
5584 btrfs_free_path(path);
5588 static int is_dropped_key(struct btrfs_key *key,
5589 struct btrfs_key *drop_key) {
5590 if (key->objectid < drop_key->objectid)
5592 else if (key->objectid == drop_key->objectid) {
5593 if (key->type < drop_key->type)
5595 else if (key->type == drop_key->type) {
5596 if (key->offset < drop_key->offset)
5604 * Here are the rules for FULL_BACKREF.
5606 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5607 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5609 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5610 * if it happened after the relocation occurred since we'll have dropped the
5611 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5612 * have no real way to know for sure.
5614 * We process the blocks one root at a time, and we start from the lowest root
5615 * objectid and go to the highest. So we can just lookup the owner backref for
5616 * the record and if we don't find it then we know it doesn't exist and we have
5619 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5620 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5621 * be set or not and then we can check later once we've gathered all the refs.
5623 static int calc_extent_flag(struct btrfs_root *root,
5624 struct cache_tree *extent_cache,
5625 struct extent_buffer *buf,
5626 struct root_item_record *ri,
5629 struct extent_record *rec;
5630 struct cache_extent *cache;
5631 struct tree_backref *tback;
5634 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5635 /* we have added this extent before */
5637 rec = container_of(cache, struct extent_record, cache);
5640 * Except file/reloc tree, we can not have
5643 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5648 if (buf->start == ri->bytenr)
5651 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5654 owner = btrfs_header_owner(buf);
5655 if (owner == ri->objectid)
5658 tback = find_tree_backref(rec, 0, owner);
5663 if (rec->flag_block_full_backref != -1 &&
5664 rec->flag_block_full_backref != 0)
5665 rec->bad_full_backref = 1;
5668 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5669 if (rec->flag_block_full_backref != -1 &&
5670 rec->flag_block_full_backref != 1)
5671 rec->bad_full_backref = 1;
5675 static int run_next_block(struct btrfs_root *root,
5676 struct block_info *bits,
5679 struct cache_tree *pending,
5680 struct cache_tree *seen,
5681 struct cache_tree *reada,
5682 struct cache_tree *nodes,
5683 struct cache_tree *extent_cache,
5684 struct cache_tree *chunk_cache,
5685 struct rb_root *dev_cache,
5686 struct block_group_tree *block_group_cache,
5687 struct device_extent_tree *dev_extent_cache,
5688 struct root_item_record *ri)
5690 struct extent_buffer *buf;
5691 struct extent_record *rec = NULL;
5702 struct btrfs_key key;
5703 struct cache_extent *cache;
5706 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5707 bits_nr, &reada_bits);
5712 for(i = 0; i < nritems; i++) {
5713 ret = add_cache_extent(reada, bits[i].start,
5718 /* fixme, get the parent transid */
5719 readahead_tree_block(root, bits[i].start,
5723 *last = bits[0].start;
5724 bytenr = bits[0].start;
5725 size = bits[0].size;
5727 cache = lookup_cache_extent(pending, bytenr, size);
5729 remove_cache_extent(pending, cache);
5732 cache = lookup_cache_extent(reada, bytenr, size);
5734 remove_cache_extent(reada, cache);
5737 cache = lookup_cache_extent(nodes, bytenr, size);
5739 remove_cache_extent(nodes, cache);
5742 cache = lookup_cache_extent(extent_cache, bytenr, size);
5744 rec = container_of(cache, struct extent_record, cache);
5745 gen = rec->parent_generation;
5748 /* fixme, get the real parent transid */
5749 buf = read_tree_block(root, bytenr, size, gen);
5750 if (!extent_buffer_uptodate(buf)) {
5751 record_bad_block_io(root->fs_info,
5752 extent_cache, bytenr, size);
5756 nritems = btrfs_header_nritems(buf);
5759 if (!init_extent_tree) {
5760 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5761 btrfs_header_level(buf), 1, NULL,
5764 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5766 fprintf(stderr, "Couldn't calc extent flags\n");
5767 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5772 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5774 fprintf(stderr, "Couldn't calc extent flags\n");
5775 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5779 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5781 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5782 ri->objectid == btrfs_header_owner(buf)) {
5784 * Ok we got to this block from it's original owner and
5785 * we have FULL_BACKREF set. Relocation can leave
5786 * converted blocks over so this is altogether possible,
5787 * however it's not possible if the generation > the
5788 * last snapshot, so check for this case.
5790 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5791 btrfs_header_generation(buf) > ri->last_snapshot) {
5792 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5793 rec->bad_full_backref = 1;
5798 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5799 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5800 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5801 rec->bad_full_backref = 1;
5805 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5806 rec->flag_block_full_backref = 1;
5810 rec->flag_block_full_backref = 0;
5812 owner = btrfs_header_owner(buf);
5815 ret = check_block(root, extent_cache, buf, flags);
5819 if (btrfs_is_leaf(buf)) {
5820 btree_space_waste += btrfs_leaf_free_space(root, buf);
5821 for (i = 0; i < nritems; i++) {
5822 struct btrfs_file_extent_item *fi;
5823 btrfs_item_key_to_cpu(buf, &key, i);
5824 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5825 process_extent_item(root, extent_cache, buf,
5829 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5830 process_extent_item(root, extent_cache, buf,
5834 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5836 btrfs_item_size_nr(buf, i);
5839 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5840 process_chunk_item(chunk_cache, &key, buf, i);
5843 if (key.type == BTRFS_DEV_ITEM_KEY) {
5844 process_device_item(dev_cache, &key, buf, i);
5847 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5848 process_block_group_item(block_group_cache,
5852 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5853 process_device_extent_item(dev_extent_cache,
5858 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5859 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5860 process_extent_ref_v0(extent_cache, buf, i);
5867 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5868 add_tree_backref(extent_cache, key.objectid, 0,
5872 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5873 add_tree_backref(extent_cache, key.objectid,
5877 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5878 struct btrfs_extent_data_ref *ref;
5879 ref = btrfs_item_ptr(buf, i,
5880 struct btrfs_extent_data_ref);
5881 add_data_backref(extent_cache,
5883 btrfs_extent_data_ref_root(buf, ref),
5884 btrfs_extent_data_ref_objectid(buf,
5886 btrfs_extent_data_ref_offset(buf, ref),
5887 btrfs_extent_data_ref_count(buf, ref),
5888 0, root->sectorsize);
5891 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5892 struct btrfs_shared_data_ref *ref;
5893 ref = btrfs_item_ptr(buf, i,
5894 struct btrfs_shared_data_ref);
5895 add_data_backref(extent_cache,
5896 key.objectid, key.offset, 0, 0, 0,
5897 btrfs_shared_data_ref_count(buf, ref),
5898 0, root->sectorsize);
5901 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5902 struct bad_item *bad;
5904 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5908 bad = malloc(sizeof(struct bad_item));
5911 INIT_LIST_HEAD(&bad->list);
5912 memcpy(&bad->key, &key,
5913 sizeof(struct btrfs_key));
5914 bad->root_id = owner;
5915 list_add_tail(&bad->list, &delete_items);
5918 if (key.type != BTRFS_EXTENT_DATA_KEY)
5920 fi = btrfs_item_ptr(buf, i,
5921 struct btrfs_file_extent_item);
5922 if (btrfs_file_extent_type(buf, fi) ==
5923 BTRFS_FILE_EXTENT_INLINE)
5925 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5928 data_bytes_allocated +=
5929 btrfs_file_extent_disk_num_bytes(buf, fi);
5930 if (data_bytes_allocated < root->sectorsize) {
5933 data_bytes_referenced +=
5934 btrfs_file_extent_num_bytes(buf, fi);
5935 add_data_backref(extent_cache,
5936 btrfs_file_extent_disk_bytenr(buf, fi),
5937 parent, owner, key.objectid, key.offset -
5938 btrfs_file_extent_offset(buf, fi), 1, 1,
5939 btrfs_file_extent_disk_num_bytes(buf, fi));
5943 struct btrfs_key first_key;
5945 first_key.objectid = 0;
5948 btrfs_item_key_to_cpu(buf, &first_key, 0);
5949 level = btrfs_header_level(buf);
5950 for (i = 0; i < nritems; i++) {
5951 ptr = btrfs_node_blockptr(buf, i);
5952 size = btrfs_level_size(root, level - 1);
5953 btrfs_node_key_to_cpu(buf, &key, i);
5955 if ((level == ri->drop_level)
5956 && is_dropped_key(&key, &ri->drop_key)) {
5960 ret = add_extent_rec(extent_cache, &key,
5961 btrfs_node_ptr_generation(buf, i),
5962 ptr, size, 0, 0, 1, 0, 1, 0,
5966 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5969 add_pending(nodes, seen, ptr, size);
5971 add_pending(pending, seen, ptr, size);
5974 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5975 nritems) * sizeof(struct btrfs_key_ptr);
5977 total_btree_bytes += buf->len;
5978 if (fs_root_objectid(btrfs_header_owner(buf)))
5979 total_fs_tree_bytes += buf->len;
5980 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5981 total_extent_tree_bytes += buf->len;
5982 if (!found_old_backref &&
5983 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5984 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5985 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5986 found_old_backref = 1;
5988 free_extent_buffer(buf);
5992 static int add_root_to_pending(struct extent_buffer *buf,
5993 struct cache_tree *extent_cache,
5994 struct cache_tree *pending,
5995 struct cache_tree *seen,
5996 struct cache_tree *nodes,
5999 if (btrfs_header_level(buf) > 0)
6000 add_pending(nodes, seen, buf->start, buf->len);
6002 add_pending(pending, seen, buf->start, buf->len);
6003 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
6004 0, 1, 1, 0, 1, 0, buf->len);
6006 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
6007 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
6008 add_tree_backref(extent_cache, buf->start, buf->start,
6011 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
6015 /* as we fix the tree, we might be deleting blocks that
6016 * we're tracking for repair. This hook makes sure we
6017 * remove any backrefs for blocks as we are fixing them.
6019 static int free_extent_hook(struct btrfs_trans_handle *trans,
6020 struct btrfs_root *root,
6021 u64 bytenr, u64 num_bytes, u64 parent,
6022 u64 root_objectid, u64 owner, u64 offset,
6025 struct extent_record *rec;
6026 struct cache_extent *cache;
6028 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6030 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6031 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6035 rec = container_of(cache, struct extent_record, cache);
6037 struct data_backref *back;
6038 back = find_data_backref(rec, parent, root_objectid, owner,
6039 offset, 1, bytenr, num_bytes);
6042 if (back->node.found_ref) {
6043 back->found_ref -= refs_to_drop;
6045 rec->refs -= refs_to_drop;
6047 if (back->node.found_extent_tree) {
6048 back->num_refs -= refs_to_drop;
6049 if (rec->extent_item_refs)
6050 rec->extent_item_refs -= refs_to_drop;
6052 if (back->found_ref == 0)
6053 back->node.found_ref = 0;
6054 if (back->num_refs == 0)
6055 back->node.found_extent_tree = 0;
6057 if (!back->node.found_extent_tree && back->node.found_ref) {
6058 list_del(&back->node.list);
6062 struct tree_backref *back;
6063 back = find_tree_backref(rec, parent, root_objectid);
6066 if (back->node.found_ref) {
6069 back->node.found_ref = 0;
6071 if (back->node.found_extent_tree) {
6072 if (rec->extent_item_refs)
6073 rec->extent_item_refs--;
6074 back->node.found_extent_tree = 0;
6076 if (!back->node.found_extent_tree && back->node.found_ref) {
6077 list_del(&back->node.list);
6081 maybe_free_extent_rec(extent_cache, rec);
6086 static int delete_extent_records(struct btrfs_trans_handle *trans,
6087 struct btrfs_root *root,
6088 struct btrfs_path *path,
6089 u64 bytenr, u64 new_len)
6091 struct btrfs_key key;
6092 struct btrfs_key found_key;
6093 struct extent_buffer *leaf;
6098 key.objectid = bytenr;
6100 key.offset = (u64)-1;
6103 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6110 if (path->slots[0] == 0)
6116 leaf = path->nodes[0];
6117 slot = path->slots[0];
6119 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6120 if (found_key.objectid != bytenr)
6123 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6124 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6125 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6126 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6127 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6128 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6129 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6130 btrfs_release_path(path);
6131 if (found_key.type == 0) {
6132 if (found_key.offset == 0)
6134 key.offset = found_key.offset - 1;
6135 key.type = found_key.type;
6137 key.type = found_key.type - 1;
6138 key.offset = (u64)-1;
6142 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6143 found_key.objectid, found_key.type, found_key.offset);
6145 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6148 btrfs_release_path(path);
6150 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6151 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6152 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6153 found_key.offset : root->leafsize;
6155 ret = btrfs_update_block_group(trans, root, bytenr,
6162 btrfs_release_path(path);
6167 * for a single backref, this will allocate a new extent
6168 * and add the backref to it.
6170 static int record_extent(struct btrfs_trans_handle *trans,
6171 struct btrfs_fs_info *info,
6172 struct btrfs_path *path,
6173 struct extent_record *rec,
6174 struct extent_backref *back,
6175 int allocated, u64 flags)
6178 struct btrfs_root *extent_root = info->extent_root;
6179 struct extent_buffer *leaf;
6180 struct btrfs_key ins_key;
6181 struct btrfs_extent_item *ei;
6182 struct tree_backref *tback;
6183 struct data_backref *dback;
6184 struct btrfs_tree_block_info *bi;
6187 rec->max_size = max_t(u64, rec->max_size,
6188 info->extent_root->leafsize);
6191 u32 item_size = sizeof(*ei);
6194 item_size += sizeof(*bi);
6196 ins_key.objectid = rec->start;
6197 ins_key.offset = rec->max_size;
6198 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6200 ret = btrfs_insert_empty_item(trans, extent_root, path,
6201 &ins_key, item_size);
6205 leaf = path->nodes[0];
6206 ei = btrfs_item_ptr(leaf, path->slots[0],
6207 struct btrfs_extent_item);
6209 btrfs_set_extent_refs(leaf, ei, 0);
6210 btrfs_set_extent_generation(leaf, ei, rec->generation);
6212 if (back->is_data) {
6213 btrfs_set_extent_flags(leaf, ei,
6214 BTRFS_EXTENT_FLAG_DATA);
6216 struct btrfs_disk_key copy_key;;
6218 tback = (struct tree_backref *)back;
6219 bi = (struct btrfs_tree_block_info *)(ei + 1);
6220 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6223 btrfs_set_disk_key_objectid(©_key,
6224 rec->info_objectid);
6225 btrfs_set_disk_key_type(©_key, 0);
6226 btrfs_set_disk_key_offset(©_key, 0);
6228 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6229 btrfs_set_tree_block_key(leaf, bi, ©_key);
6231 btrfs_set_extent_flags(leaf, ei,
6232 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6235 btrfs_mark_buffer_dirty(leaf);
6236 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6237 rec->max_size, 1, 0);
6240 btrfs_release_path(path);
6243 if (back->is_data) {
6247 dback = (struct data_backref *)back;
6248 if (back->full_backref)
6249 parent = dback->parent;
6253 for (i = 0; i < dback->found_ref; i++) {
6254 /* if parent != 0, we're doing a full backref
6255 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6256 * just makes the backref allocator create a data
6259 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6260 rec->start, rec->max_size,
6264 BTRFS_FIRST_FREE_OBJECTID :
6270 fprintf(stderr, "adding new data backref"
6271 " on %llu %s %llu owner %llu"
6272 " offset %llu found %d\n",
6273 (unsigned long long)rec->start,
6274 back->full_backref ?
6276 back->full_backref ?
6277 (unsigned long long)parent :
6278 (unsigned long long)dback->root,
6279 (unsigned long long)dback->owner,
6280 (unsigned long long)dback->offset,
6285 tback = (struct tree_backref *)back;
6286 if (back->full_backref)
6287 parent = tback->parent;
6291 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6292 rec->start, rec->max_size,
6293 parent, tback->root, 0, 0);
6294 fprintf(stderr, "adding new tree backref on "
6295 "start %llu len %llu parent %llu root %llu\n",
6296 rec->start, rec->max_size, parent, tback->root);
6301 btrfs_release_path(path);
6305 struct extent_entry {
6310 struct list_head list;
6313 static struct extent_entry *find_entry(struct list_head *entries,
6314 u64 bytenr, u64 bytes)
6316 struct extent_entry *entry = NULL;
6318 list_for_each_entry(entry, entries, list) {
6319 if (entry->bytenr == bytenr && entry->bytes == bytes)
6326 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6328 struct extent_entry *entry, *best = NULL, *prev = NULL;
6330 list_for_each_entry(entry, entries, list) {
6337 * If there are as many broken entries as entries then we know
6338 * not to trust this particular entry.
6340 if (entry->broken == entry->count)
6344 * If our current entry == best then we can't be sure our best
6345 * is really the best, so we need to keep searching.
6347 if (best && best->count == entry->count) {
6353 /* Prev == entry, not good enough, have to keep searching */
6354 if (!prev->broken && prev->count == entry->count)
6358 best = (prev->count > entry->count) ? prev : entry;
6359 else if (best->count < entry->count)
6367 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6368 struct data_backref *dback, struct extent_entry *entry)
6370 struct btrfs_trans_handle *trans;
6371 struct btrfs_root *root;
6372 struct btrfs_file_extent_item *fi;
6373 struct extent_buffer *leaf;
6374 struct btrfs_key key;
6378 key.objectid = dback->root;
6379 key.type = BTRFS_ROOT_ITEM_KEY;
6380 key.offset = (u64)-1;
6381 root = btrfs_read_fs_root(info, &key);
6383 fprintf(stderr, "Couldn't find root for our ref\n");
6388 * The backref points to the original offset of the extent if it was
6389 * split, so we need to search down to the offset we have and then walk
6390 * forward until we find the backref we're looking for.
6392 key.objectid = dback->owner;
6393 key.type = BTRFS_EXTENT_DATA_KEY;
6394 key.offset = dback->offset;
6395 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6397 fprintf(stderr, "Error looking up ref %d\n", ret);
6402 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6403 ret = btrfs_next_leaf(root, path);
6405 fprintf(stderr, "Couldn't find our ref, next\n");
6409 leaf = path->nodes[0];
6410 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6411 if (key.objectid != dback->owner ||
6412 key.type != BTRFS_EXTENT_DATA_KEY) {
6413 fprintf(stderr, "Couldn't find our ref, search\n");
6416 fi = btrfs_item_ptr(leaf, path->slots[0],
6417 struct btrfs_file_extent_item);
6418 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6419 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6421 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6426 btrfs_release_path(path);
6428 trans = btrfs_start_transaction(root, 1);
6430 return PTR_ERR(trans);
6433 * Ok we have the key of the file extent we want to fix, now we can cow
6434 * down to the thing and fix it.
6436 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6438 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6439 key.objectid, key.type, key.offset, ret);
6443 fprintf(stderr, "Well that's odd, we just found this key "
6444 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6449 leaf = path->nodes[0];
6450 fi = btrfs_item_ptr(leaf, path->slots[0],
6451 struct btrfs_file_extent_item);
6453 if (btrfs_file_extent_compression(leaf, fi) &&
6454 dback->disk_bytenr != entry->bytenr) {
6455 fprintf(stderr, "Ref doesn't match the record start and is "
6456 "compressed, please take a btrfs-image of this file "
6457 "system and send it to a btrfs developer so they can "
6458 "complete this functionality for bytenr %Lu\n",
6459 dback->disk_bytenr);
6464 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6465 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6466 } else if (dback->disk_bytenr > entry->bytenr) {
6467 u64 off_diff, offset;
6469 off_diff = dback->disk_bytenr - entry->bytenr;
6470 offset = btrfs_file_extent_offset(leaf, fi);
6471 if (dback->disk_bytenr + offset +
6472 btrfs_file_extent_num_bytes(leaf, fi) >
6473 entry->bytenr + entry->bytes) {
6474 fprintf(stderr, "Ref is past the entry end, please "
6475 "take a btrfs-image of this file system and "
6476 "send it to a btrfs developer, ref %Lu\n",
6477 dback->disk_bytenr);
6482 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6483 btrfs_set_file_extent_offset(leaf, fi, offset);
6484 } else if (dback->disk_bytenr < entry->bytenr) {
6487 offset = btrfs_file_extent_offset(leaf, fi);
6488 if (dback->disk_bytenr + offset < entry->bytenr) {
6489 fprintf(stderr, "Ref is before the entry start, please"
6490 " take a btrfs-image of this file system and "
6491 "send it to a btrfs developer, ref %Lu\n",
6492 dback->disk_bytenr);
6497 offset += dback->disk_bytenr;
6498 offset -= entry->bytenr;
6499 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6500 btrfs_set_file_extent_offset(leaf, fi, offset);
6503 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6506 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6507 * only do this if we aren't using compression, otherwise it's a
6510 if (!btrfs_file_extent_compression(leaf, fi))
6511 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6513 printf("ram bytes may be wrong?\n");
6514 btrfs_mark_buffer_dirty(leaf);
6516 err = btrfs_commit_transaction(trans, root);
6517 btrfs_release_path(path);
6518 return ret ? ret : err;
6521 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6522 struct extent_record *rec)
6524 struct extent_backref *back;
6525 struct data_backref *dback;
6526 struct extent_entry *entry, *best = NULL;
6529 int broken_entries = 0;
6534 * Metadata is easy and the backrefs should always agree on bytenr and
6535 * size, if not we've got bigger issues.
6540 list_for_each_entry(back, &rec->backrefs, list) {
6541 if (back->full_backref || !back->is_data)
6544 dback = (struct data_backref *)back;
6547 * We only pay attention to backrefs that we found a real
6550 if (dback->found_ref == 0)
6554 * For now we only catch when the bytes don't match, not the
6555 * bytenr. We can easily do this at the same time, but I want
6556 * to have a fs image to test on before we just add repair
6557 * functionality willy-nilly so we know we won't screw up the
6561 entry = find_entry(&entries, dback->disk_bytenr,
6564 entry = malloc(sizeof(struct extent_entry));
6569 memset(entry, 0, sizeof(*entry));
6570 entry->bytenr = dback->disk_bytenr;
6571 entry->bytes = dback->bytes;
6572 list_add_tail(&entry->list, &entries);
6577 * If we only have on entry we may think the entries agree when
6578 * in reality they don't so we have to do some extra checking.
6580 if (dback->disk_bytenr != rec->start ||
6581 dback->bytes != rec->nr || back->broken)
6592 /* Yay all the backrefs agree, carry on good sir */
6593 if (nr_entries <= 1 && !mismatch)
6596 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6597 "%Lu\n", rec->start);
6600 * First we want to see if the backrefs can agree amongst themselves who
6601 * is right, so figure out which one of the entries has the highest
6604 best = find_most_right_entry(&entries);
6607 * Ok so we may have an even split between what the backrefs think, so
6608 * this is where we use the extent ref to see what it thinks.
6611 entry = find_entry(&entries, rec->start, rec->nr);
6612 if (!entry && (!broken_entries || !rec->found_rec)) {
6613 fprintf(stderr, "Backrefs don't agree with each other "
6614 "and extent record doesn't agree with anybody,"
6615 " so we can't fix bytenr %Lu bytes %Lu\n",
6616 rec->start, rec->nr);
6619 } else if (!entry) {
6621 * Ok our backrefs were broken, we'll assume this is the
6622 * correct value and add an entry for this range.
6624 entry = malloc(sizeof(struct extent_entry));
6629 memset(entry, 0, sizeof(*entry));
6630 entry->bytenr = rec->start;
6631 entry->bytes = rec->nr;
6632 list_add_tail(&entry->list, &entries);
6636 best = find_most_right_entry(&entries);
6638 fprintf(stderr, "Backrefs and extent record evenly "
6639 "split on who is right, this is going to "
6640 "require user input to fix bytenr %Lu bytes "
6641 "%Lu\n", rec->start, rec->nr);
6648 * I don't think this can happen currently as we'll abort() if we catch
6649 * this case higher up, but in case somebody removes that we still can't
6650 * deal with it properly here yet, so just bail out of that's the case.
6652 if (best->bytenr != rec->start) {
6653 fprintf(stderr, "Extent start and backref starts don't match, "
6654 "please use btrfs-image on this file system and send "
6655 "it to a btrfs developer so they can make fsck fix "
6656 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6657 rec->start, rec->nr);
6663 * Ok great we all agreed on an extent record, let's go find the real
6664 * references and fix up the ones that don't match.
6666 list_for_each_entry(back, &rec->backrefs, list) {
6667 if (back->full_backref || !back->is_data)
6670 dback = (struct data_backref *)back;
6673 * Still ignoring backrefs that don't have a real ref attached
6676 if (dback->found_ref == 0)
6679 if (dback->bytes == best->bytes &&
6680 dback->disk_bytenr == best->bytenr)
6683 ret = repair_ref(info, path, dback, best);
6689 * Ok we messed with the actual refs, which means we need to drop our
6690 * entire cache and go back and rescan. I know this is a huge pain and
6691 * adds a lot of extra work, but it's the only way to be safe. Once all
6692 * the backrefs agree we may not need to do anything to the extent
6697 while (!list_empty(&entries)) {
6698 entry = list_entry(entries.next, struct extent_entry, list);
6699 list_del_init(&entry->list);
6705 static int process_duplicates(struct btrfs_root *root,
6706 struct cache_tree *extent_cache,
6707 struct extent_record *rec)
6709 struct extent_record *good, *tmp;
6710 struct cache_extent *cache;
6714 * If we found a extent record for this extent then return, or if we
6715 * have more than one duplicate we are likely going to need to delete
6718 if (rec->found_rec || rec->num_duplicates > 1)
6721 /* Shouldn't happen but just in case */
6722 BUG_ON(!rec->num_duplicates);
6725 * So this happens if we end up with a backref that doesn't match the
6726 * actual extent entry. So either the backref is bad or the extent
6727 * entry is bad. Either way we want to have the extent_record actually
6728 * reflect what we found in the extent_tree, so we need to take the
6729 * duplicate out and use that as the extent_record since the only way we
6730 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6732 remove_cache_extent(extent_cache, &rec->cache);
6734 good = list_entry(rec->dups.next, struct extent_record, list);
6735 list_del_init(&good->list);
6736 INIT_LIST_HEAD(&good->backrefs);
6737 INIT_LIST_HEAD(&good->dups);
6738 good->cache.start = good->start;
6739 good->cache.size = good->nr;
6740 good->content_checked = 0;
6741 good->owner_ref_checked = 0;
6742 good->num_duplicates = 0;
6743 good->refs = rec->refs;
6744 list_splice_init(&rec->backrefs, &good->backrefs);
6746 cache = lookup_cache_extent(extent_cache, good->start,
6750 tmp = container_of(cache, struct extent_record, cache);
6753 * If we find another overlapping extent and it's found_rec is
6754 * set then it's a duplicate and we need to try and delete
6757 if (tmp->found_rec || tmp->num_duplicates > 0) {
6758 if (list_empty(&good->list))
6759 list_add_tail(&good->list,
6760 &duplicate_extents);
6761 good->num_duplicates += tmp->num_duplicates + 1;
6762 list_splice_init(&tmp->dups, &good->dups);
6763 list_del_init(&tmp->list);
6764 list_add_tail(&tmp->list, &good->dups);
6765 remove_cache_extent(extent_cache, &tmp->cache);
6770 * Ok we have another non extent item backed extent rec, so lets
6771 * just add it to this extent and carry on like we did above.
6773 good->refs += tmp->refs;
6774 list_splice_init(&tmp->backrefs, &good->backrefs);
6775 remove_cache_extent(extent_cache, &tmp->cache);
6778 ret = insert_cache_extent(extent_cache, &good->cache);
6781 return good->num_duplicates ? 0 : 1;
6784 static int delete_duplicate_records(struct btrfs_root *root,
6785 struct extent_record *rec)
6787 struct btrfs_trans_handle *trans;
6788 LIST_HEAD(delete_list);
6789 struct btrfs_path *path;
6790 struct extent_record *tmp, *good, *n;
6793 struct btrfs_key key;
6795 path = btrfs_alloc_path();
6802 /* Find the record that covers all of the duplicates. */
6803 list_for_each_entry(tmp, &rec->dups, list) {
6804 if (good->start < tmp->start)
6806 if (good->nr > tmp->nr)
6809 if (tmp->start + tmp->nr < good->start + good->nr) {
6810 fprintf(stderr, "Ok we have overlapping extents that "
6811 "aren't completely covered by eachother, this "
6812 "is going to require more careful thought. "
6813 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6814 tmp->start, tmp->nr, good->start, good->nr);
6821 list_add_tail(&rec->list, &delete_list);
6823 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6826 list_move_tail(&tmp->list, &delete_list);
6829 root = root->fs_info->extent_root;
6830 trans = btrfs_start_transaction(root, 1);
6831 if (IS_ERR(trans)) {
6832 ret = PTR_ERR(trans);
6836 list_for_each_entry(tmp, &delete_list, list) {
6837 if (tmp->found_rec == 0)
6839 key.objectid = tmp->start;
6840 key.type = BTRFS_EXTENT_ITEM_KEY;
6841 key.offset = tmp->nr;
6843 /* Shouldn't happen but just in case */
6844 if (tmp->metadata) {
6845 fprintf(stderr, "Well this shouldn't happen, extent "
6846 "record overlaps but is metadata? "
6847 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6851 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6857 ret = btrfs_del_item(trans, root, path);
6860 btrfs_release_path(path);
6863 err = btrfs_commit_transaction(trans, root);
6867 while (!list_empty(&delete_list)) {
6868 tmp = list_entry(delete_list.next, struct extent_record, list);
6869 list_del_init(&tmp->list);
6875 while (!list_empty(&rec->dups)) {
6876 tmp = list_entry(rec->dups.next, struct extent_record, list);
6877 list_del_init(&tmp->list);
6881 btrfs_free_path(path);
6883 if (!ret && !nr_del)
6884 rec->num_duplicates = 0;
6886 return ret ? ret : nr_del;
6889 static int find_possible_backrefs(struct btrfs_fs_info *info,
6890 struct btrfs_path *path,
6891 struct cache_tree *extent_cache,
6892 struct extent_record *rec)
6894 struct btrfs_root *root;
6895 struct extent_backref *back;
6896 struct data_backref *dback;
6897 struct cache_extent *cache;
6898 struct btrfs_file_extent_item *fi;
6899 struct btrfs_key key;
6903 list_for_each_entry(back, &rec->backrefs, list) {
6904 /* Don't care about full backrefs (poor unloved backrefs) */
6905 if (back->full_backref || !back->is_data)
6908 dback = (struct data_backref *)back;
6910 /* We found this one, we don't need to do a lookup */
6911 if (dback->found_ref)
6914 key.objectid = dback->root;
6915 key.type = BTRFS_ROOT_ITEM_KEY;
6916 key.offset = (u64)-1;
6918 root = btrfs_read_fs_root(info, &key);
6920 /* No root, definitely a bad ref, skip */
6921 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6923 /* Other err, exit */
6925 return PTR_ERR(root);
6927 key.objectid = dback->owner;
6928 key.type = BTRFS_EXTENT_DATA_KEY;
6929 key.offset = dback->offset;
6930 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6932 btrfs_release_path(path);
6935 /* Didn't find it, we can carry on */
6940 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6941 struct btrfs_file_extent_item);
6942 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6943 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6944 btrfs_release_path(path);
6945 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6947 struct extent_record *tmp;
6948 tmp = container_of(cache, struct extent_record, cache);
6951 * If we found an extent record for the bytenr for this
6952 * particular backref then we can't add it to our
6953 * current extent record. We only want to add backrefs
6954 * that don't have a corresponding extent item in the
6955 * extent tree since they likely belong to this record
6956 * and we need to fix it if it doesn't match bytenrs.
6962 dback->found_ref += 1;
6963 dback->disk_bytenr = bytenr;
6964 dback->bytes = bytes;
6967 * Set this so the verify backref code knows not to trust the
6968 * values in this backref.
6977 * Record orphan data ref into corresponding root.
6979 * Return 0 if the extent item contains data ref and recorded.
6980 * Return 1 if the extent item contains no useful data ref
6981 * On that case, it may contains only shared_dataref or metadata backref
6982 * or the file extent exists(this should be handled by the extent bytenr
6984 * Return <0 if something goes wrong.
6986 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6987 struct extent_record *rec)
6989 struct btrfs_key key;
6990 struct btrfs_root *dest_root;
6991 struct extent_backref *back;
6992 struct data_backref *dback;
6993 struct orphan_data_extent *orphan;
6994 struct btrfs_path *path;
6995 int recorded_data_ref = 0;
7000 path = btrfs_alloc_path();
7003 list_for_each_entry(back, &rec->backrefs, list) {
7004 if (back->full_backref || !back->is_data ||
7005 !back->found_extent_tree)
7007 dback = (struct data_backref *)back;
7008 if (dback->found_ref)
7010 key.objectid = dback->root;
7011 key.type = BTRFS_ROOT_ITEM_KEY;
7012 key.offset = (u64)-1;
7014 dest_root = btrfs_read_fs_root(fs_info, &key);
7016 /* For non-exist root we just skip it */
7017 if (IS_ERR(dest_root) || !dest_root)
7020 key.objectid = dback->owner;
7021 key.type = BTRFS_EXTENT_DATA_KEY;
7022 key.offset = dback->offset;
7024 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7026 * For ret < 0, it's OK since the fs-tree may be corrupted,
7027 * we need to record it for inode/file extent rebuild.
7028 * For ret > 0, we record it only for file extent rebuild.
7029 * For ret == 0, the file extent exists but only bytenr
7030 * mismatch, let the original bytenr fix routine to handle,
7036 orphan = malloc(sizeof(*orphan));
7041 INIT_LIST_HEAD(&orphan->list);
7042 orphan->root = dback->root;
7043 orphan->objectid = dback->owner;
7044 orphan->offset = dback->offset;
7045 orphan->disk_bytenr = rec->cache.start;
7046 orphan->disk_len = rec->cache.size;
7047 list_add(&dest_root->orphan_data_extents, &orphan->list);
7048 recorded_data_ref = 1;
7051 btrfs_free_path(path);
7053 return !recorded_data_ref;
7059 * when an incorrect extent item is found, this will delete
7060 * all of the existing entries for it and recreate them
7061 * based on what the tree scan found.
7063 static int fixup_extent_refs(struct btrfs_fs_info *info,
7064 struct cache_tree *extent_cache,
7065 struct extent_record *rec)
7067 struct btrfs_trans_handle *trans = NULL;
7069 struct btrfs_path *path;
7070 struct list_head *cur = rec->backrefs.next;
7071 struct cache_extent *cache;
7072 struct extent_backref *back;
7076 if (rec->flag_block_full_backref)
7077 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7079 path = btrfs_alloc_path();
7083 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7085 * Sometimes the backrefs themselves are so broken they don't
7086 * get attached to any meaningful rec, so first go back and
7087 * check any of our backrefs that we couldn't find and throw
7088 * them into the list if we find the backref so that
7089 * verify_backrefs can figure out what to do.
7091 ret = find_possible_backrefs(info, path, extent_cache, rec);
7096 /* step one, make sure all of the backrefs agree */
7097 ret = verify_backrefs(info, path, rec);
7101 trans = btrfs_start_transaction(info->extent_root, 1);
7102 if (IS_ERR(trans)) {
7103 ret = PTR_ERR(trans);
7107 /* step two, delete all the existing records */
7108 ret = delete_extent_records(trans, info->extent_root, path,
7109 rec->start, rec->max_size);
7114 /* was this block corrupt? If so, don't add references to it */
7115 cache = lookup_cache_extent(info->corrupt_blocks,
7116 rec->start, rec->max_size);
7122 /* step three, recreate all the refs we did find */
7123 while(cur != &rec->backrefs) {
7124 back = list_entry(cur, struct extent_backref, list);
7128 * if we didn't find any references, don't create a
7131 if (!back->found_ref)
7134 rec->bad_full_backref = 0;
7135 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7143 int err = btrfs_commit_transaction(trans, info->extent_root);
7148 btrfs_free_path(path);
7152 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7153 struct extent_record *rec)
7155 struct btrfs_trans_handle *trans;
7156 struct btrfs_root *root = fs_info->extent_root;
7157 struct btrfs_path *path;
7158 struct btrfs_extent_item *ei;
7159 struct btrfs_key key;
7163 key.objectid = rec->start;
7164 if (rec->metadata) {
7165 key.type = BTRFS_METADATA_ITEM_KEY;
7166 key.offset = rec->info_level;
7168 key.type = BTRFS_EXTENT_ITEM_KEY;
7169 key.offset = rec->max_size;
7172 path = btrfs_alloc_path();
7176 trans = btrfs_start_transaction(root, 0);
7177 if (IS_ERR(trans)) {
7178 btrfs_free_path(path);
7179 return PTR_ERR(trans);
7182 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7184 btrfs_free_path(path);
7185 btrfs_commit_transaction(trans, root);
7188 fprintf(stderr, "Didn't find extent for %llu\n",
7189 (unsigned long long)rec->start);
7190 btrfs_free_path(path);
7191 btrfs_commit_transaction(trans, root);
7195 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7196 struct btrfs_extent_item);
7197 flags = btrfs_extent_flags(path->nodes[0], ei);
7198 if (rec->flag_block_full_backref) {
7199 fprintf(stderr, "setting full backref on %llu\n",
7200 (unsigned long long)key.objectid);
7201 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7203 fprintf(stderr, "clearing full backref on %llu\n",
7204 (unsigned long long)key.objectid);
7205 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7207 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7208 btrfs_mark_buffer_dirty(path->nodes[0]);
7209 btrfs_free_path(path);
7210 return btrfs_commit_transaction(trans, root);
7213 /* right now we only prune from the extent allocation tree */
7214 static int prune_one_block(struct btrfs_trans_handle *trans,
7215 struct btrfs_fs_info *info,
7216 struct btrfs_corrupt_block *corrupt)
7219 struct btrfs_path path;
7220 struct extent_buffer *eb;
7224 int level = corrupt->level + 1;
7226 btrfs_init_path(&path);
7228 /* we want to stop at the parent to our busted block */
7229 path.lowest_level = level;
7231 ret = btrfs_search_slot(trans, info->extent_root,
7232 &corrupt->key, &path, -1, 1);
7237 eb = path.nodes[level];
7244 * hopefully the search gave us the block we want to prune,
7245 * lets try that first
7247 slot = path.slots[level];
7248 found = btrfs_node_blockptr(eb, slot);
7249 if (found == corrupt->cache.start)
7252 nritems = btrfs_header_nritems(eb);
7254 /* the search failed, lets scan this node and hope we find it */
7255 for (slot = 0; slot < nritems; slot++) {
7256 found = btrfs_node_blockptr(eb, slot);
7257 if (found == corrupt->cache.start)
7261 * we couldn't find the bad block. TODO, search all the nodes for pointers
7264 if (eb == info->extent_root->node) {
7269 btrfs_release_path(&path);
7274 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7275 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7278 btrfs_release_path(&path);
7282 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7284 struct btrfs_trans_handle *trans = NULL;
7285 struct cache_extent *cache;
7286 struct btrfs_corrupt_block *corrupt;
7289 cache = search_cache_extent(info->corrupt_blocks, 0);
7293 trans = btrfs_start_transaction(info->extent_root, 1);
7295 return PTR_ERR(trans);
7297 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7298 prune_one_block(trans, info, corrupt);
7299 remove_cache_extent(info->corrupt_blocks, cache);
7302 return btrfs_commit_transaction(trans, info->extent_root);
7306 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7308 struct btrfs_block_group_cache *cache;
7313 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7314 &start, &end, EXTENT_DIRTY);
7317 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7323 cache = btrfs_lookup_first_block_group(fs_info, start);
7328 start = cache->key.objectid + cache->key.offset;
7332 static int check_extent_refs(struct btrfs_root *root,
7333 struct cache_tree *extent_cache)
7335 struct extent_record *rec;
7336 struct cache_extent *cache;
7345 * if we're doing a repair, we have to make sure
7346 * we don't allocate from the problem extents.
7347 * In the worst case, this will be all the
7350 cache = search_cache_extent(extent_cache, 0);
7352 rec = container_of(cache, struct extent_record, cache);
7353 set_extent_dirty(root->fs_info->excluded_extents,
7355 rec->start + rec->max_size - 1,
7357 cache = next_cache_extent(cache);
7360 /* pin down all the corrupted blocks too */
7361 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7363 set_extent_dirty(root->fs_info->excluded_extents,
7365 cache->start + cache->size - 1,
7367 cache = next_cache_extent(cache);
7369 prune_corrupt_blocks(root->fs_info);
7370 reset_cached_block_groups(root->fs_info);
7373 reset_cached_block_groups(root->fs_info);
7376 * We need to delete any duplicate entries we find first otherwise we
7377 * could mess up the extent tree when we have backrefs that actually
7378 * belong to a different extent item and not the weird duplicate one.
7380 while (repair && !list_empty(&duplicate_extents)) {
7381 rec = list_entry(duplicate_extents.next, struct extent_record,
7383 list_del_init(&rec->list);
7385 /* Sometimes we can find a backref before we find an actual
7386 * extent, so we need to process it a little bit to see if there
7387 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7388 * if this is a backref screwup. If we need to delete stuff
7389 * process_duplicates() will return 0, otherwise it will return
7392 if (process_duplicates(root, extent_cache, rec))
7394 ret = delete_duplicate_records(root, rec);
7398 * delete_duplicate_records will return the number of entries
7399 * deleted, so if it's greater than 0 then we know we actually
7400 * did something and we need to remove.
7414 cache = search_cache_extent(extent_cache, 0);
7417 rec = container_of(cache, struct extent_record, cache);
7418 if (rec->num_duplicates) {
7419 fprintf(stderr, "extent item %llu has multiple extent "
7420 "items\n", (unsigned long long)rec->start);
7425 if (rec->refs != rec->extent_item_refs) {
7426 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7427 (unsigned long long)rec->start,
7428 (unsigned long long)rec->nr);
7429 fprintf(stderr, "extent item %llu, found %llu\n",
7430 (unsigned long long)rec->extent_item_refs,
7431 (unsigned long long)rec->refs);
7432 ret = record_orphan_data_extents(root->fs_info, rec);
7439 * we can't use the extent to repair file
7440 * extent, let the fallback method handle it.
7442 if (!fixed && repair) {
7443 ret = fixup_extent_refs(
7454 if (all_backpointers_checked(rec, 1)) {
7455 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7456 (unsigned long long)rec->start,
7457 (unsigned long long)rec->nr);
7459 if (!fixed && !recorded && repair) {
7460 ret = fixup_extent_refs(root->fs_info,
7469 if (!rec->owner_ref_checked) {
7470 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7471 (unsigned long long)rec->start,
7472 (unsigned long long)rec->nr);
7473 if (!fixed && !recorded && repair) {
7474 ret = fixup_extent_refs(root->fs_info,
7483 if (rec->bad_full_backref) {
7484 fprintf(stderr, "bad full backref, on [%llu]\n",
7485 (unsigned long long)rec->start);
7487 ret = fixup_extent_flags(root->fs_info, rec);
7496 * Although it's not a extent ref's problem, we reuse this
7497 * routine for error reporting.
7498 * No repair function yet.
7500 if (rec->crossing_stripes) {
7502 "bad metadata [%llu, %llu) crossing stripe boundary\n",
7503 rec->start, rec->start + rec->max_size);
7508 remove_cache_extent(extent_cache, cache);
7509 free_all_extent_backrefs(rec);
7510 if (!init_extent_tree && repair && (!cur_err || fixed))
7511 clear_extent_dirty(root->fs_info->excluded_extents,
7513 rec->start + rec->max_size - 1,
7519 if (ret && ret != -EAGAIN) {
7520 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7523 struct btrfs_trans_handle *trans;
7525 root = root->fs_info->extent_root;
7526 trans = btrfs_start_transaction(root, 1);
7527 if (IS_ERR(trans)) {
7528 ret = PTR_ERR(trans);
7532 btrfs_fix_block_accounting(trans, root);
7533 ret = btrfs_commit_transaction(trans, root);
7538 fprintf(stderr, "repaired damaged extent references\n");
7544 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7548 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7549 stripe_size = length;
7550 stripe_size /= num_stripes;
7551 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7552 stripe_size = length * 2;
7553 stripe_size /= num_stripes;
7554 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7555 stripe_size = length;
7556 stripe_size /= (num_stripes - 1);
7557 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7558 stripe_size = length;
7559 stripe_size /= (num_stripes - 2);
7561 stripe_size = length;
7567 * Check the chunk with its block group/dev list ref:
7568 * Return 0 if all refs seems valid.
7569 * Return 1 if part of refs seems valid, need later check for rebuild ref
7570 * like missing block group and needs to search extent tree to rebuild them.
7571 * Return -1 if essential refs are missing and unable to rebuild.
7573 static int check_chunk_refs(struct chunk_record *chunk_rec,
7574 struct block_group_tree *block_group_cache,
7575 struct device_extent_tree *dev_extent_cache,
7578 struct cache_extent *block_group_item;
7579 struct block_group_record *block_group_rec;
7580 struct cache_extent *dev_extent_item;
7581 struct device_extent_record *dev_extent_rec;
7585 int metadump_v2 = 0;
7589 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7592 if (block_group_item) {
7593 block_group_rec = container_of(block_group_item,
7594 struct block_group_record,
7596 if (chunk_rec->length != block_group_rec->offset ||
7597 chunk_rec->offset != block_group_rec->objectid ||
7599 chunk_rec->type_flags != block_group_rec->flags)) {
7602 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7603 chunk_rec->objectid,
7608 chunk_rec->type_flags,
7609 block_group_rec->objectid,
7610 block_group_rec->type,
7611 block_group_rec->offset,
7612 block_group_rec->offset,
7613 block_group_rec->objectid,
7614 block_group_rec->flags);
7617 list_del_init(&block_group_rec->list);
7618 chunk_rec->bg_rec = block_group_rec;
7623 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7624 chunk_rec->objectid,
7629 chunk_rec->type_flags);
7636 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7637 chunk_rec->num_stripes);
7638 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7639 devid = chunk_rec->stripes[i].devid;
7640 offset = chunk_rec->stripes[i].offset;
7641 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7642 devid, offset, length);
7643 if (dev_extent_item) {
7644 dev_extent_rec = container_of(dev_extent_item,
7645 struct device_extent_record,
7647 if (dev_extent_rec->objectid != devid ||
7648 dev_extent_rec->offset != offset ||
7649 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7650 dev_extent_rec->length != length) {
7653 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7654 chunk_rec->objectid,
7657 chunk_rec->stripes[i].devid,
7658 chunk_rec->stripes[i].offset,
7659 dev_extent_rec->objectid,
7660 dev_extent_rec->offset,
7661 dev_extent_rec->length);
7664 list_move(&dev_extent_rec->chunk_list,
7665 &chunk_rec->dextents);
7670 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7671 chunk_rec->objectid,
7674 chunk_rec->stripes[i].devid,
7675 chunk_rec->stripes[i].offset);
7682 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7683 int check_chunks(struct cache_tree *chunk_cache,
7684 struct block_group_tree *block_group_cache,
7685 struct device_extent_tree *dev_extent_cache,
7686 struct list_head *good, struct list_head *bad,
7687 struct list_head *rebuild, int silent)
7689 struct cache_extent *chunk_item;
7690 struct chunk_record *chunk_rec;
7691 struct block_group_record *bg_rec;
7692 struct device_extent_record *dext_rec;
7696 chunk_item = first_cache_extent(chunk_cache);
7697 while (chunk_item) {
7698 chunk_rec = container_of(chunk_item, struct chunk_record,
7700 err = check_chunk_refs(chunk_rec, block_group_cache,
7701 dev_extent_cache, silent);
7704 if (err == 0 && good)
7705 list_add_tail(&chunk_rec->list, good);
7706 if (err > 0 && rebuild)
7707 list_add_tail(&chunk_rec->list, rebuild);
7709 list_add_tail(&chunk_rec->list, bad);
7710 chunk_item = next_cache_extent(chunk_item);
7713 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7716 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7724 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7728 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7739 static int check_device_used(struct device_record *dev_rec,
7740 struct device_extent_tree *dext_cache)
7742 struct cache_extent *cache;
7743 struct device_extent_record *dev_extent_rec;
7746 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7748 dev_extent_rec = container_of(cache,
7749 struct device_extent_record,
7751 if (dev_extent_rec->objectid != dev_rec->devid)
7754 list_del_init(&dev_extent_rec->device_list);
7755 total_byte += dev_extent_rec->length;
7756 cache = next_cache_extent(cache);
7759 if (total_byte != dev_rec->byte_used) {
7761 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7762 total_byte, dev_rec->byte_used, dev_rec->objectid,
7763 dev_rec->type, dev_rec->offset);
7770 /* check btrfs_dev_item -> btrfs_dev_extent */
7771 static int check_devices(struct rb_root *dev_cache,
7772 struct device_extent_tree *dev_extent_cache)
7774 struct rb_node *dev_node;
7775 struct device_record *dev_rec;
7776 struct device_extent_record *dext_rec;
7780 dev_node = rb_first(dev_cache);
7782 dev_rec = container_of(dev_node, struct device_record, node);
7783 err = check_device_used(dev_rec, dev_extent_cache);
7787 dev_node = rb_next(dev_node);
7789 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7792 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7793 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7800 static int add_root_item_to_list(struct list_head *head,
7801 u64 objectid, u64 bytenr, u64 last_snapshot,
7802 u8 level, u8 drop_level,
7803 int level_size, struct btrfs_key *drop_key)
7806 struct root_item_record *ri_rec;
7807 ri_rec = malloc(sizeof(*ri_rec));
7810 ri_rec->bytenr = bytenr;
7811 ri_rec->objectid = objectid;
7812 ri_rec->level = level;
7813 ri_rec->level_size = level_size;
7814 ri_rec->drop_level = drop_level;
7815 ri_rec->last_snapshot = last_snapshot;
7817 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7818 list_add_tail(&ri_rec->list, head);
7823 static void free_root_item_list(struct list_head *list)
7825 struct root_item_record *ri_rec;
7827 while (!list_empty(list)) {
7828 ri_rec = list_first_entry(list, struct root_item_record,
7830 list_del_init(&ri_rec->list);
7835 static int deal_root_from_list(struct list_head *list,
7836 struct btrfs_root *root,
7837 struct block_info *bits,
7839 struct cache_tree *pending,
7840 struct cache_tree *seen,
7841 struct cache_tree *reada,
7842 struct cache_tree *nodes,
7843 struct cache_tree *extent_cache,
7844 struct cache_tree *chunk_cache,
7845 struct rb_root *dev_cache,
7846 struct block_group_tree *block_group_cache,
7847 struct device_extent_tree *dev_extent_cache)
7852 while (!list_empty(list)) {
7853 struct root_item_record *rec;
7854 struct extent_buffer *buf;
7855 rec = list_entry(list->next,
7856 struct root_item_record, list);
7858 buf = read_tree_block(root->fs_info->tree_root,
7859 rec->bytenr, rec->level_size, 0);
7860 if (!extent_buffer_uptodate(buf)) {
7861 free_extent_buffer(buf);
7865 add_root_to_pending(buf, extent_cache, pending,
7866 seen, nodes, rec->objectid);
7868 * To rebuild extent tree, we need deal with snapshot
7869 * one by one, otherwise we deal with node firstly which
7870 * can maximize readahead.
7873 ret = run_next_block(root, bits, bits_nr, &last,
7874 pending, seen, reada, nodes,
7875 extent_cache, chunk_cache,
7876 dev_cache, block_group_cache,
7877 dev_extent_cache, rec);
7881 free_extent_buffer(buf);
7882 list_del(&rec->list);
7888 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7889 reada, nodes, extent_cache, chunk_cache,
7890 dev_cache, block_group_cache,
7891 dev_extent_cache, NULL);
7901 static int check_chunks_and_extents(struct btrfs_root *root)
7903 struct rb_root dev_cache;
7904 struct cache_tree chunk_cache;
7905 struct block_group_tree block_group_cache;
7906 struct device_extent_tree dev_extent_cache;
7907 struct cache_tree extent_cache;
7908 struct cache_tree seen;
7909 struct cache_tree pending;
7910 struct cache_tree reada;
7911 struct cache_tree nodes;
7912 struct extent_io_tree excluded_extents;
7913 struct cache_tree corrupt_blocks;
7914 struct btrfs_path path;
7915 struct btrfs_key key;
7916 struct btrfs_key found_key;
7918 struct block_info *bits;
7920 struct extent_buffer *leaf;
7922 struct btrfs_root_item ri;
7923 struct list_head dropping_trees;
7924 struct list_head normal_trees;
7925 struct btrfs_root *root1;
7930 dev_cache = RB_ROOT;
7931 cache_tree_init(&chunk_cache);
7932 block_group_tree_init(&block_group_cache);
7933 device_extent_tree_init(&dev_extent_cache);
7935 cache_tree_init(&extent_cache);
7936 cache_tree_init(&seen);
7937 cache_tree_init(&pending);
7938 cache_tree_init(&nodes);
7939 cache_tree_init(&reada);
7940 cache_tree_init(&corrupt_blocks);
7941 extent_io_tree_init(&excluded_extents);
7942 INIT_LIST_HEAD(&dropping_trees);
7943 INIT_LIST_HEAD(&normal_trees);
7946 root->fs_info->excluded_extents = &excluded_extents;
7947 root->fs_info->fsck_extent_cache = &extent_cache;
7948 root->fs_info->free_extent_hook = free_extent_hook;
7949 root->fs_info->corrupt_blocks = &corrupt_blocks;
7953 bits = malloc(bits_nr * sizeof(struct block_info));
7960 root1 = root->fs_info->tree_root;
7961 level = btrfs_header_level(root1->node);
7962 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7963 root1->node->start, 0, level, 0,
7964 btrfs_level_size(root1, level), NULL);
7967 root1 = root->fs_info->chunk_root;
7968 level = btrfs_header_level(root1->node);
7969 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7970 root1->node->start, 0, level, 0,
7971 btrfs_level_size(root1, level), NULL);
7974 btrfs_init_path(&path);
7977 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7978 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7983 leaf = path.nodes[0];
7984 slot = path.slots[0];
7985 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7986 ret = btrfs_next_leaf(root, &path);
7989 leaf = path.nodes[0];
7990 slot = path.slots[0];
7992 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7993 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7994 unsigned long offset;
7997 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7998 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7999 last_snapshot = btrfs_root_last_snapshot(&ri);
8000 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
8001 level = btrfs_root_level(&ri);
8002 level_size = btrfs_level_size(root, level);
8003 ret = add_root_item_to_list(&normal_trees,
8005 btrfs_root_bytenr(&ri),
8006 last_snapshot, level,
8007 0, level_size, NULL);
8011 level = btrfs_root_level(&ri);
8012 level_size = btrfs_level_size(root, level);
8013 objectid = found_key.objectid;
8014 btrfs_disk_key_to_cpu(&found_key,
8016 ret = add_root_item_to_list(&dropping_trees,
8018 btrfs_root_bytenr(&ri),
8019 last_snapshot, level,
8021 level_size, &found_key);
8028 btrfs_release_path(&path);
8031 * check_block can return -EAGAIN if it fixes something, please keep
8032 * this in mind when dealing with return values from these functions, if
8033 * we get -EAGAIN we want to fall through and restart the loop.
8035 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8036 &seen, &reada, &nodes, &extent_cache,
8037 &chunk_cache, &dev_cache, &block_group_cache,
8044 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8045 &pending, &seen, &reada, &nodes,
8046 &extent_cache, &chunk_cache, &dev_cache,
8047 &block_group_cache, &dev_extent_cache);
8054 err = check_chunks(&chunk_cache, &block_group_cache,
8055 &dev_extent_cache, NULL, NULL, NULL, 0);
8063 ret = check_extent_refs(root, &extent_cache);
8070 err = check_devices(&dev_cache, &dev_extent_cache);
8076 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8077 extent_io_tree_cleanup(&excluded_extents);
8078 root->fs_info->fsck_extent_cache = NULL;
8079 root->fs_info->free_extent_hook = NULL;
8080 root->fs_info->corrupt_blocks = NULL;
8081 root->fs_info->excluded_extents = NULL;
8084 free_chunk_cache_tree(&chunk_cache);
8085 free_device_cache_tree(&dev_cache);
8086 free_block_group_tree(&block_group_cache);
8087 free_device_extent_tree(&dev_extent_cache);
8088 free_extent_cache_tree(&seen);
8089 free_extent_cache_tree(&pending);
8090 free_extent_cache_tree(&reada);
8091 free_extent_cache_tree(&nodes);
8094 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8095 free_extent_cache_tree(&seen);
8096 free_extent_cache_tree(&pending);
8097 free_extent_cache_tree(&reada);
8098 free_extent_cache_tree(&nodes);
8099 free_chunk_cache_tree(&chunk_cache);
8100 free_block_group_tree(&block_group_cache);
8101 free_device_cache_tree(&dev_cache);
8102 free_device_extent_tree(&dev_extent_cache);
8103 free_extent_record_cache(root->fs_info, &extent_cache);
8104 free_root_item_list(&normal_trees);
8105 free_root_item_list(&dropping_trees);
8106 extent_io_tree_cleanup(&excluded_extents);
8110 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8111 struct btrfs_root *root, int overwrite)
8113 struct extent_buffer *c;
8114 struct extent_buffer *old = root->node;
8117 struct btrfs_disk_key disk_key = {0,0,0};
8123 extent_buffer_get(c);
8126 c = btrfs_alloc_free_block(trans, root,
8127 btrfs_level_size(root, 0),
8128 root->root_key.objectid,
8129 &disk_key, level, 0, 0);
8132 extent_buffer_get(c);
8136 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8137 btrfs_set_header_level(c, level);
8138 btrfs_set_header_bytenr(c, c->start);
8139 btrfs_set_header_generation(c, trans->transid);
8140 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8141 btrfs_set_header_owner(c, root->root_key.objectid);
8143 write_extent_buffer(c, root->fs_info->fsid,
8144 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8146 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8147 btrfs_header_chunk_tree_uuid(c),
8150 btrfs_mark_buffer_dirty(c);
8152 * this case can happen in the following case:
8154 * 1.overwrite previous root.
8156 * 2.reinit reloc data root, this is because we skip pin
8157 * down reloc data tree before which means we can allocate
8158 * same block bytenr here.
8160 if (old->start == c->start) {
8161 btrfs_set_root_generation(&root->root_item,
8163 root->root_item.level = btrfs_header_level(root->node);
8164 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8165 &root->root_key, &root->root_item);
8167 free_extent_buffer(c);
8171 free_extent_buffer(old);
8173 add_root_to_dirty_list(root);
8177 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8178 struct extent_buffer *eb, int tree_root)
8180 struct extent_buffer *tmp;
8181 struct btrfs_root_item *ri;
8182 struct btrfs_key key;
8185 int level = btrfs_header_level(eb);
8191 * If we have pinned this block before, don't pin it again.
8192 * This can not only avoid forever loop with broken filesystem
8193 * but also give us some speedups.
8195 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8196 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8199 btrfs_pin_extent(fs_info, eb->start, eb->len);
8201 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8202 nritems = btrfs_header_nritems(eb);
8203 for (i = 0; i < nritems; i++) {
8205 btrfs_item_key_to_cpu(eb, &key, i);
8206 if (key.type != BTRFS_ROOT_ITEM_KEY)
8208 /* Skip the extent root and reloc roots */
8209 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8210 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8211 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8213 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8214 bytenr = btrfs_disk_root_bytenr(eb, ri);
8217 * If at any point we start needing the real root we
8218 * will have to build a stump root for the root we are
8219 * in, but for now this doesn't actually use the root so
8220 * just pass in extent_root.
8222 tmp = read_tree_block(fs_info->extent_root, bytenr,
8224 if (!extent_buffer_uptodate(tmp)) {
8225 fprintf(stderr, "Error reading root block\n");
8228 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8229 free_extent_buffer(tmp);
8233 bytenr = btrfs_node_blockptr(eb, i);
8235 /* If we aren't the tree root don't read the block */
8236 if (level == 1 && !tree_root) {
8237 btrfs_pin_extent(fs_info, bytenr, leafsize);
8241 tmp = read_tree_block(fs_info->extent_root, bytenr,
8243 if (!extent_buffer_uptodate(tmp)) {
8244 fprintf(stderr, "Error reading tree block\n");
8247 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8248 free_extent_buffer(tmp);
8257 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8261 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8265 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8268 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8270 struct btrfs_block_group_cache *cache;
8271 struct btrfs_path *path;
8272 struct extent_buffer *leaf;
8273 struct btrfs_chunk *chunk;
8274 struct btrfs_key key;
8278 path = btrfs_alloc_path();
8283 key.type = BTRFS_CHUNK_ITEM_KEY;
8286 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8288 btrfs_free_path(path);
8293 * We do this in case the block groups were screwed up and had alloc
8294 * bits that aren't actually set on the chunks. This happens with
8295 * restored images every time and could happen in real life I guess.
8297 fs_info->avail_data_alloc_bits = 0;
8298 fs_info->avail_metadata_alloc_bits = 0;
8299 fs_info->avail_system_alloc_bits = 0;
8301 /* First we need to create the in-memory block groups */
8303 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8304 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8306 btrfs_free_path(path);
8314 leaf = path->nodes[0];
8315 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8316 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8321 chunk = btrfs_item_ptr(leaf, path->slots[0],
8322 struct btrfs_chunk);
8323 btrfs_add_block_group(fs_info, 0,
8324 btrfs_chunk_type(leaf, chunk),
8325 key.objectid, key.offset,
8326 btrfs_chunk_length(leaf, chunk));
8327 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8328 key.offset + btrfs_chunk_length(leaf, chunk),
8334 cache = btrfs_lookup_first_block_group(fs_info, start);
8338 start = cache->key.objectid + cache->key.offset;
8341 btrfs_free_path(path);
8345 static int reset_balance(struct btrfs_trans_handle *trans,
8346 struct btrfs_fs_info *fs_info)
8348 struct btrfs_root *root = fs_info->tree_root;
8349 struct btrfs_path *path;
8350 struct extent_buffer *leaf;
8351 struct btrfs_key key;
8352 int del_slot, del_nr = 0;
8356 path = btrfs_alloc_path();
8360 key.objectid = BTRFS_BALANCE_OBJECTID;
8361 key.type = BTRFS_BALANCE_ITEM_KEY;
8364 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8369 goto reinit_data_reloc;
8374 ret = btrfs_del_item(trans, root, path);
8377 btrfs_release_path(path);
8379 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8380 key.type = BTRFS_ROOT_ITEM_KEY;
8383 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8387 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8392 ret = btrfs_del_items(trans, root, path,
8399 btrfs_release_path(path);
8402 ret = btrfs_search_slot(trans, root, &key, path,
8409 leaf = path->nodes[0];
8410 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8411 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8413 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8418 del_slot = path->slots[0];
8427 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8431 btrfs_release_path(path);
8434 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8435 key.type = BTRFS_ROOT_ITEM_KEY;
8436 key.offset = (u64)-1;
8437 root = btrfs_read_fs_root(fs_info, &key);
8439 fprintf(stderr, "Error reading data reloc tree\n");
8440 ret = PTR_ERR(root);
8443 record_root_in_trans(trans, root);
8444 ret = btrfs_fsck_reinit_root(trans, root, 0);
8447 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8449 btrfs_free_path(path);
8453 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8454 struct btrfs_fs_info *fs_info)
8460 * The only reason we don't do this is because right now we're just
8461 * walking the trees we find and pinning down their bytes, we don't look
8462 * at any of the leaves. In order to do mixed groups we'd have to check
8463 * the leaves of any fs roots and pin down the bytes for any file
8464 * extents we find. Not hard but why do it if we don't have to?
8466 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8467 fprintf(stderr, "We don't support re-initing the extent tree "
8468 "for mixed block groups yet, please notify a btrfs "
8469 "developer you want to do this so they can add this "
8470 "functionality.\n");
8475 * first we need to walk all of the trees except the extent tree and pin
8476 * down the bytes that are in use so we don't overwrite any existing
8479 ret = pin_metadata_blocks(fs_info);
8481 fprintf(stderr, "error pinning down used bytes\n");
8486 * Need to drop all the block groups since we're going to recreate all
8489 btrfs_free_block_groups(fs_info);
8490 ret = reset_block_groups(fs_info);
8492 fprintf(stderr, "error resetting the block groups\n");
8496 /* Ok we can allocate now, reinit the extent root */
8497 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8499 fprintf(stderr, "extent root initialization failed\n");
8501 * When the transaction code is updated we should end the
8502 * transaction, but for now progs only knows about commit so
8503 * just return an error.
8509 * Now we have all the in-memory block groups setup so we can make
8510 * allocations properly, and the metadata we care about is safe since we
8511 * pinned all of it above.
8514 struct btrfs_block_group_cache *cache;
8516 cache = btrfs_lookup_first_block_group(fs_info, start);
8519 start = cache->key.objectid + cache->key.offset;
8520 ret = btrfs_insert_item(trans, fs_info->extent_root,
8521 &cache->key, &cache->item,
8522 sizeof(cache->item));
8524 fprintf(stderr, "Error adding block group\n");
8527 btrfs_extent_post_op(trans, fs_info->extent_root);
8530 ret = reset_balance(trans, fs_info);
8532 fprintf(stderr, "error reseting the pending balance\n");
8537 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8539 struct btrfs_path *path;
8540 struct btrfs_trans_handle *trans;
8541 struct btrfs_key key;
8544 printf("Recowing metadata block %llu\n", eb->start);
8545 key.objectid = btrfs_header_owner(eb);
8546 key.type = BTRFS_ROOT_ITEM_KEY;
8547 key.offset = (u64)-1;
8549 root = btrfs_read_fs_root(root->fs_info, &key);
8551 fprintf(stderr, "Couldn't find owner root %llu\n",
8553 return PTR_ERR(root);
8556 path = btrfs_alloc_path();
8560 trans = btrfs_start_transaction(root, 1);
8561 if (IS_ERR(trans)) {
8562 btrfs_free_path(path);
8563 return PTR_ERR(trans);
8566 path->lowest_level = btrfs_header_level(eb);
8567 if (path->lowest_level)
8568 btrfs_node_key_to_cpu(eb, &key, 0);
8570 btrfs_item_key_to_cpu(eb, &key, 0);
8572 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8573 btrfs_commit_transaction(trans, root);
8574 btrfs_free_path(path);
8578 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8580 struct btrfs_path *path;
8581 struct btrfs_trans_handle *trans;
8582 struct btrfs_key key;
8585 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8586 bad->key.type, bad->key.offset);
8587 key.objectid = bad->root_id;
8588 key.type = BTRFS_ROOT_ITEM_KEY;
8589 key.offset = (u64)-1;
8591 root = btrfs_read_fs_root(root->fs_info, &key);
8593 fprintf(stderr, "Couldn't find owner root %llu\n",
8595 return PTR_ERR(root);
8598 path = btrfs_alloc_path();
8602 trans = btrfs_start_transaction(root, 1);
8603 if (IS_ERR(trans)) {
8604 btrfs_free_path(path);
8605 return PTR_ERR(trans);
8608 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8614 ret = btrfs_del_item(trans, root, path);
8616 btrfs_commit_transaction(trans, root);
8617 btrfs_free_path(path);
8621 static int zero_log_tree(struct btrfs_root *root)
8623 struct btrfs_trans_handle *trans;
8626 trans = btrfs_start_transaction(root, 1);
8627 if (IS_ERR(trans)) {
8628 ret = PTR_ERR(trans);
8631 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8632 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8633 ret = btrfs_commit_transaction(trans, root);
8637 static int populate_csum(struct btrfs_trans_handle *trans,
8638 struct btrfs_root *csum_root, char *buf, u64 start,
8645 while (offset < len) {
8646 sectorsize = csum_root->sectorsize;
8647 ret = read_extent_data(csum_root, buf, start + offset,
8651 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8652 start + offset, buf, sectorsize);
8655 offset += sectorsize;
8660 static int fill_csum_tree_from_one_fs_root(struct btrfs_trans_handle *trans,
8661 struct btrfs_root *csum_root,
8662 struct btrfs_root *cur_root)
8664 struct btrfs_path *path;
8665 struct btrfs_key key;
8666 struct extent_buffer *node;
8667 struct btrfs_file_extent_item *fi;
8674 path = btrfs_alloc_path();
8677 buf = malloc(cur_root->fs_info->csum_root->sectorsize);
8687 ret = btrfs_search_slot(NULL, cur_root, &key, path, 0, 0);
8690 /* Iterate all regular file extents and fill its csum */
8692 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
8694 if (key.type != BTRFS_EXTENT_DATA_KEY)
8696 node = path->nodes[0];
8697 slot = path->slots[0];
8698 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
8699 if (btrfs_file_extent_type(node, fi) != BTRFS_FILE_EXTENT_REG)
8701 start = btrfs_file_extent_disk_bytenr(node, fi);
8702 len = btrfs_file_extent_disk_num_bytes(node, fi);
8704 ret = populate_csum(trans, csum_root, buf, start, len);
8711 * TODO: if next leaf is corrupted, jump to nearest next valid
8714 ret = btrfs_next_item(cur_root, path);
8724 btrfs_free_path(path);
8729 static int fill_csum_tree_from_fs(struct btrfs_trans_handle *trans,
8730 struct btrfs_root *csum_root)
8732 struct btrfs_fs_info *fs_info = csum_root->fs_info;
8733 struct btrfs_path *path;
8734 struct btrfs_root *tree_root = fs_info->tree_root;
8735 struct btrfs_root *cur_root;
8736 struct extent_buffer *node;
8737 struct btrfs_key key;
8741 path = btrfs_alloc_path();
8745 key.objectid = BTRFS_FS_TREE_OBJECTID;
8747 key.type = BTRFS_ROOT_ITEM_KEY;
8749 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
8758 node = path->nodes[0];
8759 slot = path->slots[0];
8760 btrfs_item_key_to_cpu(node, &key, slot);
8761 if (key.objectid > BTRFS_LAST_FREE_OBJECTID)
8763 if (key.type != BTRFS_ROOT_ITEM_KEY)
8765 if (!is_fstree(key.objectid))
8767 key.offset = (u64)-1;
8769 cur_root = btrfs_read_fs_root(fs_info, &key);
8770 if (IS_ERR(cur_root) || !cur_root) {
8771 fprintf(stderr, "Fail to read fs/subvol tree: %lld\n",
8775 ret = fill_csum_tree_from_one_fs_root(trans, csum_root,
8780 ret = btrfs_next_item(tree_root, path);
8790 btrfs_free_path(path);
8794 static int fill_csum_tree_from_extent(struct btrfs_trans_handle *trans,
8795 struct btrfs_root *csum_root)
8797 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8798 struct btrfs_path *path;
8799 struct btrfs_extent_item *ei;
8800 struct extent_buffer *leaf;
8802 struct btrfs_key key;
8805 path = btrfs_alloc_path();
8810 key.type = BTRFS_EXTENT_ITEM_KEY;
8813 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8815 btrfs_free_path(path);
8819 buf = malloc(csum_root->sectorsize);
8821 btrfs_free_path(path);
8826 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8827 ret = btrfs_next_leaf(extent_root, path);
8835 leaf = path->nodes[0];
8837 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8838 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8843 ei = btrfs_item_ptr(leaf, path->slots[0],
8844 struct btrfs_extent_item);
8845 if (!(btrfs_extent_flags(leaf, ei) &
8846 BTRFS_EXTENT_FLAG_DATA)) {
8851 ret = populate_csum(trans, csum_root, buf, key.objectid,
8858 btrfs_free_path(path);
8864 * Recalculate the csum and put it into the csum tree.
8866 * Extent tree init will wipe out all the extent info, so in that case, we
8867 * can't depend on extent tree, but use fs tree. If search_fs_tree is set, we
8868 * will use fs/subvol trees to init the csum tree.
8870 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8871 struct btrfs_root *csum_root,
8875 return fill_csum_tree_from_fs(trans, csum_root);
8877 return fill_csum_tree_from_extent(trans, csum_root);
8880 struct root_item_info {
8881 /* level of the root */
8883 /* number of nodes at this level, must be 1 for a root */
8887 struct cache_extent cache_extent;
8890 static struct cache_tree *roots_info_cache = NULL;
8892 static void free_roots_info_cache(void)
8894 if (!roots_info_cache)
8897 while (!cache_tree_empty(roots_info_cache)) {
8898 struct cache_extent *entry;
8899 struct root_item_info *rii;
8901 entry = first_cache_extent(roots_info_cache);
8904 remove_cache_extent(roots_info_cache, entry);
8905 rii = container_of(entry, struct root_item_info, cache_extent);
8909 free(roots_info_cache);
8910 roots_info_cache = NULL;
8913 static int build_roots_info_cache(struct btrfs_fs_info *info)
8916 struct btrfs_key key;
8917 struct extent_buffer *leaf;
8918 struct btrfs_path *path;
8920 if (!roots_info_cache) {
8921 roots_info_cache = malloc(sizeof(*roots_info_cache));
8922 if (!roots_info_cache)
8924 cache_tree_init(roots_info_cache);
8927 path = btrfs_alloc_path();
8932 key.type = BTRFS_EXTENT_ITEM_KEY;
8935 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8938 leaf = path->nodes[0];
8941 struct btrfs_key found_key;
8942 struct btrfs_extent_item *ei;
8943 struct btrfs_extent_inline_ref *iref;
8944 int slot = path->slots[0];
8949 struct cache_extent *entry;
8950 struct root_item_info *rii;
8952 if (slot >= btrfs_header_nritems(leaf)) {
8953 ret = btrfs_next_leaf(info->extent_root, path);
8960 leaf = path->nodes[0];
8961 slot = path->slots[0];
8964 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8966 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8967 found_key.type != BTRFS_METADATA_ITEM_KEY)
8970 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8971 flags = btrfs_extent_flags(leaf, ei);
8973 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8974 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8977 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8978 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8979 level = found_key.offset;
8981 struct btrfs_tree_block_info *info;
8983 info = (struct btrfs_tree_block_info *)(ei + 1);
8984 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8985 level = btrfs_tree_block_level(leaf, info);
8989 * For a root extent, it must be of the following type and the
8990 * first (and only one) iref in the item.
8992 type = btrfs_extent_inline_ref_type(leaf, iref);
8993 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8996 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8997 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8999 rii = malloc(sizeof(struct root_item_info));
9004 rii->cache_extent.start = root_id;
9005 rii->cache_extent.size = 1;
9006 rii->level = (u8)-1;
9007 entry = &rii->cache_extent;
9008 ret = insert_cache_extent(roots_info_cache, entry);
9011 rii = container_of(entry, struct root_item_info,
9015 ASSERT(rii->cache_extent.start == root_id);
9016 ASSERT(rii->cache_extent.size == 1);
9018 if (level > rii->level || rii->level == (u8)-1) {
9020 rii->bytenr = found_key.objectid;
9021 rii->gen = btrfs_extent_generation(leaf, ei);
9022 rii->node_count = 1;
9023 } else if (level == rii->level) {
9031 btrfs_free_path(path);
9036 static int maybe_repair_root_item(struct btrfs_fs_info *info,
9037 struct btrfs_path *path,
9038 const struct btrfs_key *root_key,
9039 const int read_only_mode)
9041 const u64 root_id = root_key->objectid;
9042 struct cache_extent *entry;
9043 struct root_item_info *rii;
9044 struct btrfs_root_item ri;
9045 unsigned long offset;
9047 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9050 "Error: could not find extent items for root %llu\n",
9051 root_key->objectid);
9055 rii = container_of(entry, struct root_item_info, cache_extent);
9056 ASSERT(rii->cache_extent.start == root_id);
9057 ASSERT(rii->cache_extent.size == 1);
9059 if (rii->node_count != 1) {
9061 "Error: could not find btree root extent for root %llu\n",
9066 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
9067 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
9069 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
9070 btrfs_root_level(&ri) != rii->level ||
9071 btrfs_root_generation(&ri) != rii->gen) {
9074 * If we're in repair mode but our caller told us to not update
9075 * the root item, i.e. just check if it needs to be updated, don't
9076 * print this message, since the caller will call us again shortly
9077 * for the same root item without read only mode (the caller will
9078 * open a transaction first).
9080 if (!(read_only_mode && repair))
9082 "%sroot item for root %llu,"
9083 " current bytenr %llu, current gen %llu, current level %u,"
9084 " new bytenr %llu, new gen %llu, new level %u\n",
9085 (read_only_mode ? "" : "fixing "),
9087 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
9088 btrfs_root_level(&ri),
9089 rii->bytenr, rii->gen, rii->level);
9091 if (btrfs_root_generation(&ri) > rii->gen) {
9093 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
9094 root_id, btrfs_root_generation(&ri), rii->gen);
9098 if (!read_only_mode) {
9099 btrfs_set_root_bytenr(&ri, rii->bytenr);
9100 btrfs_set_root_level(&ri, rii->level);
9101 btrfs_set_root_generation(&ri, rii->gen);
9102 write_extent_buffer(path->nodes[0], &ri,
9103 offset, sizeof(ri));
9113 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
9114 * caused read-only snapshots to be corrupted if they were created at a moment
9115 * when the source subvolume/snapshot had orphan items. The issue was that the
9116 * on-disk root items became incorrect, referring to the pre orphan cleanup root
9117 * node instead of the post orphan cleanup root node.
9118 * So this function, and its callees, just detects and fixes those cases. Even
9119 * though the regression was for read-only snapshots, this function applies to
9120 * any snapshot/subvolume root.
9121 * This must be run before any other repair code - not doing it so, makes other
9122 * repair code delete or modify backrefs in the extent tree for example, which
9123 * will result in an inconsistent fs after repairing the root items.
9125 static int repair_root_items(struct btrfs_fs_info *info)
9127 struct btrfs_path *path = NULL;
9128 struct btrfs_key key;
9129 struct extent_buffer *leaf;
9130 struct btrfs_trans_handle *trans = NULL;
9135 ret = build_roots_info_cache(info);
9139 path = btrfs_alloc_path();
9145 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
9146 key.type = BTRFS_ROOT_ITEM_KEY;
9151 * Avoid opening and committing transactions if a leaf doesn't have
9152 * any root items that need to be fixed, so that we avoid rotating
9153 * backup roots unnecessarily.
9156 trans = btrfs_start_transaction(info->tree_root, 1);
9157 if (IS_ERR(trans)) {
9158 ret = PTR_ERR(trans);
9163 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
9167 leaf = path->nodes[0];
9170 struct btrfs_key found_key;
9172 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
9173 int no_more_keys = find_next_key(path, &key);
9175 btrfs_release_path(path);
9177 ret = btrfs_commit_transaction(trans,
9189 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9191 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
9193 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9196 ret = maybe_repair_root_item(info, path, &found_key,
9201 if (!trans && repair) {
9204 btrfs_release_path(path);
9214 free_roots_info_cache();
9216 btrfs_free_path(path);
9218 btrfs_commit_transaction(trans, info->tree_root);
9225 const char * const cmd_check_usage[] = {
9226 "btrfs check [options] <device>",
9227 "Check an unmounted btrfs filesystem.",
9229 "-s|--super <superblock> use this superblock copy",
9230 "-b|--backup use the backup root copy",
9231 "--repair try to repair the filesystem",
9232 "--init-csum-tree create a new CRC tree",
9233 "--init-extent-tree create a new extent tree",
9234 "--check-data-csum verify checkums of data blocks",
9235 "--qgroup-report print a report on qgroup consistency",
9236 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9237 "--tree-root <bytenr> use the given bytenr for the tree root",
9241 int cmd_check(int argc, char **argv)
9243 struct cache_tree root_cache;
9244 struct btrfs_root *root;
9245 struct btrfs_fs_info *info;
9248 u64 tree_root_bytenr = 0;
9249 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9252 int init_csum_tree = 0;
9254 int qgroup_report = 0;
9255 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9259 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9260 OPT_CHECK_CSUM, OPT_READONLY };
9261 static const struct option long_options[] = {
9262 { "super", required_argument, NULL, 's' },
9263 { "repair", no_argument, NULL, OPT_REPAIR },
9264 { "readonly", no_argument, NULL, OPT_READONLY },
9265 { "init-csum-tree", no_argument, NULL, OPT_INIT_CSUM },
9266 { "init-extent-tree", no_argument, NULL, OPT_INIT_EXTENT },
9267 { "check-data-csum", no_argument, NULL, OPT_CHECK_CSUM },
9268 { "backup", no_argument, NULL, 'b' },
9269 { "subvol-extents", required_argument, NULL, 'E' },
9270 { "qgroup-report", no_argument, NULL, 'Q' },
9271 { "tree-root", required_argument, NULL, 'r' },
9275 c = getopt_long(argc, argv, "as:br:", long_options, NULL);
9279 case 'a': /* ignored */ break;
9281 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9284 num = arg_strtou64(optarg);
9285 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9287 "ERROR: super mirror should be less than: %d\n",
9288 BTRFS_SUPER_MIRROR_MAX);
9291 bytenr = btrfs_sb_offset(((int)num));
9292 printf("using SB copy %llu, bytenr %llu\n", num,
9293 (unsigned long long)bytenr);
9299 subvolid = arg_strtou64(optarg);
9302 tree_root_bytenr = arg_strtou64(optarg);
9306 usage(cmd_check_usage);
9308 printf("enabling repair mode\n");
9310 ctree_flags |= OPEN_CTREE_WRITES;
9316 printf("Creating a new CRC tree\n");
9319 ctree_flags |= OPEN_CTREE_WRITES;
9321 case OPT_INIT_EXTENT:
9322 init_extent_tree = 1;
9323 ctree_flags |= (OPEN_CTREE_WRITES |
9324 OPEN_CTREE_NO_BLOCK_GROUPS);
9327 case OPT_CHECK_CSUM:
9328 check_data_csum = 1;
9332 argc = argc - optind;
9334 if (check_argc_exact(argc, 1))
9335 usage(cmd_check_usage);
9337 /* This check is the only reason for --readonly to exist */
9338 if (readonly && repair) {
9339 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9344 cache_tree_init(&root_cache);
9346 if((ret = check_mounted(argv[optind])) < 0) {
9347 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9350 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9355 /* only allow partial opening under repair mode */
9357 ctree_flags |= OPEN_CTREE_PARTIAL;
9359 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9362 fprintf(stderr, "Couldn't open file system\n");
9367 root = info->fs_root;
9370 * repair mode will force us to commit transaction which
9371 * will make us fail to load log tree when mounting.
9373 if (repair && btrfs_super_log_root(info->super_copy)) {
9374 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9379 ret = zero_log_tree(root);
9381 fprintf(stderr, "fail to zero log tree\n");
9386 uuid_unparse(info->super_copy->fsid, uuidbuf);
9387 if (qgroup_report) {
9388 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9390 ret = qgroup_verify_all(info);
9392 print_qgroup_report(1);
9396 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9397 subvolid, argv[optind], uuidbuf);
9398 ret = print_extent_state(info, subvolid);
9401 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9403 if (!extent_buffer_uptodate(info->tree_root->node) ||
9404 !extent_buffer_uptodate(info->dev_root->node) ||
9405 !extent_buffer_uptodate(info->chunk_root->node)) {
9406 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9411 if (init_extent_tree || init_csum_tree) {
9412 struct btrfs_trans_handle *trans;
9414 trans = btrfs_start_transaction(info->extent_root, 0);
9415 if (IS_ERR(trans)) {
9416 fprintf(stderr, "Error starting transaction\n");
9417 ret = PTR_ERR(trans);
9421 if (init_extent_tree) {
9422 printf("Creating a new extent tree\n");
9423 ret = reinit_extent_tree(trans, info);
9428 if (init_csum_tree) {
9429 fprintf(stderr, "Reinit crc root\n");
9430 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9432 fprintf(stderr, "crc root initialization failed\n");
9437 ret = fill_csum_tree(trans, info->csum_root,
9440 fprintf(stderr, "crc refilling failed\n");
9445 * Ok now we commit and run the normal fsck, which will add
9446 * extent entries for all of the items it finds.
9448 ret = btrfs_commit_transaction(trans, info->extent_root);
9452 if (!extent_buffer_uptodate(info->extent_root->node)) {
9453 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9457 if (!extent_buffer_uptodate(info->csum_root->node)) {
9458 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9463 fprintf(stderr, "checking extents\n");
9464 ret = check_chunks_and_extents(root);
9466 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9468 ret = repair_root_items(info);
9472 fprintf(stderr, "Fixed %d roots.\n", ret);
9474 } else if (ret > 0) {
9476 "Found %d roots with an outdated root item.\n",
9479 "Please run a filesystem check with the option --repair to fix them.\n");
9484 fprintf(stderr, "checking free space cache\n");
9485 ret = check_space_cache(root);
9490 * We used to have to have these hole extents in between our real
9491 * extents so if we don't have this flag set we need to make sure there
9492 * are no gaps in the file extents for inodes, otherwise we can just
9493 * ignore it when this happens.
9495 no_holes = btrfs_fs_incompat(root->fs_info,
9496 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9497 fprintf(stderr, "checking fs roots\n");
9498 ret = check_fs_roots(root, &root_cache);
9502 fprintf(stderr, "checking csums\n");
9503 ret = check_csums(root);
9507 fprintf(stderr, "checking root refs\n");
9508 ret = check_root_refs(root, &root_cache);
9512 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9513 struct extent_buffer *eb;
9515 eb = list_first_entry(&root->fs_info->recow_ebs,
9516 struct extent_buffer, recow);
9517 list_del_init(&eb->recow);
9518 ret = recow_extent_buffer(root, eb);
9523 while (!list_empty(&delete_items)) {
9524 struct bad_item *bad;
9526 bad = list_first_entry(&delete_items, struct bad_item, list);
9527 list_del_init(&bad->list);
9529 ret = delete_bad_item(root, bad);
9533 if (info->quota_enabled) {
9535 fprintf(stderr, "checking quota groups\n");
9536 err = qgroup_verify_all(info);
9541 if (!list_empty(&root->fs_info->recow_ebs)) {
9542 fprintf(stderr, "Transid errors in file system\n");
9546 print_qgroup_report(0);
9547 if (found_old_backref) { /*
9548 * there was a disk format change when mixed
9549 * backref was in testing tree. The old format
9550 * existed about one week.
9552 printf("\n * Found old mixed backref format. "
9553 "The old format is not supported! *"
9554 "\n * Please mount the FS in readonly mode, "
9555 "backup data and re-format the FS. *\n\n");
9558 printf("found %llu bytes used err is %d\n",
9559 (unsigned long long)bytes_used, ret);
9560 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9561 printf("total tree bytes: %llu\n",
9562 (unsigned long long)total_btree_bytes);
9563 printf("total fs tree bytes: %llu\n",
9564 (unsigned long long)total_fs_tree_bytes);
9565 printf("total extent tree bytes: %llu\n",
9566 (unsigned long long)total_extent_tree_bytes);
9567 printf("btree space waste bytes: %llu\n",
9568 (unsigned long long)btree_space_waste);
9569 printf("file data blocks allocated: %llu\n referenced %llu\n",
9570 (unsigned long long)data_bytes_allocated,
9571 (unsigned long long)data_bytes_referenced);
9572 printf("%s\n", PACKAGE_STRING);
9574 free_root_recs_tree(&root_cache);