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;
58 static struct btrfs_fs_info *global_info;
60 struct extent_backref {
61 struct list_head list;
62 unsigned int is_data:1;
63 unsigned int found_extent_tree:1;
64 unsigned int full_backref:1;
65 unsigned int found_ref:1;
66 unsigned int broken:1;
70 struct extent_backref node;
85 * Much like data_backref, just removed the undetermined members
86 * and change it to use list_head.
87 * During extent scan, it is stored in root->orphan_data_extent.
88 * During fs tree scan, it is then moved to inode_rec->orphan_data_extents.
90 struct orphan_data_extent {
91 struct list_head list;
100 struct extent_backref node;
107 struct extent_record {
108 struct list_head backrefs;
109 struct list_head dups;
110 struct list_head list;
111 struct cache_extent cache;
112 struct btrfs_disk_key parent_key;
117 u64 extent_item_refs;
119 u64 parent_generation;
123 int flag_block_full_backref;
124 unsigned int found_rec:1;
125 unsigned int content_checked:1;
126 unsigned int owner_ref_checked:1;
127 unsigned int is_root:1;
128 unsigned int metadata:1;
129 unsigned int bad_full_backref:1;
130 unsigned int crossing_stripes:1;
131 unsigned int wrong_chunk_type:1;
134 struct inode_backref {
135 struct list_head list;
136 unsigned int found_dir_item:1;
137 unsigned int found_dir_index:1;
138 unsigned int found_inode_ref:1;
139 unsigned int filetype:8;
141 unsigned int ref_type;
148 struct root_item_record {
149 struct list_head list;
156 struct btrfs_key drop_key;
159 #define REF_ERR_NO_DIR_ITEM (1 << 0)
160 #define REF_ERR_NO_DIR_INDEX (1 << 1)
161 #define REF_ERR_NO_INODE_REF (1 << 2)
162 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
163 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
164 #define REF_ERR_DUP_INODE_REF (1 << 5)
165 #define REF_ERR_INDEX_UNMATCH (1 << 6)
166 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
167 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
168 #define REF_ERR_NO_ROOT_REF (1 << 9)
169 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
170 #define REF_ERR_DUP_ROOT_REF (1 << 11)
171 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
173 struct file_extent_hole {
179 /* Compatible function to allow reuse of old codes */
180 static u64 first_extent_gap(struct rb_root *holes)
182 struct file_extent_hole *hole;
184 if (RB_EMPTY_ROOT(holes))
187 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
191 static int compare_hole(struct rb_node *node1, struct rb_node *node2)
193 struct file_extent_hole *hole1;
194 struct file_extent_hole *hole2;
196 hole1 = rb_entry(node1, struct file_extent_hole, node);
197 hole2 = rb_entry(node2, struct file_extent_hole, node);
199 if (hole1->start > hole2->start)
201 if (hole1->start < hole2->start)
203 /* Now hole1->start == hole2->start */
204 if (hole1->len >= hole2->len)
206 * Hole 1 will be merge center
207 * Same hole will be merged later
210 /* Hole 2 will be merge center */
215 * Add a hole to the record
217 * This will do hole merge for copy_file_extent_holes(),
218 * which will ensure there won't be continuous holes.
220 static int add_file_extent_hole(struct rb_root *holes,
223 struct file_extent_hole *hole;
224 struct file_extent_hole *prev = NULL;
225 struct file_extent_hole *next = NULL;
227 hole = malloc(sizeof(*hole));
232 /* Since compare will not return 0, no -EEXIST will happen */
233 rb_insert(holes, &hole->node, compare_hole);
235 /* simple merge with previous hole */
236 if (rb_prev(&hole->node))
237 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
239 if (prev && prev->start + prev->len >= hole->start) {
240 hole->len = hole->start + hole->len - prev->start;
241 hole->start = prev->start;
242 rb_erase(&prev->node, holes);
247 /* iterate merge with next holes */
249 if (!rb_next(&hole->node))
251 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
253 if (hole->start + hole->len >= next->start) {
254 if (hole->start + hole->len <= next->start + next->len)
255 hole->len = next->start + next->len -
257 rb_erase(&next->node, holes);
266 static int compare_hole_range(struct rb_node *node, void *data)
268 struct file_extent_hole *hole;
271 hole = (struct file_extent_hole *)data;
274 hole = rb_entry(node, struct file_extent_hole, node);
275 if (start < hole->start)
277 if (start >= hole->start && start < hole->start + hole->len)
283 * Delete a hole in the record
285 * This will do the hole split and is much restrict than add.
287 static int del_file_extent_hole(struct rb_root *holes,
290 struct file_extent_hole *hole;
291 struct file_extent_hole tmp;
296 struct rb_node *node;
303 node = rb_search(holes, &tmp, compare_hole_range, NULL);
306 hole = rb_entry(node, struct file_extent_hole, node);
307 if (start + len > hole->start + hole->len)
311 * Now there will be no overflap, delete the hole and re-add the
312 * split(s) if they exists.
314 if (start > hole->start) {
315 prev_start = hole->start;
316 prev_len = start - hole->start;
319 if (hole->start + hole->len > start + len) {
320 next_start = start + len;
321 next_len = hole->start + hole->len - start - len;
324 rb_erase(node, holes);
327 ret = add_file_extent_hole(holes, prev_start, prev_len);
332 ret = add_file_extent_hole(holes, next_start, next_len);
339 static int copy_file_extent_holes(struct rb_root *dst,
342 struct file_extent_hole *hole;
343 struct rb_node *node;
346 node = rb_first(src);
348 hole = rb_entry(node, struct file_extent_hole, node);
349 ret = add_file_extent_hole(dst, hole->start, hole->len);
352 node = rb_next(node);
357 static void free_file_extent_holes(struct rb_root *holes)
359 struct rb_node *node;
360 struct file_extent_hole *hole;
362 node = rb_first(holes);
364 hole = rb_entry(node, struct file_extent_hole, node);
365 rb_erase(node, holes);
367 node = rb_first(holes);
371 struct inode_record {
372 struct list_head backrefs;
373 unsigned int checked:1;
374 unsigned int merging:1;
375 unsigned int found_inode_item:1;
376 unsigned int found_dir_item:1;
377 unsigned int found_file_extent:1;
378 unsigned int found_csum_item:1;
379 unsigned int some_csum_missing:1;
380 unsigned int nodatasum:1;
393 struct rb_root holes;
394 struct list_head orphan_extents;
399 #define I_ERR_NO_INODE_ITEM (1 << 0)
400 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
401 #define I_ERR_DUP_INODE_ITEM (1 << 2)
402 #define I_ERR_DUP_DIR_INDEX (1 << 3)
403 #define I_ERR_ODD_DIR_ITEM (1 << 4)
404 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
405 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
406 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
407 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
408 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
409 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
410 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
411 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
412 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
413 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
415 struct root_backref {
416 struct list_head list;
417 unsigned int found_dir_item:1;
418 unsigned int found_dir_index:1;
419 unsigned int found_back_ref:1;
420 unsigned int found_forward_ref:1;
421 unsigned int reachable:1;
431 struct list_head backrefs;
432 struct cache_extent cache;
433 unsigned int found_root_item:1;
439 struct cache_extent cache;
444 struct cache_extent cache;
445 struct cache_tree root_cache;
446 struct cache_tree inode_cache;
447 struct inode_record *current;
456 struct walk_control {
457 struct cache_tree shared;
458 struct shared_node *nodes[BTRFS_MAX_LEVEL];
464 struct btrfs_key key;
466 struct list_head list;
469 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
471 static void record_root_in_trans(struct btrfs_trans_handle *trans,
472 struct btrfs_root *root)
474 if (root->last_trans != trans->transid) {
475 root->track_dirty = 1;
476 root->last_trans = trans->transid;
477 root->commit_root = root->node;
478 extent_buffer_get(root->node);
482 static u8 imode_to_type(u32 imode)
485 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
486 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
487 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
488 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
489 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
490 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
491 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
492 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
495 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
499 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
501 struct device_record *rec1;
502 struct device_record *rec2;
504 rec1 = rb_entry(node1, struct device_record, node);
505 rec2 = rb_entry(node2, struct device_record, node);
506 if (rec1->devid > rec2->devid)
508 else if (rec1->devid < rec2->devid)
514 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
516 struct inode_record *rec;
517 struct inode_backref *backref;
518 struct inode_backref *orig;
519 struct orphan_data_extent *src_orphan;
520 struct orphan_data_extent *dst_orphan;
524 rec = malloc(sizeof(*rec));
525 memcpy(rec, orig_rec, sizeof(*rec));
527 INIT_LIST_HEAD(&rec->backrefs);
528 INIT_LIST_HEAD(&rec->orphan_extents);
529 rec->holes = RB_ROOT;
531 list_for_each_entry(orig, &orig_rec->backrefs, list) {
532 size = sizeof(*orig) + orig->namelen + 1;
533 backref = malloc(size);
534 memcpy(backref, orig, size);
535 list_add_tail(&backref->list, &rec->backrefs);
537 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
538 dst_orphan = malloc(sizeof(*dst_orphan));
539 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
541 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
542 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
544 ret = copy_file_extent_holes(&rec->holes, &orig_rec->holes);
550 static void print_orphan_data_extents(struct list_head *orphan_extents,
553 struct orphan_data_extent *orphan;
555 if (list_empty(orphan_extents))
557 printf("The following data extent is lost in tree %llu:\n",
559 list_for_each_entry(orphan, orphan_extents, list) {
560 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
561 orphan->objectid, orphan->offset, orphan->disk_bytenr,
566 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
568 u64 root_objectid = root->root_key.objectid;
569 int errors = rec->errors;
573 /* reloc root errors, we print its corresponding fs root objectid*/
574 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
575 root_objectid = root->root_key.offset;
576 fprintf(stderr, "reloc");
578 fprintf(stderr, "root %llu inode %llu errors %x",
579 (unsigned long long) root_objectid,
580 (unsigned long long) rec->ino, rec->errors);
582 if (errors & I_ERR_NO_INODE_ITEM)
583 fprintf(stderr, ", no inode item");
584 if (errors & I_ERR_NO_ORPHAN_ITEM)
585 fprintf(stderr, ", no orphan item");
586 if (errors & I_ERR_DUP_INODE_ITEM)
587 fprintf(stderr, ", dup inode item");
588 if (errors & I_ERR_DUP_DIR_INDEX)
589 fprintf(stderr, ", dup dir index");
590 if (errors & I_ERR_ODD_DIR_ITEM)
591 fprintf(stderr, ", odd dir item");
592 if (errors & I_ERR_ODD_FILE_EXTENT)
593 fprintf(stderr, ", odd file extent");
594 if (errors & I_ERR_BAD_FILE_EXTENT)
595 fprintf(stderr, ", bad file extent");
596 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
597 fprintf(stderr, ", file extent overlap");
598 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
599 fprintf(stderr, ", file extent discount");
600 if (errors & I_ERR_DIR_ISIZE_WRONG)
601 fprintf(stderr, ", dir isize wrong");
602 if (errors & I_ERR_FILE_NBYTES_WRONG)
603 fprintf(stderr, ", nbytes wrong");
604 if (errors & I_ERR_ODD_CSUM_ITEM)
605 fprintf(stderr, ", odd csum item");
606 if (errors & I_ERR_SOME_CSUM_MISSING)
607 fprintf(stderr, ", some csum missing");
608 if (errors & I_ERR_LINK_COUNT_WRONG)
609 fprintf(stderr, ", link count wrong");
610 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
611 fprintf(stderr, ", orphan file extent");
612 fprintf(stderr, "\n");
613 /* Print the orphan extents if needed */
614 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
615 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
617 /* Print the holes if needed */
618 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
619 struct file_extent_hole *hole;
620 struct rb_node *node;
623 node = rb_first(&rec->holes);
624 fprintf(stderr, "Found file extent holes:\n");
627 hole = rb_entry(node, struct file_extent_hole, node);
628 fprintf(stderr, "\tstart: %llu, len: %llu\n",
629 hole->start, hole->len);
630 node = rb_next(node);
633 fprintf(stderr, "\tstart: 0, len: %llu\n",
634 round_up(rec->isize, root->sectorsize));
638 static void print_ref_error(int errors)
640 if (errors & REF_ERR_NO_DIR_ITEM)
641 fprintf(stderr, ", no dir item");
642 if (errors & REF_ERR_NO_DIR_INDEX)
643 fprintf(stderr, ", no dir index");
644 if (errors & REF_ERR_NO_INODE_REF)
645 fprintf(stderr, ", no inode ref");
646 if (errors & REF_ERR_DUP_DIR_ITEM)
647 fprintf(stderr, ", dup dir item");
648 if (errors & REF_ERR_DUP_DIR_INDEX)
649 fprintf(stderr, ", dup dir index");
650 if (errors & REF_ERR_DUP_INODE_REF)
651 fprintf(stderr, ", dup inode ref");
652 if (errors & REF_ERR_INDEX_UNMATCH)
653 fprintf(stderr, ", index unmatch");
654 if (errors & REF_ERR_FILETYPE_UNMATCH)
655 fprintf(stderr, ", filetype unmatch");
656 if (errors & REF_ERR_NAME_TOO_LONG)
657 fprintf(stderr, ", name too long");
658 if (errors & REF_ERR_NO_ROOT_REF)
659 fprintf(stderr, ", no root ref");
660 if (errors & REF_ERR_NO_ROOT_BACKREF)
661 fprintf(stderr, ", no root backref");
662 if (errors & REF_ERR_DUP_ROOT_REF)
663 fprintf(stderr, ", dup root ref");
664 if (errors & REF_ERR_DUP_ROOT_BACKREF)
665 fprintf(stderr, ", dup root backref");
666 fprintf(stderr, "\n");
669 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
672 struct ptr_node *node;
673 struct cache_extent *cache;
674 struct inode_record *rec = NULL;
677 cache = lookup_cache_extent(inode_cache, ino, 1);
679 node = container_of(cache, struct ptr_node, cache);
681 if (mod && rec->refs > 1) {
682 node->data = clone_inode_rec(rec);
687 rec = calloc(1, sizeof(*rec));
689 rec->extent_start = (u64)-1;
691 INIT_LIST_HEAD(&rec->backrefs);
692 INIT_LIST_HEAD(&rec->orphan_extents);
693 rec->holes = RB_ROOT;
695 node = malloc(sizeof(*node));
696 node->cache.start = ino;
697 node->cache.size = 1;
700 if (ino == BTRFS_FREE_INO_OBJECTID)
703 ret = insert_cache_extent(inode_cache, &node->cache);
709 static void free_orphan_data_extents(struct list_head *orphan_extents)
711 struct orphan_data_extent *orphan;
713 while (!list_empty(orphan_extents)) {
714 orphan = list_entry(orphan_extents->next,
715 struct orphan_data_extent, list);
716 list_del(&orphan->list);
721 static void free_inode_rec(struct inode_record *rec)
723 struct inode_backref *backref;
728 while (!list_empty(&rec->backrefs)) {
729 backref = list_entry(rec->backrefs.next,
730 struct inode_backref, list);
731 list_del(&backref->list);
734 free_orphan_data_extents(&rec->orphan_extents);
735 free_file_extent_holes(&rec->holes);
739 static int can_free_inode_rec(struct inode_record *rec)
741 if (!rec->errors && rec->checked && rec->found_inode_item &&
742 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
747 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
748 struct inode_record *rec)
750 struct cache_extent *cache;
751 struct inode_backref *tmp, *backref;
752 struct ptr_node *node;
753 unsigned char filetype;
755 if (!rec->found_inode_item)
758 filetype = imode_to_type(rec->imode);
759 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
760 if (backref->found_dir_item && backref->found_dir_index) {
761 if (backref->filetype != filetype)
762 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
763 if (!backref->errors && backref->found_inode_ref) {
764 list_del(&backref->list);
770 if (!rec->checked || rec->merging)
773 if (S_ISDIR(rec->imode)) {
774 if (rec->found_size != rec->isize)
775 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
776 if (rec->found_file_extent)
777 rec->errors |= I_ERR_ODD_FILE_EXTENT;
778 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
779 if (rec->found_dir_item)
780 rec->errors |= I_ERR_ODD_DIR_ITEM;
781 if (rec->found_size != rec->nbytes)
782 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
783 if (rec->nlink > 0 && !no_holes &&
784 (rec->extent_end < rec->isize ||
785 first_extent_gap(&rec->holes) < rec->isize))
786 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
789 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
790 if (rec->found_csum_item && rec->nodatasum)
791 rec->errors |= I_ERR_ODD_CSUM_ITEM;
792 if (rec->some_csum_missing && !rec->nodatasum)
793 rec->errors |= I_ERR_SOME_CSUM_MISSING;
796 BUG_ON(rec->refs != 1);
797 if (can_free_inode_rec(rec)) {
798 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
799 node = container_of(cache, struct ptr_node, cache);
800 BUG_ON(node->data != rec);
801 remove_cache_extent(inode_cache, &node->cache);
807 static int check_orphan_item(struct btrfs_root *root, u64 ino)
809 struct btrfs_path path;
810 struct btrfs_key key;
813 key.objectid = BTRFS_ORPHAN_OBJECTID;
814 key.type = BTRFS_ORPHAN_ITEM_KEY;
817 btrfs_init_path(&path);
818 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
819 btrfs_release_path(&path);
825 static int process_inode_item(struct extent_buffer *eb,
826 int slot, struct btrfs_key *key,
827 struct shared_node *active_node)
829 struct inode_record *rec;
830 struct btrfs_inode_item *item;
832 rec = active_node->current;
833 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
834 if (rec->found_inode_item) {
835 rec->errors |= I_ERR_DUP_INODE_ITEM;
838 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
839 rec->nlink = btrfs_inode_nlink(eb, item);
840 rec->isize = btrfs_inode_size(eb, item);
841 rec->nbytes = btrfs_inode_nbytes(eb, item);
842 rec->imode = btrfs_inode_mode(eb, item);
843 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
845 rec->found_inode_item = 1;
847 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
848 maybe_free_inode_rec(&active_node->inode_cache, rec);
852 static struct inode_backref *get_inode_backref(struct inode_record *rec,
854 int namelen, u64 dir)
856 struct inode_backref *backref;
858 list_for_each_entry(backref, &rec->backrefs, list) {
859 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
861 if (backref->dir != dir || backref->namelen != namelen)
863 if (memcmp(name, backref->name, namelen))
868 backref = malloc(sizeof(*backref) + namelen + 1);
869 memset(backref, 0, sizeof(*backref));
871 backref->namelen = namelen;
872 memcpy(backref->name, name, namelen);
873 backref->name[namelen] = '\0';
874 list_add_tail(&backref->list, &rec->backrefs);
878 static int add_inode_backref(struct cache_tree *inode_cache,
879 u64 ino, u64 dir, u64 index,
880 const char *name, int namelen,
881 int filetype, int itemtype, int errors)
883 struct inode_record *rec;
884 struct inode_backref *backref;
886 rec = get_inode_rec(inode_cache, ino, 1);
887 backref = get_inode_backref(rec, name, namelen, dir);
889 backref->errors |= errors;
890 if (itemtype == BTRFS_DIR_INDEX_KEY) {
891 if (backref->found_dir_index)
892 backref->errors |= REF_ERR_DUP_DIR_INDEX;
893 if (backref->found_inode_ref && backref->index != index)
894 backref->errors |= REF_ERR_INDEX_UNMATCH;
895 if (backref->found_dir_item && backref->filetype != filetype)
896 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
898 backref->index = index;
899 backref->filetype = filetype;
900 backref->found_dir_index = 1;
901 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
903 if (backref->found_dir_item)
904 backref->errors |= REF_ERR_DUP_DIR_ITEM;
905 if (backref->found_dir_index && backref->filetype != filetype)
906 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
908 backref->filetype = filetype;
909 backref->found_dir_item = 1;
910 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
911 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
912 if (backref->found_inode_ref)
913 backref->errors |= REF_ERR_DUP_INODE_REF;
914 if (backref->found_dir_index && backref->index != index)
915 backref->errors |= REF_ERR_INDEX_UNMATCH;
917 backref->index = index;
919 backref->ref_type = itemtype;
920 backref->found_inode_ref = 1;
925 maybe_free_inode_rec(inode_cache, rec);
929 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
930 struct cache_tree *dst_cache)
932 struct inode_backref *backref;
937 list_for_each_entry(backref, &src->backrefs, list) {
938 if (backref->found_dir_index) {
939 add_inode_backref(dst_cache, dst->ino, backref->dir,
940 backref->index, backref->name,
941 backref->namelen, backref->filetype,
942 BTRFS_DIR_INDEX_KEY, backref->errors);
944 if (backref->found_dir_item) {
946 add_inode_backref(dst_cache, dst->ino,
947 backref->dir, 0, backref->name,
948 backref->namelen, backref->filetype,
949 BTRFS_DIR_ITEM_KEY, backref->errors);
951 if (backref->found_inode_ref) {
952 add_inode_backref(dst_cache, dst->ino,
953 backref->dir, backref->index,
954 backref->name, backref->namelen, 0,
955 backref->ref_type, backref->errors);
959 if (src->found_dir_item)
960 dst->found_dir_item = 1;
961 if (src->found_file_extent)
962 dst->found_file_extent = 1;
963 if (src->found_csum_item)
964 dst->found_csum_item = 1;
965 if (src->some_csum_missing)
966 dst->some_csum_missing = 1;
967 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
968 ret = copy_file_extent_holes(&dst->holes, &src->holes);
973 BUG_ON(src->found_link < dir_count);
974 dst->found_link += src->found_link - dir_count;
975 dst->found_size += src->found_size;
976 if (src->extent_start != (u64)-1) {
977 if (dst->extent_start == (u64)-1) {
978 dst->extent_start = src->extent_start;
979 dst->extent_end = src->extent_end;
981 if (dst->extent_end > src->extent_start)
982 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
983 else if (dst->extent_end < src->extent_start) {
984 ret = add_file_extent_hole(&dst->holes,
986 src->extent_start - dst->extent_end);
988 if (dst->extent_end < src->extent_end)
989 dst->extent_end = src->extent_end;
993 dst->errors |= src->errors;
994 if (src->found_inode_item) {
995 if (!dst->found_inode_item) {
996 dst->nlink = src->nlink;
997 dst->isize = src->isize;
998 dst->nbytes = src->nbytes;
999 dst->imode = src->imode;
1000 dst->nodatasum = src->nodatasum;
1001 dst->found_inode_item = 1;
1003 dst->errors |= I_ERR_DUP_INODE_ITEM;
1011 static int splice_shared_node(struct shared_node *src_node,
1012 struct shared_node *dst_node)
1014 struct cache_extent *cache;
1015 struct ptr_node *node, *ins;
1016 struct cache_tree *src, *dst;
1017 struct inode_record *rec, *conflict;
1018 u64 current_ino = 0;
1022 if (--src_node->refs == 0)
1024 if (src_node->current)
1025 current_ino = src_node->current->ino;
1027 src = &src_node->root_cache;
1028 dst = &dst_node->root_cache;
1030 cache = search_cache_extent(src, 0);
1032 node = container_of(cache, struct ptr_node, cache);
1034 cache = next_cache_extent(cache);
1037 remove_cache_extent(src, &node->cache);
1040 ins = malloc(sizeof(*ins));
1041 ins->cache.start = node->cache.start;
1042 ins->cache.size = node->cache.size;
1046 ret = insert_cache_extent(dst, &ins->cache);
1047 if (ret == -EEXIST) {
1048 conflict = get_inode_rec(dst, rec->ino, 1);
1049 merge_inode_recs(rec, conflict, dst);
1051 conflict->checked = 1;
1052 if (dst_node->current == conflict)
1053 dst_node->current = NULL;
1055 maybe_free_inode_rec(dst, conflict);
1056 free_inode_rec(rec);
1063 if (src == &src_node->root_cache) {
1064 src = &src_node->inode_cache;
1065 dst = &dst_node->inode_cache;
1069 if (current_ino > 0 && (!dst_node->current ||
1070 current_ino > dst_node->current->ino)) {
1071 if (dst_node->current) {
1072 dst_node->current->checked = 1;
1073 maybe_free_inode_rec(dst, dst_node->current);
1075 dst_node->current = get_inode_rec(dst, current_ino, 1);
1080 static void free_inode_ptr(struct cache_extent *cache)
1082 struct ptr_node *node;
1083 struct inode_record *rec;
1085 node = container_of(cache, struct ptr_node, cache);
1087 free_inode_rec(rec);
1091 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1093 static struct shared_node *find_shared_node(struct cache_tree *shared,
1096 struct cache_extent *cache;
1097 struct shared_node *node;
1099 cache = lookup_cache_extent(shared, bytenr, 1);
1101 node = container_of(cache, struct shared_node, cache);
1107 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1110 struct shared_node *node;
1112 node = calloc(1, sizeof(*node));
1113 node->cache.start = bytenr;
1114 node->cache.size = 1;
1115 cache_tree_init(&node->root_cache);
1116 cache_tree_init(&node->inode_cache);
1119 ret = insert_cache_extent(shared, &node->cache);
1124 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1125 struct walk_control *wc, int level)
1127 struct shared_node *node;
1128 struct shared_node *dest;
1130 if (level == wc->active_node)
1133 BUG_ON(wc->active_node <= level);
1134 node = find_shared_node(&wc->shared, bytenr);
1136 add_shared_node(&wc->shared, bytenr, refs);
1137 node = find_shared_node(&wc->shared, bytenr);
1138 wc->nodes[level] = node;
1139 wc->active_node = level;
1143 if (wc->root_level == wc->active_node &&
1144 btrfs_root_refs(&root->root_item) == 0) {
1145 if (--node->refs == 0) {
1146 free_inode_recs_tree(&node->root_cache);
1147 free_inode_recs_tree(&node->inode_cache);
1148 remove_cache_extent(&wc->shared, &node->cache);
1154 dest = wc->nodes[wc->active_node];
1155 splice_shared_node(node, dest);
1156 if (node->refs == 0) {
1157 remove_cache_extent(&wc->shared, &node->cache);
1163 static int leave_shared_node(struct btrfs_root *root,
1164 struct walk_control *wc, int level)
1166 struct shared_node *node;
1167 struct shared_node *dest;
1170 if (level == wc->root_level)
1173 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1177 BUG_ON(i >= BTRFS_MAX_LEVEL);
1179 node = wc->nodes[wc->active_node];
1180 wc->nodes[wc->active_node] = NULL;
1181 wc->active_node = i;
1183 dest = wc->nodes[wc->active_node];
1184 if (wc->active_node < wc->root_level ||
1185 btrfs_root_refs(&root->root_item) > 0) {
1186 BUG_ON(node->refs <= 1);
1187 splice_shared_node(node, dest);
1189 BUG_ON(node->refs < 2);
1198 * 1 - if the root with id child_root_id is a child of root parent_root_id
1199 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1200 * has other root(s) as parent(s)
1201 * 2 - if the root child_root_id doesn't have any parent roots
1203 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1206 struct btrfs_path path;
1207 struct btrfs_key key;
1208 struct extent_buffer *leaf;
1212 btrfs_init_path(&path);
1214 key.objectid = parent_root_id;
1215 key.type = BTRFS_ROOT_REF_KEY;
1216 key.offset = child_root_id;
1217 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1221 btrfs_release_path(&path);
1225 key.objectid = child_root_id;
1226 key.type = BTRFS_ROOT_BACKREF_KEY;
1228 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1234 leaf = path.nodes[0];
1235 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1236 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1239 leaf = path.nodes[0];
1242 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1243 if (key.objectid != child_root_id ||
1244 key.type != BTRFS_ROOT_BACKREF_KEY)
1249 if (key.offset == parent_root_id) {
1250 btrfs_release_path(&path);
1257 btrfs_release_path(&path);
1260 return has_parent ? 0 : 2;
1263 static int process_dir_item(struct btrfs_root *root,
1264 struct extent_buffer *eb,
1265 int slot, struct btrfs_key *key,
1266 struct shared_node *active_node)
1276 struct btrfs_dir_item *di;
1277 struct inode_record *rec;
1278 struct cache_tree *root_cache;
1279 struct cache_tree *inode_cache;
1280 struct btrfs_key location;
1281 char namebuf[BTRFS_NAME_LEN];
1283 root_cache = &active_node->root_cache;
1284 inode_cache = &active_node->inode_cache;
1285 rec = active_node->current;
1286 rec->found_dir_item = 1;
1288 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1289 total = btrfs_item_size_nr(eb, slot);
1290 while (cur < total) {
1292 btrfs_dir_item_key_to_cpu(eb, di, &location);
1293 name_len = btrfs_dir_name_len(eb, di);
1294 data_len = btrfs_dir_data_len(eb, di);
1295 filetype = btrfs_dir_type(eb, di);
1297 rec->found_size += name_len;
1298 if (name_len <= BTRFS_NAME_LEN) {
1302 len = BTRFS_NAME_LEN;
1303 error = REF_ERR_NAME_TOO_LONG;
1305 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1307 if (location.type == BTRFS_INODE_ITEM_KEY) {
1308 add_inode_backref(inode_cache, location.objectid,
1309 key->objectid, key->offset, namebuf,
1310 len, filetype, key->type, error);
1311 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1312 add_inode_backref(root_cache, location.objectid,
1313 key->objectid, key->offset,
1314 namebuf, len, filetype,
1317 fprintf(stderr, "invalid location in dir item %u\n",
1319 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1320 key->objectid, key->offset, namebuf,
1321 len, filetype, key->type, error);
1324 len = sizeof(*di) + name_len + data_len;
1325 di = (struct btrfs_dir_item *)((char *)di + len);
1328 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1329 rec->errors |= I_ERR_DUP_DIR_INDEX;
1334 static int process_inode_ref(struct extent_buffer *eb,
1335 int slot, struct btrfs_key *key,
1336 struct shared_node *active_node)
1344 struct cache_tree *inode_cache;
1345 struct btrfs_inode_ref *ref;
1346 char namebuf[BTRFS_NAME_LEN];
1348 inode_cache = &active_node->inode_cache;
1350 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1351 total = btrfs_item_size_nr(eb, slot);
1352 while (cur < total) {
1353 name_len = btrfs_inode_ref_name_len(eb, ref);
1354 index = btrfs_inode_ref_index(eb, ref);
1355 if (name_len <= BTRFS_NAME_LEN) {
1359 len = BTRFS_NAME_LEN;
1360 error = REF_ERR_NAME_TOO_LONG;
1362 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1363 add_inode_backref(inode_cache, key->objectid, key->offset,
1364 index, namebuf, len, 0, key->type, error);
1366 len = sizeof(*ref) + name_len;
1367 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1373 static int process_inode_extref(struct extent_buffer *eb,
1374 int slot, struct btrfs_key *key,
1375 struct shared_node *active_node)
1384 struct cache_tree *inode_cache;
1385 struct btrfs_inode_extref *extref;
1386 char namebuf[BTRFS_NAME_LEN];
1388 inode_cache = &active_node->inode_cache;
1390 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1391 total = btrfs_item_size_nr(eb, slot);
1392 while (cur < total) {
1393 name_len = btrfs_inode_extref_name_len(eb, extref);
1394 index = btrfs_inode_extref_index(eb, extref);
1395 parent = btrfs_inode_extref_parent(eb, extref);
1396 if (name_len <= BTRFS_NAME_LEN) {
1400 len = BTRFS_NAME_LEN;
1401 error = REF_ERR_NAME_TOO_LONG;
1403 read_extent_buffer(eb, namebuf,
1404 (unsigned long)(extref + 1), len);
1405 add_inode_backref(inode_cache, key->objectid, parent,
1406 index, namebuf, len, 0, key->type, error);
1408 len = sizeof(*extref) + name_len;
1409 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1416 static int count_csum_range(struct btrfs_root *root, u64 start,
1417 u64 len, u64 *found)
1419 struct btrfs_key key;
1420 struct btrfs_path path;
1421 struct extent_buffer *leaf;
1426 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1428 btrfs_init_path(&path);
1430 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1432 key.type = BTRFS_EXTENT_CSUM_KEY;
1434 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1438 if (ret > 0 && path.slots[0] > 0) {
1439 leaf = path.nodes[0];
1440 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1441 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1442 key.type == BTRFS_EXTENT_CSUM_KEY)
1447 leaf = path.nodes[0];
1448 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1449 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1454 leaf = path.nodes[0];
1457 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1458 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1459 key.type != BTRFS_EXTENT_CSUM_KEY)
1462 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1463 if (key.offset >= start + len)
1466 if (key.offset > start)
1469 size = btrfs_item_size_nr(leaf, path.slots[0]);
1470 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1471 if (csum_end > start) {
1472 size = min(csum_end - start, len);
1481 btrfs_release_path(&path);
1487 static int process_file_extent(struct btrfs_root *root,
1488 struct extent_buffer *eb,
1489 int slot, struct btrfs_key *key,
1490 struct shared_node *active_node)
1492 struct inode_record *rec;
1493 struct btrfs_file_extent_item *fi;
1495 u64 disk_bytenr = 0;
1496 u64 extent_offset = 0;
1497 u64 mask = root->sectorsize - 1;
1501 rec = active_node->current;
1502 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1503 rec->found_file_extent = 1;
1505 if (rec->extent_start == (u64)-1) {
1506 rec->extent_start = key->offset;
1507 rec->extent_end = key->offset;
1510 if (rec->extent_end > key->offset)
1511 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1512 else if (rec->extent_end < key->offset) {
1513 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1514 key->offset - rec->extent_end);
1519 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1520 extent_type = btrfs_file_extent_type(eb, fi);
1522 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1523 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1525 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1526 rec->found_size += num_bytes;
1527 num_bytes = (num_bytes + mask) & ~mask;
1528 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1529 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1530 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1531 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1532 extent_offset = btrfs_file_extent_offset(eb, fi);
1533 if (num_bytes == 0 || (num_bytes & mask))
1534 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1535 if (num_bytes + extent_offset >
1536 btrfs_file_extent_ram_bytes(eb, fi))
1537 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1538 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1539 (btrfs_file_extent_compression(eb, fi) ||
1540 btrfs_file_extent_encryption(eb, fi) ||
1541 btrfs_file_extent_other_encoding(eb, fi)))
1542 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1543 if (disk_bytenr > 0)
1544 rec->found_size += num_bytes;
1546 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1548 rec->extent_end = key->offset + num_bytes;
1551 * The data reloc tree will copy full extents into its inode and then
1552 * copy the corresponding csums. Because the extent it copied could be
1553 * a preallocated extent that hasn't been written to yet there may be no
1554 * csums to copy, ergo we won't have csums for our file extent. This is
1555 * ok so just don't bother checking csums if the inode belongs to the
1558 if (disk_bytenr > 0 &&
1559 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1561 if (btrfs_file_extent_compression(eb, fi))
1562 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1564 disk_bytenr += extent_offset;
1566 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1569 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1571 rec->found_csum_item = 1;
1572 if (found < num_bytes)
1573 rec->some_csum_missing = 1;
1574 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1576 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1582 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1583 struct walk_control *wc)
1585 struct btrfs_key key;
1589 struct cache_tree *inode_cache;
1590 struct shared_node *active_node;
1592 if (wc->root_level == wc->active_node &&
1593 btrfs_root_refs(&root->root_item) == 0)
1596 active_node = wc->nodes[wc->active_node];
1597 inode_cache = &active_node->inode_cache;
1598 nritems = btrfs_header_nritems(eb);
1599 for (i = 0; i < nritems; i++) {
1600 btrfs_item_key_to_cpu(eb, &key, i);
1602 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1604 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1607 if (active_node->current == NULL ||
1608 active_node->current->ino < key.objectid) {
1609 if (active_node->current) {
1610 active_node->current->checked = 1;
1611 maybe_free_inode_rec(inode_cache,
1612 active_node->current);
1614 active_node->current = get_inode_rec(inode_cache,
1618 case BTRFS_DIR_ITEM_KEY:
1619 case BTRFS_DIR_INDEX_KEY:
1620 ret = process_dir_item(root, eb, i, &key, active_node);
1622 case BTRFS_INODE_REF_KEY:
1623 ret = process_inode_ref(eb, i, &key, active_node);
1625 case BTRFS_INODE_EXTREF_KEY:
1626 ret = process_inode_extref(eb, i, &key, active_node);
1628 case BTRFS_INODE_ITEM_KEY:
1629 ret = process_inode_item(eb, i, &key, active_node);
1631 case BTRFS_EXTENT_DATA_KEY:
1632 ret = process_file_extent(root, eb, i, &key,
1642 static void reada_walk_down(struct btrfs_root *root,
1643 struct extent_buffer *node, int slot)
1652 level = btrfs_header_level(node);
1656 nritems = btrfs_header_nritems(node);
1657 blocksize = btrfs_level_size(root, level - 1);
1658 for (i = slot; i < nritems; i++) {
1659 bytenr = btrfs_node_blockptr(node, i);
1660 ptr_gen = btrfs_node_ptr_generation(node, i);
1661 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1666 * Check the child node/leaf by the following condition:
1667 * 1. the first item key of the node/leaf should be the same with the one
1669 * 2. block in parent node should match the child node/leaf.
1670 * 3. generation of parent node and child's header should be consistent.
1672 * Or the child node/leaf pointed by the key in parent is not valid.
1674 * We hope to check leaf owner too, but since subvol may share leaves,
1675 * which makes leaf owner check not so strong, key check should be
1676 * sufficient enough for that case.
1678 static int check_child_node(struct btrfs_root *root,
1679 struct extent_buffer *parent, int slot,
1680 struct extent_buffer *child)
1682 struct btrfs_key parent_key;
1683 struct btrfs_key child_key;
1686 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1687 if (btrfs_header_level(child) == 0)
1688 btrfs_item_key_to_cpu(child, &child_key, 0);
1690 btrfs_node_key_to_cpu(child, &child_key, 0);
1692 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1695 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1696 parent_key.objectid, parent_key.type, parent_key.offset,
1697 child_key.objectid, child_key.type, child_key.offset);
1699 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1701 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1702 btrfs_node_blockptr(parent, slot),
1703 btrfs_header_bytenr(child));
1705 if (btrfs_node_ptr_generation(parent, slot) !=
1706 btrfs_header_generation(child)) {
1708 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1709 btrfs_header_generation(child),
1710 btrfs_node_ptr_generation(parent, slot));
1715 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1716 struct walk_control *wc, int *level)
1718 enum btrfs_tree_block_status status;
1721 struct extent_buffer *next;
1722 struct extent_buffer *cur;
1727 WARN_ON(*level < 0);
1728 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1729 ret = btrfs_lookup_extent_info(NULL, root,
1730 path->nodes[*level]->start,
1731 *level, 1, &refs, NULL);
1738 ret = enter_shared_node(root, path->nodes[*level]->start,
1746 while (*level >= 0) {
1747 WARN_ON(*level < 0);
1748 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1749 cur = path->nodes[*level];
1751 if (btrfs_header_level(cur) != *level)
1754 if (path->slots[*level] >= btrfs_header_nritems(cur))
1757 ret = process_one_leaf(root, cur, wc);
1762 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1763 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1764 blocksize = btrfs_level_size(root, *level - 1);
1765 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1771 ret = enter_shared_node(root, bytenr, refs,
1774 path->slots[*level]++;
1779 next = btrfs_find_tree_block(root, bytenr, blocksize);
1780 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1781 free_extent_buffer(next);
1782 reada_walk_down(root, cur, path->slots[*level]);
1783 next = read_tree_block(root, bytenr, blocksize,
1785 if (!extent_buffer_uptodate(next)) {
1786 struct btrfs_key node_key;
1788 btrfs_node_key_to_cpu(path->nodes[*level],
1790 path->slots[*level]);
1791 btrfs_add_corrupt_extent_record(root->fs_info,
1793 path->nodes[*level]->start,
1794 root->leafsize, *level);
1800 ret = check_child_node(root, cur, path->slots[*level], next);
1806 if (btrfs_is_leaf(next))
1807 status = btrfs_check_leaf(root, NULL, next);
1809 status = btrfs_check_node(root, NULL, next);
1810 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1811 free_extent_buffer(next);
1816 *level = *level - 1;
1817 free_extent_buffer(path->nodes[*level]);
1818 path->nodes[*level] = next;
1819 path->slots[*level] = 0;
1822 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1826 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1827 struct walk_control *wc, int *level)
1830 struct extent_buffer *leaf;
1832 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1833 leaf = path->nodes[i];
1834 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1839 free_extent_buffer(path->nodes[*level]);
1840 path->nodes[*level] = NULL;
1841 BUG_ON(*level > wc->active_node);
1842 if (*level == wc->active_node)
1843 leave_shared_node(root, wc, *level);
1850 static int check_root_dir(struct inode_record *rec)
1852 struct inode_backref *backref;
1855 if (!rec->found_inode_item || rec->errors)
1857 if (rec->nlink != 1 || rec->found_link != 0)
1859 if (list_empty(&rec->backrefs))
1861 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1862 if (!backref->found_inode_ref)
1864 if (backref->index != 0 || backref->namelen != 2 ||
1865 memcmp(backref->name, "..", 2))
1867 if (backref->found_dir_index || backref->found_dir_item)
1874 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1875 struct btrfs_root *root, struct btrfs_path *path,
1876 struct inode_record *rec)
1878 struct btrfs_inode_item *ei;
1879 struct btrfs_key key;
1882 key.objectid = rec->ino;
1883 key.type = BTRFS_INODE_ITEM_KEY;
1884 key.offset = (u64)-1;
1886 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1890 if (!path->slots[0]) {
1897 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1898 if (key.objectid != rec->ino) {
1903 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1904 struct btrfs_inode_item);
1905 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1906 btrfs_mark_buffer_dirty(path->nodes[0]);
1907 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1908 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1909 root->root_key.objectid);
1911 btrfs_release_path(path);
1915 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1916 struct btrfs_root *root,
1917 struct btrfs_path *path,
1918 struct inode_record *rec)
1922 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1923 btrfs_release_path(path);
1925 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1929 static int repair_inode_nbytes(struct btrfs_trans_handle *trans,
1930 struct btrfs_root *root,
1931 struct btrfs_path *path,
1932 struct inode_record *rec)
1934 struct btrfs_inode_item *ei;
1935 struct btrfs_key key;
1938 key.objectid = rec->ino;
1939 key.type = BTRFS_INODE_ITEM_KEY;
1942 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1949 /* Since ret == 0, no need to check anything */
1950 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1951 struct btrfs_inode_item);
1952 btrfs_set_inode_nbytes(path->nodes[0], ei, rec->found_size);
1953 btrfs_mark_buffer_dirty(path->nodes[0]);
1954 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
1955 printf("reset nbytes for ino %llu root %llu\n",
1956 rec->ino, root->root_key.objectid);
1958 btrfs_release_path(path);
1962 static int add_missing_dir_index(struct btrfs_root *root,
1963 struct cache_tree *inode_cache,
1964 struct inode_record *rec,
1965 struct inode_backref *backref)
1967 struct btrfs_path *path;
1968 struct btrfs_trans_handle *trans;
1969 struct btrfs_dir_item *dir_item;
1970 struct extent_buffer *leaf;
1971 struct btrfs_key key;
1972 struct btrfs_disk_key disk_key;
1973 struct inode_record *dir_rec;
1974 unsigned long name_ptr;
1975 u32 data_size = sizeof(*dir_item) + backref->namelen;
1978 path = btrfs_alloc_path();
1982 trans = btrfs_start_transaction(root, 1);
1983 if (IS_ERR(trans)) {
1984 btrfs_free_path(path);
1985 return PTR_ERR(trans);
1988 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1989 (unsigned long long)rec->ino);
1990 key.objectid = backref->dir;
1991 key.type = BTRFS_DIR_INDEX_KEY;
1992 key.offset = backref->index;
1994 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1997 leaf = path->nodes[0];
1998 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
2000 disk_key.objectid = cpu_to_le64(rec->ino);
2001 disk_key.type = BTRFS_INODE_ITEM_KEY;
2002 disk_key.offset = 0;
2004 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
2005 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
2006 btrfs_set_dir_data_len(leaf, dir_item, 0);
2007 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
2008 name_ptr = (unsigned long)(dir_item + 1);
2009 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
2010 btrfs_mark_buffer_dirty(leaf);
2011 btrfs_free_path(path);
2012 btrfs_commit_transaction(trans, root);
2014 backref->found_dir_index = 1;
2015 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
2018 dir_rec->found_size += backref->namelen;
2019 if (dir_rec->found_size == dir_rec->isize &&
2020 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
2021 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
2022 if (dir_rec->found_size != dir_rec->isize)
2023 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
2028 static int delete_dir_index(struct btrfs_root *root,
2029 struct cache_tree *inode_cache,
2030 struct inode_record *rec,
2031 struct inode_backref *backref)
2033 struct btrfs_trans_handle *trans;
2034 struct btrfs_dir_item *di;
2035 struct btrfs_path *path;
2038 path = btrfs_alloc_path();
2042 trans = btrfs_start_transaction(root, 1);
2043 if (IS_ERR(trans)) {
2044 btrfs_free_path(path);
2045 return PTR_ERR(trans);
2049 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2050 (unsigned long long)backref->dir,
2051 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2052 (unsigned long long)root->objectid);
2054 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2055 backref->name, backref->namelen,
2056 backref->index, -1);
2059 btrfs_free_path(path);
2060 btrfs_commit_transaction(trans, root);
2067 ret = btrfs_del_item(trans, root, path);
2069 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2071 btrfs_free_path(path);
2072 btrfs_commit_transaction(trans, root);
2076 static int create_inode_item(struct btrfs_root *root,
2077 struct inode_record *rec,
2078 struct inode_backref *backref, int root_dir)
2080 struct btrfs_trans_handle *trans;
2081 struct btrfs_inode_item inode_item;
2082 time_t now = time(NULL);
2085 trans = btrfs_start_transaction(root, 1);
2086 if (IS_ERR(trans)) {
2087 ret = PTR_ERR(trans);
2091 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2092 "be incomplete, please check permissions and content after "
2093 "the fsck completes.\n", (unsigned long long)root->objectid,
2094 (unsigned long long)rec->ino);
2096 memset(&inode_item, 0, sizeof(inode_item));
2097 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2099 btrfs_set_stack_inode_nlink(&inode_item, 1);
2101 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2102 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2103 if (rec->found_dir_item) {
2104 if (rec->found_file_extent)
2105 fprintf(stderr, "root %llu inode %llu has both a dir "
2106 "item and extents, unsure if it is a dir or a "
2107 "regular file so setting it as a directory\n",
2108 (unsigned long long)root->objectid,
2109 (unsigned long long)rec->ino);
2110 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2111 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2112 } else if (!rec->found_dir_item) {
2113 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2114 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2116 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2117 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2118 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2119 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2120 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2121 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2122 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2123 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2125 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2127 btrfs_commit_transaction(trans, root);
2131 static int repair_inode_backrefs(struct btrfs_root *root,
2132 struct inode_record *rec,
2133 struct cache_tree *inode_cache,
2136 struct inode_backref *tmp, *backref;
2137 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2141 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2142 if (!delete && rec->ino == root_dirid) {
2143 if (!rec->found_inode_item) {
2144 ret = create_inode_item(root, rec, backref, 1);
2151 /* Index 0 for root dir's are special, don't mess with it */
2152 if (rec->ino == root_dirid && backref->index == 0)
2156 ((backref->found_dir_index && !backref->found_inode_ref) ||
2157 (backref->found_dir_index && backref->found_inode_ref &&
2158 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2159 ret = delete_dir_index(root, inode_cache, rec, backref);
2163 list_del(&backref->list);
2167 if (!delete && !backref->found_dir_index &&
2168 backref->found_dir_item && backref->found_inode_ref) {
2169 ret = add_missing_dir_index(root, inode_cache, rec,
2174 if (backref->found_dir_item &&
2175 backref->found_dir_index &&
2176 backref->found_dir_index) {
2177 if (!backref->errors &&
2178 backref->found_inode_ref) {
2179 list_del(&backref->list);
2185 if (!delete && (!backref->found_dir_index &&
2186 !backref->found_dir_item &&
2187 backref->found_inode_ref)) {
2188 struct btrfs_trans_handle *trans;
2189 struct btrfs_key location;
2191 ret = check_dir_conflict(root, backref->name,
2197 * let nlink fixing routine to handle it,
2198 * which can do it better.
2203 location.objectid = rec->ino;
2204 location.type = BTRFS_INODE_ITEM_KEY;
2205 location.offset = 0;
2207 trans = btrfs_start_transaction(root, 1);
2208 if (IS_ERR(trans)) {
2209 ret = PTR_ERR(trans);
2212 fprintf(stderr, "adding missing dir index/item pair "
2214 (unsigned long long)rec->ino);
2215 ret = btrfs_insert_dir_item(trans, root, backref->name,
2217 backref->dir, &location,
2218 imode_to_type(rec->imode),
2221 btrfs_commit_transaction(trans, root);
2225 if (!delete && (backref->found_inode_ref &&
2226 backref->found_dir_index &&
2227 backref->found_dir_item &&
2228 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2229 !rec->found_inode_item)) {
2230 ret = create_inode_item(root, rec, backref, 0);
2237 return ret ? ret : repaired;
2241 * To determine the file type for nlink/inode_item repair
2243 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2244 * Return -ENOENT if file type is not found.
2246 static int find_file_type(struct inode_record *rec, u8 *type)
2248 struct inode_backref *backref;
2250 /* For inode item recovered case */
2251 if (rec->found_inode_item) {
2252 *type = imode_to_type(rec->imode);
2256 list_for_each_entry(backref, &rec->backrefs, list) {
2257 if (backref->found_dir_index || backref->found_dir_item) {
2258 *type = backref->filetype;
2266 * To determine the file name for nlink repair
2268 * Return 0 if file name is found, set name and namelen.
2269 * Return -ENOENT if file name is not found.
2271 static int find_file_name(struct inode_record *rec,
2272 char *name, int *namelen)
2274 struct inode_backref *backref;
2276 list_for_each_entry(backref, &rec->backrefs, list) {
2277 if (backref->found_dir_index || backref->found_dir_item ||
2278 backref->found_inode_ref) {
2279 memcpy(name, backref->name, backref->namelen);
2280 *namelen = backref->namelen;
2287 /* Reset the nlink of the inode to the correct one */
2288 static int reset_nlink(struct btrfs_trans_handle *trans,
2289 struct btrfs_root *root,
2290 struct btrfs_path *path,
2291 struct inode_record *rec)
2293 struct inode_backref *backref;
2294 struct inode_backref *tmp;
2295 struct btrfs_key key;
2296 struct btrfs_inode_item *inode_item;
2299 /* We don't believe this either, reset it and iterate backref */
2300 rec->found_link = 0;
2302 /* Remove all backref including the valid ones */
2303 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2304 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2305 backref->index, backref->name,
2306 backref->namelen, 0);
2310 /* remove invalid backref, so it won't be added back */
2311 if (!(backref->found_dir_index &&
2312 backref->found_dir_item &&
2313 backref->found_inode_ref)) {
2314 list_del(&backref->list);
2321 /* Set nlink to 0 */
2322 key.objectid = rec->ino;
2323 key.type = BTRFS_INODE_ITEM_KEY;
2325 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2332 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2333 struct btrfs_inode_item);
2334 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2335 btrfs_mark_buffer_dirty(path->nodes[0]);
2336 btrfs_release_path(path);
2339 * Add back valid inode_ref/dir_item/dir_index,
2340 * add_link() will handle the nlink inc, so new nlink must be correct
2342 list_for_each_entry(backref, &rec->backrefs, list) {
2343 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2344 backref->name, backref->namelen,
2345 backref->ref_type, &backref->index, 1);
2350 btrfs_release_path(path);
2354 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2355 struct btrfs_root *root,
2356 struct btrfs_path *path,
2357 struct inode_record *rec)
2359 char *dir_name = "lost+found";
2360 char namebuf[BTRFS_NAME_LEN] = {0};
2365 int name_recovered = 0;
2366 int type_recovered = 0;
2370 * Get file name and type first before these invalid inode ref
2371 * are deleted by remove_all_invalid_backref()
2373 name_recovered = !find_file_name(rec, namebuf, &namelen);
2374 type_recovered = !find_file_type(rec, &type);
2376 if (!name_recovered) {
2377 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2378 rec->ino, rec->ino);
2379 namelen = count_digits(rec->ino);
2380 sprintf(namebuf, "%llu", rec->ino);
2383 if (!type_recovered) {
2384 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2386 type = BTRFS_FT_REG_FILE;
2390 ret = reset_nlink(trans, root, path, rec);
2393 "Failed to reset nlink for inode %llu: %s\n",
2394 rec->ino, strerror(-ret));
2398 if (rec->found_link == 0) {
2399 lost_found_ino = root->highest_inode;
2400 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2405 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2406 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2409 fprintf(stderr, "Failed to create '%s' dir: %s\n",
2410 dir_name, strerror(-ret));
2413 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2414 namebuf, namelen, type, NULL, 1);
2416 * Add ".INO" suffix several times to handle case where
2417 * "FILENAME.INO" is already taken by another file.
2419 while (ret == -EEXIST) {
2421 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2423 if (namelen + count_digits(rec->ino) + 1 >
2428 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2430 namelen += count_digits(rec->ino) + 1;
2431 ret = btrfs_add_link(trans, root, rec->ino,
2432 lost_found_ino, namebuf,
2433 namelen, type, NULL, 1);
2437 "Failed to link the inode %llu to %s dir: %s\n",
2438 rec->ino, dir_name, strerror(-ret));
2442 * Just increase the found_link, don't actually add the
2443 * backref. This will make things easier and this inode
2444 * record will be freed after the repair is done.
2445 * So fsck will not report problem about this inode.
2448 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2449 namelen, namebuf, dir_name);
2451 printf("Fixed the nlink of inode %llu\n", rec->ino);
2454 * Clear the flag anyway, or we will loop forever for the same inode
2455 * as it will not be removed from the bad inode list and the dead loop
2458 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2459 btrfs_release_path(path);
2464 * Check if there is any normal(reg or prealloc) file extent for given
2466 * This is used to determine the file type when neither its dir_index/item or
2467 * inode_item exists.
2469 * This will *NOT* report error, if any error happens, just consider it does
2470 * not have any normal file extent.
2472 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2474 struct btrfs_path *path;
2475 struct btrfs_key key;
2476 struct btrfs_key found_key;
2477 struct btrfs_file_extent_item *fi;
2481 path = btrfs_alloc_path();
2485 key.type = BTRFS_EXTENT_DATA_KEY;
2488 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2493 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2494 ret = btrfs_next_leaf(root, path);
2501 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2503 if (found_key.objectid != ino ||
2504 found_key.type != BTRFS_EXTENT_DATA_KEY)
2506 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2507 struct btrfs_file_extent_item);
2508 type = btrfs_file_extent_type(path->nodes[0], fi);
2509 if (type != BTRFS_FILE_EXTENT_INLINE) {
2515 btrfs_free_path(path);
2519 static u32 btrfs_type_to_imode(u8 type)
2521 static u32 imode_by_btrfs_type[] = {
2522 [BTRFS_FT_REG_FILE] = S_IFREG,
2523 [BTRFS_FT_DIR] = S_IFDIR,
2524 [BTRFS_FT_CHRDEV] = S_IFCHR,
2525 [BTRFS_FT_BLKDEV] = S_IFBLK,
2526 [BTRFS_FT_FIFO] = S_IFIFO,
2527 [BTRFS_FT_SOCK] = S_IFSOCK,
2528 [BTRFS_FT_SYMLINK] = S_IFLNK,
2531 return imode_by_btrfs_type[(type)];
2534 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2535 struct btrfs_root *root,
2536 struct btrfs_path *path,
2537 struct inode_record *rec)
2541 int type_recovered = 0;
2544 printf("Trying to rebuild inode:%llu\n", rec->ino);
2546 type_recovered = !find_file_type(rec, &filetype);
2549 * Try to determine inode type if type not found.
2551 * For found regular file extent, it must be FILE.
2552 * For found dir_item/index, it must be DIR.
2554 * For undetermined one, use FILE as fallback.
2557 * 1. If found backref(inode_index/item is already handled) to it,
2559 * Need new inode-inode ref structure to allow search for that.
2561 if (!type_recovered) {
2562 if (rec->found_file_extent &&
2563 find_normal_file_extent(root, rec->ino)) {
2565 filetype = BTRFS_FT_REG_FILE;
2566 } else if (rec->found_dir_item) {
2568 filetype = BTRFS_FT_DIR;
2569 } else if (!list_empty(&rec->orphan_extents)) {
2571 filetype = BTRFS_FT_REG_FILE;
2573 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2576 filetype = BTRFS_FT_REG_FILE;
2580 ret = btrfs_new_inode(trans, root, rec->ino,
2581 mode | btrfs_type_to_imode(filetype));
2586 * Here inode rebuild is done, we only rebuild the inode item,
2587 * don't repair the nlink(like move to lost+found).
2588 * That is the job of nlink repair.
2590 * We just fill the record and return
2592 rec->found_dir_item = 1;
2593 rec->imode = mode | btrfs_type_to_imode(filetype);
2595 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2596 /* Ensure the inode_nlinks repair function will be called */
2597 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2602 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2603 struct btrfs_root *root,
2604 struct btrfs_path *path,
2605 struct inode_record *rec)
2607 struct orphan_data_extent *orphan;
2608 struct orphan_data_extent *tmp;
2611 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2613 * Check for conflicting file extents
2615 * Here we don't know whether the extents is compressed or not,
2616 * so we can only assume it not compressed nor data offset,
2617 * and use its disk_len as extent length.
2619 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2620 orphan->offset, orphan->disk_len, 0);
2621 btrfs_release_path(path);
2626 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2627 orphan->disk_bytenr, orphan->disk_len);
2628 ret = btrfs_free_extent(trans,
2629 root->fs_info->extent_root,
2630 orphan->disk_bytenr, orphan->disk_len,
2631 0, root->objectid, orphan->objectid,
2636 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2637 orphan->offset, orphan->disk_bytenr,
2638 orphan->disk_len, orphan->disk_len);
2642 /* Update file size info */
2643 rec->found_size += orphan->disk_len;
2644 if (rec->found_size == rec->nbytes)
2645 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2647 /* Update the file extent hole info too */
2648 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2652 if (RB_EMPTY_ROOT(&rec->holes))
2653 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2655 list_del(&orphan->list);
2658 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2663 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2664 struct btrfs_root *root,
2665 struct btrfs_path *path,
2666 struct inode_record *rec)
2668 struct rb_node *node;
2669 struct file_extent_hole *hole;
2673 node = rb_first(&rec->holes);
2677 hole = rb_entry(node, struct file_extent_hole, node);
2678 ret = btrfs_punch_hole(trans, root, rec->ino,
2679 hole->start, hole->len);
2682 ret = del_file_extent_hole(&rec->holes, hole->start,
2686 if (RB_EMPTY_ROOT(&rec->holes))
2687 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2688 node = rb_first(&rec->holes);
2690 /* special case for a file losing all its file extent */
2692 ret = btrfs_punch_hole(trans, root, rec->ino, 0,
2693 round_up(rec->isize, root->sectorsize));
2697 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2698 rec->ino, root->objectid);
2703 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2705 struct btrfs_trans_handle *trans;
2706 struct btrfs_path *path;
2709 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2710 I_ERR_NO_ORPHAN_ITEM |
2711 I_ERR_LINK_COUNT_WRONG |
2712 I_ERR_NO_INODE_ITEM |
2713 I_ERR_FILE_EXTENT_ORPHAN |
2714 I_ERR_FILE_EXTENT_DISCOUNT|
2715 I_ERR_FILE_NBYTES_WRONG)))
2718 path = btrfs_alloc_path();
2723 * For nlink repair, it may create a dir and add link, so
2724 * 2 for parent(256)'s dir_index and dir_item
2725 * 2 for lost+found dir's inode_item and inode_ref
2726 * 1 for the new inode_ref of the file
2727 * 2 for lost+found dir's dir_index and dir_item for the file
2729 trans = btrfs_start_transaction(root, 7);
2730 if (IS_ERR(trans)) {
2731 btrfs_free_path(path);
2732 return PTR_ERR(trans);
2735 if (rec->errors & I_ERR_NO_INODE_ITEM)
2736 ret = repair_inode_no_item(trans, root, path, rec);
2737 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2738 ret = repair_inode_orphan_extent(trans, root, path, rec);
2739 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2740 ret = repair_inode_discount_extent(trans, root, path, rec);
2741 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2742 ret = repair_inode_isize(trans, root, path, rec);
2743 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2744 ret = repair_inode_orphan_item(trans, root, path, rec);
2745 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2746 ret = repair_inode_nlinks(trans, root, path, rec);
2747 if (!ret && rec->errors & I_ERR_FILE_NBYTES_WRONG)
2748 ret = repair_inode_nbytes(trans, root, path, rec);
2749 btrfs_commit_transaction(trans, root);
2750 btrfs_free_path(path);
2754 static int check_inode_recs(struct btrfs_root *root,
2755 struct cache_tree *inode_cache)
2757 struct cache_extent *cache;
2758 struct ptr_node *node;
2759 struct inode_record *rec;
2760 struct inode_backref *backref;
2765 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2767 if (btrfs_root_refs(&root->root_item) == 0) {
2768 if (!cache_tree_empty(inode_cache))
2769 fprintf(stderr, "warning line %d\n", __LINE__);
2774 * We need to record the highest inode number for later 'lost+found'
2776 * We must select a ino not used/refered by any existing inode, or
2777 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2778 * this may cause 'lost+found' dir has wrong nlinks.
2780 cache = last_cache_extent(inode_cache);
2782 node = container_of(cache, struct ptr_node, cache);
2784 if (rec->ino > root->highest_inode)
2785 root->highest_inode = rec->ino;
2789 * We need to repair backrefs first because we could change some of the
2790 * errors in the inode recs.
2792 * We also need to go through and delete invalid backrefs first and then
2793 * add the correct ones second. We do this because we may get EEXIST
2794 * when adding back the correct index because we hadn't yet deleted the
2797 * For example, if we were missing a dir index then the directories
2798 * isize would be wrong, so if we fixed the isize to what we thought it
2799 * would be and then fixed the backref we'd still have a invalid fs, so
2800 * we need to add back the dir index and then check to see if the isize
2805 if (stage == 3 && !err)
2808 cache = search_cache_extent(inode_cache, 0);
2809 while (repair && cache) {
2810 node = container_of(cache, struct ptr_node, cache);
2812 cache = next_cache_extent(cache);
2814 /* Need to free everything up and rescan */
2816 remove_cache_extent(inode_cache, &node->cache);
2818 free_inode_rec(rec);
2822 if (list_empty(&rec->backrefs))
2825 ret = repair_inode_backrefs(root, rec, inode_cache,
2839 rec = get_inode_rec(inode_cache, root_dirid, 0);
2841 ret = check_root_dir(rec);
2843 fprintf(stderr, "root %llu root dir %llu error\n",
2844 (unsigned long long)root->root_key.objectid,
2845 (unsigned long long)root_dirid);
2846 print_inode_error(root, rec);
2851 struct btrfs_trans_handle *trans;
2853 trans = btrfs_start_transaction(root, 1);
2854 if (IS_ERR(trans)) {
2855 err = PTR_ERR(trans);
2860 "root %llu missing its root dir, recreating\n",
2861 (unsigned long long)root->objectid);
2863 ret = btrfs_make_root_dir(trans, root, root_dirid);
2866 btrfs_commit_transaction(trans, root);
2870 fprintf(stderr, "root %llu root dir %llu not found\n",
2871 (unsigned long long)root->root_key.objectid,
2872 (unsigned long long)root_dirid);
2876 cache = search_cache_extent(inode_cache, 0);
2879 node = container_of(cache, struct ptr_node, cache);
2881 remove_cache_extent(inode_cache, &node->cache);
2883 if (rec->ino == root_dirid ||
2884 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2885 free_inode_rec(rec);
2889 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2890 ret = check_orphan_item(root, rec->ino);
2892 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2893 if (can_free_inode_rec(rec)) {
2894 free_inode_rec(rec);
2899 if (!rec->found_inode_item)
2900 rec->errors |= I_ERR_NO_INODE_ITEM;
2901 if (rec->found_link != rec->nlink)
2902 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2904 ret = try_repair_inode(root, rec);
2905 if (ret == 0 && can_free_inode_rec(rec)) {
2906 free_inode_rec(rec);
2912 if (!(repair && ret == 0))
2914 print_inode_error(root, rec);
2915 list_for_each_entry(backref, &rec->backrefs, list) {
2916 if (!backref->found_dir_item)
2917 backref->errors |= REF_ERR_NO_DIR_ITEM;
2918 if (!backref->found_dir_index)
2919 backref->errors |= REF_ERR_NO_DIR_INDEX;
2920 if (!backref->found_inode_ref)
2921 backref->errors |= REF_ERR_NO_INODE_REF;
2922 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2923 " namelen %u name %s filetype %d errors %x",
2924 (unsigned long long)backref->dir,
2925 (unsigned long long)backref->index,
2926 backref->namelen, backref->name,
2927 backref->filetype, backref->errors);
2928 print_ref_error(backref->errors);
2930 free_inode_rec(rec);
2932 return (error > 0) ? -1 : 0;
2935 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2938 struct cache_extent *cache;
2939 struct root_record *rec = NULL;
2942 cache = lookup_cache_extent(root_cache, objectid, 1);
2944 rec = container_of(cache, struct root_record, cache);
2946 rec = calloc(1, sizeof(*rec));
2947 rec->objectid = objectid;
2948 INIT_LIST_HEAD(&rec->backrefs);
2949 rec->cache.start = objectid;
2950 rec->cache.size = 1;
2952 ret = insert_cache_extent(root_cache, &rec->cache);
2958 static struct root_backref *get_root_backref(struct root_record *rec,
2959 u64 ref_root, u64 dir, u64 index,
2960 const char *name, int namelen)
2962 struct root_backref *backref;
2964 list_for_each_entry(backref, &rec->backrefs, list) {
2965 if (backref->ref_root != ref_root || backref->dir != dir ||
2966 backref->namelen != namelen)
2968 if (memcmp(name, backref->name, namelen))
2973 backref = malloc(sizeof(*backref) + namelen + 1);
2974 memset(backref, 0, sizeof(*backref) + namelen + 1);
2975 backref->ref_root = ref_root;
2977 backref->index = index;
2978 backref->namelen = namelen;
2979 memcpy(backref->name, name, namelen);
2980 backref->name[namelen] = '\0';
2981 list_add_tail(&backref->list, &rec->backrefs);
2985 static void free_root_record(struct cache_extent *cache)
2987 struct root_record *rec;
2988 struct root_backref *backref;
2990 rec = container_of(cache, struct root_record, cache);
2991 while (!list_empty(&rec->backrefs)) {
2992 backref = list_entry(rec->backrefs.next,
2993 struct root_backref, list);
2994 list_del(&backref->list);
3001 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
3003 static int add_root_backref(struct cache_tree *root_cache,
3004 u64 root_id, u64 ref_root, u64 dir, u64 index,
3005 const char *name, int namelen,
3006 int item_type, int errors)
3008 struct root_record *rec;
3009 struct root_backref *backref;
3011 rec = get_root_rec(root_cache, root_id);
3012 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
3014 backref->errors |= errors;
3016 if (item_type != BTRFS_DIR_ITEM_KEY) {
3017 if (backref->found_dir_index || backref->found_back_ref ||
3018 backref->found_forward_ref) {
3019 if (backref->index != index)
3020 backref->errors |= REF_ERR_INDEX_UNMATCH;
3022 backref->index = index;
3026 if (item_type == BTRFS_DIR_ITEM_KEY) {
3027 if (backref->found_forward_ref)
3029 backref->found_dir_item = 1;
3030 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
3031 backref->found_dir_index = 1;
3032 } else if (item_type == BTRFS_ROOT_REF_KEY) {
3033 if (backref->found_forward_ref)
3034 backref->errors |= REF_ERR_DUP_ROOT_REF;
3035 else if (backref->found_dir_item)
3037 backref->found_forward_ref = 1;
3038 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
3039 if (backref->found_back_ref)
3040 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
3041 backref->found_back_ref = 1;
3046 if (backref->found_forward_ref && backref->found_dir_item)
3047 backref->reachable = 1;
3051 static int merge_root_recs(struct btrfs_root *root,
3052 struct cache_tree *src_cache,
3053 struct cache_tree *dst_cache)
3055 struct cache_extent *cache;
3056 struct ptr_node *node;
3057 struct inode_record *rec;
3058 struct inode_backref *backref;
3061 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3062 free_inode_recs_tree(src_cache);
3067 cache = search_cache_extent(src_cache, 0);
3070 node = container_of(cache, struct ptr_node, cache);
3072 remove_cache_extent(src_cache, &node->cache);
3075 ret = is_child_root(root, root->objectid, rec->ino);
3081 list_for_each_entry(backref, &rec->backrefs, list) {
3082 BUG_ON(backref->found_inode_ref);
3083 if (backref->found_dir_item)
3084 add_root_backref(dst_cache, rec->ino,
3085 root->root_key.objectid, backref->dir,
3086 backref->index, backref->name,
3087 backref->namelen, BTRFS_DIR_ITEM_KEY,
3089 if (backref->found_dir_index)
3090 add_root_backref(dst_cache, rec->ino,
3091 root->root_key.objectid, backref->dir,
3092 backref->index, backref->name,
3093 backref->namelen, BTRFS_DIR_INDEX_KEY,
3097 free_inode_rec(rec);
3104 static int check_root_refs(struct btrfs_root *root,
3105 struct cache_tree *root_cache)
3107 struct root_record *rec;
3108 struct root_record *ref_root;
3109 struct root_backref *backref;
3110 struct cache_extent *cache;
3116 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3119 /* fixme: this can not detect circular references */
3122 cache = search_cache_extent(root_cache, 0);
3126 rec = container_of(cache, struct root_record, cache);
3127 cache = next_cache_extent(cache);
3129 if (rec->found_ref == 0)
3132 list_for_each_entry(backref, &rec->backrefs, list) {
3133 if (!backref->reachable)
3136 ref_root = get_root_rec(root_cache,
3138 if (ref_root->found_ref > 0)
3141 backref->reachable = 0;
3143 if (rec->found_ref == 0)
3149 cache = search_cache_extent(root_cache, 0);
3153 rec = container_of(cache, struct root_record, cache);
3154 cache = next_cache_extent(cache);
3156 if (rec->found_ref == 0 &&
3157 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3158 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3159 ret = check_orphan_item(root->fs_info->tree_root,
3165 * If we don't have a root item then we likely just have
3166 * a dir item in a snapshot for this root but no actual
3167 * ref key or anything so it's meaningless.
3169 if (!rec->found_root_item)
3172 fprintf(stderr, "fs tree %llu not referenced\n",
3173 (unsigned long long)rec->objectid);
3177 if (rec->found_ref > 0 && !rec->found_root_item)
3179 list_for_each_entry(backref, &rec->backrefs, list) {
3180 if (!backref->found_dir_item)
3181 backref->errors |= REF_ERR_NO_DIR_ITEM;
3182 if (!backref->found_dir_index)
3183 backref->errors |= REF_ERR_NO_DIR_INDEX;
3184 if (!backref->found_back_ref)
3185 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3186 if (!backref->found_forward_ref)
3187 backref->errors |= REF_ERR_NO_ROOT_REF;
3188 if (backref->reachable && backref->errors)
3195 fprintf(stderr, "fs tree %llu refs %u %s\n",
3196 (unsigned long long)rec->objectid, rec->found_ref,
3197 rec->found_root_item ? "" : "not found");
3199 list_for_each_entry(backref, &rec->backrefs, list) {
3200 if (!backref->reachable)
3202 if (!backref->errors && rec->found_root_item)
3204 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3205 " index %llu namelen %u name %s errors %x\n",
3206 (unsigned long long)backref->ref_root,
3207 (unsigned long long)backref->dir,
3208 (unsigned long long)backref->index,
3209 backref->namelen, backref->name,
3211 print_ref_error(backref->errors);
3214 return errors > 0 ? 1 : 0;
3217 static int process_root_ref(struct extent_buffer *eb, int slot,
3218 struct btrfs_key *key,
3219 struct cache_tree *root_cache)
3225 struct btrfs_root_ref *ref;
3226 char namebuf[BTRFS_NAME_LEN];
3229 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3231 dirid = btrfs_root_ref_dirid(eb, ref);
3232 index = btrfs_root_ref_sequence(eb, ref);
3233 name_len = btrfs_root_ref_name_len(eb, ref);
3235 if (name_len <= BTRFS_NAME_LEN) {
3239 len = BTRFS_NAME_LEN;
3240 error = REF_ERR_NAME_TOO_LONG;
3242 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3244 if (key->type == BTRFS_ROOT_REF_KEY) {
3245 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3246 index, namebuf, len, key->type, error);
3248 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3249 index, namebuf, len, key->type, error);
3254 static void free_corrupt_block(struct cache_extent *cache)
3256 struct btrfs_corrupt_block *corrupt;
3258 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3262 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3265 * Repair the btree of the given root.
3267 * The fix is to remove the node key in corrupt_blocks cache_tree.
3268 * and rebalance the tree.
3269 * After the fix, the btree should be writeable.
3271 static int repair_btree(struct btrfs_root *root,
3272 struct cache_tree *corrupt_blocks)
3274 struct btrfs_trans_handle *trans;
3275 struct btrfs_path *path;
3276 struct btrfs_corrupt_block *corrupt;
3277 struct cache_extent *cache;
3278 struct btrfs_key key;
3283 if (cache_tree_empty(corrupt_blocks))
3286 path = btrfs_alloc_path();
3290 trans = btrfs_start_transaction(root, 1);
3291 if (IS_ERR(trans)) {
3292 ret = PTR_ERR(trans);
3293 fprintf(stderr, "Error starting transaction: %s\n",
3297 cache = first_cache_extent(corrupt_blocks);
3299 corrupt = container_of(cache, struct btrfs_corrupt_block,
3301 level = corrupt->level;
3302 path->lowest_level = level;
3303 key.objectid = corrupt->key.objectid;
3304 key.type = corrupt->key.type;
3305 key.offset = corrupt->key.offset;
3308 * Here we don't want to do any tree balance, since it may
3309 * cause a balance with corrupted brother leaf/node,
3310 * so ins_len set to 0 here.
3311 * Balance will be done after all corrupt node/leaf is deleted.
3313 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3316 offset = btrfs_node_blockptr(path->nodes[level],
3317 path->slots[level]);
3319 /* Remove the ptr */
3320 ret = btrfs_del_ptr(trans, root, path, level,
3321 path->slots[level]);
3325 * Remove the corresponding extent
3326 * return value is not concerned.
3328 btrfs_release_path(path);
3329 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3330 0, root->root_key.objectid,
3332 cache = next_cache_extent(cache);
3335 /* Balance the btree using btrfs_search_slot() */
3336 cache = first_cache_extent(corrupt_blocks);
3338 corrupt = container_of(cache, struct btrfs_corrupt_block,
3340 memcpy(&key, &corrupt->key, sizeof(key));
3341 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3344 /* return will always >0 since it won't find the item */
3346 btrfs_release_path(path);
3347 cache = next_cache_extent(cache);
3350 btrfs_commit_transaction(trans, root);
3352 btrfs_free_path(path);
3356 static int check_fs_root(struct btrfs_root *root,
3357 struct cache_tree *root_cache,
3358 struct walk_control *wc)
3364 struct btrfs_path path;
3365 struct shared_node root_node;
3366 struct root_record *rec;
3367 struct btrfs_root_item *root_item = &root->root_item;
3368 struct cache_tree corrupt_blocks;
3369 struct orphan_data_extent *orphan;
3370 struct orphan_data_extent *tmp;
3371 enum btrfs_tree_block_status status;
3374 * Reuse the corrupt_block cache tree to record corrupted tree block
3376 * Unlike the usage in extent tree check, here we do it in a per
3377 * fs/subvol tree base.
3379 cache_tree_init(&corrupt_blocks);
3380 root->fs_info->corrupt_blocks = &corrupt_blocks;
3382 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3383 rec = get_root_rec(root_cache, root->root_key.objectid);
3384 if (btrfs_root_refs(root_item) > 0)
3385 rec->found_root_item = 1;
3388 btrfs_init_path(&path);
3389 memset(&root_node, 0, sizeof(root_node));
3390 cache_tree_init(&root_node.root_cache);
3391 cache_tree_init(&root_node.inode_cache);
3393 /* Move the orphan extent record to corresponding inode_record */
3394 list_for_each_entry_safe(orphan, tmp,
3395 &root->orphan_data_extents, list) {
3396 struct inode_record *inode;
3398 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3400 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3401 list_move(&orphan->list, &inode->orphan_extents);
3404 level = btrfs_header_level(root->node);
3405 memset(wc->nodes, 0, sizeof(wc->nodes));
3406 wc->nodes[level] = &root_node;
3407 wc->active_node = level;
3408 wc->root_level = level;
3410 /* We may not have checked the root block, lets do that now */
3411 if (btrfs_is_leaf(root->node))
3412 status = btrfs_check_leaf(root, NULL, root->node);
3414 status = btrfs_check_node(root, NULL, root->node);
3415 if (status != BTRFS_TREE_BLOCK_CLEAN)
3418 if (btrfs_root_refs(root_item) > 0 ||
3419 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3420 path.nodes[level] = root->node;
3421 extent_buffer_get(root->node);
3422 path.slots[level] = 0;
3424 struct btrfs_key key;
3425 struct btrfs_disk_key found_key;
3427 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3428 level = root_item->drop_level;
3429 path.lowest_level = level;
3430 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3433 btrfs_node_key(path.nodes[level], &found_key,
3435 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3436 sizeof(found_key)));
3440 wret = walk_down_tree(root, &path, wc, &level);
3446 wret = walk_up_tree(root, &path, wc, &level);
3453 btrfs_release_path(&path);
3455 if (!cache_tree_empty(&corrupt_blocks)) {
3456 struct cache_extent *cache;
3457 struct btrfs_corrupt_block *corrupt;
3459 printf("The following tree block(s) is corrupted in tree %llu:\n",
3460 root->root_key.objectid);
3461 cache = first_cache_extent(&corrupt_blocks);
3463 corrupt = container_of(cache,
3464 struct btrfs_corrupt_block,
3466 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3467 cache->start, corrupt->level,
3468 corrupt->key.objectid, corrupt->key.type,
3469 corrupt->key.offset);
3470 cache = next_cache_extent(cache);
3473 printf("Try to repair the btree for root %llu\n",
3474 root->root_key.objectid);
3475 ret = repair_btree(root, &corrupt_blocks);
3477 fprintf(stderr, "Failed to repair btree: %s\n",
3480 printf("Btree for root %llu is fixed\n",
3481 root->root_key.objectid);
3485 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3489 if (root_node.current) {
3490 root_node.current->checked = 1;
3491 maybe_free_inode_rec(&root_node.inode_cache,
3495 err = check_inode_recs(root, &root_node.inode_cache);
3499 free_corrupt_blocks_tree(&corrupt_blocks);
3500 root->fs_info->corrupt_blocks = NULL;
3501 free_orphan_data_extents(&root->orphan_data_extents);
3505 static int fs_root_objectid(u64 objectid)
3507 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3508 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3510 return is_fstree(objectid);
3513 static int check_fs_roots(struct btrfs_root *root,
3514 struct cache_tree *root_cache)
3516 struct btrfs_path path;
3517 struct btrfs_key key;
3518 struct walk_control wc;
3519 struct extent_buffer *leaf, *tree_node;
3520 struct btrfs_root *tmp_root;
3521 struct btrfs_root *tree_root = root->fs_info->tree_root;
3526 * Just in case we made any changes to the extent tree that weren't
3527 * reflected into the free space cache yet.
3530 reset_cached_block_groups(root->fs_info);
3531 memset(&wc, 0, sizeof(wc));
3532 cache_tree_init(&wc.shared);
3533 btrfs_init_path(&path);
3538 key.type = BTRFS_ROOT_ITEM_KEY;
3539 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3544 tree_node = tree_root->node;
3546 if (tree_node != tree_root->node) {
3547 free_root_recs_tree(root_cache);
3548 btrfs_release_path(&path);
3551 leaf = path.nodes[0];
3552 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3553 ret = btrfs_next_leaf(tree_root, &path);
3559 leaf = path.nodes[0];
3561 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3562 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3563 fs_root_objectid(key.objectid)) {
3564 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3565 tmp_root = btrfs_read_fs_root_no_cache(
3566 root->fs_info, &key);
3568 key.offset = (u64)-1;
3569 tmp_root = btrfs_read_fs_root(
3570 root->fs_info, &key);
3572 if (IS_ERR(tmp_root)) {
3576 ret = check_fs_root(tmp_root, root_cache, &wc);
3577 if (ret == -EAGAIN) {
3578 free_root_recs_tree(root_cache);
3579 btrfs_release_path(&path);
3584 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3585 btrfs_free_fs_root(tmp_root);
3586 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3587 key.type == BTRFS_ROOT_BACKREF_KEY) {
3588 process_root_ref(leaf, path.slots[0], &key,
3595 btrfs_release_path(&path);
3597 free_extent_cache_tree(&wc.shared);
3598 if (!cache_tree_empty(&wc.shared))
3599 fprintf(stderr, "warning line %d\n", __LINE__);
3604 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3606 struct list_head *cur = rec->backrefs.next;
3607 struct extent_backref *back;
3608 struct tree_backref *tback;
3609 struct data_backref *dback;
3613 while(cur != &rec->backrefs) {
3614 back = list_entry(cur, struct extent_backref, list);
3616 if (!back->found_extent_tree) {
3620 if (back->is_data) {
3621 dback = (struct data_backref *)back;
3622 fprintf(stderr, "Backref %llu %s %llu"
3623 " owner %llu offset %llu num_refs %lu"
3624 " not found in extent tree\n",
3625 (unsigned long long)rec->start,
3626 back->full_backref ?
3628 back->full_backref ?
3629 (unsigned long long)dback->parent:
3630 (unsigned long long)dback->root,
3631 (unsigned long long)dback->owner,
3632 (unsigned long long)dback->offset,
3633 (unsigned long)dback->num_refs);
3635 tback = (struct tree_backref *)back;
3636 fprintf(stderr, "Backref %llu parent %llu"
3637 " root %llu not found in extent tree\n",
3638 (unsigned long long)rec->start,
3639 (unsigned long long)tback->parent,
3640 (unsigned long long)tback->root);
3643 if (!back->is_data && !back->found_ref) {
3647 tback = (struct tree_backref *)back;
3648 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3649 (unsigned long long)rec->start,
3650 back->full_backref ? "parent" : "root",
3651 back->full_backref ?
3652 (unsigned long long)tback->parent :
3653 (unsigned long long)tback->root, back);
3655 if (back->is_data) {
3656 dback = (struct data_backref *)back;
3657 if (dback->found_ref != dback->num_refs) {
3661 fprintf(stderr, "Incorrect local backref count"
3662 " on %llu %s %llu owner %llu"
3663 " offset %llu found %u wanted %u back %p\n",
3664 (unsigned long long)rec->start,
3665 back->full_backref ?
3667 back->full_backref ?
3668 (unsigned long long)dback->parent:
3669 (unsigned long long)dback->root,
3670 (unsigned long long)dback->owner,
3671 (unsigned long long)dback->offset,
3672 dback->found_ref, dback->num_refs, back);
3674 if (dback->disk_bytenr != rec->start) {
3678 fprintf(stderr, "Backref disk bytenr does not"
3679 " match extent record, bytenr=%llu, "
3680 "ref bytenr=%llu\n",
3681 (unsigned long long)rec->start,
3682 (unsigned long long)dback->disk_bytenr);
3685 if (dback->bytes != rec->nr) {
3689 fprintf(stderr, "Backref bytes do not match "
3690 "extent backref, bytenr=%llu, ref "
3691 "bytes=%llu, backref bytes=%llu\n",
3692 (unsigned long long)rec->start,
3693 (unsigned long long)rec->nr,
3694 (unsigned long long)dback->bytes);
3697 if (!back->is_data) {
3700 dback = (struct data_backref *)back;
3701 found += dback->found_ref;
3704 if (found != rec->refs) {
3708 fprintf(stderr, "Incorrect global backref count "
3709 "on %llu found %llu wanted %llu\n",
3710 (unsigned long long)rec->start,
3711 (unsigned long long)found,
3712 (unsigned long long)rec->refs);
3718 static int free_all_extent_backrefs(struct extent_record *rec)
3720 struct extent_backref *back;
3721 struct list_head *cur;
3722 while (!list_empty(&rec->backrefs)) {
3723 cur = rec->backrefs.next;
3724 back = list_entry(cur, struct extent_backref, list);
3731 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3732 struct cache_tree *extent_cache)
3734 struct cache_extent *cache;
3735 struct extent_record *rec;
3738 cache = first_cache_extent(extent_cache);
3741 rec = container_of(cache, struct extent_record, cache);
3742 remove_cache_extent(extent_cache, cache);
3743 free_all_extent_backrefs(rec);
3748 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3749 struct extent_record *rec)
3751 if (rec->content_checked && rec->owner_ref_checked &&
3752 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3753 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3754 !rec->bad_full_backref && !rec->crossing_stripes &&
3755 !rec->wrong_chunk_type) {
3756 remove_cache_extent(extent_cache, &rec->cache);
3757 free_all_extent_backrefs(rec);
3758 list_del_init(&rec->list);
3764 static int check_owner_ref(struct btrfs_root *root,
3765 struct extent_record *rec,
3766 struct extent_buffer *buf)
3768 struct extent_backref *node;
3769 struct tree_backref *back;
3770 struct btrfs_root *ref_root;
3771 struct btrfs_key key;
3772 struct btrfs_path path;
3773 struct extent_buffer *parent;
3778 list_for_each_entry(node, &rec->backrefs, list) {
3781 if (!node->found_ref)
3783 if (node->full_backref)
3785 back = (struct tree_backref *)node;
3786 if (btrfs_header_owner(buf) == back->root)
3789 BUG_ON(rec->is_root);
3791 /* try to find the block by search corresponding fs tree */
3792 key.objectid = btrfs_header_owner(buf);
3793 key.type = BTRFS_ROOT_ITEM_KEY;
3794 key.offset = (u64)-1;
3796 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3797 if (IS_ERR(ref_root))
3800 level = btrfs_header_level(buf);
3802 btrfs_item_key_to_cpu(buf, &key, 0);
3804 btrfs_node_key_to_cpu(buf, &key, 0);
3806 btrfs_init_path(&path);
3807 path.lowest_level = level + 1;
3808 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3812 parent = path.nodes[level + 1];
3813 if (parent && buf->start == btrfs_node_blockptr(parent,
3814 path.slots[level + 1]))
3817 btrfs_release_path(&path);
3818 return found ? 0 : 1;
3821 static int is_extent_tree_record(struct extent_record *rec)
3823 struct list_head *cur = rec->backrefs.next;
3824 struct extent_backref *node;
3825 struct tree_backref *back;
3828 while(cur != &rec->backrefs) {
3829 node = list_entry(cur, struct extent_backref, list);
3833 back = (struct tree_backref *)node;
3834 if (node->full_backref)
3836 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3843 static int record_bad_block_io(struct btrfs_fs_info *info,
3844 struct cache_tree *extent_cache,
3847 struct extent_record *rec;
3848 struct cache_extent *cache;
3849 struct btrfs_key key;
3851 cache = lookup_cache_extent(extent_cache, start, len);
3855 rec = container_of(cache, struct extent_record, cache);
3856 if (!is_extent_tree_record(rec))
3859 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3860 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3863 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3864 struct extent_buffer *buf, int slot)
3866 if (btrfs_header_level(buf)) {
3867 struct btrfs_key_ptr ptr1, ptr2;
3869 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3870 sizeof(struct btrfs_key_ptr));
3871 read_extent_buffer(buf, &ptr2,
3872 btrfs_node_key_ptr_offset(slot + 1),
3873 sizeof(struct btrfs_key_ptr));
3874 write_extent_buffer(buf, &ptr1,
3875 btrfs_node_key_ptr_offset(slot + 1),
3876 sizeof(struct btrfs_key_ptr));
3877 write_extent_buffer(buf, &ptr2,
3878 btrfs_node_key_ptr_offset(slot),
3879 sizeof(struct btrfs_key_ptr));
3881 struct btrfs_disk_key key;
3882 btrfs_node_key(buf, &key, 0);
3883 btrfs_fixup_low_keys(root, path, &key,
3884 btrfs_header_level(buf) + 1);
3887 struct btrfs_item *item1, *item2;
3888 struct btrfs_key k1, k2;
3889 char *item1_data, *item2_data;
3890 u32 item1_offset, item2_offset, item1_size, item2_size;
3892 item1 = btrfs_item_nr(slot);
3893 item2 = btrfs_item_nr(slot + 1);
3894 btrfs_item_key_to_cpu(buf, &k1, slot);
3895 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3896 item1_offset = btrfs_item_offset(buf, item1);
3897 item2_offset = btrfs_item_offset(buf, item2);
3898 item1_size = btrfs_item_size(buf, item1);
3899 item2_size = btrfs_item_size(buf, item2);
3901 item1_data = malloc(item1_size);
3904 item2_data = malloc(item2_size);
3910 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3911 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3913 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3914 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3918 btrfs_set_item_offset(buf, item1, item2_offset);
3919 btrfs_set_item_offset(buf, item2, item1_offset);
3920 btrfs_set_item_size(buf, item1, item2_size);
3921 btrfs_set_item_size(buf, item2, item1_size);
3923 path->slots[0] = slot;
3924 btrfs_set_item_key_unsafe(root, path, &k2);
3925 path->slots[0] = slot + 1;
3926 btrfs_set_item_key_unsafe(root, path, &k1);
3931 static int fix_key_order(struct btrfs_trans_handle *trans,
3932 struct btrfs_root *root,
3933 struct btrfs_path *path)
3935 struct extent_buffer *buf;
3936 struct btrfs_key k1, k2;
3938 int level = path->lowest_level;
3941 buf = path->nodes[level];
3942 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3944 btrfs_node_key_to_cpu(buf, &k1, i);
3945 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3947 btrfs_item_key_to_cpu(buf, &k1, i);
3948 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3950 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3952 ret = swap_values(root, path, buf, i);
3955 btrfs_mark_buffer_dirty(buf);
3961 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3962 struct btrfs_root *root,
3963 struct btrfs_path *path,
3964 struct extent_buffer *buf, int slot)
3966 struct btrfs_key key;
3967 int nritems = btrfs_header_nritems(buf);
3969 btrfs_item_key_to_cpu(buf, &key, slot);
3971 /* These are all the keys we can deal with missing. */
3972 if (key.type != BTRFS_DIR_INDEX_KEY &&
3973 key.type != BTRFS_EXTENT_ITEM_KEY &&
3974 key.type != BTRFS_METADATA_ITEM_KEY &&
3975 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3976 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3979 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3980 (unsigned long long)key.objectid, key.type,
3981 (unsigned long long)key.offset, slot, buf->start);
3982 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3983 btrfs_item_nr_offset(slot + 1),
3984 sizeof(struct btrfs_item) *
3985 (nritems - slot - 1));
3986 btrfs_set_header_nritems(buf, nritems - 1);
3988 struct btrfs_disk_key disk_key;
3990 btrfs_item_key(buf, &disk_key, 0);
3991 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3993 btrfs_mark_buffer_dirty(buf);
3997 static int fix_item_offset(struct btrfs_trans_handle *trans,
3998 struct btrfs_root *root,
3999 struct btrfs_path *path)
4001 struct extent_buffer *buf;
4005 /* We should only get this for leaves */
4006 BUG_ON(path->lowest_level);
4007 buf = path->nodes[0];
4009 for (i = 0; i < btrfs_header_nritems(buf); i++) {
4010 unsigned int shift = 0, offset;
4012 if (i == 0 && btrfs_item_end_nr(buf, i) !=
4013 BTRFS_LEAF_DATA_SIZE(root)) {
4014 if (btrfs_item_end_nr(buf, i) >
4015 BTRFS_LEAF_DATA_SIZE(root)) {
4016 ret = delete_bogus_item(trans, root, path,
4020 fprintf(stderr, "item is off the end of the "
4021 "leaf, can't fix\n");
4025 shift = BTRFS_LEAF_DATA_SIZE(root) -
4026 btrfs_item_end_nr(buf, i);
4027 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
4028 btrfs_item_offset_nr(buf, i - 1)) {
4029 if (btrfs_item_end_nr(buf, i) >
4030 btrfs_item_offset_nr(buf, i - 1)) {
4031 ret = delete_bogus_item(trans, root, path,
4035 fprintf(stderr, "items overlap, can't fix\n");
4039 shift = btrfs_item_offset_nr(buf, i - 1) -
4040 btrfs_item_end_nr(buf, i);
4045 printf("Shifting item nr %d by %u bytes in block %llu\n",
4046 i, shift, (unsigned long long)buf->start);
4047 offset = btrfs_item_offset_nr(buf, i);
4048 memmove_extent_buffer(buf,
4049 btrfs_leaf_data(buf) + offset + shift,
4050 btrfs_leaf_data(buf) + offset,
4051 btrfs_item_size_nr(buf, i));
4052 btrfs_set_item_offset(buf, btrfs_item_nr(i),
4054 btrfs_mark_buffer_dirty(buf);
4058 * We may have moved things, in which case we want to exit so we don't
4059 * write those changes out. Once we have proper abort functionality in
4060 * progs this can be changed to something nicer.
4067 * Attempt to fix basic block failures. If we can't fix it for whatever reason
4068 * then just return -EIO.
4070 static int try_to_fix_bad_block(struct btrfs_root *root,
4071 struct extent_buffer *buf,
4072 enum btrfs_tree_block_status status)
4074 struct btrfs_trans_handle *trans;
4075 struct ulist *roots;
4076 struct ulist_node *node;
4077 struct btrfs_root *search_root;
4078 struct btrfs_path *path;
4079 struct ulist_iterator iter;
4080 struct btrfs_key root_key, key;
4083 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4084 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4087 path = btrfs_alloc_path();
4091 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4094 btrfs_free_path(path);
4098 ULIST_ITER_INIT(&iter);
4099 while ((node = ulist_next(roots, &iter))) {
4100 root_key.objectid = node->val;
4101 root_key.type = BTRFS_ROOT_ITEM_KEY;
4102 root_key.offset = (u64)-1;
4104 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4111 trans = btrfs_start_transaction(search_root, 0);
4112 if (IS_ERR(trans)) {
4113 ret = PTR_ERR(trans);
4117 path->lowest_level = btrfs_header_level(buf);
4118 path->skip_check_block = 1;
4119 if (path->lowest_level)
4120 btrfs_node_key_to_cpu(buf, &key, 0);
4122 btrfs_item_key_to_cpu(buf, &key, 0);
4123 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4126 btrfs_commit_transaction(trans, search_root);
4129 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4130 ret = fix_key_order(trans, search_root, path);
4131 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4132 ret = fix_item_offset(trans, search_root, path);
4134 btrfs_commit_transaction(trans, search_root);
4137 btrfs_release_path(path);
4138 btrfs_commit_transaction(trans, search_root);
4141 btrfs_free_path(path);
4145 static int check_block(struct btrfs_root *root,
4146 struct cache_tree *extent_cache,
4147 struct extent_buffer *buf, u64 flags)
4149 struct extent_record *rec;
4150 struct cache_extent *cache;
4151 struct btrfs_key key;
4152 enum btrfs_tree_block_status status;
4156 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4159 rec = container_of(cache, struct extent_record, cache);
4160 rec->generation = btrfs_header_generation(buf);
4162 level = btrfs_header_level(buf);
4163 if (btrfs_header_nritems(buf) > 0) {
4166 btrfs_item_key_to_cpu(buf, &key, 0);
4168 btrfs_node_key_to_cpu(buf, &key, 0);
4170 rec->info_objectid = key.objectid;
4172 rec->info_level = level;
4174 if (btrfs_is_leaf(buf))
4175 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4177 status = btrfs_check_node(root, &rec->parent_key, buf);
4179 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4181 status = try_to_fix_bad_block(root, buf, status);
4182 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4184 fprintf(stderr, "bad block %llu\n",
4185 (unsigned long long)buf->start);
4188 * Signal to callers we need to start the scan over
4189 * again since we'll have cow'ed blocks.
4194 rec->content_checked = 1;
4195 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4196 rec->owner_ref_checked = 1;
4198 ret = check_owner_ref(root, rec, buf);
4200 rec->owner_ref_checked = 1;
4204 maybe_free_extent_rec(extent_cache, rec);
4208 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4209 u64 parent, u64 root)
4211 struct list_head *cur = rec->backrefs.next;
4212 struct extent_backref *node;
4213 struct tree_backref *back;
4215 while(cur != &rec->backrefs) {
4216 node = list_entry(cur, struct extent_backref, list);
4220 back = (struct tree_backref *)node;
4222 if (!node->full_backref)
4224 if (parent == back->parent)
4227 if (node->full_backref)
4229 if (back->root == root)
4236 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4237 u64 parent, u64 root)
4239 struct tree_backref *ref = malloc(sizeof(*ref));
4240 memset(&ref->node, 0, sizeof(ref->node));
4242 ref->parent = parent;
4243 ref->node.full_backref = 1;
4246 ref->node.full_backref = 0;
4248 list_add_tail(&ref->node.list, &rec->backrefs);
4253 static struct data_backref *find_data_backref(struct extent_record *rec,
4254 u64 parent, u64 root,
4255 u64 owner, u64 offset,
4257 u64 disk_bytenr, u64 bytes)
4259 struct list_head *cur = rec->backrefs.next;
4260 struct extent_backref *node;
4261 struct data_backref *back;
4263 while(cur != &rec->backrefs) {
4264 node = list_entry(cur, struct extent_backref, list);
4268 back = (struct data_backref *)node;
4270 if (!node->full_backref)
4272 if (parent == back->parent)
4275 if (node->full_backref)
4277 if (back->root == root && back->owner == owner &&
4278 back->offset == offset) {
4279 if (found_ref && node->found_ref &&
4280 (back->bytes != bytes ||
4281 back->disk_bytenr != disk_bytenr))
4290 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4291 u64 parent, u64 root,
4292 u64 owner, u64 offset,
4295 struct data_backref *ref = malloc(sizeof(*ref));
4296 memset(&ref->node, 0, sizeof(ref->node));
4297 ref->node.is_data = 1;
4300 ref->parent = parent;
4303 ref->node.full_backref = 1;
4307 ref->offset = offset;
4308 ref->node.full_backref = 0;
4310 ref->bytes = max_size;
4313 list_add_tail(&ref->node.list, &rec->backrefs);
4314 if (max_size > rec->max_size)
4315 rec->max_size = max_size;
4319 /* Check if the type of extent matches with its chunk */
4320 static void check_extent_type(struct extent_record *rec)
4322 struct btrfs_block_group_cache *bg_cache;
4324 bg_cache = btrfs_lookup_first_block_group(global_info, rec->start);
4328 /* data extent, check chunk directly*/
4329 if (!rec->metadata) {
4330 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
4331 rec->wrong_chunk_type = 1;
4335 /* metadata extent, check the obvious case first */
4336 if (!(bg_cache->flags & (BTRFS_BLOCK_GROUP_SYSTEM |
4337 BTRFS_BLOCK_GROUP_METADATA))) {
4338 rec->wrong_chunk_type = 1;
4343 * Check SYSTEM extent, as it's also marked as metadata, we can only
4344 * make sure it's a SYSTEM extent by its backref
4346 if (!list_empty(&rec->backrefs)) {
4347 struct extent_backref *node;
4348 struct tree_backref *tback;
4351 node = list_entry(rec->backrefs.next, struct extent_backref,
4353 if (node->is_data) {
4354 /* tree block shouldn't have data backref */
4355 rec->wrong_chunk_type = 1;
4358 tback = container_of(node, struct tree_backref, node);
4360 if (tback->root == BTRFS_CHUNK_TREE_OBJECTID)
4361 bg_type = BTRFS_BLOCK_GROUP_SYSTEM;
4363 bg_type = BTRFS_BLOCK_GROUP_METADATA;
4364 if (!(bg_cache->flags & bg_type))
4365 rec->wrong_chunk_type = 1;
4369 static int add_extent_rec(struct cache_tree *extent_cache,
4370 struct btrfs_key *parent_key, u64 parent_gen,
4371 u64 start, u64 nr, u64 extent_item_refs,
4372 int is_root, int inc_ref, int set_checked,
4373 int metadata, int extent_rec, u64 max_size)
4375 struct extent_record *rec;
4376 struct cache_extent *cache;
4380 cache = lookup_cache_extent(extent_cache, start, nr);
4382 rec = container_of(cache, struct extent_record, cache);
4386 rec->nr = max(nr, max_size);
4389 * We need to make sure to reset nr to whatever the extent
4390 * record says was the real size, this way we can compare it to
4394 if (start != rec->start || rec->found_rec) {
4395 struct extent_record *tmp;
4398 if (list_empty(&rec->list))
4399 list_add_tail(&rec->list,
4400 &duplicate_extents);
4403 * We have to do this song and dance in case we
4404 * find an extent record that falls inside of
4405 * our current extent record but does not have
4406 * the same objectid.
4408 tmp = malloc(sizeof(*tmp));
4412 tmp->max_size = max_size;
4415 tmp->metadata = metadata;
4416 tmp->extent_item_refs = extent_item_refs;
4417 INIT_LIST_HEAD(&tmp->list);
4418 list_add_tail(&tmp->list, &rec->dups);
4419 rec->num_duplicates++;
4426 if (extent_item_refs && !dup) {
4427 if (rec->extent_item_refs) {
4428 fprintf(stderr, "block %llu rec "
4429 "extent_item_refs %llu, passed %llu\n",
4430 (unsigned long long)start,
4431 (unsigned long long)
4432 rec->extent_item_refs,
4433 (unsigned long long)extent_item_refs);
4435 rec->extent_item_refs = extent_item_refs;
4440 rec->content_checked = 1;
4441 rec->owner_ref_checked = 1;
4445 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4447 rec->parent_generation = parent_gen;
4449 if (rec->max_size < max_size)
4450 rec->max_size = max_size;
4453 * A metadata extent can't cross stripe_len boundary, otherwise
4454 * kernel scrub won't be able to handle it.
4455 * As now stripe_len is fixed to BTRFS_STRIPE_LEN, just check
4458 if (metadata && check_crossing_stripes(rec->start,
4460 rec->crossing_stripes = 1;
4461 check_extent_type(rec);
4462 maybe_free_extent_rec(extent_cache, rec);
4465 rec = malloc(sizeof(*rec));
4467 rec->max_size = max_size;
4468 rec->nr = max(nr, max_size);
4469 rec->found_rec = !!extent_rec;
4470 rec->content_checked = 0;
4471 rec->owner_ref_checked = 0;
4472 rec->num_duplicates = 0;
4473 rec->metadata = metadata;
4474 rec->flag_block_full_backref = -1;
4475 rec->bad_full_backref = 0;
4476 rec->crossing_stripes = 0;
4477 rec->wrong_chunk_type = 0;
4478 INIT_LIST_HEAD(&rec->backrefs);
4479 INIT_LIST_HEAD(&rec->dups);
4480 INIT_LIST_HEAD(&rec->list);
4492 if (extent_item_refs)
4493 rec->extent_item_refs = extent_item_refs;
4495 rec->extent_item_refs = 0;
4498 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4500 memset(&rec->parent_key, 0, sizeof(*parent_key));
4503 rec->parent_generation = parent_gen;
4505 rec->parent_generation = 0;
4507 rec->cache.start = start;
4508 rec->cache.size = nr;
4509 ret = insert_cache_extent(extent_cache, &rec->cache);
4513 rec->content_checked = 1;
4514 rec->owner_ref_checked = 1;
4518 if (check_crossing_stripes(rec->start, rec->max_size))
4519 rec->crossing_stripes = 1;
4520 check_extent_type(rec);
4524 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4525 u64 parent, u64 root, int found_ref)
4527 struct extent_record *rec;
4528 struct tree_backref *back;
4529 struct cache_extent *cache;
4531 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4533 add_extent_rec(extent_cache, NULL, 0, bytenr,
4534 1, 0, 0, 0, 0, 1, 0, 0);
4535 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4540 rec = container_of(cache, struct extent_record, cache);
4541 if (rec->start != bytenr) {
4545 back = find_tree_backref(rec, parent, root);
4547 back = alloc_tree_backref(rec, parent, root);
4550 if (back->node.found_ref) {
4551 fprintf(stderr, "Extent back ref already exists "
4552 "for %llu parent %llu root %llu \n",
4553 (unsigned long long)bytenr,
4554 (unsigned long long)parent,
4555 (unsigned long long)root);
4557 back->node.found_ref = 1;
4559 if (back->node.found_extent_tree) {
4560 fprintf(stderr, "Extent back ref already exists "
4561 "for %llu parent %llu root %llu \n",
4562 (unsigned long long)bytenr,
4563 (unsigned long long)parent,
4564 (unsigned long long)root);
4566 back->node.found_extent_tree = 1;
4568 check_extent_type(rec);
4569 maybe_free_extent_rec(extent_cache, rec);
4573 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4574 u64 parent, u64 root, u64 owner, u64 offset,
4575 u32 num_refs, int found_ref, u64 max_size)
4577 struct extent_record *rec;
4578 struct data_backref *back;
4579 struct cache_extent *cache;
4581 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4583 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4585 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4590 rec = container_of(cache, struct extent_record, cache);
4591 if (rec->max_size < max_size)
4592 rec->max_size = max_size;
4595 * If found_ref is set then max_size is the real size and must match the
4596 * existing refs. So if we have already found a ref then we need to
4597 * make sure that this ref matches the existing one, otherwise we need
4598 * to add a new backref so we can notice that the backrefs don't match
4599 * and we need to figure out who is telling the truth. This is to
4600 * account for that awful fsync bug I introduced where we'd end up with
4601 * a btrfs_file_extent_item that would have its length include multiple
4602 * prealloc extents or point inside of a prealloc extent.
4604 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4607 back = alloc_data_backref(rec, parent, root, owner, offset,
4611 BUG_ON(num_refs != 1);
4612 if (back->node.found_ref)
4613 BUG_ON(back->bytes != max_size);
4614 back->node.found_ref = 1;
4615 back->found_ref += 1;
4616 back->bytes = max_size;
4617 back->disk_bytenr = bytenr;
4619 rec->content_checked = 1;
4620 rec->owner_ref_checked = 1;
4622 if (back->node.found_extent_tree) {
4623 fprintf(stderr, "Extent back ref already exists "
4624 "for %llu parent %llu root %llu "
4625 "owner %llu offset %llu num_refs %lu\n",
4626 (unsigned long long)bytenr,
4627 (unsigned long long)parent,
4628 (unsigned long long)root,
4629 (unsigned long long)owner,
4630 (unsigned long long)offset,
4631 (unsigned long)num_refs);
4633 back->num_refs = num_refs;
4634 back->node.found_extent_tree = 1;
4636 maybe_free_extent_rec(extent_cache, rec);
4640 static int add_pending(struct cache_tree *pending,
4641 struct cache_tree *seen, u64 bytenr, u32 size)
4644 ret = add_cache_extent(seen, bytenr, size);
4647 add_cache_extent(pending, bytenr, size);
4651 static int pick_next_pending(struct cache_tree *pending,
4652 struct cache_tree *reada,
4653 struct cache_tree *nodes,
4654 u64 last, struct block_info *bits, int bits_nr,
4657 unsigned long node_start = last;
4658 struct cache_extent *cache;
4661 cache = search_cache_extent(reada, 0);
4663 bits[0].start = cache->start;
4664 bits[0].size = cache->size;
4669 if (node_start > 32768)
4670 node_start -= 32768;
4672 cache = search_cache_extent(nodes, node_start);
4674 cache = search_cache_extent(nodes, 0);
4677 cache = search_cache_extent(pending, 0);
4682 bits[ret].start = cache->start;
4683 bits[ret].size = cache->size;
4684 cache = next_cache_extent(cache);
4686 } while (cache && ret < bits_nr);
4692 bits[ret].start = cache->start;
4693 bits[ret].size = cache->size;
4694 cache = next_cache_extent(cache);
4696 } while (cache && ret < bits_nr);
4698 if (bits_nr - ret > 8) {
4699 u64 lookup = bits[0].start + bits[0].size;
4700 struct cache_extent *next;
4701 next = search_cache_extent(pending, lookup);
4703 if (next->start - lookup > 32768)
4705 bits[ret].start = next->start;
4706 bits[ret].size = next->size;
4707 lookup = next->start + next->size;
4711 next = next_cache_extent(next);
4719 static void free_chunk_record(struct cache_extent *cache)
4721 struct chunk_record *rec;
4723 rec = container_of(cache, struct chunk_record, cache);
4724 list_del_init(&rec->list);
4725 list_del_init(&rec->dextents);
4729 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4731 cache_tree_free_extents(chunk_cache, free_chunk_record);
4734 static void free_device_record(struct rb_node *node)
4736 struct device_record *rec;
4738 rec = container_of(node, struct device_record, node);
4742 FREE_RB_BASED_TREE(device_cache, free_device_record);
4744 int insert_block_group_record(struct block_group_tree *tree,
4745 struct block_group_record *bg_rec)
4749 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4753 list_add_tail(&bg_rec->list, &tree->block_groups);
4757 static void free_block_group_record(struct cache_extent *cache)
4759 struct block_group_record *rec;
4761 rec = container_of(cache, struct block_group_record, cache);
4762 list_del_init(&rec->list);
4766 void free_block_group_tree(struct block_group_tree *tree)
4768 cache_tree_free_extents(&tree->tree, free_block_group_record);
4771 int insert_device_extent_record(struct device_extent_tree *tree,
4772 struct device_extent_record *de_rec)
4777 * Device extent is a bit different from the other extents, because
4778 * the extents which belong to the different devices may have the
4779 * same start and size, so we need use the special extent cache
4780 * search/insert functions.
4782 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4786 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4787 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4791 static void free_device_extent_record(struct cache_extent *cache)
4793 struct device_extent_record *rec;
4795 rec = container_of(cache, struct device_extent_record, cache);
4796 if (!list_empty(&rec->chunk_list))
4797 list_del_init(&rec->chunk_list);
4798 if (!list_empty(&rec->device_list))
4799 list_del_init(&rec->device_list);
4803 void free_device_extent_tree(struct device_extent_tree *tree)
4805 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4808 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4809 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4810 struct extent_buffer *leaf, int slot)
4812 struct btrfs_extent_ref_v0 *ref0;
4813 struct btrfs_key key;
4815 btrfs_item_key_to_cpu(leaf, &key, slot);
4816 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4817 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4818 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4820 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4821 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4827 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4828 struct btrfs_key *key,
4831 struct btrfs_chunk *ptr;
4832 struct chunk_record *rec;
4835 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4836 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4838 rec = malloc(btrfs_chunk_record_size(num_stripes));
4840 fprintf(stderr, "memory allocation failed\n");
4844 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4846 INIT_LIST_HEAD(&rec->list);
4847 INIT_LIST_HEAD(&rec->dextents);
4850 rec->cache.start = key->offset;
4851 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4853 rec->generation = btrfs_header_generation(leaf);
4855 rec->objectid = key->objectid;
4856 rec->type = key->type;
4857 rec->offset = key->offset;
4859 rec->length = rec->cache.size;
4860 rec->owner = btrfs_chunk_owner(leaf, ptr);
4861 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4862 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4863 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4864 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4865 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4866 rec->num_stripes = num_stripes;
4867 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4869 for (i = 0; i < rec->num_stripes; ++i) {
4870 rec->stripes[i].devid =
4871 btrfs_stripe_devid_nr(leaf, ptr, i);
4872 rec->stripes[i].offset =
4873 btrfs_stripe_offset_nr(leaf, ptr, i);
4874 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4875 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4882 static int process_chunk_item(struct cache_tree *chunk_cache,
4883 struct btrfs_key *key, struct extent_buffer *eb,
4886 struct chunk_record *rec;
4889 rec = btrfs_new_chunk_record(eb, key, slot);
4890 ret = insert_cache_extent(chunk_cache, &rec->cache);
4892 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4893 rec->offset, rec->length);
4900 static int process_device_item(struct rb_root *dev_cache,
4901 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4903 struct btrfs_dev_item *ptr;
4904 struct device_record *rec;
4907 ptr = btrfs_item_ptr(eb,
4908 slot, struct btrfs_dev_item);
4910 rec = malloc(sizeof(*rec));
4912 fprintf(stderr, "memory allocation failed\n");
4916 rec->devid = key->offset;
4917 rec->generation = btrfs_header_generation(eb);
4919 rec->objectid = key->objectid;
4920 rec->type = key->type;
4921 rec->offset = key->offset;
4923 rec->devid = btrfs_device_id(eb, ptr);
4924 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4925 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4927 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4929 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4936 struct block_group_record *
4937 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4940 struct btrfs_block_group_item *ptr;
4941 struct block_group_record *rec;
4943 rec = malloc(sizeof(*rec));
4945 fprintf(stderr, "memory allocation failed\n");
4948 memset(rec, 0, sizeof(*rec));
4950 rec->cache.start = key->objectid;
4951 rec->cache.size = key->offset;
4953 rec->generation = btrfs_header_generation(leaf);
4955 rec->objectid = key->objectid;
4956 rec->type = key->type;
4957 rec->offset = key->offset;
4959 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4960 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4962 INIT_LIST_HEAD(&rec->list);
4967 static int process_block_group_item(struct block_group_tree *block_group_cache,
4968 struct btrfs_key *key,
4969 struct extent_buffer *eb, int slot)
4971 struct block_group_record *rec;
4974 rec = btrfs_new_block_group_record(eb, key, slot);
4975 ret = insert_block_group_record(block_group_cache, rec);
4977 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4978 rec->objectid, rec->offset);
4985 struct device_extent_record *
4986 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4987 struct btrfs_key *key, int slot)
4989 struct device_extent_record *rec;
4990 struct btrfs_dev_extent *ptr;
4992 rec = malloc(sizeof(*rec));
4994 fprintf(stderr, "memory allocation failed\n");
4997 memset(rec, 0, sizeof(*rec));
4999 rec->cache.objectid = key->objectid;
5000 rec->cache.start = key->offset;
5002 rec->generation = btrfs_header_generation(leaf);
5004 rec->objectid = key->objectid;
5005 rec->type = key->type;
5006 rec->offset = key->offset;
5008 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
5009 rec->chunk_objecteid =
5010 btrfs_dev_extent_chunk_objectid(leaf, ptr);
5012 btrfs_dev_extent_chunk_offset(leaf, ptr);
5013 rec->length = btrfs_dev_extent_length(leaf, ptr);
5014 rec->cache.size = rec->length;
5016 INIT_LIST_HEAD(&rec->chunk_list);
5017 INIT_LIST_HEAD(&rec->device_list);
5023 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
5024 struct btrfs_key *key, struct extent_buffer *eb,
5027 struct device_extent_record *rec;
5030 rec = btrfs_new_device_extent_record(eb, key, slot);
5031 ret = insert_device_extent_record(dev_extent_cache, rec);
5034 "Device extent[%llu, %llu, %llu] existed.\n",
5035 rec->objectid, rec->offset, rec->length);
5042 static int process_extent_item(struct btrfs_root *root,
5043 struct cache_tree *extent_cache,
5044 struct extent_buffer *eb, int slot)
5046 struct btrfs_extent_item *ei;
5047 struct btrfs_extent_inline_ref *iref;
5048 struct btrfs_extent_data_ref *dref;
5049 struct btrfs_shared_data_ref *sref;
5050 struct btrfs_key key;
5054 u32 item_size = btrfs_item_size_nr(eb, slot);
5060 btrfs_item_key_to_cpu(eb, &key, slot);
5062 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5064 num_bytes = root->leafsize;
5066 num_bytes = key.offset;
5069 if (item_size < sizeof(*ei)) {
5070 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5071 struct btrfs_extent_item_v0 *ei0;
5072 BUG_ON(item_size != sizeof(*ei0));
5073 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
5074 refs = btrfs_extent_refs_v0(eb, ei0);
5078 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
5079 num_bytes, refs, 0, 0, 0, metadata, 1,
5083 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
5084 refs = btrfs_extent_refs(eb, ei);
5086 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
5087 refs, 0, 0, 0, metadata, 1, num_bytes);
5089 ptr = (unsigned long)(ei + 1);
5090 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
5091 key.type == BTRFS_EXTENT_ITEM_KEY)
5092 ptr += sizeof(struct btrfs_tree_block_info);
5094 end = (unsigned long)ei + item_size;
5096 iref = (struct btrfs_extent_inline_ref *)ptr;
5097 type = btrfs_extent_inline_ref_type(eb, iref);
5098 offset = btrfs_extent_inline_ref_offset(eb, iref);
5100 case BTRFS_TREE_BLOCK_REF_KEY:
5101 add_tree_backref(extent_cache, key.objectid,
5104 case BTRFS_SHARED_BLOCK_REF_KEY:
5105 add_tree_backref(extent_cache, key.objectid,
5108 case BTRFS_EXTENT_DATA_REF_KEY:
5109 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
5110 add_data_backref(extent_cache, key.objectid, 0,
5111 btrfs_extent_data_ref_root(eb, dref),
5112 btrfs_extent_data_ref_objectid(eb,
5114 btrfs_extent_data_ref_offset(eb, dref),
5115 btrfs_extent_data_ref_count(eb, dref),
5118 case BTRFS_SHARED_DATA_REF_KEY:
5119 sref = (struct btrfs_shared_data_ref *)(iref + 1);
5120 add_data_backref(extent_cache, key.objectid, offset,
5122 btrfs_shared_data_ref_count(eb, sref),
5126 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
5127 key.objectid, key.type, num_bytes);
5130 ptr += btrfs_extent_inline_ref_size(type);
5137 static int check_cache_range(struct btrfs_root *root,
5138 struct btrfs_block_group_cache *cache,
5139 u64 offset, u64 bytes)
5141 struct btrfs_free_space *entry;
5147 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5148 bytenr = btrfs_sb_offset(i);
5149 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5150 cache->key.objectid, bytenr, 0,
5151 &logical, &nr, &stripe_len);
5156 if (logical[nr] + stripe_len <= offset)
5158 if (offset + bytes <= logical[nr])
5160 if (logical[nr] == offset) {
5161 if (stripe_len >= bytes) {
5165 bytes -= stripe_len;
5166 offset += stripe_len;
5167 } else if (logical[nr] < offset) {
5168 if (logical[nr] + stripe_len >=
5173 bytes = (offset + bytes) -
5174 (logical[nr] + stripe_len);
5175 offset = logical[nr] + stripe_len;
5178 * Could be tricky, the super may land in the
5179 * middle of the area we're checking. First
5180 * check the easiest case, it's at the end.
5182 if (logical[nr] + stripe_len >=
5184 bytes = logical[nr] - offset;
5188 /* Check the left side */
5189 ret = check_cache_range(root, cache,
5191 logical[nr] - offset);
5197 /* Now we continue with the right side */
5198 bytes = (offset + bytes) -
5199 (logical[nr] + stripe_len);
5200 offset = logical[nr] + stripe_len;
5207 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5209 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5210 offset, offset+bytes);
5214 if (entry->offset != offset) {
5215 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5220 if (entry->bytes != bytes) {
5221 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5222 bytes, entry->bytes, offset);
5226 unlink_free_space(cache->free_space_ctl, entry);
5231 static int verify_space_cache(struct btrfs_root *root,
5232 struct btrfs_block_group_cache *cache)
5234 struct btrfs_path *path;
5235 struct extent_buffer *leaf;
5236 struct btrfs_key key;
5240 path = btrfs_alloc_path();
5244 root = root->fs_info->extent_root;
5246 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5248 key.objectid = last;
5250 key.type = BTRFS_EXTENT_ITEM_KEY;
5252 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5257 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5258 ret = btrfs_next_leaf(root, path);
5266 leaf = path->nodes[0];
5267 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5268 if (key.objectid >= cache->key.offset + cache->key.objectid)
5270 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5271 key.type != BTRFS_METADATA_ITEM_KEY) {
5276 if (last == key.objectid) {
5277 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5278 last = key.objectid + key.offset;
5280 last = key.objectid + root->leafsize;
5285 ret = check_cache_range(root, cache, last,
5286 key.objectid - last);
5289 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5290 last = key.objectid + key.offset;
5292 last = key.objectid + root->leafsize;
5296 if (last < cache->key.objectid + cache->key.offset)
5297 ret = check_cache_range(root, cache, last,
5298 cache->key.objectid +
5299 cache->key.offset - last);
5302 btrfs_free_path(path);
5305 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5306 fprintf(stderr, "There are still entries left in the space "
5314 static int check_space_cache(struct btrfs_root *root)
5316 struct btrfs_block_group_cache *cache;
5317 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5321 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5322 btrfs_super_generation(root->fs_info->super_copy) !=
5323 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5324 printf("cache and super generation don't match, space cache "
5325 "will be invalidated\n");
5330 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5334 start = cache->key.objectid + cache->key.offset;
5335 if (!cache->free_space_ctl) {
5336 if (btrfs_init_free_space_ctl(cache,
5337 root->sectorsize)) {
5342 btrfs_remove_free_space_cache(cache);
5345 ret = load_free_space_cache(root->fs_info, cache);
5349 ret = verify_space_cache(root, cache);
5351 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5352 cache->key.objectid);
5357 return error ? -EINVAL : 0;
5360 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5361 u64 num_bytes, unsigned long leaf_offset,
5362 struct extent_buffer *eb) {
5365 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5367 unsigned long csum_offset;
5371 u64 data_checked = 0;
5377 if (num_bytes % root->sectorsize)
5380 data = malloc(num_bytes);
5384 while (offset < num_bytes) {
5387 read_len = num_bytes - offset;
5388 /* read as much space once a time */
5389 ret = read_extent_data(root, data + offset,
5390 bytenr + offset, &read_len, mirror);
5394 /* verify every 4k data's checksum */
5395 while (data_checked < read_len) {
5397 tmp = offset + data_checked;
5399 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5400 csum, root->sectorsize);
5401 btrfs_csum_final(csum, (char *)&csum);
5403 csum_offset = leaf_offset +
5404 tmp / root->sectorsize * csum_size;
5405 read_extent_buffer(eb, (char *)&csum_expected,
5406 csum_offset, csum_size);
5407 /* try another mirror */
5408 if (csum != csum_expected) {
5409 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5410 mirror, bytenr + tmp,
5411 csum, csum_expected);
5412 num_copies = btrfs_num_copies(
5413 &root->fs_info->mapping_tree,
5415 if (mirror < num_copies - 1) {
5420 data_checked += root->sectorsize;
5429 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5432 struct btrfs_path *path;
5433 struct extent_buffer *leaf;
5434 struct btrfs_key key;
5437 path = btrfs_alloc_path();
5439 fprintf(stderr, "Error allocing path\n");
5443 key.objectid = bytenr;
5444 key.type = BTRFS_EXTENT_ITEM_KEY;
5445 key.offset = (u64)-1;
5448 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5451 fprintf(stderr, "Error looking up extent record %d\n", ret);
5452 btrfs_free_path(path);
5455 if (path->slots[0] > 0) {
5458 ret = btrfs_prev_leaf(root, path);
5461 } else if (ret > 0) {
5468 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5471 * Block group items come before extent items if they have the same
5472 * bytenr, so walk back one more just in case. Dear future traveler,
5473 * first congrats on mastering time travel. Now if it's not too much
5474 * trouble could you go back to 2006 and tell Chris to make the
5475 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5476 * EXTENT_ITEM_KEY please?
5478 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5479 if (path->slots[0] > 0) {
5482 ret = btrfs_prev_leaf(root, path);
5485 } else if (ret > 0) {
5490 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5494 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5495 ret = btrfs_next_leaf(root, path);
5497 fprintf(stderr, "Error going to next leaf "
5499 btrfs_free_path(path);
5505 leaf = path->nodes[0];
5506 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5507 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5511 if (key.objectid + key.offset < bytenr) {
5515 if (key.objectid > bytenr + num_bytes)
5518 if (key.objectid == bytenr) {
5519 if (key.offset >= num_bytes) {
5523 num_bytes -= key.offset;
5524 bytenr += key.offset;
5525 } else if (key.objectid < bytenr) {
5526 if (key.objectid + key.offset >= bytenr + num_bytes) {
5530 num_bytes = (bytenr + num_bytes) -
5531 (key.objectid + key.offset);
5532 bytenr = key.objectid + key.offset;
5534 if (key.objectid + key.offset < bytenr + num_bytes) {
5535 u64 new_start = key.objectid + key.offset;
5536 u64 new_bytes = bytenr + num_bytes - new_start;
5539 * Weird case, the extent is in the middle of
5540 * our range, we'll have to search one side
5541 * and then the other. Not sure if this happens
5542 * in real life, but no harm in coding it up
5543 * anyway just in case.
5545 btrfs_release_path(path);
5546 ret = check_extent_exists(root, new_start,
5549 fprintf(stderr, "Right section didn't "
5553 num_bytes = key.objectid - bytenr;
5556 num_bytes = key.objectid - bytenr;
5563 if (num_bytes && !ret) {
5564 fprintf(stderr, "There are no extents for csum range "
5565 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5569 btrfs_free_path(path);
5573 static int check_csums(struct btrfs_root *root)
5575 struct btrfs_path *path;
5576 struct extent_buffer *leaf;
5577 struct btrfs_key key;
5578 u64 offset = 0, num_bytes = 0;
5579 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5583 unsigned long leaf_offset;
5585 root = root->fs_info->csum_root;
5586 if (!extent_buffer_uptodate(root->node)) {
5587 fprintf(stderr, "No valid csum tree found\n");
5591 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5592 key.type = BTRFS_EXTENT_CSUM_KEY;
5595 path = btrfs_alloc_path();
5599 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5601 fprintf(stderr, "Error searching csum tree %d\n", ret);
5602 btrfs_free_path(path);
5606 if (ret > 0 && path->slots[0])
5611 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5612 ret = btrfs_next_leaf(root, path);
5614 fprintf(stderr, "Error going to next leaf "
5621 leaf = path->nodes[0];
5623 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5624 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5629 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5630 csum_size) * root->sectorsize;
5631 if (!check_data_csum)
5632 goto skip_csum_check;
5633 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5634 ret = check_extent_csums(root, key.offset, data_len,
5640 offset = key.offset;
5641 } else if (key.offset != offset + num_bytes) {
5642 ret = check_extent_exists(root, offset, num_bytes);
5644 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5645 "there is no extent record\n",
5646 offset, offset+num_bytes);
5649 offset = key.offset;
5652 num_bytes += data_len;
5656 btrfs_free_path(path);
5660 static int is_dropped_key(struct btrfs_key *key,
5661 struct btrfs_key *drop_key) {
5662 if (key->objectid < drop_key->objectid)
5664 else if (key->objectid == drop_key->objectid) {
5665 if (key->type < drop_key->type)
5667 else if (key->type == drop_key->type) {
5668 if (key->offset < drop_key->offset)
5676 * Here are the rules for FULL_BACKREF.
5678 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5679 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5681 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5682 * if it happened after the relocation occurred since we'll have dropped the
5683 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5684 * have no real way to know for sure.
5686 * We process the blocks one root at a time, and we start from the lowest root
5687 * objectid and go to the highest. So we can just lookup the owner backref for
5688 * the record and if we don't find it then we know it doesn't exist and we have
5691 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5692 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5693 * be set or not and then we can check later once we've gathered all the refs.
5695 static int calc_extent_flag(struct btrfs_root *root,
5696 struct cache_tree *extent_cache,
5697 struct extent_buffer *buf,
5698 struct root_item_record *ri,
5701 struct extent_record *rec;
5702 struct cache_extent *cache;
5703 struct tree_backref *tback;
5706 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5707 /* we have added this extent before */
5709 rec = container_of(cache, struct extent_record, cache);
5712 * Except file/reloc tree, we can not have
5715 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5720 if (buf->start == ri->bytenr)
5723 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5726 owner = btrfs_header_owner(buf);
5727 if (owner == ri->objectid)
5730 tback = find_tree_backref(rec, 0, owner);
5735 if (rec->flag_block_full_backref != -1 &&
5736 rec->flag_block_full_backref != 0)
5737 rec->bad_full_backref = 1;
5740 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5741 if (rec->flag_block_full_backref != -1 &&
5742 rec->flag_block_full_backref != 1)
5743 rec->bad_full_backref = 1;
5747 static int run_next_block(struct btrfs_root *root,
5748 struct block_info *bits,
5751 struct cache_tree *pending,
5752 struct cache_tree *seen,
5753 struct cache_tree *reada,
5754 struct cache_tree *nodes,
5755 struct cache_tree *extent_cache,
5756 struct cache_tree *chunk_cache,
5757 struct rb_root *dev_cache,
5758 struct block_group_tree *block_group_cache,
5759 struct device_extent_tree *dev_extent_cache,
5760 struct root_item_record *ri)
5762 struct extent_buffer *buf;
5763 struct extent_record *rec = NULL;
5774 struct btrfs_key key;
5775 struct cache_extent *cache;
5778 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5779 bits_nr, &reada_bits);
5784 for(i = 0; i < nritems; i++) {
5785 ret = add_cache_extent(reada, bits[i].start,
5790 /* fixme, get the parent transid */
5791 readahead_tree_block(root, bits[i].start,
5795 *last = bits[0].start;
5796 bytenr = bits[0].start;
5797 size = bits[0].size;
5799 cache = lookup_cache_extent(pending, bytenr, size);
5801 remove_cache_extent(pending, cache);
5804 cache = lookup_cache_extent(reada, bytenr, size);
5806 remove_cache_extent(reada, cache);
5809 cache = lookup_cache_extent(nodes, bytenr, size);
5811 remove_cache_extent(nodes, cache);
5814 cache = lookup_cache_extent(extent_cache, bytenr, size);
5816 rec = container_of(cache, struct extent_record, cache);
5817 gen = rec->parent_generation;
5820 /* fixme, get the real parent transid */
5821 buf = read_tree_block(root, bytenr, size, gen);
5822 if (!extent_buffer_uptodate(buf)) {
5823 record_bad_block_io(root->fs_info,
5824 extent_cache, bytenr, size);
5828 nritems = btrfs_header_nritems(buf);
5831 if (!init_extent_tree) {
5832 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5833 btrfs_header_level(buf), 1, NULL,
5836 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5838 fprintf(stderr, "Couldn't calc extent flags\n");
5839 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5844 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5846 fprintf(stderr, "Couldn't calc extent flags\n");
5847 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5851 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5853 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5854 ri->objectid == btrfs_header_owner(buf)) {
5856 * Ok we got to this block from it's original owner and
5857 * we have FULL_BACKREF set. Relocation can leave
5858 * converted blocks over so this is altogether possible,
5859 * however it's not possible if the generation > the
5860 * last snapshot, so check for this case.
5862 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5863 btrfs_header_generation(buf) > ri->last_snapshot) {
5864 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5865 rec->bad_full_backref = 1;
5870 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5871 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5872 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5873 rec->bad_full_backref = 1;
5877 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5878 rec->flag_block_full_backref = 1;
5882 rec->flag_block_full_backref = 0;
5884 owner = btrfs_header_owner(buf);
5887 ret = check_block(root, extent_cache, buf, flags);
5891 if (btrfs_is_leaf(buf)) {
5892 btree_space_waste += btrfs_leaf_free_space(root, buf);
5893 for (i = 0; i < nritems; i++) {
5894 struct btrfs_file_extent_item *fi;
5895 btrfs_item_key_to_cpu(buf, &key, i);
5896 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5897 process_extent_item(root, extent_cache, buf,
5901 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5902 process_extent_item(root, extent_cache, buf,
5906 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5908 btrfs_item_size_nr(buf, i);
5911 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5912 process_chunk_item(chunk_cache, &key, buf, i);
5915 if (key.type == BTRFS_DEV_ITEM_KEY) {
5916 process_device_item(dev_cache, &key, buf, i);
5919 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5920 process_block_group_item(block_group_cache,
5924 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5925 process_device_extent_item(dev_extent_cache,
5930 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5931 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5932 process_extent_ref_v0(extent_cache, buf, i);
5939 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5940 add_tree_backref(extent_cache, key.objectid, 0,
5944 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5945 add_tree_backref(extent_cache, key.objectid,
5949 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5950 struct btrfs_extent_data_ref *ref;
5951 ref = btrfs_item_ptr(buf, i,
5952 struct btrfs_extent_data_ref);
5953 add_data_backref(extent_cache,
5955 btrfs_extent_data_ref_root(buf, ref),
5956 btrfs_extent_data_ref_objectid(buf,
5958 btrfs_extent_data_ref_offset(buf, ref),
5959 btrfs_extent_data_ref_count(buf, ref),
5960 0, root->sectorsize);
5963 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5964 struct btrfs_shared_data_ref *ref;
5965 ref = btrfs_item_ptr(buf, i,
5966 struct btrfs_shared_data_ref);
5967 add_data_backref(extent_cache,
5968 key.objectid, key.offset, 0, 0, 0,
5969 btrfs_shared_data_ref_count(buf, ref),
5970 0, root->sectorsize);
5973 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5974 struct bad_item *bad;
5976 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5980 bad = malloc(sizeof(struct bad_item));
5983 INIT_LIST_HEAD(&bad->list);
5984 memcpy(&bad->key, &key,
5985 sizeof(struct btrfs_key));
5986 bad->root_id = owner;
5987 list_add_tail(&bad->list, &delete_items);
5990 if (key.type != BTRFS_EXTENT_DATA_KEY)
5992 fi = btrfs_item_ptr(buf, i,
5993 struct btrfs_file_extent_item);
5994 if (btrfs_file_extent_type(buf, fi) ==
5995 BTRFS_FILE_EXTENT_INLINE)
5997 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
6000 data_bytes_allocated +=
6001 btrfs_file_extent_disk_num_bytes(buf, fi);
6002 if (data_bytes_allocated < root->sectorsize) {
6005 data_bytes_referenced +=
6006 btrfs_file_extent_num_bytes(buf, fi);
6007 add_data_backref(extent_cache,
6008 btrfs_file_extent_disk_bytenr(buf, fi),
6009 parent, owner, key.objectid, key.offset -
6010 btrfs_file_extent_offset(buf, fi), 1, 1,
6011 btrfs_file_extent_disk_num_bytes(buf, fi));
6015 struct btrfs_key first_key;
6017 first_key.objectid = 0;
6020 btrfs_item_key_to_cpu(buf, &first_key, 0);
6021 level = btrfs_header_level(buf);
6022 for (i = 0; i < nritems; i++) {
6023 ptr = btrfs_node_blockptr(buf, i);
6024 size = btrfs_level_size(root, level - 1);
6025 btrfs_node_key_to_cpu(buf, &key, i);
6027 if ((level == ri->drop_level)
6028 && is_dropped_key(&key, &ri->drop_key)) {
6032 ret = add_extent_rec(extent_cache, &key,
6033 btrfs_node_ptr_generation(buf, i),
6034 ptr, size, 0, 0, 1, 0, 1, 0,
6038 add_tree_backref(extent_cache, ptr, parent, owner, 1);
6041 add_pending(nodes, seen, ptr, size);
6043 add_pending(pending, seen, ptr, size);
6046 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
6047 nritems) * sizeof(struct btrfs_key_ptr);
6049 total_btree_bytes += buf->len;
6050 if (fs_root_objectid(btrfs_header_owner(buf)))
6051 total_fs_tree_bytes += buf->len;
6052 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
6053 total_extent_tree_bytes += buf->len;
6054 if (!found_old_backref &&
6055 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
6056 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
6057 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
6058 found_old_backref = 1;
6060 free_extent_buffer(buf);
6064 static int add_root_to_pending(struct extent_buffer *buf,
6065 struct cache_tree *extent_cache,
6066 struct cache_tree *pending,
6067 struct cache_tree *seen,
6068 struct cache_tree *nodes,
6071 if (btrfs_header_level(buf) > 0)
6072 add_pending(nodes, seen, buf->start, buf->len);
6074 add_pending(pending, seen, buf->start, buf->len);
6075 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
6076 0, 1, 1, 0, 1, 0, buf->len);
6078 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
6079 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
6080 add_tree_backref(extent_cache, buf->start, buf->start,
6083 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
6087 /* as we fix the tree, we might be deleting blocks that
6088 * we're tracking for repair. This hook makes sure we
6089 * remove any backrefs for blocks as we are fixing them.
6091 static int free_extent_hook(struct btrfs_trans_handle *trans,
6092 struct btrfs_root *root,
6093 u64 bytenr, u64 num_bytes, u64 parent,
6094 u64 root_objectid, u64 owner, u64 offset,
6097 struct extent_record *rec;
6098 struct cache_extent *cache;
6100 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6102 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6103 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6107 rec = container_of(cache, struct extent_record, cache);
6109 struct data_backref *back;
6110 back = find_data_backref(rec, parent, root_objectid, owner,
6111 offset, 1, bytenr, num_bytes);
6114 if (back->node.found_ref) {
6115 back->found_ref -= refs_to_drop;
6117 rec->refs -= refs_to_drop;
6119 if (back->node.found_extent_tree) {
6120 back->num_refs -= refs_to_drop;
6121 if (rec->extent_item_refs)
6122 rec->extent_item_refs -= refs_to_drop;
6124 if (back->found_ref == 0)
6125 back->node.found_ref = 0;
6126 if (back->num_refs == 0)
6127 back->node.found_extent_tree = 0;
6129 if (!back->node.found_extent_tree && back->node.found_ref) {
6130 list_del(&back->node.list);
6134 struct tree_backref *back;
6135 back = find_tree_backref(rec, parent, root_objectid);
6138 if (back->node.found_ref) {
6141 back->node.found_ref = 0;
6143 if (back->node.found_extent_tree) {
6144 if (rec->extent_item_refs)
6145 rec->extent_item_refs--;
6146 back->node.found_extent_tree = 0;
6148 if (!back->node.found_extent_tree && back->node.found_ref) {
6149 list_del(&back->node.list);
6153 maybe_free_extent_rec(extent_cache, rec);
6158 static int delete_extent_records(struct btrfs_trans_handle *trans,
6159 struct btrfs_root *root,
6160 struct btrfs_path *path,
6161 u64 bytenr, u64 new_len)
6163 struct btrfs_key key;
6164 struct btrfs_key found_key;
6165 struct extent_buffer *leaf;
6170 key.objectid = bytenr;
6172 key.offset = (u64)-1;
6175 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6182 if (path->slots[0] == 0)
6188 leaf = path->nodes[0];
6189 slot = path->slots[0];
6191 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6192 if (found_key.objectid != bytenr)
6195 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6196 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6197 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6198 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6199 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6200 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6201 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6202 btrfs_release_path(path);
6203 if (found_key.type == 0) {
6204 if (found_key.offset == 0)
6206 key.offset = found_key.offset - 1;
6207 key.type = found_key.type;
6209 key.type = found_key.type - 1;
6210 key.offset = (u64)-1;
6214 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6215 found_key.objectid, found_key.type, found_key.offset);
6217 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6220 btrfs_release_path(path);
6222 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6223 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6224 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6225 found_key.offset : root->leafsize;
6227 ret = btrfs_update_block_group(trans, root, bytenr,
6234 btrfs_release_path(path);
6239 * for a single backref, this will allocate a new extent
6240 * and add the backref to it.
6242 static int record_extent(struct btrfs_trans_handle *trans,
6243 struct btrfs_fs_info *info,
6244 struct btrfs_path *path,
6245 struct extent_record *rec,
6246 struct extent_backref *back,
6247 int allocated, u64 flags)
6250 struct btrfs_root *extent_root = info->extent_root;
6251 struct extent_buffer *leaf;
6252 struct btrfs_key ins_key;
6253 struct btrfs_extent_item *ei;
6254 struct tree_backref *tback;
6255 struct data_backref *dback;
6256 struct btrfs_tree_block_info *bi;
6259 rec->max_size = max_t(u64, rec->max_size,
6260 info->extent_root->leafsize);
6263 u32 item_size = sizeof(*ei);
6266 item_size += sizeof(*bi);
6268 ins_key.objectid = rec->start;
6269 ins_key.offset = rec->max_size;
6270 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6272 ret = btrfs_insert_empty_item(trans, extent_root, path,
6273 &ins_key, item_size);
6277 leaf = path->nodes[0];
6278 ei = btrfs_item_ptr(leaf, path->slots[0],
6279 struct btrfs_extent_item);
6281 btrfs_set_extent_refs(leaf, ei, 0);
6282 btrfs_set_extent_generation(leaf, ei, rec->generation);
6284 if (back->is_data) {
6285 btrfs_set_extent_flags(leaf, ei,
6286 BTRFS_EXTENT_FLAG_DATA);
6288 struct btrfs_disk_key copy_key;;
6290 tback = (struct tree_backref *)back;
6291 bi = (struct btrfs_tree_block_info *)(ei + 1);
6292 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6295 btrfs_set_disk_key_objectid(©_key,
6296 rec->info_objectid);
6297 btrfs_set_disk_key_type(©_key, 0);
6298 btrfs_set_disk_key_offset(©_key, 0);
6300 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6301 btrfs_set_tree_block_key(leaf, bi, ©_key);
6303 btrfs_set_extent_flags(leaf, ei,
6304 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6307 btrfs_mark_buffer_dirty(leaf);
6308 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6309 rec->max_size, 1, 0);
6312 btrfs_release_path(path);
6315 if (back->is_data) {
6319 dback = (struct data_backref *)back;
6320 if (back->full_backref)
6321 parent = dback->parent;
6325 for (i = 0; i < dback->found_ref; i++) {
6326 /* if parent != 0, we're doing a full backref
6327 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6328 * just makes the backref allocator create a data
6331 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6332 rec->start, rec->max_size,
6336 BTRFS_FIRST_FREE_OBJECTID :
6342 fprintf(stderr, "adding new data backref"
6343 " on %llu %s %llu owner %llu"
6344 " offset %llu found %d\n",
6345 (unsigned long long)rec->start,
6346 back->full_backref ?
6348 back->full_backref ?
6349 (unsigned long long)parent :
6350 (unsigned long long)dback->root,
6351 (unsigned long long)dback->owner,
6352 (unsigned long long)dback->offset,
6357 tback = (struct tree_backref *)back;
6358 if (back->full_backref)
6359 parent = tback->parent;
6363 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6364 rec->start, rec->max_size,
6365 parent, tback->root, 0, 0);
6366 fprintf(stderr, "adding new tree backref on "
6367 "start %llu len %llu parent %llu root %llu\n",
6368 rec->start, rec->max_size, parent, tback->root);
6373 btrfs_release_path(path);
6377 struct extent_entry {
6382 struct list_head list;
6385 static struct extent_entry *find_entry(struct list_head *entries,
6386 u64 bytenr, u64 bytes)
6388 struct extent_entry *entry = NULL;
6390 list_for_each_entry(entry, entries, list) {
6391 if (entry->bytenr == bytenr && entry->bytes == bytes)
6398 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6400 struct extent_entry *entry, *best = NULL, *prev = NULL;
6402 list_for_each_entry(entry, entries, list) {
6409 * If there are as many broken entries as entries then we know
6410 * not to trust this particular entry.
6412 if (entry->broken == entry->count)
6416 * If our current entry == best then we can't be sure our best
6417 * is really the best, so we need to keep searching.
6419 if (best && best->count == entry->count) {
6425 /* Prev == entry, not good enough, have to keep searching */
6426 if (!prev->broken && prev->count == entry->count)
6430 best = (prev->count > entry->count) ? prev : entry;
6431 else if (best->count < entry->count)
6439 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6440 struct data_backref *dback, struct extent_entry *entry)
6442 struct btrfs_trans_handle *trans;
6443 struct btrfs_root *root;
6444 struct btrfs_file_extent_item *fi;
6445 struct extent_buffer *leaf;
6446 struct btrfs_key key;
6450 key.objectid = dback->root;
6451 key.type = BTRFS_ROOT_ITEM_KEY;
6452 key.offset = (u64)-1;
6453 root = btrfs_read_fs_root(info, &key);
6455 fprintf(stderr, "Couldn't find root for our ref\n");
6460 * The backref points to the original offset of the extent if it was
6461 * split, so we need to search down to the offset we have and then walk
6462 * forward until we find the backref we're looking for.
6464 key.objectid = dback->owner;
6465 key.type = BTRFS_EXTENT_DATA_KEY;
6466 key.offset = dback->offset;
6467 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6469 fprintf(stderr, "Error looking up ref %d\n", ret);
6474 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6475 ret = btrfs_next_leaf(root, path);
6477 fprintf(stderr, "Couldn't find our ref, next\n");
6481 leaf = path->nodes[0];
6482 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6483 if (key.objectid != dback->owner ||
6484 key.type != BTRFS_EXTENT_DATA_KEY) {
6485 fprintf(stderr, "Couldn't find our ref, search\n");
6488 fi = btrfs_item_ptr(leaf, path->slots[0],
6489 struct btrfs_file_extent_item);
6490 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6491 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6493 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6498 btrfs_release_path(path);
6500 trans = btrfs_start_transaction(root, 1);
6502 return PTR_ERR(trans);
6505 * Ok we have the key of the file extent we want to fix, now we can cow
6506 * down to the thing and fix it.
6508 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6510 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6511 key.objectid, key.type, key.offset, ret);
6515 fprintf(stderr, "Well that's odd, we just found this key "
6516 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6521 leaf = path->nodes[0];
6522 fi = btrfs_item_ptr(leaf, path->slots[0],
6523 struct btrfs_file_extent_item);
6525 if (btrfs_file_extent_compression(leaf, fi) &&
6526 dback->disk_bytenr != entry->bytenr) {
6527 fprintf(stderr, "Ref doesn't match the record start and is "
6528 "compressed, please take a btrfs-image of this file "
6529 "system and send it to a btrfs developer so they can "
6530 "complete this functionality for bytenr %Lu\n",
6531 dback->disk_bytenr);
6536 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6537 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6538 } else if (dback->disk_bytenr > entry->bytenr) {
6539 u64 off_diff, offset;
6541 off_diff = dback->disk_bytenr - entry->bytenr;
6542 offset = btrfs_file_extent_offset(leaf, fi);
6543 if (dback->disk_bytenr + offset +
6544 btrfs_file_extent_num_bytes(leaf, fi) >
6545 entry->bytenr + entry->bytes) {
6546 fprintf(stderr, "Ref is past the entry end, please "
6547 "take a btrfs-image of this file system and "
6548 "send it to a btrfs developer, ref %Lu\n",
6549 dback->disk_bytenr);
6554 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6555 btrfs_set_file_extent_offset(leaf, fi, offset);
6556 } else if (dback->disk_bytenr < entry->bytenr) {
6559 offset = btrfs_file_extent_offset(leaf, fi);
6560 if (dback->disk_bytenr + offset < entry->bytenr) {
6561 fprintf(stderr, "Ref is before the entry start, please"
6562 " take a btrfs-image of this file system and "
6563 "send it to a btrfs developer, ref %Lu\n",
6564 dback->disk_bytenr);
6569 offset += dback->disk_bytenr;
6570 offset -= entry->bytenr;
6571 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6572 btrfs_set_file_extent_offset(leaf, fi, offset);
6575 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6578 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6579 * only do this if we aren't using compression, otherwise it's a
6582 if (!btrfs_file_extent_compression(leaf, fi))
6583 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6585 printf("ram bytes may be wrong?\n");
6586 btrfs_mark_buffer_dirty(leaf);
6588 err = btrfs_commit_transaction(trans, root);
6589 btrfs_release_path(path);
6590 return ret ? ret : err;
6593 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6594 struct extent_record *rec)
6596 struct extent_backref *back;
6597 struct data_backref *dback;
6598 struct extent_entry *entry, *best = NULL;
6601 int broken_entries = 0;
6606 * Metadata is easy and the backrefs should always agree on bytenr and
6607 * size, if not we've got bigger issues.
6612 list_for_each_entry(back, &rec->backrefs, list) {
6613 if (back->full_backref || !back->is_data)
6616 dback = (struct data_backref *)back;
6619 * We only pay attention to backrefs that we found a real
6622 if (dback->found_ref == 0)
6626 * For now we only catch when the bytes don't match, not the
6627 * bytenr. We can easily do this at the same time, but I want
6628 * to have a fs image to test on before we just add repair
6629 * functionality willy-nilly so we know we won't screw up the
6633 entry = find_entry(&entries, dback->disk_bytenr,
6636 entry = malloc(sizeof(struct extent_entry));
6641 memset(entry, 0, sizeof(*entry));
6642 entry->bytenr = dback->disk_bytenr;
6643 entry->bytes = dback->bytes;
6644 list_add_tail(&entry->list, &entries);
6649 * If we only have on entry we may think the entries agree when
6650 * in reality they don't so we have to do some extra checking.
6652 if (dback->disk_bytenr != rec->start ||
6653 dback->bytes != rec->nr || back->broken)
6664 /* Yay all the backrefs agree, carry on good sir */
6665 if (nr_entries <= 1 && !mismatch)
6668 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6669 "%Lu\n", rec->start);
6672 * First we want to see if the backrefs can agree amongst themselves who
6673 * is right, so figure out which one of the entries has the highest
6676 best = find_most_right_entry(&entries);
6679 * Ok so we may have an even split between what the backrefs think, so
6680 * this is where we use the extent ref to see what it thinks.
6683 entry = find_entry(&entries, rec->start, rec->nr);
6684 if (!entry && (!broken_entries || !rec->found_rec)) {
6685 fprintf(stderr, "Backrefs don't agree with each other "
6686 "and extent record doesn't agree with anybody,"
6687 " so we can't fix bytenr %Lu bytes %Lu\n",
6688 rec->start, rec->nr);
6691 } else if (!entry) {
6693 * Ok our backrefs were broken, we'll assume this is the
6694 * correct value and add an entry for this range.
6696 entry = malloc(sizeof(struct extent_entry));
6701 memset(entry, 0, sizeof(*entry));
6702 entry->bytenr = rec->start;
6703 entry->bytes = rec->nr;
6704 list_add_tail(&entry->list, &entries);
6708 best = find_most_right_entry(&entries);
6710 fprintf(stderr, "Backrefs and extent record evenly "
6711 "split on who is right, this is going to "
6712 "require user input to fix bytenr %Lu bytes "
6713 "%Lu\n", rec->start, rec->nr);
6720 * I don't think this can happen currently as we'll abort() if we catch
6721 * this case higher up, but in case somebody removes that we still can't
6722 * deal with it properly here yet, so just bail out of that's the case.
6724 if (best->bytenr != rec->start) {
6725 fprintf(stderr, "Extent start and backref starts don't match, "
6726 "please use btrfs-image on this file system and send "
6727 "it to a btrfs developer so they can make fsck fix "
6728 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6729 rec->start, rec->nr);
6735 * Ok great we all agreed on an extent record, let's go find the real
6736 * references and fix up the ones that don't match.
6738 list_for_each_entry(back, &rec->backrefs, list) {
6739 if (back->full_backref || !back->is_data)
6742 dback = (struct data_backref *)back;
6745 * Still ignoring backrefs that don't have a real ref attached
6748 if (dback->found_ref == 0)
6751 if (dback->bytes == best->bytes &&
6752 dback->disk_bytenr == best->bytenr)
6755 ret = repair_ref(info, path, dback, best);
6761 * Ok we messed with the actual refs, which means we need to drop our
6762 * entire cache and go back and rescan. I know this is a huge pain and
6763 * adds a lot of extra work, but it's the only way to be safe. Once all
6764 * the backrefs agree we may not need to do anything to the extent
6769 while (!list_empty(&entries)) {
6770 entry = list_entry(entries.next, struct extent_entry, list);
6771 list_del_init(&entry->list);
6777 static int process_duplicates(struct btrfs_root *root,
6778 struct cache_tree *extent_cache,
6779 struct extent_record *rec)
6781 struct extent_record *good, *tmp;
6782 struct cache_extent *cache;
6786 * If we found a extent record for this extent then return, or if we
6787 * have more than one duplicate we are likely going to need to delete
6790 if (rec->found_rec || rec->num_duplicates > 1)
6793 /* Shouldn't happen but just in case */
6794 BUG_ON(!rec->num_duplicates);
6797 * So this happens if we end up with a backref that doesn't match the
6798 * actual extent entry. So either the backref is bad or the extent
6799 * entry is bad. Either way we want to have the extent_record actually
6800 * reflect what we found in the extent_tree, so we need to take the
6801 * duplicate out and use that as the extent_record since the only way we
6802 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6804 remove_cache_extent(extent_cache, &rec->cache);
6806 good = list_entry(rec->dups.next, struct extent_record, list);
6807 list_del_init(&good->list);
6808 INIT_LIST_HEAD(&good->backrefs);
6809 INIT_LIST_HEAD(&good->dups);
6810 good->cache.start = good->start;
6811 good->cache.size = good->nr;
6812 good->content_checked = 0;
6813 good->owner_ref_checked = 0;
6814 good->num_duplicates = 0;
6815 good->refs = rec->refs;
6816 list_splice_init(&rec->backrefs, &good->backrefs);
6818 cache = lookup_cache_extent(extent_cache, good->start,
6822 tmp = container_of(cache, struct extent_record, cache);
6825 * If we find another overlapping extent and it's found_rec is
6826 * set then it's a duplicate and we need to try and delete
6829 if (tmp->found_rec || tmp->num_duplicates > 0) {
6830 if (list_empty(&good->list))
6831 list_add_tail(&good->list,
6832 &duplicate_extents);
6833 good->num_duplicates += tmp->num_duplicates + 1;
6834 list_splice_init(&tmp->dups, &good->dups);
6835 list_del_init(&tmp->list);
6836 list_add_tail(&tmp->list, &good->dups);
6837 remove_cache_extent(extent_cache, &tmp->cache);
6842 * Ok we have another non extent item backed extent rec, so lets
6843 * just add it to this extent and carry on like we did above.
6845 good->refs += tmp->refs;
6846 list_splice_init(&tmp->backrefs, &good->backrefs);
6847 remove_cache_extent(extent_cache, &tmp->cache);
6850 ret = insert_cache_extent(extent_cache, &good->cache);
6853 return good->num_duplicates ? 0 : 1;
6856 static int delete_duplicate_records(struct btrfs_root *root,
6857 struct extent_record *rec)
6859 struct btrfs_trans_handle *trans;
6860 LIST_HEAD(delete_list);
6861 struct btrfs_path *path;
6862 struct extent_record *tmp, *good, *n;
6865 struct btrfs_key key;
6867 path = btrfs_alloc_path();
6874 /* Find the record that covers all of the duplicates. */
6875 list_for_each_entry(tmp, &rec->dups, list) {
6876 if (good->start < tmp->start)
6878 if (good->nr > tmp->nr)
6881 if (tmp->start + tmp->nr < good->start + good->nr) {
6882 fprintf(stderr, "Ok we have overlapping extents that "
6883 "aren't completely covered by eachother, this "
6884 "is going to require more careful thought. "
6885 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6886 tmp->start, tmp->nr, good->start, good->nr);
6893 list_add_tail(&rec->list, &delete_list);
6895 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6898 list_move_tail(&tmp->list, &delete_list);
6901 root = root->fs_info->extent_root;
6902 trans = btrfs_start_transaction(root, 1);
6903 if (IS_ERR(trans)) {
6904 ret = PTR_ERR(trans);
6908 list_for_each_entry(tmp, &delete_list, list) {
6909 if (tmp->found_rec == 0)
6911 key.objectid = tmp->start;
6912 key.type = BTRFS_EXTENT_ITEM_KEY;
6913 key.offset = tmp->nr;
6915 /* Shouldn't happen but just in case */
6916 if (tmp->metadata) {
6917 fprintf(stderr, "Well this shouldn't happen, extent "
6918 "record overlaps but is metadata? "
6919 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6923 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6929 ret = btrfs_del_item(trans, root, path);
6932 btrfs_release_path(path);
6935 err = btrfs_commit_transaction(trans, root);
6939 while (!list_empty(&delete_list)) {
6940 tmp = list_entry(delete_list.next, struct extent_record, list);
6941 list_del_init(&tmp->list);
6947 while (!list_empty(&rec->dups)) {
6948 tmp = list_entry(rec->dups.next, struct extent_record, list);
6949 list_del_init(&tmp->list);
6953 btrfs_free_path(path);
6955 if (!ret && !nr_del)
6956 rec->num_duplicates = 0;
6958 return ret ? ret : nr_del;
6961 static int find_possible_backrefs(struct btrfs_fs_info *info,
6962 struct btrfs_path *path,
6963 struct cache_tree *extent_cache,
6964 struct extent_record *rec)
6966 struct btrfs_root *root;
6967 struct extent_backref *back;
6968 struct data_backref *dback;
6969 struct cache_extent *cache;
6970 struct btrfs_file_extent_item *fi;
6971 struct btrfs_key key;
6975 list_for_each_entry(back, &rec->backrefs, list) {
6976 /* Don't care about full backrefs (poor unloved backrefs) */
6977 if (back->full_backref || !back->is_data)
6980 dback = (struct data_backref *)back;
6982 /* We found this one, we don't need to do a lookup */
6983 if (dback->found_ref)
6986 key.objectid = dback->root;
6987 key.type = BTRFS_ROOT_ITEM_KEY;
6988 key.offset = (u64)-1;
6990 root = btrfs_read_fs_root(info, &key);
6992 /* No root, definitely a bad ref, skip */
6993 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6995 /* Other err, exit */
6997 return PTR_ERR(root);
6999 key.objectid = dback->owner;
7000 key.type = BTRFS_EXTENT_DATA_KEY;
7001 key.offset = dback->offset;
7002 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7004 btrfs_release_path(path);
7007 /* Didn't find it, we can carry on */
7012 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
7013 struct btrfs_file_extent_item);
7014 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
7015 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
7016 btrfs_release_path(path);
7017 cache = lookup_cache_extent(extent_cache, bytenr, 1);
7019 struct extent_record *tmp;
7020 tmp = container_of(cache, struct extent_record, cache);
7023 * If we found an extent record for the bytenr for this
7024 * particular backref then we can't add it to our
7025 * current extent record. We only want to add backrefs
7026 * that don't have a corresponding extent item in the
7027 * extent tree since they likely belong to this record
7028 * and we need to fix it if it doesn't match bytenrs.
7034 dback->found_ref += 1;
7035 dback->disk_bytenr = bytenr;
7036 dback->bytes = bytes;
7039 * Set this so the verify backref code knows not to trust the
7040 * values in this backref.
7049 * Record orphan data ref into corresponding root.
7051 * Return 0 if the extent item contains data ref and recorded.
7052 * Return 1 if the extent item contains no useful data ref
7053 * On that case, it may contains only shared_dataref or metadata backref
7054 * or the file extent exists(this should be handled by the extent bytenr
7056 * Return <0 if something goes wrong.
7058 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
7059 struct extent_record *rec)
7061 struct btrfs_key key;
7062 struct btrfs_root *dest_root;
7063 struct extent_backref *back;
7064 struct data_backref *dback;
7065 struct orphan_data_extent *orphan;
7066 struct btrfs_path *path;
7067 int recorded_data_ref = 0;
7072 path = btrfs_alloc_path();
7075 list_for_each_entry(back, &rec->backrefs, list) {
7076 if (back->full_backref || !back->is_data ||
7077 !back->found_extent_tree)
7079 dback = (struct data_backref *)back;
7080 if (dback->found_ref)
7082 key.objectid = dback->root;
7083 key.type = BTRFS_ROOT_ITEM_KEY;
7084 key.offset = (u64)-1;
7086 dest_root = btrfs_read_fs_root(fs_info, &key);
7088 /* For non-exist root we just skip it */
7089 if (IS_ERR(dest_root) || !dest_root)
7092 key.objectid = dback->owner;
7093 key.type = BTRFS_EXTENT_DATA_KEY;
7094 key.offset = dback->offset;
7096 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7098 * For ret < 0, it's OK since the fs-tree may be corrupted,
7099 * we need to record it for inode/file extent rebuild.
7100 * For ret > 0, we record it only for file extent rebuild.
7101 * For ret == 0, the file extent exists but only bytenr
7102 * mismatch, let the original bytenr fix routine to handle,
7108 orphan = malloc(sizeof(*orphan));
7113 INIT_LIST_HEAD(&orphan->list);
7114 orphan->root = dback->root;
7115 orphan->objectid = dback->owner;
7116 orphan->offset = dback->offset;
7117 orphan->disk_bytenr = rec->cache.start;
7118 orphan->disk_len = rec->cache.size;
7119 list_add(&dest_root->orphan_data_extents, &orphan->list);
7120 recorded_data_ref = 1;
7123 btrfs_free_path(path);
7125 return !recorded_data_ref;
7131 * when an incorrect extent item is found, this will delete
7132 * all of the existing entries for it and recreate them
7133 * based on what the tree scan found.
7135 static int fixup_extent_refs(struct btrfs_fs_info *info,
7136 struct cache_tree *extent_cache,
7137 struct extent_record *rec)
7139 struct btrfs_trans_handle *trans = NULL;
7141 struct btrfs_path *path;
7142 struct list_head *cur = rec->backrefs.next;
7143 struct cache_extent *cache;
7144 struct extent_backref *back;
7148 if (rec->flag_block_full_backref)
7149 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7151 path = btrfs_alloc_path();
7155 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7157 * Sometimes the backrefs themselves are so broken they don't
7158 * get attached to any meaningful rec, so first go back and
7159 * check any of our backrefs that we couldn't find and throw
7160 * them into the list if we find the backref so that
7161 * verify_backrefs can figure out what to do.
7163 ret = find_possible_backrefs(info, path, extent_cache, rec);
7168 /* step one, make sure all of the backrefs agree */
7169 ret = verify_backrefs(info, path, rec);
7173 trans = btrfs_start_transaction(info->extent_root, 1);
7174 if (IS_ERR(trans)) {
7175 ret = PTR_ERR(trans);
7179 /* step two, delete all the existing records */
7180 ret = delete_extent_records(trans, info->extent_root, path,
7181 rec->start, rec->max_size);
7186 /* was this block corrupt? If so, don't add references to it */
7187 cache = lookup_cache_extent(info->corrupt_blocks,
7188 rec->start, rec->max_size);
7194 /* step three, recreate all the refs we did find */
7195 while(cur != &rec->backrefs) {
7196 back = list_entry(cur, struct extent_backref, list);
7200 * if we didn't find any references, don't create a
7203 if (!back->found_ref)
7206 rec->bad_full_backref = 0;
7207 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7215 int err = btrfs_commit_transaction(trans, info->extent_root);
7220 btrfs_free_path(path);
7224 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7225 struct extent_record *rec)
7227 struct btrfs_trans_handle *trans;
7228 struct btrfs_root *root = fs_info->extent_root;
7229 struct btrfs_path *path;
7230 struct btrfs_extent_item *ei;
7231 struct btrfs_key key;
7235 key.objectid = rec->start;
7236 if (rec->metadata) {
7237 key.type = BTRFS_METADATA_ITEM_KEY;
7238 key.offset = rec->info_level;
7240 key.type = BTRFS_EXTENT_ITEM_KEY;
7241 key.offset = rec->max_size;
7244 path = btrfs_alloc_path();
7248 trans = btrfs_start_transaction(root, 0);
7249 if (IS_ERR(trans)) {
7250 btrfs_free_path(path);
7251 return PTR_ERR(trans);
7254 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7256 btrfs_free_path(path);
7257 btrfs_commit_transaction(trans, root);
7260 fprintf(stderr, "Didn't find extent for %llu\n",
7261 (unsigned long long)rec->start);
7262 btrfs_free_path(path);
7263 btrfs_commit_transaction(trans, root);
7267 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7268 struct btrfs_extent_item);
7269 flags = btrfs_extent_flags(path->nodes[0], ei);
7270 if (rec->flag_block_full_backref) {
7271 fprintf(stderr, "setting full backref on %llu\n",
7272 (unsigned long long)key.objectid);
7273 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7275 fprintf(stderr, "clearing full backref on %llu\n",
7276 (unsigned long long)key.objectid);
7277 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7279 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7280 btrfs_mark_buffer_dirty(path->nodes[0]);
7281 btrfs_free_path(path);
7282 return btrfs_commit_transaction(trans, root);
7285 /* right now we only prune from the extent allocation tree */
7286 static int prune_one_block(struct btrfs_trans_handle *trans,
7287 struct btrfs_fs_info *info,
7288 struct btrfs_corrupt_block *corrupt)
7291 struct btrfs_path path;
7292 struct extent_buffer *eb;
7296 int level = corrupt->level + 1;
7298 btrfs_init_path(&path);
7300 /* we want to stop at the parent to our busted block */
7301 path.lowest_level = level;
7303 ret = btrfs_search_slot(trans, info->extent_root,
7304 &corrupt->key, &path, -1, 1);
7309 eb = path.nodes[level];
7316 * hopefully the search gave us the block we want to prune,
7317 * lets try that first
7319 slot = path.slots[level];
7320 found = btrfs_node_blockptr(eb, slot);
7321 if (found == corrupt->cache.start)
7324 nritems = btrfs_header_nritems(eb);
7326 /* the search failed, lets scan this node and hope we find it */
7327 for (slot = 0; slot < nritems; slot++) {
7328 found = btrfs_node_blockptr(eb, slot);
7329 if (found == corrupt->cache.start)
7333 * we couldn't find the bad block. TODO, search all the nodes for pointers
7336 if (eb == info->extent_root->node) {
7341 btrfs_release_path(&path);
7346 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7347 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7350 btrfs_release_path(&path);
7354 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7356 struct btrfs_trans_handle *trans = NULL;
7357 struct cache_extent *cache;
7358 struct btrfs_corrupt_block *corrupt;
7361 cache = search_cache_extent(info->corrupt_blocks, 0);
7365 trans = btrfs_start_transaction(info->extent_root, 1);
7367 return PTR_ERR(trans);
7369 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7370 prune_one_block(trans, info, corrupt);
7371 remove_cache_extent(info->corrupt_blocks, cache);
7374 return btrfs_commit_transaction(trans, info->extent_root);
7378 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7380 struct btrfs_block_group_cache *cache;
7385 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7386 &start, &end, EXTENT_DIRTY);
7389 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7395 cache = btrfs_lookup_first_block_group(fs_info, start);
7400 start = cache->key.objectid + cache->key.offset;
7404 static int check_extent_refs(struct btrfs_root *root,
7405 struct cache_tree *extent_cache)
7407 struct extent_record *rec;
7408 struct cache_extent *cache;
7417 * if we're doing a repair, we have to make sure
7418 * we don't allocate from the problem extents.
7419 * In the worst case, this will be all the
7422 cache = search_cache_extent(extent_cache, 0);
7424 rec = container_of(cache, struct extent_record, cache);
7425 set_extent_dirty(root->fs_info->excluded_extents,
7427 rec->start + rec->max_size - 1,
7429 cache = next_cache_extent(cache);
7432 /* pin down all the corrupted blocks too */
7433 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7435 set_extent_dirty(root->fs_info->excluded_extents,
7437 cache->start + cache->size - 1,
7439 cache = next_cache_extent(cache);
7441 prune_corrupt_blocks(root->fs_info);
7442 reset_cached_block_groups(root->fs_info);
7445 reset_cached_block_groups(root->fs_info);
7448 * We need to delete any duplicate entries we find first otherwise we
7449 * could mess up the extent tree when we have backrefs that actually
7450 * belong to a different extent item and not the weird duplicate one.
7452 while (repair && !list_empty(&duplicate_extents)) {
7453 rec = list_entry(duplicate_extents.next, struct extent_record,
7455 list_del_init(&rec->list);
7457 /* Sometimes we can find a backref before we find an actual
7458 * extent, so we need to process it a little bit to see if there
7459 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7460 * if this is a backref screwup. If we need to delete stuff
7461 * process_duplicates() will return 0, otherwise it will return
7464 if (process_duplicates(root, extent_cache, rec))
7466 ret = delete_duplicate_records(root, rec);
7470 * delete_duplicate_records will return the number of entries
7471 * deleted, so if it's greater than 0 then we know we actually
7472 * did something and we need to remove.
7486 cache = search_cache_extent(extent_cache, 0);
7489 rec = container_of(cache, struct extent_record, cache);
7490 if (rec->num_duplicates) {
7491 fprintf(stderr, "extent item %llu has multiple extent "
7492 "items\n", (unsigned long long)rec->start);
7497 if (rec->refs != rec->extent_item_refs) {
7498 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7499 (unsigned long long)rec->start,
7500 (unsigned long long)rec->nr);
7501 fprintf(stderr, "extent item %llu, found %llu\n",
7502 (unsigned long long)rec->extent_item_refs,
7503 (unsigned long long)rec->refs);
7504 ret = record_orphan_data_extents(root->fs_info, rec);
7511 * we can't use the extent to repair file
7512 * extent, let the fallback method handle it.
7514 if (!fixed && repair) {
7515 ret = fixup_extent_refs(
7526 if (all_backpointers_checked(rec, 1)) {
7527 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7528 (unsigned long long)rec->start,
7529 (unsigned long long)rec->nr);
7531 if (!fixed && !recorded && repair) {
7532 ret = fixup_extent_refs(root->fs_info,
7541 if (!rec->owner_ref_checked) {
7542 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7543 (unsigned long long)rec->start,
7544 (unsigned long long)rec->nr);
7545 if (!fixed && !recorded && repair) {
7546 ret = fixup_extent_refs(root->fs_info,
7555 if (rec->bad_full_backref) {
7556 fprintf(stderr, "bad full backref, on [%llu]\n",
7557 (unsigned long long)rec->start);
7559 ret = fixup_extent_flags(root->fs_info, rec);
7568 * Although it's not a extent ref's problem, we reuse this
7569 * routine for error reporting.
7570 * No repair function yet.
7572 if (rec->crossing_stripes) {
7574 "bad metadata [%llu, %llu) crossing stripe boundary\n",
7575 rec->start, rec->start + rec->max_size);
7580 if (rec->wrong_chunk_type) {
7582 "bad extent [%llu, %llu), type mismatch with chunk\n",
7583 rec->start, rec->start + rec->max_size);
7588 remove_cache_extent(extent_cache, cache);
7589 free_all_extent_backrefs(rec);
7590 if (!init_extent_tree && repair && (!cur_err || fixed))
7591 clear_extent_dirty(root->fs_info->excluded_extents,
7593 rec->start + rec->max_size - 1,
7599 if (ret && ret != -EAGAIN) {
7600 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7603 struct btrfs_trans_handle *trans;
7605 root = root->fs_info->extent_root;
7606 trans = btrfs_start_transaction(root, 1);
7607 if (IS_ERR(trans)) {
7608 ret = PTR_ERR(trans);
7612 btrfs_fix_block_accounting(trans, root);
7613 ret = btrfs_commit_transaction(trans, root);
7618 fprintf(stderr, "repaired damaged extent references\n");
7624 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7628 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7629 stripe_size = length;
7630 stripe_size /= num_stripes;
7631 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7632 stripe_size = length * 2;
7633 stripe_size /= num_stripes;
7634 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7635 stripe_size = length;
7636 stripe_size /= (num_stripes - 1);
7637 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7638 stripe_size = length;
7639 stripe_size /= (num_stripes - 2);
7641 stripe_size = length;
7647 * Check the chunk with its block group/dev list ref:
7648 * Return 0 if all refs seems valid.
7649 * Return 1 if part of refs seems valid, need later check for rebuild ref
7650 * like missing block group and needs to search extent tree to rebuild them.
7651 * Return -1 if essential refs are missing and unable to rebuild.
7653 static int check_chunk_refs(struct chunk_record *chunk_rec,
7654 struct block_group_tree *block_group_cache,
7655 struct device_extent_tree *dev_extent_cache,
7658 struct cache_extent *block_group_item;
7659 struct block_group_record *block_group_rec;
7660 struct cache_extent *dev_extent_item;
7661 struct device_extent_record *dev_extent_rec;
7665 int metadump_v2 = 0;
7669 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7672 if (block_group_item) {
7673 block_group_rec = container_of(block_group_item,
7674 struct block_group_record,
7676 if (chunk_rec->length != block_group_rec->offset ||
7677 chunk_rec->offset != block_group_rec->objectid ||
7679 chunk_rec->type_flags != block_group_rec->flags)) {
7682 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7683 chunk_rec->objectid,
7688 chunk_rec->type_flags,
7689 block_group_rec->objectid,
7690 block_group_rec->type,
7691 block_group_rec->offset,
7692 block_group_rec->offset,
7693 block_group_rec->objectid,
7694 block_group_rec->flags);
7697 list_del_init(&block_group_rec->list);
7698 chunk_rec->bg_rec = block_group_rec;
7703 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7704 chunk_rec->objectid,
7709 chunk_rec->type_flags);
7716 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7717 chunk_rec->num_stripes);
7718 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7719 devid = chunk_rec->stripes[i].devid;
7720 offset = chunk_rec->stripes[i].offset;
7721 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7722 devid, offset, length);
7723 if (dev_extent_item) {
7724 dev_extent_rec = container_of(dev_extent_item,
7725 struct device_extent_record,
7727 if (dev_extent_rec->objectid != devid ||
7728 dev_extent_rec->offset != offset ||
7729 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7730 dev_extent_rec->length != length) {
7733 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7734 chunk_rec->objectid,
7737 chunk_rec->stripes[i].devid,
7738 chunk_rec->stripes[i].offset,
7739 dev_extent_rec->objectid,
7740 dev_extent_rec->offset,
7741 dev_extent_rec->length);
7744 list_move(&dev_extent_rec->chunk_list,
7745 &chunk_rec->dextents);
7750 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7751 chunk_rec->objectid,
7754 chunk_rec->stripes[i].devid,
7755 chunk_rec->stripes[i].offset);
7762 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7763 int check_chunks(struct cache_tree *chunk_cache,
7764 struct block_group_tree *block_group_cache,
7765 struct device_extent_tree *dev_extent_cache,
7766 struct list_head *good, struct list_head *bad,
7767 struct list_head *rebuild, int silent)
7769 struct cache_extent *chunk_item;
7770 struct chunk_record *chunk_rec;
7771 struct block_group_record *bg_rec;
7772 struct device_extent_record *dext_rec;
7776 chunk_item = first_cache_extent(chunk_cache);
7777 while (chunk_item) {
7778 chunk_rec = container_of(chunk_item, struct chunk_record,
7780 err = check_chunk_refs(chunk_rec, block_group_cache,
7781 dev_extent_cache, silent);
7784 if (err == 0 && good)
7785 list_add_tail(&chunk_rec->list, good);
7786 if (err > 0 && rebuild)
7787 list_add_tail(&chunk_rec->list, rebuild);
7789 list_add_tail(&chunk_rec->list, bad);
7790 chunk_item = next_cache_extent(chunk_item);
7793 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7796 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7804 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7808 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7819 static int check_device_used(struct device_record *dev_rec,
7820 struct device_extent_tree *dext_cache)
7822 struct cache_extent *cache;
7823 struct device_extent_record *dev_extent_rec;
7826 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7828 dev_extent_rec = container_of(cache,
7829 struct device_extent_record,
7831 if (dev_extent_rec->objectid != dev_rec->devid)
7834 list_del_init(&dev_extent_rec->device_list);
7835 total_byte += dev_extent_rec->length;
7836 cache = next_cache_extent(cache);
7839 if (total_byte != dev_rec->byte_used) {
7841 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7842 total_byte, dev_rec->byte_used, dev_rec->objectid,
7843 dev_rec->type, dev_rec->offset);
7850 /* check btrfs_dev_item -> btrfs_dev_extent */
7851 static int check_devices(struct rb_root *dev_cache,
7852 struct device_extent_tree *dev_extent_cache)
7854 struct rb_node *dev_node;
7855 struct device_record *dev_rec;
7856 struct device_extent_record *dext_rec;
7860 dev_node = rb_first(dev_cache);
7862 dev_rec = container_of(dev_node, struct device_record, node);
7863 err = check_device_used(dev_rec, dev_extent_cache);
7867 dev_node = rb_next(dev_node);
7869 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7872 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7873 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7880 static int add_root_item_to_list(struct list_head *head,
7881 u64 objectid, u64 bytenr, u64 last_snapshot,
7882 u8 level, u8 drop_level,
7883 int level_size, struct btrfs_key *drop_key)
7886 struct root_item_record *ri_rec;
7887 ri_rec = malloc(sizeof(*ri_rec));
7890 ri_rec->bytenr = bytenr;
7891 ri_rec->objectid = objectid;
7892 ri_rec->level = level;
7893 ri_rec->level_size = level_size;
7894 ri_rec->drop_level = drop_level;
7895 ri_rec->last_snapshot = last_snapshot;
7897 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7898 list_add_tail(&ri_rec->list, head);
7903 static void free_root_item_list(struct list_head *list)
7905 struct root_item_record *ri_rec;
7907 while (!list_empty(list)) {
7908 ri_rec = list_first_entry(list, struct root_item_record,
7910 list_del_init(&ri_rec->list);
7915 static int deal_root_from_list(struct list_head *list,
7916 struct btrfs_root *root,
7917 struct block_info *bits,
7919 struct cache_tree *pending,
7920 struct cache_tree *seen,
7921 struct cache_tree *reada,
7922 struct cache_tree *nodes,
7923 struct cache_tree *extent_cache,
7924 struct cache_tree *chunk_cache,
7925 struct rb_root *dev_cache,
7926 struct block_group_tree *block_group_cache,
7927 struct device_extent_tree *dev_extent_cache)
7932 while (!list_empty(list)) {
7933 struct root_item_record *rec;
7934 struct extent_buffer *buf;
7935 rec = list_entry(list->next,
7936 struct root_item_record, list);
7938 buf = read_tree_block(root->fs_info->tree_root,
7939 rec->bytenr, rec->level_size, 0);
7940 if (!extent_buffer_uptodate(buf)) {
7941 free_extent_buffer(buf);
7945 add_root_to_pending(buf, extent_cache, pending,
7946 seen, nodes, rec->objectid);
7948 * To rebuild extent tree, we need deal with snapshot
7949 * one by one, otherwise we deal with node firstly which
7950 * can maximize readahead.
7953 ret = run_next_block(root, bits, bits_nr, &last,
7954 pending, seen, reada, nodes,
7955 extent_cache, chunk_cache,
7956 dev_cache, block_group_cache,
7957 dev_extent_cache, rec);
7961 free_extent_buffer(buf);
7962 list_del(&rec->list);
7968 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7969 reada, nodes, extent_cache, chunk_cache,
7970 dev_cache, block_group_cache,
7971 dev_extent_cache, NULL);
7981 static int check_chunks_and_extents(struct btrfs_root *root)
7983 struct rb_root dev_cache;
7984 struct cache_tree chunk_cache;
7985 struct block_group_tree block_group_cache;
7986 struct device_extent_tree dev_extent_cache;
7987 struct cache_tree extent_cache;
7988 struct cache_tree seen;
7989 struct cache_tree pending;
7990 struct cache_tree reada;
7991 struct cache_tree nodes;
7992 struct extent_io_tree excluded_extents;
7993 struct cache_tree corrupt_blocks;
7994 struct btrfs_path path;
7995 struct btrfs_key key;
7996 struct btrfs_key found_key;
7998 struct block_info *bits;
8000 struct extent_buffer *leaf;
8002 struct btrfs_root_item ri;
8003 struct list_head dropping_trees;
8004 struct list_head normal_trees;
8005 struct btrfs_root *root1;
8010 dev_cache = RB_ROOT;
8011 cache_tree_init(&chunk_cache);
8012 block_group_tree_init(&block_group_cache);
8013 device_extent_tree_init(&dev_extent_cache);
8015 cache_tree_init(&extent_cache);
8016 cache_tree_init(&seen);
8017 cache_tree_init(&pending);
8018 cache_tree_init(&nodes);
8019 cache_tree_init(&reada);
8020 cache_tree_init(&corrupt_blocks);
8021 extent_io_tree_init(&excluded_extents);
8022 INIT_LIST_HEAD(&dropping_trees);
8023 INIT_LIST_HEAD(&normal_trees);
8026 root->fs_info->excluded_extents = &excluded_extents;
8027 root->fs_info->fsck_extent_cache = &extent_cache;
8028 root->fs_info->free_extent_hook = free_extent_hook;
8029 root->fs_info->corrupt_blocks = &corrupt_blocks;
8033 bits = malloc(bits_nr * sizeof(struct block_info));
8040 root1 = root->fs_info->tree_root;
8041 level = btrfs_header_level(root1->node);
8042 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
8043 root1->node->start, 0, level, 0,
8044 btrfs_level_size(root1, level), NULL);
8047 root1 = root->fs_info->chunk_root;
8048 level = btrfs_header_level(root1->node);
8049 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
8050 root1->node->start, 0, level, 0,
8051 btrfs_level_size(root1, level), NULL);
8054 btrfs_init_path(&path);
8057 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
8058 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
8063 leaf = path.nodes[0];
8064 slot = path.slots[0];
8065 if (slot >= btrfs_header_nritems(path.nodes[0])) {
8066 ret = btrfs_next_leaf(root, &path);
8069 leaf = path.nodes[0];
8070 slot = path.slots[0];
8072 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
8073 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
8074 unsigned long offset;
8077 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
8078 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
8079 last_snapshot = btrfs_root_last_snapshot(&ri);
8080 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
8081 level = btrfs_root_level(&ri);
8082 level_size = btrfs_level_size(root, level);
8083 ret = add_root_item_to_list(&normal_trees,
8085 btrfs_root_bytenr(&ri),
8086 last_snapshot, level,
8087 0, level_size, NULL);
8091 level = btrfs_root_level(&ri);
8092 level_size = btrfs_level_size(root, level);
8093 objectid = found_key.objectid;
8094 btrfs_disk_key_to_cpu(&found_key,
8096 ret = add_root_item_to_list(&dropping_trees,
8098 btrfs_root_bytenr(&ri),
8099 last_snapshot, level,
8101 level_size, &found_key);
8108 btrfs_release_path(&path);
8111 * check_block can return -EAGAIN if it fixes something, please keep
8112 * this in mind when dealing with return values from these functions, if
8113 * we get -EAGAIN we want to fall through and restart the loop.
8115 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8116 &seen, &reada, &nodes, &extent_cache,
8117 &chunk_cache, &dev_cache, &block_group_cache,
8124 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8125 &pending, &seen, &reada, &nodes,
8126 &extent_cache, &chunk_cache, &dev_cache,
8127 &block_group_cache, &dev_extent_cache);
8134 err = check_chunks(&chunk_cache, &block_group_cache,
8135 &dev_extent_cache, NULL, NULL, NULL, 0);
8143 ret = check_extent_refs(root, &extent_cache);
8150 err = check_devices(&dev_cache, &dev_extent_cache);
8156 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8157 extent_io_tree_cleanup(&excluded_extents);
8158 root->fs_info->fsck_extent_cache = NULL;
8159 root->fs_info->free_extent_hook = NULL;
8160 root->fs_info->corrupt_blocks = NULL;
8161 root->fs_info->excluded_extents = NULL;
8164 free_chunk_cache_tree(&chunk_cache);
8165 free_device_cache_tree(&dev_cache);
8166 free_block_group_tree(&block_group_cache);
8167 free_device_extent_tree(&dev_extent_cache);
8168 free_extent_cache_tree(&seen);
8169 free_extent_cache_tree(&pending);
8170 free_extent_cache_tree(&reada);
8171 free_extent_cache_tree(&nodes);
8174 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8175 free_extent_cache_tree(&seen);
8176 free_extent_cache_tree(&pending);
8177 free_extent_cache_tree(&reada);
8178 free_extent_cache_tree(&nodes);
8179 free_chunk_cache_tree(&chunk_cache);
8180 free_block_group_tree(&block_group_cache);
8181 free_device_cache_tree(&dev_cache);
8182 free_device_extent_tree(&dev_extent_cache);
8183 free_extent_record_cache(root->fs_info, &extent_cache);
8184 free_root_item_list(&normal_trees);
8185 free_root_item_list(&dropping_trees);
8186 extent_io_tree_cleanup(&excluded_extents);
8190 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8191 struct btrfs_root *root, int overwrite)
8193 struct extent_buffer *c;
8194 struct extent_buffer *old = root->node;
8197 struct btrfs_disk_key disk_key = {0,0,0};
8203 extent_buffer_get(c);
8206 c = btrfs_alloc_free_block(trans, root,
8207 btrfs_level_size(root, 0),
8208 root->root_key.objectid,
8209 &disk_key, level, 0, 0);
8212 extent_buffer_get(c);
8216 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8217 btrfs_set_header_level(c, level);
8218 btrfs_set_header_bytenr(c, c->start);
8219 btrfs_set_header_generation(c, trans->transid);
8220 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8221 btrfs_set_header_owner(c, root->root_key.objectid);
8223 write_extent_buffer(c, root->fs_info->fsid,
8224 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8226 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8227 btrfs_header_chunk_tree_uuid(c),
8230 btrfs_mark_buffer_dirty(c);
8232 * this case can happen in the following case:
8234 * 1.overwrite previous root.
8236 * 2.reinit reloc data root, this is because we skip pin
8237 * down reloc data tree before which means we can allocate
8238 * same block bytenr here.
8240 if (old->start == c->start) {
8241 btrfs_set_root_generation(&root->root_item,
8243 root->root_item.level = btrfs_header_level(root->node);
8244 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8245 &root->root_key, &root->root_item);
8247 free_extent_buffer(c);
8251 free_extent_buffer(old);
8253 add_root_to_dirty_list(root);
8257 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8258 struct extent_buffer *eb, int tree_root)
8260 struct extent_buffer *tmp;
8261 struct btrfs_root_item *ri;
8262 struct btrfs_key key;
8265 int level = btrfs_header_level(eb);
8271 * If we have pinned this block before, don't pin it again.
8272 * This can not only avoid forever loop with broken filesystem
8273 * but also give us some speedups.
8275 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8276 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8279 btrfs_pin_extent(fs_info, eb->start, eb->len);
8281 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8282 nritems = btrfs_header_nritems(eb);
8283 for (i = 0; i < nritems; i++) {
8285 btrfs_item_key_to_cpu(eb, &key, i);
8286 if (key.type != BTRFS_ROOT_ITEM_KEY)
8288 /* Skip the extent root and reloc roots */
8289 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8290 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8291 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8293 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8294 bytenr = btrfs_disk_root_bytenr(eb, ri);
8297 * If at any point we start needing the real root we
8298 * will have to build a stump root for the root we are
8299 * in, but for now this doesn't actually use the root so
8300 * just pass in extent_root.
8302 tmp = read_tree_block(fs_info->extent_root, bytenr,
8304 if (!extent_buffer_uptodate(tmp)) {
8305 fprintf(stderr, "Error reading root block\n");
8308 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8309 free_extent_buffer(tmp);
8313 bytenr = btrfs_node_blockptr(eb, i);
8315 /* If we aren't the tree root don't read the block */
8316 if (level == 1 && !tree_root) {
8317 btrfs_pin_extent(fs_info, bytenr, leafsize);
8321 tmp = read_tree_block(fs_info->extent_root, bytenr,
8323 if (!extent_buffer_uptodate(tmp)) {
8324 fprintf(stderr, "Error reading tree block\n");
8327 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8328 free_extent_buffer(tmp);
8337 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8341 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8345 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8348 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8350 struct btrfs_block_group_cache *cache;
8351 struct btrfs_path *path;
8352 struct extent_buffer *leaf;
8353 struct btrfs_chunk *chunk;
8354 struct btrfs_key key;
8358 path = btrfs_alloc_path();
8363 key.type = BTRFS_CHUNK_ITEM_KEY;
8366 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8368 btrfs_free_path(path);
8373 * We do this in case the block groups were screwed up and had alloc
8374 * bits that aren't actually set on the chunks. This happens with
8375 * restored images every time and could happen in real life I guess.
8377 fs_info->avail_data_alloc_bits = 0;
8378 fs_info->avail_metadata_alloc_bits = 0;
8379 fs_info->avail_system_alloc_bits = 0;
8381 /* First we need to create the in-memory block groups */
8383 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8384 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8386 btrfs_free_path(path);
8394 leaf = path->nodes[0];
8395 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8396 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8401 chunk = btrfs_item_ptr(leaf, path->slots[0],
8402 struct btrfs_chunk);
8403 btrfs_add_block_group(fs_info, 0,
8404 btrfs_chunk_type(leaf, chunk),
8405 key.objectid, key.offset,
8406 btrfs_chunk_length(leaf, chunk));
8407 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8408 key.offset + btrfs_chunk_length(leaf, chunk),
8414 cache = btrfs_lookup_first_block_group(fs_info, start);
8418 start = cache->key.objectid + cache->key.offset;
8421 btrfs_free_path(path);
8425 static int reset_balance(struct btrfs_trans_handle *trans,
8426 struct btrfs_fs_info *fs_info)
8428 struct btrfs_root *root = fs_info->tree_root;
8429 struct btrfs_path *path;
8430 struct extent_buffer *leaf;
8431 struct btrfs_key key;
8432 int del_slot, del_nr = 0;
8436 path = btrfs_alloc_path();
8440 key.objectid = BTRFS_BALANCE_OBJECTID;
8441 key.type = BTRFS_BALANCE_ITEM_KEY;
8444 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8449 goto reinit_data_reloc;
8454 ret = btrfs_del_item(trans, root, path);
8457 btrfs_release_path(path);
8459 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8460 key.type = BTRFS_ROOT_ITEM_KEY;
8463 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8467 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8472 ret = btrfs_del_items(trans, root, path,
8479 btrfs_release_path(path);
8482 ret = btrfs_search_slot(trans, root, &key, path,
8489 leaf = path->nodes[0];
8490 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8491 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8493 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8498 del_slot = path->slots[0];
8507 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8511 btrfs_release_path(path);
8514 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8515 key.type = BTRFS_ROOT_ITEM_KEY;
8516 key.offset = (u64)-1;
8517 root = btrfs_read_fs_root(fs_info, &key);
8519 fprintf(stderr, "Error reading data reloc tree\n");
8520 ret = PTR_ERR(root);
8523 record_root_in_trans(trans, root);
8524 ret = btrfs_fsck_reinit_root(trans, root, 0);
8527 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8529 btrfs_free_path(path);
8533 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8534 struct btrfs_fs_info *fs_info)
8540 * The only reason we don't do this is because right now we're just
8541 * walking the trees we find and pinning down their bytes, we don't look
8542 * at any of the leaves. In order to do mixed groups we'd have to check
8543 * the leaves of any fs roots and pin down the bytes for any file
8544 * extents we find. Not hard but why do it if we don't have to?
8546 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8547 fprintf(stderr, "We don't support re-initing the extent tree "
8548 "for mixed block groups yet, please notify a btrfs "
8549 "developer you want to do this so they can add this "
8550 "functionality.\n");
8555 * first we need to walk all of the trees except the extent tree and pin
8556 * down the bytes that are in use so we don't overwrite any existing
8559 ret = pin_metadata_blocks(fs_info);
8561 fprintf(stderr, "error pinning down used bytes\n");
8566 * Need to drop all the block groups since we're going to recreate all
8569 btrfs_free_block_groups(fs_info);
8570 ret = reset_block_groups(fs_info);
8572 fprintf(stderr, "error resetting the block groups\n");
8576 /* Ok we can allocate now, reinit the extent root */
8577 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8579 fprintf(stderr, "extent root initialization failed\n");
8581 * When the transaction code is updated we should end the
8582 * transaction, but for now progs only knows about commit so
8583 * just return an error.
8589 * Now we have all the in-memory block groups setup so we can make
8590 * allocations properly, and the metadata we care about is safe since we
8591 * pinned all of it above.
8594 struct btrfs_block_group_cache *cache;
8596 cache = btrfs_lookup_first_block_group(fs_info, start);
8599 start = cache->key.objectid + cache->key.offset;
8600 ret = btrfs_insert_item(trans, fs_info->extent_root,
8601 &cache->key, &cache->item,
8602 sizeof(cache->item));
8604 fprintf(stderr, "Error adding block group\n");
8607 btrfs_extent_post_op(trans, fs_info->extent_root);
8610 ret = reset_balance(trans, fs_info);
8612 fprintf(stderr, "error reseting the pending balance\n");
8617 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8619 struct btrfs_path *path;
8620 struct btrfs_trans_handle *trans;
8621 struct btrfs_key key;
8624 printf("Recowing metadata block %llu\n", eb->start);
8625 key.objectid = btrfs_header_owner(eb);
8626 key.type = BTRFS_ROOT_ITEM_KEY;
8627 key.offset = (u64)-1;
8629 root = btrfs_read_fs_root(root->fs_info, &key);
8631 fprintf(stderr, "Couldn't find owner root %llu\n",
8633 return PTR_ERR(root);
8636 path = btrfs_alloc_path();
8640 trans = btrfs_start_transaction(root, 1);
8641 if (IS_ERR(trans)) {
8642 btrfs_free_path(path);
8643 return PTR_ERR(trans);
8646 path->lowest_level = btrfs_header_level(eb);
8647 if (path->lowest_level)
8648 btrfs_node_key_to_cpu(eb, &key, 0);
8650 btrfs_item_key_to_cpu(eb, &key, 0);
8652 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8653 btrfs_commit_transaction(trans, root);
8654 btrfs_free_path(path);
8658 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8660 struct btrfs_path *path;
8661 struct btrfs_trans_handle *trans;
8662 struct btrfs_key key;
8665 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8666 bad->key.type, bad->key.offset);
8667 key.objectid = bad->root_id;
8668 key.type = BTRFS_ROOT_ITEM_KEY;
8669 key.offset = (u64)-1;
8671 root = btrfs_read_fs_root(root->fs_info, &key);
8673 fprintf(stderr, "Couldn't find owner root %llu\n",
8675 return PTR_ERR(root);
8678 path = btrfs_alloc_path();
8682 trans = btrfs_start_transaction(root, 1);
8683 if (IS_ERR(trans)) {
8684 btrfs_free_path(path);
8685 return PTR_ERR(trans);
8688 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8694 ret = btrfs_del_item(trans, root, path);
8696 btrfs_commit_transaction(trans, root);
8697 btrfs_free_path(path);
8701 static int zero_log_tree(struct btrfs_root *root)
8703 struct btrfs_trans_handle *trans;
8706 trans = btrfs_start_transaction(root, 1);
8707 if (IS_ERR(trans)) {
8708 ret = PTR_ERR(trans);
8711 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8712 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8713 ret = btrfs_commit_transaction(trans, root);
8717 static int populate_csum(struct btrfs_trans_handle *trans,
8718 struct btrfs_root *csum_root, char *buf, u64 start,
8725 while (offset < len) {
8726 sectorsize = csum_root->sectorsize;
8727 ret = read_extent_data(csum_root, buf, start + offset,
8731 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8732 start + offset, buf, sectorsize);
8735 offset += sectorsize;
8740 static int fill_csum_tree_from_one_fs_root(struct btrfs_trans_handle *trans,
8741 struct btrfs_root *csum_root,
8742 struct btrfs_root *cur_root)
8744 struct btrfs_path *path;
8745 struct btrfs_key key;
8746 struct extent_buffer *node;
8747 struct btrfs_file_extent_item *fi;
8754 path = btrfs_alloc_path();
8757 buf = malloc(cur_root->fs_info->csum_root->sectorsize);
8767 ret = btrfs_search_slot(NULL, cur_root, &key, path, 0, 0);
8770 /* Iterate all regular file extents and fill its csum */
8772 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
8774 if (key.type != BTRFS_EXTENT_DATA_KEY)
8776 node = path->nodes[0];
8777 slot = path->slots[0];
8778 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
8779 if (btrfs_file_extent_type(node, fi) != BTRFS_FILE_EXTENT_REG)
8781 start = btrfs_file_extent_disk_bytenr(node, fi);
8782 len = btrfs_file_extent_disk_num_bytes(node, fi);
8784 ret = populate_csum(trans, csum_root, buf, start, len);
8791 * TODO: if next leaf is corrupted, jump to nearest next valid
8794 ret = btrfs_next_item(cur_root, path);
8804 btrfs_free_path(path);
8809 static int fill_csum_tree_from_fs(struct btrfs_trans_handle *trans,
8810 struct btrfs_root *csum_root)
8812 struct btrfs_fs_info *fs_info = csum_root->fs_info;
8813 struct btrfs_path *path;
8814 struct btrfs_root *tree_root = fs_info->tree_root;
8815 struct btrfs_root *cur_root;
8816 struct extent_buffer *node;
8817 struct btrfs_key key;
8821 path = btrfs_alloc_path();
8825 key.objectid = BTRFS_FS_TREE_OBJECTID;
8827 key.type = BTRFS_ROOT_ITEM_KEY;
8829 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
8838 node = path->nodes[0];
8839 slot = path->slots[0];
8840 btrfs_item_key_to_cpu(node, &key, slot);
8841 if (key.objectid > BTRFS_LAST_FREE_OBJECTID)
8843 if (key.type != BTRFS_ROOT_ITEM_KEY)
8845 if (!is_fstree(key.objectid))
8847 key.offset = (u64)-1;
8849 cur_root = btrfs_read_fs_root(fs_info, &key);
8850 if (IS_ERR(cur_root) || !cur_root) {
8851 fprintf(stderr, "Fail to read fs/subvol tree: %lld\n",
8855 ret = fill_csum_tree_from_one_fs_root(trans, csum_root,
8860 ret = btrfs_next_item(tree_root, path);
8870 btrfs_free_path(path);
8874 static int fill_csum_tree_from_extent(struct btrfs_trans_handle *trans,
8875 struct btrfs_root *csum_root)
8877 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8878 struct btrfs_path *path;
8879 struct btrfs_extent_item *ei;
8880 struct extent_buffer *leaf;
8882 struct btrfs_key key;
8885 path = btrfs_alloc_path();
8890 key.type = BTRFS_EXTENT_ITEM_KEY;
8893 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8895 btrfs_free_path(path);
8899 buf = malloc(csum_root->sectorsize);
8901 btrfs_free_path(path);
8906 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8907 ret = btrfs_next_leaf(extent_root, path);
8915 leaf = path->nodes[0];
8917 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8918 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8923 ei = btrfs_item_ptr(leaf, path->slots[0],
8924 struct btrfs_extent_item);
8925 if (!(btrfs_extent_flags(leaf, ei) &
8926 BTRFS_EXTENT_FLAG_DATA)) {
8931 ret = populate_csum(trans, csum_root, buf, key.objectid,
8938 btrfs_free_path(path);
8944 * Recalculate the csum and put it into the csum tree.
8946 * Extent tree init will wipe out all the extent info, so in that case, we
8947 * can't depend on extent tree, but use fs tree. If search_fs_tree is set, we
8948 * will use fs/subvol trees to init the csum tree.
8950 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8951 struct btrfs_root *csum_root,
8955 return fill_csum_tree_from_fs(trans, csum_root);
8957 return fill_csum_tree_from_extent(trans, csum_root);
8960 struct root_item_info {
8961 /* level of the root */
8963 /* number of nodes at this level, must be 1 for a root */
8967 struct cache_extent cache_extent;
8970 static struct cache_tree *roots_info_cache = NULL;
8972 static void free_roots_info_cache(void)
8974 if (!roots_info_cache)
8977 while (!cache_tree_empty(roots_info_cache)) {
8978 struct cache_extent *entry;
8979 struct root_item_info *rii;
8981 entry = first_cache_extent(roots_info_cache);
8984 remove_cache_extent(roots_info_cache, entry);
8985 rii = container_of(entry, struct root_item_info, cache_extent);
8989 free(roots_info_cache);
8990 roots_info_cache = NULL;
8993 static int build_roots_info_cache(struct btrfs_fs_info *info)
8996 struct btrfs_key key;
8997 struct extent_buffer *leaf;
8998 struct btrfs_path *path;
9000 if (!roots_info_cache) {
9001 roots_info_cache = malloc(sizeof(*roots_info_cache));
9002 if (!roots_info_cache)
9004 cache_tree_init(roots_info_cache);
9007 path = btrfs_alloc_path();
9012 key.type = BTRFS_EXTENT_ITEM_KEY;
9015 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
9018 leaf = path->nodes[0];
9021 struct btrfs_key found_key;
9022 struct btrfs_extent_item *ei;
9023 struct btrfs_extent_inline_ref *iref;
9024 int slot = path->slots[0];
9029 struct cache_extent *entry;
9030 struct root_item_info *rii;
9032 if (slot >= btrfs_header_nritems(leaf)) {
9033 ret = btrfs_next_leaf(info->extent_root, path);
9040 leaf = path->nodes[0];
9041 slot = path->slots[0];
9044 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9046 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
9047 found_key.type != BTRFS_METADATA_ITEM_KEY)
9050 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
9051 flags = btrfs_extent_flags(leaf, ei);
9053 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
9054 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
9057 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
9058 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
9059 level = found_key.offset;
9061 struct btrfs_tree_block_info *info;
9063 info = (struct btrfs_tree_block_info *)(ei + 1);
9064 iref = (struct btrfs_extent_inline_ref *)(info + 1);
9065 level = btrfs_tree_block_level(leaf, info);
9069 * For a root extent, it must be of the following type and the
9070 * first (and only one) iref in the item.
9072 type = btrfs_extent_inline_ref_type(leaf, iref);
9073 if (type != BTRFS_TREE_BLOCK_REF_KEY)
9076 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
9077 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9079 rii = malloc(sizeof(struct root_item_info));
9084 rii->cache_extent.start = root_id;
9085 rii->cache_extent.size = 1;
9086 rii->level = (u8)-1;
9087 entry = &rii->cache_extent;
9088 ret = insert_cache_extent(roots_info_cache, entry);
9091 rii = container_of(entry, struct root_item_info,
9095 ASSERT(rii->cache_extent.start == root_id);
9096 ASSERT(rii->cache_extent.size == 1);
9098 if (level > rii->level || rii->level == (u8)-1) {
9100 rii->bytenr = found_key.objectid;
9101 rii->gen = btrfs_extent_generation(leaf, ei);
9102 rii->node_count = 1;
9103 } else if (level == rii->level) {
9111 btrfs_free_path(path);
9116 static int maybe_repair_root_item(struct btrfs_fs_info *info,
9117 struct btrfs_path *path,
9118 const struct btrfs_key *root_key,
9119 const int read_only_mode)
9121 const u64 root_id = root_key->objectid;
9122 struct cache_extent *entry;
9123 struct root_item_info *rii;
9124 struct btrfs_root_item ri;
9125 unsigned long offset;
9127 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9130 "Error: could not find extent items for root %llu\n",
9131 root_key->objectid);
9135 rii = container_of(entry, struct root_item_info, cache_extent);
9136 ASSERT(rii->cache_extent.start == root_id);
9137 ASSERT(rii->cache_extent.size == 1);
9139 if (rii->node_count != 1) {
9141 "Error: could not find btree root extent for root %llu\n",
9146 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
9147 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
9149 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
9150 btrfs_root_level(&ri) != rii->level ||
9151 btrfs_root_generation(&ri) != rii->gen) {
9154 * If we're in repair mode but our caller told us to not update
9155 * the root item, i.e. just check if it needs to be updated, don't
9156 * print this message, since the caller will call us again shortly
9157 * for the same root item without read only mode (the caller will
9158 * open a transaction first).
9160 if (!(read_only_mode && repair))
9162 "%sroot item for root %llu,"
9163 " current bytenr %llu, current gen %llu, current level %u,"
9164 " new bytenr %llu, new gen %llu, new level %u\n",
9165 (read_only_mode ? "" : "fixing "),
9167 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
9168 btrfs_root_level(&ri),
9169 rii->bytenr, rii->gen, rii->level);
9171 if (btrfs_root_generation(&ri) > rii->gen) {
9173 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
9174 root_id, btrfs_root_generation(&ri), rii->gen);
9178 if (!read_only_mode) {
9179 btrfs_set_root_bytenr(&ri, rii->bytenr);
9180 btrfs_set_root_level(&ri, rii->level);
9181 btrfs_set_root_generation(&ri, rii->gen);
9182 write_extent_buffer(path->nodes[0], &ri,
9183 offset, sizeof(ri));
9193 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
9194 * caused read-only snapshots to be corrupted if they were created at a moment
9195 * when the source subvolume/snapshot had orphan items. The issue was that the
9196 * on-disk root items became incorrect, referring to the pre orphan cleanup root
9197 * node instead of the post orphan cleanup root node.
9198 * So this function, and its callees, just detects and fixes those cases. Even
9199 * though the regression was for read-only snapshots, this function applies to
9200 * any snapshot/subvolume root.
9201 * This must be run before any other repair code - not doing it so, makes other
9202 * repair code delete or modify backrefs in the extent tree for example, which
9203 * will result in an inconsistent fs after repairing the root items.
9205 static int repair_root_items(struct btrfs_fs_info *info)
9207 struct btrfs_path *path = NULL;
9208 struct btrfs_key key;
9209 struct extent_buffer *leaf;
9210 struct btrfs_trans_handle *trans = NULL;
9215 ret = build_roots_info_cache(info);
9219 path = btrfs_alloc_path();
9225 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
9226 key.type = BTRFS_ROOT_ITEM_KEY;
9231 * Avoid opening and committing transactions if a leaf doesn't have
9232 * any root items that need to be fixed, so that we avoid rotating
9233 * backup roots unnecessarily.
9236 trans = btrfs_start_transaction(info->tree_root, 1);
9237 if (IS_ERR(trans)) {
9238 ret = PTR_ERR(trans);
9243 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
9247 leaf = path->nodes[0];
9250 struct btrfs_key found_key;
9252 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
9253 int no_more_keys = find_next_key(path, &key);
9255 btrfs_release_path(path);
9257 ret = btrfs_commit_transaction(trans,
9269 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9271 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
9273 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9276 ret = maybe_repair_root_item(info, path, &found_key,
9281 if (!trans && repair) {
9284 btrfs_release_path(path);
9294 free_roots_info_cache();
9295 btrfs_free_path(path);
9297 btrfs_commit_transaction(trans, info->tree_root);
9304 const char * const cmd_check_usage[] = {
9305 "btrfs check [options] <device>",
9306 "Check an unmounted btrfs filesystem.",
9308 "-s|--super <superblock> use this superblock copy",
9309 "-b|--backup use the backup root copy",
9310 "--repair try to repair the filesystem",
9311 "--init-csum-tree create a new CRC tree",
9312 "--init-extent-tree create a new extent tree",
9313 "--check-data-csum verify checkums of data blocks",
9314 "--qgroup-report print a report on qgroup consistency",
9315 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9316 "--tree-root <bytenr> use the given bytenr for the tree root",
9320 int cmd_check(int argc, char **argv)
9322 struct cache_tree root_cache;
9323 struct btrfs_root *root;
9324 struct btrfs_fs_info *info;
9327 u64 tree_root_bytenr = 0;
9328 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9331 int init_csum_tree = 0;
9333 int qgroup_report = 0;
9334 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9338 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9339 OPT_CHECK_CSUM, OPT_READONLY };
9340 static const struct option long_options[] = {
9341 { "super", required_argument, NULL, 's' },
9342 { "repair", no_argument, NULL, OPT_REPAIR },
9343 { "readonly", no_argument, NULL, OPT_READONLY },
9344 { "init-csum-tree", no_argument, NULL, OPT_INIT_CSUM },
9345 { "init-extent-tree", no_argument, NULL, OPT_INIT_EXTENT },
9346 { "check-data-csum", no_argument, NULL, OPT_CHECK_CSUM },
9347 { "backup", no_argument, NULL, 'b' },
9348 { "subvol-extents", required_argument, NULL, 'E' },
9349 { "qgroup-report", no_argument, NULL, 'Q' },
9350 { "tree-root", required_argument, NULL, 'r' },
9354 c = getopt_long(argc, argv, "as:br:", long_options, NULL);
9358 case 'a': /* ignored */ break;
9360 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9363 num = arg_strtou64(optarg);
9364 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9366 "ERROR: super mirror should be less than: %d\n",
9367 BTRFS_SUPER_MIRROR_MAX);
9370 bytenr = btrfs_sb_offset(((int)num));
9371 printf("using SB copy %llu, bytenr %llu\n", num,
9372 (unsigned long long)bytenr);
9378 subvolid = arg_strtou64(optarg);
9381 tree_root_bytenr = arg_strtou64(optarg);
9385 usage(cmd_check_usage);
9387 printf("enabling repair mode\n");
9389 ctree_flags |= OPEN_CTREE_WRITES;
9395 printf("Creating a new CRC tree\n");
9398 ctree_flags |= OPEN_CTREE_WRITES;
9400 case OPT_INIT_EXTENT:
9401 init_extent_tree = 1;
9402 ctree_flags |= (OPEN_CTREE_WRITES |
9403 OPEN_CTREE_NO_BLOCK_GROUPS);
9406 case OPT_CHECK_CSUM:
9407 check_data_csum = 1;
9411 argc = argc - optind;
9413 if (check_argc_exact(argc, 1))
9414 usage(cmd_check_usage);
9416 /* This check is the only reason for --readonly to exist */
9417 if (readonly && repair) {
9418 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9423 cache_tree_init(&root_cache);
9425 if((ret = check_mounted(argv[optind])) < 0) {
9426 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9429 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9434 /* only allow partial opening under repair mode */
9436 ctree_flags |= OPEN_CTREE_PARTIAL;
9438 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9441 fprintf(stderr, "Couldn't open file system\n");
9447 root = info->fs_root;
9450 * repair mode will force us to commit transaction which
9451 * will make us fail to load log tree when mounting.
9453 if (repair && btrfs_super_log_root(info->super_copy)) {
9454 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9459 ret = zero_log_tree(root);
9461 fprintf(stderr, "fail to zero log tree\n");
9466 uuid_unparse(info->super_copy->fsid, uuidbuf);
9467 if (qgroup_report) {
9468 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9470 ret = qgroup_verify_all(info);
9472 print_qgroup_report(1);
9476 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9477 subvolid, argv[optind], uuidbuf);
9478 ret = print_extent_state(info, subvolid);
9481 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9483 if (!extent_buffer_uptodate(info->tree_root->node) ||
9484 !extent_buffer_uptodate(info->dev_root->node) ||
9485 !extent_buffer_uptodate(info->chunk_root->node)) {
9486 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9491 if (init_extent_tree || init_csum_tree) {
9492 struct btrfs_trans_handle *trans;
9494 trans = btrfs_start_transaction(info->extent_root, 0);
9495 if (IS_ERR(trans)) {
9496 fprintf(stderr, "Error starting transaction\n");
9497 ret = PTR_ERR(trans);
9501 if (init_extent_tree) {
9502 printf("Creating a new extent tree\n");
9503 ret = reinit_extent_tree(trans, info);
9508 if (init_csum_tree) {
9509 fprintf(stderr, "Reinit crc root\n");
9510 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9512 fprintf(stderr, "crc root initialization failed\n");
9517 ret = fill_csum_tree(trans, info->csum_root,
9520 fprintf(stderr, "crc refilling failed\n");
9525 * Ok now we commit and run the normal fsck, which will add
9526 * extent entries for all of the items it finds.
9528 ret = btrfs_commit_transaction(trans, info->extent_root);
9532 if (!extent_buffer_uptodate(info->extent_root->node)) {
9533 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9537 if (!extent_buffer_uptodate(info->csum_root->node)) {
9538 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9543 fprintf(stderr, "checking extents\n");
9544 ret = check_chunks_and_extents(root);
9546 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9548 ret = repair_root_items(info);
9552 fprintf(stderr, "Fixed %d roots.\n", ret);
9554 } else if (ret > 0) {
9556 "Found %d roots with an outdated root item.\n",
9559 "Please run a filesystem check with the option --repair to fix them.\n");
9564 fprintf(stderr, "checking free space cache\n");
9565 ret = check_space_cache(root);
9570 * We used to have to have these hole extents in between our real
9571 * extents so if we don't have this flag set we need to make sure there
9572 * are no gaps in the file extents for inodes, otherwise we can just
9573 * ignore it when this happens.
9575 no_holes = btrfs_fs_incompat(root->fs_info,
9576 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9577 fprintf(stderr, "checking fs roots\n");
9578 ret = check_fs_roots(root, &root_cache);
9582 fprintf(stderr, "checking csums\n");
9583 ret = check_csums(root);
9587 fprintf(stderr, "checking root refs\n");
9588 ret = check_root_refs(root, &root_cache);
9592 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9593 struct extent_buffer *eb;
9595 eb = list_first_entry(&root->fs_info->recow_ebs,
9596 struct extent_buffer, recow);
9597 list_del_init(&eb->recow);
9598 ret = recow_extent_buffer(root, eb);
9603 while (!list_empty(&delete_items)) {
9604 struct bad_item *bad;
9606 bad = list_first_entry(&delete_items, struct bad_item, list);
9607 list_del_init(&bad->list);
9609 ret = delete_bad_item(root, bad);
9613 if (info->quota_enabled) {
9615 fprintf(stderr, "checking quota groups\n");
9616 err = qgroup_verify_all(info);
9621 if (!list_empty(&root->fs_info->recow_ebs)) {
9622 fprintf(stderr, "Transid errors in file system\n");
9626 print_qgroup_report(0);
9627 if (found_old_backref) { /*
9628 * there was a disk format change when mixed
9629 * backref was in testing tree. The old format
9630 * existed about one week.
9632 printf("\n * Found old mixed backref format. "
9633 "The old format is not supported! *"
9634 "\n * Please mount the FS in readonly mode, "
9635 "backup data and re-format the FS. *\n\n");
9638 printf("found %llu bytes used err is %d\n",
9639 (unsigned long long)bytes_used, ret);
9640 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9641 printf("total tree bytes: %llu\n",
9642 (unsigned long long)total_btree_bytes);
9643 printf("total fs tree bytes: %llu\n",
9644 (unsigned long long)total_fs_tree_bytes);
9645 printf("total extent tree bytes: %llu\n",
9646 (unsigned long long)total_extent_tree_bytes);
9647 printf("btree space waste bytes: %llu\n",
9648 (unsigned long long)btree_space_waste);
9649 printf("file data blocks allocated: %llu\n referenced %llu\n",
9650 (unsigned long long)data_bytes_allocated,
9651 (unsigned long long)data_bytes_referenced);
9652 printf("%s\n", PACKAGE_STRING);
9654 free_root_recs_tree(&root_cache);
9657 btrfs_close_all_devices();