2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
23 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include "print-tree.h"
33 #include "transaction.h"
36 #include "free-space-cache.h"
38 #include "qgroup-verify.h"
39 #include "rbtree-utils.h"
43 static u64 bytes_used = 0;
44 static u64 total_csum_bytes = 0;
45 static u64 total_btree_bytes = 0;
46 static u64 total_fs_tree_bytes = 0;
47 static u64 total_extent_tree_bytes = 0;
48 static u64 btree_space_waste = 0;
49 static u64 data_bytes_allocated = 0;
50 static u64 data_bytes_referenced = 0;
51 static int found_old_backref = 0;
52 static LIST_HEAD(duplicate_extents);
53 static LIST_HEAD(delete_items);
54 static int repair = 0;
55 static int no_holes = 0;
56 static int init_extent_tree = 0;
57 static int check_data_csum = 0;
59 struct extent_backref {
60 struct list_head list;
61 unsigned int is_data:1;
62 unsigned int found_extent_tree:1;
63 unsigned int full_backref:1;
64 unsigned int found_ref:1;
65 unsigned int broken:1;
69 struct extent_backref node;
84 * Much like data_backref, just removed the undetermined members
85 * and change it to use list_head.
86 * During extent scan, it is stored in root->orphan_data_extent.
87 * During fs tree scan, it is then moved to inode_rec->orphan_data_extents.
89 struct orphan_data_extent {
90 struct list_head list;
99 struct extent_backref node;
106 struct extent_record {
107 struct list_head backrefs;
108 struct list_head dups;
109 struct list_head list;
110 struct cache_extent cache;
111 struct btrfs_disk_key parent_key;
116 u64 extent_item_refs;
118 u64 parent_generation;
122 int flag_block_full_backref;
123 unsigned int found_rec:1;
124 unsigned int content_checked:1;
125 unsigned int owner_ref_checked:1;
126 unsigned int is_root:1;
127 unsigned int metadata:1;
128 unsigned int bad_full_backref:1;
131 struct inode_backref {
132 struct list_head list;
133 unsigned int found_dir_item:1;
134 unsigned int found_dir_index:1;
135 unsigned int found_inode_ref:1;
136 unsigned int filetype:8;
138 unsigned int ref_type;
145 struct root_item_record {
146 struct list_head list;
153 struct btrfs_key drop_key;
156 #define REF_ERR_NO_DIR_ITEM (1 << 0)
157 #define REF_ERR_NO_DIR_INDEX (1 << 1)
158 #define REF_ERR_NO_INODE_REF (1 << 2)
159 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
160 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
161 #define REF_ERR_DUP_INODE_REF (1 << 5)
162 #define REF_ERR_INDEX_UNMATCH (1 << 6)
163 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
164 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
165 #define REF_ERR_NO_ROOT_REF (1 << 9)
166 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
167 #define REF_ERR_DUP_ROOT_REF (1 << 11)
168 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
170 struct file_extent_hole {
176 /* Compatible function to allow reuse of old codes */
177 static u64 first_extent_gap(struct rb_root *holes)
179 struct file_extent_hole *hole;
181 if (RB_EMPTY_ROOT(holes))
184 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
188 int compare_hole(struct rb_node *node1, struct rb_node *node2)
190 struct file_extent_hole *hole1;
191 struct file_extent_hole *hole2;
193 hole1 = rb_entry(node1, struct file_extent_hole, node);
194 hole2 = rb_entry(node2, struct file_extent_hole, node);
196 if (hole1->start > hole2->start)
198 if (hole1->start < hole2->start)
200 /* Now hole1->start == hole2->start */
201 if (hole1->len >= hole2->len)
203 * Hole 1 will be merge center
204 * Same hole will be merged later
207 /* Hole 2 will be merge center */
212 * Add a hole to the record
214 * This will do hole merge for copy_file_extent_holes(),
215 * which will ensure there won't be continuous holes.
217 static int add_file_extent_hole(struct rb_root *holes,
220 struct file_extent_hole *hole;
221 struct file_extent_hole *prev = NULL;
222 struct file_extent_hole *next = NULL;
224 hole = malloc(sizeof(*hole));
229 /* Since compare will not return 0, no -EEXIST will happen */
230 rb_insert(holes, &hole->node, compare_hole);
232 /* simple merge with previous hole */
233 if (rb_prev(&hole->node))
234 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
236 if (prev && prev->start + prev->len >= hole->start) {
237 hole->len = hole->start + hole->len - prev->start;
238 hole->start = prev->start;
239 rb_erase(&prev->node, holes);
244 /* iterate merge with next holes */
246 if (!rb_next(&hole->node))
248 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
250 if (hole->start + hole->len >= next->start) {
251 if (hole->start + hole->len <= next->start + next->len)
252 hole->len = next->start + next->len -
254 rb_erase(&next->node, holes);
263 static int compare_hole_range(struct rb_node *node, void *data)
265 struct file_extent_hole *hole;
268 hole = (struct file_extent_hole *)data;
271 hole = rb_entry(node, struct file_extent_hole, node);
272 if (start < hole->start)
274 if (start >= hole->start && start < hole->start + hole->len)
280 * Delete a hole in the record
282 * This will do the hole split and is much restrict than add.
284 static int del_file_extent_hole(struct rb_root *holes,
287 struct file_extent_hole *hole;
288 struct file_extent_hole tmp;
289 struct file_extent_hole prev;
290 struct file_extent_hole next;
291 struct rb_node *node;
298 node = rb_search(holes, &tmp, compare_hole_range, NULL);
301 hole = rb_entry(node, struct file_extent_hole, node);
302 if (start + len > hole->start + hole->len)
306 * Now there will be no overflap, delete the hole and re-add the
307 * split(s) if they exists.
309 if (start > hole->start) {
310 prev.start = hole->start;
311 prev.len = start - hole->start;
314 if (hole->start + hole->len > start + len) {
315 next.start = start + len;
316 next.len = hole->start + hole->len - start - len;
319 rb_erase(node, holes);
322 ret = add_file_extent_hole(holes, prev.start, prev.len);
327 ret = add_file_extent_hole(holes, next.start, next.len);
334 static int copy_file_extent_holes(struct rb_root *dst,
337 struct file_extent_hole *hole;
338 struct rb_node *node;
341 node = rb_first(src);
343 hole = rb_entry(node, struct file_extent_hole, node);
344 ret = add_file_extent_hole(dst, hole->start, hole->len);
347 node = rb_next(node);
352 static void free_file_extent_holes(struct rb_root *holes)
354 struct rb_node *node;
355 struct file_extent_hole *hole;
357 node = rb_first(holes);
359 hole = rb_entry(node, struct file_extent_hole, node);
360 rb_erase(node, holes);
362 node = rb_first(holes);
366 struct inode_record {
367 struct list_head backrefs;
368 unsigned int checked:1;
369 unsigned int merging:1;
370 unsigned int found_inode_item:1;
371 unsigned int found_dir_item:1;
372 unsigned int found_file_extent:1;
373 unsigned int found_csum_item:1;
374 unsigned int some_csum_missing:1;
375 unsigned int nodatasum:1;
388 struct rb_root holes;
389 struct list_head orphan_extents;
394 #define I_ERR_NO_INODE_ITEM (1 << 0)
395 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
396 #define I_ERR_DUP_INODE_ITEM (1 << 2)
397 #define I_ERR_DUP_DIR_INDEX (1 << 3)
398 #define I_ERR_ODD_DIR_ITEM (1 << 4)
399 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
400 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
401 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
402 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
403 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
404 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
405 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
406 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
407 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
408 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
410 struct root_backref {
411 struct list_head list;
412 unsigned int found_dir_item:1;
413 unsigned int found_dir_index:1;
414 unsigned int found_back_ref:1;
415 unsigned int found_forward_ref:1;
416 unsigned int reachable:1;
426 struct list_head backrefs;
427 struct cache_extent cache;
428 unsigned int found_root_item:1;
434 struct cache_extent cache;
439 struct cache_extent cache;
440 struct cache_tree root_cache;
441 struct cache_tree inode_cache;
442 struct inode_record *current;
451 struct walk_control {
452 struct cache_tree shared;
453 struct shared_node *nodes[BTRFS_MAX_LEVEL];
459 struct btrfs_key key;
461 struct list_head list;
464 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
466 static void record_root_in_trans(struct btrfs_trans_handle *trans,
467 struct btrfs_root *root)
469 if (root->last_trans != trans->transid) {
470 root->track_dirty = 1;
471 root->last_trans = trans->transid;
472 root->commit_root = root->node;
473 extent_buffer_get(root->node);
477 static u8 imode_to_type(u32 imode)
480 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
481 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
482 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
483 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
484 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
485 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
486 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
487 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
490 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
494 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
496 struct device_record *rec1;
497 struct device_record *rec2;
499 rec1 = rb_entry(node1, struct device_record, node);
500 rec2 = rb_entry(node2, struct device_record, node);
501 if (rec1->devid > rec2->devid)
503 else if (rec1->devid < rec2->devid)
509 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
511 struct inode_record *rec;
512 struct inode_backref *backref;
513 struct inode_backref *orig;
514 struct orphan_data_extent *src_orphan;
515 struct orphan_data_extent *dst_orphan;
518 rec = malloc(sizeof(*rec));
519 memcpy(rec, orig_rec, sizeof(*rec));
521 INIT_LIST_HEAD(&rec->backrefs);
522 INIT_LIST_HEAD(&rec->orphan_extents);
524 list_for_each_entry(orig, &orig_rec->backrefs, list) {
525 size = sizeof(*orig) + orig->namelen + 1;
526 backref = malloc(size);
527 memcpy(backref, orig, size);
528 list_add_tail(&backref->list, &rec->backrefs);
530 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
531 dst_orphan = malloc(sizeof(*dst_orphan));
532 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
534 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
535 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
540 static void print_orphan_data_extents(struct list_head *orphan_extents,
543 struct orphan_data_extent *orphan;
545 if (list_empty(orphan_extents))
547 printf("The following data extent is lost in tree %llu:\n",
549 list_for_each_entry(orphan, orphan_extents, list) {
550 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
551 orphan->objectid, orphan->offset, orphan->disk_bytenr,
556 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
558 u64 root_objectid = root->root_key.objectid;
559 int errors = rec->errors;
563 /* reloc root errors, we print its corresponding fs root objectid*/
564 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
565 root_objectid = root->root_key.offset;
566 fprintf(stderr, "reloc");
568 fprintf(stderr, "root %llu inode %llu errors %x",
569 (unsigned long long) root_objectid,
570 (unsigned long long) rec->ino, rec->errors);
572 if (errors & I_ERR_NO_INODE_ITEM)
573 fprintf(stderr, ", no inode item");
574 if (errors & I_ERR_NO_ORPHAN_ITEM)
575 fprintf(stderr, ", no orphan item");
576 if (errors & I_ERR_DUP_INODE_ITEM)
577 fprintf(stderr, ", dup inode item");
578 if (errors & I_ERR_DUP_DIR_INDEX)
579 fprintf(stderr, ", dup dir index");
580 if (errors & I_ERR_ODD_DIR_ITEM)
581 fprintf(stderr, ", odd dir item");
582 if (errors & I_ERR_ODD_FILE_EXTENT)
583 fprintf(stderr, ", odd file extent");
584 if (errors & I_ERR_BAD_FILE_EXTENT)
585 fprintf(stderr, ", bad file extent");
586 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
587 fprintf(stderr, ", file extent overlap");
588 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
589 fprintf(stderr, ", file extent discount");
590 if (errors & I_ERR_DIR_ISIZE_WRONG)
591 fprintf(stderr, ", dir isize wrong");
592 if (errors & I_ERR_FILE_NBYTES_WRONG)
593 fprintf(stderr, ", nbytes wrong");
594 if (errors & I_ERR_ODD_CSUM_ITEM)
595 fprintf(stderr, ", odd csum item");
596 if (errors & I_ERR_SOME_CSUM_MISSING)
597 fprintf(stderr, ", some csum missing");
598 if (errors & I_ERR_LINK_COUNT_WRONG)
599 fprintf(stderr, ", link count wrong");
600 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
601 fprintf(stderr, ", orphan file extent");
602 fprintf(stderr, "\n");
603 /* Print the orphan extents if needed */
604 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
605 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
607 /* Print the holes if needed */
608 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
609 struct file_extent_hole *hole;
610 struct rb_node *node;
612 node = rb_first(&rec->holes);
613 fprintf(stderr, "Found file extent holes:\n");
615 hole = rb_entry(node, struct file_extent_hole, node);
616 fprintf(stderr, "\tstart: %llu, len:%llu\n",
617 hole->start, hole->len);
618 node = rb_next(node);
623 static void print_ref_error(int errors)
625 if (errors & REF_ERR_NO_DIR_ITEM)
626 fprintf(stderr, ", no dir item");
627 if (errors & REF_ERR_NO_DIR_INDEX)
628 fprintf(stderr, ", no dir index");
629 if (errors & REF_ERR_NO_INODE_REF)
630 fprintf(stderr, ", no inode ref");
631 if (errors & REF_ERR_DUP_DIR_ITEM)
632 fprintf(stderr, ", dup dir item");
633 if (errors & REF_ERR_DUP_DIR_INDEX)
634 fprintf(stderr, ", dup dir index");
635 if (errors & REF_ERR_DUP_INODE_REF)
636 fprintf(stderr, ", dup inode ref");
637 if (errors & REF_ERR_INDEX_UNMATCH)
638 fprintf(stderr, ", index unmatch");
639 if (errors & REF_ERR_FILETYPE_UNMATCH)
640 fprintf(stderr, ", filetype unmatch");
641 if (errors & REF_ERR_NAME_TOO_LONG)
642 fprintf(stderr, ", name too long");
643 if (errors & REF_ERR_NO_ROOT_REF)
644 fprintf(stderr, ", no root ref");
645 if (errors & REF_ERR_NO_ROOT_BACKREF)
646 fprintf(stderr, ", no root backref");
647 if (errors & REF_ERR_DUP_ROOT_REF)
648 fprintf(stderr, ", dup root ref");
649 if (errors & REF_ERR_DUP_ROOT_BACKREF)
650 fprintf(stderr, ", dup root backref");
651 fprintf(stderr, "\n");
654 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
657 struct ptr_node *node;
658 struct cache_extent *cache;
659 struct inode_record *rec = NULL;
662 cache = lookup_cache_extent(inode_cache, ino, 1);
664 node = container_of(cache, struct ptr_node, cache);
666 if (mod && rec->refs > 1) {
667 node->data = clone_inode_rec(rec);
672 rec = calloc(1, sizeof(*rec));
674 rec->extent_start = (u64)-1;
676 INIT_LIST_HEAD(&rec->backrefs);
677 INIT_LIST_HEAD(&rec->orphan_extents);
678 rec->holes = RB_ROOT;
680 node = malloc(sizeof(*node));
681 node->cache.start = ino;
682 node->cache.size = 1;
685 if (ino == BTRFS_FREE_INO_OBJECTID)
688 ret = insert_cache_extent(inode_cache, &node->cache);
694 static void free_orphan_data_extents(struct list_head *orphan_extents)
696 struct orphan_data_extent *orphan;
698 while (!list_empty(orphan_extents)) {
699 orphan = list_entry(orphan_extents->next,
700 struct orphan_data_extent, list);
701 list_del(&orphan->list);
706 static void free_inode_rec(struct inode_record *rec)
708 struct inode_backref *backref;
713 while (!list_empty(&rec->backrefs)) {
714 backref = list_entry(rec->backrefs.next,
715 struct inode_backref, list);
716 list_del(&backref->list);
719 free_orphan_data_extents(&rec->orphan_extents);
720 free_file_extent_holes(&rec->holes);
724 static int can_free_inode_rec(struct inode_record *rec)
726 if (!rec->errors && rec->checked && rec->found_inode_item &&
727 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
732 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
733 struct inode_record *rec)
735 struct cache_extent *cache;
736 struct inode_backref *tmp, *backref;
737 struct ptr_node *node;
738 unsigned char filetype;
740 if (!rec->found_inode_item)
743 filetype = imode_to_type(rec->imode);
744 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
745 if (backref->found_dir_item && backref->found_dir_index) {
746 if (backref->filetype != filetype)
747 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
748 if (!backref->errors && backref->found_inode_ref) {
749 list_del(&backref->list);
755 if (!rec->checked || rec->merging)
758 if (S_ISDIR(rec->imode)) {
759 if (rec->found_size != rec->isize)
760 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
761 if (rec->found_file_extent)
762 rec->errors |= I_ERR_ODD_FILE_EXTENT;
763 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
764 if (rec->found_dir_item)
765 rec->errors |= I_ERR_ODD_DIR_ITEM;
766 if (rec->found_size != rec->nbytes)
767 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
768 if (rec->nlink > 0 && !no_holes &&
769 (rec->extent_end < rec->isize ||
770 first_extent_gap(&rec->holes) < rec->isize))
771 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
774 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
775 if (rec->found_csum_item && rec->nodatasum)
776 rec->errors |= I_ERR_ODD_CSUM_ITEM;
777 if (rec->some_csum_missing && !rec->nodatasum)
778 rec->errors |= I_ERR_SOME_CSUM_MISSING;
781 BUG_ON(rec->refs != 1);
782 if (can_free_inode_rec(rec)) {
783 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
784 node = container_of(cache, struct ptr_node, cache);
785 BUG_ON(node->data != rec);
786 remove_cache_extent(inode_cache, &node->cache);
792 static int check_orphan_item(struct btrfs_root *root, u64 ino)
794 struct btrfs_path path;
795 struct btrfs_key key;
798 key.objectid = BTRFS_ORPHAN_OBJECTID;
799 key.type = BTRFS_ORPHAN_ITEM_KEY;
802 btrfs_init_path(&path);
803 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
804 btrfs_release_path(&path);
810 static int process_inode_item(struct extent_buffer *eb,
811 int slot, struct btrfs_key *key,
812 struct shared_node *active_node)
814 struct inode_record *rec;
815 struct btrfs_inode_item *item;
817 rec = active_node->current;
818 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
819 if (rec->found_inode_item) {
820 rec->errors |= I_ERR_DUP_INODE_ITEM;
823 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
824 rec->nlink = btrfs_inode_nlink(eb, item);
825 rec->isize = btrfs_inode_size(eb, item);
826 rec->nbytes = btrfs_inode_nbytes(eb, item);
827 rec->imode = btrfs_inode_mode(eb, item);
828 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
830 rec->found_inode_item = 1;
832 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
833 maybe_free_inode_rec(&active_node->inode_cache, rec);
837 static struct inode_backref *get_inode_backref(struct inode_record *rec,
839 int namelen, u64 dir)
841 struct inode_backref *backref;
843 list_for_each_entry(backref, &rec->backrefs, list) {
844 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
846 if (backref->dir != dir || backref->namelen != namelen)
848 if (memcmp(name, backref->name, namelen))
853 backref = malloc(sizeof(*backref) + namelen + 1);
854 memset(backref, 0, sizeof(*backref));
856 backref->namelen = namelen;
857 memcpy(backref->name, name, namelen);
858 backref->name[namelen] = '\0';
859 list_add_tail(&backref->list, &rec->backrefs);
863 static int add_inode_backref(struct cache_tree *inode_cache,
864 u64 ino, u64 dir, u64 index,
865 const char *name, int namelen,
866 int filetype, int itemtype, int errors)
868 struct inode_record *rec;
869 struct inode_backref *backref;
871 rec = get_inode_rec(inode_cache, ino, 1);
872 backref = get_inode_backref(rec, name, namelen, dir);
874 backref->errors |= errors;
875 if (itemtype == BTRFS_DIR_INDEX_KEY) {
876 if (backref->found_dir_index)
877 backref->errors |= REF_ERR_DUP_DIR_INDEX;
878 if (backref->found_inode_ref && backref->index != index)
879 backref->errors |= REF_ERR_INDEX_UNMATCH;
880 if (backref->found_dir_item && backref->filetype != filetype)
881 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
883 backref->index = index;
884 backref->filetype = filetype;
885 backref->found_dir_index = 1;
886 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
888 if (backref->found_dir_item)
889 backref->errors |= REF_ERR_DUP_DIR_ITEM;
890 if (backref->found_dir_index && backref->filetype != filetype)
891 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
893 backref->filetype = filetype;
894 backref->found_dir_item = 1;
895 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
896 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
897 if (backref->found_inode_ref)
898 backref->errors |= REF_ERR_DUP_INODE_REF;
899 if (backref->found_dir_index && backref->index != index)
900 backref->errors |= REF_ERR_INDEX_UNMATCH;
902 backref->index = index;
904 backref->ref_type = itemtype;
905 backref->found_inode_ref = 1;
910 maybe_free_inode_rec(inode_cache, rec);
914 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
915 struct cache_tree *dst_cache)
917 struct inode_backref *backref;
922 list_for_each_entry(backref, &src->backrefs, list) {
923 if (backref->found_dir_index) {
924 add_inode_backref(dst_cache, dst->ino, backref->dir,
925 backref->index, backref->name,
926 backref->namelen, backref->filetype,
927 BTRFS_DIR_INDEX_KEY, backref->errors);
929 if (backref->found_dir_item) {
931 add_inode_backref(dst_cache, dst->ino,
932 backref->dir, 0, backref->name,
933 backref->namelen, backref->filetype,
934 BTRFS_DIR_ITEM_KEY, backref->errors);
936 if (backref->found_inode_ref) {
937 add_inode_backref(dst_cache, dst->ino,
938 backref->dir, backref->index,
939 backref->name, backref->namelen, 0,
940 backref->ref_type, backref->errors);
944 if (src->found_dir_item)
945 dst->found_dir_item = 1;
946 if (src->found_file_extent)
947 dst->found_file_extent = 1;
948 if (src->found_csum_item)
949 dst->found_csum_item = 1;
950 if (src->some_csum_missing)
951 dst->some_csum_missing = 1;
952 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
953 ret = copy_file_extent_holes(&dst->holes, &src->holes);
958 BUG_ON(src->found_link < dir_count);
959 dst->found_link += src->found_link - dir_count;
960 dst->found_size += src->found_size;
961 if (src->extent_start != (u64)-1) {
962 if (dst->extent_start == (u64)-1) {
963 dst->extent_start = src->extent_start;
964 dst->extent_end = src->extent_end;
966 if (dst->extent_end > src->extent_start)
967 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
968 else if (dst->extent_end < src->extent_start) {
969 ret = add_file_extent_hole(&dst->holes,
971 src->extent_start - dst->extent_end);
973 if (dst->extent_end < src->extent_end)
974 dst->extent_end = src->extent_end;
978 dst->errors |= src->errors;
979 if (src->found_inode_item) {
980 if (!dst->found_inode_item) {
981 dst->nlink = src->nlink;
982 dst->isize = src->isize;
983 dst->nbytes = src->nbytes;
984 dst->imode = src->imode;
985 dst->nodatasum = src->nodatasum;
986 dst->found_inode_item = 1;
988 dst->errors |= I_ERR_DUP_INODE_ITEM;
996 static int splice_shared_node(struct shared_node *src_node,
997 struct shared_node *dst_node)
999 struct cache_extent *cache;
1000 struct ptr_node *node, *ins;
1001 struct cache_tree *src, *dst;
1002 struct inode_record *rec, *conflict;
1003 u64 current_ino = 0;
1007 if (--src_node->refs == 0)
1009 if (src_node->current)
1010 current_ino = src_node->current->ino;
1012 src = &src_node->root_cache;
1013 dst = &dst_node->root_cache;
1015 cache = search_cache_extent(src, 0);
1017 node = container_of(cache, struct ptr_node, cache);
1019 cache = next_cache_extent(cache);
1022 remove_cache_extent(src, &node->cache);
1025 ins = malloc(sizeof(*ins));
1026 ins->cache.start = node->cache.start;
1027 ins->cache.size = node->cache.size;
1031 ret = insert_cache_extent(dst, &ins->cache);
1032 if (ret == -EEXIST) {
1033 conflict = get_inode_rec(dst, rec->ino, 1);
1034 merge_inode_recs(rec, conflict, dst);
1036 conflict->checked = 1;
1037 if (dst_node->current == conflict)
1038 dst_node->current = NULL;
1040 maybe_free_inode_rec(dst, conflict);
1041 free_inode_rec(rec);
1048 if (src == &src_node->root_cache) {
1049 src = &src_node->inode_cache;
1050 dst = &dst_node->inode_cache;
1054 if (current_ino > 0 && (!dst_node->current ||
1055 current_ino > dst_node->current->ino)) {
1056 if (dst_node->current) {
1057 dst_node->current->checked = 1;
1058 maybe_free_inode_rec(dst, dst_node->current);
1060 dst_node->current = get_inode_rec(dst, current_ino, 1);
1065 static void free_inode_ptr(struct cache_extent *cache)
1067 struct ptr_node *node;
1068 struct inode_record *rec;
1070 node = container_of(cache, struct ptr_node, cache);
1072 free_inode_rec(rec);
1076 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1078 static struct shared_node *find_shared_node(struct cache_tree *shared,
1081 struct cache_extent *cache;
1082 struct shared_node *node;
1084 cache = lookup_cache_extent(shared, bytenr, 1);
1086 node = container_of(cache, struct shared_node, cache);
1092 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1095 struct shared_node *node;
1097 node = calloc(1, sizeof(*node));
1098 node->cache.start = bytenr;
1099 node->cache.size = 1;
1100 cache_tree_init(&node->root_cache);
1101 cache_tree_init(&node->inode_cache);
1104 ret = insert_cache_extent(shared, &node->cache);
1109 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1110 struct walk_control *wc, int level)
1112 struct shared_node *node;
1113 struct shared_node *dest;
1115 if (level == wc->active_node)
1118 BUG_ON(wc->active_node <= level);
1119 node = find_shared_node(&wc->shared, bytenr);
1121 add_shared_node(&wc->shared, bytenr, refs);
1122 node = find_shared_node(&wc->shared, bytenr);
1123 wc->nodes[level] = node;
1124 wc->active_node = level;
1128 if (wc->root_level == wc->active_node &&
1129 btrfs_root_refs(&root->root_item) == 0) {
1130 if (--node->refs == 0) {
1131 free_inode_recs_tree(&node->root_cache);
1132 free_inode_recs_tree(&node->inode_cache);
1133 remove_cache_extent(&wc->shared, &node->cache);
1139 dest = wc->nodes[wc->active_node];
1140 splice_shared_node(node, dest);
1141 if (node->refs == 0) {
1142 remove_cache_extent(&wc->shared, &node->cache);
1148 static int leave_shared_node(struct btrfs_root *root,
1149 struct walk_control *wc, int level)
1151 struct shared_node *node;
1152 struct shared_node *dest;
1155 if (level == wc->root_level)
1158 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1162 BUG_ON(i >= BTRFS_MAX_LEVEL);
1164 node = wc->nodes[wc->active_node];
1165 wc->nodes[wc->active_node] = NULL;
1166 wc->active_node = i;
1168 dest = wc->nodes[wc->active_node];
1169 if (wc->active_node < wc->root_level ||
1170 btrfs_root_refs(&root->root_item) > 0) {
1171 BUG_ON(node->refs <= 1);
1172 splice_shared_node(node, dest);
1174 BUG_ON(node->refs < 2);
1183 * 1 - if the root with id child_root_id is a child of root parent_root_id
1184 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1185 * has other root(s) as parent(s)
1186 * 2 - if the root child_root_id doesn't have any parent roots
1188 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1191 struct btrfs_path path;
1192 struct btrfs_key key;
1193 struct extent_buffer *leaf;
1197 btrfs_init_path(&path);
1199 key.objectid = parent_root_id;
1200 key.type = BTRFS_ROOT_REF_KEY;
1201 key.offset = child_root_id;
1202 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1206 btrfs_release_path(&path);
1210 key.objectid = child_root_id;
1211 key.type = BTRFS_ROOT_BACKREF_KEY;
1213 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1219 leaf = path.nodes[0];
1220 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1221 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1224 leaf = path.nodes[0];
1227 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1228 if (key.objectid != child_root_id ||
1229 key.type != BTRFS_ROOT_BACKREF_KEY)
1234 if (key.offset == parent_root_id) {
1235 btrfs_release_path(&path);
1242 btrfs_release_path(&path);
1245 return has_parent ? 0 : 2;
1248 static int process_dir_item(struct btrfs_root *root,
1249 struct extent_buffer *eb,
1250 int slot, struct btrfs_key *key,
1251 struct shared_node *active_node)
1261 struct btrfs_dir_item *di;
1262 struct inode_record *rec;
1263 struct cache_tree *root_cache;
1264 struct cache_tree *inode_cache;
1265 struct btrfs_key location;
1266 char namebuf[BTRFS_NAME_LEN];
1268 root_cache = &active_node->root_cache;
1269 inode_cache = &active_node->inode_cache;
1270 rec = active_node->current;
1271 rec->found_dir_item = 1;
1273 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1274 total = btrfs_item_size_nr(eb, slot);
1275 while (cur < total) {
1277 btrfs_dir_item_key_to_cpu(eb, di, &location);
1278 name_len = btrfs_dir_name_len(eb, di);
1279 data_len = btrfs_dir_data_len(eb, di);
1280 filetype = btrfs_dir_type(eb, di);
1282 rec->found_size += name_len;
1283 if (name_len <= BTRFS_NAME_LEN) {
1287 len = BTRFS_NAME_LEN;
1288 error = REF_ERR_NAME_TOO_LONG;
1290 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1292 if (location.type == BTRFS_INODE_ITEM_KEY) {
1293 add_inode_backref(inode_cache, location.objectid,
1294 key->objectid, key->offset, namebuf,
1295 len, filetype, key->type, error);
1296 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1297 add_inode_backref(root_cache, location.objectid,
1298 key->objectid, key->offset,
1299 namebuf, len, filetype,
1302 fprintf(stderr, "invalid location in dir item %u\n",
1304 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1305 key->objectid, key->offset, namebuf,
1306 len, filetype, key->type, error);
1309 len = sizeof(*di) + name_len + data_len;
1310 di = (struct btrfs_dir_item *)((char *)di + len);
1313 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1314 rec->errors |= I_ERR_DUP_DIR_INDEX;
1319 static int process_inode_ref(struct extent_buffer *eb,
1320 int slot, struct btrfs_key *key,
1321 struct shared_node *active_node)
1329 struct cache_tree *inode_cache;
1330 struct btrfs_inode_ref *ref;
1331 char namebuf[BTRFS_NAME_LEN];
1333 inode_cache = &active_node->inode_cache;
1335 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1336 total = btrfs_item_size_nr(eb, slot);
1337 while (cur < total) {
1338 name_len = btrfs_inode_ref_name_len(eb, ref);
1339 index = btrfs_inode_ref_index(eb, ref);
1340 if (name_len <= BTRFS_NAME_LEN) {
1344 len = BTRFS_NAME_LEN;
1345 error = REF_ERR_NAME_TOO_LONG;
1347 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1348 add_inode_backref(inode_cache, key->objectid, key->offset,
1349 index, namebuf, len, 0, key->type, error);
1351 len = sizeof(*ref) + name_len;
1352 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1358 static int process_inode_extref(struct extent_buffer *eb,
1359 int slot, struct btrfs_key *key,
1360 struct shared_node *active_node)
1369 struct cache_tree *inode_cache;
1370 struct btrfs_inode_extref *extref;
1371 char namebuf[BTRFS_NAME_LEN];
1373 inode_cache = &active_node->inode_cache;
1375 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1376 total = btrfs_item_size_nr(eb, slot);
1377 while (cur < total) {
1378 name_len = btrfs_inode_extref_name_len(eb, extref);
1379 index = btrfs_inode_extref_index(eb, extref);
1380 parent = btrfs_inode_extref_parent(eb, extref);
1381 if (name_len <= BTRFS_NAME_LEN) {
1385 len = BTRFS_NAME_LEN;
1386 error = REF_ERR_NAME_TOO_LONG;
1388 read_extent_buffer(eb, namebuf,
1389 (unsigned long)(extref + 1), len);
1390 add_inode_backref(inode_cache, key->objectid, parent,
1391 index, namebuf, len, 0, key->type, error);
1393 len = sizeof(*extref) + name_len;
1394 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1401 static int count_csum_range(struct btrfs_root *root, u64 start,
1402 u64 len, u64 *found)
1404 struct btrfs_key key;
1405 struct btrfs_path path;
1406 struct extent_buffer *leaf;
1411 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1413 btrfs_init_path(&path);
1415 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1417 key.type = BTRFS_EXTENT_CSUM_KEY;
1419 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1423 if (ret > 0 && path.slots[0] > 0) {
1424 leaf = path.nodes[0];
1425 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1426 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1427 key.type == BTRFS_EXTENT_CSUM_KEY)
1432 leaf = path.nodes[0];
1433 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1434 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1439 leaf = path.nodes[0];
1442 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1443 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1444 key.type != BTRFS_EXTENT_CSUM_KEY)
1447 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1448 if (key.offset >= start + len)
1451 if (key.offset > start)
1454 size = btrfs_item_size_nr(leaf, path.slots[0]);
1455 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1456 if (csum_end > start) {
1457 size = min(csum_end - start, len);
1466 btrfs_release_path(&path);
1472 static int process_file_extent(struct btrfs_root *root,
1473 struct extent_buffer *eb,
1474 int slot, struct btrfs_key *key,
1475 struct shared_node *active_node)
1477 struct inode_record *rec;
1478 struct btrfs_file_extent_item *fi;
1480 u64 disk_bytenr = 0;
1481 u64 extent_offset = 0;
1482 u64 mask = root->sectorsize - 1;
1486 rec = active_node->current;
1487 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1488 rec->found_file_extent = 1;
1490 if (rec->extent_start == (u64)-1) {
1491 rec->extent_start = key->offset;
1492 rec->extent_end = key->offset;
1495 if (rec->extent_end > key->offset)
1496 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1497 else if (rec->extent_end < key->offset) {
1498 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1499 key->offset - rec->extent_end);
1504 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1505 extent_type = btrfs_file_extent_type(eb, fi);
1507 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1508 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1510 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1511 rec->found_size += num_bytes;
1512 num_bytes = (num_bytes + mask) & ~mask;
1513 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1514 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1515 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1516 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1517 extent_offset = btrfs_file_extent_offset(eb, fi);
1518 if (num_bytes == 0 || (num_bytes & mask))
1519 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1520 if (num_bytes + extent_offset >
1521 btrfs_file_extent_ram_bytes(eb, fi))
1522 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1523 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1524 (btrfs_file_extent_compression(eb, fi) ||
1525 btrfs_file_extent_encryption(eb, fi) ||
1526 btrfs_file_extent_other_encoding(eb, fi)))
1527 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1528 if (disk_bytenr > 0)
1529 rec->found_size += num_bytes;
1531 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1533 rec->extent_end = key->offset + num_bytes;
1536 * The data reloc tree will copy full extents into its inode and then
1537 * copy the corresponding csums. Because the extent it copied could be
1538 * a preallocated extent that hasn't been written to yet there may be no
1539 * csums to copy, ergo we won't have csums for our file extent. This is
1540 * ok so just don't bother checking csums if the inode belongs to the
1543 if (disk_bytenr > 0 &&
1544 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1546 if (btrfs_file_extent_compression(eb, fi))
1547 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1549 disk_bytenr += extent_offset;
1551 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1554 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1556 rec->found_csum_item = 1;
1557 if (found < num_bytes)
1558 rec->some_csum_missing = 1;
1559 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1561 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1567 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1568 struct walk_control *wc)
1570 struct btrfs_key key;
1574 struct cache_tree *inode_cache;
1575 struct shared_node *active_node;
1577 if (wc->root_level == wc->active_node &&
1578 btrfs_root_refs(&root->root_item) == 0)
1581 active_node = wc->nodes[wc->active_node];
1582 inode_cache = &active_node->inode_cache;
1583 nritems = btrfs_header_nritems(eb);
1584 for (i = 0; i < nritems; i++) {
1585 btrfs_item_key_to_cpu(eb, &key, i);
1587 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1589 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1592 if (active_node->current == NULL ||
1593 active_node->current->ino < key.objectid) {
1594 if (active_node->current) {
1595 active_node->current->checked = 1;
1596 maybe_free_inode_rec(inode_cache,
1597 active_node->current);
1599 active_node->current = get_inode_rec(inode_cache,
1603 case BTRFS_DIR_ITEM_KEY:
1604 case BTRFS_DIR_INDEX_KEY:
1605 ret = process_dir_item(root, eb, i, &key, active_node);
1607 case BTRFS_INODE_REF_KEY:
1608 ret = process_inode_ref(eb, i, &key, active_node);
1610 case BTRFS_INODE_EXTREF_KEY:
1611 ret = process_inode_extref(eb, i, &key, active_node);
1613 case BTRFS_INODE_ITEM_KEY:
1614 ret = process_inode_item(eb, i, &key, active_node);
1616 case BTRFS_EXTENT_DATA_KEY:
1617 ret = process_file_extent(root, eb, i, &key,
1627 static void reada_walk_down(struct btrfs_root *root,
1628 struct extent_buffer *node, int slot)
1637 level = btrfs_header_level(node);
1641 nritems = btrfs_header_nritems(node);
1642 blocksize = btrfs_level_size(root, level - 1);
1643 for (i = slot; i < nritems; i++) {
1644 bytenr = btrfs_node_blockptr(node, i);
1645 ptr_gen = btrfs_node_ptr_generation(node, i);
1646 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1651 * Check the child node/leaf by the following condition:
1652 * 1. the first item key of the node/leaf should be the same with the one
1654 * 2. block in parent node should match the child node/leaf.
1655 * 3. generation of parent node and child's header should be consistent.
1657 * Or the child node/leaf pointed by the key in parent is not valid.
1659 * We hope to check leaf owner too, but since subvol may share leaves,
1660 * which makes leaf owner check not so strong, key check should be
1661 * sufficient enough for that case.
1663 static int check_child_node(struct btrfs_root *root,
1664 struct extent_buffer *parent, int slot,
1665 struct extent_buffer *child)
1667 struct btrfs_key parent_key;
1668 struct btrfs_key child_key;
1671 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1672 if (btrfs_header_level(child) == 0)
1673 btrfs_item_key_to_cpu(child, &child_key, 0);
1675 btrfs_node_key_to_cpu(child, &child_key, 0);
1677 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1680 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1681 parent_key.objectid, parent_key.type, parent_key.offset,
1682 child_key.objectid, child_key.type, child_key.offset);
1684 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1686 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1687 btrfs_node_blockptr(parent, slot),
1688 btrfs_header_bytenr(child));
1690 if (btrfs_node_ptr_generation(parent, slot) !=
1691 btrfs_header_generation(child)) {
1693 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1694 btrfs_header_generation(child),
1695 btrfs_node_ptr_generation(parent, slot));
1700 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1701 struct walk_control *wc, int *level)
1703 enum btrfs_tree_block_status status;
1706 struct extent_buffer *next;
1707 struct extent_buffer *cur;
1712 WARN_ON(*level < 0);
1713 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1714 ret = btrfs_lookup_extent_info(NULL, root,
1715 path->nodes[*level]->start,
1716 *level, 1, &refs, NULL);
1723 ret = enter_shared_node(root, path->nodes[*level]->start,
1731 while (*level >= 0) {
1732 WARN_ON(*level < 0);
1733 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1734 cur = path->nodes[*level];
1736 if (btrfs_header_level(cur) != *level)
1739 if (path->slots[*level] >= btrfs_header_nritems(cur))
1742 ret = process_one_leaf(root, cur, wc);
1747 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1748 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1749 blocksize = btrfs_level_size(root, *level - 1);
1750 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1756 ret = enter_shared_node(root, bytenr, refs,
1759 path->slots[*level]++;
1764 next = btrfs_find_tree_block(root, bytenr, blocksize);
1765 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1766 free_extent_buffer(next);
1767 reada_walk_down(root, cur, path->slots[*level]);
1768 next = read_tree_block(root, bytenr, blocksize,
1770 if (!extent_buffer_uptodate(next)) {
1771 struct btrfs_key node_key;
1773 btrfs_node_key_to_cpu(path->nodes[*level],
1775 path->slots[*level]);
1776 btrfs_add_corrupt_extent_record(root->fs_info,
1778 path->nodes[*level]->start,
1779 root->leafsize, *level);
1785 ret = check_child_node(root, cur, path->slots[*level], next);
1791 if (btrfs_is_leaf(next))
1792 status = btrfs_check_leaf(root, NULL, next);
1794 status = btrfs_check_node(root, NULL, next);
1795 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1796 free_extent_buffer(next);
1801 *level = *level - 1;
1802 free_extent_buffer(path->nodes[*level]);
1803 path->nodes[*level] = next;
1804 path->slots[*level] = 0;
1807 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1811 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1812 struct walk_control *wc, int *level)
1815 struct extent_buffer *leaf;
1817 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1818 leaf = path->nodes[i];
1819 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1824 free_extent_buffer(path->nodes[*level]);
1825 path->nodes[*level] = NULL;
1826 BUG_ON(*level > wc->active_node);
1827 if (*level == wc->active_node)
1828 leave_shared_node(root, wc, *level);
1835 static int check_root_dir(struct inode_record *rec)
1837 struct inode_backref *backref;
1840 if (!rec->found_inode_item || rec->errors)
1842 if (rec->nlink != 1 || rec->found_link != 0)
1844 if (list_empty(&rec->backrefs))
1846 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1847 if (!backref->found_inode_ref)
1849 if (backref->index != 0 || backref->namelen != 2 ||
1850 memcmp(backref->name, "..", 2))
1852 if (backref->found_dir_index || backref->found_dir_item)
1859 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1860 struct btrfs_root *root, struct btrfs_path *path,
1861 struct inode_record *rec)
1863 struct btrfs_inode_item *ei;
1864 struct btrfs_key key;
1867 key.objectid = rec->ino;
1868 key.type = BTRFS_INODE_ITEM_KEY;
1869 key.offset = (u64)-1;
1871 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1875 if (!path->slots[0]) {
1882 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1883 if (key.objectid != rec->ino) {
1888 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1889 struct btrfs_inode_item);
1890 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1891 btrfs_mark_buffer_dirty(path->nodes[0]);
1892 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1893 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1894 root->root_key.objectid);
1896 btrfs_release_path(path);
1900 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1901 struct btrfs_root *root,
1902 struct btrfs_path *path,
1903 struct inode_record *rec)
1907 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1908 btrfs_release_path(path);
1910 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1914 static int add_missing_dir_index(struct btrfs_root *root,
1915 struct cache_tree *inode_cache,
1916 struct inode_record *rec,
1917 struct inode_backref *backref)
1919 struct btrfs_path *path;
1920 struct btrfs_trans_handle *trans;
1921 struct btrfs_dir_item *dir_item;
1922 struct extent_buffer *leaf;
1923 struct btrfs_key key;
1924 struct btrfs_disk_key disk_key;
1925 struct inode_record *dir_rec;
1926 unsigned long name_ptr;
1927 u32 data_size = sizeof(*dir_item) + backref->namelen;
1930 path = btrfs_alloc_path();
1934 trans = btrfs_start_transaction(root, 1);
1935 if (IS_ERR(trans)) {
1936 btrfs_free_path(path);
1937 return PTR_ERR(trans);
1940 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1941 (unsigned long long)rec->ino);
1942 key.objectid = backref->dir;
1943 key.type = BTRFS_DIR_INDEX_KEY;
1944 key.offset = backref->index;
1946 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1949 leaf = path->nodes[0];
1950 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
1952 disk_key.objectid = cpu_to_le64(rec->ino);
1953 disk_key.type = BTRFS_INODE_ITEM_KEY;
1954 disk_key.offset = 0;
1956 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
1957 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
1958 btrfs_set_dir_data_len(leaf, dir_item, 0);
1959 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
1960 name_ptr = (unsigned long)(dir_item + 1);
1961 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
1962 btrfs_mark_buffer_dirty(leaf);
1963 btrfs_free_path(path);
1964 btrfs_commit_transaction(trans, root);
1966 backref->found_dir_index = 1;
1967 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
1970 dir_rec->found_size += backref->namelen;
1971 if (dir_rec->found_size == dir_rec->isize &&
1972 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
1973 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1974 if (dir_rec->found_size != dir_rec->isize)
1975 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
1980 static int delete_dir_index(struct btrfs_root *root,
1981 struct cache_tree *inode_cache,
1982 struct inode_record *rec,
1983 struct inode_backref *backref)
1985 struct btrfs_trans_handle *trans;
1986 struct btrfs_dir_item *di;
1987 struct btrfs_path *path;
1990 path = btrfs_alloc_path();
1994 trans = btrfs_start_transaction(root, 1);
1995 if (IS_ERR(trans)) {
1996 btrfs_free_path(path);
1997 return PTR_ERR(trans);
2001 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2002 (unsigned long long)backref->dir,
2003 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2004 (unsigned long long)root->objectid);
2006 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2007 backref->name, backref->namelen,
2008 backref->index, -1);
2011 btrfs_free_path(path);
2012 btrfs_commit_transaction(trans, root);
2019 ret = btrfs_del_item(trans, root, path);
2021 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2023 btrfs_free_path(path);
2024 btrfs_commit_transaction(trans, root);
2028 static int create_inode_item(struct btrfs_root *root,
2029 struct inode_record *rec,
2030 struct inode_backref *backref, int root_dir)
2032 struct btrfs_trans_handle *trans;
2033 struct btrfs_inode_item inode_item;
2034 time_t now = time(NULL);
2037 trans = btrfs_start_transaction(root, 1);
2038 if (IS_ERR(trans)) {
2039 ret = PTR_ERR(trans);
2043 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2044 "be incomplete, please check permissions and content after "
2045 "the fsck completes.\n", (unsigned long long)root->objectid,
2046 (unsigned long long)rec->ino);
2048 memset(&inode_item, 0, sizeof(inode_item));
2049 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2051 btrfs_set_stack_inode_nlink(&inode_item, 1);
2053 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2054 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2055 if (rec->found_dir_item) {
2056 if (rec->found_file_extent)
2057 fprintf(stderr, "root %llu inode %llu has both a dir "
2058 "item and extents, unsure if it is a dir or a "
2059 "regular file so setting it as a directory\n",
2060 (unsigned long long)root->objectid,
2061 (unsigned long long)rec->ino);
2062 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2063 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2064 } else if (!rec->found_dir_item) {
2065 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2066 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2068 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2069 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2070 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2071 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2072 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2073 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2074 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2075 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2077 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2079 btrfs_commit_transaction(trans, root);
2083 static int repair_inode_backrefs(struct btrfs_root *root,
2084 struct inode_record *rec,
2085 struct cache_tree *inode_cache,
2088 struct inode_backref *tmp, *backref;
2089 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2093 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2094 if (!delete && rec->ino == root_dirid) {
2095 if (!rec->found_inode_item) {
2096 ret = create_inode_item(root, rec, backref, 1);
2103 /* Index 0 for root dir's are special, don't mess with it */
2104 if (rec->ino == root_dirid && backref->index == 0)
2108 ((backref->found_dir_index && !backref->found_inode_ref) ||
2109 (backref->found_dir_index && backref->found_inode_ref &&
2110 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2111 ret = delete_dir_index(root, inode_cache, rec, backref);
2115 list_del(&backref->list);
2119 if (!delete && !backref->found_dir_index &&
2120 backref->found_dir_item && backref->found_inode_ref) {
2121 ret = add_missing_dir_index(root, inode_cache, rec,
2126 if (backref->found_dir_item &&
2127 backref->found_dir_index &&
2128 backref->found_dir_index) {
2129 if (!backref->errors &&
2130 backref->found_inode_ref) {
2131 list_del(&backref->list);
2137 if (!delete && (!backref->found_dir_index &&
2138 !backref->found_dir_item &&
2139 backref->found_inode_ref)) {
2140 struct btrfs_trans_handle *trans;
2141 struct btrfs_key location;
2143 ret = check_dir_conflict(root, backref->name,
2149 * let nlink fixing routine to handle it,
2150 * which can do it better.
2155 location.objectid = rec->ino;
2156 location.type = BTRFS_INODE_ITEM_KEY;
2157 location.offset = 0;
2159 trans = btrfs_start_transaction(root, 1);
2160 if (IS_ERR(trans)) {
2161 ret = PTR_ERR(trans);
2164 fprintf(stderr, "adding missing dir index/item pair "
2166 (unsigned long long)rec->ino);
2167 ret = btrfs_insert_dir_item(trans, root, backref->name,
2169 backref->dir, &location,
2170 imode_to_type(rec->imode),
2173 btrfs_commit_transaction(trans, root);
2177 if (!delete && (backref->found_inode_ref &&
2178 backref->found_dir_index &&
2179 backref->found_dir_item &&
2180 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2181 !rec->found_inode_item)) {
2182 ret = create_inode_item(root, rec, backref, 0);
2189 return ret ? ret : repaired;
2193 * To determine the file type for nlink/inode_item repair
2195 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2196 * Return -ENOENT if file type is not found.
2198 static int find_file_type(struct inode_record *rec, u8 *type)
2200 struct inode_backref *backref;
2202 /* For inode item recovered case */
2203 if (rec->found_inode_item) {
2204 *type = imode_to_type(rec->imode);
2208 list_for_each_entry(backref, &rec->backrefs, list) {
2209 if (backref->found_dir_index || backref->found_dir_item) {
2210 *type = backref->filetype;
2218 * To determine the file name for nlink repair
2220 * Return 0 if file name is found, set name and namelen.
2221 * Return -ENOENT if file name is not found.
2223 static int find_file_name(struct inode_record *rec,
2224 char *name, int *namelen)
2226 struct inode_backref *backref;
2228 list_for_each_entry(backref, &rec->backrefs, list) {
2229 if (backref->found_dir_index || backref->found_dir_item ||
2230 backref->found_inode_ref) {
2231 memcpy(name, backref->name, backref->namelen);
2232 *namelen = backref->namelen;
2239 /* Reset the nlink of the inode to the correct one */
2240 static int reset_nlink(struct btrfs_trans_handle *trans,
2241 struct btrfs_root *root,
2242 struct btrfs_path *path,
2243 struct inode_record *rec)
2245 struct inode_backref *backref;
2246 struct inode_backref *tmp;
2247 struct btrfs_key key;
2248 struct btrfs_inode_item *inode_item;
2251 /* We don't believe this either, reset it and iterate backref */
2252 rec->found_link = 0;
2254 /* Remove all backref including the valid ones */
2255 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2256 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2257 backref->index, backref->name,
2258 backref->namelen, 0);
2262 /* remove invalid backref, so it won't be added back */
2263 if (!(backref->found_dir_index &&
2264 backref->found_dir_item &&
2265 backref->found_inode_ref)) {
2266 list_del(&backref->list);
2273 /* Set nlink to 0 */
2274 key.objectid = rec->ino;
2275 key.type = BTRFS_INODE_ITEM_KEY;
2277 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2284 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2285 struct btrfs_inode_item);
2286 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2287 btrfs_mark_buffer_dirty(path->nodes[0]);
2288 btrfs_release_path(path);
2291 * Add back valid inode_ref/dir_item/dir_index,
2292 * add_link() will handle the nlink inc, so new nlink must be correct
2294 list_for_each_entry(backref, &rec->backrefs, list) {
2295 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2296 backref->name, backref->namelen,
2297 backref->ref_type, &backref->index, 1);
2302 btrfs_release_path(path);
2306 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2307 struct btrfs_root *root,
2308 struct btrfs_path *path,
2309 struct inode_record *rec)
2311 char *dir_name = "lost+found";
2312 char namebuf[BTRFS_NAME_LEN] = {0};
2317 int name_recovered = 0;
2318 int type_recovered = 0;
2322 * Get file name and type first before these invalid inode ref
2323 * are deleted by remove_all_invalid_backref()
2325 name_recovered = !find_file_name(rec, namebuf, &namelen);
2326 type_recovered = !find_file_type(rec, &type);
2328 if (!name_recovered) {
2329 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2330 rec->ino, rec->ino);
2331 namelen = count_digits(rec->ino);
2332 sprintf(namebuf, "%llu", rec->ino);
2335 if (!type_recovered) {
2336 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2338 type = BTRFS_FT_REG_FILE;
2342 ret = reset_nlink(trans, root, path, rec);
2345 "Failed to reset nlink for inode %llu: %s\n",
2346 rec->ino, strerror(-ret));
2350 if (rec->found_link == 0) {
2351 lost_found_ino = root->highest_inode;
2352 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2357 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2358 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2361 fprintf(stderr, "Failed to create '%s' dir: %s",
2362 dir_name, strerror(-ret));
2365 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2366 namebuf, namelen, type, NULL, 1);
2368 * Add ".INO" suffix several times to handle case where
2369 * "FILENAME.INO" is already taken by another file.
2371 while (ret == -EEXIST) {
2373 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2375 if (namelen + count_digits(rec->ino) + 1 >
2380 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2382 namelen += count_digits(rec->ino) + 1;
2383 ret = btrfs_add_link(trans, root, rec->ino,
2384 lost_found_ino, namebuf,
2385 namelen, type, NULL, 1);
2389 "Failed to link the inode %llu to %s dir: %s",
2390 rec->ino, dir_name, strerror(-ret));
2394 * Just increase the found_link, don't actually add the
2395 * backref. This will make things easier and this inode
2396 * record will be freed after the repair is done.
2397 * So fsck will not report problem about this inode.
2400 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2401 namelen, namebuf, dir_name);
2403 printf("Fixed the nlink of inode %llu\n", rec->ino);
2406 * Clear the flag anyway, or we will loop forever for the same inode
2407 * as it will not be removed from the bad inode list and the dead loop
2410 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2411 btrfs_release_path(path);
2416 * Check if there is any normal(reg or prealloc) file extent for given
2418 * This is used to determine the file type when neither its dir_index/item or
2419 * inode_item exists.
2421 * This will *NOT* report error, if any error happens, just consider it does
2422 * not have any normal file extent.
2424 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2426 struct btrfs_path *path;
2427 struct btrfs_key key;
2428 struct btrfs_key found_key;
2429 struct btrfs_file_extent_item *fi;
2433 path = btrfs_alloc_path();
2437 key.type = BTRFS_EXTENT_DATA_KEY;
2440 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2445 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2446 ret = btrfs_next_leaf(root, path);
2453 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2455 if (found_key.objectid != ino ||
2456 found_key.type != BTRFS_EXTENT_DATA_KEY)
2458 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2459 struct btrfs_file_extent_item);
2460 type = btrfs_file_extent_type(path->nodes[0], fi);
2461 if (type != BTRFS_FILE_EXTENT_INLINE) {
2467 btrfs_free_path(path);
2471 static u32 btrfs_type_to_imode(u8 type)
2473 static u32 imode_by_btrfs_type[] = {
2474 [BTRFS_FT_REG_FILE] = S_IFREG,
2475 [BTRFS_FT_DIR] = S_IFDIR,
2476 [BTRFS_FT_CHRDEV] = S_IFCHR,
2477 [BTRFS_FT_BLKDEV] = S_IFBLK,
2478 [BTRFS_FT_FIFO] = S_IFIFO,
2479 [BTRFS_FT_SOCK] = S_IFSOCK,
2480 [BTRFS_FT_SYMLINK] = S_IFLNK,
2483 return imode_by_btrfs_type[(type)];
2486 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2487 struct btrfs_root *root,
2488 struct btrfs_path *path,
2489 struct inode_record *rec)
2493 int type_recovered = 0;
2496 printf("Trying to rebuild inode:%llu\n", rec->ino);
2498 type_recovered = !find_file_type(rec, &filetype);
2501 * Try to determine inode type if type not found.
2503 * For found regular file extent, it must be FILE.
2504 * For found dir_item/index, it must be DIR.
2506 * For undetermined one, use FILE as fallback.
2509 * 1. If found backref(inode_index/item is already handled) to it,
2511 * Need new inode-inode ref structure to allow search for that.
2513 if (!type_recovered) {
2514 if (rec->found_file_extent &&
2515 find_normal_file_extent(root, rec->ino)) {
2517 filetype = BTRFS_FT_REG_FILE;
2518 } else if (rec->found_dir_item) {
2520 filetype = BTRFS_FT_DIR;
2521 } else if (!list_empty(&rec->orphan_extents)) {
2523 filetype = BTRFS_FT_REG_FILE;
2525 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2528 filetype = BTRFS_FT_REG_FILE;
2532 ret = btrfs_new_inode(trans, root, rec->ino,
2533 mode | btrfs_type_to_imode(filetype));
2538 * Here inode rebuild is done, we only rebuild the inode item,
2539 * don't repair the nlink(like move to lost+found).
2540 * That is the job of nlink repair.
2542 * We just fill the record and return
2544 rec->found_dir_item = 1;
2545 rec->imode = mode | btrfs_type_to_imode(filetype);
2547 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2548 /* Ensure the inode_nlinks repair function will be called */
2549 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2554 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2555 struct btrfs_root *root,
2556 struct btrfs_path *path,
2557 struct inode_record *rec)
2559 struct orphan_data_extent *orphan;
2560 struct orphan_data_extent *tmp;
2563 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2565 * Check for conflicting file extents
2567 * Here we don't know whether the extents is compressed or not,
2568 * so we can only assume it not compressed nor data offset,
2569 * and use its disk_len as extent length.
2571 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2572 orphan->offset, orphan->disk_len, 0);
2573 btrfs_release_path(path);
2578 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2579 orphan->disk_bytenr, orphan->disk_len);
2580 ret = btrfs_free_extent(trans,
2581 root->fs_info->extent_root,
2582 orphan->disk_bytenr, orphan->disk_len,
2583 0, root->objectid, orphan->objectid,
2588 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2589 orphan->offset, orphan->disk_bytenr,
2590 orphan->disk_len, orphan->disk_len);
2594 /* Update file size info */
2595 rec->found_size += orphan->disk_len;
2596 if (rec->found_size == rec->nbytes)
2597 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2599 /* Update the file extent hole info too */
2600 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2604 if (RB_EMPTY_ROOT(&rec->holes))
2605 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2607 list_del(&orphan->list);
2610 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2615 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2616 struct btrfs_root *root,
2617 struct btrfs_path *path,
2618 struct inode_record *rec)
2620 struct rb_node *node;
2621 struct file_extent_hole *hole;
2624 node = rb_first(&rec->holes);
2627 hole = rb_entry(node, struct file_extent_hole, node);
2628 ret = btrfs_punch_hole(trans, root, rec->ino,
2629 hole->start, hole->len);
2632 ret = del_file_extent_hole(&rec->holes, hole->start,
2636 if (RB_EMPTY_ROOT(&rec->holes))
2637 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2638 node = rb_first(&rec->holes);
2640 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2641 rec->ino, root->objectid);
2646 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2648 struct btrfs_trans_handle *trans;
2649 struct btrfs_path *path;
2652 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2653 I_ERR_NO_ORPHAN_ITEM |
2654 I_ERR_LINK_COUNT_WRONG |
2655 I_ERR_NO_INODE_ITEM |
2656 I_ERR_FILE_EXTENT_ORPHAN |
2657 I_ERR_FILE_EXTENT_DISCOUNT)))
2660 path = btrfs_alloc_path();
2665 * For nlink repair, it may create a dir and add link, so
2666 * 2 for parent(256)'s dir_index and dir_item
2667 * 2 for lost+found dir's inode_item and inode_ref
2668 * 1 for the new inode_ref of the file
2669 * 2 for lost+found dir's dir_index and dir_item for the file
2671 trans = btrfs_start_transaction(root, 7);
2672 if (IS_ERR(trans)) {
2673 btrfs_free_path(path);
2674 return PTR_ERR(trans);
2677 if (rec->errors & I_ERR_NO_INODE_ITEM)
2678 ret = repair_inode_no_item(trans, root, path, rec);
2679 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2680 ret = repair_inode_orphan_extent(trans, root, path, rec);
2681 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2682 ret = repair_inode_discount_extent(trans, root, path, rec);
2683 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2684 ret = repair_inode_isize(trans, root, path, rec);
2685 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2686 ret = repair_inode_orphan_item(trans, root, path, rec);
2687 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2688 ret = repair_inode_nlinks(trans, root, path, rec);
2689 btrfs_commit_transaction(trans, root);
2690 btrfs_free_path(path);
2694 static int check_inode_recs(struct btrfs_root *root,
2695 struct cache_tree *inode_cache)
2697 struct cache_extent *cache;
2698 struct ptr_node *node;
2699 struct inode_record *rec;
2700 struct inode_backref *backref;
2705 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2707 if (btrfs_root_refs(&root->root_item) == 0) {
2708 if (!cache_tree_empty(inode_cache))
2709 fprintf(stderr, "warning line %d\n", __LINE__);
2714 * We need to record the highest inode number for later 'lost+found'
2716 * We must select a ino not used/refered by any existing inode, or
2717 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2718 * this may cause 'lost+found' dir has wrong nlinks.
2720 cache = last_cache_extent(inode_cache);
2722 node = container_of(cache, struct ptr_node, cache);
2724 if (rec->ino > root->highest_inode)
2725 root->highest_inode = rec->ino;
2729 * We need to repair backrefs first because we could change some of the
2730 * errors in the inode recs.
2732 * We also need to go through and delete invalid backrefs first and then
2733 * add the correct ones second. We do this because we may get EEXIST
2734 * when adding back the correct index because we hadn't yet deleted the
2737 * For example, if we were missing a dir index then the directories
2738 * isize would be wrong, so if we fixed the isize to what we thought it
2739 * would be and then fixed the backref we'd still have a invalid fs, so
2740 * we need to add back the dir index and then check to see if the isize
2745 if (stage == 3 && !err)
2748 cache = search_cache_extent(inode_cache, 0);
2749 while (repair && cache) {
2750 node = container_of(cache, struct ptr_node, cache);
2752 cache = next_cache_extent(cache);
2754 /* Need to free everything up and rescan */
2756 remove_cache_extent(inode_cache, &node->cache);
2758 free_inode_rec(rec);
2762 if (list_empty(&rec->backrefs))
2765 ret = repair_inode_backrefs(root, rec, inode_cache,
2779 rec = get_inode_rec(inode_cache, root_dirid, 0);
2781 ret = check_root_dir(rec);
2783 fprintf(stderr, "root %llu root dir %llu error\n",
2784 (unsigned long long)root->root_key.objectid,
2785 (unsigned long long)root_dirid);
2786 print_inode_error(root, rec);
2791 struct btrfs_trans_handle *trans;
2793 trans = btrfs_start_transaction(root, 1);
2794 if (IS_ERR(trans)) {
2795 err = PTR_ERR(trans);
2800 "root %llu missing its root dir, recreating\n",
2801 (unsigned long long)root->objectid);
2803 ret = btrfs_make_root_dir(trans, root, root_dirid);
2806 btrfs_commit_transaction(trans, root);
2810 fprintf(stderr, "root %llu root dir %llu not found\n",
2811 (unsigned long long)root->root_key.objectid,
2812 (unsigned long long)root_dirid);
2816 cache = search_cache_extent(inode_cache, 0);
2819 node = container_of(cache, struct ptr_node, cache);
2821 remove_cache_extent(inode_cache, &node->cache);
2823 if (rec->ino == root_dirid ||
2824 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2825 free_inode_rec(rec);
2829 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2830 ret = check_orphan_item(root, rec->ino);
2832 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2833 if (can_free_inode_rec(rec)) {
2834 free_inode_rec(rec);
2839 if (!rec->found_inode_item)
2840 rec->errors |= I_ERR_NO_INODE_ITEM;
2841 if (rec->found_link != rec->nlink)
2842 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2844 ret = try_repair_inode(root, rec);
2845 if (ret == 0 && can_free_inode_rec(rec)) {
2846 free_inode_rec(rec);
2852 if (!(repair && ret == 0))
2854 print_inode_error(root, rec);
2855 list_for_each_entry(backref, &rec->backrefs, list) {
2856 if (!backref->found_dir_item)
2857 backref->errors |= REF_ERR_NO_DIR_ITEM;
2858 if (!backref->found_dir_index)
2859 backref->errors |= REF_ERR_NO_DIR_INDEX;
2860 if (!backref->found_inode_ref)
2861 backref->errors |= REF_ERR_NO_INODE_REF;
2862 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2863 " namelen %u name %s filetype %d errors %x",
2864 (unsigned long long)backref->dir,
2865 (unsigned long long)backref->index,
2866 backref->namelen, backref->name,
2867 backref->filetype, backref->errors);
2868 print_ref_error(backref->errors);
2870 free_inode_rec(rec);
2872 return (error > 0) ? -1 : 0;
2875 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2878 struct cache_extent *cache;
2879 struct root_record *rec = NULL;
2882 cache = lookup_cache_extent(root_cache, objectid, 1);
2884 rec = container_of(cache, struct root_record, cache);
2886 rec = calloc(1, sizeof(*rec));
2887 rec->objectid = objectid;
2888 INIT_LIST_HEAD(&rec->backrefs);
2889 rec->cache.start = objectid;
2890 rec->cache.size = 1;
2892 ret = insert_cache_extent(root_cache, &rec->cache);
2898 static struct root_backref *get_root_backref(struct root_record *rec,
2899 u64 ref_root, u64 dir, u64 index,
2900 const char *name, int namelen)
2902 struct root_backref *backref;
2904 list_for_each_entry(backref, &rec->backrefs, list) {
2905 if (backref->ref_root != ref_root || backref->dir != dir ||
2906 backref->namelen != namelen)
2908 if (memcmp(name, backref->name, namelen))
2913 backref = malloc(sizeof(*backref) + namelen + 1);
2914 memset(backref, 0, sizeof(*backref));
2915 backref->ref_root = ref_root;
2917 backref->index = index;
2918 backref->namelen = namelen;
2919 memcpy(backref->name, name, namelen);
2920 backref->name[namelen] = '\0';
2921 list_add_tail(&backref->list, &rec->backrefs);
2925 static void free_root_record(struct cache_extent *cache)
2927 struct root_record *rec;
2928 struct root_backref *backref;
2930 rec = container_of(cache, struct root_record, cache);
2931 while (!list_empty(&rec->backrefs)) {
2932 backref = list_entry(rec->backrefs.next,
2933 struct root_backref, list);
2934 list_del(&backref->list);
2941 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2943 static int add_root_backref(struct cache_tree *root_cache,
2944 u64 root_id, u64 ref_root, u64 dir, u64 index,
2945 const char *name, int namelen,
2946 int item_type, int errors)
2948 struct root_record *rec;
2949 struct root_backref *backref;
2951 rec = get_root_rec(root_cache, root_id);
2952 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2954 backref->errors |= errors;
2956 if (item_type != BTRFS_DIR_ITEM_KEY) {
2957 if (backref->found_dir_index || backref->found_back_ref ||
2958 backref->found_forward_ref) {
2959 if (backref->index != index)
2960 backref->errors |= REF_ERR_INDEX_UNMATCH;
2962 backref->index = index;
2966 if (item_type == BTRFS_DIR_ITEM_KEY) {
2967 if (backref->found_forward_ref)
2969 backref->found_dir_item = 1;
2970 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
2971 backref->found_dir_index = 1;
2972 } else if (item_type == BTRFS_ROOT_REF_KEY) {
2973 if (backref->found_forward_ref)
2974 backref->errors |= REF_ERR_DUP_ROOT_REF;
2975 else if (backref->found_dir_item)
2977 backref->found_forward_ref = 1;
2978 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
2979 if (backref->found_back_ref)
2980 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
2981 backref->found_back_ref = 1;
2986 if (backref->found_forward_ref && backref->found_dir_item)
2987 backref->reachable = 1;
2991 static int merge_root_recs(struct btrfs_root *root,
2992 struct cache_tree *src_cache,
2993 struct cache_tree *dst_cache)
2995 struct cache_extent *cache;
2996 struct ptr_node *node;
2997 struct inode_record *rec;
2998 struct inode_backref *backref;
3001 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3002 free_inode_recs_tree(src_cache);
3007 cache = search_cache_extent(src_cache, 0);
3010 node = container_of(cache, struct ptr_node, cache);
3012 remove_cache_extent(src_cache, &node->cache);
3015 ret = is_child_root(root, root->objectid, rec->ino);
3021 list_for_each_entry(backref, &rec->backrefs, list) {
3022 BUG_ON(backref->found_inode_ref);
3023 if (backref->found_dir_item)
3024 add_root_backref(dst_cache, rec->ino,
3025 root->root_key.objectid, backref->dir,
3026 backref->index, backref->name,
3027 backref->namelen, BTRFS_DIR_ITEM_KEY,
3029 if (backref->found_dir_index)
3030 add_root_backref(dst_cache, rec->ino,
3031 root->root_key.objectid, backref->dir,
3032 backref->index, backref->name,
3033 backref->namelen, BTRFS_DIR_INDEX_KEY,
3037 free_inode_rec(rec);
3044 static int check_root_refs(struct btrfs_root *root,
3045 struct cache_tree *root_cache)
3047 struct root_record *rec;
3048 struct root_record *ref_root;
3049 struct root_backref *backref;
3050 struct cache_extent *cache;
3056 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3059 /* fixme: this can not detect circular references */
3062 cache = search_cache_extent(root_cache, 0);
3066 rec = container_of(cache, struct root_record, cache);
3067 cache = next_cache_extent(cache);
3069 if (rec->found_ref == 0)
3072 list_for_each_entry(backref, &rec->backrefs, list) {
3073 if (!backref->reachable)
3076 ref_root = get_root_rec(root_cache,
3078 if (ref_root->found_ref > 0)
3081 backref->reachable = 0;
3083 if (rec->found_ref == 0)
3089 cache = search_cache_extent(root_cache, 0);
3093 rec = container_of(cache, struct root_record, cache);
3094 cache = next_cache_extent(cache);
3096 if (rec->found_ref == 0 &&
3097 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3098 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3099 ret = check_orphan_item(root->fs_info->tree_root,
3105 * If we don't have a root item then we likely just have
3106 * a dir item in a snapshot for this root but no actual
3107 * ref key or anything so it's meaningless.
3109 if (!rec->found_root_item)
3112 fprintf(stderr, "fs tree %llu not referenced\n",
3113 (unsigned long long)rec->objectid);
3117 if (rec->found_ref > 0 && !rec->found_root_item)
3119 list_for_each_entry(backref, &rec->backrefs, list) {
3120 if (!backref->found_dir_item)
3121 backref->errors |= REF_ERR_NO_DIR_ITEM;
3122 if (!backref->found_dir_index)
3123 backref->errors |= REF_ERR_NO_DIR_INDEX;
3124 if (!backref->found_back_ref)
3125 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3126 if (!backref->found_forward_ref)
3127 backref->errors |= REF_ERR_NO_ROOT_REF;
3128 if (backref->reachable && backref->errors)
3135 fprintf(stderr, "fs tree %llu refs %u %s\n",
3136 (unsigned long long)rec->objectid, rec->found_ref,
3137 rec->found_root_item ? "" : "not found");
3139 list_for_each_entry(backref, &rec->backrefs, list) {
3140 if (!backref->reachable)
3142 if (!backref->errors && rec->found_root_item)
3144 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3145 " index %llu namelen %u name %s errors %x\n",
3146 (unsigned long long)backref->ref_root,
3147 (unsigned long long)backref->dir,
3148 (unsigned long long)backref->index,
3149 backref->namelen, backref->name,
3151 print_ref_error(backref->errors);
3154 return errors > 0 ? 1 : 0;
3157 static int process_root_ref(struct extent_buffer *eb, int slot,
3158 struct btrfs_key *key,
3159 struct cache_tree *root_cache)
3165 struct btrfs_root_ref *ref;
3166 char namebuf[BTRFS_NAME_LEN];
3169 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3171 dirid = btrfs_root_ref_dirid(eb, ref);
3172 index = btrfs_root_ref_sequence(eb, ref);
3173 name_len = btrfs_root_ref_name_len(eb, ref);
3175 if (name_len <= BTRFS_NAME_LEN) {
3179 len = BTRFS_NAME_LEN;
3180 error = REF_ERR_NAME_TOO_LONG;
3182 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3184 if (key->type == BTRFS_ROOT_REF_KEY) {
3185 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3186 index, namebuf, len, key->type, error);
3188 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3189 index, namebuf, len, key->type, error);
3194 static void free_corrupt_block(struct cache_extent *cache)
3196 struct btrfs_corrupt_block *corrupt;
3198 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3202 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3205 * Repair the btree of the given root.
3207 * The fix is to remove the node key in corrupt_blocks cache_tree.
3208 * and rebalance the tree.
3209 * After the fix, the btree should be writeable.
3211 static int repair_btree(struct btrfs_root *root,
3212 struct cache_tree *corrupt_blocks)
3214 struct btrfs_trans_handle *trans;
3215 struct btrfs_path *path;
3216 struct btrfs_corrupt_block *corrupt;
3217 struct cache_extent *cache;
3218 struct btrfs_key key;
3223 if (cache_tree_empty(corrupt_blocks))
3226 path = btrfs_alloc_path();
3230 trans = btrfs_start_transaction(root, 1);
3231 if (IS_ERR(trans)) {
3232 ret = PTR_ERR(trans);
3233 fprintf(stderr, "Error starting transaction: %s\n",
3237 cache = first_cache_extent(corrupt_blocks);
3239 corrupt = container_of(cache, struct btrfs_corrupt_block,
3241 level = corrupt->level;
3242 path->lowest_level = level;
3243 key.objectid = corrupt->key.objectid;
3244 key.type = corrupt->key.type;
3245 key.offset = corrupt->key.offset;
3248 * Here we don't want to do any tree balance, since it may
3249 * cause a balance with corrupted brother leaf/node,
3250 * so ins_len set to 0 here.
3251 * Balance will be done after all corrupt node/leaf is deleted.
3253 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3256 offset = btrfs_node_blockptr(path->nodes[level],
3257 path->slots[level]);
3259 /* Remove the ptr */
3260 ret = btrfs_del_ptr(trans, root, path, level,
3261 path->slots[level]);
3265 * Remove the corresponding extent
3266 * return value is not concerned.
3268 btrfs_release_path(path);
3269 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3270 0, root->root_key.objectid,
3272 cache = next_cache_extent(cache);
3275 /* Balance the btree using btrfs_search_slot() */
3276 cache = first_cache_extent(corrupt_blocks);
3278 corrupt = container_of(cache, struct btrfs_corrupt_block,
3280 memcpy(&key, &corrupt->key, sizeof(key));
3281 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3284 /* return will always >0 since it won't find the item */
3286 btrfs_release_path(path);
3287 cache = next_cache_extent(cache);
3290 btrfs_commit_transaction(trans, root);
3292 btrfs_free_path(path);
3296 static int check_fs_root(struct btrfs_root *root,
3297 struct cache_tree *root_cache,
3298 struct walk_control *wc)
3304 struct btrfs_path path;
3305 struct shared_node root_node;
3306 struct root_record *rec;
3307 struct btrfs_root_item *root_item = &root->root_item;
3308 struct cache_tree corrupt_blocks;
3309 struct orphan_data_extent *orphan;
3310 struct orphan_data_extent *tmp;
3311 enum btrfs_tree_block_status status;
3314 * Reuse the corrupt_block cache tree to record corrupted tree block
3316 * Unlike the usage in extent tree check, here we do it in a per
3317 * fs/subvol tree base.
3319 cache_tree_init(&corrupt_blocks);
3320 root->fs_info->corrupt_blocks = &corrupt_blocks;
3322 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3323 rec = get_root_rec(root_cache, root->root_key.objectid);
3324 if (btrfs_root_refs(root_item) > 0)
3325 rec->found_root_item = 1;
3328 btrfs_init_path(&path);
3329 memset(&root_node, 0, sizeof(root_node));
3330 cache_tree_init(&root_node.root_cache);
3331 cache_tree_init(&root_node.inode_cache);
3333 /* Move the orphan extent record to corresponding inode_record */
3334 list_for_each_entry_safe(orphan, tmp,
3335 &root->orphan_data_extents, list) {
3336 struct inode_record *inode;
3338 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3340 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3341 list_move(&orphan->list, &inode->orphan_extents);
3344 level = btrfs_header_level(root->node);
3345 memset(wc->nodes, 0, sizeof(wc->nodes));
3346 wc->nodes[level] = &root_node;
3347 wc->active_node = level;
3348 wc->root_level = level;
3350 /* We may not have checked the root block, lets do that now */
3351 if (btrfs_is_leaf(root->node))
3352 status = btrfs_check_leaf(root, NULL, root->node);
3354 status = btrfs_check_node(root, NULL, root->node);
3355 if (status != BTRFS_TREE_BLOCK_CLEAN)
3358 if (btrfs_root_refs(root_item) > 0 ||
3359 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3360 path.nodes[level] = root->node;
3361 extent_buffer_get(root->node);
3362 path.slots[level] = 0;
3364 struct btrfs_key key;
3365 struct btrfs_disk_key found_key;
3367 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3368 level = root_item->drop_level;
3369 path.lowest_level = level;
3370 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3373 btrfs_node_key(path.nodes[level], &found_key,
3375 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3376 sizeof(found_key)));
3380 wret = walk_down_tree(root, &path, wc, &level);
3386 wret = walk_up_tree(root, &path, wc, &level);
3393 btrfs_release_path(&path);
3395 if (!cache_tree_empty(&corrupt_blocks)) {
3396 struct cache_extent *cache;
3397 struct btrfs_corrupt_block *corrupt;
3399 printf("The following tree block(s) is corrupted in tree %llu:\n",
3400 root->root_key.objectid);
3401 cache = first_cache_extent(&corrupt_blocks);
3403 corrupt = container_of(cache,
3404 struct btrfs_corrupt_block,
3406 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3407 cache->start, corrupt->level,
3408 corrupt->key.objectid, corrupt->key.type,
3409 corrupt->key.offset);
3410 cache = next_cache_extent(cache);
3413 printf("Try to repair the btree for root %llu\n",
3414 root->root_key.objectid);
3415 ret = repair_btree(root, &corrupt_blocks);
3417 fprintf(stderr, "Failed to repair btree: %s\n",
3420 printf("Btree for root %llu is fixed\n",
3421 root->root_key.objectid);
3425 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3429 if (root_node.current) {
3430 root_node.current->checked = 1;
3431 maybe_free_inode_rec(&root_node.inode_cache,
3435 err = check_inode_recs(root, &root_node.inode_cache);
3439 free_corrupt_blocks_tree(&corrupt_blocks);
3440 root->fs_info->corrupt_blocks = NULL;
3441 free_orphan_data_extents(&root->orphan_data_extents);
3445 static int fs_root_objectid(u64 objectid)
3447 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3448 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3450 return is_fstree(objectid);
3453 static int check_fs_roots(struct btrfs_root *root,
3454 struct cache_tree *root_cache)
3456 struct btrfs_path path;
3457 struct btrfs_key key;
3458 struct walk_control wc;
3459 struct extent_buffer *leaf, *tree_node;
3460 struct btrfs_root *tmp_root;
3461 struct btrfs_root *tree_root = root->fs_info->tree_root;
3466 * Just in case we made any changes to the extent tree that weren't
3467 * reflected into the free space cache yet.
3470 reset_cached_block_groups(root->fs_info);
3471 memset(&wc, 0, sizeof(wc));
3472 cache_tree_init(&wc.shared);
3473 btrfs_init_path(&path);
3478 key.type = BTRFS_ROOT_ITEM_KEY;
3479 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3484 tree_node = tree_root->node;
3486 if (tree_node != tree_root->node) {
3487 free_root_recs_tree(root_cache);
3488 btrfs_release_path(&path);
3491 leaf = path.nodes[0];
3492 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3493 ret = btrfs_next_leaf(tree_root, &path);
3499 leaf = path.nodes[0];
3501 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3502 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3503 fs_root_objectid(key.objectid)) {
3504 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3505 tmp_root = btrfs_read_fs_root_no_cache(
3506 root->fs_info, &key);
3508 key.offset = (u64)-1;
3509 tmp_root = btrfs_read_fs_root(
3510 root->fs_info, &key);
3512 if (IS_ERR(tmp_root)) {
3516 ret = check_fs_root(tmp_root, root_cache, &wc);
3517 if (ret == -EAGAIN) {
3518 free_root_recs_tree(root_cache);
3519 btrfs_release_path(&path);
3524 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3525 btrfs_free_fs_root(tmp_root);
3526 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3527 key.type == BTRFS_ROOT_BACKREF_KEY) {
3528 process_root_ref(leaf, path.slots[0], &key,
3535 btrfs_release_path(&path);
3537 free_extent_cache_tree(&wc.shared);
3538 if (!cache_tree_empty(&wc.shared))
3539 fprintf(stderr, "warning line %d\n", __LINE__);
3544 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3546 struct list_head *cur = rec->backrefs.next;
3547 struct extent_backref *back;
3548 struct tree_backref *tback;
3549 struct data_backref *dback;
3553 while(cur != &rec->backrefs) {
3554 back = list_entry(cur, struct extent_backref, list);
3556 if (!back->found_extent_tree) {
3560 if (back->is_data) {
3561 dback = (struct data_backref *)back;
3562 fprintf(stderr, "Backref %llu %s %llu"
3563 " owner %llu offset %llu num_refs %lu"
3564 " not found in extent tree\n",
3565 (unsigned long long)rec->start,
3566 back->full_backref ?
3568 back->full_backref ?
3569 (unsigned long long)dback->parent:
3570 (unsigned long long)dback->root,
3571 (unsigned long long)dback->owner,
3572 (unsigned long long)dback->offset,
3573 (unsigned long)dback->num_refs);
3575 tback = (struct tree_backref *)back;
3576 fprintf(stderr, "Backref %llu parent %llu"
3577 " root %llu not found in extent tree\n",
3578 (unsigned long long)rec->start,
3579 (unsigned long long)tback->parent,
3580 (unsigned long long)tback->root);
3583 if (!back->is_data && !back->found_ref) {
3587 tback = (struct tree_backref *)back;
3588 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3589 (unsigned long long)rec->start,
3590 back->full_backref ? "parent" : "root",
3591 back->full_backref ?
3592 (unsigned long long)tback->parent :
3593 (unsigned long long)tback->root, back);
3595 if (back->is_data) {
3596 dback = (struct data_backref *)back;
3597 if (dback->found_ref != dback->num_refs) {
3601 fprintf(stderr, "Incorrect local backref count"
3602 " on %llu %s %llu owner %llu"
3603 " offset %llu found %u wanted %u back %p\n",
3604 (unsigned long long)rec->start,
3605 back->full_backref ?
3607 back->full_backref ?
3608 (unsigned long long)dback->parent:
3609 (unsigned long long)dback->root,
3610 (unsigned long long)dback->owner,
3611 (unsigned long long)dback->offset,
3612 dback->found_ref, dback->num_refs, back);
3614 if (dback->disk_bytenr != rec->start) {
3618 fprintf(stderr, "Backref disk bytenr does not"
3619 " match extent record, bytenr=%llu, "
3620 "ref bytenr=%llu\n",
3621 (unsigned long long)rec->start,
3622 (unsigned long long)dback->disk_bytenr);
3625 if (dback->bytes != rec->nr) {
3629 fprintf(stderr, "Backref bytes do not match "
3630 "extent backref, bytenr=%llu, ref "
3631 "bytes=%llu, backref bytes=%llu\n",
3632 (unsigned long long)rec->start,
3633 (unsigned long long)rec->nr,
3634 (unsigned long long)dback->bytes);
3637 if (!back->is_data) {
3640 dback = (struct data_backref *)back;
3641 found += dback->found_ref;
3644 if (found != rec->refs) {
3648 fprintf(stderr, "Incorrect global backref count "
3649 "on %llu found %llu wanted %llu\n",
3650 (unsigned long long)rec->start,
3651 (unsigned long long)found,
3652 (unsigned long long)rec->refs);
3658 static int free_all_extent_backrefs(struct extent_record *rec)
3660 struct extent_backref *back;
3661 struct list_head *cur;
3662 while (!list_empty(&rec->backrefs)) {
3663 cur = rec->backrefs.next;
3664 back = list_entry(cur, struct extent_backref, list);
3671 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3672 struct cache_tree *extent_cache)
3674 struct cache_extent *cache;
3675 struct extent_record *rec;
3678 cache = first_cache_extent(extent_cache);
3681 rec = container_of(cache, struct extent_record, cache);
3682 remove_cache_extent(extent_cache, cache);
3683 free_all_extent_backrefs(rec);
3688 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3689 struct extent_record *rec)
3691 if (rec->content_checked && rec->owner_ref_checked &&
3692 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3693 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3694 !rec->bad_full_backref) {
3695 remove_cache_extent(extent_cache, &rec->cache);
3696 free_all_extent_backrefs(rec);
3697 list_del_init(&rec->list);
3703 static int check_owner_ref(struct btrfs_root *root,
3704 struct extent_record *rec,
3705 struct extent_buffer *buf)
3707 struct extent_backref *node;
3708 struct tree_backref *back;
3709 struct btrfs_root *ref_root;
3710 struct btrfs_key key;
3711 struct btrfs_path path;
3712 struct extent_buffer *parent;
3717 list_for_each_entry(node, &rec->backrefs, list) {
3720 if (!node->found_ref)
3722 if (node->full_backref)
3724 back = (struct tree_backref *)node;
3725 if (btrfs_header_owner(buf) == back->root)
3728 BUG_ON(rec->is_root);
3730 /* try to find the block by search corresponding fs tree */
3731 key.objectid = btrfs_header_owner(buf);
3732 key.type = BTRFS_ROOT_ITEM_KEY;
3733 key.offset = (u64)-1;
3735 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3736 if (IS_ERR(ref_root))
3739 level = btrfs_header_level(buf);
3741 btrfs_item_key_to_cpu(buf, &key, 0);
3743 btrfs_node_key_to_cpu(buf, &key, 0);
3745 btrfs_init_path(&path);
3746 path.lowest_level = level + 1;
3747 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3751 parent = path.nodes[level + 1];
3752 if (parent && buf->start == btrfs_node_blockptr(parent,
3753 path.slots[level + 1]))
3756 btrfs_release_path(&path);
3757 return found ? 0 : 1;
3760 static int is_extent_tree_record(struct extent_record *rec)
3762 struct list_head *cur = rec->backrefs.next;
3763 struct extent_backref *node;
3764 struct tree_backref *back;
3767 while(cur != &rec->backrefs) {
3768 node = list_entry(cur, struct extent_backref, list);
3772 back = (struct tree_backref *)node;
3773 if (node->full_backref)
3775 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3782 static int record_bad_block_io(struct btrfs_fs_info *info,
3783 struct cache_tree *extent_cache,
3786 struct extent_record *rec;
3787 struct cache_extent *cache;
3788 struct btrfs_key key;
3790 cache = lookup_cache_extent(extent_cache, start, len);
3794 rec = container_of(cache, struct extent_record, cache);
3795 if (!is_extent_tree_record(rec))
3798 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3799 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3802 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3803 struct extent_buffer *buf, int slot)
3805 if (btrfs_header_level(buf)) {
3806 struct btrfs_key_ptr ptr1, ptr2;
3808 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3809 sizeof(struct btrfs_key_ptr));
3810 read_extent_buffer(buf, &ptr2,
3811 btrfs_node_key_ptr_offset(slot + 1),
3812 sizeof(struct btrfs_key_ptr));
3813 write_extent_buffer(buf, &ptr1,
3814 btrfs_node_key_ptr_offset(slot + 1),
3815 sizeof(struct btrfs_key_ptr));
3816 write_extent_buffer(buf, &ptr2,
3817 btrfs_node_key_ptr_offset(slot),
3818 sizeof(struct btrfs_key_ptr));
3820 struct btrfs_disk_key key;
3821 btrfs_node_key(buf, &key, 0);
3822 btrfs_fixup_low_keys(root, path, &key,
3823 btrfs_header_level(buf) + 1);
3826 struct btrfs_item *item1, *item2;
3827 struct btrfs_key k1, k2;
3828 char *item1_data, *item2_data;
3829 u32 item1_offset, item2_offset, item1_size, item2_size;
3831 item1 = btrfs_item_nr(slot);
3832 item2 = btrfs_item_nr(slot + 1);
3833 btrfs_item_key_to_cpu(buf, &k1, slot);
3834 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3835 item1_offset = btrfs_item_offset(buf, item1);
3836 item2_offset = btrfs_item_offset(buf, item2);
3837 item1_size = btrfs_item_size(buf, item1);
3838 item2_size = btrfs_item_size(buf, item2);
3840 item1_data = malloc(item1_size);
3843 item2_data = malloc(item2_size);
3849 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3850 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3852 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3853 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3857 btrfs_set_item_offset(buf, item1, item2_offset);
3858 btrfs_set_item_offset(buf, item2, item1_offset);
3859 btrfs_set_item_size(buf, item1, item2_size);
3860 btrfs_set_item_size(buf, item2, item1_size);
3862 path->slots[0] = slot;
3863 btrfs_set_item_key_unsafe(root, path, &k2);
3864 path->slots[0] = slot + 1;
3865 btrfs_set_item_key_unsafe(root, path, &k1);
3870 static int fix_key_order(struct btrfs_trans_handle *trans,
3871 struct btrfs_root *root,
3872 struct btrfs_path *path)
3874 struct extent_buffer *buf;
3875 struct btrfs_key k1, k2;
3877 int level = path->lowest_level;
3880 buf = path->nodes[level];
3881 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3883 btrfs_node_key_to_cpu(buf, &k1, i);
3884 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3886 btrfs_item_key_to_cpu(buf, &k1, i);
3887 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3889 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3891 ret = swap_values(root, path, buf, i);
3894 btrfs_mark_buffer_dirty(buf);
3900 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3901 struct btrfs_root *root,
3902 struct btrfs_path *path,
3903 struct extent_buffer *buf, int slot)
3905 struct btrfs_key key;
3906 int nritems = btrfs_header_nritems(buf);
3908 btrfs_item_key_to_cpu(buf, &key, slot);
3910 /* These are all the keys we can deal with missing. */
3911 if (key.type != BTRFS_DIR_INDEX_KEY &&
3912 key.type != BTRFS_EXTENT_ITEM_KEY &&
3913 key.type != BTRFS_METADATA_ITEM_KEY &&
3914 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3915 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3918 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3919 (unsigned long long)key.objectid, key.type,
3920 (unsigned long long)key.offset, slot, buf->start);
3921 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3922 btrfs_item_nr_offset(slot + 1),
3923 sizeof(struct btrfs_item) *
3924 (nritems - slot - 1));
3925 btrfs_set_header_nritems(buf, nritems - 1);
3927 struct btrfs_disk_key disk_key;
3929 btrfs_item_key(buf, &disk_key, 0);
3930 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3932 btrfs_mark_buffer_dirty(buf);
3936 static int fix_item_offset(struct btrfs_trans_handle *trans,
3937 struct btrfs_root *root,
3938 struct btrfs_path *path)
3940 struct extent_buffer *buf;
3944 /* We should only get this for leaves */
3945 BUG_ON(path->lowest_level);
3946 buf = path->nodes[0];
3948 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3949 unsigned int shift = 0, offset;
3951 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3952 BTRFS_LEAF_DATA_SIZE(root)) {
3953 if (btrfs_item_end_nr(buf, i) >
3954 BTRFS_LEAF_DATA_SIZE(root)) {
3955 ret = delete_bogus_item(trans, root, path,
3959 fprintf(stderr, "item is off the end of the "
3960 "leaf, can't fix\n");
3964 shift = BTRFS_LEAF_DATA_SIZE(root) -
3965 btrfs_item_end_nr(buf, i);
3966 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
3967 btrfs_item_offset_nr(buf, i - 1)) {
3968 if (btrfs_item_end_nr(buf, i) >
3969 btrfs_item_offset_nr(buf, i - 1)) {
3970 ret = delete_bogus_item(trans, root, path,
3974 fprintf(stderr, "items overlap, can't fix\n");
3978 shift = btrfs_item_offset_nr(buf, i - 1) -
3979 btrfs_item_end_nr(buf, i);
3984 printf("Shifting item nr %d by %u bytes in block %llu\n",
3985 i, shift, (unsigned long long)buf->start);
3986 offset = btrfs_item_offset_nr(buf, i);
3987 memmove_extent_buffer(buf,
3988 btrfs_leaf_data(buf) + offset + shift,
3989 btrfs_leaf_data(buf) + offset,
3990 btrfs_item_size_nr(buf, i));
3991 btrfs_set_item_offset(buf, btrfs_item_nr(i),
3993 btrfs_mark_buffer_dirty(buf);
3997 * We may have moved things, in which case we want to exit so we don't
3998 * write those changes out. Once we have proper abort functionality in
3999 * progs this can be changed to something nicer.
4006 * Attempt to fix basic block failures. If we can't fix it for whatever reason
4007 * then just return -EIO.
4009 static int try_to_fix_bad_block(struct btrfs_root *root,
4010 struct extent_buffer *buf,
4011 enum btrfs_tree_block_status status)
4013 struct btrfs_trans_handle *trans;
4014 struct ulist *roots;
4015 struct ulist_node *node;
4016 struct btrfs_root *search_root;
4017 struct btrfs_path *path;
4018 struct ulist_iterator iter;
4019 struct btrfs_key root_key, key;
4022 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4023 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4026 path = btrfs_alloc_path();
4030 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4033 btrfs_free_path(path);
4037 ULIST_ITER_INIT(&iter);
4038 while ((node = ulist_next(roots, &iter))) {
4039 root_key.objectid = node->val;
4040 root_key.type = BTRFS_ROOT_ITEM_KEY;
4041 root_key.offset = (u64)-1;
4043 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4050 trans = btrfs_start_transaction(search_root, 0);
4051 if (IS_ERR(trans)) {
4052 ret = PTR_ERR(trans);
4056 path->lowest_level = btrfs_header_level(buf);
4057 path->skip_check_block = 1;
4058 if (path->lowest_level)
4059 btrfs_node_key_to_cpu(buf, &key, 0);
4061 btrfs_item_key_to_cpu(buf, &key, 0);
4062 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4065 btrfs_commit_transaction(trans, search_root);
4068 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4069 ret = fix_key_order(trans, search_root, path);
4070 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4071 ret = fix_item_offset(trans, search_root, path);
4073 btrfs_commit_transaction(trans, search_root);
4076 btrfs_release_path(path);
4077 btrfs_commit_transaction(trans, search_root);
4080 btrfs_free_path(path);
4084 static int check_block(struct btrfs_root *root,
4085 struct cache_tree *extent_cache,
4086 struct extent_buffer *buf, u64 flags)
4088 struct extent_record *rec;
4089 struct cache_extent *cache;
4090 struct btrfs_key key;
4091 enum btrfs_tree_block_status status;
4095 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4098 rec = container_of(cache, struct extent_record, cache);
4099 rec->generation = btrfs_header_generation(buf);
4101 level = btrfs_header_level(buf);
4102 if (btrfs_header_nritems(buf) > 0) {
4105 btrfs_item_key_to_cpu(buf, &key, 0);
4107 btrfs_node_key_to_cpu(buf, &key, 0);
4109 rec->info_objectid = key.objectid;
4111 rec->info_level = level;
4113 if (btrfs_is_leaf(buf))
4114 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4116 status = btrfs_check_node(root, &rec->parent_key, buf);
4118 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4120 status = try_to_fix_bad_block(root, buf, status);
4121 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4123 fprintf(stderr, "bad block %llu\n",
4124 (unsigned long long)buf->start);
4127 * Signal to callers we need to start the scan over
4128 * again since we'll have cow'ed blocks.
4133 rec->content_checked = 1;
4134 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4135 rec->owner_ref_checked = 1;
4137 ret = check_owner_ref(root, rec, buf);
4139 rec->owner_ref_checked = 1;
4143 maybe_free_extent_rec(extent_cache, rec);
4147 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4148 u64 parent, u64 root)
4150 struct list_head *cur = rec->backrefs.next;
4151 struct extent_backref *node;
4152 struct tree_backref *back;
4154 while(cur != &rec->backrefs) {
4155 node = list_entry(cur, struct extent_backref, list);
4159 back = (struct tree_backref *)node;
4161 if (!node->full_backref)
4163 if (parent == back->parent)
4166 if (node->full_backref)
4168 if (back->root == root)
4175 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4176 u64 parent, u64 root)
4178 struct tree_backref *ref = malloc(sizeof(*ref));
4179 memset(&ref->node, 0, sizeof(ref->node));
4181 ref->parent = parent;
4182 ref->node.full_backref = 1;
4185 ref->node.full_backref = 0;
4187 list_add_tail(&ref->node.list, &rec->backrefs);
4192 static struct data_backref *find_data_backref(struct extent_record *rec,
4193 u64 parent, u64 root,
4194 u64 owner, u64 offset,
4196 u64 disk_bytenr, u64 bytes)
4198 struct list_head *cur = rec->backrefs.next;
4199 struct extent_backref *node;
4200 struct data_backref *back;
4202 while(cur != &rec->backrefs) {
4203 node = list_entry(cur, struct extent_backref, list);
4207 back = (struct data_backref *)node;
4209 if (!node->full_backref)
4211 if (parent == back->parent)
4214 if (node->full_backref)
4216 if (back->root == root && back->owner == owner &&
4217 back->offset == offset) {
4218 if (found_ref && node->found_ref &&
4219 (back->bytes != bytes ||
4220 back->disk_bytenr != disk_bytenr))
4229 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4230 u64 parent, u64 root,
4231 u64 owner, u64 offset,
4234 struct data_backref *ref = malloc(sizeof(*ref));
4235 memset(&ref->node, 0, sizeof(ref->node));
4236 ref->node.is_data = 1;
4239 ref->parent = parent;
4242 ref->node.full_backref = 1;
4246 ref->offset = offset;
4247 ref->node.full_backref = 0;
4249 ref->bytes = max_size;
4252 list_add_tail(&ref->node.list, &rec->backrefs);
4253 if (max_size > rec->max_size)
4254 rec->max_size = max_size;
4258 static int add_extent_rec(struct cache_tree *extent_cache,
4259 struct btrfs_key *parent_key, u64 parent_gen,
4260 u64 start, u64 nr, u64 extent_item_refs,
4261 int is_root, int inc_ref, int set_checked,
4262 int metadata, int extent_rec, u64 max_size)
4264 struct extent_record *rec;
4265 struct cache_extent *cache;
4269 cache = lookup_cache_extent(extent_cache, start, nr);
4271 rec = container_of(cache, struct extent_record, cache);
4275 rec->nr = max(nr, max_size);
4278 * We need to make sure to reset nr to whatever the extent
4279 * record says was the real size, this way we can compare it to
4283 if (start != rec->start || rec->found_rec) {
4284 struct extent_record *tmp;
4287 if (list_empty(&rec->list))
4288 list_add_tail(&rec->list,
4289 &duplicate_extents);
4292 * We have to do this song and dance in case we
4293 * find an extent record that falls inside of
4294 * our current extent record but does not have
4295 * the same objectid.
4297 tmp = malloc(sizeof(*tmp));
4301 tmp->max_size = max_size;
4304 tmp->metadata = metadata;
4305 tmp->extent_item_refs = extent_item_refs;
4306 INIT_LIST_HEAD(&tmp->list);
4307 list_add_tail(&tmp->list, &rec->dups);
4308 rec->num_duplicates++;
4315 if (extent_item_refs && !dup) {
4316 if (rec->extent_item_refs) {
4317 fprintf(stderr, "block %llu rec "
4318 "extent_item_refs %llu, passed %llu\n",
4319 (unsigned long long)start,
4320 (unsigned long long)
4321 rec->extent_item_refs,
4322 (unsigned long long)extent_item_refs);
4324 rec->extent_item_refs = extent_item_refs;
4329 rec->content_checked = 1;
4330 rec->owner_ref_checked = 1;
4334 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4336 rec->parent_generation = parent_gen;
4338 if (rec->max_size < max_size)
4339 rec->max_size = max_size;
4341 maybe_free_extent_rec(extent_cache, rec);
4344 rec = malloc(sizeof(*rec));
4346 rec->max_size = max_size;
4347 rec->nr = max(nr, max_size);
4348 rec->found_rec = !!extent_rec;
4349 rec->content_checked = 0;
4350 rec->owner_ref_checked = 0;
4351 rec->num_duplicates = 0;
4352 rec->metadata = metadata;
4353 rec->flag_block_full_backref = -1;
4354 rec->bad_full_backref = 0;
4355 INIT_LIST_HEAD(&rec->backrefs);
4356 INIT_LIST_HEAD(&rec->dups);
4357 INIT_LIST_HEAD(&rec->list);
4369 if (extent_item_refs)
4370 rec->extent_item_refs = extent_item_refs;
4372 rec->extent_item_refs = 0;
4375 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4377 memset(&rec->parent_key, 0, sizeof(*parent_key));
4380 rec->parent_generation = parent_gen;
4382 rec->parent_generation = 0;
4384 rec->cache.start = start;
4385 rec->cache.size = nr;
4386 ret = insert_cache_extent(extent_cache, &rec->cache);
4390 rec->content_checked = 1;
4391 rec->owner_ref_checked = 1;
4396 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4397 u64 parent, u64 root, int found_ref)
4399 struct extent_record *rec;
4400 struct tree_backref *back;
4401 struct cache_extent *cache;
4403 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4405 add_extent_rec(extent_cache, NULL, 0, bytenr,
4406 1, 0, 0, 0, 0, 1, 0, 0);
4407 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4412 rec = container_of(cache, struct extent_record, cache);
4413 if (rec->start != bytenr) {
4417 back = find_tree_backref(rec, parent, root);
4419 back = alloc_tree_backref(rec, parent, root);
4422 if (back->node.found_ref) {
4423 fprintf(stderr, "Extent back ref already exists "
4424 "for %llu parent %llu root %llu \n",
4425 (unsigned long long)bytenr,
4426 (unsigned long long)parent,
4427 (unsigned long long)root);
4429 back->node.found_ref = 1;
4431 if (back->node.found_extent_tree) {
4432 fprintf(stderr, "Extent back ref already exists "
4433 "for %llu parent %llu root %llu \n",
4434 (unsigned long long)bytenr,
4435 (unsigned long long)parent,
4436 (unsigned long long)root);
4438 back->node.found_extent_tree = 1;
4440 maybe_free_extent_rec(extent_cache, rec);
4444 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4445 u64 parent, u64 root, u64 owner, u64 offset,
4446 u32 num_refs, int found_ref, u64 max_size)
4448 struct extent_record *rec;
4449 struct data_backref *back;
4450 struct cache_extent *cache;
4452 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4454 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4456 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4461 rec = container_of(cache, struct extent_record, cache);
4462 if (rec->max_size < max_size)
4463 rec->max_size = max_size;
4466 * If found_ref is set then max_size is the real size and must match the
4467 * existing refs. So if we have already found a ref then we need to
4468 * make sure that this ref matches the existing one, otherwise we need
4469 * to add a new backref so we can notice that the backrefs don't match
4470 * and we need to figure out who is telling the truth. This is to
4471 * account for that awful fsync bug I introduced where we'd end up with
4472 * a btrfs_file_extent_item that would have its length include multiple
4473 * prealloc extents or point inside of a prealloc extent.
4475 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4478 back = alloc_data_backref(rec, parent, root, owner, offset,
4482 BUG_ON(num_refs != 1);
4483 if (back->node.found_ref)
4484 BUG_ON(back->bytes != max_size);
4485 back->node.found_ref = 1;
4486 back->found_ref += 1;
4487 back->bytes = max_size;
4488 back->disk_bytenr = bytenr;
4490 rec->content_checked = 1;
4491 rec->owner_ref_checked = 1;
4493 if (back->node.found_extent_tree) {
4494 fprintf(stderr, "Extent back ref already exists "
4495 "for %llu parent %llu root %llu "
4496 "owner %llu offset %llu num_refs %lu\n",
4497 (unsigned long long)bytenr,
4498 (unsigned long long)parent,
4499 (unsigned long long)root,
4500 (unsigned long long)owner,
4501 (unsigned long long)offset,
4502 (unsigned long)num_refs);
4504 back->num_refs = num_refs;
4505 back->node.found_extent_tree = 1;
4507 maybe_free_extent_rec(extent_cache, rec);
4511 static int add_pending(struct cache_tree *pending,
4512 struct cache_tree *seen, u64 bytenr, u32 size)
4515 ret = add_cache_extent(seen, bytenr, size);
4518 add_cache_extent(pending, bytenr, size);
4522 static int pick_next_pending(struct cache_tree *pending,
4523 struct cache_tree *reada,
4524 struct cache_tree *nodes,
4525 u64 last, struct block_info *bits, int bits_nr,
4528 unsigned long node_start = last;
4529 struct cache_extent *cache;
4532 cache = search_cache_extent(reada, 0);
4534 bits[0].start = cache->start;
4535 bits[0].size = cache->size;
4540 if (node_start > 32768)
4541 node_start -= 32768;
4543 cache = search_cache_extent(nodes, node_start);
4545 cache = search_cache_extent(nodes, 0);
4548 cache = search_cache_extent(pending, 0);
4553 bits[ret].start = cache->start;
4554 bits[ret].size = cache->size;
4555 cache = next_cache_extent(cache);
4557 } while (cache && ret < bits_nr);
4563 bits[ret].start = cache->start;
4564 bits[ret].size = cache->size;
4565 cache = next_cache_extent(cache);
4567 } while (cache && ret < bits_nr);
4569 if (bits_nr - ret > 8) {
4570 u64 lookup = bits[0].start + bits[0].size;
4571 struct cache_extent *next;
4572 next = search_cache_extent(pending, lookup);
4574 if (next->start - lookup > 32768)
4576 bits[ret].start = next->start;
4577 bits[ret].size = next->size;
4578 lookup = next->start + next->size;
4582 next = next_cache_extent(next);
4590 static void free_chunk_record(struct cache_extent *cache)
4592 struct chunk_record *rec;
4594 rec = container_of(cache, struct chunk_record, cache);
4595 list_del_init(&rec->list);
4596 list_del_init(&rec->dextents);
4600 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4602 cache_tree_free_extents(chunk_cache, free_chunk_record);
4605 static void free_device_record(struct rb_node *node)
4607 struct device_record *rec;
4609 rec = container_of(node, struct device_record, node);
4613 FREE_RB_BASED_TREE(device_cache, free_device_record);
4615 int insert_block_group_record(struct block_group_tree *tree,
4616 struct block_group_record *bg_rec)
4620 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4624 list_add_tail(&bg_rec->list, &tree->block_groups);
4628 static void free_block_group_record(struct cache_extent *cache)
4630 struct block_group_record *rec;
4632 rec = container_of(cache, struct block_group_record, cache);
4633 list_del_init(&rec->list);
4637 void free_block_group_tree(struct block_group_tree *tree)
4639 cache_tree_free_extents(&tree->tree, free_block_group_record);
4642 int insert_device_extent_record(struct device_extent_tree *tree,
4643 struct device_extent_record *de_rec)
4648 * Device extent is a bit different from the other extents, because
4649 * the extents which belong to the different devices may have the
4650 * same start and size, so we need use the special extent cache
4651 * search/insert functions.
4653 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4657 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4658 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4662 static void free_device_extent_record(struct cache_extent *cache)
4664 struct device_extent_record *rec;
4666 rec = container_of(cache, struct device_extent_record, cache);
4667 if (!list_empty(&rec->chunk_list))
4668 list_del_init(&rec->chunk_list);
4669 if (!list_empty(&rec->device_list))
4670 list_del_init(&rec->device_list);
4674 void free_device_extent_tree(struct device_extent_tree *tree)
4676 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4679 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4680 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4681 struct extent_buffer *leaf, int slot)
4683 struct btrfs_extent_ref_v0 *ref0;
4684 struct btrfs_key key;
4686 btrfs_item_key_to_cpu(leaf, &key, slot);
4687 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4688 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4689 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4691 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4692 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4698 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4699 struct btrfs_key *key,
4702 struct btrfs_chunk *ptr;
4703 struct chunk_record *rec;
4706 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4707 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4709 rec = malloc(btrfs_chunk_record_size(num_stripes));
4711 fprintf(stderr, "memory allocation failed\n");
4715 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4717 INIT_LIST_HEAD(&rec->list);
4718 INIT_LIST_HEAD(&rec->dextents);
4721 rec->cache.start = key->offset;
4722 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4724 rec->generation = btrfs_header_generation(leaf);
4726 rec->objectid = key->objectid;
4727 rec->type = key->type;
4728 rec->offset = key->offset;
4730 rec->length = rec->cache.size;
4731 rec->owner = btrfs_chunk_owner(leaf, ptr);
4732 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4733 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4734 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4735 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4736 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4737 rec->num_stripes = num_stripes;
4738 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4740 for (i = 0; i < rec->num_stripes; ++i) {
4741 rec->stripes[i].devid =
4742 btrfs_stripe_devid_nr(leaf, ptr, i);
4743 rec->stripes[i].offset =
4744 btrfs_stripe_offset_nr(leaf, ptr, i);
4745 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4746 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4753 static int process_chunk_item(struct cache_tree *chunk_cache,
4754 struct btrfs_key *key, struct extent_buffer *eb,
4757 struct chunk_record *rec;
4760 rec = btrfs_new_chunk_record(eb, key, slot);
4761 ret = insert_cache_extent(chunk_cache, &rec->cache);
4763 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4764 rec->offset, rec->length);
4771 static int process_device_item(struct rb_root *dev_cache,
4772 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4774 struct btrfs_dev_item *ptr;
4775 struct device_record *rec;
4778 ptr = btrfs_item_ptr(eb,
4779 slot, struct btrfs_dev_item);
4781 rec = malloc(sizeof(*rec));
4783 fprintf(stderr, "memory allocation failed\n");
4787 rec->devid = key->offset;
4788 rec->generation = btrfs_header_generation(eb);
4790 rec->objectid = key->objectid;
4791 rec->type = key->type;
4792 rec->offset = key->offset;
4794 rec->devid = btrfs_device_id(eb, ptr);
4795 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4796 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4798 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4800 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4807 struct block_group_record *
4808 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4811 struct btrfs_block_group_item *ptr;
4812 struct block_group_record *rec;
4814 rec = malloc(sizeof(*rec));
4816 fprintf(stderr, "memory allocation failed\n");
4819 memset(rec, 0, sizeof(*rec));
4821 rec->cache.start = key->objectid;
4822 rec->cache.size = key->offset;
4824 rec->generation = btrfs_header_generation(leaf);
4826 rec->objectid = key->objectid;
4827 rec->type = key->type;
4828 rec->offset = key->offset;
4830 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4831 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4833 INIT_LIST_HEAD(&rec->list);
4838 static int process_block_group_item(struct block_group_tree *block_group_cache,
4839 struct btrfs_key *key,
4840 struct extent_buffer *eb, int slot)
4842 struct block_group_record *rec;
4845 rec = btrfs_new_block_group_record(eb, key, slot);
4846 ret = insert_block_group_record(block_group_cache, rec);
4848 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4849 rec->objectid, rec->offset);
4856 struct device_extent_record *
4857 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4858 struct btrfs_key *key, int slot)
4860 struct device_extent_record *rec;
4861 struct btrfs_dev_extent *ptr;
4863 rec = malloc(sizeof(*rec));
4865 fprintf(stderr, "memory allocation failed\n");
4868 memset(rec, 0, sizeof(*rec));
4870 rec->cache.objectid = key->objectid;
4871 rec->cache.start = key->offset;
4873 rec->generation = btrfs_header_generation(leaf);
4875 rec->objectid = key->objectid;
4876 rec->type = key->type;
4877 rec->offset = key->offset;
4879 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4880 rec->chunk_objecteid =
4881 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4883 btrfs_dev_extent_chunk_offset(leaf, ptr);
4884 rec->length = btrfs_dev_extent_length(leaf, ptr);
4885 rec->cache.size = rec->length;
4887 INIT_LIST_HEAD(&rec->chunk_list);
4888 INIT_LIST_HEAD(&rec->device_list);
4894 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4895 struct btrfs_key *key, struct extent_buffer *eb,
4898 struct device_extent_record *rec;
4901 rec = btrfs_new_device_extent_record(eb, key, slot);
4902 ret = insert_device_extent_record(dev_extent_cache, rec);
4905 "Device extent[%llu, %llu, %llu] existed.\n",
4906 rec->objectid, rec->offset, rec->length);
4913 static int process_extent_item(struct btrfs_root *root,
4914 struct cache_tree *extent_cache,
4915 struct extent_buffer *eb, int slot)
4917 struct btrfs_extent_item *ei;
4918 struct btrfs_extent_inline_ref *iref;
4919 struct btrfs_extent_data_ref *dref;
4920 struct btrfs_shared_data_ref *sref;
4921 struct btrfs_key key;
4925 u32 item_size = btrfs_item_size_nr(eb, slot);
4931 btrfs_item_key_to_cpu(eb, &key, slot);
4933 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4935 num_bytes = root->leafsize;
4937 num_bytes = key.offset;
4940 if (item_size < sizeof(*ei)) {
4941 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4942 struct btrfs_extent_item_v0 *ei0;
4943 BUG_ON(item_size != sizeof(*ei0));
4944 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4945 refs = btrfs_extent_refs_v0(eb, ei0);
4949 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4950 num_bytes, refs, 0, 0, 0, metadata, 1,
4954 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4955 refs = btrfs_extent_refs(eb, ei);
4957 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
4958 refs, 0, 0, 0, metadata, 1, num_bytes);
4960 ptr = (unsigned long)(ei + 1);
4961 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
4962 key.type == BTRFS_EXTENT_ITEM_KEY)
4963 ptr += sizeof(struct btrfs_tree_block_info);
4965 end = (unsigned long)ei + item_size;
4967 iref = (struct btrfs_extent_inline_ref *)ptr;
4968 type = btrfs_extent_inline_ref_type(eb, iref);
4969 offset = btrfs_extent_inline_ref_offset(eb, iref);
4971 case BTRFS_TREE_BLOCK_REF_KEY:
4972 add_tree_backref(extent_cache, key.objectid,
4975 case BTRFS_SHARED_BLOCK_REF_KEY:
4976 add_tree_backref(extent_cache, key.objectid,
4979 case BTRFS_EXTENT_DATA_REF_KEY:
4980 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
4981 add_data_backref(extent_cache, key.objectid, 0,
4982 btrfs_extent_data_ref_root(eb, dref),
4983 btrfs_extent_data_ref_objectid(eb,
4985 btrfs_extent_data_ref_offset(eb, dref),
4986 btrfs_extent_data_ref_count(eb, dref),
4989 case BTRFS_SHARED_DATA_REF_KEY:
4990 sref = (struct btrfs_shared_data_ref *)(iref + 1);
4991 add_data_backref(extent_cache, key.objectid, offset,
4993 btrfs_shared_data_ref_count(eb, sref),
4997 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
4998 key.objectid, key.type, num_bytes);
5001 ptr += btrfs_extent_inline_ref_size(type);
5008 static int check_cache_range(struct btrfs_root *root,
5009 struct btrfs_block_group_cache *cache,
5010 u64 offset, u64 bytes)
5012 struct btrfs_free_space *entry;
5018 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5019 bytenr = btrfs_sb_offset(i);
5020 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5021 cache->key.objectid, bytenr, 0,
5022 &logical, &nr, &stripe_len);
5027 if (logical[nr] + stripe_len <= offset)
5029 if (offset + bytes <= logical[nr])
5031 if (logical[nr] == offset) {
5032 if (stripe_len >= bytes) {
5036 bytes -= stripe_len;
5037 offset += stripe_len;
5038 } else if (logical[nr] < offset) {
5039 if (logical[nr] + stripe_len >=
5044 bytes = (offset + bytes) -
5045 (logical[nr] + stripe_len);
5046 offset = logical[nr] + stripe_len;
5049 * Could be tricky, the super may land in the
5050 * middle of the area we're checking. First
5051 * check the easiest case, it's at the end.
5053 if (logical[nr] + stripe_len >=
5055 bytes = logical[nr] - offset;
5059 /* Check the left side */
5060 ret = check_cache_range(root, cache,
5062 logical[nr] - offset);
5068 /* Now we continue with the right side */
5069 bytes = (offset + bytes) -
5070 (logical[nr] + stripe_len);
5071 offset = logical[nr] + stripe_len;
5078 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5080 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5081 offset, offset+bytes);
5085 if (entry->offset != offset) {
5086 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5091 if (entry->bytes != bytes) {
5092 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5093 bytes, entry->bytes, offset);
5097 unlink_free_space(cache->free_space_ctl, entry);
5102 static int verify_space_cache(struct btrfs_root *root,
5103 struct btrfs_block_group_cache *cache)
5105 struct btrfs_path *path;
5106 struct extent_buffer *leaf;
5107 struct btrfs_key key;
5111 path = btrfs_alloc_path();
5115 root = root->fs_info->extent_root;
5117 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5119 key.objectid = last;
5121 key.type = BTRFS_EXTENT_ITEM_KEY;
5123 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5128 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5129 ret = btrfs_next_leaf(root, path);
5137 leaf = path->nodes[0];
5138 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5139 if (key.objectid >= cache->key.offset + cache->key.objectid)
5141 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5142 key.type != BTRFS_METADATA_ITEM_KEY) {
5147 if (last == key.objectid) {
5148 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5149 last = key.objectid + key.offset;
5151 last = key.objectid + root->leafsize;
5156 ret = check_cache_range(root, cache, last,
5157 key.objectid - last);
5160 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5161 last = key.objectid + key.offset;
5163 last = key.objectid + root->leafsize;
5167 if (last < cache->key.objectid + cache->key.offset)
5168 ret = check_cache_range(root, cache, last,
5169 cache->key.objectid +
5170 cache->key.offset - last);
5173 btrfs_free_path(path);
5176 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5177 fprintf(stderr, "There are still entries left in the space "
5185 static int check_space_cache(struct btrfs_root *root)
5187 struct btrfs_block_group_cache *cache;
5188 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5192 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5193 btrfs_super_generation(root->fs_info->super_copy) !=
5194 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5195 printf("cache and super generation don't match, space cache "
5196 "will be invalidated\n");
5201 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5205 start = cache->key.objectid + cache->key.offset;
5206 if (!cache->free_space_ctl) {
5207 if (btrfs_init_free_space_ctl(cache,
5208 root->sectorsize)) {
5213 btrfs_remove_free_space_cache(cache);
5216 ret = load_free_space_cache(root->fs_info, cache);
5220 ret = verify_space_cache(root, cache);
5222 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5223 cache->key.objectid);
5228 return error ? -EINVAL : 0;
5231 static int read_extent_data(struct btrfs_root *root, char *data,
5232 u64 logical, u64 *len, int mirror)
5235 struct btrfs_multi_bio *multi = NULL;
5236 struct btrfs_fs_info *info = root->fs_info;
5237 struct btrfs_device *device;
5241 ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
5242 &multi, mirror, NULL);
5244 fprintf(stderr, "Couldn't map the block %llu\n",
5248 device = multi->stripes[0].dev;
5250 if (device->fd == 0)
5255 ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
5265 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5266 u64 num_bytes, unsigned long leaf_offset,
5267 struct extent_buffer *eb) {
5270 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5272 unsigned long csum_offset;
5276 u64 data_checked = 0;
5282 if (num_bytes % root->sectorsize)
5285 data = malloc(num_bytes);
5289 while (offset < num_bytes) {
5292 read_len = num_bytes - offset;
5293 /* read as much space once a time */
5294 ret = read_extent_data(root, data + offset,
5295 bytenr + offset, &read_len, mirror);
5299 /* verify every 4k data's checksum */
5300 while (data_checked < read_len) {
5302 tmp = offset + data_checked;
5304 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5305 csum, root->sectorsize);
5306 btrfs_csum_final(csum, (char *)&csum);
5308 csum_offset = leaf_offset +
5309 tmp / root->sectorsize * csum_size;
5310 read_extent_buffer(eb, (char *)&csum_expected,
5311 csum_offset, csum_size);
5312 /* try another mirror */
5313 if (csum != csum_expected) {
5314 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5315 mirror, bytenr + tmp,
5316 csum, csum_expected);
5317 num_copies = btrfs_num_copies(
5318 &root->fs_info->mapping_tree,
5320 if (mirror < num_copies - 1) {
5325 data_checked += root->sectorsize;
5334 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5337 struct btrfs_path *path;
5338 struct extent_buffer *leaf;
5339 struct btrfs_key key;
5342 path = btrfs_alloc_path();
5344 fprintf(stderr, "Error allocing path\n");
5348 key.objectid = bytenr;
5349 key.type = BTRFS_EXTENT_ITEM_KEY;
5350 key.offset = (u64)-1;
5353 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5356 fprintf(stderr, "Error looking up extent record %d\n", ret);
5357 btrfs_free_path(path);
5360 if (path->slots[0] > 0) {
5363 ret = btrfs_prev_leaf(root, path);
5366 } else if (ret > 0) {
5373 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5376 * Block group items come before extent items if they have the same
5377 * bytenr, so walk back one more just in case. Dear future traveler,
5378 * first congrats on mastering time travel. Now if it's not too much
5379 * trouble could you go back to 2006 and tell Chris to make the
5380 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5381 * EXTENT_ITEM_KEY please?
5383 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5384 if (path->slots[0] > 0) {
5387 ret = btrfs_prev_leaf(root, path);
5390 } else if (ret > 0) {
5395 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5399 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5400 ret = btrfs_next_leaf(root, path);
5402 fprintf(stderr, "Error going to next leaf "
5404 btrfs_free_path(path);
5410 leaf = path->nodes[0];
5411 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5412 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5416 if (key.objectid + key.offset < bytenr) {
5420 if (key.objectid > bytenr + num_bytes)
5423 if (key.objectid == bytenr) {
5424 if (key.offset >= num_bytes) {
5428 num_bytes -= key.offset;
5429 bytenr += key.offset;
5430 } else if (key.objectid < bytenr) {
5431 if (key.objectid + key.offset >= bytenr + num_bytes) {
5435 num_bytes = (bytenr + num_bytes) -
5436 (key.objectid + key.offset);
5437 bytenr = key.objectid + key.offset;
5439 if (key.objectid + key.offset < bytenr + num_bytes) {
5440 u64 new_start = key.objectid + key.offset;
5441 u64 new_bytes = bytenr + num_bytes - new_start;
5444 * Weird case, the extent is in the middle of
5445 * our range, we'll have to search one side
5446 * and then the other. Not sure if this happens
5447 * in real life, but no harm in coding it up
5448 * anyway just in case.
5450 btrfs_release_path(path);
5451 ret = check_extent_exists(root, new_start,
5454 fprintf(stderr, "Right section didn't "
5458 num_bytes = key.objectid - bytenr;
5461 num_bytes = key.objectid - bytenr;
5468 if (num_bytes && !ret) {
5469 fprintf(stderr, "There are no extents for csum range "
5470 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5474 btrfs_free_path(path);
5478 static int check_csums(struct btrfs_root *root)
5480 struct btrfs_path *path;
5481 struct extent_buffer *leaf;
5482 struct btrfs_key key;
5483 u64 offset = 0, num_bytes = 0;
5484 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5488 unsigned long leaf_offset;
5490 root = root->fs_info->csum_root;
5491 if (!extent_buffer_uptodate(root->node)) {
5492 fprintf(stderr, "No valid csum tree found\n");
5496 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5497 key.type = BTRFS_EXTENT_CSUM_KEY;
5500 path = btrfs_alloc_path();
5504 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5506 fprintf(stderr, "Error searching csum tree %d\n", ret);
5507 btrfs_free_path(path);
5511 if (ret > 0 && path->slots[0])
5516 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5517 ret = btrfs_next_leaf(root, path);
5519 fprintf(stderr, "Error going to next leaf "
5526 leaf = path->nodes[0];
5528 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5529 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5534 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5535 csum_size) * root->sectorsize;
5536 if (!check_data_csum)
5537 goto skip_csum_check;
5538 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5539 ret = check_extent_csums(root, key.offset, data_len,
5545 offset = key.offset;
5546 } else if (key.offset != offset + num_bytes) {
5547 ret = check_extent_exists(root, offset, num_bytes);
5549 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5550 "there is no extent record\n",
5551 offset, offset+num_bytes);
5554 offset = key.offset;
5557 num_bytes += data_len;
5561 btrfs_free_path(path);
5565 static int is_dropped_key(struct btrfs_key *key,
5566 struct btrfs_key *drop_key) {
5567 if (key->objectid < drop_key->objectid)
5569 else if (key->objectid == drop_key->objectid) {
5570 if (key->type < drop_key->type)
5572 else if (key->type == drop_key->type) {
5573 if (key->offset < drop_key->offset)
5581 * Here are the rules for FULL_BACKREF.
5583 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5584 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5586 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5587 * if it happened after the relocation occurred since we'll have dropped the
5588 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5589 * have no real way to know for sure.
5591 * We process the blocks one root at a time, and we start from the lowest root
5592 * objectid and go to the highest. So we can just lookup the owner backref for
5593 * the record and if we don't find it then we know it doesn't exist and we have
5596 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5597 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5598 * be set or not and then we can check later once we've gathered all the refs.
5600 static int calc_extent_flag(struct btrfs_root *root,
5601 struct cache_tree *extent_cache,
5602 struct extent_buffer *buf,
5603 struct root_item_record *ri,
5606 struct extent_record *rec;
5607 struct cache_extent *cache;
5608 struct tree_backref *tback;
5611 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5612 /* we have added this extent before */
5614 rec = container_of(cache, struct extent_record, cache);
5617 * Except file/reloc tree, we can not have
5620 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5625 if (buf->start == ri->bytenr)
5628 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5631 owner = btrfs_header_owner(buf);
5632 if (owner == ri->objectid)
5635 tback = find_tree_backref(rec, 0, owner);
5640 if (rec->flag_block_full_backref != -1 &&
5641 rec->flag_block_full_backref != 0)
5642 rec->bad_full_backref = 1;
5645 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5646 if (rec->flag_block_full_backref != -1 &&
5647 rec->flag_block_full_backref != 1)
5648 rec->bad_full_backref = 1;
5652 static int run_next_block(struct btrfs_root *root,
5653 struct block_info *bits,
5656 struct cache_tree *pending,
5657 struct cache_tree *seen,
5658 struct cache_tree *reada,
5659 struct cache_tree *nodes,
5660 struct cache_tree *extent_cache,
5661 struct cache_tree *chunk_cache,
5662 struct rb_root *dev_cache,
5663 struct block_group_tree *block_group_cache,
5664 struct device_extent_tree *dev_extent_cache,
5665 struct root_item_record *ri)
5667 struct extent_buffer *buf;
5668 struct extent_record *rec = NULL;
5679 struct btrfs_key key;
5680 struct cache_extent *cache;
5683 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5684 bits_nr, &reada_bits);
5689 for(i = 0; i < nritems; i++) {
5690 ret = add_cache_extent(reada, bits[i].start,
5695 /* fixme, get the parent transid */
5696 readahead_tree_block(root, bits[i].start,
5700 *last = bits[0].start;
5701 bytenr = bits[0].start;
5702 size = bits[0].size;
5704 cache = lookup_cache_extent(pending, bytenr, size);
5706 remove_cache_extent(pending, cache);
5709 cache = lookup_cache_extent(reada, bytenr, size);
5711 remove_cache_extent(reada, cache);
5714 cache = lookup_cache_extent(nodes, bytenr, size);
5716 remove_cache_extent(nodes, cache);
5719 cache = lookup_cache_extent(extent_cache, bytenr, size);
5721 rec = container_of(cache, struct extent_record, cache);
5722 gen = rec->parent_generation;
5725 /* fixme, get the real parent transid */
5726 buf = read_tree_block(root, bytenr, size, gen);
5727 if (!extent_buffer_uptodate(buf)) {
5728 record_bad_block_io(root->fs_info,
5729 extent_cache, bytenr, size);
5733 nritems = btrfs_header_nritems(buf);
5736 if (!init_extent_tree) {
5737 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5738 btrfs_header_level(buf), 1, NULL,
5741 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5743 fprintf(stderr, "Couldn't calc extent flags\n");
5744 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5749 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5751 fprintf(stderr, "Couldn't calc extent flags\n");
5752 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5756 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5758 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5759 ri->objectid == btrfs_header_owner(buf)) {
5761 * Ok we got to this block from it's original owner and
5762 * we have FULL_BACKREF set. Relocation can leave
5763 * converted blocks over so this is altogether possible,
5764 * however it's not possible if the generation > the
5765 * last snapshot, so check for this case.
5767 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5768 btrfs_header_generation(buf) > ri->last_snapshot) {
5769 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5770 rec->bad_full_backref = 1;
5775 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5776 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5777 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5778 rec->bad_full_backref = 1;
5782 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5783 rec->flag_block_full_backref = 1;
5787 rec->flag_block_full_backref = 0;
5789 owner = btrfs_header_owner(buf);
5792 ret = check_block(root, extent_cache, buf, flags);
5796 if (btrfs_is_leaf(buf)) {
5797 btree_space_waste += btrfs_leaf_free_space(root, buf);
5798 for (i = 0; i < nritems; i++) {
5799 struct btrfs_file_extent_item *fi;
5800 btrfs_item_key_to_cpu(buf, &key, i);
5801 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5802 process_extent_item(root, extent_cache, buf,
5806 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5807 process_extent_item(root, extent_cache, buf,
5811 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5813 btrfs_item_size_nr(buf, i);
5816 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5817 process_chunk_item(chunk_cache, &key, buf, i);
5820 if (key.type == BTRFS_DEV_ITEM_KEY) {
5821 process_device_item(dev_cache, &key, buf, i);
5824 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5825 process_block_group_item(block_group_cache,
5829 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5830 process_device_extent_item(dev_extent_cache,
5835 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5836 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5837 process_extent_ref_v0(extent_cache, buf, i);
5844 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5845 add_tree_backref(extent_cache, key.objectid, 0,
5849 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5850 add_tree_backref(extent_cache, key.objectid,
5854 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5855 struct btrfs_extent_data_ref *ref;
5856 ref = btrfs_item_ptr(buf, i,
5857 struct btrfs_extent_data_ref);
5858 add_data_backref(extent_cache,
5860 btrfs_extent_data_ref_root(buf, ref),
5861 btrfs_extent_data_ref_objectid(buf,
5863 btrfs_extent_data_ref_offset(buf, ref),
5864 btrfs_extent_data_ref_count(buf, ref),
5865 0, root->sectorsize);
5868 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5869 struct btrfs_shared_data_ref *ref;
5870 ref = btrfs_item_ptr(buf, i,
5871 struct btrfs_shared_data_ref);
5872 add_data_backref(extent_cache,
5873 key.objectid, key.offset, 0, 0, 0,
5874 btrfs_shared_data_ref_count(buf, ref),
5875 0, root->sectorsize);
5878 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5879 struct bad_item *bad;
5881 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5885 bad = malloc(sizeof(struct bad_item));
5888 INIT_LIST_HEAD(&bad->list);
5889 memcpy(&bad->key, &key,
5890 sizeof(struct btrfs_key));
5891 bad->root_id = owner;
5892 list_add_tail(&bad->list, &delete_items);
5895 if (key.type != BTRFS_EXTENT_DATA_KEY)
5897 fi = btrfs_item_ptr(buf, i,
5898 struct btrfs_file_extent_item);
5899 if (btrfs_file_extent_type(buf, fi) ==
5900 BTRFS_FILE_EXTENT_INLINE)
5902 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5905 data_bytes_allocated +=
5906 btrfs_file_extent_disk_num_bytes(buf, fi);
5907 if (data_bytes_allocated < root->sectorsize) {
5910 data_bytes_referenced +=
5911 btrfs_file_extent_num_bytes(buf, fi);
5912 add_data_backref(extent_cache,
5913 btrfs_file_extent_disk_bytenr(buf, fi),
5914 parent, owner, key.objectid, key.offset -
5915 btrfs_file_extent_offset(buf, fi), 1, 1,
5916 btrfs_file_extent_disk_num_bytes(buf, fi));
5920 struct btrfs_key first_key;
5922 first_key.objectid = 0;
5925 btrfs_item_key_to_cpu(buf, &first_key, 0);
5926 level = btrfs_header_level(buf);
5927 for (i = 0; i < nritems; i++) {
5928 ptr = btrfs_node_blockptr(buf, i);
5929 size = btrfs_level_size(root, level - 1);
5930 btrfs_node_key_to_cpu(buf, &key, i);
5932 if ((level == ri->drop_level)
5933 && is_dropped_key(&key, &ri->drop_key)) {
5937 ret = add_extent_rec(extent_cache, &key,
5938 btrfs_node_ptr_generation(buf, i),
5939 ptr, size, 0, 0, 1, 0, 1, 0,
5943 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5946 add_pending(nodes, seen, ptr, size);
5948 add_pending(pending, seen, ptr, size);
5951 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5952 nritems) * sizeof(struct btrfs_key_ptr);
5954 total_btree_bytes += buf->len;
5955 if (fs_root_objectid(btrfs_header_owner(buf)))
5956 total_fs_tree_bytes += buf->len;
5957 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5958 total_extent_tree_bytes += buf->len;
5959 if (!found_old_backref &&
5960 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5961 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5962 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5963 found_old_backref = 1;
5965 free_extent_buffer(buf);
5969 static int add_root_to_pending(struct extent_buffer *buf,
5970 struct cache_tree *extent_cache,
5971 struct cache_tree *pending,
5972 struct cache_tree *seen,
5973 struct cache_tree *nodes,
5976 if (btrfs_header_level(buf) > 0)
5977 add_pending(nodes, seen, buf->start, buf->len);
5979 add_pending(pending, seen, buf->start, buf->len);
5980 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5981 0, 1, 1, 0, 1, 0, buf->len);
5983 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5984 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5985 add_tree_backref(extent_cache, buf->start, buf->start,
5988 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
5992 /* as we fix the tree, we might be deleting blocks that
5993 * we're tracking for repair. This hook makes sure we
5994 * remove any backrefs for blocks as we are fixing them.
5996 static int free_extent_hook(struct btrfs_trans_handle *trans,
5997 struct btrfs_root *root,
5998 u64 bytenr, u64 num_bytes, u64 parent,
5999 u64 root_objectid, u64 owner, u64 offset,
6002 struct extent_record *rec;
6003 struct cache_extent *cache;
6005 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6007 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6008 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6012 rec = container_of(cache, struct extent_record, cache);
6014 struct data_backref *back;
6015 back = find_data_backref(rec, parent, root_objectid, owner,
6016 offset, 1, bytenr, num_bytes);
6019 if (back->node.found_ref) {
6020 back->found_ref -= refs_to_drop;
6022 rec->refs -= refs_to_drop;
6024 if (back->node.found_extent_tree) {
6025 back->num_refs -= refs_to_drop;
6026 if (rec->extent_item_refs)
6027 rec->extent_item_refs -= refs_to_drop;
6029 if (back->found_ref == 0)
6030 back->node.found_ref = 0;
6031 if (back->num_refs == 0)
6032 back->node.found_extent_tree = 0;
6034 if (!back->node.found_extent_tree && back->node.found_ref) {
6035 list_del(&back->node.list);
6039 struct tree_backref *back;
6040 back = find_tree_backref(rec, parent, root_objectid);
6043 if (back->node.found_ref) {
6046 back->node.found_ref = 0;
6048 if (back->node.found_extent_tree) {
6049 if (rec->extent_item_refs)
6050 rec->extent_item_refs--;
6051 back->node.found_extent_tree = 0;
6053 if (!back->node.found_extent_tree && back->node.found_ref) {
6054 list_del(&back->node.list);
6058 maybe_free_extent_rec(extent_cache, rec);
6063 static int delete_extent_records(struct btrfs_trans_handle *trans,
6064 struct btrfs_root *root,
6065 struct btrfs_path *path,
6066 u64 bytenr, u64 new_len)
6068 struct btrfs_key key;
6069 struct btrfs_key found_key;
6070 struct extent_buffer *leaf;
6075 key.objectid = bytenr;
6077 key.offset = (u64)-1;
6080 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6087 if (path->slots[0] == 0)
6093 leaf = path->nodes[0];
6094 slot = path->slots[0];
6096 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6097 if (found_key.objectid != bytenr)
6100 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6101 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6102 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6103 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6104 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6105 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6106 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6107 btrfs_release_path(path);
6108 if (found_key.type == 0) {
6109 if (found_key.offset == 0)
6111 key.offset = found_key.offset - 1;
6112 key.type = found_key.type;
6114 key.type = found_key.type - 1;
6115 key.offset = (u64)-1;
6119 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6120 found_key.objectid, found_key.type, found_key.offset);
6122 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6125 btrfs_release_path(path);
6127 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6128 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6129 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6130 found_key.offset : root->leafsize;
6132 ret = btrfs_update_block_group(trans, root, bytenr,
6139 btrfs_release_path(path);
6144 * for a single backref, this will allocate a new extent
6145 * and add the backref to it.
6147 static int record_extent(struct btrfs_trans_handle *trans,
6148 struct btrfs_fs_info *info,
6149 struct btrfs_path *path,
6150 struct extent_record *rec,
6151 struct extent_backref *back,
6152 int allocated, u64 flags)
6155 struct btrfs_root *extent_root = info->extent_root;
6156 struct extent_buffer *leaf;
6157 struct btrfs_key ins_key;
6158 struct btrfs_extent_item *ei;
6159 struct tree_backref *tback;
6160 struct data_backref *dback;
6161 struct btrfs_tree_block_info *bi;
6164 rec->max_size = max_t(u64, rec->max_size,
6165 info->extent_root->leafsize);
6168 u32 item_size = sizeof(*ei);
6171 item_size += sizeof(*bi);
6173 ins_key.objectid = rec->start;
6174 ins_key.offset = rec->max_size;
6175 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6177 ret = btrfs_insert_empty_item(trans, extent_root, path,
6178 &ins_key, item_size);
6182 leaf = path->nodes[0];
6183 ei = btrfs_item_ptr(leaf, path->slots[0],
6184 struct btrfs_extent_item);
6186 btrfs_set_extent_refs(leaf, ei, 0);
6187 btrfs_set_extent_generation(leaf, ei, rec->generation);
6189 if (back->is_data) {
6190 btrfs_set_extent_flags(leaf, ei,
6191 BTRFS_EXTENT_FLAG_DATA);
6193 struct btrfs_disk_key copy_key;;
6195 tback = (struct tree_backref *)back;
6196 bi = (struct btrfs_tree_block_info *)(ei + 1);
6197 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6200 btrfs_set_disk_key_objectid(©_key,
6201 rec->info_objectid);
6202 btrfs_set_disk_key_type(©_key, 0);
6203 btrfs_set_disk_key_offset(©_key, 0);
6205 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6206 btrfs_set_tree_block_key(leaf, bi, ©_key);
6208 btrfs_set_extent_flags(leaf, ei,
6209 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6212 btrfs_mark_buffer_dirty(leaf);
6213 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6214 rec->max_size, 1, 0);
6217 btrfs_release_path(path);
6220 if (back->is_data) {
6224 dback = (struct data_backref *)back;
6225 if (back->full_backref)
6226 parent = dback->parent;
6230 for (i = 0; i < dback->found_ref; i++) {
6231 /* if parent != 0, we're doing a full backref
6232 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6233 * just makes the backref allocator create a data
6236 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6237 rec->start, rec->max_size,
6241 BTRFS_FIRST_FREE_OBJECTID :
6247 fprintf(stderr, "adding new data backref"
6248 " on %llu %s %llu owner %llu"
6249 " offset %llu found %d\n",
6250 (unsigned long long)rec->start,
6251 back->full_backref ?
6253 back->full_backref ?
6254 (unsigned long long)parent :
6255 (unsigned long long)dback->root,
6256 (unsigned long long)dback->owner,
6257 (unsigned long long)dback->offset,
6262 tback = (struct tree_backref *)back;
6263 if (back->full_backref)
6264 parent = tback->parent;
6268 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6269 rec->start, rec->max_size,
6270 parent, tback->root, 0, 0);
6271 fprintf(stderr, "adding new tree backref on "
6272 "start %llu len %llu parent %llu root %llu\n",
6273 rec->start, rec->max_size, parent, tback->root);
6278 btrfs_release_path(path);
6282 struct extent_entry {
6287 struct list_head list;
6290 static struct extent_entry *find_entry(struct list_head *entries,
6291 u64 bytenr, u64 bytes)
6293 struct extent_entry *entry = NULL;
6295 list_for_each_entry(entry, entries, list) {
6296 if (entry->bytenr == bytenr && entry->bytes == bytes)
6303 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6305 struct extent_entry *entry, *best = NULL, *prev = NULL;
6307 list_for_each_entry(entry, entries, list) {
6314 * If there are as many broken entries as entries then we know
6315 * not to trust this particular entry.
6317 if (entry->broken == entry->count)
6321 * If our current entry == best then we can't be sure our best
6322 * is really the best, so we need to keep searching.
6324 if (best && best->count == entry->count) {
6330 /* Prev == entry, not good enough, have to keep searching */
6331 if (!prev->broken && prev->count == entry->count)
6335 best = (prev->count > entry->count) ? prev : entry;
6336 else if (best->count < entry->count)
6344 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6345 struct data_backref *dback, struct extent_entry *entry)
6347 struct btrfs_trans_handle *trans;
6348 struct btrfs_root *root;
6349 struct btrfs_file_extent_item *fi;
6350 struct extent_buffer *leaf;
6351 struct btrfs_key key;
6355 key.objectid = dback->root;
6356 key.type = BTRFS_ROOT_ITEM_KEY;
6357 key.offset = (u64)-1;
6358 root = btrfs_read_fs_root(info, &key);
6360 fprintf(stderr, "Couldn't find root for our ref\n");
6365 * The backref points to the original offset of the extent if it was
6366 * split, so we need to search down to the offset we have and then walk
6367 * forward until we find the backref we're looking for.
6369 key.objectid = dback->owner;
6370 key.type = BTRFS_EXTENT_DATA_KEY;
6371 key.offset = dback->offset;
6372 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6374 fprintf(stderr, "Error looking up ref %d\n", ret);
6379 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6380 ret = btrfs_next_leaf(root, path);
6382 fprintf(stderr, "Couldn't find our ref, next\n");
6386 leaf = path->nodes[0];
6387 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6388 if (key.objectid != dback->owner ||
6389 key.type != BTRFS_EXTENT_DATA_KEY) {
6390 fprintf(stderr, "Couldn't find our ref, search\n");
6393 fi = btrfs_item_ptr(leaf, path->slots[0],
6394 struct btrfs_file_extent_item);
6395 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6396 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6398 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6403 btrfs_release_path(path);
6405 trans = btrfs_start_transaction(root, 1);
6407 return PTR_ERR(trans);
6410 * Ok we have the key of the file extent we want to fix, now we can cow
6411 * down to the thing and fix it.
6413 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6415 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6416 key.objectid, key.type, key.offset, ret);
6420 fprintf(stderr, "Well that's odd, we just found this key "
6421 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6426 leaf = path->nodes[0];
6427 fi = btrfs_item_ptr(leaf, path->slots[0],
6428 struct btrfs_file_extent_item);
6430 if (btrfs_file_extent_compression(leaf, fi) &&
6431 dback->disk_bytenr != entry->bytenr) {
6432 fprintf(stderr, "Ref doesn't match the record start and is "
6433 "compressed, please take a btrfs-image of this file "
6434 "system and send it to a btrfs developer so they can "
6435 "complete this functionality for bytenr %Lu\n",
6436 dback->disk_bytenr);
6441 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6442 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6443 } else if (dback->disk_bytenr > entry->bytenr) {
6444 u64 off_diff, offset;
6446 off_diff = dback->disk_bytenr - entry->bytenr;
6447 offset = btrfs_file_extent_offset(leaf, fi);
6448 if (dback->disk_bytenr + offset +
6449 btrfs_file_extent_num_bytes(leaf, fi) >
6450 entry->bytenr + entry->bytes) {
6451 fprintf(stderr, "Ref is past the entry end, please "
6452 "take a btrfs-image of this file system and "
6453 "send it to a btrfs developer, ref %Lu\n",
6454 dback->disk_bytenr);
6459 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6460 btrfs_set_file_extent_offset(leaf, fi, offset);
6461 } else if (dback->disk_bytenr < entry->bytenr) {
6464 offset = btrfs_file_extent_offset(leaf, fi);
6465 if (dback->disk_bytenr + offset < entry->bytenr) {
6466 fprintf(stderr, "Ref is before the entry start, please"
6467 " take a btrfs-image of this file system and "
6468 "send it to a btrfs developer, ref %Lu\n",
6469 dback->disk_bytenr);
6474 offset += dback->disk_bytenr;
6475 offset -= entry->bytenr;
6476 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6477 btrfs_set_file_extent_offset(leaf, fi, offset);
6480 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6483 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6484 * only do this if we aren't using compression, otherwise it's a
6487 if (!btrfs_file_extent_compression(leaf, fi))
6488 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6490 printf("ram bytes may be wrong?\n");
6491 btrfs_mark_buffer_dirty(leaf);
6493 err = btrfs_commit_transaction(trans, root);
6494 btrfs_release_path(path);
6495 return ret ? ret : err;
6498 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6499 struct extent_record *rec)
6501 struct extent_backref *back;
6502 struct data_backref *dback;
6503 struct extent_entry *entry, *best = NULL;
6506 int broken_entries = 0;
6511 * Metadata is easy and the backrefs should always agree on bytenr and
6512 * size, if not we've got bigger issues.
6517 list_for_each_entry(back, &rec->backrefs, list) {
6518 if (back->full_backref || !back->is_data)
6521 dback = (struct data_backref *)back;
6524 * We only pay attention to backrefs that we found a real
6527 if (dback->found_ref == 0)
6531 * For now we only catch when the bytes don't match, not the
6532 * bytenr. We can easily do this at the same time, but I want
6533 * to have a fs image to test on before we just add repair
6534 * functionality willy-nilly so we know we won't screw up the
6538 entry = find_entry(&entries, dback->disk_bytenr,
6541 entry = malloc(sizeof(struct extent_entry));
6546 memset(entry, 0, sizeof(*entry));
6547 entry->bytenr = dback->disk_bytenr;
6548 entry->bytes = dback->bytes;
6549 list_add_tail(&entry->list, &entries);
6554 * If we only have on entry we may think the entries agree when
6555 * in reality they don't so we have to do some extra checking.
6557 if (dback->disk_bytenr != rec->start ||
6558 dback->bytes != rec->nr || back->broken)
6569 /* Yay all the backrefs agree, carry on good sir */
6570 if (nr_entries <= 1 && !mismatch)
6573 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6574 "%Lu\n", rec->start);
6577 * First we want to see if the backrefs can agree amongst themselves who
6578 * is right, so figure out which one of the entries has the highest
6581 best = find_most_right_entry(&entries);
6584 * Ok so we may have an even split between what the backrefs think, so
6585 * this is where we use the extent ref to see what it thinks.
6588 entry = find_entry(&entries, rec->start, rec->nr);
6589 if (!entry && (!broken_entries || !rec->found_rec)) {
6590 fprintf(stderr, "Backrefs don't agree with each other "
6591 "and extent record doesn't agree with anybody,"
6592 " so we can't fix bytenr %Lu bytes %Lu\n",
6593 rec->start, rec->nr);
6596 } else if (!entry) {
6598 * Ok our backrefs were broken, we'll assume this is the
6599 * correct value and add an entry for this range.
6601 entry = malloc(sizeof(struct extent_entry));
6606 memset(entry, 0, sizeof(*entry));
6607 entry->bytenr = rec->start;
6608 entry->bytes = rec->nr;
6609 list_add_tail(&entry->list, &entries);
6613 best = find_most_right_entry(&entries);
6615 fprintf(stderr, "Backrefs and extent record evenly "
6616 "split on who is right, this is going to "
6617 "require user input to fix bytenr %Lu bytes "
6618 "%Lu\n", rec->start, rec->nr);
6625 * I don't think this can happen currently as we'll abort() if we catch
6626 * this case higher up, but in case somebody removes that we still can't
6627 * deal with it properly here yet, so just bail out of that's the case.
6629 if (best->bytenr != rec->start) {
6630 fprintf(stderr, "Extent start and backref starts don't match, "
6631 "please use btrfs-image on this file system and send "
6632 "it to a btrfs developer so they can make fsck fix "
6633 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6634 rec->start, rec->nr);
6640 * Ok great we all agreed on an extent record, let's go find the real
6641 * references and fix up the ones that don't match.
6643 list_for_each_entry(back, &rec->backrefs, list) {
6644 if (back->full_backref || !back->is_data)
6647 dback = (struct data_backref *)back;
6650 * Still ignoring backrefs that don't have a real ref attached
6653 if (dback->found_ref == 0)
6656 if (dback->bytes == best->bytes &&
6657 dback->disk_bytenr == best->bytenr)
6660 ret = repair_ref(info, path, dback, best);
6666 * Ok we messed with the actual refs, which means we need to drop our
6667 * entire cache and go back and rescan. I know this is a huge pain and
6668 * adds a lot of extra work, but it's the only way to be safe. Once all
6669 * the backrefs agree we may not need to do anything to the extent
6674 while (!list_empty(&entries)) {
6675 entry = list_entry(entries.next, struct extent_entry, list);
6676 list_del_init(&entry->list);
6682 static int process_duplicates(struct btrfs_root *root,
6683 struct cache_tree *extent_cache,
6684 struct extent_record *rec)
6686 struct extent_record *good, *tmp;
6687 struct cache_extent *cache;
6691 * If we found a extent record for this extent then return, or if we
6692 * have more than one duplicate we are likely going to need to delete
6695 if (rec->found_rec || rec->num_duplicates > 1)
6698 /* Shouldn't happen but just in case */
6699 BUG_ON(!rec->num_duplicates);
6702 * So this happens if we end up with a backref that doesn't match the
6703 * actual extent entry. So either the backref is bad or the extent
6704 * entry is bad. Either way we want to have the extent_record actually
6705 * reflect what we found in the extent_tree, so we need to take the
6706 * duplicate out and use that as the extent_record since the only way we
6707 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6709 remove_cache_extent(extent_cache, &rec->cache);
6711 good = list_entry(rec->dups.next, struct extent_record, list);
6712 list_del_init(&good->list);
6713 INIT_LIST_HEAD(&good->backrefs);
6714 INIT_LIST_HEAD(&good->dups);
6715 good->cache.start = good->start;
6716 good->cache.size = good->nr;
6717 good->content_checked = 0;
6718 good->owner_ref_checked = 0;
6719 good->num_duplicates = 0;
6720 good->refs = rec->refs;
6721 list_splice_init(&rec->backrefs, &good->backrefs);
6723 cache = lookup_cache_extent(extent_cache, good->start,
6727 tmp = container_of(cache, struct extent_record, cache);
6730 * If we find another overlapping extent and it's found_rec is
6731 * set then it's a duplicate and we need to try and delete
6734 if (tmp->found_rec || tmp->num_duplicates > 0) {
6735 if (list_empty(&good->list))
6736 list_add_tail(&good->list,
6737 &duplicate_extents);
6738 good->num_duplicates += tmp->num_duplicates + 1;
6739 list_splice_init(&tmp->dups, &good->dups);
6740 list_del_init(&tmp->list);
6741 list_add_tail(&tmp->list, &good->dups);
6742 remove_cache_extent(extent_cache, &tmp->cache);
6747 * Ok we have another non extent item backed extent rec, so lets
6748 * just add it to this extent and carry on like we did above.
6750 good->refs += tmp->refs;
6751 list_splice_init(&tmp->backrefs, &good->backrefs);
6752 remove_cache_extent(extent_cache, &tmp->cache);
6755 ret = insert_cache_extent(extent_cache, &good->cache);
6758 return good->num_duplicates ? 0 : 1;
6761 static int delete_duplicate_records(struct btrfs_root *root,
6762 struct extent_record *rec)
6764 struct btrfs_trans_handle *trans;
6765 LIST_HEAD(delete_list);
6766 struct btrfs_path *path;
6767 struct extent_record *tmp, *good, *n;
6770 struct btrfs_key key;
6772 path = btrfs_alloc_path();
6779 /* Find the record that covers all of the duplicates. */
6780 list_for_each_entry(tmp, &rec->dups, list) {
6781 if (good->start < tmp->start)
6783 if (good->nr > tmp->nr)
6786 if (tmp->start + tmp->nr < good->start + good->nr) {
6787 fprintf(stderr, "Ok we have overlapping extents that "
6788 "aren't completely covered by eachother, this "
6789 "is going to require more careful thought. "
6790 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6791 tmp->start, tmp->nr, good->start, good->nr);
6798 list_add_tail(&rec->list, &delete_list);
6800 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6803 list_move_tail(&tmp->list, &delete_list);
6806 root = root->fs_info->extent_root;
6807 trans = btrfs_start_transaction(root, 1);
6808 if (IS_ERR(trans)) {
6809 ret = PTR_ERR(trans);
6813 list_for_each_entry(tmp, &delete_list, list) {
6814 if (tmp->found_rec == 0)
6816 key.objectid = tmp->start;
6817 key.type = BTRFS_EXTENT_ITEM_KEY;
6818 key.offset = tmp->nr;
6820 /* Shouldn't happen but just in case */
6821 if (tmp->metadata) {
6822 fprintf(stderr, "Well this shouldn't happen, extent "
6823 "record overlaps but is metadata? "
6824 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6828 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6834 ret = btrfs_del_item(trans, root, path);
6837 btrfs_release_path(path);
6840 err = btrfs_commit_transaction(trans, root);
6844 while (!list_empty(&delete_list)) {
6845 tmp = list_entry(delete_list.next, struct extent_record, list);
6846 list_del_init(&tmp->list);
6852 while (!list_empty(&rec->dups)) {
6853 tmp = list_entry(rec->dups.next, struct extent_record, list);
6854 list_del_init(&tmp->list);
6858 btrfs_free_path(path);
6860 if (!ret && !nr_del)
6861 rec->num_duplicates = 0;
6863 return ret ? ret : nr_del;
6866 static int find_possible_backrefs(struct btrfs_fs_info *info,
6867 struct btrfs_path *path,
6868 struct cache_tree *extent_cache,
6869 struct extent_record *rec)
6871 struct btrfs_root *root;
6872 struct extent_backref *back;
6873 struct data_backref *dback;
6874 struct cache_extent *cache;
6875 struct btrfs_file_extent_item *fi;
6876 struct btrfs_key key;
6880 list_for_each_entry(back, &rec->backrefs, list) {
6881 /* Don't care about full backrefs (poor unloved backrefs) */
6882 if (back->full_backref || !back->is_data)
6885 dback = (struct data_backref *)back;
6887 /* We found this one, we don't need to do a lookup */
6888 if (dback->found_ref)
6891 key.objectid = dback->root;
6892 key.type = BTRFS_ROOT_ITEM_KEY;
6893 key.offset = (u64)-1;
6895 root = btrfs_read_fs_root(info, &key);
6897 /* No root, definitely a bad ref, skip */
6898 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6900 /* Other err, exit */
6902 return PTR_ERR(root);
6904 key.objectid = dback->owner;
6905 key.type = BTRFS_EXTENT_DATA_KEY;
6906 key.offset = dback->offset;
6907 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6909 btrfs_release_path(path);
6912 /* Didn't find it, we can carry on */
6917 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6918 struct btrfs_file_extent_item);
6919 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6920 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6921 btrfs_release_path(path);
6922 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6924 struct extent_record *tmp;
6925 tmp = container_of(cache, struct extent_record, cache);
6928 * If we found an extent record for the bytenr for this
6929 * particular backref then we can't add it to our
6930 * current extent record. We only want to add backrefs
6931 * that don't have a corresponding extent item in the
6932 * extent tree since they likely belong to this record
6933 * and we need to fix it if it doesn't match bytenrs.
6939 dback->found_ref += 1;
6940 dback->disk_bytenr = bytenr;
6941 dback->bytes = bytes;
6944 * Set this so the verify backref code knows not to trust the
6945 * values in this backref.
6954 * Record orphan data ref into corresponding root.
6956 * Return 0 if the extent item contains data ref and recorded.
6957 * Return 1 if the extent item contains no useful data ref
6958 * On that case, it may contains only shared_dataref or metadata backref
6959 * or the file extent exists(this should be handled by the extent bytenr
6961 * Return <0 if something goes wrong.
6963 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6964 struct extent_record *rec)
6966 struct btrfs_key key;
6967 struct btrfs_root *dest_root;
6968 struct extent_backref *back;
6969 struct data_backref *dback;
6970 struct orphan_data_extent *orphan;
6971 struct btrfs_path *path;
6972 int recorded_data_ref = 0;
6977 path = btrfs_alloc_path();
6980 list_for_each_entry(back, &rec->backrefs, list) {
6981 if (back->full_backref || !back->is_data ||
6982 !back->found_extent_tree)
6984 dback = (struct data_backref *)back;
6985 if (dback->found_ref)
6987 key.objectid = dback->root;
6988 key.type = BTRFS_ROOT_ITEM_KEY;
6989 key.offset = (u64)-1;
6991 dest_root = btrfs_read_fs_root(fs_info, &key);
6993 /* For non-exist root we just skip it */
6994 if (IS_ERR(dest_root) || !dest_root)
6997 key.objectid = dback->owner;
6998 key.type = BTRFS_EXTENT_DATA_KEY;
6999 key.offset = dback->offset;
7001 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7003 * For ret < 0, it's OK since the fs-tree may be corrupted,
7004 * we need to record it for inode/file extent rebuild.
7005 * For ret > 0, we record it only for file extent rebuild.
7006 * For ret == 0, the file extent exists but only bytenr
7007 * mismatch, let the original bytenr fix routine to handle,
7013 orphan = malloc(sizeof(*orphan));
7018 INIT_LIST_HEAD(&orphan->list);
7019 orphan->root = dback->root;
7020 orphan->objectid = dback->owner;
7021 orphan->offset = dback->offset;
7022 orphan->disk_bytenr = rec->cache.start;
7023 orphan->disk_len = rec->cache.size;
7024 list_add(&dest_root->orphan_data_extents, &orphan->list);
7025 recorded_data_ref = 1;
7028 btrfs_free_path(path);
7030 return !recorded_data_ref;
7036 * when an incorrect extent item is found, this will delete
7037 * all of the existing entries for it and recreate them
7038 * based on what the tree scan found.
7040 static int fixup_extent_refs(struct btrfs_fs_info *info,
7041 struct cache_tree *extent_cache,
7042 struct extent_record *rec)
7044 struct btrfs_trans_handle *trans = NULL;
7046 struct btrfs_path *path;
7047 struct list_head *cur = rec->backrefs.next;
7048 struct cache_extent *cache;
7049 struct extent_backref *back;
7053 if (rec->flag_block_full_backref)
7054 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7056 path = btrfs_alloc_path();
7060 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7062 * Sometimes the backrefs themselves are so broken they don't
7063 * get attached to any meaningful rec, so first go back and
7064 * check any of our backrefs that we couldn't find and throw
7065 * them into the list if we find the backref so that
7066 * verify_backrefs can figure out what to do.
7068 ret = find_possible_backrefs(info, path, extent_cache, rec);
7073 /* step one, make sure all of the backrefs agree */
7074 ret = verify_backrefs(info, path, rec);
7078 trans = btrfs_start_transaction(info->extent_root, 1);
7079 if (IS_ERR(trans)) {
7080 ret = PTR_ERR(trans);
7084 /* step two, delete all the existing records */
7085 ret = delete_extent_records(trans, info->extent_root, path,
7086 rec->start, rec->max_size);
7091 /* was this block corrupt? If so, don't add references to it */
7092 cache = lookup_cache_extent(info->corrupt_blocks,
7093 rec->start, rec->max_size);
7099 /* step three, recreate all the refs we did find */
7100 while(cur != &rec->backrefs) {
7101 back = list_entry(cur, struct extent_backref, list);
7105 * if we didn't find any references, don't create a
7108 if (!back->found_ref)
7111 rec->bad_full_backref = 0;
7112 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7120 int err = btrfs_commit_transaction(trans, info->extent_root);
7125 btrfs_free_path(path);
7129 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7130 struct extent_record *rec)
7132 struct btrfs_trans_handle *trans;
7133 struct btrfs_root *root = fs_info->extent_root;
7134 struct btrfs_path *path;
7135 struct btrfs_extent_item *ei;
7136 struct btrfs_key key;
7140 key.objectid = rec->start;
7141 if (rec->metadata) {
7142 key.type = BTRFS_METADATA_ITEM_KEY;
7143 key.offset = rec->info_level;
7145 key.type = BTRFS_EXTENT_ITEM_KEY;
7146 key.offset = rec->max_size;
7149 path = btrfs_alloc_path();
7153 trans = btrfs_start_transaction(root, 0);
7154 if (IS_ERR(trans)) {
7155 btrfs_free_path(path);
7156 return PTR_ERR(trans);
7159 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7161 btrfs_free_path(path);
7162 btrfs_commit_transaction(trans, root);
7165 fprintf(stderr, "Didn't find extent for %llu\n",
7166 (unsigned long long)rec->start);
7167 btrfs_free_path(path);
7168 btrfs_commit_transaction(trans, root);
7172 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7173 struct btrfs_extent_item);
7174 flags = btrfs_extent_flags(path->nodes[0], ei);
7175 if (rec->flag_block_full_backref) {
7176 fprintf(stderr, "setting full backref on %llu\n",
7177 (unsigned long long)key.objectid);
7178 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7180 fprintf(stderr, "clearing full backref on %llu\n",
7181 (unsigned long long)key.objectid);
7182 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7184 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7185 btrfs_mark_buffer_dirty(path->nodes[0]);
7186 btrfs_free_path(path);
7187 return btrfs_commit_transaction(trans, root);
7190 /* right now we only prune from the extent allocation tree */
7191 static int prune_one_block(struct btrfs_trans_handle *trans,
7192 struct btrfs_fs_info *info,
7193 struct btrfs_corrupt_block *corrupt)
7196 struct btrfs_path path;
7197 struct extent_buffer *eb;
7201 int level = corrupt->level + 1;
7203 btrfs_init_path(&path);
7205 /* we want to stop at the parent to our busted block */
7206 path.lowest_level = level;
7208 ret = btrfs_search_slot(trans, info->extent_root,
7209 &corrupt->key, &path, -1, 1);
7214 eb = path.nodes[level];
7221 * hopefully the search gave us the block we want to prune,
7222 * lets try that first
7224 slot = path.slots[level];
7225 found = btrfs_node_blockptr(eb, slot);
7226 if (found == corrupt->cache.start)
7229 nritems = btrfs_header_nritems(eb);
7231 /* the search failed, lets scan this node and hope we find it */
7232 for (slot = 0; slot < nritems; slot++) {
7233 found = btrfs_node_blockptr(eb, slot);
7234 if (found == corrupt->cache.start)
7238 * we couldn't find the bad block. TODO, search all the nodes for pointers
7241 if (eb == info->extent_root->node) {
7246 btrfs_release_path(&path);
7251 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7252 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7255 btrfs_release_path(&path);
7259 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7261 struct btrfs_trans_handle *trans = NULL;
7262 struct cache_extent *cache;
7263 struct btrfs_corrupt_block *corrupt;
7266 cache = search_cache_extent(info->corrupt_blocks, 0);
7270 trans = btrfs_start_transaction(info->extent_root, 1);
7272 return PTR_ERR(trans);
7274 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7275 prune_one_block(trans, info, corrupt);
7276 remove_cache_extent(info->corrupt_blocks, cache);
7279 return btrfs_commit_transaction(trans, info->extent_root);
7283 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7285 struct btrfs_block_group_cache *cache;
7290 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7291 &start, &end, EXTENT_DIRTY);
7294 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7300 cache = btrfs_lookup_first_block_group(fs_info, start);
7305 start = cache->key.objectid + cache->key.offset;
7309 static int check_extent_refs(struct btrfs_root *root,
7310 struct cache_tree *extent_cache)
7312 struct extent_record *rec;
7313 struct cache_extent *cache;
7322 * if we're doing a repair, we have to make sure
7323 * we don't allocate from the problem extents.
7324 * In the worst case, this will be all the
7327 cache = search_cache_extent(extent_cache, 0);
7329 rec = container_of(cache, struct extent_record, cache);
7330 set_extent_dirty(root->fs_info->excluded_extents,
7332 rec->start + rec->max_size - 1,
7334 cache = next_cache_extent(cache);
7337 /* pin down all the corrupted blocks too */
7338 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7340 set_extent_dirty(root->fs_info->excluded_extents,
7342 cache->start + cache->size - 1,
7344 cache = next_cache_extent(cache);
7346 prune_corrupt_blocks(root->fs_info);
7347 reset_cached_block_groups(root->fs_info);
7350 reset_cached_block_groups(root->fs_info);
7353 * We need to delete any duplicate entries we find first otherwise we
7354 * could mess up the extent tree when we have backrefs that actually
7355 * belong to a different extent item and not the weird duplicate one.
7357 while (repair && !list_empty(&duplicate_extents)) {
7358 rec = list_entry(duplicate_extents.next, struct extent_record,
7360 list_del_init(&rec->list);
7362 /* Sometimes we can find a backref before we find an actual
7363 * extent, so we need to process it a little bit to see if there
7364 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7365 * if this is a backref screwup. If we need to delete stuff
7366 * process_duplicates() will return 0, otherwise it will return
7369 if (process_duplicates(root, extent_cache, rec))
7371 ret = delete_duplicate_records(root, rec);
7375 * delete_duplicate_records will return the number of entries
7376 * deleted, so if it's greater than 0 then we know we actually
7377 * did something and we need to remove.
7391 cache = search_cache_extent(extent_cache, 0);
7394 rec = container_of(cache, struct extent_record, cache);
7395 if (rec->num_duplicates) {
7396 fprintf(stderr, "extent item %llu has multiple extent "
7397 "items\n", (unsigned long long)rec->start);
7402 if (rec->refs != rec->extent_item_refs) {
7403 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7404 (unsigned long long)rec->start,
7405 (unsigned long long)rec->nr);
7406 fprintf(stderr, "extent item %llu, found %llu\n",
7407 (unsigned long long)rec->extent_item_refs,
7408 (unsigned long long)rec->refs);
7409 ret = record_orphan_data_extents(root->fs_info, rec);
7416 * we can't use the extent to repair file
7417 * extent, let the fallback method handle it.
7419 if (!fixed && repair) {
7420 ret = fixup_extent_refs(
7431 if (all_backpointers_checked(rec, 1)) {
7432 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7433 (unsigned long long)rec->start,
7434 (unsigned long long)rec->nr);
7436 if (!fixed && !recorded && repair) {
7437 ret = fixup_extent_refs(root->fs_info,
7446 if (!rec->owner_ref_checked) {
7447 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7448 (unsigned long long)rec->start,
7449 (unsigned long long)rec->nr);
7450 if (!fixed && !recorded && repair) {
7451 ret = fixup_extent_refs(root->fs_info,
7460 if (rec->bad_full_backref) {
7461 fprintf(stderr, "bad full backref, on [%llu]\n",
7462 (unsigned long long)rec->start);
7464 ret = fixup_extent_flags(root->fs_info, rec);
7473 remove_cache_extent(extent_cache, cache);
7474 free_all_extent_backrefs(rec);
7475 if (!init_extent_tree && repair && (!cur_err || fixed))
7476 clear_extent_dirty(root->fs_info->excluded_extents,
7478 rec->start + rec->max_size - 1,
7484 if (ret && ret != -EAGAIN) {
7485 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7488 struct btrfs_trans_handle *trans;
7490 root = root->fs_info->extent_root;
7491 trans = btrfs_start_transaction(root, 1);
7492 if (IS_ERR(trans)) {
7493 ret = PTR_ERR(trans);
7497 btrfs_fix_block_accounting(trans, root);
7498 ret = btrfs_commit_transaction(trans, root);
7503 fprintf(stderr, "repaired damaged extent references\n");
7509 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7513 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7514 stripe_size = length;
7515 stripe_size /= num_stripes;
7516 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7517 stripe_size = length * 2;
7518 stripe_size /= num_stripes;
7519 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7520 stripe_size = length;
7521 stripe_size /= (num_stripes - 1);
7522 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7523 stripe_size = length;
7524 stripe_size /= (num_stripes - 2);
7526 stripe_size = length;
7532 * Check the chunk with its block group/dev list ref:
7533 * Return 0 if all refs seems valid.
7534 * Return 1 if part of refs seems valid, need later check for rebuild ref
7535 * like missing block group and needs to search extent tree to rebuild them.
7536 * Return -1 if essential refs are missing and unable to rebuild.
7538 static int check_chunk_refs(struct chunk_record *chunk_rec,
7539 struct block_group_tree *block_group_cache,
7540 struct device_extent_tree *dev_extent_cache,
7543 struct cache_extent *block_group_item;
7544 struct block_group_record *block_group_rec;
7545 struct cache_extent *dev_extent_item;
7546 struct device_extent_record *dev_extent_rec;
7550 int metadump_v2 = 0;
7554 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7557 if (block_group_item) {
7558 block_group_rec = container_of(block_group_item,
7559 struct block_group_record,
7561 if (chunk_rec->length != block_group_rec->offset ||
7562 chunk_rec->offset != block_group_rec->objectid ||
7564 chunk_rec->type_flags != block_group_rec->flags)) {
7567 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7568 chunk_rec->objectid,
7573 chunk_rec->type_flags,
7574 block_group_rec->objectid,
7575 block_group_rec->type,
7576 block_group_rec->offset,
7577 block_group_rec->offset,
7578 block_group_rec->objectid,
7579 block_group_rec->flags);
7582 list_del_init(&block_group_rec->list);
7583 chunk_rec->bg_rec = block_group_rec;
7588 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7589 chunk_rec->objectid,
7594 chunk_rec->type_flags);
7601 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7602 chunk_rec->num_stripes);
7603 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7604 devid = chunk_rec->stripes[i].devid;
7605 offset = chunk_rec->stripes[i].offset;
7606 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7607 devid, offset, length);
7608 if (dev_extent_item) {
7609 dev_extent_rec = container_of(dev_extent_item,
7610 struct device_extent_record,
7612 if (dev_extent_rec->objectid != devid ||
7613 dev_extent_rec->offset != offset ||
7614 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7615 dev_extent_rec->length != length) {
7618 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7619 chunk_rec->objectid,
7622 chunk_rec->stripes[i].devid,
7623 chunk_rec->stripes[i].offset,
7624 dev_extent_rec->objectid,
7625 dev_extent_rec->offset,
7626 dev_extent_rec->length);
7629 list_move(&dev_extent_rec->chunk_list,
7630 &chunk_rec->dextents);
7635 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7636 chunk_rec->objectid,
7639 chunk_rec->stripes[i].devid,
7640 chunk_rec->stripes[i].offset);
7647 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7648 int check_chunks(struct cache_tree *chunk_cache,
7649 struct block_group_tree *block_group_cache,
7650 struct device_extent_tree *dev_extent_cache,
7651 struct list_head *good, struct list_head *bad,
7652 struct list_head *rebuild, int silent)
7654 struct cache_extent *chunk_item;
7655 struct chunk_record *chunk_rec;
7656 struct block_group_record *bg_rec;
7657 struct device_extent_record *dext_rec;
7661 chunk_item = first_cache_extent(chunk_cache);
7662 while (chunk_item) {
7663 chunk_rec = container_of(chunk_item, struct chunk_record,
7665 err = check_chunk_refs(chunk_rec, block_group_cache,
7666 dev_extent_cache, silent);
7669 if (err == 0 && good)
7670 list_add_tail(&chunk_rec->list, good);
7671 if (err > 0 && rebuild)
7672 list_add_tail(&chunk_rec->list, rebuild);
7674 list_add_tail(&chunk_rec->list, bad);
7675 chunk_item = next_cache_extent(chunk_item);
7678 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7681 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7689 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7693 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7704 static int check_device_used(struct device_record *dev_rec,
7705 struct device_extent_tree *dext_cache)
7707 struct cache_extent *cache;
7708 struct device_extent_record *dev_extent_rec;
7711 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7713 dev_extent_rec = container_of(cache,
7714 struct device_extent_record,
7716 if (dev_extent_rec->objectid != dev_rec->devid)
7719 list_del_init(&dev_extent_rec->device_list);
7720 total_byte += dev_extent_rec->length;
7721 cache = next_cache_extent(cache);
7724 if (total_byte != dev_rec->byte_used) {
7726 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7727 total_byte, dev_rec->byte_used, dev_rec->objectid,
7728 dev_rec->type, dev_rec->offset);
7735 /* check btrfs_dev_item -> btrfs_dev_extent */
7736 static int check_devices(struct rb_root *dev_cache,
7737 struct device_extent_tree *dev_extent_cache)
7739 struct rb_node *dev_node;
7740 struct device_record *dev_rec;
7741 struct device_extent_record *dext_rec;
7745 dev_node = rb_first(dev_cache);
7747 dev_rec = container_of(dev_node, struct device_record, node);
7748 err = check_device_used(dev_rec, dev_extent_cache);
7752 dev_node = rb_next(dev_node);
7754 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7757 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7758 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7765 static int add_root_item_to_list(struct list_head *head,
7766 u64 objectid, u64 bytenr, u64 last_snapshot,
7767 u8 level, u8 drop_level,
7768 int level_size, struct btrfs_key *drop_key)
7771 struct root_item_record *ri_rec;
7772 ri_rec = malloc(sizeof(*ri_rec));
7775 ri_rec->bytenr = bytenr;
7776 ri_rec->objectid = objectid;
7777 ri_rec->level = level;
7778 ri_rec->level_size = level_size;
7779 ri_rec->drop_level = drop_level;
7780 ri_rec->last_snapshot = last_snapshot;
7782 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7783 list_add_tail(&ri_rec->list, head);
7788 static void free_root_item_list(struct list_head *list)
7790 struct root_item_record *ri_rec;
7792 while (!list_empty(list)) {
7793 ri_rec = list_first_entry(list, struct root_item_record,
7795 list_del_init(&ri_rec->list);
7800 static int deal_root_from_list(struct list_head *list,
7801 struct btrfs_root *root,
7802 struct block_info *bits,
7804 struct cache_tree *pending,
7805 struct cache_tree *seen,
7806 struct cache_tree *reada,
7807 struct cache_tree *nodes,
7808 struct cache_tree *extent_cache,
7809 struct cache_tree *chunk_cache,
7810 struct rb_root *dev_cache,
7811 struct block_group_tree *block_group_cache,
7812 struct device_extent_tree *dev_extent_cache)
7817 while (!list_empty(list)) {
7818 struct root_item_record *rec;
7819 struct extent_buffer *buf;
7820 rec = list_entry(list->next,
7821 struct root_item_record, list);
7823 buf = read_tree_block(root->fs_info->tree_root,
7824 rec->bytenr, rec->level_size, 0);
7825 if (!extent_buffer_uptodate(buf)) {
7826 free_extent_buffer(buf);
7830 add_root_to_pending(buf, extent_cache, pending,
7831 seen, nodes, rec->objectid);
7833 * To rebuild extent tree, we need deal with snapshot
7834 * one by one, otherwise we deal with node firstly which
7835 * can maximize readahead.
7838 ret = run_next_block(root, bits, bits_nr, &last,
7839 pending, seen, reada, nodes,
7840 extent_cache, chunk_cache,
7841 dev_cache, block_group_cache,
7842 dev_extent_cache, rec);
7846 free_extent_buffer(buf);
7847 list_del(&rec->list);
7853 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7854 reada, nodes, extent_cache, chunk_cache,
7855 dev_cache, block_group_cache,
7856 dev_extent_cache, NULL);
7866 static int check_chunks_and_extents(struct btrfs_root *root)
7868 struct rb_root dev_cache;
7869 struct cache_tree chunk_cache;
7870 struct block_group_tree block_group_cache;
7871 struct device_extent_tree dev_extent_cache;
7872 struct cache_tree extent_cache;
7873 struct cache_tree seen;
7874 struct cache_tree pending;
7875 struct cache_tree reada;
7876 struct cache_tree nodes;
7877 struct extent_io_tree excluded_extents;
7878 struct cache_tree corrupt_blocks;
7879 struct btrfs_path path;
7880 struct btrfs_key key;
7881 struct btrfs_key found_key;
7883 struct block_info *bits;
7885 struct extent_buffer *leaf;
7887 struct btrfs_root_item ri;
7888 struct list_head dropping_trees;
7889 struct list_head normal_trees;
7890 struct btrfs_root *root1;
7895 dev_cache = RB_ROOT;
7896 cache_tree_init(&chunk_cache);
7897 block_group_tree_init(&block_group_cache);
7898 device_extent_tree_init(&dev_extent_cache);
7900 cache_tree_init(&extent_cache);
7901 cache_tree_init(&seen);
7902 cache_tree_init(&pending);
7903 cache_tree_init(&nodes);
7904 cache_tree_init(&reada);
7905 cache_tree_init(&corrupt_blocks);
7906 extent_io_tree_init(&excluded_extents);
7907 INIT_LIST_HEAD(&dropping_trees);
7908 INIT_LIST_HEAD(&normal_trees);
7911 root->fs_info->excluded_extents = &excluded_extents;
7912 root->fs_info->fsck_extent_cache = &extent_cache;
7913 root->fs_info->free_extent_hook = free_extent_hook;
7914 root->fs_info->corrupt_blocks = &corrupt_blocks;
7918 bits = malloc(bits_nr * sizeof(struct block_info));
7925 root1 = root->fs_info->tree_root;
7926 level = btrfs_header_level(root1->node);
7927 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7928 root1->node->start, 0, level, 0,
7929 btrfs_level_size(root1, level), NULL);
7932 root1 = root->fs_info->chunk_root;
7933 level = btrfs_header_level(root1->node);
7934 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7935 root1->node->start, 0, level, 0,
7936 btrfs_level_size(root1, level), NULL);
7939 btrfs_init_path(&path);
7942 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7943 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7948 leaf = path.nodes[0];
7949 slot = path.slots[0];
7950 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7951 ret = btrfs_next_leaf(root, &path);
7954 leaf = path.nodes[0];
7955 slot = path.slots[0];
7957 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7958 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7959 unsigned long offset;
7962 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7963 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7964 last_snapshot = btrfs_root_last_snapshot(&ri);
7965 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7966 level = btrfs_root_level(&ri);
7967 level_size = btrfs_level_size(root, level);
7968 ret = add_root_item_to_list(&normal_trees,
7970 btrfs_root_bytenr(&ri),
7971 last_snapshot, level,
7972 0, level_size, NULL);
7976 level = btrfs_root_level(&ri);
7977 level_size = btrfs_level_size(root, level);
7978 objectid = found_key.objectid;
7979 btrfs_disk_key_to_cpu(&found_key,
7981 ret = add_root_item_to_list(&dropping_trees,
7983 btrfs_root_bytenr(&ri),
7984 last_snapshot, level,
7986 level_size, &found_key);
7993 btrfs_release_path(&path);
7996 * check_block can return -EAGAIN if it fixes something, please keep
7997 * this in mind when dealing with return values from these functions, if
7998 * we get -EAGAIN we want to fall through and restart the loop.
8000 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8001 &seen, &reada, &nodes, &extent_cache,
8002 &chunk_cache, &dev_cache, &block_group_cache,
8009 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8010 &pending, &seen, &reada, &nodes,
8011 &extent_cache, &chunk_cache, &dev_cache,
8012 &block_group_cache, &dev_extent_cache);
8019 err = check_chunks(&chunk_cache, &block_group_cache,
8020 &dev_extent_cache, NULL, NULL, NULL, 0);
8028 ret = check_extent_refs(root, &extent_cache);
8035 err = check_devices(&dev_cache, &dev_extent_cache);
8041 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8042 extent_io_tree_cleanup(&excluded_extents);
8043 root->fs_info->fsck_extent_cache = NULL;
8044 root->fs_info->free_extent_hook = NULL;
8045 root->fs_info->corrupt_blocks = NULL;
8046 root->fs_info->excluded_extents = NULL;
8049 free_chunk_cache_tree(&chunk_cache);
8050 free_device_cache_tree(&dev_cache);
8051 free_block_group_tree(&block_group_cache);
8052 free_device_extent_tree(&dev_extent_cache);
8053 free_extent_cache_tree(&seen);
8054 free_extent_cache_tree(&pending);
8055 free_extent_cache_tree(&reada);
8056 free_extent_cache_tree(&nodes);
8059 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8060 free_extent_cache_tree(&seen);
8061 free_extent_cache_tree(&pending);
8062 free_extent_cache_tree(&reada);
8063 free_extent_cache_tree(&nodes);
8064 free_chunk_cache_tree(&chunk_cache);
8065 free_block_group_tree(&block_group_cache);
8066 free_device_cache_tree(&dev_cache);
8067 free_device_extent_tree(&dev_extent_cache);
8068 free_extent_record_cache(root->fs_info, &extent_cache);
8069 free_root_item_list(&normal_trees);
8070 free_root_item_list(&dropping_trees);
8071 extent_io_tree_cleanup(&excluded_extents);
8075 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8076 struct btrfs_root *root, int overwrite)
8078 struct extent_buffer *c;
8079 struct extent_buffer *old = root->node;
8082 struct btrfs_disk_key disk_key = {0,0,0};
8088 extent_buffer_get(c);
8091 c = btrfs_alloc_free_block(trans, root,
8092 btrfs_level_size(root, 0),
8093 root->root_key.objectid,
8094 &disk_key, level, 0, 0);
8097 extent_buffer_get(c);
8101 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8102 btrfs_set_header_level(c, level);
8103 btrfs_set_header_bytenr(c, c->start);
8104 btrfs_set_header_generation(c, trans->transid);
8105 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8106 btrfs_set_header_owner(c, root->root_key.objectid);
8108 write_extent_buffer(c, root->fs_info->fsid,
8109 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8111 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8112 btrfs_header_chunk_tree_uuid(c),
8115 btrfs_mark_buffer_dirty(c);
8117 * this case can happen in the following case:
8119 * 1.overwrite previous root.
8121 * 2.reinit reloc data root, this is because we skip pin
8122 * down reloc data tree before which means we can allocate
8123 * same block bytenr here.
8125 if (old->start == c->start) {
8126 btrfs_set_root_generation(&root->root_item,
8128 root->root_item.level = btrfs_header_level(root->node);
8129 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8130 &root->root_key, &root->root_item);
8132 free_extent_buffer(c);
8136 free_extent_buffer(old);
8138 add_root_to_dirty_list(root);
8142 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8143 struct extent_buffer *eb, int tree_root)
8145 struct extent_buffer *tmp;
8146 struct btrfs_root_item *ri;
8147 struct btrfs_key key;
8150 int level = btrfs_header_level(eb);
8156 * If we have pinned this block before, don't pin it again.
8157 * This can not only avoid forever loop with broken filesystem
8158 * but also give us some speedups.
8160 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8161 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8164 btrfs_pin_extent(fs_info, eb->start, eb->len);
8166 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8167 nritems = btrfs_header_nritems(eb);
8168 for (i = 0; i < nritems; i++) {
8170 btrfs_item_key_to_cpu(eb, &key, i);
8171 if (key.type != BTRFS_ROOT_ITEM_KEY)
8173 /* Skip the extent root and reloc roots */
8174 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8175 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8176 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8178 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8179 bytenr = btrfs_disk_root_bytenr(eb, ri);
8182 * If at any point we start needing the real root we
8183 * will have to build a stump root for the root we are
8184 * in, but for now this doesn't actually use the root so
8185 * just pass in extent_root.
8187 tmp = read_tree_block(fs_info->extent_root, bytenr,
8189 if (!extent_buffer_uptodate(tmp)) {
8190 fprintf(stderr, "Error reading root block\n");
8193 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8194 free_extent_buffer(tmp);
8198 bytenr = btrfs_node_blockptr(eb, i);
8200 /* If we aren't the tree root don't read the block */
8201 if (level == 1 && !tree_root) {
8202 btrfs_pin_extent(fs_info, bytenr, leafsize);
8206 tmp = read_tree_block(fs_info->extent_root, bytenr,
8208 if (!extent_buffer_uptodate(tmp)) {
8209 fprintf(stderr, "Error reading tree block\n");
8212 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8213 free_extent_buffer(tmp);
8222 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8226 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8230 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8233 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8235 struct btrfs_block_group_cache *cache;
8236 struct btrfs_path *path;
8237 struct extent_buffer *leaf;
8238 struct btrfs_chunk *chunk;
8239 struct btrfs_key key;
8243 path = btrfs_alloc_path();
8248 key.type = BTRFS_CHUNK_ITEM_KEY;
8251 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8253 btrfs_free_path(path);
8258 * We do this in case the block groups were screwed up and had alloc
8259 * bits that aren't actually set on the chunks. This happens with
8260 * restored images every time and could happen in real life I guess.
8262 fs_info->avail_data_alloc_bits = 0;
8263 fs_info->avail_metadata_alloc_bits = 0;
8264 fs_info->avail_system_alloc_bits = 0;
8266 /* First we need to create the in-memory block groups */
8268 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8269 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8271 btrfs_free_path(path);
8279 leaf = path->nodes[0];
8280 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8281 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8286 chunk = btrfs_item_ptr(leaf, path->slots[0],
8287 struct btrfs_chunk);
8288 btrfs_add_block_group(fs_info, 0,
8289 btrfs_chunk_type(leaf, chunk),
8290 key.objectid, key.offset,
8291 btrfs_chunk_length(leaf, chunk));
8292 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8293 key.offset + btrfs_chunk_length(leaf, chunk),
8299 cache = btrfs_lookup_first_block_group(fs_info, start);
8303 start = cache->key.objectid + cache->key.offset;
8306 btrfs_free_path(path);
8310 static int reset_balance(struct btrfs_trans_handle *trans,
8311 struct btrfs_fs_info *fs_info)
8313 struct btrfs_root *root = fs_info->tree_root;
8314 struct btrfs_path *path;
8315 struct extent_buffer *leaf;
8316 struct btrfs_key key;
8317 int del_slot, del_nr = 0;
8321 path = btrfs_alloc_path();
8325 key.objectid = BTRFS_BALANCE_OBJECTID;
8326 key.type = BTRFS_BALANCE_ITEM_KEY;
8329 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8334 goto reinit_data_reloc;
8339 ret = btrfs_del_item(trans, root, path);
8342 btrfs_release_path(path);
8344 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8345 key.type = BTRFS_ROOT_ITEM_KEY;
8348 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8352 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8357 ret = btrfs_del_items(trans, root, path,
8364 btrfs_release_path(path);
8367 ret = btrfs_search_slot(trans, root, &key, path,
8374 leaf = path->nodes[0];
8375 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8376 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8378 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8383 del_slot = path->slots[0];
8392 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8396 btrfs_release_path(path);
8399 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8400 key.type = BTRFS_ROOT_ITEM_KEY;
8401 key.offset = (u64)-1;
8402 root = btrfs_read_fs_root(fs_info, &key);
8404 fprintf(stderr, "Error reading data reloc tree\n");
8405 ret = PTR_ERR(root);
8408 record_root_in_trans(trans, root);
8409 ret = btrfs_fsck_reinit_root(trans, root, 0);
8412 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8414 btrfs_free_path(path);
8418 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8419 struct btrfs_fs_info *fs_info)
8425 * The only reason we don't do this is because right now we're just
8426 * walking the trees we find and pinning down their bytes, we don't look
8427 * at any of the leaves. In order to do mixed groups we'd have to check
8428 * the leaves of any fs roots and pin down the bytes for any file
8429 * extents we find. Not hard but why do it if we don't have to?
8431 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8432 fprintf(stderr, "We don't support re-initing the extent tree "
8433 "for mixed block groups yet, please notify a btrfs "
8434 "developer you want to do this so they can add this "
8435 "functionality.\n");
8440 * first we need to walk all of the trees except the extent tree and pin
8441 * down the bytes that are in use so we don't overwrite any existing
8444 ret = pin_metadata_blocks(fs_info);
8446 fprintf(stderr, "error pinning down used bytes\n");
8451 * Need to drop all the block groups since we're going to recreate all
8454 btrfs_free_block_groups(fs_info);
8455 ret = reset_block_groups(fs_info);
8457 fprintf(stderr, "error resetting the block groups\n");
8461 /* Ok we can allocate now, reinit the extent root */
8462 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8464 fprintf(stderr, "extent root initialization failed\n");
8466 * When the transaction code is updated we should end the
8467 * transaction, but for now progs only knows about commit so
8468 * just return an error.
8474 * Now we have all the in-memory block groups setup so we can make
8475 * allocations properly, and the metadata we care about is safe since we
8476 * pinned all of it above.
8479 struct btrfs_block_group_cache *cache;
8481 cache = btrfs_lookup_first_block_group(fs_info, start);
8484 start = cache->key.objectid + cache->key.offset;
8485 ret = btrfs_insert_item(trans, fs_info->extent_root,
8486 &cache->key, &cache->item,
8487 sizeof(cache->item));
8489 fprintf(stderr, "Error adding block group\n");
8492 btrfs_extent_post_op(trans, fs_info->extent_root);
8495 ret = reset_balance(trans, fs_info);
8497 fprintf(stderr, "error reseting the pending balance\n");
8502 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8504 struct btrfs_path *path;
8505 struct btrfs_trans_handle *trans;
8506 struct btrfs_key key;
8509 printf("Recowing metadata block %llu\n", eb->start);
8510 key.objectid = btrfs_header_owner(eb);
8511 key.type = BTRFS_ROOT_ITEM_KEY;
8512 key.offset = (u64)-1;
8514 root = btrfs_read_fs_root(root->fs_info, &key);
8516 fprintf(stderr, "Couldn't find owner root %llu\n",
8518 return PTR_ERR(root);
8521 path = btrfs_alloc_path();
8525 trans = btrfs_start_transaction(root, 1);
8526 if (IS_ERR(trans)) {
8527 btrfs_free_path(path);
8528 return PTR_ERR(trans);
8531 path->lowest_level = btrfs_header_level(eb);
8532 if (path->lowest_level)
8533 btrfs_node_key_to_cpu(eb, &key, 0);
8535 btrfs_item_key_to_cpu(eb, &key, 0);
8537 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8538 btrfs_commit_transaction(trans, root);
8539 btrfs_free_path(path);
8543 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8545 struct btrfs_path *path;
8546 struct btrfs_trans_handle *trans;
8547 struct btrfs_key key;
8550 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8551 bad->key.type, bad->key.offset);
8552 key.objectid = bad->root_id;
8553 key.type = BTRFS_ROOT_ITEM_KEY;
8554 key.offset = (u64)-1;
8556 root = btrfs_read_fs_root(root->fs_info, &key);
8558 fprintf(stderr, "Couldn't find owner root %llu\n",
8560 return PTR_ERR(root);
8563 path = btrfs_alloc_path();
8567 trans = btrfs_start_transaction(root, 1);
8568 if (IS_ERR(trans)) {
8569 btrfs_free_path(path);
8570 return PTR_ERR(trans);
8573 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8579 ret = btrfs_del_item(trans, root, path);
8581 btrfs_commit_transaction(trans, root);
8582 btrfs_free_path(path);
8586 static int zero_log_tree(struct btrfs_root *root)
8588 struct btrfs_trans_handle *trans;
8591 trans = btrfs_start_transaction(root, 1);
8592 if (IS_ERR(trans)) {
8593 ret = PTR_ERR(trans);
8596 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8597 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8598 ret = btrfs_commit_transaction(trans, root);
8602 static int populate_csum(struct btrfs_trans_handle *trans,
8603 struct btrfs_root *csum_root, char *buf, u64 start,
8610 while (offset < len) {
8611 sectorsize = csum_root->sectorsize;
8612 ret = read_extent_data(csum_root, buf, start + offset,
8616 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8617 start + offset, buf, sectorsize);
8620 offset += sectorsize;
8625 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8626 struct btrfs_root *csum_root)
8628 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8629 struct btrfs_path *path;
8630 struct btrfs_extent_item *ei;
8631 struct extent_buffer *leaf;
8633 struct btrfs_key key;
8636 path = btrfs_alloc_path();
8641 key.type = BTRFS_EXTENT_ITEM_KEY;
8644 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8646 btrfs_free_path(path);
8650 buf = malloc(csum_root->sectorsize);
8652 btrfs_free_path(path);
8657 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8658 ret = btrfs_next_leaf(extent_root, path);
8666 leaf = path->nodes[0];
8668 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8669 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8674 ei = btrfs_item_ptr(leaf, path->slots[0],
8675 struct btrfs_extent_item);
8676 if (!(btrfs_extent_flags(leaf, ei) &
8677 BTRFS_EXTENT_FLAG_DATA)) {
8682 ret = populate_csum(trans, csum_root, buf, key.objectid,
8689 btrfs_free_path(path);
8694 struct root_item_info {
8695 /* level of the root */
8697 /* number of nodes at this level, must be 1 for a root */
8701 struct cache_extent cache_extent;
8704 static struct cache_tree *roots_info_cache = NULL;
8706 static void free_roots_info_cache(void)
8708 if (!roots_info_cache)
8711 while (!cache_tree_empty(roots_info_cache)) {
8712 struct cache_extent *entry;
8713 struct root_item_info *rii;
8715 entry = first_cache_extent(roots_info_cache);
8718 remove_cache_extent(roots_info_cache, entry);
8719 rii = container_of(entry, struct root_item_info, cache_extent);
8723 free(roots_info_cache);
8724 roots_info_cache = NULL;
8727 static int build_roots_info_cache(struct btrfs_fs_info *info)
8730 struct btrfs_key key;
8731 struct extent_buffer *leaf;
8732 struct btrfs_path *path;
8734 if (!roots_info_cache) {
8735 roots_info_cache = malloc(sizeof(*roots_info_cache));
8736 if (!roots_info_cache)
8738 cache_tree_init(roots_info_cache);
8741 path = btrfs_alloc_path();
8746 key.type = BTRFS_EXTENT_ITEM_KEY;
8749 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8752 leaf = path->nodes[0];
8755 struct btrfs_key found_key;
8756 struct btrfs_extent_item *ei;
8757 struct btrfs_extent_inline_ref *iref;
8758 int slot = path->slots[0];
8763 struct cache_extent *entry;
8764 struct root_item_info *rii;
8766 if (slot >= btrfs_header_nritems(leaf)) {
8767 ret = btrfs_next_leaf(info->extent_root, path);
8774 leaf = path->nodes[0];
8775 slot = path->slots[0];
8778 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8780 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8781 found_key.type != BTRFS_METADATA_ITEM_KEY)
8784 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8785 flags = btrfs_extent_flags(leaf, ei);
8787 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8788 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8791 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8792 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8793 level = found_key.offset;
8795 struct btrfs_tree_block_info *info;
8797 info = (struct btrfs_tree_block_info *)(ei + 1);
8798 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8799 level = btrfs_tree_block_level(leaf, info);
8803 * For a root extent, it must be of the following type and the
8804 * first (and only one) iref in the item.
8806 type = btrfs_extent_inline_ref_type(leaf, iref);
8807 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8810 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8811 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8813 rii = malloc(sizeof(struct root_item_info));
8818 rii->cache_extent.start = root_id;
8819 rii->cache_extent.size = 1;
8820 rii->level = (u8)-1;
8821 entry = &rii->cache_extent;
8822 ret = insert_cache_extent(roots_info_cache, entry);
8825 rii = container_of(entry, struct root_item_info,
8829 ASSERT(rii->cache_extent.start == root_id);
8830 ASSERT(rii->cache_extent.size == 1);
8832 if (level > rii->level || rii->level == (u8)-1) {
8834 rii->bytenr = found_key.objectid;
8835 rii->gen = btrfs_extent_generation(leaf, ei);
8836 rii->node_count = 1;
8837 } else if (level == rii->level) {
8845 btrfs_free_path(path);
8850 static int maybe_repair_root_item(struct btrfs_fs_info *info,
8851 struct btrfs_path *path,
8852 const struct btrfs_key *root_key,
8853 const int read_only_mode)
8855 const u64 root_id = root_key->objectid;
8856 struct cache_extent *entry;
8857 struct root_item_info *rii;
8858 struct btrfs_root_item ri;
8859 unsigned long offset;
8861 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8864 "Error: could not find extent items for root %llu\n",
8865 root_key->objectid);
8869 rii = container_of(entry, struct root_item_info, cache_extent);
8870 ASSERT(rii->cache_extent.start == root_id);
8871 ASSERT(rii->cache_extent.size == 1);
8873 if (rii->node_count != 1) {
8875 "Error: could not find btree root extent for root %llu\n",
8880 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
8881 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
8883 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
8884 btrfs_root_level(&ri) != rii->level ||
8885 btrfs_root_generation(&ri) != rii->gen) {
8888 * If we're in repair mode but our caller told us to not update
8889 * the root item, i.e. just check if it needs to be updated, don't
8890 * print this message, since the caller will call us again shortly
8891 * for the same root item without read only mode (the caller will
8892 * open a transaction first).
8894 if (!(read_only_mode && repair))
8896 "%sroot item for root %llu,"
8897 " current bytenr %llu, current gen %llu, current level %u,"
8898 " new bytenr %llu, new gen %llu, new level %u\n",
8899 (read_only_mode ? "" : "fixing "),
8901 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
8902 btrfs_root_level(&ri),
8903 rii->bytenr, rii->gen, rii->level);
8905 if (btrfs_root_generation(&ri) > rii->gen) {
8907 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
8908 root_id, btrfs_root_generation(&ri), rii->gen);
8912 if (!read_only_mode) {
8913 btrfs_set_root_bytenr(&ri, rii->bytenr);
8914 btrfs_set_root_level(&ri, rii->level);
8915 btrfs_set_root_generation(&ri, rii->gen);
8916 write_extent_buffer(path->nodes[0], &ri,
8917 offset, sizeof(ri));
8927 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
8928 * caused read-only snapshots to be corrupted if they were created at a moment
8929 * when the source subvolume/snapshot had orphan items. The issue was that the
8930 * on-disk root items became incorrect, referring to the pre orphan cleanup root
8931 * node instead of the post orphan cleanup root node.
8932 * So this function, and its callees, just detects and fixes those cases. Even
8933 * though the regression was for read-only snapshots, this function applies to
8934 * any snapshot/subvolume root.
8935 * This must be run before any other repair code - not doing it so, makes other
8936 * repair code delete or modify backrefs in the extent tree for example, which
8937 * will result in an inconsistent fs after repairing the root items.
8939 static int repair_root_items(struct btrfs_fs_info *info)
8941 struct btrfs_path *path = NULL;
8942 struct btrfs_key key;
8943 struct extent_buffer *leaf;
8944 struct btrfs_trans_handle *trans = NULL;
8949 ret = build_roots_info_cache(info);
8953 path = btrfs_alloc_path();
8959 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
8960 key.type = BTRFS_ROOT_ITEM_KEY;
8965 * Avoid opening and committing transactions if a leaf doesn't have
8966 * any root items that need to be fixed, so that we avoid rotating
8967 * backup roots unnecessarily.
8970 trans = btrfs_start_transaction(info->tree_root, 1);
8971 if (IS_ERR(trans)) {
8972 ret = PTR_ERR(trans);
8977 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
8981 leaf = path->nodes[0];
8984 struct btrfs_key found_key;
8986 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
8987 int no_more_keys = find_next_key(path, &key);
8989 btrfs_release_path(path);
8991 ret = btrfs_commit_transaction(trans,
9003 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9005 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
9007 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9010 ret = maybe_repair_root_item(info, path, &found_key,
9015 if (!trans && repair) {
9018 btrfs_release_path(path);
9028 free_roots_info_cache();
9030 btrfs_free_path(path);
9032 btrfs_commit_transaction(trans, info->tree_root);
9039 const char * const cmd_check_usage[] = {
9040 "btrfs check [options] <device>",
9041 "Check an unmounted btrfs filesystem.",
9043 "-s|--super <superblock> use this superblock copy",
9044 "-b|--backup use the backup root copy",
9045 "--repair try to repair the filesystem",
9046 "--init-csum-tree create a new CRC tree",
9047 "--init-extent-tree create a new extent tree",
9048 "--check-data-csum verify checkums of data blocks",
9049 "--qgroup-report print a report on qgroup consistency",
9050 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9051 "--tree-root <bytenr> use the given bytenr for the tree root",
9055 int cmd_check(int argc, char **argv)
9057 struct cache_tree root_cache;
9058 struct btrfs_root *root;
9059 struct btrfs_fs_info *info;
9062 u64 tree_root_bytenr = 0;
9063 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9066 int init_csum_tree = 0;
9068 int qgroup_report = 0;
9069 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9073 int option_index = 0;
9074 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9075 OPT_CHECK_CSUM, OPT_READONLY };
9076 static const struct option long_options[] = {
9077 { "super", 1, NULL, 's' },
9078 { "repair", 0, NULL, OPT_REPAIR },
9079 { "readonly", 0, NULL, OPT_READONLY },
9080 { "init-csum-tree", 0, NULL, OPT_INIT_CSUM },
9081 { "init-extent-tree", 0, NULL, OPT_INIT_EXTENT },
9082 { "check-data-csum", 0, NULL, OPT_CHECK_CSUM },
9083 { "backup", 0, NULL, 'b' },
9084 { "subvol-extents", 1, NULL, 'E' },
9085 { "qgroup-report", 0, NULL, 'Q' },
9086 { "tree-root", 1, NULL, 'r' },
9090 c = getopt_long(argc, argv, "as:br:", long_options,
9095 case 'a': /* ignored */ break;
9097 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9100 num = arg_strtou64(optarg);
9101 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9103 "ERROR: super mirror should be less than: %d\n",
9104 BTRFS_SUPER_MIRROR_MAX);
9107 bytenr = btrfs_sb_offset(((int)num));
9108 printf("using SB copy %llu, bytenr %llu\n", num,
9109 (unsigned long long)bytenr);
9115 subvolid = arg_strtou64(optarg);
9118 tree_root_bytenr = arg_strtou64(optarg);
9122 usage(cmd_check_usage);
9124 printf("enabling repair mode\n");
9126 ctree_flags |= OPEN_CTREE_WRITES;
9132 printf("Creating a new CRC tree\n");
9135 ctree_flags |= OPEN_CTREE_WRITES;
9137 case OPT_INIT_EXTENT:
9138 init_extent_tree = 1;
9139 ctree_flags |= (OPEN_CTREE_WRITES |
9140 OPEN_CTREE_NO_BLOCK_GROUPS);
9143 case OPT_CHECK_CSUM:
9144 check_data_csum = 1;
9148 argc = argc - optind;
9150 if (check_argc_exact(argc, 1))
9151 usage(cmd_check_usage);
9153 /* This check is the only reason for --readonly to exist */
9154 if (readonly && repair) {
9155 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9160 cache_tree_init(&root_cache);
9162 if((ret = check_mounted(argv[optind])) < 0) {
9163 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9166 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9171 /* only allow partial opening under repair mode */
9173 ctree_flags |= OPEN_CTREE_PARTIAL;
9175 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9178 fprintf(stderr, "Couldn't open file system\n");
9183 root = info->fs_root;
9186 * repair mode will force us to commit transaction which
9187 * will make us fail to load log tree when mounting.
9189 if (repair && btrfs_super_log_root(info->super_copy)) {
9190 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9195 ret = zero_log_tree(root);
9197 fprintf(stderr, "fail to zero log tree\n");
9202 uuid_unparse(info->super_copy->fsid, uuidbuf);
9203 if (qgroup_report) {
9204 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9206 ret = qgroup_verify_all(info);
9208 print_qgroup_report(1);
9212 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9213 subvolid, argv[optind], uuidbuf);
9214 ret = print_extent_state(info, subvolid);
9217 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9219 if (!extent_buffer_uptodate(info->tree_root->node) ||
9220 !extent_buffer_uptodate(info->dev_root->node) ||
9221 !extent_buffer_uptodate(info->chunk_root->node)) {
9222 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9227 if (init_extent_tree || init_csum_tree) {
9228 struct btrfs_trans_handle *trans;
9230 trans = btrfs_start_transaction(info->extent_root, 0);
9231 if (IS_ERR(trans)) {
9232 fprintf(stderr, "Error starting transaction\n");
9233 ret = PTR_ERR(trans);
9237 if (init_extent_tree) {
9238 printf("Creating a new extent tree\n");
9239 ret = reinit_extent_tree(trans, info);
9244 if (init_csum_tree) {
9245 fprintf(stderr, "Reinit crc root\n");
9246 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9248 fprintf(stderr, "crc root initialization failed\n");
9253 ret = fill_csum_tree(trans, info->csum_root);
9255 fprintf(stderr, "crc refilling failed\n");
9260 * Ok now we commit and run the normal fsck, which will add
9261 * extent entries for all of the items it finds.
9263 ret = btrfs_commit_transaction(trans, info->extent_root);
9267 if (!extent_buffer_uptodate(info->extent_root->node)) {
9268 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9272 if (!extent_buffer_uptodate(info->csum_root->node)) {
9273 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9278 fprintf(stderr, "checking extents\n");
9279 ret = check_chunks_and_extents(root);
9281 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9283 ret = repair_root_items(info);
9287 fprintf(stderr, "Fixed %d roots.\n", ret);
9289 } else if (ret > 0) {
9291 "Found %d roots with an outdated root item.\n",
9294 "Please run a filesystem check with the option --repair to fix them.\n");
9299 fprintf(stderr, "checking free space cache\n");
9300 ret = check_space_cache(root);
9305 * We used to have to have these hole extents in between our real
9306 * extents so if we don't have this flag set we need to make sure there
9307 * are no gaps in the file extents for inodes, otherwise we can just
9308 * ignore it when this happens.
9310 no_holes = btrfs_fs_incompat(root->fs_info,
9311 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9312 fprintf(stderr, "checking fs roots\n");
9313 ret = check_fs_roots(root, &root_cache);
9317 fprintf(stderr, "checking csums\n");
9318 ret = check_csums(root);
9322 fprintf(stderr, "checking root refs\n");
9323 ret = check_root_refs(root, &root_cache);
9327 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9328 struct extent_buffer *eb;
9330 eb = list_first_entry(&root->fs_info->recow_ebs,
9331 struct extent_buffer, recow);
9332 list_del_init(&eb->recow);
9333 ret = recow_extent_buffer(root, eb);
9338 while (!list_empty(&delete_items)) {
9339 struct bad_item *bad;
9341 bad = list_first_entry(&delete_items, struct bad_item, list);
9342 list_del_init(&bad->list);
9344 ret = delete_bad_item(root, bad);
9348 if (info->quota_enabled) {
9350 fprintf(stderr, "checking quota groups\n");
9351 err = qgroup_verify_all(info);
9356 if (!list_empty(&root->fs_info->recow_ebs)) {
9357 fprintf(stderr, "Transid errors in file system\n");
9361 print_qgroup_report(0);
9362 if (found_old_backref) { /*
9363 * there was a disk format change when mixed
9364 * backref was in testing tree. The old format
9365 * existed about one week.
9367 printf("\n * Found old mixed backref format. "
9368 "The old format is not supported! *"
9369 "\n * Please mount the FS in readonly mode, "
9370 "backup data and re-format the FS. *\n\n");
9373 printf("found %llu bytes used err is %d\n",
9374 (unsigned long long)bytes_used, ret);
9375 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9376 printf("total tree bytes: %llu\n",
9377 (unsigned long long)total_btree_bytes);
9378 printf("total fs tree bytes: %llu\n",
9379 (unsigned long long)total_fs_tree_bytes);
9380 printf("total extent tree bytes: %llu\n",
9381 (unsigned long long)total_extent_tree_bytes);
9382 printf("btree space waste bytes: %llu\n",
9383 (unsigned long long)btree_space_waste);
9384 printf("file data blocks allocated: %llu\n referenced %llu\n",
9385 (unsigned long long)data_bytes_allocated,
9386 (unsigned long long)data_bytes_referenced);
9387 printf("%s\n", PACKAGE_STRING);
9389 free_root_recs_tree(&root_cache);