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);
2367 if (ret == -EEXIST) {
2369 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2371 if (namelen + count_digits(rec->ino) + 1 >
2376 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2378 namelen += count_digits(rec->ino) + 1;
2379 ret = btrfs_add_link(trans, root, rec->ino,
2380 lost_found_ino, namebuf,
2381 namelen, type, NULL, 1);
2385 "Failed to link the inode %llu to %s dir: %s",
2386 rec->ino, dir_name, strerror(-ret));
2390 * Just increase the found_link, don't actually add the
2391 * backref. This will make things easier and this inode
2392 * record will be freed after the repair is done.
2393 * So fsck will not report problem about this inode.
2396 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2397 namelen, namebuf, dir_name);
2399 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2400 printf("Fixed the nlink of inode %llu\n", rec->ino);
2402 btrfs_release_path(path);
2407 * Check if there is any normal(reg or prealloc) file extent for given
2409 * This is used to determine the file type when neither its dir_index/item or
2410 * inode_item exists.
2412 * This will *NOT* report error, if any error happens, just consider it does
2413 * not have any normal file extent.
2415 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2417 struct btrfs_path *path;
2418 struct btrfs_key key;
2419 struct btrfs_key found_key;
2420 struct btrfs_file_extent_item *fi;
2424 path = btrfs_alloc_path();
2428 key.type = BTRFS_EXTENT_DATA_KEY;
2431 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2436 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2437 ret = btrfs_next_leaf(root, path);
2444 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2446 if (found_key.objectid != ino ||
2447 found_key.type != BTRFS_EXTENT_DATA_KEY)
2449 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2450 struct btrfs_file_extent_item);
2451 type = btrfs_file_extent_type(path->nodes[0], fi);
2452 if (type != BTRFS_FILE_EXTENT_INLINE) {
2458 btrfs_free_path(path);
2462 static u32 btrfs_type_to_imode(u8 type)
2464 static u32 imode_by_btrfs_type[] = {
2465 [BTRFS_FT_REG_FILE] = S_IFREG,
2466 [BTRFS_FT_DIR] = S_IFDIR,
2467 [BTRFS_FT_CHRDEV] = S_IFCHR,
2468 [BTRFS_FT_BLKDEV] = S_IFBLK,
2469 [BTRFS_FT_FIFO] = S_IFIFO,
2470 [BTRFS_FT_SOCK] = S_IFSOCK,
2471 [BTRFS_FT_SYMLINK] = S_IFLNK,
2474 return imode_by_btrfs_type[(type)];
2477 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2478 struct btrfs_root *root,
2479 struct btrfs_path *path,
2480 struct inode_record *rec)
2484 int type_recovered = 0;
2487 printf("Trying to rebuild inode:%llu\n", rec->ino);
2489 type_recovered = !find_file_type(rec, &filetype);
2492 * Try to determine inode type if type not found.
2494 * For found regular file extent, it must be FILE.
2495 * For found dir_item/index, it must be DIR.
2497 * For undetermined one, use FILE as fallback.
2500 * 1. If found backref(inode_index/item is already handled) to it,
2502 * Need new inode-inode ref structure to allow search for that.
2504 if (!type_recovered) {
2505 if (rec->found_file_extent &&
2506 find_normal_file_extent(root, rec->ino)) {
2508 filetype = BTRFS_FT_REG_FILE;
2509 } else if (rec->found_dir_item) {
2511 filetype = BTRFS_FT_DIR;
2512 } else if (!list_empty(&rec->orphan_extents)) {
2514 filetype = BTRFS_FT_REG_FILE;
2516 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2519 filetype = BTRFS_FT_REG_FILE;
2523 ret = btrfs_new_inode(trans, root, rec->ino,
2524 mode | btrfs_type_to_imode(filetype));
2529 * Here inode rebuild is done, we only rebuild the inode item,
2530 * don't repair the nlink(like move to lost+found).
2531 * That is the job of nlink repair.
2533 * We just fill the record and return
2535 rec->found_dir_item = 1;
2536 rec->imode = mode | btrfs_type_to_imode(filetype);
2538 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2539 /* Ensure the inode_nlinks repair function will be called */
2540 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2545 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2546 struct btrfs_root *root,
2547 struct btrfs_path *path,
2548 struct inode_record *rec)
2550 struct orphan_data_extent *orphan;
2551 struct orphan_data_extent *tmp;
2554 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2556 * Check for conflicting file extents
2558 * Here we don't know whether the extents is compressed or not,
2559 * so we can only assume it not compressed nor data offset,
2560 * and use its disk_len as extent length.
2562 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2563 orphan->offset, orphan->disk_len, 0);
2564 btrfs_release_path(path);
2569 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2570 orphan->disk_bytenr, orphan->disk_len);
2571 ret = btrfs_free_extent(trans,
2572 root->fs_info->extent_root,
2573 orphan->disk_bytenr, orphan->disk_len,
2574 0, root->objectid, orphan->objectid,
2579 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2580 orphan->offset, orphan->disk_bytenr,
2581 orphan->disk_len, orphan->disk_len);
2585 /* Update file size info */
2586 rec->found_size += orphan->disk_len;
2587 if (rec->found_size == rec->nbytes)
2588 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2590 /* Update the file extent hole info too */
2591 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2595 if (RB_EMPTY_ROOT(&rec->holes))
2596 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2598 list_del(&orphan->list);
2601 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2606 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2607 struct btrfs_root *root,
2608 struct btrfs_path *path,
2609 struct inode_record *rec)
2611 struct rb_node *node;
2612 struct file_extent_hole *hole;
2615 node = rb_first(&rec->holes);
2618 hole = rb_entry(node, struct file_extent_hole, node);
2619 ret = btrfs_punch_hole(trans, root, rec->ino,
2620 hole->start, hole->len);
2623 ret = del_file_extent_hole(&rec->holes, hole->start,
2627 if (RB_EMPTY_ROOT(&rec->holes))
2628 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2629 node = rb_first(&rec->holes);
2631 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2632 rec->ino, root->objectid);
2637 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2639 struct btrfs_trans_handle *trans;
2640 struct btrfs_path *path;
2643 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2644 I_ERR_NO_ORPHAN_ITEM |
2645 I_ERR_LINK_COUNT_WRONG |
2646 I_ERR_NO_INODE_ITEM |
2647 I_ERR_FILE_EXTENT_ORPHAN |
2648 I_ERR_FILE_EXTENT_DISCOUNT)))
2651 path = btrfs_alloc_path();
2656 * For nlink repair, it may create a dir and add link, so
2657 * 2 for parent(256)'s dir_index and dir_item
2658 * 2 for lost+found dir's inode_item and inode_ref
2659 * 1 for the new inode_ref of the file
2660 * 2 for lost+found dir's dir_index and dir_item for the file
2662 trans = btrfs_start_transaction(root, 7);
2663 if (IS_ERR(trans)) {
2664 btrfs_free_path(path);
2665 return PTR_ERR(trans);
2668 if (rec->errors & I_ERR_NO_INODE_ITEM)
2669 ret = repair_inode_no_item(trans, root, path, rec);
2670 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2671 ret = repair_inode_orphan_extent(trans, root, path, rec);
2672 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2673 ret = repair_inode_discount_extent(trans, root, path, rec);
2674 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2675 ret = repair_inode_isize(trans, root, path, rec);
2676 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2677 ret = repair_inode_orphan_item(trans, root, path, rec);
2678 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2679 ret = repair_inode_nlinks(trans, root, path, rec);
2680 btrfs_commit_transaction(trans, root);
2681 btrfs_free_path(path);
2685 static int check_inode_recs(struct btrfs_root *root,
2686 struct cache_tree *inode_cache)
2688 struct cache_extent *cache;
2689 struct ptr_node *node;
2690 struct inode_record *rec;
2691 struct inode_backref *backref;
2696 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2698 if (btrfs_root_refs(&root->root_item) == 0) {
2699 if (!cache_tree_empty(inode_cache))
2700 fprintf(stderr, "warning line %d\n", __LINE__);
2705 * We need to record the highest inode number for later 'lost+found'
2707 * We must select a ino not used/refered by any existing inode, or
2708 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2709 * this may cause 'lost+found' dir has wrong nlinks.
2711 cache = last_cache_extent(inode_cache);
2713 node = container_of(cache, struct ptr_node, cache);
2715 if (rec->ino > root->highest_inode)
2716 root->highest_inode = rec->ino;
2720 * We need to repair backrefs first because we could change some of the
2721 * errors in the inode recs.
2723 * We also need to go through and delete invalid backrefs first and then
2724 * add the correct ones second. We do this because we may get EEXIST
2725 * when adding back the correct index because we hadn't yet deleted the
2728 * For example, if we were missing a dir index then the directories
2729 * isize would be wrong, so if we fixed the isize to what we thought it
2730 * would be and then fixed the backref we'd still have a invalid fs, so
2731 * we need to add back the dir index and then check to see if the isize
2736 if (stage == 3 && !err)
2739 cache = search_cache_extent(inode_cache, 0);
2740 while (repair && cache) {
2741 node = container_of(cache, struct ptr_node, cache);
2743 cache = next_cache_extent(cache);
2745 /* Need to free everything up and rescan */
2747 remove_cache_extent(inode_cache, &node->cache);
2749 free_inode_rec(rec);
2753 if (list_empty(&rec->backrefs))
2756 ret = repair_inode_backrefs(root, rec, inode_cache,
2770 rec = get_inode_rec(inode_cache, root_dirid, 0);
2772 ret = check_root_dir(rec);
2774 fprintf(stderr, "root %llu root dir %llu error\n",
2775 (unsigned long long)root->root_key.objectid,
2776 (unsigned long long)root_dirid);
2777 print_inode_error(root, rec);
2782 struct btrfs_trans_handle *trans;
2784 trans = btrfs_start_transaction(root, 1);
2785 if (IS_ERR(trans)) {
2786 err = PTR_ERR(trans);
2791 "root %llu missing its root dir, recreating\n",
2792 (unsigned long long)root->objectid);
2794 ret = btrfs_make_root_dir(trans, root, root_dirid);
2797 btrfs_commit_transaction(trans, root);
2801 fprintf(stderr, "root %llu root dir %llu not found\n",
2802 (unsigned long long)root->root_key.objectid,
2803 (unsigned long long)root_dirid);
2807 cache = search_cache_extent(inode_cache, 0);
2810 node = container_of(cache, struct ptr_node, cache);
2812 remove_cache_extent(inode_cache, &node->cache);
2814 if (rec->ino == root_dirid ||
2815 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2816 free_inode_rec(rec);
2820 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2821 ret = check_orphan_item(root, rec->ino);
2823 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2824 if (can_free_inode_rec(rec)) {
2825 free_inode_rec(rec);
2830 if (!rec->found_inode_item)
2831 rec->errors |= I_ERR_NO_INODE_ITEM;
2832 if (rec->found_link != rec->nlink)
2833 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2835 ret = try_repair_inode(root, rec);
2836 if (ret == 0 && can_free_inode_rec(rec)) {
2837 free_inode_rec(rec);
2843 if (!(repair && ret == 0))
2845 print_inode_error(root, rec);
2846 list_for_each_entry(backref, &rec->backrefs, list) {
2847 if (!backref->found_dir_item)
2848 backref->errors |= REF_ERR_NO_DIR_ITEM;
2849 if (!backref->found_dir_index)
2850 backref->errors |= REF_ERR_NO_DIR_INDEX;
2851 if (!backref->found_inode_ref)
2852 backref->errors |= REF_ERR_NO_INODE_REF;
2853 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2854 " namelen %u name %s filetype %d errors %x",
2855 (unsigned long long)backref->dir,
2856 (unsigned long long)backref->index,
2857 backref->namelen, backref->name,
2858 backref->filetype, backref->errors);
2859 print_ref_error(backref->errors);
2861 free_inode_rec(rec);
2863 return (error > 0) ? -1 : 0;
2866 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2869 struct cache_extent *cache;
2870 struct root_record *rec = NULL;
2873 cache = lookup_cache_extent(root_cache, objectid, 1);
2875 rec = container_of(cache, struct root_record, cache);
2877 rec = calloc(1, sizeof(*rec));
2878 rec->objectid = objectid;
2879 INIT_LIST_HEAD(&rec->backrefs);
2880 rec->cache.start = objectid;
2881 rec->cache.size = 1;
2883 ret = insert_cache_extent(root_cache, &rec->cache);
2889 static struct root_backref *get_root_backref(struct root_record *rec,
2890 u64 ref_root, u64 dir, u64 index,
2891 const char *name, int namelen)
2893 struct root_backref *backref;
2895 list_for_each_entry(backref, &rec->backrefs, list) {
2896 if (backref->ref_root != ref_root || backref->dir != dir ||
2897 backref->namelen != namelen)
2899 if (memcmp(name, backref->name, namelen))
2904 backref = malloc(sizeof(*backref) + namelen + 1);
2905 memset(backref, 0, sizeof(*backref));
2906 backref->ref_root = ref_root;
2908 backref->index = index;
2909 backref->namelen = namelen;
2910 memcpy(backref->name, name, namelen);
2911 backref->name[namelen] = '\0';
2912 list_add_tail(&backref->list, &rec->backrefs);
2916 static void free_root_record(struct cache_extent *cache)
2918 struct root_record *rec;
2919 struct root_backref *backref;
2921 rec = container_of(cache, struct root_record, cache);
2922 while (!list_empty(&rec->backrefs)) {
2923 backref = list_entry(rec->backrefs.next,
2924 struct root_backref, list);
2925 list_del(&backref->list);
2932 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2934 static int add_root_backref(struct cache_tree *root_cache,
2935 u64 root_id, u64 ref_root, u64 dir, u64 index,
2936 const char *name, int namelen,
2937 int item_type, int errors)
2939 struct root_record *rec;
2940 struct root_backref *backref;
2942 rec = get_root_rec(root_cache, root_id);
2943 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2945 backref->errors |= errors;
2947 if (item_type != BTRFS_DIR_ITEM_KEY) {
2948 if (backref->found_dir_index || backref->found_back_ref ||
2949 backref->found_forward_ref) {
2950 if (backref->index != index)
2951 backref->errors |= REF_ERR_INDEX_UNMATCH;
2953 backref->index = index;
2957 if (item_type == BTRFS_DIR_ITEM_KEY) {
2958 if (backref->found_forward_ref)
2960 backref->found_dir_item = 1;
2961 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
2962 backref->found_dir_index = 1;
2963 } else if (item_type == BTRFS_ROOT_REF_KEY) {
2964 if (backref->found_forward_ref)
2965 backref->errors |= REF_ERR_DUP_ROOT_REF;
2966 else if (backref->found_dir_item)
2968 backref->found_forward_ref = 1;
2969 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
2970 if (backref->found_back_ref)
2971 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
2972 backref->found_back_ref = 1;
2977 if (backref->found_forward_ref && backref->found_dir_item)
2978 backref->reachable = 1;
2982 static int merge_root_recs(struct btrfs_root *root,
2983 struct cache_tree *src_cache,
2984 struct cache_tree *dst_cache)
2986 struct cache_extent *cache;
2987 struct ptr_node *node;
2988 struct inode_record *rec;
2989 struct inode_backref *backref;
2992 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
2993 free_inode_recs_tree(src_cache);
2998 cache = search_cache_extent(src_cache, 0);
3001 node = container_of(cache, struct ptr_node, cache);
3003 remove_cache_extent(src_cache, &node->cache);
3006 ret = is_child_root(root, root->objectid, rec->ino);
3012 list_for_each_entry(backref, &rec->backrefs, list) {
3013 BUG_ON(backref->found_inode_ref);
3014 if (backref->found_dir_item)
3015 add_root_backref(dst_cache, rec->ino,
3016 root->root_key.objectid, backref->dir,
3017 backref->index, backref->name,
3018 backref->namelen, BTRFS_DIR_ITEM_KEY,
3020 if (backref->found_dir_index)
3021 add_root_backref(dst_cache, rec->ino,
3022 root->root_key.objectid, backref->dir,
3023 backref->index, backref->name,
3024 backref->namelen, BTRFS_DIR_INDEX_KEY,
3028 free_inode_rec(rec);
3035 static int check_root_refs(struct btrfs_root *root,
3036 struct cache_tree *root_cache)
3038 struct root_record *rec;
3039 struct root_record *ref_root;
3040 struct root_backref *backref;
3041 struct cache_extent *cache;
3047 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3050 /* fixme: this can not detect circular references */
3053 cache = search_cache_extent(root_cache, 0);
3057 rec = container_of(cache, struct root_record, cache);
3058 cache = next_cache_extent(cache);
3060 if (rec->found_ref == 0)
3063 list_for_each_entry(backref, &rec->backrefs, list) {
3064 if (!backref->reachable)
3067 ref_root = get_root_rec(root_cache,
3069 if (ref_root->found_ref > 0)
3072 backref->reachable = 0;
3074 if (rec->found_ref == 0)
3080 cache = search_cache_extent(root_cache, 0);
3084 rec = container_of(cache, struct root_record, cache);
3085 cache = next_cache_extent(cache);
3087 if (rec->found_ref == 0 &&
3088 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3089 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3090 ret = check_orphan_item(root->fs_info->tree_root,
3096 * If we don't have a root item then we likely just have
3097 * a dir item in a snapshot for this root but no actual
3098 * ref key or anything so it's meaningless.
3100 if (!rec->found_root_item)
3103 fprintf(stderr, "fs tree %llu not referenced\n",
3104 (unsigned long long)rec->objectid);
3108 if (rec->found_ref > 0 && !rec->found_root_item)
3110 list_for_each_entry(backref, &rec->backrefs, list) {
3111 if (!backref->found_dir_item)
3112 backref->errors |= REF_ERR_NO_DIR_ITEM;
3113 if (!backref->found_dir_index)
3114 backref->errors |= REF_ERR_NO_DIR_INDEX;
3115 if (!backref->found_back_ref)
3116 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3117 if (!backref->found_forward_ref)
3118 backref->errors |= REF_ERR_NO_ROOT_REF;
3119 if (backref->reachable && backref->errors)
3126 fprintf(stderr, "fs tree %llu refs %u %s\n",
3127 (unsigned long long)rec->objectid, rec->found_ref,
3128 rec->found_root_item ? "" : "not found");
3130 list_for_each_entry(backref, &rec->backrefs, list) {
3131 if (!backref->reachable)
3133 if (!backref->errors && rec->found_root_item)
3135 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3136 " index %llu namelen %u name %s errors %x\n",
3137 (unsigned long long)backref->ref_root,
3138 (unsigned long long)backref->dir,
3139 (unsigned long long)backref->index,
3140 backref->namelen, backref->name,
3142 print_ref_error(backref->errors);
3145 return errors > 0 ? 1 : 0;
3148 static int process_root_ref(struct extent_buffer *eb, int slot,
3149 struct btrfs_key *key,
3150 struct cache_tree *root_cache)
3156 struct btrfs_root_ref *ref;
3157 char namebuf[BTRFS_NAME_LEN];
3160 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3162 dirid = btrfs_root_ref_dirid(eb, ref);
3163 index = btrfs_root_ref_sequence(eb, ref);
3164 name_len = btrfs_root_ref_name_len(eb, ref);
3166 if (name_len <= BTRFS_NAME_LEN) {
3170 len = BTRFS_NAME_LEN;
3171 error = REF_ERR_NAME_TOO_LONG;
3173 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3175 if (key->type == BTRFS_ROOT_REF_KEY) {
3176 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3177 index, namebuf, len, key->type, error);
3179 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3180 index, namebuf, len, key->type, error);
3185 static void free_corrupt_block(struct cache_extent *cache)
3187 struct btrfs_corrupt_block *corrupt;
3189 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3193 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3196 * Repair the btree of the given root.
3198 * The fix is to remove the node key in corrupt_blocks cache_tree.
3199 * and rebalance the tree.
3200 * After the fix, the btree should be writeable.
3202 static int repair_btree(struct btrfs_root *root,
3203 struct cache_tree *corrupt_blocks)
3205 struct btrfs_trans_handle *trans;
3206 struct btrfs_path *path;
3207 struct btrfs_corrupt_block *corrupt;
3208 struct cache_extent *cache;
3209 struct btrfs_key key;
3214 if (cache_tree_empty(corrupt_blocks))
3217 path = btrfs_alloc_path();
3221 trans = btrfs_start_transaction(root, 1);
3222 if (IS_ERR(trans)) {
3223 ret = PTR_ERR(trans);
3224 fprintf(stderr, "Error starting transaction: %s\n",
3228 cache = first_cache_extent(corrupt_blocks);
3230 corrupt = container_of(cache, struct btrfs_corrupt_block,
3232 level = corrupt->level;
3233 path->lowest_level = level;
3234 key.objectid = corrupt->key.objectid;
3235 key.type = corrupt->key.type;
3236 key.offset = corrupt->key.offset;
3239 * Here we don't want to do any tree balance, since it may
3240 * cause a balance with corrupted brother leaf/node,
3241 * so ins_len set to 0 here.
3242 * Balance will be done after all corrupt node/leaf is deleted.
3244 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3247 offset = btrfs_node_blockptr(path->nodes[level],
3248 path->slots[level]);
3250 /* Remove the ptr */
3251 ret = btrfs_del_ptr(trans, root, path, level,
3252 path->slots[level]);
3256 * Remove the corresponding extent
3257 * return value is not concerned.
3259 btrfs_release_path(path);
3260 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3261 0, root->root_key.objectid,
3263 cache = next_cache_extent(cache);
3266 /* Balance the btree using btrfs_search_slot() */
3267 cache = first_cache_extent(corrupt_blocks);
3269 corrupt = container_of(cache, struct btrfs_corrupt_block,
3271 memcpy(&key, &corrupt->key, sizeof(key));
3272 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3275 /* return will always >0 since it won't find the item */
3277 btrfs_release_path(path);
3278 cache = next_cache_extent(cache);
3281 btrfs_commit_transaction(trans, root);
3283 btrfs_free_path(path);
3287 static int check_fs_root(struct btrfs_root *root,
3288 struct cache_tree *root_cache,
3289 struct walk_control *wc)
3295 struct btrfs_path path;
3296 struct shared_node root_node;
3297 struct root_record *rec;
3298 struct btrfs_root_item *root_item = &root->root_item;
3299 struct cache_tree corrupt_blocks;
3300 struct orphan_data_extent *orphan;
3301 struct orphan_data_extent *tmp;
3302 enum btrfs_tree_block_status status;
3305 * Reuse the corrupt_block cache tree to record corrupted tree block
3307 * Unlike the usage in extent tree check, here we do it in a per
3308 * fs/subvol tree base.
3310 cache_tree_init(&corrupt_blocks);
3311 root->fs_info->corrupt_blocks = &corrupt_blocks;
3313 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3314 rec = get_root_rec(root_cache, root->root_key.objectid);
3315 if (btrfs_root_refs(root_item) > 0)
3316 rec->found_root_item = 1;
3319 btrfs_init_path(&path);
3320 memset(&root_node, 0, sizeof(root_node));
3321 cache_tree_init(&root_node.root_cache);
3322 cache_tree_init(&root_node.inode_cache);
3324 /* Move the orphan extent record to corresponding inode_record */
3325 list_for_each_entry_safe(orphan, tmp,
3326 &root->orphan_data_extents, list) {
3327 struct inode_record *inode;
3329 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3331 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3332 list_move(&orphan->list, &inode->orphan_extents);
3335 level = btrfs_header_level(root->node);
3336 memset(wc->nodes, 0, sizeof(wc->nodes));
3337 wc->nodes[level] = &root_node;
3338 wc->active_node = level;
3339 wc->root_level = level;
3341 /* We may not have checked the root block, lets do that now */
3342 if (btrfs_is_leaf(root->node))
3343 status = btrfs_check_leaf(root, NULL, root->node);
3345 status = btrfs_check_node(root, NULL, root->node);
3346 if (status != BTRFS_TREE_BLOCK_CLEAN)
3349 if (btrfs_root_refs(root_item) > 0 ||
3350 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3351 path.nodes[level] = root->node;
3352 extent_buffer_get(root->node);
3353 path.slots[level] = 0;
3355 struct btrfs_key key;
3356 struct btrfs_disk_key found_key;
3358 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3359 level = root_item->drop_level;
3360 path.lowest_level = level;
3361 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3364 btrfs_node_key(path.nodes[level], &found_key,
3366 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3367 sizeof(found_key)));
3371 wret = walk_down_tree(root, &path, wc, &level);
3377 wret = walk_up_tree(root, &path, wc, &level);
3384 btrfs_release_path(&path);
3386 if (!cache_tree_empty(&corrupt_blocks)) {
3387 struct cache_extent *cache;
3388 struct btrfs_corrupt_block *corrupt;
3390 printf("The following tree block(s) is corrupted in tree %llu:\n",
3391 root->root_key.objectid);
3392 cache = first_cache_extent(&corrupt_blocks);
3394 corrupt = container_of(cache,
3395 struct btrfs_corrupt_block,
3397 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3398 cache->start, corrupt->level,
3399 corrupt->key.objectid, corrupt->key.type,
3400 corrupt->key.offset);
3401 cache = next_cache_extent(cache);
3404 printf("Try to repair the btree for root %llu\n",
3405 root->root_key.objectid);
3406 ret = repair_btree(root, &corrupt_blocks);
3408 fprintf(stderr, "Failed to repair btree: %s\n",
3411 printf("Btree for root %llu is fixed\n",
3412 root->root_key.objectid);
3416 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3420 if (root_node.current) {
3421 root_node.current->checked = 1;
3422 maybe_free_inode_rec(&root_node.inode_cache,
3426 err = check_inode_recs(root, &root_node.inode_cache);
3430 free_corrupt_blocks_tree(&corrupt_blocks);
3431 root->fs_info->corrupt_blocks = NULL;
3432 free_orphan_data_extents(&root->orphan_data_extents);
3436 static int fs_root_objectid(u64 objectid)
3438 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3439 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3441 return is_fstree(objectid);
3444 static int check_fs_roots(struct btrfs_root *root,
3445 struct cache_tree *root_cache)
3447 struct btrfs_path path;
3448 struct btrfs_key key;
3449 struct walk_control wc;
3450 struct extent_buffer *leaf, *tree_node;
3451 struct btrfs_root *tmp_root;
3452 struct btrfs_root *tree_root = root->fs_info->tree_root;
3457 * Just in case we made any changes to the extent tree that weren't
3458 * reflected into the free space cache yet.
3461 reset_cached_block_groups(root->fs_info);
3462 memset(&wc, 0, sizeof(wc));
3463 cache_tree_init(&wc.shared);
3464 btrfs_init_path(&path);
3469 key.type = BTRFS_ROOT_ITEM_KEY;
3470 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3475 tree_node = tree_root->node;
3477 if (tree_node != tree_root->node) {
3478 free_root_recs_tree(root_cache);
3479 btrfs_release_path(&path);
3482 leaf = path.nodes[0];
3483 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3484 ret = btrfs_next_leaf(tree_root, &path);
3490 leaf = path.nodes[0];
3492 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3493 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3494 fs_root_objectid(key.objectid)) {
3495 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3496 tmp_root = btrfs_read_fs_root_no_cache(
3497 root->fs_info, &key);
3499 key.offset = (u64)-1;
3500 tmp_root = btrfs_read_fs_root(
3501 root->fs_info, &key);
3503 if (IS_ERR(tmp_root)) {
3507 ret = check_fs_root(tmp_root, root_cache, &wc);
3508 if (ret == -EAGAIN) {
3509 free_root_recs_tree(root_cache);
3510 btrfs_release_path(&path);
3515 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3516 btrfs_free_fs_root(tmp_root);
3517 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3518 key.type == BTRFS_ROOT_BACKREF_KEY) {
3519 process_root_ref(leaf, path.slots[0], &key,
3526 btrfs_release_path(&path);
3528 free_extent_cache_tree(&wc.shared);
3529 if (!cache_tree_empty(&wc.shared))
3530 fprintf(stderr, "warning line %d\n", __LINE__);
3535 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3537 struct list_head *cur = rec->backrefs.next;
3538 struct extent_backref *back;
3539 struct tree_backref *tback;
3540 struct data_backref *dback;
3544 while(cur != &rec->backrefs) {
3545 back = list_entry(cur, struct extent_backref, list);
3547 if (!back->found_extent_tree) {
3551 if (back->is_data) {
3552 dback = (struct data_backref *)back;
3553 fprintf(stderr, "Backref %llu %s %llu"
3554 " owner %llu offset %llu num_refs %lu"
3555 " not found in extent tree\n",
3556 (unsigned long long)rec->start,
3557 back->full_backref ?
3559 back->full_backref ?
3560 (unsigned long long)dback->parent:
3561 (unsigned long long)dback->root,
3562 (unsigned long long)dback->owner,
3563 (unsigned long long)dback->offset,
3564 (unsigned long)dback->num_refs);
3566 tback = (struct tree_backref *)back;
3567 fprintf(stderr, "Backref %llu parent %llu"
3568 " root %llu not found in extent tree\n",
3569 (unsigned long long)rec->start,
3570 (unsigned long long)tback->parent,
3571 (unsigned long long)tback->root);
3574 if (!back->is_data && !back->found_ref) {
3578 tback = (struct tree_backref *)back;
3579 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3580 (unsigned long long)rec->start,
3581 back->full_backref ? "parent" : "root",
3582 back->full_backref ?
3583 (unsigned long long)tback->parent :
3584 (unsigned long long)tback->root, back);
3586 if (back->is_data) {
3587 dback = (struct data_backref *)back;
3588 if (dback->found_ref != dback->num_refs) {
3592 fprintf(stderr, "Incorrect local backref count"
3593 " on %llu %s %llu owner %llu"
3594 " offset %llu found %u wanted %u back %p\n",
3595 (unsigned long long)rec->start,
3596 back->full_backref ?
3598 back->full_backref ?
3599 (unsigned long long)dback->parent:
3600 (unsigned long long)dback->root,
3601 (unsigned long long)dback->owner,
3602 (unsigned long long)dback->offset,
3603 dback->found_ref, dback->num_refs, back);
3605 if (dback->disk_bytenr != rec->start) {
3609 fprintf(stderr, "Backref disk bytenr does not"
3610 " match extent record, bytenr=%llu, "
3611 "ref bytenr=%llu\n",
3612 (unsigned long long)rec->start,
3613 (unsigned long long)dback->disk_bytenr);
3616 if (dback->bytes != rec->nr) {
3620 fprintf(stderr, "Backref bytes do not match "
3621 "extent backref, bytenr=%llu, ref "
3622 "bytes=%llu, backref bytes=%llu\n",
3623 (unsigned long long)rec->start,
3624 (unsigned long long)rec->nr,
3625 (unsigned long long)dback->bytes);
3628 if (!back->is_data) {
3631 dback = (struct data_backref *)back;
3632 found += dback->found_ref;
3635 if (found != rec->refs) {
3639 fprintf(stderr, "Incorrect global backref count "
3640 "on %llu found %llu wanted %llu\n",
3641 (unsigned long long)rec->start,
3642 (unsigned long long)found,
3643 (unsigned long long)rec->refs);
3649 static int free_all_extent_backrefs(struct extent_record *rec)
3651 struct extent_backref *back;
3652 struct list_head *cur;
3653 while (!list_empty(&rec->backrefs)) {
3654 cur = rec->backrefs.next;
3655 back = list_entry(cur, struct extent_backref, list);
3662 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3663 struct cache_tree *extent_cache)
3665 struct cache_extent *cache;
3666 struct extent_record *rec;
3669 cache = first_cache_extent(extent_cache);
3672 rec = container_of(cache, struct extent_record, cache);
3673 remove_cache_extent(extent_cache, cache);
3674 free_all_extent_backrefs(rec);
3679 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3680 struct extent_record *rec)
3682 if (rec->content_checked && rec->owner_ref_checked &&
3683 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3684 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3685 !rec->bad_full_backref) {
3686 remove_cache_extent(extent_cache, &rec->cache);
3687 free_all_extent_backrefs(rec);
3688 list_del_init(&rec->list);
3694 static int check_owner_ref(struct btrfs_root *root,
3695 struct extent_record *rec,
3696 struct extent_buffer *buf)
3698 struct extent_backref *node;
3699 struct tree_backref *back;
3700 struct btrfs_root *ref_root;
3701 struct btrfs_key key;
3702 struct btrfs_path path;
3703 struct extent_buffer *parent;
3708 list_for_each_entry(node, &rec->backrefs, list) {
3711 if (!node->found_ref)
3713 if (node->full_backref)
3715 back = (struct tree_backref *)node;
3716 if (btrfs_header_owner(buf) == back->root)
3719 BUG_ON(rec->is_root);
3721 /* try to find the block by search corresponding fs tree */
3722 key.objectid = btrfs_header_owner(buf);
3723 key.type = BTRFS_ROOT_ITEM_KEY;
3724 key.offset = (u64)-1;
3726 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3727 if (IS_ERR(ref_root))
3730 level = btrfs_header_level(buf);
3732 btrfs_item_key_to_cpu(buf, &key, 0);
3734 btrfs_node_key_to_cpu(buf, &key, 0);
3736 btrfs_init_path(&path);
3737 path.lowest_level = level + 1;
3738 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3742 parent = path.nodes[level + 1];
3743 if (parent && buf->start == btrfs_node_blockptr(parent,
3744 path.slots[level + 1]))
3747 btrfs_release_path(&path);
3748 return found ? 0 : 1;
3751 static int is_extent_tree_record(struct extent_record *rec)
3753 struct list_head *cur = rec->backrefs.next;
3754 struct extent_backref *node;
3755 struct tree_backref *back;
3758 while(cur != &rec->backrefs) {
3759 node = list_entry(cur, struct extent_backref, list);
3763 back = (struct tree_backref *)node;
3764 if (node->full_backref)
3766 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3773 static int record_bad_block_io(struct btrfs_fs_info *info,
3774 struct cache_tree *extent_cache,
3777 struct extent_record *rec;
3778 struct cache_extent *cache;
3779 struct btrfs_key key;
3781 cache = lookup_cache_extent(extent_cache, start, len);
3785 rec = container_of(cache, struct extent_record, cache);
3786 if (!is_extent_tree_record(rec))
3789 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3790 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3793 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3794 struct extent_buffer *buf, int slot)
3796 if (btrfs_header_level(buf)) {
3797 struct btrfs_key_ptr ptr1, ptr2;
3799 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3800 sizeof(struct btrfs_key_ptr));
3801 read_extent_buffer(buf, &ptr2,
3802 btrfs_node_key_ptr_offset(slot + 1),
3803 sizeof(struct btrfs_key_ptr));
3804 write_extent_buffer(buf, &ptr1,
3805 btrfs_node_key_ptr_offset(slot + 1),
3806 sizeof(struct btrfs_key_ptr));
3807 write_extent_buffer(buf, &ptr2,
3808 btrfs_node_key_ptr_offset(slot),
3809 sizeof(struct btrfs_key_ptr));
3811 struct btrfs_disk_key key;
3812 btrfs_node_key(buf, &key, 0);
3813 btrfs_fixup_low_keys(root, path, &key,
3814 btrfs_header_level(buf) + 1);
3817 struct btrfs_item *item1, *item2;
3818 struct btrfs_key k1, k2;
3819 char *item1_data, *item2_data;
3820 u32 item1_offset, item2_offset, item1_size, item2_size;
3822 item1 = btrfs_item_nr(slot);
3823 item2 = btrfs_item_nr(slot + 1);
3824 btrfs_item_key_to_cpu(buf, &k1, slot);
3825 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3826 item1_offset = btrfs_item_offset(buf, item1);
3827 item2_offset = btrfs_item_offset(buf, item2);
3828 item1_size = btrfs_item_size(buf, item1);
3829 item2_size = btrfs_item_size(buf, item2);
3831 item1_data = malloc(item1_size);
3834 item2_data = malloc(item2_size);
3840 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3841 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3843 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3844 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3848 btrfs_set_item_offset(buf, item1, item2_offset);
3849 btrfs_set_item_offset(buf, item2, item1_offset);
3850 btrfs_set_item_size(buf, item1, item2_size);
3851 btrfs_set_item_size(buf, item2, item1_size);
3853 path->slots[0] = slot;
3854 btrfs_set_item_key_unsafe(root, path, &k2);
3855 path->slots[0] = slot + 1;
3856 btrfs_set_item_key_unsafe(root, path, &k1);
3861 static int fix_key_order(struct btrfs_trans_handle *trans,
3862 struct btrfs_root *root,
3863 struct btrfs_path *path)
3865 struct extent_buffer *buf;
3866 struct btrfs_key k1, k2;
3868 int level = path->lowest_level;
3871 buf = path->nodes[level];
3872 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3874 btrfs_node_key_to_cpu(buf, &k1, i);
3875 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3877 btrfs_item_key_to_cpu(buf, &k1, i);
3878 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3880 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3882 ret = swap_values(root, path, buf, i);
3885 btrfs_mark_buffer_dirty(buf);
3891 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3892 struct btrfs_root *root,
3893 struct btrfs_path *path,
3894 struct extent_buffer *buf, int slot)
3896 struct btrfs_key key;
3897 int nritems = btrfs_header_nritems(buf);
3899 btrfs_item_key_to_cpu(buf, &key, slot);
3901 /* These are all the keys we can deal with missing. */
3902 if (key.type != BTRFS_DIR_INDEX_KEY &&
3903 key.type != BTRFS_EXTENT_ITEM_KEY &&
3904 key.type != BTRFS_METADATA_ITEM_KEY &&
3905 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3906 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3909 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3910 (unsigned long long)key.objectid, key.type,
3911 (unsigned long long)key.offset, slot, buf->start);
3912 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3913 btrfs_item_nr_offset(slot + 1),
3914 sizeof(struct btrfs_item) *
3915 (nritems - slot - 1));
3916 btrfs_set_header_nritems(buf, nritems - 1);
3918 struct btrfs_disk_key disk_key;
3920 btrfs_item_key(buf, &disk_key, 0);
3921 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3923 btrfs_mark_buffer_dirty(buf);
3927 static int fix_item_offset(struct btrfs_trans_handle *trans,
3928 struct btrfs_root *root,
3929 struct btrfs_path *path)
3931 struct extent_buffer *buf;
3935 /* We should only get this for leaves */
3936 BUG_ON(path->lowest_level);
3937 buf = path->nodes[0];
3939 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3940 unsigned int shift = 0, offset;
3942 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3943 BTRFS_LEAF_DATA_SIZE(root)) {
3944 if (btrfs_item_end_nr(buf, i) >
3945 BTRFS_LEAF_DATA_SIZE(root)) {
3946 ret = delete_bogus_item(trans, root, path,
3950 fprintf(stderr, "item is off the end of the "
3951 "leaf, can't fix\n");
3955 shift = BTRFS_LEAF_DATA_SIZE(root) -
3956 btrfs_item_end_nr(buf, i);
3957 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
3958 btrfs_item_offset_nr(buf, i - 1)) {
3959 if (btrfs_item_end_nr(buf, i) >
3960 btrfs_item_offset_nr(buf, i - 1)) {
3961 ret = delete_bogus_item(trans, root, path,
3965 fprintf(stderr, "items overlap, can't fix\n");
3969 shift = btrfs_item_offset_nr(buf, i - 1) -
3970 btrfs_item_end_nr(buf, i);
3975 printf("Shifting item nr %d by %u bytes in block %llu\n",
3976 i, shift, (unsigned long long)buf->start);
3977 offset = btrfs_item_offset_nr(buf, i);
3978 memmove_extent_buffer(buf,
3979 btrfs_leaf_data(buf) + offset + shift,
3980 btrfs_leaf_data(buf) + offset,
3981 btrfs_item_size_nr(buf, i));
3982 btrfs_set_item_offset(buf, btrfs_item_nr(i),
3984 btrfs_mark_buffer_dirty(buf);
3988 * We may have moved things, in which case we want to exit so we don't
3989 * write those changes out. Once we have proper abort functionality in
3990 * progs this can be changed to something nicer.
3997 * Attempt to fix basic block failures. If we can't fix it for whatever reason
3998 * then just return -EIO.
4000 static int try_to_fix_bad_block(struct btrfs_root *root,
4001 struct extent_buffer *buf,
4002 enum btrfs_tree_block_status status)
4004 struct btrfs_trans_handle *trans;
4005 struct ulist *roots;
4006 struct ulist_node *node;
4007 struct btrfs_root *search_root;
4008 struct btrfs_path *path;
4009 struct ulist_iterator iter;
4010 struct btrfs_key root_key, key;
4013 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4014 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4017 path = btrfs_alloc_path();
4021 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4024 btrfs_free_path(path);
4028 ULIST_ITER_INIT(&iter);
4029 while ((node = ulist_next(roots, &iter))) {
4030 root_key.objectid = node->val;
4031 root_key.type = BTRFS_ROOT_ITEM_KEY;
4032 root_key.offset = (u64)-1;
4034 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4041 trans = btrfs_start_transaction(search_root, 0);
4042 if (IS_ERR(trans)) {
4043 ret = PTR_ERR(trans);
4047 path->lowest_level = btrfs_header_level(buf);
4048 path->skip_check_block = 1;
4049 if (path->lowest_level)
4050 btrfs_node_key_to_cpu(buf, &key, 0);
4052 btrfs_item_key_to_cpu(buf, &key, 0);
4053 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4056 btrfs_commit_transaction(trans, search_root);
4059 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4060 ret = fix_key_order(trans, search_root, path);
4061 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4062 ret = fix_item_offset(trans, search_root, path);
4064 btrfs_commit_transaction(trans, search_root);
4067 btrfs_release_path(path);
4068 btrfs_commit_transaction(trans, search_root);
4071 btrfs_free_path(path);
4075 static int check_block(struct btrfs_root *root,
4076 struct cache_tree *extent_cache,
4077 struct extent_buffer *buf, u64 flags)
4079 struct extent_record *rec;
4080 struct cache_extent *cache;
4081 struct btrfs_key key;
4082 enum btrfs_tree_block_status status;
4086 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4089 rec = container_of(cache, struct extent_record, cache);
4090 rec->generation = btrfs_header_generation(buf);
4092 level = btrfs_header_level(buf);
4093 if (btrfs_header_nritems(buf) > 0) {
4096 btrfs_item_key_to_cpu(buf, &key, 0);
4098 btrfs_node_key_to_cpu(buf, &key, 0);
4100 rec->info_objectid = key.objectid;
4102 rec->info_level = level;
4104 if (btrfs_is_leaf(buf))
4105 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4107 status = btrfs_check_node(root, &rec->parent_key, buf);
4109 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4111 status = try_to_fix_bad_block(root, buf, status);
4112 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4114 fprintf(stderr, "bad block %llu\n",
4115 (unsigned long long)buf->start);
4118 * Signal to callers we need to start the scan over
4119 * again since we'll have cow'ed blocks.
4124 rec->content_checked = 1;
4125 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4126 rec->owner_ref_checked = 1;
4128 ret = check_owner_ref(root, rec, buf);
4130 rec->owner_ref_checked = 1;
4134 maybe_free_extent_rec(extent_cache, rec);
4138 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4139 u64 parent, u64 root)
4141 struct list_head *cur = rec->backrefs.next;
4142 struct extent_backref *node;
4143 struct tree_backref *back;
4145 while(cur != &rec->backrefs) {
4146 node = list_entry(cur, struct extent_backref, list);
4150 back = (struct tree_backref *)node;
4152 if (!node->full_backref)
4154 if (parent == back->parent)
4157 if (node->full_backref)
4159 if (back->root == root)
4166 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4167 u64 parent, u64 root)
4169 struct tree_backref *ref = malloc(sizeof(*ref));
4170 memset(&ref->node, 0, sizeof(ref->node));
4172 ref->parent = parent;
4173 ref->node.full_backref = 1;
4176 ref->node.full_backref = 0;
4178 list_add_tail(&ref->node.list, &rec->backrefs);
4183 static struct data_backref *find_data_backref(struct extent_record *rec,
4184 u64 parent, u64 root,
4185 u64 owner, u64 offset,
4187 u64 disk_bytenr, u64 bytes)
4189 struct list_head *cur = rec->backrefs.next;
4190 struct extent_backref *node;
4191 struct data_backref *back;
4193 while(cur != &rec->backrefs) {
4194 node = list_entry(cur, struct extent_backref, list);
4198 back = (struct data_backref *)node;
4200 if (!node->full_backref)
4202 if (parent == back->parent)
4205 if (node->full_backref)
4207 if (back->root == root && back->owner == owner &&
4208 back->offset == offset) {
4209 if (found_ref && node->found_ref &&
4210 (back->bytes != bytes ||
4211 back->disk_bytenr != disk_bytenr))
4220 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4221 u64 parent, u64 root,
4222 u64 owner, u64 offset,
4225 struct data_backref *ref = malloc(sizeof(*ref));
4226 memset(&ref->node, 0, sizeof(ref->node));
4227 ref->node.is_data = 1;
4230 ref->parent = parent;
4233 ref->node.full_backref = 1;
4237 ref->offset = offset;
4238 ref->node.full_backref = 0;
4240 ref->bytes = max_size;
4243 list_add_tail(&ref->node.list, &rec->backrefs);
4244 if (max_size > rec->max_size)
4245 rec->max_size = max_size;
4249 static int add_extent_rec(struct cache_tree *extent_cache,
4250 struct btrfs_key *parent_key, u64 parent_gen,
4251 u64 start, u64 nr, u64 extent_item_refs,
4252 int is_root, int inc_ref, int set_checked,
4253 int metadata, int extent_rec, u64 max_size)
4255 struct extent_record *rec;
4256 struct cache_extent *cache;
4260 cache = lookup_cache_extent(extent_cache, start, nr);
4262 rec = container_of(cache, struct extent_record, cache);
4266 rec->nr = max(nr, max_size);
4269 * We need to make sure to reset nr to whatever the extent
4270 * record says was the real size, this way we can compare it to
4274 if (start != rec->start || rec->found_rec) {
4275 struct extent_record *tmp;
4278 if (list_empty(&rec->list))
4279 list_add_tail(&rec->list,
4280 &duplicate_extents);
4283 * We have to do this song and dance in case we
4284 * find an extent record that falls inside of
4285 * our current extent record but does not have
4286 * the same objectid.
4288 tmp = malloc(sizeof(*tmp));
4292 tmp->max_size = max_size;
4295 tmp->metadata = metadata;
4296 tmp->extent_item_refs = extent_item_refs;
4297 INIT_LIST_HEAD(&tmp->list);
4298 list_add_tail(&tmp->list, &rec->dups);
4299 rec->num_duplicates++;
4306 if (extent_item_refs && !dup) {
4307 if (rec->extent_item_refs) {
4308 fprintf(stderr, "block %llu rec "
4309 "extent_item_refs %llu, passed %llu\n",
4310 (unsigned long long)start,
4311 (unsigned long long)
4312 rec->extent_item_refs,
4313 (unsigned long long)extent_item_refs);
4315 rec->extent_item_refs = extent_item_refs;
4320 rec->content_checked = 1;
4321 rec->owner_ref_checked = 1;
4325 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4327 rec->parent_generation = parent_gen;
4329 if (rec->max_size < max_size)
4330 rec->max_size = max_size;
4332 maybe_free_extent_rec(extent_cache, rec);
4335 rec = malloc(sizeof(*rec));
4337 rec->max_size = max_size;
4338 rec->nr = max(nr, max_size);
4339 rec->found_rec = !!extent_rec;
4340 rec->content_checked = 0;
4341 rec->owner_ref_checked = 0;
4342 rec->num_duplicates = 0;
4343 rec->metadata = metadata;
4344 rec->flag_block_full_backref = -1;
4345 rec->bad_full_backref = 0;
4346 INIT_LIST_HEAD(&rec->backrefs);
4347 INIT_LIST_HEAD(&rec->dups);
4348 INIT_LIST_HEAD(&rec->list);
4360 if (extent_item_refs)
4361 rec->extent_item_refs = extent_item_refs;
4363 rec->extent_item_refs = 0;
4366 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4368 memset(&rec->parent_key, 0, sizeof(*parent_key));
4371 rec->parent_generation = parent_gen;
4373 rec->parent_generation = 0;
4375 rec->cache.start = start;
4376 rec->cache.size = nr;
4377 ret = insert_cache_extent(extent_cache, &rec->cache);
4381 rec->content_checked = 1;
4382 rec->owner_ref_checked = 1;
4387 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4388 u64 parent, u64 root, int found_ref)
4390 struct extent_record *rec;
4391 struct tree_backref *back;
4392 struct cache_extent *cache;
4394 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4396 add_extent_rec(extent_cache, NULL, 0, bytenr,
4397 1, 0, 0, 0, 0, 1, 0, 0);
4398 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4403 rec = container_of(cache, struct extent_record, cache);
4404 if (rec->start != bytenr) {
4408 back = find_tree_backref(rec, parent, root);
4410 back = alloc_tree_backref(rec, parent, root);
4413 if (back->node.found_ref) {
4414 fprintf(stderr, "Extent back ref already exists "
4415 "for %llu parent %llu root %llu \n",
4416 (unsigned long long)bytenr,
4417 (unsigned long long)parent,
4418 (unsigned long long)root);
4420 back->node.found_ref = 1;
4422 if (back->node.found_extent_tree) {
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_extent_tree = 1;
4431 maybe_free_extent_rec(extent_cache, rec);
4435 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4436 u64 parent, u64 root, u64 owner, u64 offset,
4437 u32 num_refs, int found_ref, u64 max_size)
4439 struct extent_record *rec;
4440 struct data_backref *back;
4441 struct cache_extent *cache;
4443 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4445 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4447 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4452 rec = container_of(cache, struct extent_record, cache);
4453 if (rec->max_size < max_size)
4454 rec->max_size = max_size;
4457 * If found_ref is set then max_size is the real size and must match the
4458 * existing refs. So if we have already found a ref then we need to
4459 * make sure that this ref matches the existing one, otherwise we need
4460 * to add a new backref so we can notice that the backrefs don't match
4461 * and we need to figure out who is telling the truth. This is to
4462 * account for that awful fsync bug I introduced where we'd end up with
4463 * a btrfs_file_extent_item that would have its length include multiple
4464 * prealloc extents or point inside of a prealloc extent.
4466 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4469 back = alloc_data_backref(rec, parent, root, owner, offset,
4473 BUG_ON(num_refs != 1);
4474 if (back->node.found_ref)
4475 BUG_ON(back->bytes != max_size);
4476 back->node.found_ref = 1;
4477 back->found_ref += 1;
4478 back->bytes = max_size;
4479 back->disk_bytenr = bytenr;
4481 rec->content_checked = 1;
4482 rec->owner_ref_checked = 1;
4484 if (back->node.found_extent_tree) {
4485 fprintf(stderr, "Extent back ref already exists "
4486 "for %llu parent %llu root %llu "
4487 "owner %llu offset %llu num_refs %lu\n",
4488 (unsigned long long)bytenr,
4489 (unsigned long long)parent,
4490 (unsigned long long)root,
4491 (unsigned long long)owner,
4492 (unsigned long long)offset,
4493 (unsigned long)num_refs);
4495 back->num_refs = num_refs;
4496 back->node.found_extent_tree = 1;
4498 maybe_free_extent_rec(extent_cache, rec);
4502 static int add_pending(struct cache_tree *pending,
4503 struct cache_tree *seen, u64 bytenr, u32 size)
4506 ret = add_cache_extent(seen, bytenr, size);
4509 add_cache_extent(pending, bytenr, size);
4513 static int pick_next_pending(struct cache_tree *pending,
4514 struct cache_tree *reada,
4515 struct cache_tree *nodes,
4516 u64 last, struct block_info *bits, int bits_nr,
4519 unsigned long node_start = last;
4520 struct cache_extent *cache;
4523 cache = search_cache_extent(reada, 0);
4525 bits[0].start = cache->start;
4526 bits[0].size = cache->size;
4531 if (node_start > 32768)
4532 node_start -= 32768;
4534 cache = search_cache_extent(nodes, node_start);
4536 cache = search_cache_extent(nodes, 0);
4539 cache = search_cache_extent(pending, 0);
4544 bits[ret].start = cache->start;
4545 bits[ret].size = cache->size;
4546 cache = next_cache_extent(cache);
4548 } while (cache && ret < bits_nr);
4554 bits[ret].start = cache->start;
4555 bits[ret].size = cache->size;
4556 cache = next_cache_extent(cache);
4558 } while (cache && ret < bits_nr);
4560 if (bits_nr - ret > 8) {
4561 u64 lookup = bits[0].start + bits[0].size;
4562 struct cache_extent *next;
4563 next = search_cache_extent(pending, lookup);
4565 if (next->start - lookup > 32768)
4567 bits[ret].start = next->start;
4568 bits[ret].size = next->size;
4569 lookup = next->start + next->size;
4573 next = next_cache_extent(next);
4581 static void free_chunk_record(struct cache_extent *cache)
4583 struct chunk_record *rec;
4585 rec = container_of(cache, struct chunk_record, cache);
4586 list_del_init(&rec->list);
4587 list_del_init(&rec->dextents);
4591 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4593 cache_tree_free_extents(chunk_cache, free_chunk_record);
4596 static void free_device_record(struct rb_node *node)
4598 struct device_record *rec;
4600 rec = container_of(node, struct device_record, node);
4604 FREE_RB_BASED_TREE(device_cache, free_device_record);
4606 int insert_block_group_record(struct block_group_tree *tree,
4607 struct block_group_record *bg_rec)
4611 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4615 list_add_tail(&bg_rec->list, &tree->block_groups);
4619 static void free_block_group_record(struct cache_extent *cache)
4621 struct block_group_record *rec;
4623 rec = container_of(cache, struct block_group_record, cache);
4624 list_del_init(&rec->list);
4628 void free_block_group_tree(struct block_group_tree *tree)
4630 cache_tree_free_extents(&tree->tree, free_block_group_record);
4633 int insert_device_extent_record(struct device_extent_tree *tree,
4634 struct device_extent_record *de_rec)
4639 * Device extent is a bit different from the other extents, because
4640 * the extents which belong to the different devices may have the
4641 * same start and size, so we need use the special extent cache
4642 * search/insert functions.
4644 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4648 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4649 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4653 static void free_device_extent_record(struct cache_extent *cache)
4655 struct device_extent_record *rec;
4657 rec = container_of(cache, struct device_extent_record, cache);
4658 if (!list_empty(&rec->chunk_list))
4659 list_del_init(&rec->chunk_list);
4660 if (!list_empty(&rec->device_list))
4661 list_del_init(&rec->device_list);
4665 void free_device_extent_tree(struct device_extent_tree *tree)
4667 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4670 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4671 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4672 struct extent_buffer *leaf, int slot)
4674 struct btrfs_extent_ref_v0 *ref0;
4675 struct btrfs_key key;
4677 btrfs_item_key_to_cpu(leaf, &key, slot);
4678 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4679 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4680 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4682 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4683 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4689 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4690 struct btrfs_key *key,
4693 struct btrfs_chunk *ptr;
4694 struct chunk_record *rec;
4697 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4698 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4700 rec = malloc(btrfs_chunk_record_size(num_stripes));
4702 fprintf(stderr, "memory allocation failed\n");
4706 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4708 INIT_LIST_HEAD(&rec->list);
4709 INIT_LIST_HEAD(&rec->dextents);
4712 rec->cache.start = key->offset;
4713 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4715 rec->generation = btrfs_header_generation(leaf);
4717 rec->objectid = key->objectid;
4718 rec->type = key->type;
4719 rec->offset = key->offset;
4721 rec->length = rec->cache.size;
4722 rec->owner = btrfs_chunk_owner(leaf, ptr);
4723 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4724 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4725 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4726 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4727 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4728 rec->num_stripes = num_stripes;
4729 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4731 for (i = 0; i < rec->num_stripes; ++i) {
4732 rec->stripes[i].devid =
4733 btrfs_stripe_devid_nr(leaf, ptr, i);
4734 rec->stripes[i].offset =
4735 btrfs_stripe_offset_nr(leaf, ptr, i);
4736 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4737 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4744 static int process_chunk_item(struct cache_tree *chunk_cache,
4745 struct btrfs_key *key, struct extent_buffer *eb,
4748 struct chunk_record *rec;
4751 rec = btrfs_new_chunk_record(eb, key, slot);
4752 ret = insert_cache_extent(chunk_cache, &rec->cache);
4754 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4755 rec->offset, rec->length);
4762 static int process_device_item(struct rb_root *dev_cache,
4763 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4765 struct btrfs_dev_item *ptr;
4766 struct device_record *rec;
4769 ptr = btrfs_item_ptr(eb,
4770 slot, struct btrfs_dev_item);
4772 rec = malloc(sizeof(*rec));
4774 fprintf(stderr, "memory allocation failed\n");
4778 rec->devid = key->offset;
4779 rec->generation = btrfs_header_generation(eb);
4781 rec->objectid = key->objectid;
4782 rec->type = key->type;
4783 rec->offset = key->offset;
4785 rec->devid = btrfs_device_id(eb, ptr);
4786 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4787 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4789 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4791 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4798 struct block_group_record *
4799 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4802 struct btrfs_block_group_item *ptr;
4803 struct block_group_record *rec;
4805 rec = malloc(sizeof(*rec));
4807 fprintf(stderr, "memory allocation failed\n");
4810 memset(rec, 0, sizeof(*rec));
4812 rec->cache.start = key->objectid;
4813 rec->cache.size = key->offset;
4815 rec->generation = btrfs_header_generation(leaf);
4817 rec->objectid = key->objectid;
4818 rec->type = key->type;
4819 rec->offset = key->offset;
4821 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4822 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4824 INIT_LIST_HEAD(&rec->list);
4829 static int process_block_group_item(struct block_group_tree *block_group_cache,
4830 struct btrfs_key *key,
4831 struct extent_buffer *eb, int slot)
4833 struct block_group_record *rec;
4836 rec = btrfs_new_block_group_record(eb, key, slot);
4837 ret = insert_block_group_record(block_group_cache, rec);
4839 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4840 rec->objectid, rec->offset);
4847 struct device_extent_record *
4848 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4849 struct btrfs_key *key, int slot)
4851 struct device_extent_record *rec;
4852 struct btrfs_dev_extent *ptr;
4854 rec = malloc(sizeof(*rec));
4856 fprintf(stderr, "memory allocation failed\n");
4859 memset(rec, 0, sizeof(*rec));
4861 rec->cache.objectid = key->objectid;
4862 rec->cache.start = key->offset;
4864 rec->generation = btrfs_header_generation(leaf);
4866 rec->objectid = key->objectid;
4867 rec->type = key->type;
4868 rec->offset = key->offset;
4870 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4871 rec->chunk_objecteid =
4872 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4874 btrfs_dev_extent_chunk_offset(leaf, ptr);
4875 rec->length = btrfs_dev_extent_length(leaf, ptr);
4876 rec->cache.size = rec->length;
4878 INIT_LIST_HEAD(&rec->chunk_list);
4879 INIT_LIST_HEAD(&rec->device_list);
4885 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4886 struct btrfs_key *key, struct extent_buffer *eb,
4889 struct device_extent_record *rec;
4892 rec = btrfs_new_device_extent_record(eb, key, slot);
4893 ret = insert_device_extent_record(dev_extent_cache, rec);
4896 "Device extent[%llu, %llu, %llu] existed.\n",
4897 rec->objectid, rec->offset, rec->length);
4904 static int process_extent_item(struct btrfs_root *root,
4905 struct cache_tree *extent_cache,
4906 struct extent_buffer *eb, int slot)
4908 struct btrfs_extent_item *ei;
4909 struct btrfs_extent_inline_ref *iref;
4910 struct btrfs_extent_data_ref *dref;
4911 struct btrfs_shared_data_ref *sref;
4912 struct btrfs_key key;
4916 u32 item_size = btrfs_item_size_nr(eb, slot);
4922 btrfs_item_key_to_cpu(eb, &key, slot);
4924 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4926 num_bytes = root->leafsize;
4928 num_bytes = key.offset;
4931 if (item_size < sizeof(*ei)) {
4932 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4933 struct btrfs_extent_item_v0 *ei0;
4934 BUG_ON(item_size != sizeof(*ei0));
4935 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4936 refs = btrfs_extent_refs_v0(eb, ei0);
4940 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4941 num_bytes, refs, 0, 0, 0, metadata, 1,
4945 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4946 refs = btrfs_extent_refs(eb, ei);
4948 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
4949 refs, 0, 0, 0, metadata, 1, num_bytes);
4951 ptr = (unsigned long)(ei + 1);
4952 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
4953 key.type == BTRFS_EXTENT_ITEM_KEY)
4954 ptr += sizeof(struct btrfs_tree_block_info);
4956 end = (unsigned long)ei + item_size;
4958 iref = (struct btrfs_extent_inline_ref *)ptr;
4959 type = btrfs_extent_inline_ref_type(eb, iref);
4960 offset = btrfs_extent_inline_ref_offset(eb, iref);
4962 case BTRFS_TREE_BLOCK_REF_KEY:
4963 add_tree_backref(extent_cache, key.objectid,
4966 case BTRFS_SHARED_BLOCK_REF_KEY:
4967 add_tree_backref(extent_cache, key.objectid,
4970 case BTRFS_EXTENT_DATA_REF_KEY:
4971 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
4972 add_data_backref(extent_cache, key.objectid, 0,
4973 btrfs_extent_data_ref_root(eb, dref),
4974 btrfs_extent_data_ref_objectid(eb,
4976 btrfs_extent_data_ref_offset(eb, dref),
4977 btrfs_extent_data_ref_count(eb, dref),
4980 case BTRFS_SHARED_DATA_REF_KEY:
4981 sref = (struct btrfs_shared_data_ref *)(iref + 1);
4982 add_data_backref(extent_cache, key.objectid, offset,
4984 btrfs_shared_data_ref_count(eb, sref),
4988 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
4989 key.objectid, key.type, num_bytes);
4992 ptr += btrfs_extent_inline_ref_size(type);
4999 static int check_cache_range(struct btrfs_root *root,
5000 struct btrfs_block_group_cache *cache,
5001 u64 offset, u64 bytes)
5003 struct btrfs_free_space *entry;
5009 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5010 bytenr = btrfs_sb_offset(i);
5011 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5012 cache->key.objectid, bytenr, 0,
5013 &logical, &nr, &stripe_len);
5018 if (logical[nr] + stripe_len <= offset)
5020 if (offset + bytes <= logical[nr])
5022 if (logical[nr] == offset) {
5023 if (stripe_len >= bytes) {
5027 bytes -= stripe_len;
5028 offset += stripe_len;
5029 } else if (logical[nr] < offset) {
5030 if (logical[nr] + stripe_len >=
5035 bytes = (offset + bytes) -
5036 (logical[nr] + stripe_len);
5037 offset = logical[nr] + stripe_len;
5040 * Could be tricky, the super may land in the
5041 * middle of the area we're checking. First
5042 * check the easiest case, it's at the end.
5044 if (logical[nr] + stripe_len >=
5046 bytes = logical[nr] - offset;
5050 /* Check the left side */
5051 ret = check_cache_range(root, cache,
5053 logical[nr] - offset);
5059 /* Now we continue with the right side */
5060 bytes = (offset + bytes) -
5061 (logical[nr] + stripe_len);
5062 offset = logical[nr] + stripe_len;
5069 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5071 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5072 offset, offset+bytes);
5076 if (entry->offset != offset) {
5077 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5082 if (entry->bytes != bytes) {
5083 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5084 bytes, entry->bytes, offset);
5088 unlink_free_space(cache->free_space_ctl, entry);
5093 static int verify_space_cache(struct btrfs_root *root,
5094 struct btrfs_block_group_cache *cache)
5096 struct btrfs_path *path;
5097 struct extent_buffer *leaf;
5098 struct btrfs_key key;
5102 path = btrfs_alloc_path();
5106 root = root->fs_info->extent_root;
5108 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5110 key.objectid = last;
5112 key.type = BTRFS_EXTENT_ITEM_KEY;
5114 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5119 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5120 ret = btrfs_next_leaf(root, path);
5128 leaf = path->nodes[0];
5129 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5130 if (key.objectid >= cache->key.offset + cache->key.objectid)
5132 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5133 key.type != BTRFS_METADATA_ITEM_KEY) {
5138 if (last == key.objectid) {
5139 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5140 last = key.objectid + key.offset;
5142 last = key.objectid + root->leafsize;
5147 ret = check_cache_range(root, cache, last,
5148 key.objectid - last);
5151 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5152 last = key.objectid + key.offset;
5154 last = key.objectid + root->leafsize;
5158 if (last < cache->key.objectid + cache->key.offset)
5159 ret = check_cache_range(root, cache, last,
5160 cache->key.objectid +
5161 cache->key.offset - last);
5164 btrfs_free_path(path);
5167 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5168 fprintf(stderr, "There are still entries left in the space "
5176 static int check_space_cache(struct btrfs_root *root)
5178 struct btrfs_block_group_cache *cache;
5179 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5183 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5184 btrfs_super_generation(root->fs_info->super_copy) !=
5185 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5186 printf("cache and super generation don't match, space cache "
5187 "will be invalidated\n");
5192 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5196 start = cache->key.objectid + cache->key.offset;
5197 if (!cache->free_space_ctl) {
5198 if (btrfs_init_free_space_ctl(cache,
5199 root->sectorsize)) {
5204 btrfs_remove_free_space_cache(cache);
5207 ret = load_free_space_cache(root->fs_info, cache);
5211 ret = verify_space_cache(root, cache);
5213 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5214 cache->key.objectid);
5219 return error ? -EINVAL : 0;
5222 static int read_extent_data(struct btrfs_root *root, char *data,
5223 u64 logical, u64 *len, int mirror)
5226 struct btrfs_multi_bio *multi = NULL;
5227 struct btrfs_fs_info *info = root->fs_info;
5228 struct btrfs_device *device;
5232 ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
5233 &multi, mirror, NULL);
5235 fprintf(stderr, "Couldn't map the block %llu\n",
5239 device = multi->stripes[0].dev;
5241 if (device->fd == 0)
5246 ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
5256 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5257 u64 num_bytes, unsigned long leaf_offset,
5258 struct extent_buffer *eb) {
5261 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5263 unsigned long csum_offset;
5267 u64 data_checked = 0;
5273 if (num_bytes % root->sectorsize)
5276 data = malloc(num_bytes);
5280 while (offset < num_bytes) {
5283 read_len = num_bytes - offset;
5284 /* read as much space once a time */
5285 ret = read_extent_data(root, data + offset,
5286 bytenr + offset, &read_len, mirror);
5290 /* verify every 4k data's checksum */
5291 while (data_checked < read_len) {
5293 tmp = offset + data_checked;
5295 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5296 csum, root->sectorsize);
5297 btrfs_csum_final(csum, (char *)&csum);
5299 csum_offset = leaf_offset +
5300 tmp / root->sectorsize * csum_size;
5301 read_extent_buffer(eb, (char *)&csum_expected,
5302 csum_offset, csum_size);
5303 /* try another mirror */
5304 if (csum != csum_expected) {
5305 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5306 mirror, bytenr + tmp,
5307 csum, csum_expected);
5308 num_copies = btrfs_num_copies(
5309 &root->fs_info->mapping_tree,
5311 if (mirror < num_copies - 1) {
5316 data_checked += root->sectorsize;
5325 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5328 struct btrfs_path *path;
5329 struct extent_buffer *leaf;
5330 struct btrfs_key key;
5333 path = btrfs_alloc_path();
5335 fprintf(stderr, "Error allocing path\n");
5339 key.objectid = bytenr;
5340 key.type = BTRFS_EXTENT_ITEM_KEY;
5341 key.offset = (u64)-1;
5344 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5347 fprintf(stderr, "Error looking up extent record %d\n", ret);
5348 btrfs_free_path(path);
5351 if (path->slots[0] > 0) {
5354 ret = btrfs_prev_leaf(root, path);
5357 } else if (ret > 0) {
5364 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5367 * Block group items come before extent items if they have the same
5368 * bytenr, so walk back one more just in case. Dear future traveler,
5369 * first congrats on mastering time travel. Now if it's not too much
5370 * trouble could you go back to 2006 and tell Chris to make the
5371 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5372 * EXTENT_ITEM_KEY please?
5374 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5375 if (path->slots[0] > 0) {
5378 ret = btrfs_prev_leaf(root, path);
5381 } else if (ret > 0) {
5386 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5390 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5391 ret = btrfs_next_leaf(root, path);
5393 fprintf(stderr, "Error going to next leaf "
5395 btrfs_free_path(path);
5401 leaf = path->nodes[0];
5402 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5403 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5407 if (key.objectid + key.offset < bytenr) {
5411 if (key.objectid > bytenr + num_bytes)
5414 if (key.objectid == bytenr) {
5415 if (key.offset >= num_bytes) {
5419 num_bytes -= key.offset;
5420 bytenr += key.offset;
5421 } else if (key.objectid < bytenr) {
5422 if (key.objectid + key.offset >= bytenr + num_bytes) {
5426 num_bytes = (bytenr + num_bytes) -
5427 (key.objectid + key.offset);
5428 bytenr = key.objectid + key.offset;
5430 if (key.objectid + key.offset < bytenr + num_bytes) {
5431 u64 new_start = key.objectid + key.offset;
5432 u64 new_bytes = bytenr + num_bytes - new_start;
5435 * Weird case, the extent is in the middle of
5436 * our range, we'll have to search one side
5437 * and then the other. Not sure if this happens
5438 * in real life, but no harm in coding it up
5439 * anyway just in case.
5441 btrfs_release_path(path);
5442 ret = check_extent_exists(root, new_start,
5445 fprintf(stderr, "Right section didn't "
5449 num_bytes = key.objectid - bytenr;
5452 num_bytes = key.objectid - bytenr;
5459 if (num_bytes && !ret) {
5460 fprintf(stderr, "There are no extents for csum range "
5461 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5465 btrfs_free_path(path);
5469 static int check_csums(struct btrfs_root *root)
5471 struct btrfs_path *path;
5472 struct extent_buffer *leaf;
5473 struct btrfs_key key;
5474 u64 offset = 0, num_bytes = 0;
5475 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5479 unsigned long leaf_offset;
5481 root = root->fs_info->csum_root;
5482 if (!extent_buffer_uptodate(root->node)) {
5483 fprintf(stderr, "No valid csum tree found\n");
5487 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5488 key.type = BTRFS_EXTENT_CSUM_KEY;
5491 path = btrfs_alloc_path();
5495 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5497 fprintf(stderr, "Error searching csum tree %d\n", ret);
5498 btrfs_free_path(path);
5502 if (ret > 0 && path->slots[0])
5507 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5508 ret = btrfs_next_leaf(root, path);
5510 fprintf(stderr, "Error going to next leaf "
5517 leaf = path->nodes[0];
5519 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5520 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5525 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5526 csum_size) * root->sectorsize;
5527 if (!check_data_csum)
5528 goto skip_csum_check;
5529 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5530 ret = check_extent_csums(root, key.offset, data_len,
5536 offset = key.offset;
5537 } else if (key.offset != offset + num_bytes) {
5538 ret = check_extent_exists(root, offset, num_bytes);
5540 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5541 "there is no extent record\n",
5542 offset, offset+num_bytes);
5545 offset = key.offset;
5548 num_bytes += data_len;
5552 btrfs_free_path(path);
5556 static int is_dropped_key(struct btrfs_key *key,
5557 struct btrfs_key *drop_key) {
5558 if (key->objectid < drop_key->objectid)
5560 else if (key->objectid == drop_key->objectid) {
5561 if (key->type < drop_key->type)
5563 else if (key->type == drop_key->type) {
5564 if (key->offset < drop_key->offset)
5572 * Here are the rules for FULL_BACKREF.
5574 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5575 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5577 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5578 * if it happened after the relocation occurred since we'll have dropped the
5579 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5580 * have no real way to know for sure.
5582 * We process the blocks one root at a time, and we start from the lowest root
5583 * objectid and go to the highest. So we can just lookup the owner backref for
5584 * the record and if we don't find it then we know it doesn't exist and we have
5587 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5588 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5589 * be set or not and then we can check later once we've gathered all the refs.
5591 static int calc_extent_flag(struct btrfs_root *root,
5592 struct cache_tree *extent_cache,
5593 struct extent_buffer *buf,
5594 struct root_item_record *ri,
5597 struct extent_record *rec;
5598 struct cache_extent *cache;
5599 struct tree_backref *tback;
5602 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5603 /* we have added this extent before */
5605 rec = container_of(cache, struct extent_record, cache);
5608 * Except file/reloc tree, we can not have
5611 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5616 if (buf->start == ri->bytenr)
5619 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5622 owner = btrfs_header_owner(buf);
5623 if (owner == ri->objectid)
5626 tback = find_tree_backref(rec, 0, owner);
5631 if (rec->flag_block_full_backref != -1 &&
5632 rec->flag_block_full_backref != 0)
5633 rec->bad_full_backref = 1;
5636 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5637 if (rec->flag_block_full_backref != -1 &&
5638 rec->flag_block_full_backref != 1)
5639 rec->bad_full_backref = 1;
5643 static int run_next_block(struct btrfs_root *root,
5644 struct block_info *bits,
5647 struct cache_tree *pending,
5648 struct cache_tree *seen,
5649 struct cache_tree *reada,
5650 struct cache_tree *nodes,
5651 struct cache_tree *extent_cache,
5652 struct cache_tree *chunk_cache,
5653 struct rb_root *dev_cache,
5654 struct block_group_tree *block_group_cache,
5655 struct device_extent_tree *dev_extent_cache,
5656 struct root_item_record *ri)
5658 struct extent_buffer *buf;
5659 struct extent_record *rec = NULL;
5670 struct btrfs_key key;
5671 struct cache_extent *cache;
5674 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5675 bits_nr, &reada_bits);
5680 for(i = 0; i < nritems; i++) {
5681 ret = add_cache_extent(reada, bits[i].start,
5686 /* fixme, get the parent transid */
5687 readahead_tree_block(root, bits[i].start,
5691 *last = bits[0].start;
5692 bytenr = bits[0].start;
5693 size = bits[0].size;
5695 cache = lookup_cache_extent(pending, bytenr, size);
5697 remove_cache_extent(pending, cache);
5700 cache = lookup_cache_extent(reada, bytenr, size);
5702 remove_cache_extent(reada, cache);
5705 cache = lookup_cache_extent(nodes, bytenr, size);
5707 remove_cache_extent(nodes, cache);
5710 cache = lookup_cache_extent(extent_cache, bytenr, size);
5712 rec = container_of(cache, struct extent_record, cache);
5713 gen = rec->parent_generation;
5716 /* fixme, get the real parent transid */
5717 buf = read_tree_block(root, bytenr, size, gen);
5718 if (!extent_buffer_uptodate(buf)) {
5719 record_bad_block_io(root->fs_info,
5720 extent_cache, bytenr, size);
5724 nritems = btrfs_header_nritems(buf);
5727 if (!init_extent_tree) {
5728 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5729 btrfs_header_level(buf), 1, NULL,
5732 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5734 fprintf(stderr, "Couldn't calc extent flags\n");
5735 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5740 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5742 fprintf(stderr, "Couldn't calc extent flags\n");
5743 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5747 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5749 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5750 ri->objectid == btrfs_header_owner(buf)) {
5752 * Ok we got to this block from it's original owner and
5753 * we have FULL_BACKREF set. Relocation can leave
5754 * converted blocks over so this is altogether possible,
5755 * however it's not possible if the generation > the
5756 * last snapshot, so check for this case.
5758 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5759 btrfs_header_generation(buf) > ri->last_snapshot) {
5760 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5761 rec->bad_full_backref = 1;
5766 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5767 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5768 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5769 rec->bad_full_backref = 1;
5773 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5774 rec->flag_block_full_backref = 1;
5778 rec->flag_block_full_backref = 0;
5780 owner = btrfs_header_owner(buf);
5783 ret = check_block(root, extent_cache, buf, flags);
5787 if (btrfs_is_leaf(buf)) {
5788 btree_space_waste += btrfs_leaf_free_space(root, buf);
5789 for (i = 0; i < nritems; i++) {
5790 struct btrfs_file_extent_item *fi;
5791 btrfs_item_key_to_cpu(buf, &key, i);
5792 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5793 process_extent_item(root, extent_cache, buf,
5797 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5798 process_extent_item(root, extent_cache, buf,
5802 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5804 btrfs_item_size_nr(buf, i);
5807 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5808 process_chunk_item(chunk_cache, &key, buf, i);
5811 if (key.type == BTRFS_DEV_ITEM_KEY) {
5812 process_device_item(dev_cache, &key, buf, i);
5815 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5816 process_block_group_item(block_group_cache,
5820 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5821 process_device_extent_item(dev_extent_cache,
5826 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5827 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5828 process_extent_ref_v0(extent_cache, buf, i);
5835 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5836 add_tree_backref(extent_cache, key.objectid, 0,
5840 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5841 add_tree_backref(extent_cache, key.objectid,
5845 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5846 struct btrfs_extent_data_ref *ref;
5847 ref = btrfs_item_ptr(buf, i,
5848 struct btrfs_extent_data_ref);
5849 add_data_backref(extent_cache,
5851 btrfs_extent_data_ref_root(buf, ref),
5852 btrfs_extent_data_ref_objectid(buf,
5854 btrfs_extent_data_ref_offset(buf, ref),
5855 btrfs_extent_data_ref_count(buf, ref),
5856 0, root->sectorsize);
5859 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5860 struct btrfs_shared_data_ref *ref;
5861 ref = btrfs_item_ptr(buf, i,
5862 struct btrfs_shared_data_ref);
5863 add_data_backref(extent_cache,
5864 key.objectid, key.offset, 0, 0, 0,
5865 btrfs_shared_data_ref_count(buf, ref),
5866 0, root->sectorsize);
5869 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5870 struct bad_item *bad;
5872 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5876 bad = malloc(sizeof(struct bad_item));
5879 INIT_LIST_HEAD(&bad->list);
5880 memcpy(&bad->key, &key,
5881 sizeof(struct btrfs_key));
5882 bad->root_id = owner;
5883 list_add_tail(&bad->list, &delete_items);
5886 if (key.type != BTRFS_EXTENT_DATA_KEY)
5888 fi = btrfs_item_ptr(buf, i,
5889 struct btrfs_file_extent_item);
5890 if (btrfs_file_extent_type(buf, fi) ==
5891 BTRFS_FILE_EXTENT_INLINE)
5893 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5896 data_bytes_allocated +=
5897 btrfs_file_extent_disk_num_bytes(buf, fi);
5898 if (data_bytes_allocated < root->sectorsize) {
5901 data_bytes_referenced +=
5902 btrfs_file_extent_num_bytes(buf, fi);
5903 add_data_backref(extent_cache,
5904 btrfs_file_extent_disk_bytenr(buf, fi),
5905 parent, owner, key.objectid, key.offset -
5906 btrfs_file_extent_offset(buf, fi), 1, 1,
5907 btrfs_file_extent_disk_num_bytes(buf, fi));
5911 struct btrfs_key first_key;
5913 first_key.objectid = 0;
5916 btrfs_item_key_to_cpu(buf, &first_key, 0);
5917 level = btrfs_header_level(buf);
5918 for (i = 0; i < nritems; i++) {
5919 ptr = btrfs_node_blockptr(buf, i);
5920 size = btrfs_level_size(root, level - 1);
5921 btrfs_node_key_to_cpu(buf, &key, i);
5923 if ((level == ri->drop_level)
5924 && is_dropped_key(&key, &ri->drop_key)) {
5928 ret = add_extent_rec(extent_cache, &key,
5929 btrfs_node_ptr_generation(buf, i),
5930 ptr, size, 0, 0, 1, 0, 1, 0,
5934 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5937 add_pending(nodes, seen, ptr, size);
5939 add_pending(pending, seen, ptr, size);
5942 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5943 nritems) * sizeof(struct btrfs_key_ptr);
5945 total_btree_bytes += buf->len;
5946 if (fs_root_objectid(btrfs_header_owner(buf)))
5947 total_fs_tree_bytes += buf->len;
5948 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5949 total_extent_tree_bytes += buf->len;
5950 if (!found_old_backref &&
5951 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5952 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5953 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5954 found_old_backref = 1;
5956 free_extent_buffer(buf);
5960 static int add_root_to_pending(struct extent_buffer *buf,
5961 struct cache_tree *extent_cache,
5962 struct cache_tree *pending,
5963 struct cache_tree *seen,
5964 struct cache_tree *nodes,
5967 if (btrfs_header_level(buf) > 0)
5968 add_pending(nodes, seen, buf->start, buf->len);
5970 add_pending(pending, seen, buf->start, buf->len);
5971 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5972 0, 1, 1, 0, 1, 0, buf->len);
5974 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5975 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5976 add_tree_backref(extent_cache, buf->start, buf->start,
5979 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
5983 /* as we fix the tree, we might be deleting blocks that
5984 * we're tracking for repair. This hook makes sure we
5985 * remove any backrefs for blocks as we are fixing them.
5987 static int free_extent_hook(struct btrfs_trans_handle *trans,
5988 struct btrfs_root *root,
5989 u64 bytenr, u64 num_bytes, u64 parent,
5990 u64 root_objectid, u64 owner, u64 offset,
5993 struct extent_record *rec;
5994 struct cache_extent *cache;
5996 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
5998 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
5999 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6003 rec = container_of(cache, struct extent_record, cache);
6005 struct data_backref *back;
6006 back = find_data_backref(rec, parent, root_objectid, owner,
6007 offset, 1, bytenr, num_bytes);
6010 if (back->node.found_ref) {
6011 back->found_ref -= refs_to_drop;
6013 rec->refs -= refs_to_drop;
6015 if (back->node.found_extent_tree) {
6016 back->num_refs -= refs_to_drop;
6017 if (rec->extent_item_refs)
6018 rec->extent_item_refs -= refs_to_drop;
6020 if (back->found_ref == 0)
6021 back->node.found_ref = 0;
6022 if (back->num_refs == 0)
6023 back->node.found_extent_tree = 0;
6025 if (!back->node.found_extent_tree && back->node.found_ref) {
6026 list_del(&back->node.list);
6030 struct tree_backref *back;
6031 back = find_tree_backref(rec, parent, root_objectid);
6034 if (back->node.found_ref) {
6037 back->node.found_ref = 0;
6039 if (back->node.found_extent_tree) {
6040 if (rec->extent_item_refs)
6041 rec->extent_item_refs--;
6042 back->node.found_extent_tree = 0;
6044 if (!back->node.found_extent_tree && back->node.found_ref) {
6045 list_del(&back->node.list);
6049 maybe_free_extent_rec(extent_cache, rec);
6054 static int delete_extent_records(struct btrfs_trans_handle *trans,
6055 struct btrfs_root *root,
6056 struct btrfs_path *path,
6057 u64 bytenr, u64 new_len)
6059 struct btrfs_key key;
6060 struct btrfs_key found_key;
6061 struct extent_buffer *leaf;
6066 key.objectid = bytenr;
6068 key.offset = (u64)-1;
6071 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6078 if (path->slots[0] == 0)
6084 leaf = path->nodes[0];
6085 slot = path->slots[0];
6087 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6088 if (found_key.objectid != bytenr)
6091 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6092 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6093 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6094 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6095 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6096 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6097 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6098 btrfs_release_path(path);
6099 if (found_key.type == 0) {
6100 if (found_key.offset == 0)
6102 key.offset = found_key.offset - 1;
6103 key.type = found_key.type;
6105 key.type = found_key.type - 1;
6106 key.offset = (u64)-1;
6110 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6111 found_key.objectid, found_key.type, found_key.offset);
6113 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6116 btrfs_release_path(path);
6118 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6119 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6120 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6121 found_key.offset : root->leafsize;
6123 ret = btrfs_update_block_group(trans, root, bytenr,
6130 btrfs_release_path(path);
6135 * for a single backref, this will allocate a new extent
6136 * and add the backref to it.
6138 static int record_extent(struct btrfs_trans_handle *trans,
6139 struct btrfs_fs_info *info,
6140 struct btrfs_path *path,
6141 struct extent_record *rec,
6142 struct extent_backref *back,
6143 int allocated, u64 flags)
6146 struct btrfs_root *extent_root = info->extent_root;
6147 struct extent_buffer *leaf;
6148 struct btrfs_key ins_key;
6149 struct btrfs_extent_item *ei;
6150 struct tree_backref *tback;
6151 struct data_backref *dback;
6152 struct btrfs_tree_block_info *bi;
6155 rec->max_size = max_t(u64, rec->max_size,
6156 info->extent_root->leafsize);
6159 u32 item_size = sizeof(*ei);
6162 item_size += sizeof(*bi);
6164 ins_key.objectid = rec->start;
6165 ins_key.offset = rec->max_size;
6166 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6168 ret = btrfs_insert_empty_item(trans, extent_root, path,
6169 &ins_key, item_size);
6173 leaf = path->nodes[0];
6174 ei = btrfs_item_ptr(leaf, path->slots[0],
6175 struct btrfs_extent_item);
6177 btrfs_set_extent_refs(leaf, ei, 0);
6178 btrfs_set_extent_generation(leaf, ei, rec->generation);
6180 if (back->is_data) {
6181 btrfs_set_extent_flags(leaf, ei,
6182 BTRFS_EXTENT_FLAG_DATA);
6184 struct btrfs_disk_key copy_key;;
6186 tback = (struct tree_backref *)back;
6187 bi = (struct btrfs_tree_block_info *)(ei + 1);
6188 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6191 btrfs_set_disk_key_objectid(©_key,
6192 rec->info_objectid);
6193 btrfs_set_disk_key_type(©_key, 0);
6194 btrfs_set_disk_key_offset(©_key, 0);
6196 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6197 btrfs_set_tree_block_key(leaf, bi, ©_key);
6199 btrfs_set_extent_flags(leaf, ei,
6200 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6203 btrfs_mark_buffer_dirty(leaf);
6204 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6205 rec->max_size, 1, 0);
6208 btrfs_release_path(path);
6211 if (back->is_data) {
6215 dback = (struct data_backref *)back;
6216 if (back->full_backref)
6217 parent = dback->parent;
6221 for (i = 0; i < dback->found_ref; i++) {
6222 /* if parent != 0, we're doing a full backref
6223 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6224 * just makes the backref allocator create a data
6227 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6228 rec->start, rec->max_size,
6232 BTRFS_FIRST_FREE_OBJECTID :
6238 fprintf(stderr, "adding new data backref"
6239 " on %llu %s %llu owner %llu"
6240 " offset %llu found %d\n",
6241 (unsigned long long)rec->start,
6242 back->full_backref ?
6244 back->full_backref ?
6245 (unsigned long long)parent :
6246 (unsigned long long)dback->root,
6247 (unsigned long long)dback->owner,
6248 (unsigned long long)dback->offset,
6253 tback = (struct tree_backref *)back;
6254 if (back->full_backref)
6255 parent = tback->parent;
6259 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6260 rec->start, rec->max_size,
6261 parent, tback->root, 0, 0);
6262 fprintf(stderr, "adding new tree backref on "
6263 "start %llu len %llu parent %llu root %llu\n",
6264 rec->start, rec->max_size, parent, tback->root);
6269 btrfs_release_path(path);
6273 struct extent_entry {
6278 struct list_head list;
6281 static struct extent_entry *find_entry(struct list_head *entries,
6282 u64 bytenr, u64 bytes)
6284 struct extent_entry *entry = NULL;
6286 list_for_each_entry(entry, entries, list) {
6287 if (entry->bytenr == bytenr && entry->bytes == bytes)
6294 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6296 struct extent_entry *entry, *best = NULL, *prev = NULL;
6298 list_for_each_entry(entry, entries, list) {
6305 * If there are as many broken entries as entries then we know
6306 * not to trust this particular entry.
6308 if (entry->broken == entry->count)
6312 * If our current entry == best then we can't be sure our best
6313 * is really the best, so we need to keep searching.
6315 if (best && best->count == entry->count) {
6321 /* Prev == entry, not good enough, have to keep searching */
6322 if (!prev->broken && prev->count == entry->count)
6326 best = (prev->count > entry->count) ? prev : entry;
6327 else if (best->count < entry->count)
6335 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6336 struct data_backref *dback, struct extent_entry *entry)
6338 struct btrfs_trans_handle *trans;
6339 struct btrfs_root *root;
6340 struct btrfs_file_extent_item *fi;
6341 struct extent_buffer *leaf;
6342 struct btrfs_key key;
6346 key.objectid = dback->root;
6347 key.type = BTRFS_ROOT_ITEM_KEY;
6348 key.offset = (u64)-1;
6349 root = btrfs_read_fs_root(info, &key);
6351 fprintf(stderr, "Couldn't find root for our ref\n");
6356 * The backref points to the original offset of the extent if it was
6357 * split, so we need to search down to the offset we have and then walk
6358 * forward until we find the backref we're looking for.
6360 key.objectid = dback->owner;
6361 key.type = BTRFS_EXTENT_DATA_KEY;
6362 key.offset = dback->offset;
6363 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6365 fprintf(stderr, "Error looking up ref %d\n", ret);
6370 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6371 ret = btrfs_next_leaf(root, path);
6373 fprintf(stderr, "Couldn't find our ref, next\n");
6377 leaf = path->nodes[0];
6378 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6379 if (key.objectid != dback->owner ||
6380 key.type != BTRFS_EXTENT_DATA_KEY) {
6381 fprintf(stderr, "Couldn't find our ref, search\n");
6384 fi = btrfs_item_ptr(leaf, path->slots[0],
6385 struct btrfs_file_extent_item);
6386 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6387 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6389 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6394 btrfs_release_path(path);
6396 trans = btrfs_start_transaction(root, 1);
6398 return PTR_ERR(trans);
6401 * Ok we have the key of the file extent we want to fix, now we can cow
6402 * down to the thing and fix it.
6404 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6406 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6407 key.objectid, key.type, key.offset, ret);
6411 fprintf(stderr, "Well that's odd, we just found this key "
6412 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6417 leaf = path->nodes[0];
6418 fi = btrfs_item_ptr(leaf, path->slots[0],
6419 struct btrfs_file_extent_item);
6421 if (btrfs_file_extent_compression(leaf, fi) &&
6422 dback->disk_bytenr != entry->bytenr) {
6423 fprintf(stderr, "Ref doesn't match the record start and is "
6424 "compressed, please take a btrfs-image of this file "
6425 "system and send it to a btrfs developer so they can "
6426 "complete this functionality for bytenr %Lu\n",
6427 dback->disk_bytenr);
6432 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6433 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6434 } else if (dback->disk_bytenr > entry->bytenr) {
6435 u64 off_diff, offset;
6437 off_diff = dback->disk_bytenr - entry->bytenr;
6438 offset = btrfs_file_extent_offset(leaf, fi);
6439 if (dback->disk_bytenr + offset +
6440 btrfs_file_extent_num_bytes(leaf, fi) >
6441 entry->bytenr + entry->bytes) {
6442 fprintf(stderr, "Ref is past the entry end, please "
6443 "take a btrfs-image of this file system and "
6444 "send it to a btrfs developer, ref %Lu\n",
6445 dback->disk_bytenr);
6450 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6451 btrfs_set_file_extent_offset(leaf, fi, offset);
6452 } else if (dback->disk_bytenr < entry->bytenr) {
6455 offset = btrfs_file_extent_offset(leaf, fi);
6456 if (dback->disk_bytenr + offset < entry->bytenr) {
6457 fprintf(stderr, "Ref is before the entry start, please"
6458 " take a btrfs-image of this file system and "
6459 "send it to a btrfs developer, ref %Lu\n",
6460 dback->disk_bytenr);
6465 offset += dback->disk_bytenr;
6466 offset -= entry->bytenr;
6467 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6468 btrfs_set_file_extent_offset(leaf, fi, offset);
6471 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6474 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6475 * only do this if we aren't using compression, otherwise it's a
6478 if (!btrfs_file_extent_compression(leaf, fi))
6479 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6481 printf("ram bytes may be wrong?\n");
6482 btrfs_mark_buffer_dirty(leaf);
6484 err = btrfs_commit_transaction(trans, root);
6485 btrfs_release_path(path);
6486 return ret ? ret : err;
6489 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6490 struct extent_record *rec)
6492 struct extent_backref *back;
6493 struct data_backref *dback;
6494 struct extent_entry *entry, *best = NULL;
6497 int broken_entries = 0;
6502 * Metadata is easy and the backrefs should always agree on bytenr and
6503 * size, if not we've got bigger issues.
6508 list_for_each_entry(back, &rec->backrefs, list) {
6509 if (back->full_backref || !back->is_data)
6512 dback = (struct data_backref *)back;
6515 * We only pay attention to backrefs that we found a real
6518 if (dback->found_ref == 0)
6522 * For now we only catch when the bytes don't match, not the
6523 * bytenr. We can easily do this at the same time, but I want
6524 * to have a fs image to test on before we just add repair
6525 * functionality willy-nilly so we know we won't screw up the
6529 entry = find_entry(&entries, dback->disk_bytenr,
6532 entry = malloc(sizeof(struct extent_entry));
6537 memset(entry, 0, sizeof(*entry));
6538 entry->bytenr = dback->disk_bytenr;
6539 entry->bytes = dback->bytes;
6540 list_add_tail(&entry->list, &entries);
6545 * If we only have on entry we may think the entries agree when
6546 * in reality they don't so we have to do some extra checking.
6548 if (dback->disk_bytenr != rec->start ||
6549 dback->bytes != rec->nr || back->broken)
6560 /* Yay all the backrefs agree, carry on good sir */
6561 if (nr_entries <= 1 && !mismatch)
6564 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6565 "%Lu\n", rec->start);
6568 * First we want to see if the backrefs can agree amongst themselves who
6569 * is right, so figure out which one of the entries has the highest
6572 best = find_most_right_entry(&entries);
6575 * Ok so we may have an even split between what the backrefs think, so
6576 * this is where we use the extent ref to see what it thinks.
6579 entry = find_entry(&entries, rec->start, rec->nr);
6580 if (!entry && (!broken_entries || !rec->found_rec)) {
6581 fprintf(stderr, "Backrefs don't agree with each other "
6582 "and extent record doesn't agree with anybody,"
6583 " so we can't fix bytenr %Lu bytes %Lu\n",
6584 rec->start, rec->nr);
6587 } else if (!entry) {
6589 * Ok our backrefs were broken, we'll assume this is the
6590 * correct value and add an entry for this range.
6592 entry = malloc(sizeof(struct extent_entry));
6597 memset(entry, 0, sizeof(*entry));
6598 entry->bytenr = rec->start;
6599 entry->bytes = rec->nr;
6600 list_add_tail(&entry->list, &entries);
6604 best = find_most_right_entry(&entries);
6606 fprintf(stderr, "Backrefs and extent record evenly "
6607 "split on who is right, this is going to "
6608 "require user input to fix bytenr %Lu bytes "
6609 "%Lu\n", rec->start, rec->nr);
6616 * I don't think this can happen currently as we'll abort() if we catch
6617 * this case higher up, but in case somebody removes that we still can't
6618 * deal with it properly here yet, so just bail out of that's the case.
6620 if (best->bytenr != rec->start) {
6621 fprintf(stderr, "Extent start and backref starts don't match, "
6622 "please use btrfs-image on this file system and send "
6623 "it to a btrfs developer so they can make fsck fix "
6624 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6625 rec->start, rec->nr);
6631 * Ok great we all agreed on an extent record, let's go find the real
6632 * references and fix up the ones that don't match.
6634 list_for_each_entry(back, &rec->backrefs, list) {
6635 if (back->full_backref || !back->is_data)
6638 dback = (struct data_backref *)back;
6641 * Still ignoring backrefs that don't have a real ref attached
6644 if (dback->found_ref == 0)
6647 if (dback->bytes == best->bytes &&
6648 dback->disk_bytenr == best->bytenr)
6651 ret = repair_ref(info, path, dback, best);
6657 * Ok we messed with the actual refs, which means we need to drop our
6658 * entire cache and go back and rescan. I know this is a huge pain and
6659 * adds a lot of extra work, but it's the only way to be safe. Once all
6660 * the backrefs agree we may not need to do anything to the extent
6665 while (!list_empty(&entries)) {
6666 entry = list_entry(entries.next, struct extent_entry, list);
6667 list_del_init(&entry->list);
6673 static int process_duplicates(struct btrfs_root *root,
6674 struct cache_tree *extent_cache,
6675 struct extent_record *rec)
6677 struct extent_record *good, *tmp;
6678 struct cache_extent *cache;
6682 * If we found a extent record for this extent then return, or if we
6683 * have more than one duplicate we are likely going to need to delete
6686 if (rec->found_rec || rec->num_duplicates > 1)
6689 /* Shouldn't happen but just in case */
6690 BUG_ON(!rec->num_duplicates);
6693 * So this happens if we end up with a backref that doesn't match the
6694 * actual extent entry. So either the backref is bad or the extent
6695 * entry is bad. Either way we want to have the extent_record actually
6696 * reflect what we found in the extent_tree, so we need to take the
6697 * duplicate out and use that as the extent_record since the only way we
6698 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6700 remove_cache_extent(extent_cache, &rec->cache);
6702 good = list_entry(rec->dups.next, struct extent_record, list);
6703 list_del_init(&good->list);
6704 INIT_LIST_HEAD(&good->backrefs);
6705 INIT_LIST_HEAD(&good->dups);
6706 good->cache.start = good->start;
6707 good->cache.size = good->nr;
6708 good->content_checked = 0;
6709 good->owner_ref_checked = 0;
6710 good->num_duplicates = 0;
6711 good->refs = rec->refs;
6712 list_splice_init(&rec->backrefs, &good->backrefs);
6714 cache = lookup_cache_extent(extent_cache, good->start,
6718 tmp = container_of(cache, struct extent_record, cache);
6721 * If we find another overlapping extent and it's found_rec is
6722 * set then it's a duplicate and we need to try and delete
6725 if (tmp->found_rec || tmp->num_duplicates > 0) {
6726 if (list_empty(&good->list))
6727 list_add_tail(&good->list,
6728 &duplicate_extents);
6729 good->num_duplicates += tmp->num_duplicates + 1;
6730 list_splice_init(&tmp->dups, &good->dups);
6731 list_del_init(&tmp->list);
6732 list_add_tail(&tmp->list, &good->dups);
6733 remove_cache_extent(extent_cache, &tmp->cache);
6738 * Ok we have another non extent item backed extent rec, so lets
6739 * just add it to this extent and carry on like we did above.
6741 good->refs += tmp->refs;
6742 list_splice_init(&tmp->backrefs, &good->backrefs);
6743 remove_cache_extent(extent_cache, &tmp->cache);
6746 ret = insert_cache_extent(extent_cache, &good->cache);
6749 return good->num_duplicates ? 0 : 1;
6752 static int delete_duplicate_records(struct btrfs_root *root,
6753 struct extent_record *rec)
6755 struct btrfs_trans_handle *trans;
6756 LIST_HEAD(delete_list);
6757 struct btrfs_path *path;
6758 struct extent_record *tmp, *good, *n;
6761 struct btrfs_key key;
6763 path = btrfs_alloc_path();
6770 /* Find the record that covers all of the duplicates. */
6771 list_for_each_entry(tmp, &rec->dups, list) {
6772 if (good->start < tmp->start)
6774 if (good->nr > tmp->nr)
6777 if (tmp->start + tmp->nr < good->start + good->nr) {
6778 fprintf(stderr, "Ok we have overlapping extents that "
6779 "aren't completely covered by eachother, this "
6780 "is going to require more careful thought. "
6781 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6782 tmp->start, tmp->nr, good->start, good->nr);
6789 list_add_tail(&rec->list, &delete_list);
6791 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6794 list_move_tail(&tmp->list, &delete_list);
6797 root = root->fs_info->extent_root;
6798 trans = btrfs_start_transaction(root, 1);
6799 if (IS_ERR(trans)) {
6800 ret = PTR_ERR(trans);
6804 list_for_each_entry(tmp, &delete_list, list) {
6805 if (tmp->found_rec == 0)
6807 key.objectid = tmp->start;
6808 key.type = BTRFS_EXTENT_ITEM_KEY;
6809 key.offset = tmp->nr;
6811 /* Shouldn't happen but just in case */
6812 if (tmp->metadata) {
6813 fprintf(stderr, "Well this shouldn't happen, extent "
6814 "record overlaps but is metadata? "
6815 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6819 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6825 ret = btrfs_del_item(trans, root, path);
6828 btrfs_release_path(path);
6831 err = btrfs_commit_transaction(trans, root);
6835 while (!list_empty(&delete_list)) {
6836 tmp = list_entry(delete_list.next, struct extent_record, list);
6837 list_del_init(&tmp->list);
6843 while (!list_empty(&rec->dups)) {
6844 tmp = list_entry(rec->dups.next, struct extent_record, list);
6845 list_del_init(&tmp->list);
6849 btrfs_free_path(path);
6851 if (!ret && !nr_del)
6852 rec->num_duplicates = 0;
6854 return ret ? ret : nr_del;
6857 static int find_possible_backrefs(struct btrfs_fs_info *info,
6858 struct btrfs_path *path,
6859 struct cache_tree *extent_cache,
6860 struct extent_record *rec)
6862 struct btrfs_root *root;
6863 struct extent_backref *back;
6864 struct data_backref *dback;
6865 struct cache_extent *cache;
6866 struct btrfs_file_extent_item *fi;
6867 struct btrfs_key key;
6871 list_for_each_entry(back, &rec->backrefs, list) {
6872 /* Don't care about full backrefs (poor unloved backrefs) */
6873 if (back->full_backref || !back->is_data)
6876 dback = (struct data_backref *)back;
6878 /* We found this one, we don't need to do a lookup */
6879 if (dback->found_ref)
6882 key.objectid = dback->root;
6883 key.type = BTRFS_ROOT_ITEM_KEY;
6884 key.offset = (u64)-1;
6886 root = btrfs_read_fs_root(info, &key);
6888 /* No root, definitely a bad ref, skip */
6889 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6891 /* Other err, exit */
6893 return PTR_ERR(root);
6895 key.objectid = dback->owner;
6896 key.type = BTRFS_EXTENT_DATA_KEY;
6897 key.offset = dback->offset;
6898 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6900 btrfs_release_path(path);
6903 /* Didn't find it, we can carry on */
6908 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6909 struct btrfs_file_extent_item);
6910 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6911 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6912 btrfs_release_path(path);
6913 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6915 struct extent_record *tmp;
6916 tmp = container_of(cache, struct extent_record, cache);
6919 * If we found an extent record for the bytenr for this
6920 * particular backref then we can't add it to our
6921 * current extent record. We only want to add backrefs
6922 * that don't have a corresponding extent item in the
6923 * extent tree since they likely belong to this record
6924 * and we need to fix it if it doesn't match bytenrs.
6930 dback->found_ref += 1;
6931 dback->disk_bytenr = bytenr;
6932 dback->bytes = bytes;
6935 * Set this so the verify backref code knows not to trust the
6936 * values in this backref.
6945 * Record orphan data ref into corresponding root.
6947 * Return 0 if the extent item contains data ref and recorded.
6948 * Return 1 if the extent item contains no useful data ref
6949 * On that case, it may contains only shared_dataref or metadata backref
6950 * or the file extent exists(this should be handled by the extent bytenr
6952 * Return <0 if something goes wrong.
6954 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6955 struct extent_record *rec)
6957 struct btrfs_key key;
6958 struct btrfs_root *dest_root;
6959 struct extent_backref *back;
6960 struct data_backref *dback;
6961 struct orphan_data_extent *orphan;
6962 struct btrfs_path *path;
6963 int recorded_data_ref = 0;
6968 path = btrfs_alloc_path();
6971 list_for_each_entry(back, &rec->backrefs, list) {
6972 if (back->full_backref || !back->is_data ||
6973 !back->found_extent_tree)
6975 dback = (struct data_backref *)back;
6976 if (dback->found_ref)
6978 key.objectid = dback->root;
6979 key.type = BTRFS_ROOT_ITEM_KEY;
6980 key.offset = (u64)-1;
6982 dest_root = btrfs_read_fs_root(fs_info, &key);
6984 /* For non-exist root we just skip it */
6985 if (IS_ERR(dest_root) || !dest_root)
6988 key.objectid = dback->owner;
6989 key.type = BTRFS_EXTENT_DATA_KEY;
6990 key.offset = dback->offset;
6992 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
6994 * For ret < 0, it's OK since the fs-tree may be corrupted,
6995 * we need to record it for inode/file extent rebuild.
6996 * For ret > 0, we record it only for file extent rebuild.
6997 * For ret == 0, the file extent exists but only bytenr
6998 * mismatch, let the original bytenr fix routine to handle,
7004 orphan = malloc(sizeof(*orphan));
7009 INIT_LIST_HEAD(&orphan->list);
7010 orphan->root = dback->root;
7011 orphan->objectid = dback->owner;
7012 orphan->offset = dback->offset;
7013 orphan->disk_bytenr = rec->cache.start;
7014 orphan->disk_len = rec->cache.size;
7015 list_add(&dest_root->orphan_data_extents, &orphan->list);
7016 recorded_data_ref = 1;
7019 btrfs_free_path(path);
7021 return !recorded_data_ref;
7027 * when an incorrect extent item is found, this will delete
7028 * all of the existing entries for it and recreate them
7029 * based on what the tree scan found.
7031 static int fixup_extent_refs(struct btrfs_fs_info *info,
7032 struct cache_tree *extent_cache,
7033 struct extent_record *rec)
7035 struct btrfs_trans_handle *trans = NULL;
7037 struct btrfs_path *path;
7038 struct list_head *cur = rec->backrefs.next;
7039 struct cache_extent *cache;
7040 struct extent_backref *back;
7044 if (rec->flag_block_full_backref)
7045 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7047 path = btrfs_alloc_path();
7051 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7053 * Sometimes the backrefs themselves are so broken they don't
7054 * get attached to any meaningful rec, so first go back and
7055 * check any of our backrefs that we couldn't find and throw
7056 * them into the list if we find the backref so that
7057 * verify_backrefs can figure out what to do.
7059 ret = find_possible_backrefs(info, path, extent_cache, rec);
7064 /* step one, make sure all of the backrefs agree */
7065 ret = verify_backrefs(info, path, rec);
7069 trans = btrfs_start_transaction(info->extent_root, 1);
7070 if (IS_ERR(trans)) {
7071 ret = PTR_ERR(trans);
7075 /* step two, delete all the existing records */
7076 ret = delete_extent_records(trans, info->extent_root, path,
7077 rec->start, rec->max_size);
7082 /* was this block corrupt? If so, don't add references to it */
7083 cache = lookup_cache_extent(info->corrupt_blocks,
7084 rec->start, rec->max_size);
7090 /* step three, recreate all the refs we did find */
7091 while(cur != &rec->backrefs) {
7092 back = list_entry(cur, struct extent_backref, list);
7096 * if we didn't find any references, don't create a
7099 if (!back->found_ref)
7102 rec->bad_full_backref = 0;
7103 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7111 int err = btrfs_commit_transaction(trans, info->extent_root);
7116 btrfs_free_path(path);
7120 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7121 struct extent_record *rec)
7123 struct btrfs_trans_handle *trans;
7124 struct btrfs_root *root = fs_info->extent_root;
7125 struct btrfs_path *path;
7126 struct btrfs_extent_item *ei;
7127 struct btrfs_key key;
7131 key.objectid = rec->start;
7132 if (rec->metadata) {
7133 key.type = BTRFS_METADATA_ITEM_KEY;
7134 key.offset = rec->info_level;
7136 key.type = BTRFS_EXTENT_ITEM_KEY;
7137 key.offset = rec->max_size;
7140 path = btrfs_alloc_path();
7144 trans = btrfs_start_transaction(root, 0);
7145 if (IS_ERR(trans)) {
7146 btrfs_free_path(path);
7147 return PTR_ERR(trans);
7150 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7152 btrfs_free_path(path);
7153 btrfs_commit_transaction(trans, root);
7156 fprintf(stderr, "Didn't find extent for %llu\n",
7157 (unsigned long long)rec->start);
7158 btrfs_free_path(path);
7159 btrfs_commit_transaction(trans, root);
7163 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7164 struct btrfs_extent_item);
7165 flags = btrfs_extent_flags(path->nodes[0], ei);
7166 if (rec->flag_block_full_backref) {
7167 fprintf(stderr, "setting full backref on %llu\n",
7168 (unsigned long long)key.objectid);
7169 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7171 fprintf(stderr, "clearing full backref on %llu\n",
7172 (unsigned long long)key.objectid);
7173 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7175 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7176 btrfs_mark_buffer_dirty(path->nodes[0]);
7177 btrfs_free_path(path);
7178 return btrfs_commit_transaction(trans, root);
7181 /* right now we only prune from the extent allocation tree */
7182 static int prune_one_block(struct btrfs_trans_handle *trans,
7183 struct btrfs_fs_info *info,
7184 struct btrfs_corrupt_block *corrupt)
7187 struct btrfs_path path;
7188 struct extent_buffer *eb;
7192 int level = corrupt->level + 1;
7194 btrfs_init_path(&path);
7196 /* we want to stop at the parent to our busted block */
7197 path.lowest_level = level;
7199 ret = btrfs_search_slot(trans, info->extent_root,
7200 &corrupt->key, &path, -1, 1);
7205 eb = path.nodes[level];
7212 * hopefully the search gave us the block we want to prune,
7213 * lets try that first
7215 slot = path.slots[level];
7216 found = btrfs_node_blockptr(eb, slot);
7217 if (found == corrupt->cache.start)
7220 nritems = btrfs_header_nritems(eb);
7222 /* the search failed, lets scan this node and hope we find it */
7223 for (slot = 0; slot < nritems; slot++) {
7224 found = btrfs_node_blockptr(eb, slot);
7225 if (found == corrupt->cache.start)
7229 * we couldn't find the bad block. TODO, search all the nodes for pointers
7232 if (eb == info->extent_root->node) {
7237 btrfs_release_path(&path);
7242 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7243 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7246 btrfs_release_path(&path);
7250 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7252 struct btrfs_trans_handle *trans = NULL;
7253 struct cache_extent *cache;
7254 struct btrfs_corrupt_block *corrupt;
7257 cache = search_cache_extent(info->corrupt_blocks, 0);
7261 trans = btrfs_start_transaction(info->extent_root, 1);
7263 return PTR_ERR(trans);
7265 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7266 prune_one_block(trans, info, corrupt);
7267 remove_cache_extent(info->corrupt_blocks, cache);
7270 return btrfs_commit_transaction(trans, info->extent_root);
7274 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7276 struct btrfs_block_group_cache *cache;
7281 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7282 &start, &end, EXTENT_DIRTY);
7285 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7291 cache = btrfs_lookup_first_block_group(fs_info, start);
7296 start = cache->key.objectid + cache->key.offset;
7300 static int check_extent_refs(struct btrfs_root *root,
7301 struct cache_tree *extent_cache)
7303 struct extent_record *rec;
7304 struct cache_extent *cache;
7313 * if we're doing a repair, we have to make sure
7314 * we don't allocate from the problem extents.
7315 * In the worst case, this will be all the
7318 cache = search_cache_extent(extent_cache, 0);
7320 rec = container_of(cache, struct extent_record, cache);
7321 set_extent_dirty(root->fs_info->excluded_extents,
7323 rec->start + rec->max_size - 1,
7325 cache = next_cache_extent(cache);
7328 /* pin down all the corrupted blocks too */
7329 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7331 set_extent_dirty(root->fs_info->excluded_extents,
7333 cache->start + cache->size - 1,
7335 cache = next_cache_extent(cache);
7337 prune_corrupt_blocks(root->fs_info);
7338 reset_cached_block_groups(root->fs_info);
7341 reset_cached_block_groups(root->fs_info);
7344 * We need to delete any duplicate entries we find first otherwise we
7345 * could mess up the extent tree when we have backrefs that actually
7346 * belong to a different extent item and not the weird duplicate one.
7348 while (repair && !list_empty(&duplicate_extents)) {
7349 rec = list_entry(duplicate_extents.next, struct extent_record,
7351 list_del_init(&rec->list);
7353 /* Sometimes we can find a backref before we find an actual
7354 * extent, so we need to process it a little bit to see if there
7355 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7356 * if this is a backref screwup. If we need to delete stuff
7357 * process_duplicates() will return 0, otherwise it will return
7360 if (process_duplicates(root, extent_cache, rec))
7362 ret = delete_duplicate_records(root, rec);
7366 * delete_duplicate_records will return the number of entries
7367 * deleted, so if it's greater than 0 then we know we actually
7368 * did something and we need to remove.
7382 cache = search_cache_extent(extent_cache, 0);
7385 rec = container_of(cache, struct extent_record, cache);
7386 if (rec->num_duplicates) {
7387 fprintf(stderr, "extent item %llu has multiple extent "
7388 "items\n", (unsigned long long)rec->start);
7393 if (rec->refs != rec->extent_item_refs) {
7394 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7395 (unsigned long long)rec->start,
7396 (unsigned long long)rec->nr);
7397 fprintf(stderr, "extent item %llu, found %llu\n",
7398 (unsigned long long)rec->extent_item_refs,
7399 (unsigned long long)rec->refs);
7400 ret = record_orphan_data_extents(root->fs_info, rec);
7407 * we can't use the extent to repair file
7408 * extent, let the fallback method handle it.
7410 if (!fixed && repair) {
7411 ret = fixup_extent_refs(
7422 if (all_backpointers_checked(rec, 1)) {
7423 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7424 (unsigned long long)rec->start,
7425 (unsigned long long)rec->nr);
7427 if (!fixed && !recorded && repair) {
7428 ret = fixup_extent_refs(root->fs_info,
7437 if (!rec->owner_ref_checked) {
7438 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7439 (unsigned long long)rec->start,
7440 (unsigned long long)rec->nr);
7441 if (!fixed && !recorded && repair) {
7442 ret = fixup_extent_refs(root->fs_info,
7451 if (rec->bad_full_backref) {
7452 fprintf(stderr, "bad full backref, on [%llu]\n",
7453 (unsigned long long)rec->start);
7455 ret = fixup_extent_flags(root->fs_info, rec);
7464 remove_cache_extent(extent_cache, cache);
7465 free_all_extent_backrefs(rec);
7466 if (!init_extent_tree && repair && (!cur_err || fixed))
7467 clear_extent_dirty(root->fs_info->excluded_extents,
7469 rec->start + rec->max_size - 1,
7475 if (ret && ret != -EAGAIN) {
7476 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7479 struct btrfs_trans_handle *trans;
7481 root = root->fs_info->extent_root;
7482 trans = btrfs_start_transaction(root, 1);
7483 if (IS_ERR(trans)) {
7484 ret = PTR_ERR(trans);
7488 btrfs_fix_block_accounting(trans, root);
7489 ret = btrfs_commit_transaction(trans, root);
7494 fprintf(stderr, "repaired damaged extent references\n");
7500 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7504 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7505 stripe_size = length;
7506 stripe_size /= num_stripes;
7507 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7508 stripe_size = length * 2;
7509 stripe_size /= num_stripes;
7510 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7511 stripe_size = length;
7512 stripe_size /= (num_stripes - 1);
7513 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7514 stripe_size = length;
7515 stripe_size /= (num_stripes - 2);
7517 stripe_size = length;
7523 * Check the chunk with its block group/dev list ref:
7524 * Return 0 if all refs seems valid.
7525 * Return 1 if part of refs seems valid, need later check for rebuild ref
7526 * like missing block group and needs to search extent tree to rebuild them.
7527 * Return -1 if essential refs are missing and unable to rebuild.
7529 static int check_chunk_refs(struct chunk_record *chunk_rec,
7530 struct block_group_tree *block_group_cache,
7531 struct device_extent_tree *dev_extent_cache,
7534 struct cache_extent *block_group_item;
7535 struct block_group_record *block_group_rec;
7536 struct cache_extent *dev_extent_item;
7537 struct device_extent_record *dev_extent_rec;
7541 int metadump_v2 = 0;
7545 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7548 if (block_group_item) {
7549 block_group_rec = container_of(block_group_item,
7550 struct block_group_record,
7552 if (chunk_rec->length != block_group_rec->offset ||
7553 chunk_rec->offset != block_group_rec->objectid ||
7555 chunk_rec->type_flags != block_group_rec->flags)) {
7558 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7559 chunk_rec->objectid,
7564 chunk_rec->type_flags,
7565 block_group_rec->objectid,
7566 block_group_rec->type,
7567 block_group_rec->offset,
7568 block_group_rec->offset,
7569 block_group_rec->objectid,
7570 block_group_rec->flags);
7573 list_del_init(&block_group_rec->list);
7574 chunk_rec->bg_rec = block_group_rec;
7579 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7580 chunk_rec->objectid,
7585 chunk_rec->type_flags);
7592 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7593 chunk_rec->num_stripes);
7594 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7595 devid = chunk_rec->stripes[i].devid;
7596 offset = chunk_rec->stripes[i].offset;
7597 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7598 devid, offset, length);
7599 if (dev_extent_item) {
7600 dev_extent_rec = container_of(dev_extent_item,
7601 struct device_extent_record,
7603 if (dev_extent_rec->objectid != devid ||
7604 dev_extent_rec->offset != offset ||
7605 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7606 dev_extent_rec->length != length) {
7609 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7610 chunk_rec->objectid,
7613 chunk_rec->stripes[i].devid,
7614 chunk_rec->stripes[i].offset,
7615 dev_extent_rec->objectid,
7616 dev_extent_rec->offset,
7617 dev_extent_rec->length);
7620 list_move(&dev_extent_rec->chunk_list,
7621 &chunk_rec->dextents);
7626 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7627 chunk_rec->objectid,
7630 chunk_rec->stripes[i].devid,
7631 chunk_rec->stripes[i].offset);
7638 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7639 int check_chunks(struct cache_tree *chunk_cache,
7640 struct block_group_tree *block_group_cache,
7641 struct device_extent_tree *dev_extent_cache,
7642 struct list_head *good, struct list_head *bad,
7643 struct list_head *rebuild, int silent)
7645 struct cache_extent *chunk_item;
7646 struct chunk_record *chunk_rec;
7647 struct block_group_record *bg_rec;
7648 struct device_extent_record *dext_rec;
7652 chunk_item = first_cache_extent(chunk_cache);
7653 while (chunk_item) {
7654 chunk_rec = container_of(chunk_item, struct chunk_record,
7656 err = check_chunk_refs(chunk_rec, block_group_cache,
7657 dev_extent_cache, silent);
7660 if (err == 0 && good)
7661 list_add_tail(&chunk_rec->list, good);
7662 if (err > 0 && rebuild)
7663 list_add_tail(&chunk_rec->list, rebuild);
7665 list_add_tail(&chunk_rec->list, bad);
7666 chunk_item = next_cache_extent(chunk_item);
7669 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7672 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7680 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7684 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7695 static int check_device_used(struct device_record *dev_rec,
7696 struct device_extent_tree *dext_cache)
7698 struct cache_extent *cache;
7699 struct device_extent_record *dev_extent_rec;
7702 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7704 dev_extent_rec = container_of(cache,
7705 struct device_extent_record,
7707 if (dev_extent_rec->objectid != dev_rec->devid)
7710 list_del_init(&dev_extent_rec->device_list);
7711 total_byte += dev_extent_rec->length;
7712 cache = next_cache_extent(cache);
7715 if (total_byte != dev_rec->byte_used) {
7717 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7718 total_byte, dev_rec->byte_used, dev_rec->objectid,
7719 dev_rec->type, dev_rec->offset);
7726 /* check btrfs_dev_item -> btrfs_dev_extent */
7727 static int check_devices(struct rb_root *dev_cache,
7728 struct device_extent_tree *dev_extent_cache)
7730 struct rb_node *dev_node;
7731 struct device_record *dev_rec;
7732 struct device_extent_record *dext_rec;
7736 dev_node = rb_first(dev_cache);
7738 dev_rec = container_of(dev_node, struct device_record, node);
7739 err = check_device_used(dev_rec, dev_extent_cache);
7743 dev_node = rb_next(dev_node);
7745 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7748 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7749 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7756 static int add_root_item_to_list(struct list_head *head,
7757 u64 objectid, u64 bytenr, u64 last_snapshot,
7758 u8 level, u8 drop_level,
7759 int level_size, struct btrfs_key *drop_key)
7762 struct root_item_record *ri_rec;
7763 ri_rec = malloc(sizeof(*ri_rec));
7766 ri_rec->bytenr = bytenr;
7767 ri_rec->objectid = objectid;
7768 ri_rec->level = level;
7769 ri_rec->level_size = level_size;
7770 ri_rec->drop_level = drop_level;
7771 ri_rec->last_snapshot = last_snapshot;
7773 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7774 list_add_tail(&ri_rec->list, head);
7779 static void free_root_item_list(struct list_head *list)
7781 struct root_item_record *ri_rec;
7783 while (!list_empty(list)) {
7784 ri_rec = list_first_entry(list, struct root_item_record,
7786 list_del_init(&ri_rec->list);
7791 static int deal_root_from_list(struct list_head *list,
7792 struct btrfs_root *root,
7793 struct block_info *bits,
7795 struct cache_tree *pending,
7796 struct cache_tree *seen,
7797 struct cache_tree *reada,
7798 struct cache_tree *nodes,
7799 struct cache_tree *extent_cache,
7800 struct cache_tree *chunk_cache,
7801 struct rb_root *dev_cache,
7802 struct block_group_tree *block_group_cache,
7803 struct device_extent_tree *dev_extent_cache)
7808 while (!list_empty(list)) {
7809 struct root_item_record *rec;
7810 struct extent_buffer *buf;
7811 rec = list_entry(list->next,
7812 struct root_item_record, list);
7814 buf = read_tree_block(root->fs_info->tree_root,
7815 rec->bytenr, rec->level_size, 0);
7816 if (!extent_buffer_uptodate(buf)) {
7817 free_extent_buffer(buf);
7821 add_root_to_pending(buf, extent_cache, pending,
7822 seen, nodes, rec->objectid);
7824 * To rebuild extent tree, we need deal with snapshot
7825 * one by one, otherwise we deal with node firstly which
7826 * can maximize readahead.
7829 ret = run_next_block(root, bits, bits_nr, &last,
7830 pending, seen, reada, nodes,
7831 extent_cache, chunk_cache,
7832 dev_cache, block_group_cache,
7833 dev_extent_cache, rec);
7837 free_extent_buffer(buf);
7838 list_del(&rec->list);
7844 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7845 reada, nodes, extent_cache, chunk_cache,
7846 dev_cache, block_group_cache,
7847 dev_extent_cache, NULL);
7857 static int check_chunks_and_extents(struct btrfs_root *root)
7859 struct rb_root dev_cache;
7860 struct cache_tree chunk_cache;
7861 struct block_group_tree block_group_cache;
7862 struct device_extent_tree dev_extent_cache;
7863 struct cache_tree extent_cache;
7864 struct cache_tree seen;
7865 struct cache_tree pending;
7866 struct cache_tree reada;
7867 struct cache_tree nodes;
7868 struct extent_io_tree excluded_extents;
7869 struct cache_tree corrupt_blocks;
7870 struct btrfs_path path;
7871 struct btrfs_key key;
7872 struct btrfs_key found_key;
7874 struct block_info *bits;
7876 struct extent_buffer *leaf;
7878 struct btrfs_root_item ri;
7879 struct list_head dropping_trees;
7880 struct list_head normal_trees;
7881 struct btrfs_root *root1;
7886 dev_cache = RB_ROOT;
7887 cache_tree_init(&chunk_cache);
7888 block_group_tree_init(&block_group_cache);
7889 device_extent_tree_init(&dev_extent_cache);
7891 cache_tree_init(&extent_cache);
7892 cache_tree_init(&seen);
7893 cache_tree_init(&pending);
7894 cache_tree_init(&nodes);
7895 cache_tree_init(&reada);
7896 cache_tree_init(&corrupt_blocks);
7897 extent_io_tree_init(&excluded_extents);
7898 INIT_LIST_HEAD(&dropping_trees);
7899 INIT_LIST_HEAD(&normal_trees);
7902 root->fs_info->excluded_extents = &excluded_extents;
7903 root->fs_info->fsck_extent_cache = &extent_cache;
7904 root->fs_info->free_extent_hook = free_extent_hook;
7905 root->fs_info->corrupt_blocks = &corrupt_blocks;
7909 bits = malloc(bits_nr * sizeof(struct block_info));
7916 root1 = root->fs_info->tree_root;
7917 level = btrfs_header_level(root1->node);
7918 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7919 root1->node->start, 0, level, 0,
7920 btrfs_level_size(root1, level), NULL);
7923 root1 = root->fs_info->chunk_root;
7924 level = btrfs_header_level(root1->node);
7925 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7926 root1->node->start, 0, level, 0,
7927 btrfs_level_size(root1, level), NULL);
7930 btrfs_init_path(&path);
7933 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7934 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7939 leaf = path.nodes[0];
7940 slot = path.slots[0];
7941 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7942 ret = btrfs_next_leaf(root, &path);
7945 leaf = path.nodes[0];
7946 slot = path.slots[0];
7948 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7949 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7950 unsigned long offset;
7953 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7954 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7955 last_snapshot = btrfs_root_last_snapshot(&ri);
7956 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7957 level = btrfs_root_level(&ri);
7958 level_size = btrfs_level_size(root, level);
7959 ret = add_root_item_to_list(&normal_trees,
7961 btrfs_root_bytenr(&ri),
7962 last_snapshot, level,
7963 0, level_size, NULL);
7967 level = btrfs_root_level(&ri);
7968 level_size = btrfs_level_size(root, level);
7969 objectid = found_key.objectid;
7970 btrfs_disk_key_to_cpu(&found_key,
7972 ret = add_root_item_to_list(&dropping_trees,
7974 btrfs_root_bytenr(&ri),
7975 last_snapshot, level,
7977 level_size, &found_key);
7984 btrfs_release_path(&path);
7987 * check_block can return -EAGAIN if it fixes something, please keep
7988 * this in mind when dealing with return values from these functions, if
7989 * we get -EAGAIN we want to fall through and restart the loop.
7991 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
7992 &seen, &reada, &nodes, &extent_cache,
7993 &chunk_cache, &dev_cache, &block_group_cache,
8000 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8001 &pending, &seen, &reada, &nodes,
8002 &extent_cache, &chunk_cache, &dev_cache,
8003 &block_group_cache, &dev_extent_cache);
8010 err = check_chunks(&chunk_cache, &block_group_cache,
8011 &dev_extent_cache, NULL, NULL, NULL, 0);
8019 ret = check_extent_refs(root, &extent_cache);
8026 err = check_devices(&dev_cache, &dev_extent_cache);
8032 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8033 extent_io_tree_cleanup(&excluded_extents);
8034 root->fs_info->fsck_extent_cache = NULL;
8035 root->fs_info->free_extent_hook = NULL;
8036 root->fs_info->corrupt_blocks = NULL;
8037 root->fs_info->excluded_extents = NULL;
8040 free_chunk_cache_tree(&chunk_cache);
8041 free_device_cache_tree(&dev_cache);
8042 free_block_group_tree(&block_group_cache);
8043 free_device_extent_tree(&dev_extent_cache);
8044 free_extent_cache_tree(&seen);
8045 free_extent_cache_tree(&pending);
8046 free_extent_cache_tree(&reada);
8047 free_extent_cache_tree(&nodes);
8050 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8051 free_extent_cache_tree(&seen);
8052 free_extent_cache_tree(&pending);
8053 free_extent_cache_tree(&reada);
8054 free_extent_cache_tree(&nodes);
8055 free_chunk_cache_tree(&chunk_cache);
8056 free_block_group_tree(&block_group_cache);
8057 free_device_cache_tree(&dev_cache);
8058 free_device_extent_tree(&dev_extent_cache);
8059 free_extent_record_cache(root->fs_info, &extent_cache);
8060 free_root_item_list(&normal_trees);
8061 free_root_item_list(&dropping_trees);
8062 extent_io_tree_cleanup(&excluded_extents);
8066 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8067 struct btrfs_root *root, int overwrite)
8069 struct extent_buffer *c;
8070 struct extent_buffer *old = root->node;
8073 struct btrfs_disk_key disk_key = {0,0,0};
8079 extent_buffer_get(c);
8082 c = btrfs_alloc_free_block(trans, root,
8083 btrfs_level_size(root, 0),
8084 root->root_key.objectid,
8085 &disk_key, level, 0, 0);
8088 extent_buffer_get(c);
8092 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8093 btrfs_set_header_level(c, level);
8094 btrfs_set_header_bytenr(c, c->start);
8095 btrfs_set_header_generation(c, trans->transid);
8096 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8097 btrfs_set_header_owner(c, root->root_key.objectid);
8099 write_extent_buffer(c, root->fs_info->fsid,
8100 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8102 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8103 btrfs_header_chunk_tree_uuid(c),
8106 btrfs_mark_buffer_dirty(c);
8108 * this case can happen in the following case:
8110 * 1.overwrite previous root.
8112 * 2.reinit reloc data root, this is because we skip pin
8113 * down reloc data tree before which means we can allocate
8114 * same block bytenr here.
8116 if (old->start == c->start) {
8117 btrfs_set_root_generation(&root->root_item,
8119 root->root_item.level = btrfs_header_level(root->node);
8120 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8121 &root->root_key, &root->root_item);
8123 free_extent_buffer(c);
8127 free_extent_buffer(old);
8129 add_root_to_dirty_list(root);
8133 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8134 struct extent_buffer *eb, int tree_root)
8136 struct extent_buffer *tmp;
8137 struct btrfs_root_item *ri;
8138 struct btrfs_key key;
8141 int level = btrfs_header_level(eb);
8147 * If we have pinned this block before, don't pin it again.
8148 * This can not only avoid forever loop with broken filesystem
8149 * but also give us some speedups.
8151 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8152 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8155 btrfs_pin_extent(fs_info, eb->start, eb->len);
8157 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8158 nritems = btrfs_header_nritems(eb);
8159 for (i = 0; i < nritems; i++) {
8161 btrfs_item_key_to_cpu(eb, &key, i);
8162 if (key.type != BTRFS_ROOT_ITEM_KEY)
8164 /* Skip the extent root and reloc roots */
8165 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8166 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8167 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8169 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8170 bytenr = btrfs_disk_root_bytenr(eb, ri);
8173 * If at any point we start needing the real root we
8174 * will have to build a stump root for the root we are
8175 * in, but for now this doesn't actually use the root so
8176 * just pass in extent_root.
8178 tmp = read_tree_block(fs_info->extent_root, bytenr,
8180 if (!extent_buffer_uptodate(tmp)) {
8181 fprintf(stderr, "Error reading root block\n");
8184 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8185 free_extent_buffer(tmp);
8189 bytenr = btrfs_node_blockptr(eb, i);
8191 /* If we aren't the tree root don't read the block */
8192 if (level == 1 && !tree_root) {
8193 btrfs_pin_extent(fs_info, bytenr, leafsize);
8197 tmp = read_tree_block(fs_info->extent_root, bytenr,
8199 if (!extent_buffer_uptodate(tmp)) {
8200 fprintf(stderr, "Error reading tree block\n");
8203 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8204 free_extent_buffer(tmp);
8213 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8217 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8221 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8224 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8226 struct btrfs_block_group_cache *cache;
8227 struct btrfs_path *path;
8228 struct extent_buffer *leaf;
8229 struct btrfs_chunk *chunk;
8230 struct btrfs_key key;
8234 path = btrfs_alloc_path();
8239 key.type = BTRFS_CHUNK_ITEM_KEY;
8242 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8244 btrfs_free_path(path);
8249 * We do this in case the block groups were screwed up and had alloc
8250 * bits that aren't actually set on the chunks. This happens with
8251 * restored images every time and could happen in real life I guess.
8253 fs_info->avail_data_alloc_bits = 0;
8254 fs_info->avail_metadata_alloc_bits = 0;
8255 fs_info->avail_system_alloc_bits = 0;
8257 /* First we need to create the in-memory block groups */
8259 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8260 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8262 btrfs_free_path(path);
8270 leaf = path->nodes[0];
8271 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8272 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8277 chunk = btrfs_item_ptr(leaf, path->slots[0],
8278 struct btrfs_chunk);
8279 btrfs_add_block_group(fs_info, 0,
8280 btrfs_chunk_type(leaf, chunk),
8281 key.objectid, key.offset,
8282 btrfs_chunk_length(leaf, chunk));
8283 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8284 key.offset + btrfs_chunk_length(leaf, chunk),
8290 cache = btrfs_lookup_first_block_group(fs_info, start);
8294 start = cache->key.objectid + cache->key.offset;
8297 btrfs_free_path(path);
8301 static int reset_balance(struct btrfs_trans_handle *trans,
8302 struct btrfs_fs_info *fs_info)
8304 struct btrfs_root *root = fs_info->tree_root;
8305 struct btrfs_path *path;
8306 struct extent_buffer *leaf;
8307 struct btrfs_key key;
8308 int del_slot, del_nr = 0;
8312 path = btrfs_alloc_path();
8316 key.objectid = BTRFS_BALANCE_OBJECTID;
8317 key.type = BTRFS_BALANCE_ITEM_KEY;
8320 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8325 goto reinit_data_reloc;
8330 ret = btrfs_del_item(trans, root, path);
8333 btrfs_release_path(path);
8335 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8336 key.type = BTRFS_ROOT_ITEM_KEY;
8339 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8343 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8348 ret = btrfs_del_items(trans, root, path,
8355 btrfs_release_path(path);
8358 ret = btrfs_search_slot(trans, root, &key, path,
8365 leaf = path->nodes[0];
8366 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8367 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8369 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8374 del_slot = path->slots[0];
8383 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8387 btrfs_release_path(path);
8390 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8391 key.type = BTRFS_ROOT_ITEM_KEY;
8392 key.offset = (u64)-1;
8393 root = btrfs_read_fs_root(fs_info, &key);
8395 fprintf(stderr, "Error reading data reloc tree\n");
8396 ret = PTR_ERR(root);
8399 record_root_in_trans(trans, root);
8400 ret = btrfs_fsck_reinit_root(trans, root, 0);
8403 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8405 btrfs_free_path(path);
8409 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8410 struct btrfs_fs_info *fs_info)
8416 * The only reason we don't do this is because right now we're just
8417 * walking the trees we find and pinning down their bytes, we don't look
8418 * at any of the leaves. In order to do mixed groups we'd have to check
8419 * the leaves of any fs roots and pin down the bytes for any file
8420 * extents we find. Not hard but why do it if we don't have to?
8422 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8423 fprintf(stderr, "We don't support re-initing the extent tree "
8424 "for mixed block groups yet, please notify a btrfs "
8425 "developer you want to do this so they can add this "
8426 "functionality.\n");
8431 * first we need to walk all of the trees except the extent tree and pin
8432 * down the bytes that are in use so we don't overwrite any existing
8435 ret = pin_metadata_blocks(fs_info);
8437 fprintf(stderr, "error pinning down used bytes\n");
8442 * Need to drop all the block groups since we're going to recreate all
8445 btrfs_free_block_groups(fs_info);
8446 ret = reset_block_groups(fs_info);
8448 fprintf(stderr, "error resetting the block groups\n");
8452 /* Ok we can allocate now, reinit the extent root */
8453 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8455 fprintf(stderr, "extent root initialization failed\n");
8457 * When the transaction code is updated we should end the
8458 * transaction, but for now progs only knows about commit so
8459 * just return an error.
8465 * Now we have all the in-memory block groups setup so we can make
8466 * allocations properly, and the metadata we care about is safe since we
8467 * pinned all of it above.
8470 struct btrfs_block_group_cache *cache;
8472 cache = btrfs_lookup_first_block_group(fs_info, start);
8475 start = cache->key.objectid + cache->key.offset;
8476 ret = btrfs_insert_item(trans, fs_info->extent_root,
8477 &cache->key, &cache->item,
8478 sizeof(cache->item));
8480 fprintf(stderr, "Error adding block group\n");
8483 btrfs_extent_post_op(trans, fs_info->extent_root);
8486 ret = reset_balance(trans, fs_info);
8488 fprintf(stderr, "error reseting the pending balance\n");
8493 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8495 struct btrfs_path *path;
8496 struct btrfs_trans_handle *trans;
8497 struct btrfs_key key;
8500 printf("Recowing metadata block %llu\n", eb->start);
8501 key.objectid = btrfs_header_owner(eb);
8502 key.type = BTRFS_ROOT_ITEM_KEY;
8503 key.offset = (u64)-1;
8505 root = btrfs_read_fs_root(root->fs_info, &key);
8507 fprintf(stderr, "Couldn't find owner root %llu\n",
8509 return PTR_ERR(root);
8512 path = btrfs_alloc_path();
8516 trans = btrfs_start_transaction(root, 1);
8517 if (IS_ERR(trans)) {
8518 btrfs_free_path(path);
8519 return PTR_ERR(trans);
8522 path->lowest_level = btrfs_header_level(eb);
8523 if (path->lowest_level)
8524 btrfs_node_key_to_cpu(eb, &key, 0);
8526 btrfs_item_key_to_cpu(eb, &key, 0);
8528 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8529 btrfs_commit_transaction(trans, root);
8530 btrfs_free_path(path);
8534 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8536 struct btrfs_path *path;
8537 struct btrfs_trans_handle *trans;
8538 struct btrfs_key key;
8541 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8542 bad->key.type, bad->key.offset);
8543 key.objectid = bad->root_id;
8544 key.type = BTRFS_ROOT_ITEM_KEY;
8545 key.offset = (u64)-1;
8547 root = btrfs_read_fs_root(root->fs_info, &key);
8549 fprintf(stderr, "Couldn't find owner root %llu\n",
8551 return PTR_ERR(root);
8554 path = btrfs_alloc_path();
8558 trans = btrfs_start_transaction(root, 1);
8559 if (IS_ERR(trans)) {
8560 btrfs_free_path(path);
8561 return PTR_ERR(trans);
8564 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8570 ret = btrfs_del_item(trans, root, path);
8572 btrfs_commit_transaction(trans, root);
8573 btrfs_free_path(path);
8577 static int zero_log_tree(struct btrfs_root *root)
8579 struct btrfs_trans_handle *trans;
8582 trans = btrfs_start_transaction(root, 1);
8583 if (IS_ERR(trans)) {
8584 ret = PTR_ERR(trans);
8587 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8588 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8589 ret = btrfs_commit_transaction(trans, root);
8593 static int populate_csum(struct btrfs_trans_handle *trans,
8594 struct btrfs_root *csum_root, char *buf, u64 start,
8601 while (offset < len) {
8602 sectorsize = csum_root->sectorsize;
8603 ret = read_extent_data(csum_root, buf, start + offset,
8607 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8608 start + offset, buf, sectorsize);
8611 offset += sectorsize;
8616 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8617 struct btrfs_root *csum_root)
8619 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8620 struct btrfs_path *path;
8621 struct btrfs_extent_item *ei;
8622 struct extent_buffer *leaf;
8624 struct btrfs_key key;
8627 path = btrfs_alloc_path();
8632 key.type = BTRFS_EXTENT_ITEM_KEY;
8635 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8637 btrfs_free_path(path);
8641 buf = malloc(csum_root->sectorsize);
8643 btrfs_free_path(path);
8648 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8649 ret = btrfs_next_leaf(extent_root, path);
8657 leaf = path->nodes[0];
8659 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8660 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8665 ei = btrfs_item_ptr(leaf, path->slots[0],
8666 struct btrfs_extent_item);
8667 if (!(btrfs_extent_flags(leaf, ei) &
8668 BTRFS_EXTENT_FLAG_DATA)) {
8673 ret = populate_csum(trans, csum_root, buf, key.objectid,
8680 btrfs_free_path(path);
8685 struct root_item_info {
8686 /* level of the root */
8688 /* number of nodes at this level, must be 1 for a root */
8692 struct cache_extent cache_extent;
8695 static struct cache_tree *roots_info_cache = NULL;
8697 static void free_roots_info_cache(void)
8699 if (!roots_info_cache)
8702 while (!cache_tree_empty(roots_info_cache)) {
8703 struct cache_extent *entry;
8704 struct root_item_info *rii;
8706 entry = first_cache_extent(roots_info_cache);
8709 remove_cache_extent(roots_info_cache, entry);
8710 rii = container_of(entry, struct root_item_info, cache_extent);
8714 free(roots_info_cache);
8715 roots_info_cache = NULL;
8718 static int build_roots_info_cache(struct btrfs_fs_info *info)
8721 struct btrfs_key key;
8722 struct extent_buffer *leaf;
8723 struct btrfs_path *path;
8725 if (!roots_info_cache) {
8726 roots_info_cache = malloc(sizeof(*roots_info_cache));
8727 if (!roots_info_cache)
8729 cache_tree_init(roots_info_cache);
8732 path = btrfs_alloc_path();
8737 key.type = BTRFS_EXTENT_ITEM_KEY;
8740 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8743 leaf = path->nodes[0];
8746 struct btrfs_key found_key;
8747 struct btrfs_extent_item *ei;
8748 struct btrfs_extent_inline_ref *iref;
8749 int slot = path->slots[0];
8754 struct cache_extent *entry;
8755 struct root_item_info *rii;
8757 if (slot >= btrfs_header_nritems(leaf)) {
8758 ret = btrfs_next_leaf(info->extent_root, path);
8765 leaf = path->nodes[0];
8766 slot = path->slots[0];
8769 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8771 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8772 found_key.type != BTRFS_METADATA_ITEM_KEY)
8775 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8776 flags = btrfs_extent_flags(leaf, ei);
8778 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8779 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8782 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8783 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8784 level = found_key.offset;
8786 struct btrfs_tree_block_info *info;
8788 info = (struct btrfs_tree_block_info *)(ei + 1);
8789 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8790 level = btrfs_tree_block_level(leaf, info);
8794 * For a root extent, it must be of the following type and the
8795 * first (and only one) iref in the item.
8797 type = btrfs_extent_inline_ref_type(leaf, iref);
8798 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8801 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8802 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8804 rii = malloc(sizeof(struct root_item_info));
8809 rii->cache_extent.start = root_id;
8810 rii->cache_extent.size = 1;
8811 rii->level = (u8)-1;
8812 entry = &rii->cache_extent;
8813 ret = insert_cache_extent(roots_info_cache, entry);
8816 rii = container_of(entry, struct root_item_info,
8820 ASSERT(rii->cache_extent.start == root_id);
8821 ASSERT(rii->cache_extent.size == 1);
8823 if (level > rii->level || rii->level == (u8)-1) {
8825 rii->bytenr = found_key.objectid;
8826 rii->gen = btrfs_extent_generation(leaf, ei);
8827 rii->node_count = 1;
8828 } else if (level == rii->level) {
8836 btrfs_free_path(path);
8841 static int maybe_repair_root_item(struct btrfs_fs_info *info,
8842 struct btrfs_path *path,
8843 const struct btrfs_key *root_key,
8844 const int read_only_mode)
8846 const u64 root_id = root_key->objectid;
8847 struct cache_extent *entry;
8848 struct root_item_info *rii;
8849 struct btrfs_root_item ri;
8850 unsigned long offset;
8852 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8855 "Error: could not find extent items for root %llu\n",
8856 root_key->objectid);
8860 rii = container_of(entry, struct root_item_info, cache_extent);
8861 ASSERT(rii->cache_extent.start == root_id);
8862 ASSERT(rii->cache_extent.size == 1);
8864 if (rii->node_count != 1) {
8866 "Error: could not find btree root extent for root %llu\n",
8871 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
8872 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
8874 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
8875 btrfs_root_level(&ri) != rii->level ||
8876 btrfs_root_generation(&ri) != rii->gen) {
8879 * If we're in repair mode but our caller told us to not update
8880 * the root item, i.e. just check if it needs to be updated, don't
8881 * print this message, since the caller will call us again shortly
8882 * for the same root item without read only mode (the caller will
8883 * open a transaction first).
8885 if (!(read_only_mode && repair))
8887 "%sroot item for root %llu,"
8888 " current bytenr %llu, current gen %llu, current level %u,"
8889 " new bytenr %llu, new gen %llu, new level %u\n",
8890 (read_only_mode ? "" : "fixing "),
8892 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
8893 btrfs_root_level(&ri),
8894 rii->bytenr, rii->gen, rii->level);
8896 if (btrfs_root_generation(&ri) > rii->gen) {
8898 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
8899 root_id, btrfs_root_generation(&ri), rii->gen);
8903 if (!read_only_mode) {
8904 btrfs_set_root_bytenr(&ri, rii->bytenr);
8905 btrfs_set_root_level(&ri, rii->level);
8906 btrfs_set_root_generation(&ri, rii->gen);
8907 write_extent_buffer(path->nodes[0], &ri,
8908 offset, sizeof(ri));
8918 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
8919 * caused read-only snapshots to be corrupted if they were created at a moment
8920 * when the source subvolume/snapshot had orphan items. The issue was that the
8921 * on-disk root items became incorrect, referring to the pre orphan cleanup root
8922 * node instead of the post orphan cleanup root node.
8923 * So this function, and its callees, just detects and fixes those cases. Even
8924 * though the regression was for read-only snapshots, this function applies to
8925 * any snapshot/subvolume root.
8926 * This must be run before any other repair code - not doing it so, makes other
8927 * repair code delete or modify backrefs in the extent tree for example, which
8928 * will result in an inconsistent fs after repairing the root items.
8930 static int repair_root_items(struct btrfs_fs_info *info)
8932 struct btrfs_path *path = NULL;
8933 struct btrfs_key key;
8934 struct extent_buffer *leaf;
8935 struct btrfs_trans_handle *trans = NULL;
8940 ret = build_roots_info_cache(info);
8944 path = btrfs_alloc_path();
8950 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
8951 key.type = BTRFS_ROOT_ITEM_KEY;
8956 * Avoid opening and committing transactions if a leaf doesn't have
8957 * any root items that need to be fixed, so that we avoid rotating
8958 * backup roots unnecessarily.
8961 trans = btrfs_start_transaction(info->tree_root, 1);
8962 if (IS_ERR(trans)) {
8963 ret = PTR_ERR(trans);
8968 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
8972 leaf = path->nodes[0];
8975 struct btrfs_key found_key;
8977 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
8978 int no_more_keys = find_next_key(path, &key);
8980 btrfs_release_path(path);
8982 ret = btrfs_commit_transaction(trans,
8994 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8996 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
8998 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9001 ret = maybe_repair_root_item(info, path, &found_key,
9006 if (!trans && repair) {
9009 btrfs_release_path(path);
9019 free_roots_info_cache();
9021 btrfs_free_path(path);
9023 btrfs_commit_transaction(trans, info->tree_root);
9030 const char * const cmd_check_usage[] = {
9031 "btrfs check [options] <device>",
9032 "Check an unmounted btrfs filesystem.",
9034 "-s|--super <superblock> use this superblock copy",
9035 "-b|--backup use the backup root copy",
9036 "--repair try to repair the filesystem",
9037 "--init-csum-tree create a new CRC tree",
9038 "--init-extent-tree create a new extent tree",
9039 "--check-data-csum verify checkums of data blocks",
9040 "--qgroup-report print a report on qgroup consistency",
9041 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9042 "--tree-root <bytenr> use the given bytenr for the tree root",
9046 int cmd_check(int argc, char **argv)
9048 struct cache_tree root_cache;
9049 struct btrfs_root *root;
9050 struct btrfs_fs_info *info;
9053 u64 tree_root_bytenr = 0;
9054 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9057 int init_csum_tree = 0;
9059 int qgroup_report = 0;
9060 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9064 int option_index = 0;
9065 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9066 OPT_CHECK_CSUM, OPT_READONLY };
9067 static const struct option long_options[] = {
9068 { "super", 1, NULL, 's' },
9069 { "repair", 0, NULL, OPT_REPAIR },
9070 { "readonly", 0, NULL, OPT_READONLY },
9071 { "init-csum-tree", 0, NULL, OPT_INIT_CSUM },
9072 { "init-extent-tree", 0, NULL, OPT_INIT_EXTENT },
9073 { "check-data-csum", 0, NULL, OPT_CHECK_CSUM },
9074 { "backup", 0, NULL, 'b' },
9075 { "subvol-extents", 1, NULL, 'E' },
9076 { "qgroup-report", 0, NULL, 'Q' },
9077 { "tree-root", 1, NULL, 'r' },
9081 c = getopt_long(argc, argv, "as:br:", long_options,
9086 case 'a': /* ignored */ break;
9088 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9091 num = arg_strtou64(optarg);
9092 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9094 "ERROR: super mirror should be less than: %d\n",
9095 BTRFS_SUPER_MIRROR_MAX);
9098 bytenr = btrfs_sb_offset(((int)num));
9099 printf("using SB copy %llu, bytenr %llu\n", num,
9100 (unsigned long long)bytenr);
9106 subvolid = arg_strtou64(optarg);
9109 tree_root_bytenr = arg_strtou64(optarg);
9113 usage(cmd_check_usage);
9115 printf("enabling repair mode\n");
9117 ctree_flags |= OPEN_CTREE_WRITES;
9123 printf("Creating a new CRC tree\n");
9126 ctree_flags |= OPEN_CTREE_WRITES;
9128 case OPT_INIT_EXTENT:
9129 init_extent_tree = 1;
9130 ctree_flags |= (OPEN_CTREE_WRITES |
9131 OPEN_CTREE_NO_BLOCK_GROUPS);
9134 case OPT_CHECK_CSUM:
9135 check_data_csum = 1;
9139 argc = argc - optind;
9141 if (check_argc_exact(argc, 1))
9142 usage(cmd_check_usage);
9144 /* This check is the only reason for --readonly to exist */
9145 if (readonly && repair) {
9146 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9151 cache_tree_init(&root_cache);
9153 if((ret = check_mounted(argv[optind])) < 0) {
9154 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9157 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9162 /* only allow partial opening under repair mode */
9164 ctree_flags |= OPEN_CTREE_PARTIAL;
9166 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9169 fprintf(stderr, "Couldn't open file system\n");
9174 root = info->fs_root;
9177 * repair mode will force us to commit transaction which
9178 * will make us fail to load log tree when mounting.
9180 if (repair && btrfs_super_log_root(info->super_copy)) {
9181 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9186 ret = zero_log_tree(root);
9188 fprintf(stderr, "fail to zero log tree\n");
9193 uuid_unparse(info->super_copy->fsid, uuidbuf);
9194 if (qgroup_report) {
9195 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9197 ret = qgroup_verify_all(info);
9199 print_qgroup_report(1);
9203 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9204 subvolid, argv[optind], uuidbuf);
9205 ret = print_extent_state(info, subvolid);
9208 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9210 if (!extent_buffer_uptodate(info->tree_root->node) ||
9211 !extent_buffer_uptodate(info->dev_root->node) ||
9212 !extent_buffer_uptodate(info->chunk_root->node)) {
9213 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9218 if (init_extent_tree || init_csum_tree) {
9219 struct btrfs_trans_handle *trans;
9221 trans = btrfs_start_transaction(info->extent_root, 0);
9222 if (IS_ERR(trans)) {
9223 fprintf(stderr, "Error starting transaction\n");
9224 ret = PTR_ERR(trans);
9228 if (init_extent_tree) {
9229 printf("Creating a new extent tree\n");
9230 ret = reinit_extent_tree(trans, info);
9235 if (init_csum_tree) {
9236 fprintf(stderr, "Reinit crc root\n");
9237 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9239 fprintf(stderr, "crc root initialization failed\n");
9244 ret = fill_csum_tree(trans, info->csum_root);
9246 fprintf(stderr, "crc refilling failed\n");
9251 * Ok now we commit and run the normal fsck, which will add
9252 * extent entries for all of the items it finds.
9254 ret = btrfs_commit_transaction(trans, info->extent_root);
9258 if (!extent_buffer_uptodate(info->extent_root->node)) {
9259 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9263 if (!extent_buffer_uptodate(info->csum_root->node)) {
9264 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9269 fprintf(stderr, "checking extents\n");
9270 ret = check_chunks_and_extents(root);
9272 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9274 ret = repair_root_items(info);
9278 fprintf(stderr, "Fixed %d roots.\n", ret);
9280 } else if (ret > 0) {
9282 "Found %d roots with an outdated root item.\n",
9285 "Please run a filesystem check with the option --repair to fix them.\n");
9290 fprintf(stderr, "checking free space cache\n");
9291 ret = check_space_cache(root);
9296 * We used to have to have these hole extents in between our real
9297 * extents so if we don't have this flag set we need to make sure there
9298 * are no gaps in the file extents for inodes, otherwise we can just
9299 * ignore it when this happens.
9301 no_holes = btrfs_fs_incompat(root->fs_info,
9302 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9303 fprintf(stderr, "checking fs roots\n");
9304 ret = check_fs_roots(root, &root_cache);
9308 fprintf(stderr, "checking csums\n");
9309 ret = check_csums(root);
9313 fprintf(stderr, "checking root refs\n");
9314 ret = check_root_refs(root, &root_cache);
9318 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9319 struct extent_buffer *eb;
9321 eb = list_first_entry(&root->fs_info->recow_ebs,
9322 struct extent_buffer, recow);
9323 list_del_init(&eb->recow);
9324 ret = recow_extent_buffer(root, eb);
9329 while (!list_empty(&delete_items)) {
9330 struct bad_item *bad;
9332 bad = list_first_entry(&delete_items, struct bad_item, list);
9333 list_del_init(&bad->list);
9335 ret = delete_bad_item(root, bad);
9339 if (info->quota_enabled) {
9341 fprintf(stderr, "checking quota groups\n");
9342 err = qgroup_verify_all(info);
9347 if (!list_empty(&root->fs_info->recow_ebs)) {
9348 fprintf(stderr, "Transid errors in file system\n");
9352 print_qgroup_report(0);
9353 if (found_old_backref) { /*
9354 * there was a disk format change when mixed
9355 * backref was in testing tree. The old format
9356 * existed about one week.
9358 printf("\n * Found old mixed backref format. "
9359 "The old format is not supported! *"
9360 "\n * Please mount the FS in readonly mode, "
9361 "backup data and re-format the FS. *\n\n");
9364 printf("found %llu bytes used err is %d\n",
9365 (unsigned long long)bytes_used, ret);
9366 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9367 printf("total tree bytes: %llu\n",
9368 (unsigned long long)total_btree_bytes);
9369 printf("total fs tree bytes: %llu\n",
9370 (unsigned long long)total_fs_tree_bytes);
9371 printf("total extent tree bytes: %llu\n",
9372 (unsigned long long)total_extent_tree_bytes);
9373 printf("btree space waste bytes: %llu\n",
9374 (unsigned long long)btree_space_waste);
9375 printf("file data blocks allocated: %llu\n referenced %llu\n",
9376 (unsigned long long)data_bytes_allocated,
9377 (unsigned long long)data_bytes_referenced);
9378 printf("%s\n", PACKAGE_STRING);
9380 free_root_recs_tree(&root_cache);