2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
23 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include "print-tree.h"
33 #include "transaction.h"
36 #include "free-space-cache.h"
38 #include "qgroup-verify.h"
39 #include "rbtree-utils.h"
43 static u64 bytes_used = 0;
44 static u64 total_csum_bytes = 0;
45 static u64 total_btree_bytes = 0;
46 static u64 total_fs_tree_bytes = 0;
47 static u64 total_extent_tree_bytes = 0;
48 static u64 btree_space_waste = 0;
49 static u64 data_bytes_allocated = 0;
50 static u64 data_bytes_referenced = 0;
51 static int found_old_backref = 0;
52 static LIST_HEAD(duplicate_extents);
53 static LIST_HEAD(delete_items);
54 static int repair = 0;
55 static int no_holes = 0;
56 static int init_extent_tree = 0;
57 static int check_data_csum = 0;
59 struct extent_backref {
60 struct list_head list;
61 unsigned int is_data:1;
62 unsigned int found_extent_tree:1;
63 unsigned int full_backref:1;
64 unsigned int found_ref:1;
65 unsigned int broken:1;
69 struct extent_backref node;
84 * Much like data_backref, just removed the undetermined members
85 * and change it to use list_head.
86 * During extent scan, it is stored in root->orphan_data_extent.
87 * During fs tree scan, it is then moved to inode_rec->orphan_data_extents.
89 struct orphan_data_extent {
90 struct list_head list;
99 struct extent_backref node;
106 struct extent_record {
107 struct list_head backrefs;
108 struct list_head dups;
109 struct list_head list;
110 struct cache_extent cache;
111 struct btrfs_disk_key parent_key;
116 u64 extent_item_refs;
118 u64 parent_generation;
122 int flag_block_full_backref;
123 unsigned int found_rec:1;
124 unsigned int content_checked:1;
125 unsigned int owner_ref_checked:1;
126 unsigned int is_root:1;
127 unsigned int metadata:1;
128 unsigned int bad_full_backref:1;
129 unsigned int crossing_stripes:1;
132 struct inode_backref {
133 struct list_head list;
134 unsigned int found_dir_item:1;
135 unsigned int found_dir_index:1;
136 unsigned int found_inode_ref:1;
137 unsigned int filetype:8;
139 unsigned int ref_type;
146 struct root_item_record {
147 struct list_head list;
154 struct btrfs_key drop_key;
157 #define REF_ERR_NO_DIR_ITEM (1 << 0)
158 #define REF_ERR_NO_DIR_INDEX (1 << 1)
159 #define REF_ERR_NO_INODE_REF (1 << 2)
160 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
161 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
162 #define REF_ERR_DUP_INODE_REF (1 << 5)
163 #define REF_ERR_INDEX_UNMATCH (1 << 6)
164 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
165 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
166 #define REF_ERR_NO_ROOT_REF (1 << 9)
167 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
168 #define REF_ERR_DUP_ROOT_REF (1 << 11)
169 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
171 struct file_extent_hole {
177 /* Compatible function to allow reuse of old codes */
178 static u64 first_extent_gap(struct rb_root *holes)
180 struct file_extent_hole *hole;
182 if (RB_EMPTY_ROOT(holes))
185 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
189 int compare_hole(struct rb_node *node1, struct rb_node *node2)
191 struct file_extent_hole *hole1;
192 struct file_extent_hole *hole2;
194 hole1 = rb_entry(node1, struct file_extent_hole, node);
195 hole2 = rb_entry(node2, struct file_extent_hole, node);
197 if (hole1->start > hole2->start)
199 if (hole1->start < hole2->start)
201 /* Now hole1->start == hole2->start */
202 if (hole1->len >= hole2->len)
204 * Hole 1 will be merge center
205 * Same hole will be merged later
208 /* Hole 2 will be merge center */
213 * Add a hole to the record
215 * This will do hole merge for copy_file_extent_holes(),
216 * which will ensure there won't be continuous holes.
218 static int add_file_extent_hole(struct rb_root *holes,
221 struct file_extent_hole *hole;
222 struct file_extent_hole *prev = NULL;
223 struct file_extent_hole *next = NULL;
225 hole = malloc(sizeof(*hole));
230 /* Since compare will not return 0, no -EEXIST will happen */
231 rb_insert(holes, &hole->node, compare_hole);
233 /* simple merge with previous hole */
234 if (rb_prev(&hole->node))
235 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
237 if (prev && prev->start + prev->len >= hole->start) {
238 hole->len = hole->start + hole->len - prev->start;
239 hole->start = prev->start;
240 rb_erase(&prev->node, holes);
245 /* iterate merge with next holes */
247 if (!rb_next(&hole->node))
249 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
251 if (hole->start + hole->len >= next->start) {
252 if (hole->start + hole->len <= next->start + next->len)
253 hole->len = next->start + next->len -
255 rb_erase(&next->node, holes);
264 static int compare_hole_range(struct rb_node *node, void *data)
266 struct file_extent_hole *hole;
269 hole = (struct file_extent_hole *)data;
272 hole = rb_entry(node, struct file_extent_hole, node);
273 if (start < hole->start)
275 if (start >= hole->start && start < hole->start + hole->len)
281 * Delete a hole in the record
283 * This will do the hole split and is much restrict than add.
285 static int del_file_extent_hole(struct rb_root *holes,
288 struct file_extent_hole *hole;
289 struct file_extent_hole tmp;
294 struct rb_node *node;
301 node = rb_search(holes, &tmp, compare_hole_range, NULL);
304 hole = rb_entry(node, struct file_extent_hole, node);
305 if (start + len > hole->start + hole->len)
309 * Now there will be no overflap, delete the hole and re-add the
310 * split(s) if they exists.
312 if (start > hole->start) {
313 prev_start = hole->start;
314 prev_len = start - hole->start;
317 if (hole->start + hole->len > start + len) {
318 next_start = start + len;
319 next_len = hole->start + hole->len - start - len;
322 rb_erase(node, holes);
325 ret = add_file_extent_hole(holes, prev_start, prev_len);
330 ret = add_file_extent_hole(holes, next_start, next_len);
337 static int copy_file_extent_holes(struct rb_root *dst,
340 struct file_extent_hole *hole;
341 struct rb_node *node;
344 node = rb_first(src);
346 hole = rb_entry(node, struct file_extent_hole, node);
347 ret = add_file_extent_hole(dst, hole->start, hole->len);
350 node = rb_next(node);
355 static void free_file_extent_holes(struct rb_root *holes)
357 struct rb_node *node;
358 struct file_extent_hole *hole;
360 node = rb_first(holes);
362 hole = rb_entry(node, struct file_extent_hole, node);
363 rb_erase(node, holes);
365 node = rb_first(holes);
369 struct inode_record {
370 struct list_head backrefs;
371 unsigned int checked:1;
372 unsigned int merging:1;
373 unsigned int found_inode_item:1;
374 unsigned int found_dir_item:1;
375 unsigned int found_file_extent:1;
376 unsigned int found_csum_item:1;
377 unsigned int some_csum_missing:1;
378 unsigned int nodatasum:1;
391 struct rb_root holes;
392 struct list_head orphan_extents;
397 #define I_ERR_NO_INODE_ITEM (1 << 0)
398 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
399 #define I_ERR_DUP_INODE_ITEM (1 << 2)
400 #define I_ERR_DUP_DIR_INDEX (1 << 3)
401 #define I_ERR_ODD_DIR_ITEM (1 << 4)
402 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
403 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
404 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
405 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
406 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
407 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
408 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
409 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
410 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
411 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
413 struct root_backref {
414 struct list_head list;
415 unsigned int found_dir_item:1;
416 unsigned int found_dir_index:1;
417 unsigned int found_back_ref:1;
418 unsigned int found_forward_ref:1;
419 unsigned int reachable:1;
429 struct list_head backrefs;
430 struct cache_extent cache;
431 unsigned int found_root_item:1;
437 struct cache_extent cache;
442 struct cache_extent cache;
443 struct cache_tree root_cache;
444 struct cache_tree inode_cache;
445 struct inode_record *current;
454 struct walk_control {
455 struct cache_tree shared;
456 struct shared_node *nodes[BTRFS_MAX_LEVEL];
462 struct btrfs_key key;
464 struct list_head list;
467 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
469 static void record_root_in_trans(struct btrfs_trans_handle *trans,
470 struct btrfs_root *root)
472 if (root->last_trans != trans->transid) {
473 root->track_dirty = 1;
474 root->last_trans = trans->transid;
475 root->commit_root = root->node;
476 extent_buffer_get(root->node);
480 static u8 imode_to_type(u32 imode)
483 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
484 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
485 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
486 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
487 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
488 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
489 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
490 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
493 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
497 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
499 struct device_record *rec1;
500 struct device_record *rec2;
502 rec1 = rb_entry(node1, struct device_record, node);
503 rec2 = rb_entry(node2, struct device_record, node);
504 if (rec1->devid > rec2->devid)
506 else if (rec1->devid < rec2->devid)
512 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
514 struct inode_record *rec;
515 struct inode_backref *backref;
516 struct inode_backref *orig;
517 struct orphan_data_extent *src_orphan;
518 struct orphan_data_extent *dst_orphan;
522 rec = malloc(sizeof(*rec));
523 memcpy(rec, orig_rec, sizeof(*rec));
525 INIT_LIST_HEAD(&rec->backrefs);
526 INIT_LIST_HEAD(&rec->orphan_extents);
527 rec->holes = RB_ROOT;
529 list_for_each_entry(orig, &orig_rec->backrefs, list) {
530 size = sizeof(*orig) + orig->namelen + 1;
531 backref = malloc(size);
532 memcpy(backref, orig, size);
533 list_add_tail(&backref->list, &rec->backrefs);
535 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
536 dst_orphan = malloc(sizeof(*dst_orphan));
537 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
539 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
540 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
542 ret = copy_file_extent_holes(&rec->holes, &orig_rec->holes);
548 static void print_orphan_data_extents(struct list_head *orphan_extents,
551 struct orphan_data_extent *orphan;
553 if (list_empty(orphan_extents))
555 printf("The following data extent is lost in tree %llu:\n",
557 list_for_each_entry(orphan, orphan_extents, list) {
558 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
559 orphan->objectid, orphan->offset, orphan->disk_bytenr,
564 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
566 u64 root_objectid = root->root_key.objectid;
567 int errors = rec->errors;
571 /* reloc root errors, we print its corresponding fs root objectid*/
572 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
573 root_objectid = root->root_key.offset;
574 fprintf(stderr, "reloc");
576 fprintf(stderr, "root %llu inode %llu errors %x",
577 (unsigned long long) root_objectid,
578 (unsigned long long) rec->ino, rec->errors);
580 if (errors & I_ERR_NO_INODE_ITEM)
581 fprintf(stderr, ", no inode item");
582 if (errors & I_ERR_NO_ORPHAN_ITEM)
583 fprintf(stderr, ", no orphan item");
584 if (errors & I_ERR_DUP_INODE_ITEM)
585 fprintf(stderr, ", dup inode item");
586 if (errors & I_ERR_DUP_DIR_INDEX)
587 fprintf(stderr, ", dup dir index");
588 if (errors & I_ERR_ODD_DIR_ITEM)
589 fprintf(stderr, ", odd dir item");
590 if (errors & I_ERR_ODD_FILE_EXTENT)
591 fprintf(stderr, ", odd file extent");
592 if (errors & I_ERR_BAD_FILE_EXTENT)
593 fprintf(stderr, ", bad file extent");
594 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
595 fprintf(stderr, ", file extent overlap");
596 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
597 fprintf(stderr, ", file extent discount");
598 if (errors & I_ERR_DIR_ISIZE_WRONG)
599 fprintf(stderr, ", dir isize wrong");
600 if (errors & I_ERR_FILE_NBYTES_WRONG)
601 fprintf(stderr, ", nbytes wrong");
602 if (errors & I_ERR_ODD_CSUM_ITEM)
603 fprintf(stderr, ", odd csum item");
604 if (errors & I_ERR_SOME_CSUM_MISSING)
605 fprintf(stderr, ", some csum missing");
606 if (errors & I_ERR_LINK_COUNT_WRONG)
607 fprintf(stderr, ", link count wrong");
608 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
609 fprintf(stderr, ", orphan file extent");
610 fprintf(stderr, "\n");
611 /* Print the orphan extents if needed */
612 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
613 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
615 /* Print the holes if needed */
616 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
617 struct file_extent_hole *hole;
618 struct rb_node *node;
621 node = rb_first(&rec->holes);
622 fprintf(stderr, "Found file extent holes:\n");
625 hole = rb_entry(node, struct file_extent_hole, node);
626 fprintf(stderr, "\tstart: %llu, len: %llu\n",
627 hole->start, hole->len);
628 node = rb_next(node);
631 fprintf(stderr, "\tstart: 0, len: %llu\n",
632 round_up(rec->isize, root->sectorsize));
636 static void print_ref_error(int errors)
638 if (errors & REF_ERR_NO_DIR_ITEM)
639 fprintf(stderr, ", no dir item");
640 if (errors & REF_ERR_NO_DIR_INDEX)
641 fprintf(stderr, ", no dir index");
642 if (errors & REF_ERR_NO_INODE_REF)
643 fprintf(stderr, ", no inode ref");
644 if (errors & REF_ERR_DUP_DIR_ITEM)
645 fprintf(stderr, ", dup dir item");
646 if (errors & REF_ERR_DUP_DIR_INDEX)
647 fprintf(stderr, ", dup dir index");
648 if (errors & REF_ERR_DUP_INODE_REF)
649 fprintf(stderr, ", dup inode ref");
650 if (errors & REF_ERR_INDEX_UNMATCH)
651 fprintf(stderr, ", index unmatch");
652 if (errors & REF_ERR_FILETYPE_UNMATCH)
653 fprintf(stderr, ", filetype unmatch");
654 if (errors & REF_ERR_NAME_TOO_LONG)
655 fprintf(stderr, ", name too long");
656 if (errors & REF_ERR_NO_ROOT_REF)
657 fprintf(stderr, ", no root ref");
658 if (errors & REF_ERR_NO_ROOT_BACKREF)
659 fprintf(stderr, ", no root backref");
660 if (errors & REF_ERR_DUP_ROOT_REF)
661 fprintf(stderr, ", dup root ref");
662 if (errors & REF_ERR_DUP_ROOT_BACKREF)
663 fprintf(stderr, ", dup root backref");
664 fprintf(stderr, "\n");
667 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
670 struct ptr_node *node;
671 struct cache_extent *cache;
672 struct inode_record *rec = NULL;
675 cache = lookup_cache_extent(inode_cache, ino, 1);
677 node = container_of(cache, struct ptr_node, cache);
679 if (mod && rec->refs > 1) {
680 node->data = clone_inode_rec(rec);
685 rec = calloc(1, sizeof(*rec));
687 rec->extent_start = (u64)-1;
689 INIT_LIST_HEAD(&rec->backrefs);
690 INIT_LIST_HEAD(&rec->orphan_extents);
691 rec->holes = RB_ROOT;
693 node = malloc(sizeof(*node));
694 node->cache.start = ino;
695 node->cache.size = 1;
698 if (ino == BTRFS_FREE_INO_OBJECTID)
701 ret = insert_cache_extent(inode_cache, &node->cache);
707 static void free_orphan_data_extents(struct list_head *orphan_extents)
709 struct orphan_data_extent *orphan;
711 while (!list_empty(orphan_extents)) {
712 orphan = list_entry(orphan_extents->next,
713 struct orphan_data_extent, list);
714 list_del(&orphan->list);
719 static void free_inode_rec(struct inode_record *rec)
721 struct inode_backref *backref;
726 while (!list_empty(&rec->backrefs)) {
727 backref = list_entry(rec->backrefs.next,
728 struct inode_backref, list);
729 list_del(&backref->list);
732 free_orphan_data_extents(&rec->orphan_extents);
733 free_file_extent_holes(&rec->holes);
737 static int can_free_inode_rec(struct inode_record *rec)
739 if (!rec->errors && rec->checked && rec->found_inode_item &&
740 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
745 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
746 struct inode_record *rec)
748 struct cache_extent *cache;
749 struct inode_backref *tmp, *backref;
750 struct ptr_node *node;
751 unsigned char filetype;
753 if (!rec->found_inode_item)
756 filetype = imode_to_type(rec->imode);
757 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
758 if (backref->found_dir_item && backref->found_dir_index) {
759 if (backref->filetype != filetype)
760 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
761 if (!backref->errors && backref->found_inode_ref) {
762 list_del(&backref->list);
768 if (!rec->checked || rec->merging)
771 if (S_ISDIR(rec->imode)) {
772 if (rec->found_size != rec->isize)
773 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
774 if (rec->found_file_extent)
775 rec->errors |= I_ERR_ODD_FILE_EXTENT;
776 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
777 if (rec->found_dir_item)
778 rec->errors |= I_ERR_ODD_DIR_ITEM;
779 if (rec->found_size != rec->nbytes)
780 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
781 if (rec->nlink > 0 && !no_holes &&
782 (rec->extent_end < rec->isize ||
783 first_extent_gap(&rec->holes) < rec->isize))
784 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
787 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
788 if (rec->found_csum_item && rec->nodatasum)
789 rec->errors |= I_ERR_ODD_CSUM_ITEM;
790 if (rec->some_csum_missing && !rec->nodatasum)
791 rec->errors |= I_ERR_SOME_CSUM_MISSING;
794 BUG_ON(rec->refs != 1);
795 if (can_free_inode_rec(rec)) {
796 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
797 node = container_of(cache, struct ptr_node, cache);
798 BUG_ON(node->data != rec);
799 remove_cache_extent(inode_cache, &node->cache);
805 static int check_orphan_item(struct btrfs_root *root, u64 ino)
807 struct btrfs_path path;
808 struct btrfs_key key;
811 key.objectid = BTRFS_ORPHAN_OBJECTID;
812 key.type = BTRFS_ORPHAN_ITEM_KEY;
815 btrfs_init_path(&path);
816 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
817 btrfs_release_path(&path);
823 static int process_inode_item(struct extent_buffer *eb,
824 int slot, struct btrfs_key *key,
825 struct shared_node *active_node)
827 struct inode_record *rec;
828 struct btrfs_inode_item *item;
830 rec = active_node->current;
831 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
832 if (rec->found_inode_item) {
833 rec->errors |= I_ERR_DUP_INODE_ITEM;
836 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
837 rec->nlink = btrfs_inode_nlink(eb, item);
838 rec->isize = btrfs_inode_size(eb, item);
839 rec->nbytes = btrfs_inode_nbytes(eb, item);
840 rec->imode = btrfs_inode_mode(eb, item);
841 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
843 rec->found_inode_item = 1;
845 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
846 maybe_free_inode_rec(&active_node->inode_cache, rec);
850 static struct inode_backref *get_inode_backref(struct inode_record *rec,
852 int namelen, u64 dir)
854 struct inode_backref *backref;
856 list_for_each_entry(backref, &rec->backrefs, list) {
857 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
859 if (backref->dir != dir || backref->namelen != namelen)
861 if (memcmp(name, backref->name, namelen))
866 backref = malloc(sizeof(*backref) + namelen + 1);
867 memset(backref, 0, sizeof(*backref));
869 backref->namelen = namelen;
870 memcpy(backref->name, name, namelen);
871 backref->name[namelen] = '\0';
872 list_add_tail(&backref->list, &rec->backrefs);
876 static int add_inode_backref(struct cache_tree *inode_cache,
877 u64 ino, u64 dir, u64 index,
878 const char *name, int namelen,
879 int filetype, int itemtype, int errors)
881 struct inode_record *rec;
882 struct inode_backref *backref;
884 rec = get_inode_rec(inode_cache, ino, 1);
885 backref = get_inode_backref(rec, name, namelen, dir);
887 backref->errors |= errors;
888 if (itemtype == BTRFS_DIR_INDEX_KEY) {
889 if (backref->found_dir_index)
890 backref->errors |= REF_ERR_DUP_DIR_INDEX;
891 if (backref->found_inode_ref && backref->index != index)
892 backref->errors |= REF_ERR_INDEX_UNMATCH;
893 if (backref->found_dir_item && backref->filetype != filetype)
894 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
896 backref->index = index;
897 backref->filetype = filetype;
898 backref->found_dir_index = 1;
899 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
901 if (backref->found_dir_item)
902 backref->errors |= REF_ERR_DUP_DIR_ITEM;
903 if (backref->found_dir_index && backref->filetype != filetype)
904 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
906 backref->filetype = filetype;
907 backref->found_dir_item = 1;
908 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
909 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
910 if (backref->found_inode_ref)
911 backref->errors |= REF_ERR_DUP_INODE_REF;
912 if (backref->found_dir_index && backref->index != index)
913 backref->errors |= REF_ERR_INDEX_UNMATCH;
915 backref->index = index;
917 backref->ref_type = itemtype;
918 backref->found_inode_ref = 1;
923 maybe_free_inode_rec(inode_cache, rec);
927 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
928 struct cache_tree *dst_cache)
930 struct inode_backref *backref;
935 list_for_each_entry(backref, &src->backrefs, list) {
936 if (backref->found_dir_index) {
937 add_inode_backref(dst_cache, dst->ino, backref->dir,
938 backref->index, backref->name,
939 backref->namelen, backref->filetype,
940 BTRFS_DIR_INDEX_KEY, backref->errors);
942 if (backref->found_dir_item) {
944 add_inode_backref(dst_cache, dst->ino,
945 backref->dir, 0, backref->name,
946 backref->namelen, backref->filetype,
947 BTRFS_DIR_ITEM_KEY, backref->errors);
949 if (backref->found_inode_ref) {
950 add_inode_backref(dst_cache, dst->ino,
951 backref->dir, backref->index,
952 backref->name, backref->namelen, 0,
953 backref->ref_type, backref->errors);
957 if (src->found_dir_item)
958 dst->found_dir_item = 1;
959 if (src->found_file_extent)
960 dst->found_file_extent = 1;
961 if (src->found_csum_item)
962 dst->found_csum_item = 1;
963 if (src->some_csum_missing)
964 dst->some_csum_missing = 1;
965 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
966 ret = copy_file_extent_holes(&dst->holes, &src->holes);
971 BUG_ON(src->found_link < dir_count);
972 dst->found_link += src->found_link - dir_count;
973 dst->found_size += src->found_size;
974 if (src->extent_start != (u64)-1) {
975 if (dst->extent_start == (u64)-1) {
976 dst->extent_start = src->extent_start;
977 dst->extent_end = src->extent_end;
979 if (dst->extent_end > src->extent_start)
980 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
981 else if (dst->extent_end < src->extent_start) {
982 ret = add_file_extent_hole(&dst->holes,
984 src->extent_start - dst->extent_end);
986 if (dst->extent_end < src->extent_end)
987 dst->extent_end = src->extent_end;
991 dst->errors |= src->errors;
992 if (src->found_inode_item) {
993 if (!dst->found_inode_item) {
994 dst->nlink = src->nlink;
995 dst->isize = src->isize;
996 dst->nbytes = src->nbytes;
997 dst->imode = src->imode;
998 dst->nodatasum = src->nodatasum;
999 dst->found_inode_item = 1;
1001 dst->errors |= I_ERR_DUP_INODE_ITEM;
1009 static int splice_shared_node(struct shared_node *src_node,
1010 struct shared_node *dst_node)
1012 struct cache_extent *cache;
1013 struct ptr_node *node, *ins;
1014 struct cache_tree *src, *dst;
1015 struct inode_record *rec, *conflict;
1016 u64 current_ino = 0;
1020 if (--src_node->refs == 0)
1022 if (src_node->current)
1023 current_ino = src_node->current->ino;
1025 src = &src_node->root_cache;
1026 dst = &dst_node->root_cache;
1028 cache = search_cache_extent(src, 0);
1030 node = container_of(cache, struct ptr_node, cache);
1032 cache = next_cache_extent(cache);
1035 remove_cache_extent(src, &node->cache);
1038 ins = malloc(sizeof(*ins));
1039 ins->cache.start = node->cache.start;
1040 ins->cache.size = node->cache.size;
1044 ret = insert_cache_extent(dst, &ins->cache);
1045 if (ret == -EEXIST) {
1046 conflict = get_inode_rec(dst, rec->ino, 1);
1047 merge_inode_recs(rec, conflict, dst);
1049 conflict->checked = 1;
1050 if (dst_node->current == conflict)
1051 dst_node->current = NULL;
1053 maybe_free_inode_rec(dst, conflict);
1054 free_inode_rec(rec);
1061 if (src == &src_node->root_cache) {
1062 src = &src_node->inode_cache;
1063 dst = &dst_node->inode_cache;
1067 if (current_ino > 0 && (!dst_node->current ||
1068 current_ino > dst_node->current->ino)) {
1069 if (dst_node->current) {
1070 dst_node->current->checked = 1;
1071 maybe_free_inode_rec(dst, dst_node->current);
1073 dst_node->current = get_inode_rec(dst, current_ino, 1);
1078 static void free_inode_ptr(struct cache_extent *cache)
1080 struct ptr_node *node;
1081 struct inode_record *rec;
1083 node = container_of(cache, struct ptr_node, cache);
1085 free_inode_rec(rec);
1089 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1091 static struct shared_node *find_shared_node(struct cache_tree *shared,
1094 struct cache_extent *cache;
1095 struct shared_node *node;
1097 cache = lookup_cache_extent(shared, bytenr, 1);
1099 node = container_of(cache, struct shared_node, cache);
1105 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1108 struct shared_node *node;
1110 node = calloc(1, sizeof(*node));
1111 node->cache.start = bytenr;
1112 node->cache.size = 1;
1113 cache_tree_init(&node->root_cache);
1114 cache_tree_init(&node->inode_cache);
1117 ret = insert_cache_extent(shared, &node->cache);
1122 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1123 struct walk_control *wc, int level)
1125 struct shared_node *node;
1126 struct shared_node *dest;
1128 if (level == wc->active_node)
1131 BUG_ON(wc->active_node <= level);
1132 node = find_shared_node(&wc->shared, bytenr);
1134 add_shared_node(&wc->shared, bytenr, refs);
1135 node = find_shared_node(&wc->shared, bytenr);
1136 wc->nodes[level] = node;
1137 wc->active_node = level;
1141 if (wc->root_level == wc->active_node &&
1142 btrfs_root_refs(&root->root_item) == 0) {
1143 if (--node->refs == 0) {
1144 free_inode_recs_tree(&node->root_cache);
1145 free_inode_recs_tree(&node->inode_cache);
1146 remove_cache_extent(&wc->shared, &node->cache);
1152 dest = wc->nodes[wc->active_node];
1153 splice_shared_node(node, dest);
1154 if (node->refs == 0) {
1155 remove_cache_extent(&wc->shared, &node->cache);
1161 static int leave_shared_node(struct btrfs_root *root,
1162 struct walk_control *wc, int level)
1164 struct shared_node *node;
1165 struct shared_node *dest;
1168 if (level == wc->root_level)
1171 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1175 BUG_ON(i >= BTRFS_MAX_LEVEL);
1177 node = wc->nodes[wc->active_node];
1178 wc->nodes[wc->active_node] = NULL;
1179 wc->active_node = i;
1181 dest = wc->nodes[wc->active_node];
1182 if (wc->active_node < wc->root_level ||
1183 btrfs_root_refs(&root->root_item) > 0) {
1184 BUG_ON(node->refs <= 1);
1185 splice_shared_node(node, dest);
1187 BUG_ON(node->refs < 2);
1196 * 1 - if the root with id child_root_id is a child of root parent_root_id
1197 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1198 * has other root(s) as parent(s)
1199 * 2 - if the root child_root_id doesn't have any parent roots
1201 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1204 struct btrfs_path path;
1205 struct btrfs_key key;
1206 struct extent_buffer *leaf;
1210 btrfs_init_path(&path);
1212 key.objectid = parent_root_id;
1213 key.type = BTRFS_ROOT_REF_KEY;
1214 key.offset = child_root_id;
1215 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1219 btrfs_release_path(&path);
1223 key.objectid = child_root_id;
1224 key.type = BTRFS_ROOT_BACKREF_KEY;
1226 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1232 leaf = path.nodes[0];
1233 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1234 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1237 leaf = path.nodes[0];
1240 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1241 if (key.objectid != child_root_id ||
1242 key.type != BTRFS_ROOT_BACKREF_KEY)
1247 if (key.offset == parent_root_id) {
1248 btrfs_release_path(&path);
1255 btrfs_release_path(&path);
1258 return has_parent ? 0 : 2;
1261 static int process_dir_item(struct btrfs_root *root,
1262 struct extent_buffer *eb,
1263 int slot, struct btrfs_key *key,
1264 struct shared_node *active_node)
1274 struct btrfs_dir_item *di;
1275 struct inode_record *rec;
1276 struct cache_tree *root_cache;
1277 struct cache_tree *inode_cache;
1278 struct btrfs_key location;
1279 char namebuf[BTRFS_NAME_LEN];
1281 root_cache = &active_node->root_cache;
1282 inode_cache = &active_node->inode_cache;
1283 rec = active_node->current;
1284 rec->found_dir_item = 1;
1286 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1287 total = btrfs_item_size_nr(eb, slot);
1288 while (cur < total) {
1290 btrfs_dir_item_key_to_cpu(eb, di, &location);
1291 name_len = btrfs_dir_name_len(eb, di);
1292 data_len = btrfs_dir_data_len(eb, di);
1293 filetype = btrfs_dir_type(eb, di);
1295 rec->found_size += name_len;
1296 if (name_len <= BTRFS_NAME_LEN) {
1300 len = BTRFS_NAME_LEN;
1301 error = REF_ERR_NAME_TOO_LONG;
1303 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1305 if (location.type == BTRFS_INODE_ITEM_KEY) {
1306 add_inode_backref(inode_cache, location.objectid,
1307 key->objectid, key->offset, namebuf,
1308 len, filetype, key->type, error);
1309 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1310 add_inode_backref(root_cache, location.objectid,
1311 key->objectid, key->offset,
1312 namebuf, len, filetype,
1315 fprintf(stderr, "invalid location in dir item %u\n",
1317 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1318 key->objectid, key->offset, namebuf,
1319 len, filetype, key->type, error);
1322 len = sizeof(*di) + name_len + data_len;
1323 di = (struct btrfs_dir_item *)((char *)di + len);
1326 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1327 rec->errors |= I_ERR_DUP_DIR_INDEX;
1332 static int process_inode_ref(struct extent_buffer *eb,
1333 int slot, struct btrfs_key *key,
1334 struct shared_node *active_node)
1342 struct cache_tree *inode_cache;
1343 struct btrfs_inode_ref *ref;
1344 char namebuf[BTRFS_NAME_LEN];
1346 inode_cache = &active_node->inode_cache;
1348 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1349 total = btrfs_item_size_nr(eb, slot);
1350 while (cur < total) {
1351 name_len = btrfs_inode_ref_name_len(eb, ref);
1352 index = btrfs_inode_ref_index(eb, ref);
1353 if (name_len <= BTRFS_NAME_LEN) {
1357 len = BTRFS_NAME_LEN;
1358 error = REF_ERR_NAME_TOO_LONG;
1360 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1361 add_inode_backref(inode_cache, key->objectid, key->offset,
1362 index, namebuf, len, 0, key->type, error);
1364 len = sizeof(*ref) + name_len;
1365 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1371 static int process_inode_extref(struct extent_buffer *eb,
1372 int slot, struct btrfs_key *key,
1373 struct shared_node *active_node)
1382 struct cache_tree *inode_cache;
1383 struct btrfs_inode_extref *extref;
1384 char namebuf[BTRFS_NAME_LEN];
1386 inode_cache = &active_node->inode_cache;
1388 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1389 total = btrfs_item_size_nr(eb, slot);
1390 while (cur < total) {
1391 name_len = btrfs_inode_extref_name_len(eb, extref);
1392 index = btrfs_inode_extref_index(eb, extref);
1393 parent = btrfs_inode_extref_parent(eb, extref);
1394 if (name_len <= BTRFS_NAME_LEN) {
1398 len = BTRFS_NAME_LEN;
1399 error = REF_ERR_NAME_TOO_LONG;
1401 read_extent_buffer(eb, namebuf,
1402 (unsigned long)(extref + 1), len);
1403 add_inode_backref(inode_cache, key->objectid, parent,
1404 index, namebuf, len, 0, key->type, error);
1406 len = sizeof(*extref) + name_len;
1407 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1414 static int count_csum_range(struct btrfs_root *root, u64 start,
1415 u64 len, u64 *found)
1417 struct btrfs_key key;
1418 struct btrfs_path path;
1419 struct extent_buffer *leaf;
1424 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1426 btrfs_init_path(&path);
1428 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1430 key.type = BTRFS_EXTENT_CSUM_KEY;
1432 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1436 if (ret > 0 && path.slots[0] > 0) {
1437 leaf = path.nodes[0];
1438 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1439 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1440 key.type == BTRFS_EXTENT_CSUM_KEY)
1445 leaf = path.nodes[0];
1446 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1447 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1452 leaf = path.nodes[0];
1455 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1456 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1457 key.type != BTRFS_EXTENT_CSUM_KEY)
1460 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1461 if (key.offset >= start + len)
1464 if (key.offset > start)
1467 size = btrfs_item_size_nr(leaf, path.slots[0]);
1468 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1469 if (csum_end > start) {
1470 size = min(csum_end - start, len);
1479 btrfs_release_path(&path);
1485 static int process_file_extent(struct btrfs_root *root,
1486 struct extent_buffer *eb,
1487 int slot, struct btrfs_key *key,
1488 struct shared_node *active_node)
1490 struct inode_record *rec;
1491 struct btrfs_file_extent_item *fi;
1493 u64 disk_bytenr = 0;
1494 u64 extent_offset = 0;
1495 u64 mask = root->sectorsize - 1;
1499 rec = active_node->current;
1500 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1501 rec->found_file_extent = 1;
1503 if (rec->extent_start == (u64)-1) {
1504 rec->extent_start = key->offset;
1505 rec->extent_end = key->offset;
1508 if (rec->extent_end > key->offset)
1509 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1510 else if (rec->extent_end < key->offset) {
1511 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1512 key->offset - rec->extent_end);
1517 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1518 extent_type = btrfs_file_extent_type(eb, fi);
1520 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1521 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1523 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1524 rec->found_size += num_bytes;
1525 num_bytes = (num_bytes + mask) & ~mask;
1526 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1527 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1528 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1529 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1530 extent_offset = btrfs_file_extent_offset(eb, fi);
1531 if (num_bytes == 0 || (num_bytes & mask))
1532 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1533 if (num_bytes + extent_offset >
1534 btrfs_file_extent_ram_bytes(eb, fi))
1535 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1536 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1537 (btrfs_file_extent_compression(eb, fi) ||
1538 btrfs_file_extent_encryption(eb, fi) ||
1539 btrfs_file_extent_other_encoding(eb, fi)))
1540 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1541 if (disk_bytenr > 0)
1542 rec->found_size += num_bytes;
1544 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1546 rec->extent_end = key->offset + num_bytes;
1549 * The data reloc tree will copy full extents into its inode and then
1550 * copy the corresponding csums. Because the extent it copied could be
1551 * a preallocated extent that hasn't been written to yet there may be no
1552 * csums to copy, ergo we won't have csums for our file extent. This is
1553 * ok so just don't bother checking csums if the inode belongs to the
1556 if (disk_bytenr > 0 &&
1557 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1559 if (btrfs_file_extent_compression(eb, fi))
1560 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1562 disk_bytenr += extent_offset;
1564 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1567 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1569 rec->found_csum_item = 1;
1570 if (found < num_bytes)
1571 rec->some_csum_missing = 1;
1572 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1574 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1580 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1581 struct walk_control *wc)
1583 struct btrfs_key key;
1587 struct cache_tree *inode_cache;
1588 struct shared_node *active_node;
1590 if (wc->root_level == wc->active_node &&
1591 btrfs_root_refs(&root->root_item) == 0)
1594 active_node = wc->nodes[wc->active_node];
1595 inode_cache = &active_node->inode_cache;
1596 nritems = btrfs_header_nritems(eb);
1597 for (i = 0; i < nritems; i++) {
1598 btrfs_item_key_to_cpu(eb, &key, i);
1600 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1602 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1605 if (active_node->current == NULL ||
1606 active_node->current->ino < key.objectid) {
1607 if (active_node->current) {
1608 active_node->current->checked = 1;
1609 maybe_free_inode_rec(inode_cache,
1610 active_node->current);
1612 active_node->current = get_inode_rec(inode_cache,
1616 case BTRFS_DIR_ITEM_KEY:
1617 case BTRFS_DIR_INDEX_KEY:
1618 ret = process_dir_item(root, eb, i, &key, active_node);
1620 case BTRFS_INODE_REF_KEY:
1621 ret = process_inode_ref(eb, i, &key, active_node);
1623 case BTRFS_INODE_EXTREF_KEY:
1624 ret = process_inode_extref(eb, i, &key, active_node);
1626 case BTRFS_INODE_ITEM_KEY:
1627 ret = process_inode_item(eb, i, &key, active_node);
1629 case BTRFS_EXTENT_DATA_KEY:
1630 ret = process_file_extent(root, eb, i, &key,
1640 static void reada_walk_down(struct btrfs_root *root,
1641 struct extent_buffer *node, int slot)
1650 level = btrfs_header_level(node);
1654 nritems = btrfs_header_nritems(node);
1655 blocksize = btrfs_level_size(root, level - 1);
1656 for (i = slot; i < nritems; i++) {
1657 bytenr = btrfs_node_blockptr(node, i);
1658 ptr_gen = btrfs_node_ptr_generation(node, i);
1659 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1664 * Check the child node/leaf by the following condition:
1665 * 1. the first item key of the node/leaf should be the same with the one
1667 * 2. block in parent node should match the child node/leaf.
1668 * 3. generation of parent node and child's header should be consistent.
1670 * Or the child node/leaf pointed by the key in parent is not valid.
1672 * We hope to check leaf owner too, but since subvol may share leaves,
1673 * which makes leaf owner check not so strong, key check should be
1674 * sufficient enough for that case.
1676 static int check_child_node(struct btrfs_root *root,
1677 struct extent_buffer *parent, int slot,
1678 struct extent_buffer *child)
1680 struct btrfs_key parent_key;
1681 struct btrfs_key child_key;
1684 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1685 if (btrfs_header_level(child) == 0)
1686 btrfs_item_key_to_cpu(child, &child_key, 0);
1688 btrfs_node_key_to_cpu(child, &child_key, 0);
1690 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1693 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1694 parent_key.objectid, parent_key.type, parent_key.offset,
1695 child_key.objectid, child_key.type, child_key.offset);
1697 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1699 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1700 btrfs_node_blockptr(parent, slot),
1701 btrfs_header_bytenr(child));
1703 if (btrfs_node_ptr_generation(parent, slot) !=
1704 btrfs_header_generation(child)) {
1706 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1707 btrfs_header_generation(child),
1708 btrfs_node_ptr_generation(parent, slot));
1713 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1714 struct walk_control *wc, int *level)
1716 enum btrfs_tree_block_status status;
1719 struct extent_buffer *next;
1720 struct extent_buffer *cur;
1725 WARN_ON(*level < 0);
1726 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1727 ret = btrfs_lookup_extent_info(NULL, root,
1728 path->nodes[*level]->start,
1729 *level, 1, &refs, NULL);
1736 ret = enter_shared_node(root, path->nodes[*level]->start,
1744 while (*level >= 0) {
1745 WARN_ON(*level < 0);
1746 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1747 cur = path->nodes[*level];
1749 if (btrfs_header_level(cur) != *level)
1752 if (path->slots[*level] >= btrfs_header_nritems(cur))
1755 ret = process_one_leaf(root, cur, wc);
1760 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1761 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1762 blocksize = btrfs_level_size(root, *level - 1);
1763 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1769 ret = enter_shared_node(root, bytenr, refs,
1772 path->slots[*level]++;
1777 next = btrfs_find_tree_block(root, bytenr, blocksize);
1778 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1779 free_extent_buffer(next);
1780 reada_walk_down(root, cur, path->slots[*level]);
1781 next = read_tree_block(root, bytenr, blocksize,
1783 if (!extent_buffer_uptodate(next)) {
1784 struct btrfs_key node_key;
1786 btrfs_node_key_to_cpu(path->nodes[*level],
1788 path->slots[*level]);
1789 btrfs_add_corrupt_extent_record(root->fs_info,
1791 path->nodes[*level]->start,
1792 root->leafsize, *level);
1798 ret = check_child_node(root, cur, path->slots[*level], next);
1804 if (btrfs_is_leaf(next))
1805 status = btrfs_check_leaf(root, NULL, next);
1807 status = btrfs_check_node(root, NULL, next);
1808 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1809 free_extent_buffer(next);
1814 *level = *level - 1;
1815 free_extent_buffer(path->nodes[*level]);
1816 path->nodes[*level] = next;
1817 path->slots[*level] = 0;
1820 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1824 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1825 struct walk_control *wc, int *level)
1828 struct extent_buffer *leaf;
1830 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1831 leaf = path->nodes[i];
1832 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1837 free_extent_buffer(path->nodes[*level]);
1838 path->nodes[*level] = NULL;
1839 BUG_ON(*level > wc->active_node);
1840 if (*level == wc->active_node)
1841 leave_shared_node(root, wc, *level);
1848 static int check_root_dir(struct inode_record *rec)
1850 struct inode_backref *backref;
1853 if (!rec->found_inode_item || rec->errors)
1855 if (rec->nlink != 1 || rec->found_link != 0)
1857 if (list_empty(&rec->backrefs))
1859 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1860 if (!backref->found_inode_ref)
1862 if (backref->index != 0 || backref->namelen != 2 ||
1863 memcmp(backref->name, "..", 2))
1865 if (backref->found_dir_index || backref->found_dir_item)
1872 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1873 struct btrfs_root *root, struct btrfs_path *path,
1874 struct inode_record *rec)
1876 struct btrfs_inode_item *ei;
1877 struct btrfs_key key;
1880 key.objectid = rec->ino;
1881 key.type = BTRFS_INODE_ITEM_KEY;
1882 key.offset = (u64)-1;
1884 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1888 if (!path->slots[0]) {
1895 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1896 if (key.objectid != rec->ino) {
1901 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1902 struct btrfs_inode_item);
1903 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1904 btrfs_mark_buffer_dirty(path->nodes[0]);
1905 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1906 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1907 root->root_key.objectid);
1909 btrfs_release_path(path);
1913 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1914 struct btrfs_root *root,
1915 struct btrfs_path *path,
1916 struct inode_record *rec)
1920 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1921 btrfs_release_path(path);
1923 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1927 static int repair_inode_nbytes(struct btrfs_trans_handle *trans,
1928 struct btrfs_root *root,
1929 struct btrfs_path *path,
1930 struct inode_record *rec)
1932 struct btrfs_inode_item *ei;
1933 struct btrfs_key key;
1936 key.objectid = rec->ino;
1937 key.type = BTRFS_INODE_ITEM_KEY;
1940 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1947 /* Since ret == 0, no need to check anything */
1948 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1949 struct btrfs_inode_item);
1950 btrfs_set_inode_nbytes(path->nodes[0], ei, rec->found_size);
1951 btrfs_mark_buffer_dirty(path->nodes[0]);
1952 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
1953 printf("reset nbytes for ino %llu root %llu\n",
1954 rec->ino, root->root_key.objectid);
1956 btrfs_release_path(path);
1960 static int add_missing_dir_index(struct btrfs_root *root,
1961 struct cache_tree *inode_cache,
1962 struct inode_record *rec,
1963 struct inode_backref *backref)
1965 struct btrfs_path *path;
1966 struct btrfs_trans_handle *trans;
1967 struct btrfs_dir_item *dir_item;
1968 struct extent_buffer *leaf;
1969 struct btrfs_key key;
1970 struct btrfs_disk_key disk_key;
1971 struct inode_record *dir_rec;
1972 unsigned long name_ptr;
1973 u32 data_size = sizeof(*dir_item) + backref->namelen;
1976 path = btrfs_alloc_path();
1980 trans = btrfs_start_transaction(root, 1);
1981 if (IS_ERR(trans)) {
1982 btrfs_free_path(path);
1983 return PTR_ERR(trans);
1986 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1987 (unsigned long long)rec->ino);
1988 key.objectid = backref->dir;
1989 key.type = BTRFS_DIR_INDEX_KEY;
1990 key.offset = backref->index;
1992 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1995 leaf = path->nodes[0];
1996 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
1998 disk_key.objectid = cpu_to_le64(rec->ino);
1999 disk_key.type = BTRFS_INODE_ITEM_KEY;
2000 disk_key.offset = 0;
2002 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
2003 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
2004 btrfs_set_dir_data_len(leaf, dir_item, 0);
2005 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
2006 name_ptr = (unsigned long)(dir_item + 1);
2007 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
2008 btrfs_mark_buffer_dirty(leaf);
2009 btrfs_free_path(path);
2010 btrfs_commit_transaction(trans, root);
2012 backref->found_dir_index = 1;
2013 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
2016 dir_rec->found_size += backref->namelen;
2017 if (dir_rec->found_size == dir_rec->isize &&
2018 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
2019 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
2020 if (dir_rec->found_size != dir_rec->isize)
2021 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
2026 static int delete_dir_index(struct btrfs_root *root,
2027 struct cache_tree *inode_cache,
2028 struct inode_record *rec,
2029 struct inode_backref *backref)
2031 struct btrfs_trans_handle *trans;
2032 struct btrfs_dir_item *di;
2033 struct btrfs_path *path;
2036 path = btrfs_alloc_path();
2040 trans = btrfs_start_transaction(root, 1);
2041 if (IS_ERR(trans)) {
2042 btrfs_free_path(path);
2043 return PTR_ERR(trans);
2047 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2048 (unsigned long long)backref->dir,
2049 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2050 (unsigned long long)root->objectid);
2052 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2053 backref->name, backref->namelen,
2054 backref->index, -1);
2057 btrfs_free_path(path);
2058 btrfs_commit_transaction(trans, root);
2065 ret = btrfs_del_item(trans, root, path);
2067 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2069 btrfs_free_path(path);
2070 btrfs_commit_transaction(trans, root);
2074 static int create_inode_item(struct btrfs_root *root,
2075 struct inode_record *rec,
2076 struct inode_backref *backref, int root_dir)
2078 struct btrfs_trans_handle *trans;
2079 struct btrfs_inode_item inode_item;
2080 time_t now = time(NULL);
2083 trans = btrfs_start_transaction(root, 1);
2084 if (IS_ERR(trans)) {
2085 ret = PTR_ERR(trans);
2089 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2090 "be incomplete, please check permissions and content after "
2091 "the fsck completes.\n", (unsigned long long)root->objectid,
2092 (unsigned long long)rec->ino);
2094 memset(&inode_item, 0, sizeof(inode_item));
2095 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2097 btrfs_set_stack_inode_nlink(&inode_item, 1);
2099 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2100 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2101 if (rec->found_dir_item) {
2102 if (rec->found_file_extent)
2103 fprintf(stderr, "root %llu inode %llu has both a dir "
2104 "item and extents, unsure if it is a dir or a "
2105 "regular file so setting it as a directory\n",
2106 (unsigned long long)root->objectid,
2107 (unsigned long long)rec->ino);
2108 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2109 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2110 } else if (!rec->found_dir_item) {
2111 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2112 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2114 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2115 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2116 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2117 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2118 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2119 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2120 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2121 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2123 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2125 btrfs_commit_transaction(trans, root);
2129 static int repair_inode_backrefs(struct btrfs_root *root,
2130 struct inode_record *rec,
2131 struct cache_tree *inode_cache,
2134 struct inode_backref *tmp, *backref;
2135 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2139 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2140 if (!delete && rec->ino == root_dirid) {
2141 if (!rec->found_inode_item) {
2142 ret = create_inode_item(root, rec, backref, 1);
2149 /* Index 0 for root dir's are special, don't mess with it */
2150 if (rec->ino == root_dirid && backref->index == 0)
2154 ((backref->found_dir_index && !backref->found_inode_ref) ||
2155 (backref->found_dir_index && backref->found_inode_ref &&
2156 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2157 ret = delete_dir_index(root, inode_cache, rec, backref);
2161 list_del(&backref->list);
2165 if (!delete && !backref->found_dir_index &&
2166 backref->found_dir_item && backref->found_inode_ref) {
2167 ret = add_missing_dir_index(root, inode_cache, rec,
2172 if (backref->found_dir_item &&
2173 backref->found_dir_index &&
2174 backref->found_dir_index) {
2175 if (!backref->errors &&
2176 backref->found_inode_ref) {
2177 list_del(&backref->list);
2183 if (!delete && (!backref->found_dir_index &&
2184 !backref->found_dir_item &&
2185 backref->found_inode_ref)) {
2186 struct btrfs_trans_handle *trans;
2187 struct btrfs_key location;
2189 ret = check_dir_conflict(root, backref->name,
2195 * let nlink fixing routine to handle it,
2196 * which can do it better.
2201 location.objectid = rec->ino;
2202 location.type = BTRFS_INODE_ITEM_KEY;
2203 location.offset = 0;
2205 trans = btrfs_start_transaction(root, 1);
2206 if (IS_ERR(trans)) {
2207 ret = PTR_ERR(trans);
2210 fprintf(stderr, "adding missing dir index/item pair "
2212 (unsigned long long)rec->ino);
2213 ret = btrfs_insert_dir_item(trans, root, backref->name,
2215 backref->dir, &location,
2216 imode_to_type(rec->imode),
2219 btrfs_commit_transaction(trans, root);
2223 if (!delete && (backref->found_inode_ref &&
2224 backref->found_dir_index &&
2225 backref->found_dir_item &&
2226 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2227 !rec->found_inode_item)) {
2228 ret = create_inode_item(root, rec, backref, 0);
2235 return ret ? ret : repaired;
2239 * To determine the file type for nlink/inode_item repair
2241 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2242 * Return -ENOENT if file type is not found.
2244 static int find_file_type(struct inode_record *rec, u8 *type)
2246 struct inode_backref *backref;
2248 /* For inode item recovered case */
2249 if (rec->found_inode_item) {
2250 *type = imode_to_type(rec->imode);
2254 list_for_each_entry(backref, &rec->backrefs, list) {
2255 if (backref->found_dir_index || backref->found_dir_item) {
2256 *type = backref->filetype;
2264 * To determine the file name for nlink repair
2266 * Return 0 if file name is found, set name and namelen.
2267 * Return -ENOENT if file name is not found.
2269 static int find_file_name(struct inode_record *rec,
2270 char *name, int *namelen)
2272 struct inode_backref *backref;
2274 list_for_each_entry(backref, &rec->backrefs, list) {
2275 if (backref->found_dir_index || backref->found_dir_item ||
2276 backref->found_inode_ref) {
2277 memcpy(name, backref->name, backref->namelen);
2278 *namelen = backref->namelen;
2285 /* Reset the nlink of the inode to the correct one */
2286 static int reset_nlink(struct btrfs_trans_handle *trans,
2287 struct btrfs_root *root,
2288 struct btrfs_path *path,
2289 struct inode_record *rec)
2291 struct inode_backref *backref;
2292 struct inode_backref *tmp;
2293 struct btrfs_key key;
2294 struct btrfs_inode_item *inode_item;
2297 /* We don't believe this either, reset it and iterate backref */
2298 rec->found_link = 0;
2300 /* Remove all backref including the valid ones */
2301 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2302 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2303 backref->index, backref->name,
2304 backref->namelen, 0);
2308 /* remove invalid backref, so it won't be added back */
2309 if (!(backref->found_dir_index &&
2310 backref->found_dir_item &&
2311 backref->found_inode_ref)) {
2312 list_del(&backref->list);
2319 /* Set nlink to 0 */
2320 key.objectid = rec->ino;
2321 key.type = BTRFS_INODE_ITEM_KEY;
2323 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2330 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2331 struct btrfs_inode_item);
2332 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2333 btrfs_mark_buffer_dirty(path->nodes[0]);
2334 btrfs_release_path(path);
2337 * Add back valid inode_ref/dir_item/dir_index,
2338 * add_link() will handle the nlink inc, so new nlink must be correct
2340 list_for_each_entry(backref, &rec->backrefs, list) {
2341 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2342 backref->name, backref->namelen,
2343 backref->ref_type, &backref->index, 1);
2348 btrfs_release_path(path);
2352 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2353 struct btrfs_root *root,
2354 struct btrfs_path *path,
2355 struct inode_record *rec)
2357 char *dir_name = "lost+found";
2358 char namebuf[BTRFS_NAME_LEN] = {0};
2363 int name_recovered = 0;
2364 int type_recovered = 0;
2368 * Get file name and type first before these invalid inode ref
2369 * are deleted by remove_all_invalid_backref()
2371 name_recovered = !find_file_name(rec, namebuf, &namelen);
2372 type_recovered = !find_file_type(rec, &type);
2374 if (!name_recovered) {
2375 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2376 rec->ino, rec->ino);
2377 namelen = count_digits(rec->ino);
2378 sprintf(namebuf, "%llu", rec->ino);
2381 if (!type_recovered) {
2382 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2384 type = BTRFS_FT_REG_FILE;
2388 ret = reset_nlink(trans, root, path, rec);
2391 "Failed to reset nlink for inode %llu: %s\n",
2392 rec->ino, strerror(-ret));
2396 if (rec->found_link == 0) {
2397 lost_found_ino = root->highest_inode;
2398 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2403 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2404 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2407 fprintf(stderr, "Failed to create '%s' dir: %s",
2408 dir_name, strerror(-ret));
2411 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2412 namebuf, namelen, type, NULL, 1);
2414 * Add ".INO" suffix several times to handle case where
2415 * "FILENAME.INO" is already taken by another file.
2417 while (ret == -EEXIST) {
2419 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2421 if (namelen + count_digits(rec->ino) + 1 >
2426 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2428 namelen += count_digits(rec->ino) + 1;
2429 ret = btrfs_add_link(trans, root, rec->ino,
2430 lost_found_ino, namebuf,
2431 namelen, type, NULL, 1);
2435 "Failed to link the inode %llu to %s dir: %s",
2436 rec->ino, dir_name, strerror(-ret));
2440 * Just increase the found_link, don't actually add the
2441 * backref. This will make things easier and this inode
2442 * record will be freed after the repair is done.
2443 * So fsck will not report problem about this inode.
2446 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2447 namelen, namebuf, dir_name);
2449 printf("Fixed the nlink of inode %llu\n", rec->ino);
2452 * Clear the flag anyway, or we will loop forever for the same inode
2453 * as it will not be removed from the bad inode list and the dead loop
2456 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2457 btrfs_release_path(path);
2462 * Check if there is any normal(reg or prealloc) file extent for given
2464 * This is used to determine the file type when neither its dir_index/item or
2465 * inode_item exists.
2467 * This will *NOT* report error, if any error happens, just consider it does
2468 * not have any normal file extent.
2470 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2472 struct btrfs_path *path;
2473 struct btrfs_key key;
2474 struct btrfs_key found_key;
2475 struct btrfs_file_extent_item *fi;
2479 path = btrfs_alloc_path();
2483 key.type = BTRFS_EXTENT_DATA_KEY;
2486 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2491 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2492 ret = btrfs_next_leaf(root, path);
2499 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2501 if (found_key.objectid != ino ||
2502 found_key.type != BTRFS_EXTENT_DATA_KEY)
2504 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2505 struct btrfs_file_extent_item);
2506 type = btrfs_file_extent_type(path->nodes[0], fi);
2507 if (type != BTRFS_FILE_EXTENT_INLINE) {
2513 btrfs_free_path(path);
2517 static u32 btrfs_type_to_imode(u8 type)
2519 static u32 imode_by_btrfs_type[] = {
2520 [BTRFS_FT_REG_FILE] = S_IFREG,
2521 [BTRFS_FT_DIR] = S_IFDIR,
2522 [BTRFS_FT_CHRDEV] = S_IFCHR,
2523 [BTRFS_FT_BLKDEV] = S_IFBLK,
2524 [BTRFS_FT_FIFO] = S_IFIFO,
2525 [BTRFS_FT_SOCK] = S_IFSOCK,
2526 [BTRFS_FT_SYMLINK] = S_IFLNK,
2529 return imode_by_btrfs_type[(type)];
2532 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2533 struct btrfs_root *root,
2534 struct btrfs_path *path,
2535 struct inode_record *rec)
2539 int type_recovered = 0;
2542 printf("Trying to rebuild inode:%llu\n", rec->ino);
2544 type_recovered = !find_file_type(rec, &filetype);
2547 * Try to determine inode type if type not found.
2549 * For found regular file extent, it must be FILE.
2550 * For found dir_item/index, it must be DIR.
2552 * For undetermined one, use FILE as fallback.
2555 * 1. If found backref(inode_index/item is already handled) to it,
2557 * Need new inode-inode ref structure to allow search for that.
2559 if (!type_recovered) {
2560 if (rec->found_file_extent &&
2561 find_normal_file_extent(root, rec->ino)) {
2563 filetype = BTRFS_FT_REG_FILE;
2564 } else if (rec->found_dir_item) {
2566 filetype = BTRFS_FT_DIR;
2567 } else if (!list_empty(&rec->orphan_extents)) {
2569 filetype = BTRFS_FT_REG_FILE;
2571 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2574 filetype = BTRFS_FT_REG_FILE;
2578 ret = btrfs_new_inode(trans, root, rec->ino,
2579 mode | btrfs_type_to_imode(filetype));
2584 * Here inode rebuild is done, we only rebuild the inode item,
2585 * don't repair the nlink(like move to lost+found).
2586 * That is the job of nlink repair.
2588 * We just fill the record and return
2590 rec->found_dir_item = 1;
2591 rec->imode = mode | btrfs_type_to_imode(filetype);
2593 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2594 /* Ensure the inode_nlinks repair function will be called */
2595 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2600 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2601 struct btrfs_root *root,
2602 struct btrfs_path *path,
2603 struct inode_record *rec)
2605 struct orphan_data_extent *orphan;
2606 struct orphan_data_extent *tmp;
2609 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2611 * Check for conflicting file extents
2613 * Here we don't know whether the extents is compressed or not,
2614 * so we can only assume it not compressed nor data offset,
2615 * and use its disk_len as extent length.
2617 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2618 orphan->offset, orphan->disk_len, 0);
2619 btrfs_release_path(path);
2624 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2625 orphan->disk_bytenr, orphan->disk_len);
2626 ret = btrfs_free_extent(trans,
2627 root->fs_info->extent_root,
2628 orphan->disk_bytenr, orphan->disk_len,
2629 0, root->objectid, orphan->objectid,
2634 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2635 orphan->offset, orphan->disk_bytenr,
2636 orphan->disk_len, orphan->disk_len);
2640 /* Update file size info */
2641 rec->found_size += orphan->disk_len;
2642 if (rec->found_size == rec->nbytes)
2643 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2645 /* Update the file extent hole info too */
2646 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2650 if (RB_EMPTY_ROOT(&rec->holes))
2651 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2653 list_del(&orphan->list);
2656 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2661 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2662 struct btrfs_root *root,
2663 struct btrfs_path *path,
2664 struct inode_record *rec)
2666 struct rb_node *node;
2667 struct file_extent_hole *hole;
2670 node = rb_first(&rec->holes);
2673 hole = rb_entry(node, struct file_extent_hole, node);
2674 ret = btrfs_punch_hole(trans, root, rec->ino,
2675 hole->start, hole->len);
2678 ret = del_file_extent_hole(&rec->holes, hole->start,
2682 if (RB_EMPTY_ROOT(&rec->holes))
2683 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2684 node = rb_first(&rec->holes);
2686 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2687 rec->ino, root->objectid);
2692 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2694 struct btrfs_trans_handle *trans;
2695 struct btrfs_path *path;
2698 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2699 I_ERR_NO_ORPHAN_ITEM |
2700 I_ERR_LINK_COUNT_WRONG |
2701 I_ERR_NO_INODE_ITEM |
2702 I_ERR_FILE_EXTENT_ORPHAN |
2703 I_ERR_FILE_EXTENT_DISCOUNT|
2704 I_ERR_FILE_NBYTES_WRONG)))
2707 path = btrfs_alloc_path();
2712 * For nlink repair, it may create a dir and add link, so
2713 * 2 for parent(256)'s dir_index and dir_item
2714 * 2 for lost+found dir's inode_item and inode_ref
2715 * 1 for the new inode_ref of the file
2716 * 2 for lost+found dir's dir_index and dir_item for the file
2718 trans = btrfs_start_transaction(root, 7);
2719 if (IS_ERR(trans)) {
2720 btrfs_free_path(path);
2721 return PTR_ERR(trans);
2724 if (rec->errors & I_ERR_NO_INODE_ITEM)
2725 ret = repair_inode_no_item(trans, root, path, rec);
2726 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2727 ret = repair_inode_orphan_extent(trans, root, path, rec);
2728 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2729 ret = repair_inode_discount_extent(trans, root, path, rec);
2730 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2731 ret = repair_inode_isize(trans, root, path, rec);
2732 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2733 ret = repair_inode_orphan_item(trans, root, path, rec);
2734 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2735 ret = repair_inode_nlinks(trans, root, path, rec);
2736 if (!ret && rec->errors & I_ERR_FILE_NBYTES_WRONG)
2737 ret = repair_inode_nbytes(trans, root, path, rec);
2738 btrfs_commit_transaction(trans, root);
2739 btrfs_free_path(path);
2743 static int check_inode_recs(struct btrfs_root *root,
2744 struct cache_tree *inode_cache)
2746 struct cache_extent *cache;
2747 struct ptr_node *node;
2748 struct inode_record *rec;
2749 struct inode_backref *backref;
2754 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2756 if (btrfs_root_refs(&root->root_item) == 0) {
2757 if (!cache_tree_empty(inode_cache))
2758 fprintf(stderr, "warning line %d\n", __LINE__);
2763 * We need to record the highest inode number for later 'lost+found'
2765 * We must select a ino not used/refered by any existing inode, or
2766 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2767 * this may cause 'lost+found' dir has wrong nlinks.
2769 cache = last_cache_extent(inode_cache);
2771 node = container_of(cache, struct ptr_node, cache);
2773 if (rec->ino > root->highest_inode)
2774 root->highest_inode = rec->ino;
2778 * We need to repair backrefs first because we could change some of the
2779 * errors in the inode recs.
2781 * We also need to go through and delete invalid backrefs first and then
2782 * add the correct ones second. We do this because we may get EEXIST
2783 * when adding back the correct index because we hadn't yet deleted the
2786 * For example, if we were missing a dir index then the directories
2787 * isize would be wrong, so if we fixed the isize to what we thought it
2788 * would be and then fixed the backref we'd still have a invalid fs, so
2789 * we need to add back the dir index and then check to see if the isize
2794 if (stage == 3 && !err)
2797 cache = search_cache_extent(inode_cache, 0);
2798 while (repair && cache) {
2799 node = container_of(cache, struct ptr_node, cache);
2801 cache = next_cache_extent(cache);
2803 /* Need to free everything up and rescan */
2805 remove_cache_extent(inode_cache, &node->cache);
2807 free_inode_rec(rec);
2811 if (list_empty(&rec->backrefs))
2814 ret = repair_inode_backrefs(root, rec, inode_cache,
2828 rec = get_inode_rec(inode_cache, root_dirid, 0);
2830 ret = check_root_dir(rec);
2832 fprintf(stderr, "root %llu root dir %llu error\n",
2833 (unsigned long long)root->root_key.objectid,
2834 (unsigned long long)root_dirid);
2835 print_inode_error(root, rec);
2840 struct btrfs_trans_handle *trans;
2842 trans = btrfs_start_transaction(root, 1);
2843 if (IS_ERR(trans)) {
2844 err = PTR_ERR(trans);
2849 "root %llu missing its root dir, recreating\n",
2850 (unsigned long long)root->objectid);
2852 ret = btrfs_make_root_dir(trans, root, root_dirid);
2855 btrfs_commit_transaction(trans, root);
2859 fprintf(stderr, "root %llu root dir %llu not found\n",
2860 (unsigned long long)root->root_key.objectid,
2861 (unsigned long long)root_dirid);
2865 cache = search_cache_extent(inode_cache, 0);
2868 node = container_of(cache, struct ptr_node, cache);
2870 remove_cache_extent(inode_cache, &node->cache);
2872 if (rec->ino == root_dirid ||
2873 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2874 free_inode_rec(rec);
2878 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2879 ret = check_orphan_item(root, rec->ino);
2881 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2882 if (can_free_inode_rec(rec)) {
2883 free_inode_rec(rec);
2888 if (!rec->found_inode_item)
2889 rec->errors |= I_ERR_NO_INODE_ITEM;
2890 if (rec->found_link != rec->nlink)
2891 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2893 ret = try_repair_inode(root, rec);
2894 if (ret == 0 && can_free_inode_rec(rec)) {
2895 free_inode_rec(rec);
2901 if (!(repair && ret == 0))
2903 print_inode_error(root, rec);
2904 list_for_each_entry(backref, &rec->backrefs, list) {
2905 if (!backref->found_dir_item)
2906 backref->errors |= REF_ERR_NO_DIR_ITEM;
2907 if (!backref->found_dir_index)
2908 backref->errors |= REF_ERR_NO_DIR_INDEX;
2909 if (!backref->found_inode_ref)
2910 backref->errors |= REF_ERR_NO_INODE_REF;
2911 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2912 " namelen %u name %s filetype %d errors %x",
2913 (unsigned long long)backref->dir,
2914 (unsigned long long)backref->index,
2915 backref->namelen, backref->name,
2916 backref->filetype, backref->errors);
2917 print_ref_error(backref->errors);
2919 free_inode_rec(rec);
2921 return (error > 0) ? -1 : 0;
2924 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2927 struct cache_extent *cache;
2928 struct root_record *rec = NULL;
2931 cache = lookup_cache_extent(root_cache, objectid, 1);
2933 rec = container_of(cache, struct root_record, cache);
2935 rec = calloc(1, sizeof(*rec));
2936 rec->objectid = objectid;
2937 INIT_LIST_HEAD(&rec->backrefs);
2938 rec->cache.start = objectid;
2939 rec->cache.size = 1;
2941 ret = insert_cache_extent(root_cache, &rec->cache);
2947 static struct root_backref *get_root_backref(struct root_record *rec,
2948 u64 ref_root, u64 dir, u64 index,
2949 const char *name, int namelen)
2951 struct root_backref *backref;
2953 list_for_each_entry(backref, &rec->backrefs, list) {
2954 if (backref->ref_root != ref_root || backref->dir != dir ||
2955 backref->namelen != namelen)
2957 if (memcmp(name, backref->name, namelen))
2962 backref = malloc(sizeof(*backref) + namelen + 1);
2963 memset(backref, 0, sizeof(*backref));
2964 backref->ref_root = ref_root;
2966 backref->index = index;
2967 backref->namelen = namelen;
2968 memcpy(backref->name, name, namelen);
2969 backref->name[namelen] = '\0';
2970 list_add_tail(&backref->list, &rec->backrefs);
2974 static void free_root_record(struct cache_extent *cache)
2976 struct root_record *rec;
2977 struct root_backref *backref;
2979 rec = container_of(cache, struct root_record, cache);
2980 while (!list_empty(&rec->backrefs)) {
2981 backref = list_entry(rec->backrefs.next,
2982 struct root_backref, list);
2983 list_del(&backref->list);
2990 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2992 static int add_root_backref(struct cache_tree *root_cache,
2993 u64 root_id, u64 ref_root, u64 dir, u64 index,
2994 const char *name, int namelen,
2995 int item_type, int errors)
2997 struct root_record *rec;
2998 struct root_backref *backref;
3000 rec = get_root_rec(root_cache, root_id);
3001 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
3003 backref->errors |= errors;
3005 if (item_type != BTRFS_DIR_ITEM_KEY) {
3006 if (backref->found_dir_index || backref->found_back_ref ||
3007 backref->found_forward_ref) {
3008 if (backref->index != index)
3009 backref->errors |= REF_ERR_INDEX_UNMATCH;
3011 backref->index = index;
3015 if (item_type == BTRFS_DIR_ITEM_KEY) {
3016 if (backref->found_forward_ref)
3018 backref->found_dir_item = 1;
3019 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
3020 backref->found_dir_index = 1;
3021 } else if (item_type == BTRFS_ROOT_REF_KEY) {
3022 if (backref->found_forward_ref)
3023 backref->errors |= REF_ERR_DUP_ROOT_REF;
3024 else if (backref->found_dir_item)
3026 backref->found_forward_ref = 1;
3027 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
3028 if (backref->found_back_ref)
3029 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
3030 backref->found_back_ref = 1;
3035 if (backref->found_forward_ref && backref->found_dir_item)
3036 backref->reachable = 1;
3040 static int merge_root_recs(struct btrfs_root *root,
3041 struct cache_tree *src_cache,
3042 struct cache_tree *dst_cache)
3044 struct cache_extent *cache;
3045 struct ptr_node *node;
3046 struct inode_record *rec;
3047 struct inode_backref *backref;
3050 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3051 free_inode_recs_tree(src_cache);
3056 cache = search_cache_extent(src_cache, 0);
3059 node = container_of(cache, struct ptr_node, cache);
3061 remove_cache_extent(src_cache, &node->cache);
3064 ret = is_child_root(root, root->objectid, rec->ino);
3070 list_for_each_entry(backref, &rec->backrefs, list) {
3071 BUG_ON(backref->found_inode_ref);
3072 if (backref->found_dir_item)
3073 add_root_backref(dst_cache, rec->ino,
3074 root->root_key.objectid, backref->dir,
3075 backref->index, backref->name,
3076 backref->namelen, BTRFS_DIR_ITEM_KEY,
3078 if (backref->found_dir_index)
3079 add_root_backref(dst_cache, rec->ino,
3080 root->root_key.objectid, backref->dir,
3081 backref->index, backref->name,
3082 backref->namelen, BTRFS_DIR_INDEX_KEY,
3086 free_inode_rec(rec);
3093 static int check_root_refs(struct btrfs_root *root,
3094 struct cache_tree *root_cache)
3096 struct root_record *rec;
3097 struct root_record *ref_root;
3098 struct root_backref *backref;
3099 struct cache_extent *cache;
3105 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3108 /* fixme: this can not detect circular references */
3111 cache = search_cache_extent(root_cache, 0);
3115 rec = container_of(cache, struct root_record, cache);
3116 cache = next_cache_extent(cache);
3118 if (rec->found_ref == 0)
3121 list_for_each_entry(backref, &rec->backrefs, list) {
3122 if (!backref->reachable)
3125 ref_root = get_root_rec(root_cache,
3127 if (ref_root->found_ref > 0)
3130 backref->reachable = 0;
3132 if (rec->found_ref == 0)
3138 cache = search_cache_extent(root_cache, 0);
3142 rec = container_of(cache, struct root_record, cache);
3143 cache = next_cache_extent(cache);
3145 if (rec->found_ref == 0 &&
3146 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3147 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3148 ret = check_orphan_item(root->fs_info->tree_root,
3154 * If we don't have a root item then we likely just have
3155 * a dir item in a snapshot for this root but no actual
3156 * ref key or anything so it's meaningless.
3158 if (!rec->found_root_item)
3161 fprintf(stderr, "fs tree %llu not referenced\n",
3162 (unsigned long long)rec->objectid);
3166 if (rec->found_ref > 0 && !rec->found_root_item)
3168 list_for_each_entry(backref, &rec->backrefs, list) {
3169 if (!backref->found_dir_item)
3170 backref->errors |= REF_ERR_NO_DIR_ITEM;
3171 if (!backref->found_dir_index)
3172 backref->errors |= REF_ERR_NO_DIR_INDEX;
3173 if (!backref->found_back_ref)
3174 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3175 if (!backref->found_forward_ref)
3176 backref->errors |= REF_ERR_NO_ROOT_REF;
3177 if (backref->reachable && backref->errors)
3184 fprintf(stderr, "fs tree %llu refs %u %s\n",
3185 (unsigned long long)rec->objectid, rec->found_ref,
3186 rec->found_root_item ? "" : "not found");
3188 list_for_each_entry(backref, &rec->backrefs, list) {
3189 if (!backref->reachable)
3191 if (!backref->errors && rec->found_root_item)
3193 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3194 " index %llu namelen %u name %s errors %x\n",
3195 (unsigned long long)backref->ref_root,
3196 (unsigned long long)backref->dir,
3197 (unsigned long long)backref->index,
3198 backref->namelen, backref->name,
3200 print_ref_error(backref->errors);
3203 return errors > 0 ? 1 : 0;
3206 static int process_root_ref(struct extent_buffer *eb, int slot,
3207 struct btrfs_key *key,
3208 struct cache_tree *root_cache)
3214 struct btrfs_root_ref *ref;
3215 char namebuf[BTRFS_NAME_LEN];
3218 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3220 dirid = btrfs_root_ref_dirid(eb, ref);
3221 index = btrfs_root_ref_sequence(eb, ref);
3222 name_len = btrfs_root_ref_name_len(eb, ref);
3224 if (name_len <= BTRFS_NAME_LEN) {
3228 len = BTRFS_NAME_LEN;
3229 error = REF_ERR_NAME_TOO_LONG;
3231 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3233 if (key->type == BTRFS_ROOT_REF_KEY) {
3234 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3235 index, namebuf, len, key->type, error);
3237 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3238 index, namebuf, len, key->type, error);
3243 static void free_corrupt_block(struct cache_extent *cache)
3245 struct btrfs_corrupt_block *corrupt;
3247 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3251 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3254 * Repair the btree of the given root.
3256 * The fix is to remove the node key in corrupt_blocks cache_tree.
3257 * and rebalance the tree.
3258 * After the fix, the btree should be writeable.
3260 static int repair_btree(struct btrfs_root *root,
3261 struct cache_tree *corrupt_blocks)
3263 struct btrfs_trans_handle *trans;
3264 struct btrfs_path *path;
3265 struct btrfs_corrupt_block *corrupt;
3266 struct cache_extent *cache;
3267 struct btrfs_key key;
3272 if (cache_tree_empty(corrupt_blocks))
3275 path = btrfs_alloc_path();
3279 trans = btrfs_start_transaction(root, 1);
3280 if (IS_ERR(trans)) {
3281 ret = PTR_ERR(trans);
3282 fprintf(stderr, "Error starting transaction: %s\n",
3286 cache = first_cache_extent(corrupt_blocks);
3288 corrupt = container_of(cache, struct btrfs_corrupt_block,
3290 level = corrupt->level;
3291 path->lowest_level = level;
3292 key.objectid = corrupt->key.objectid;
3293 key.type = corrupt->key.type;
3294 key.offset = corrupt->key.offset;
3297 * Here we don't want to do any tree balance, since it may
3298 * cause a balance with corrupted brother leaf/node,
3299 * so ins_len set to 0 here.
3300 * Balance will be done after all corrupt node/leaf is deleted.
3302 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3305 offset = btrfs_node_blockptr(path->nodes[level],
3306 path->slots[level]);
3308 /* Remove the ptr */
3309 ret = btrfs_del_ptr(trans, root, path, level,
3310 path->slots[level]);
3314 * Remove the corresponding extent
3315 * return value is not concerned.
3317 btrfs_release_path(path);
3318 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3319 0, root->root_key.objectid,
3321 cache = next_cache_extent(cache);
3324 /* Balance the btree using btrfs_search_slot() */
3325 cache = first_cache_extent(corrupt_blocks);
3327 corrupt = container_of(cache, struct btrfs_corrupt_block,
3329 memcpy(&key, &corrupt->key, sizeof(key));
3330 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3333 /* return will always >0 since it won't find the item */
3335 btrfs_release_path(path);
3336 cache = next_cache_extent(cache);
3339 btrfs_commit_transaction(trans, root);
3341 btrfs_free_path(path);
3345 static int check_fs_root(struct btrfs_root *root,
3346 struct cache_tree *root_cache,
3347 struct walk_control *wc)
3353 struct btrfs_path path;
3354 struct shared_node root_node;
3355 struct root_record *rec;
3356 struct btrfs_root_item *root_item = &root->root_item;
3357 struct cache_tree corrupt_blocks;
3358 struct orphan_data_extent *orphan;
3359 struct orphan_data_extent *tmp;
3360 enum btrfs_tree_block_status status;
3363 * Reuse the corrupt_block cache tree to record corrupted tree block
3365 * Unlike the usage in extent tree check, here we do it in a per
3366 * fs/subvol tree base.
3368 cache_tree_init(&corrupt_blocks);
3369 root->fs_info->corrupt_blocks = &corrupt_blocks;
3371 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3372 rec = get_root_rec(root_cache, root->root_key.objectid);
3373 if (btrfs_root_refs(root_item) > 0)
3374 rec->found_root_item = 1;
3377 btrfs_init_path(&path);
3378 memset(&root_node, 0, sizeof(root_node));
3379 cache_tree_init(&root_node.root_cache);
3380 cache_tree_init(&root_node.inode_cache);
3382 /* Move the orphan extent record to corresponding inode_record */
3383 list_for_each_entry_safe(orphan, tmp,
3384 &root->orphan_data_extents, list) {
3385 struct inode_record *inode;
3387 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3389 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3390 list_move(&orphan->list, &inode->orphan_extents);
3393 level = btrfs_header_level(root->node);
3394 memset(wc->nodes, 0, sizeof(wc->nodes));
3395 wc->nodes[level] = &root_node;
3396 wc->active_node = level;
3397 wc->root_level = level;
3399 /* We may not have checked the root block, lets do that now */
3400 if (btrfs_is_leaf(root->node))
3401 status = btrfs_check_leaf(root, NULL, root->node);
3403 status = btrfs_check_node(root, NULL, root->node);
3404 if (status != BTRFS_TREE_BLOCK_CLEAN)
3407 if (btrfs_root_refs(root_item) > 0 ||
3408 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3409 path.nodes[level] = root->node;
3410 extent_buffer_get(root->node);
3411 path.slots[level] = 0;
3413 struct btrfs_key key;
3414 struct btrfs_disk_key found_key;
3416 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3417 level = root_item->drop_level;
3418 path.lowest_level = level;
3419 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3422 btrfs_node_key(path.nodes[level], &found_key,
3424 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3425 sizeof(found_key)));
3429 wret = walk_down_tree(root, &path, wc, &level);
3435 wret = walk_up_tree(root, &path, wc, &level);
3442 btrfs_release_path(&path);
3444 if (!cache_tree_empty(&corrupt_blocks)) {
3445 struct cache_extent *cache;
3446 struct btrfs_corrupt_block *corrupt;
3448 printf("The following tree block(s) is corrupted in tree %llu:\n",
3449 root->root_key.objectid);
3450 cache = first_cache_extent(&corrupt_blocks);
3452 corrupt = container_of(cache,
3453 struct btrfs_corrupt_block,
3455 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3456 cache->start, corrupt->level,
3457 corrupt->key.objectid, corrupt->key.type,
3458 corrupt->key.offset);
3459 cache = next_cache_extent(cache);
3462 printf("Try to repair the btree for root %llu\n",
3463 root->root_key.objectid);
3464 ret = repair_btree(root, &corrupt_blocks);
3466 fprintf(stderr, "Failed to repair btree: %s\n",
3469 printf("Btree for root %llu is fixed\n",
3470 root->root_key.objectid);
3474 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3478 if (root_node.current) {
3479 root_node.current->checked = 1;
3480 maybe_free_inode_rec(&root_node.inode_cache,
3484 err = check_inode_recs(root, &root_node.inode_cache);
3488 free_corrupt_blocks_tree(&corrupt_blocks);
3489 root->fs_info->corrupt_blocks = NULL;
3490 free_orphan_data_extents(&root->orphan_data_extents);
3494 static int fs_root_objectid(u64 objectid)
3496 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3497 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3499 return is_fstree(objectid);
3502 static int check_fs_roots(struct btrfs_root *root,
3503 struct cache_tree *root_cache)
3505 struct btrfs_path path;
3506 struct btrfs_key key;
3507 struct walk_control wc;
3508 struct extent_buffer *leaf, *tree_node;
3509 struct btrfs_root *tmp_root;
3510 struct btrfs_root *tree_root = root->fs_info->tree_root;
3515 * Just in case we made any changes to the extent tree that weren't
3516 * reflected into the free space cache yet.
3519 reset_cached_block_groups(root->fs_info);
3520 memset(&wc, 0, sizeof(wc));
3521 cache_tree_init(&wc.shared);
3522 btrfs_init_path(&path);
3527 key.type = BTRFS_ROOT_ITEM_KEY;
3528 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3533 tree_node = tree_root->node;
3535 if (tree_node != tree_root->node) {
3536 free_root_recs_tree(root_cache);
3537 btrfs_release_path(&path);
3540 leaf = path.nodes[0];
3541 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3542 ret = btrfs_next_leaf(tree_root, &path);
3548 leaf = path.nodes[0];
3550 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3551 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3552 fs_root_objectid(key.objectid)) {
3553 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3554 tmp_root = btrfs_read_fs_root_no_cache(
3555 root->fs_info, &key);
3557 key.offset = (u64)-1;
3558 tmp_root = btrfs_read_fs_root(
3559 root->fs_info, &key);
3561 if (IS_ERR(tmp_root)) {
3565 ret = check_fs_root(tmp_root, root_cache, &wc);
3566 if (ret == -EAGAIN) {
3567 free_root_recs_tree(root_cache);
3568 btrfs_release_path(&path);
3573 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3574 btrfs_free_fs_root(tmp_root);
3575 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3576 key.type == BTRFS_ROOT_BACKREF_KEY) {
3577 process_root_ref(leaf, path.slots[0], &key,
3584 btrfs_release_path(&path);
3586 free_extent_cache_tree(&wc.shared);
3587 if (!cache_tree_empty(&wc.shared))
3588 fprintf(stderr, "warning line %d\n", __LINE__);
3593 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3595 struct list_head *cur = rec->backrefs.next;
3596 struct extent_backref *back;
3597 struct tree_backref *tback;
3598 struct data_backref *dback;
3602 while(cur != &rec->backrefs) {
3603 back = list_entry(cur, struct extent_backref, list);
3605 if (!back->found_extent_tree) {
3609 if (back->is_data) {
3610 dback = (struct data_backref *)back;
3611 fprintf(stderr, "Backref %llu %s %llu"
3612 " owner %llu offset %llu num_refs %lu"
3613 " not found in extent tree\n",
3614 (unsigned long long)rec->start,
3615 back->full_backref ?
3617 back->full_backref ?
3618 (unsigned long long)dback->parent:
3619 (unsigned long long)dback->root,
3620 (unsigned long long)dback->owner,
3621 (unsigned long long)dback->offset,
3622 (unsigned long)dback->num_refs);
3624 tback = (struct tree_backref *)back;
3625 fprintf(stderr, "Backref %llu parent %llu"
3626 " root %llu not found in extent tree\n",
3627 (unsigned long long)rec->start,
3628 (unsigned long long)tback->parent,
3629 (unsigned long long)tback->root);
3632 if (!back->is_data && !back->found_ref) {
3636 tback = (struct tree_backref *)back;
3637 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3638 (unsigned long long)rec->start,
3639 back->full_backref ? "parent" : "root",
3640 back->full_backref ?
3641 (unsigned long long)tback->parent :
3642 (unsigned long long)tback->root, back);
3644 if (back->is_data) {
3645 dback = (struct data_backref *)back;
3646 if (dback->found_ref != dback->num_refs) {
3650 fprintf(stderr, "Incorrect local backref count"
3651 " on %llu %s %llu owner %llu"
3652 " offset %llu found %u wanted %u back %p\n",
3653 (unsigned long long)rec->start,
3654 back->full_backref ?
3656 back->full_backref ?
3657 (unsigned long long)dback->parent:
3658 (unsigned long long)dback->root,
3659 (unsigned long long)dback->owner,
3660 (unsigned long long)dback->offset,
3661 dback->found_ref, dback->num_refs, back);
3663 if (dback->disk_bytenr != rec->start) {
3667 fprintf(stderr, "Backref disk bytenr does not"
3668 " match extent record, bytenr=%llu, "
3669 "ref bytenr=%llu\n",
3670 (unsigned long long)rec->start,
3671 (unsigned long long)dback->disk_bytenr);
3674 if (dback->bytes != rec->nr) {
3678 fprintf(stderr, "Backref bytes do not match "
3679 "extent backref, bytenr=%llu, ref "
3680 "bytes=%llu, backref bytes=%llu\n",
3681 (unsigned long long)rec->start,
3682 (unsigned long long)rec->nr,
3683 (unsigned long long)dback->bytes);
3686 if (!back->is_data) {
3689 dback = (struct data_backref *)back;
3690 found += dback->found_ref;
3693 if (found != rec->refs) {
3697 fprintf(stderr, "Incorrect global backref count "
3698 "on %llu found %llu wanted %llu\n",
3699 (unsigned long long)rec->start,
3700 (unsigned long long)found,
3701 (unsigned long long)rec->refs);
3707 static int free_all_extent_backrefs(struct extent_record *rec)
3709 struct extent_backref *back;
3710 struct list_head *cur;
3711 while (!list_empty(&rec->backrefs)) {
3712 cur = rec->backrefs.next;
3713 back = list_entry(cur, struct extent_backref, list);
3720 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3721 struct cache_tree *extent_cache)
3723 struct cache_extent *cache;
3724 struct extent_record *rec;
3727 cache = first_cache_extent(extent_cache);
3730 rec = container_of(cache, struct extent_record, cache);
3731 remove_cache_extent(extent_cache, cache);
3732 free_all_extent_backrefs(rec);
3737 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3738 struct extent_record *rec)
3740 if (rec->content_checked && rec->owner_ref_checked &&
3741 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3742 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3743 !rec->bad_full_backref && !rec->crossing_stripes) {
3744 remove_cache_extent(extent_cache, &rec->cache);
3745 free_all_extent_backrefs(rec);
3746 list_del_init(&rec->list);
3752 static int check_owner_ref(struct btrfs_root *root,
3753 struct extent_record *rec,
3754 struct extent_buffer *buf)
3756 struct extent_backref *node;
3757 struct tree_backref *back;
3758 struct btrfs_root *ref_root;
3759 struct btrfs_key key;
3760 struct btrfs_path path;
3761 struct extent_buffer *parent;
3766 list_for_each_entry(node, &rec->backrefs, list) {
3769 if (!node->found_ref)
3771 if (node->full_backref)
3773 back = (struct tree_backref *)node;
3774 if (btrfs_header_owner(buf) == back->root)
3777 BUG_ON(rec->is_root);
3779 /* try to find the block by search corresponding fs tree */
3780 key.objectid = btrfs_header_owner(buf);
3781 key.type = BTRFS_ROOT_ITEM_KEY;
3782 key.offset = (u64)-1;
3784 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3785 if (IS_ERR(ref_root))
3788 level = btrfs_header_level(buf);
3790 btrfs_item_key_to_cpu(buf, &key, 0);
3792 btrfs_node_key_to_cpu(buf, &key, 0);
3794 btrfs_init_path(&path);
3795 path.lowest_level = level + 1;
3796 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3800 parent = path.nodes[level + 1];
3801 if (parent && buf->start == btrfs_node_blockptr(parent,
3802 path.slots[level + 1]))
3805 btrfs_release_path(&path);
3806 return found ? 0 : 1;
3809 static int is_extent_tree_record(struct extent_record *rec)
3811 struct list_head *cur = rec->backrefs.next;
3812 struct extent_backref *node;
3813 struct tree_backref *back;
3816 while(cur != &rec->backrefs) {
3817 node = list_entry(cur, struct extent_backref, list);
3821 back = (struct tree_backref *)node;
3822 if (node->full_backref)
3824 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3831 static int record_bad_block_io(struct btrfs_fs_info *info,
3832 struct cache_tree *extent_cache,
3835 struct extent_record *rec;
3836 struct cache_extent *cache;
3837 struct btrfs_key key;
3839 cache = lookup_cache_extent(extent_cache, start, len);
3843 rec = container_of(cache, struct extent_record, cache);
3844 if (!is_extent_tree_record(rec))
3847 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3848 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3851 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3852 struct extent_buffer *buf, int slot)
3854 if (btrfs_header_level(buf)) {
3855 struct btrfs_key_ptr ptr1, ptr2;
3857 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3858 sizeof(struct btrfs_key_ptr));
3859 read_extent_buffer(buf, &ptr2,
3860 btrfs_node_key_ptr_offset(slot + 1),
3861 sizeof(struct btrfs_key_ptr));
3862 write_extent_buffer(buf, &ptr1,
3863 btrfs_node_key_ptr_offset(slot + 1),
3864 sizeof(struct btrfs_key_ptr));
3865 write_extent_buffer(buf, &ptr2,
3866 btrfs_node_key_ptr_offset(slot),
3867 sizeof(struct btrfs_key_ptr));
3869 struct btrfs_disk_key key;
3870 btrfs_node_key(buf, &key, 0);
3871 btrfs_fixup_low_keys(root, path, &key,
3872 btrfs_header_level(buf) + 1);
3875 struct btrfs_item *item1, *item2;
3876 struct btrfs_key k1, k2;
3877 char *item1_data, *item2_data;
3878 u32 item1_offset, item2_offset, item1_size, item2_size;
3880 item1 = btrfs_item_nr(slot);
3881 item2 = btrfs_item_nr(slot + 1);
3882 btrfs_item_key_to_cpu(buf, &k1, slot);
3883 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3884 item1_offset = btrfs_item_offset(buf, item1);
3885 item2_offset = btrfs_item_offset(buf, item2);
3886 item1_size = btrfs_item_size(buf, item1);
3887 item2_size = btrfs_item_size(buf, item2);
3889 item1_data = malloc(item1_size);
3892 item2_data = malloc(item2_size);
3898 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3899 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3901 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3902 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3906 btrfs_set_item_offset(buf, item1, item2_offset);
3907 btrfs_set_item_offset(buf, item2, item1_offset);
3908 btrfs_set_item_size(buf, item1, item2_size);
3909 btrfs_set_item_size(buf, item2, item1_size);
3911 path->slots[0] = slot;
3912 btrfs_set_item_key_unsafe(root, path, &k2);
3913 path->slots[0] = slot + 1;
3914 btrfs_set_item_key_unsafe(root, path, &k1);
3919 static int fix_key_order(struct btrfs_trans_handle *trans,
3920 struct btrfs_root *root,
3921 struct btrfs_path *path)
3923 struct extent_buffer *buf;
3924 struct btrfs_key k1, k2;
3926 int level = path->lowest_level;
3929 buf = path->nodes[level];
3930 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3932 btrfs_node_key_to_cpu(buf, &k1, i);
3933 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3935 btrfs_item_key_to_cpu(buf, &k1, i);
3936 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3938 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3940 ret = swap_values(root, path, buf, i);
3943 btrfs_mark_buffer_dirty(buf);
3949 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3950 struct btrfs_root *root,
3951 struct btrfs_path *path,
3952 struct extent_buffer *buf, int slot)
3954 struct btrfs_key key;
3955 int nritems = btrfs_header_nritems(buf);
3957 btrfs_item_key_to_cpu(buf, &key, slot);
3959 /* These are all the keys we can deal with missing. */
3960 if (key.type != BTRFS_DIR_INDEX_KEY &&
3961 key.type != BTRFS_EXTENT_ITEM_KEY &&
3962 key.type != BTRFS_METADATA_ITEM_KEY &&
3963 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3964 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3967 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3968 (unsigned long long)key.objectid, key.type,
3969 (unsigned long long)key.offset, slot, buf->start);
3970 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3971 btrfs_item_nr_offset(slot + 1),
3972 sizeof(struct btrfs_item) *
3973 (nritems - slot - 1));
3974 btrfs_set_header_nritems(buf, nritems - 1);
3976 struct btrfs_disk_key disk_key;
3978 btrfs_item_key(buf, &disk_key, 0);
3979 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3981 btrfs_mark_buffer_dirty(buf);
3985 static int fix_item_offset(struct btrfs_trans_handle *trans,
3986 struct btrfs_root *root,
3987 struct btrfs_path *path)
3989 struct extent_buffer *buf;
3993 /* We should only get this for leaves */
3994 BUG_ON(path->lowest_level);
3995 buf = path->nodes[0];
3997 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3998 unsigned int shift = 0, offset;
4000 if (i == 0 && btrfs_item_end_nr(buf, i) !=
4001 BTRFS_LEAF_DATA_SIZE(root)) {
4002 if (btrfs_item_end_nr(buf, i) >
4003 BTRFS_LEAF_DATA_SIZE(root)) {
4004 ret = delete_bogus_item(trans, root, path,
4008 fprintf(stderr, "item is off the end of the "
4009 "leaf, can't fix\n");
4013 shift = BTRFS_LEAF_DATA_SIZE(root) -
4014 btrfs_item_end_nr(buf, i);
4015 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
4016 btrfs_item_offset_nr(buf, i - 1)) {
4017 if (btrfs_item_end_nr(buf, i) >
4018 btrfs_item_offset_nr(buf, i - 1)) {
4019 ret = delete_bogus_item(trans, root, path,
4023 fprintf(stderr, "items overlap, can't fix\n");
4027 shift = btrfs_item_offset_nr(buf, i - 1) -
4028 btrfs_item_end_nr(buf, i);
4033 printf("Shifting item nr %d by %u bytes in block %llu\n",
4034 i, shift, (unsigned long long)buf->start);
4035 offset = btrfs_item_offset_nr(buf, i);
4036 memmove_extent_buffer(buf,
4037 btrfs_leaf_data(buf) + offset + shift,
4038 btrfs_leaf_data(buf) + offset,
4039 btrfs_item_size_nr(buf, i));
4040 btrfs_set_item_offset(buf, btrfs_item_nr(i),
4042 btrfs_mark_buffer_dirty(buf);
4046 * We may have moved things, in which case we want to exit so we don't
4047 * write those changes out. Once we have proper abort functionality in
4048 * progs this can be changed to something nicer.
4055 * Attempt to fix basic block failures. If we can't fix it for whatever reason
4056 * then just return -EIO.
4058 static int try_to_fix_bad_block(struct btrfs_root *root,
4059 struct extent_buffer *buf,
4060 enum btrfs_tree_block_status status)
4062 struct btrfs_trans_handle *trans;
4063 struct ulist *roots;
4064 struct ulist_node *node;
4065 struct btrfs_root *search_root;
4066 struct btrfs_path *path;
4067 struct ulist_iterator iter;
4068 struct btrfs_key root_key, key;
4071 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4072 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4075 path = btrfs_alloc_path();
4079 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4082 btrfs_free_path(path);
4086 ULIST_ITER_INIT(&iter);
4087 while ((node = ulist_next(roots, &iter))) {
4088 root_key.objectid = node->val;
4089 root_key.type = BTRFS_ROOT_ITEM_KEY;
4090 root_key.offset = (u64)-1;
4092 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4099 trans = btrfs_start_transaction(search_root, 0);
4100 if (IS_ERR(trans)) {
4101 ret = PTR_ERR(trans);
4105 path->lowest_level = btrfs_header_level(buf);
4106 path->skip_check_block = 1;
4107 if (path->lowest_level)
4108 btrfs_node_key_to_cpu(buf, &key, 0);
4110 btrfs_item_key_to_cpu(buf, &key, 0);
4111 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4114 btrfs_commit_transaction(trans, search_root);
4117 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4118 ret = fix_key_order(trans, search_root, path);
4119 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4120 ret = fix_item_offset(trans, search_root, path);
4122 btrfs_commit_transaction(trans, search_root);
4125 btrfs_release_path(path);
4126 btrfs_commit_transaction(trans, search_root);
4129 btrfs_free_path(path);
4133 static int check_block(struct btrfs_root *root,
4134 struct cache_tree *extent_cache,
4135 struct extent_buffer *buf, u64 flags)
4137 struct extent_record *rec;
4138 struct cache_extent *cache;
4139 struct btrfs_key key;
4140 enum btrfs_tree_block_status status;
4144 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4147 rec = container_of(cache, struct extent_record, cache);
4148 rec->generation = btrfs_header_generation(buf);
4150 level = btrfs_header_level(buf);
4151 if (btrfs_header_nritems(buf) > 0) {
4154 btrfs_item_key_to_cpu(buf, &key, 0);
4156 btrfs_node_key_to_cpu(buf, &key, 0);
4158 rec->info_objectid = key.objectid;
4160 rec->info_level = level;
4162 if (btrfs_is_leaf(buf))
4163 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4165 status = btrfs_check_node(root, &rec->parent_key, buf);
4167 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4169 status = try_to_fix_bad_block(root, buf, status);
4170 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4172 fprintf(stderr, "bad block %llu\n",
4173 (unsigned long long)buf->start);
4176 * Signal to callers we need to start the scan over
4177 * again since we'll have cow'ed blocks.
4182 rec->content_checked = 1;
4183 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4184 rec->owner_ref_checked = 1;
4186 ret = check_owner_ref(root, rec, buf);
4188 rec->owner_ref_checked = 1;
4192 maybe_free_extent_rec(extent_cache, rec);
4196 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4197 u64 parent, u64 root)
4199 struct list_head *cur = rec->backrefs.next;
4200 struct extent_backref *node;
4201 struct tree_backref *back;
4203 while(cur != &rec->backrefs) {
4204 node = list_entry(cur, struct extent_backref, list);
4208 back = (struct tree_backref *)node;
4210 if (!node->full_backref)
4212 if (parent == back->parent)
4215 if (node->full_backref)
4217 if (back->root == root)
4224 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4225 u64 parent, u64 root)
4227 struct tree_backref *ref = malloc(sizeof(*ref));
4228 memset(&ref->node, 0, sizeof(ref->node));
4230 ref->parent = parent;
4231 ref->node.full_backref = 1;
4234 ref->node.full_backref = 0;
4236 list_add_tail(&ref->node.list, &rec->backrefs);
4241 static struct data_backref *find_data_backref(struct extent_record *rec,
4242 u64 parent, u64 root,
4243 u64 owner, u64 offset,
4245 u64 disk_bytenr, u64 bytes)
4247 struct list_head *cur = rec->backrefs.next;
4248 struct extent_backref *node;
4249 struct data_backref *back;
4251 while(cur != &rec->backrefs) {
4252 node = list_entry(cur, struct extent_backref, list);
4256 back = (struct data_backref *)node;
4258 if (!node->full_backref)
4260 if (parent == back->parent)
4263 if (node->full_backref)
4265 if (back->root == root && back->owner == owner &&
4266 back->offset == offset) {
4267 if (found_ref && node->found_ref &&
4268 (back->bytes != bytes ||
4269 back->disk_bytenr != disk_bytenr))
4278 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4279 u64 parent, u64 root,
4280 u64 owner, u64 offset,
4283 struct data_backref *ref = malloc(sizeof(*ref));
4284 memset(&ref->node, 0, sizeof(ref->node));
4285 ref->node.is_data = 1;
4288 ref->parent = parent;
4291 ref->node.full_backref = 1;
4295 ref->offset = offset;
4296 ref->node.full_backref = 0;
4298 ref->bytes = max_size;
4301 list_add_tail(&ref->node.list, &rec->backrefs);
4302 if (max_size > rec->max_size)
4303 rec->max_size = max_size;
4307 static int add_extent_rec(struct cache_tree *extent_cache,
4308 struct btrfs_key *parent_key, u64 parent_gen,
4309 u64 start, u64 nr, u64 extent_item_refs,
4310 int is_root, int inc_ref, int set_checked,
4311 int metadata, int extent_rec, u64 max_size)
4313 struct extent_record *rec;
4314 struct cache_extent *cache;
4318 cache = lookup_cache_extent(extent_cache, start, nr);
4320 rec = container_of(cache, struct extent_record, cache);
4324 rec->nr = max(nr, max_size);
4327 * We need to make sure to reset nr to whatever the extent
4328 * record says was the real size, this way we can compare it to
4332 if (start != rec->start || rec->found_rec) {
4333 struct extent_record *tmp;
4336 if (list_empty(&rec->list))
4337 list_add_tail(&rec->list,
4338 &duplicate_extents);
4341 * We have to do this song and dance in case we
4342 * find an extent record that falls inside of
4343 * our current extent record but does not have
4344 * the same objectid.
4346 tmp = malloc(sizeof(*tmp));
4350 tmp->max_size = max_size;
4353 tmp->metadata = metadata;
4354 tmp->extent_item_refs = extent_item_refs;
4355 INIT_LIST_HEAD(&tmp->list);
4356 list_add_tail(&tmp->list, &rec->dups);
4357 rec->num_duplicates++;
4364 if (extent_item_refs && !dup) {
4365 if (rec->extent_item_refs) {
4366 fprintf(stderr, "block %llu rec "
4367 "extent_item_refs %llu, passed %llu\n",
4368 (unsigned long long)start,
4369 (unsigned long long)
4370 rec->extent_item_refs,
4371 (unsigned long long)extent_item_refs);
4373 rec->extent_item_refs = extent_item_refs;
4378 rec->content_checked = 1;
4379 rec->owner_ref_checked = 1;
4383 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4385 rec->parent_generation = parent_gen;
4387 if (rec->max_size < max_size)
4388 rec->max_size = max_size;
4391 * A metadata extent can't cross stripe_len boundary, otherwise
4392 * kernel scrub won't be able to handle it.
4393 * As now stripe_len is fixed to BTRFS_STRIPE_LEN, just check
4396 if (metadata && check_crossing_stripes(rec->start,
4398 rec->crossing_stripes = 1;
4399 maybe_free_extent_rec(extent_cache, rec);
4402 rec = malloc(sizeof(*rec));
4404 rec->max_size = max_size;
4405 rec->nr = max(nr, max_size);
4406 rec->found_rec = !!extent_rec;
4407 rec->content_checked = 0;
4408 rec->owner_ref_checked = 0;
4409 rec->num_duplicates = 0;
4410 rec->metadata = metadata;
4411 rec->flag_block_full_backref = -1;
4412 rec->bad_full_backref = 0;
4413 INIT_LIST_HEAD(&rec->backrefs);
4414 INIT_LIST_HEAD(&rec->dups);
4415 INIT_LIST_HEAD(&rec->list);
4427 if (extent_item_refs)
4428 rec->extent_item_refs = extent_item_refs;
4430 rec->extent_item_refs = 0;
4433 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4435 memset(&rec->parent_key, 0, sizeof(*parent_key));
4438 rec->parent_generation = parent_gen;
4440 rec->parent_generation = 0;
4442 rec->cache.start = start;
4443 rec->cache.size = nr;
4444 ret = insert_cache_extent(extent_cache, &rec->cache);
4448 rec->content_checked = 1;
4449 rec->owner_ref_checked = 1;
4453 if (check_crossing_stripes(rec->start, rec->max_size))
4454 rec->crossing_stripes = 1;
4458 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4459 u64 parent, u64 root, int found_ref)
4461 struct extent_record *rec;
4462 struct tree_backref *back;
4463 struct cache_extent *cache;
4465 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4467 add_extent_rec(extent_cache, NULL, 0, bytenr,
4468 1, 0, 0, 0, 0, 1, 0, 0);
4469 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4474 rec = container_of(cache, struct extent_record, cache);
4475 if (rec->start != bytenr) {
4479 back = find_tree_backref(rec, parent, root);
4481 back = alloc_tree_backref(rec, parent, root);
4484 if (back->node.found_ref) {
4485 fprintf(stderr, "Extent back ref already exists "
4486 "for %llu parent %llu root %llu \n",
4487 (unsigned long long)bytenr,
4488 (unsigned long long)parent,
4489 (unsigned long long)root);
4491 back->node.found_ref = 1;
4493 if (back->node.found_extent_tree) {
4494 fprintf(stderr, "Extent back ref already exists "
4495 "for %llu parent %llu root %llu \n",
4496 (unsigned long long)bytenr,
4497 (unsigned long long)parent,
4498 (unsigned long long)root);
4500 back->node.found_extent_tree = 1;
4502 maybe_free_extent_rec(extent_cache, rec);
4506 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4507 u64 parent, u64 root, u64 owner, u64 offset,
4508 u32 num_refs, int found_ref, u64 max_size)
4510 struct extent_record *rec;
4511 struct data_backref *back;
4512 struct cache_extent *cache;
4514 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4516 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4518 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4523 rec = container_of(cache, struct extent_record, cache);
4524 if (rec->max_size < max_size)
4525 rec->max_size = max_size;
4528 * If found_ref is set then max_size is the real size and must match the
4529 * existing refs. So if we have already found a ref then we need to
4530 * make sure that this ref matches the existing one, otherwise we need
4531 * to add a new backref so we can notice that the backrefs don't match
4532 * and we need to figure out who is telling the truth. This is to
4533 * account for that awful fsync bug I introduced where we'd end up with
4534 * a btrfs_file_extent_item that would have its length include multiple
4535 * prealloc extents or point inside of a prealloc extent.
4537 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4540 back = alloc_data_backref(rec, parent, root, owner, offset,
4544 BUG_ON(num_refs != 1);
4545 if (back->node.found_ref)
4546 BUG_ON(back->bytes != max_size);
4547 back->node.found_ref = 1;
4548 back->found_ref += 1;
4549 back->bytes = max_size;
4550 back->disk_bytenr = bytenr;
4552 rec->content_checked = 1;
4553 rec->owner_ref_checked = 1;
4555 if (back->node.found_extent_tree) {
4556 fprintf(stderr, "Extent back ref already exists "
4557 "for %llu parent %llu root %llu "
4558 "owner %llu offset %llu num_refs %lu\n",
4559 (unsigned long long)bytenr,
4560 (unsigned long long)parent,
4561 (unsigned long long)root,
4562 (unsigned long long)owner,
4563 (unsigned long long)offset,
4564 (unsigned long)num_refs);
4566 back->num_refs = num_refs;
4567 back->node.found_extent_tree = 1;
4569 maybe_free_extent_rec(extent_cache, rec);
4573 static int add_pending(struct cache_tree *pending,
4574 struct cache_tree *seen, u64 bytenr, u32 size)
4577 ret = add_cache_extent(seen, bytenr, size);
4580 add_cache_extent(pending, bytenr, size);
4584 static int pick_next_pending(struct cache_tree *pending,
4585 struct cache_tree *reada,
4586 struct cache_tree *nodes,
4587 u64 last, struct block_info *bits, int bits_nr,
4590 unsigned long node_start = last;
4591 struct cache_extent *cache;
4594 cache = search_cache_extent(reada, 0);
4596 bits[0].start = cache->start;
4597 bits[0].size = cache->size;
4602 if (node_start > 32768)
4603 node_start -= 32768;
4605 cache = search_cache_extent(nodes, node_start);
4607 cache = search_cache_extent(nodes, 0);
4610 cache = search_cache_extent(pending, 0);
4615 bits[ret].start = cache->start;
4616 bits[ret].size = cache->size;
4617 cache = next_cache_extent(cache);
4619 } while (cache && ret < bits_nr);
4625 bits[ret].start = cache->start;
4626 bits[ret].size = cache->size;
4627 cache = next_cache_extent(cache);
4629 } while (cache && ret < bits_nr);
4631 if (bits_nr - ret > 8) {
4632 u64 lookup = bits[0].start + bits[0].size;
4633 struct cache_extent *next;
4634 next = search_cache_extent(pending, lookup);
4636 if (next->start - lookup > 32768)
4638 bits[ret].start = next->start;
4639 bits[ret].size = next->size;
4640 lookup = next->start + next->size;
4644 next = next_cache_extent(next);
4652 static void free_chunk_record(struct cache_extent *cache)
4654 struct chunk_record *rec;
4656 rec = container_of(cache, struct chunk_record, cache);
4657 list_del_init(&rec->list);
4658 list_del_init(&rec->dextents);
4662 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4664 cache_tree_free_extents(chunk_cache, free_chunk_record);
4667 static void free_device_record(struct rb_node *node)
4669 struct device_record *rec;
4671 rec = container_of(node, struct device_record, node);
4675 FREE_RB_BASED_TREE(device_cache, free_device_record);
4677 int insert_block_group_record(struct block_group_tree *tree,
4678 struct block_group_record *bg_rec)
4682 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4686 list_add_tail(&bg_rec->list, &tree->block_groups);
4690 static void free_block_group_record(struct cache_extent *cache)
4692 struct block_group_record *rec;
4694 rec = container_of(cache, struct block_group_record, cache);
4695 list_del_init(&rec->list);
4699 void free_block_group_tree(struct block_group_tree *tree)
4701 cache_tree_free_extents(&tree->tree, free_block_group_record);
4704 int insert_device_extent_record(struct device_extent_tree *tree,
4705 struct device_extent_record *de_rec)
4710 * Device extent is a bit different from the other extents, because
4711 * the extents which belong to the different devices may have the
4712 * same start and size, so we need use the special extent cache
4713 * search/insert functions.
4715 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4719 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4720 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4724 static void free_device_extent_record(struct cache_extent *cache)
4726 struct device_extent_record *rec;
4728 rec = container_of(cache, struct device_extent_record, cache);
4729 if (!list_empty(&rec->chunk_list))
4730 list_del_init(&rec->chunk_list);
4731 if (!list_empty(&rec->device_list))
4732 list_del_init(&rec->device_list);
4736 void free_device_extent_tree(struct device_extent_tree *tree)
4738 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4741 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4742 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4743 struct extent_buffer *leaf, int slot)
4745 struct btrfs_extent_ref_v0 *ref0;
4746 struct btrfs_key key;
4748 btrfs_item_key_to_cpu(leaf, &key, slot);
4749 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4750 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4751 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4753 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4754 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4760 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4761 struct btrfs_key *key,
4764 struct btrfs_chunk *ptr;
4765 struct chunk_record *rec;
4768 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4769 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4771 rec = malloc(btrfs_chunk_record_size(num_stripes));
4773 fprintf(stderr, "memory allocation failed\n");
4777 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4779 INIT_LIST_HEAD(&rec->list);
4780 INIT_LIST_HEAD(&rec->dextents);
4783 rec->cache.start = key->offset;
4784 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4786 rec->generation = btrfs_header_generation(leaf);
4788 rec->objectid = key->objectid;
4789 rec->type = key->type;
4790 rec->offset = key->offset;
4792 rec->length = rec->cache.size;
4793 rec->owner = btrfs_chunk_owner(leaf, ptr);
4794 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4795 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4796 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4797 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4798 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4799 rec->num_stripes = num_stripes;
4800 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4802 for (i = 0; i < rec->num_stripes; ++i) {
4803 rec->stripes[i].devid =
4804 btrfs_stripe_devid_nr(leaf, ptr, i);
4805 rec->stripes[i].offset =
4806 btrfs_stripe_offset_nr(leaf, ptr, i);
4807 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4808 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4815 static int process_chunk_item(struct cache_tree *chunk_cache,
4816 struct btrfs_key *key, struct extent_buffer *eb,
4819 struct chunk_record *rec;
4822 rec = btrfs_new_chunk_record(eb, key, slot);
4823 ret = insert_cache_extent(chunk_cache, &rec->cache);
4825 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4826 rec->offset, rec->length);
4833 static int process_device_item(struct rb_root *dev_cache,
4834 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4836 struct btrfs_dev_item *ptr;
4837 struct device_record *rec;
4840 ptr = btrfs_item_ptr(eb,
4841 slot, struct btrfs_dev_item);
4843 rec = malloc(sizeof(*rec));
4845 fprintf(stderr, "memory allocation failed\n");
4849 rec->devid = key->offset;
4850 rec->generation = btrfs_header_generation(eb);
4852 rec->objectid = key->objectid;
4853 rec->type = key->type;
4854 rec->offset = key->offset;
4856 rec->devid = btrfs_device_id(eb, ptr);
4857 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4858 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4860 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4862 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4869 struct block_group_record *
4870 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4873 struct btrfs_block_group_item *ptr;
4874 struct block_group_record *rec;
4876 rec = malloc(sizeof(*rec));
4878 fprintf(stderr, "memory allocation failed\n");
4881 memset(rec, 0, sizeof(*rec));
4883 rec->cache.start = key->objectid;
4884 rec->cache.size = key->offset;
4886 rec->generation = btrfs_header_generation(leaf);
4888 rec->objectid = key->objectid;
4889 rec->type = key->type;
4890 rec->offset = key->offset;
4892 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4893 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4895 INIT_LIST_HEAD(&rec->list);
4900 static int process_block_group_item(struct block_group_tree *block_group_cache,
4901 struct btrfs_key *key,
4902 struct extent_buffer *eb, int slot)
4904 struct block_group_record *rec;
4907 rec = btrfs_new_block_group_record(eb, key, slot);
4908 ret = insert_block_group_record(block_group_cache, rec);
4910 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4911 rec->objectid, rec->offset);
4918 struct device_extent_record *
4919 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4920 struct btrfs_key *key, int slot)
4922 struct device_extent_record *rec;
4923 struct btrfs_dev_extent *ptr;
4925 rec = malloc(sizeof(*rec));
4927 fprintf(stderr, "memory allocation failed\n");
4930 memset(rec, 0, sizeof(*rec));
4932 rec->cache.objectid = key->objectid;
4933 rec->cache.start = key->offset;
4935 rec->generation = btrfs_header_generation(leaf);
4937 rec->objectid = key->objectid;
4938 rec->type = key->type;
4939 rec->offset = key->offset;
4941 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4942 rec->chunk_objecteid =
4943 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4945 btrfs_dev_extent_chunk_offset(leaf, ptr);
4946 rec->length = btrfs_dev_extent_length(leaf, ptr);
4947 rec->cache.size = rec->length;
4949 INIT_LIST_HEAD(&rec->chunk_list);
4950 INIT_LIST_HEAD(&rec->device_list);
4956 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4957 struct btrfs_key *key, struct extent_buffer *eb,
4960 struct device_extent_record *rec;
4963 rec = btrfs_new_device_extent_record(eb, key, slot);
4964 ret = insert_device_extent_record(dev_extent_cache, rec);
4967 "Device extent[%llu, %llu, %llu] existed.\n",
4968 rec->objectid, rec->offset, rec->length);
4975 static int process_extent_item(struct btrfs_root *root,
4976 struct cache_tree *extent_cache,
4977 struct extent_buffer *eb, int slot)
4979 struct btrfs_extent_item *ei;
4980 struct btrfs_extent_inline_ref *iref;
4981 struct btrfs_extent_data_ref *dref;
4982 struct btrfs_shared_data_ref *sref;
4983 struct btrfs_key key;
4987 u32 item_size = btrfs_item_size_nr(eb, slot);
4993 btrfs_item_key_to_cpu(eb, &key, slot);
4995 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4997 num_bytes = root->leafsize;
4999 num_bytes = key.offset;
5002 if (item_size < sizeof(*ei)) {
5003 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5004 struct btrfs_extent_item_v0 *ei0;
5005 BUG_ON(item_size != sizeof(*ei0));
5006 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
5007 refs = btrfs_extent_refs_v0(eb, ei0);
5011 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
5012 num_bytes, refs, 0, 0, 0, metadata, 1,
5016 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
5017 refs = btrfs_extent_refs(eb, ei);
5019 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
5020 refs, 0, 0, 0, metadata, 1, num_bytes);
5022 ptr = (unsigned long)(ei + 1);
5023 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
5024 key.type == BTRFS_EXTENT_ITEM_KEY)
5025 ptr += sizeof(struct btrfs_tree_block_info);
5027 end = (unsigned long)ei + item_size;
5029 iref = (struct btrfs_extent_inline_ref *)ptr;
5030 type = btrfs_extent_inline_ref_type(eb, iref);
5031 offset = btrfs_extent_inline_ref_offset(eb, iref);
5033 case BTRFS_TREE_BLOCK_REF_KEY:
5034 add_tree_backref(extent_cache, key.objectid,
5037 case BTRFS_SHARED_BLOCK_REF_KEY:
5038 add_tree_backref(extent_cache, key.objectid,
5041 case BTRFS_EXTENT_DATA_REF_KEY:
5042 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
5043 add_data_backref(extent_cache, key.objectid, 0,
5044 btrfs_extent_data_ref_root(eb, dref),
5045 btrfs_extent_data_ref_objectid(eb,
5047 btrfs_extent_data_ref_offset(eb, dref),
5048 btrfs_extent_data_ref_count(eb, dref),
5051 case BTRFS_SHARED_DATA_REF_KEY:
5052 sref = (struct btrfs_shared_data_ref *)(iref + 1);
5053 add_data_backref(extent_cache, key.objectid, offset,
5055 btrfs_shared_data_ref_count(eb, sref),
5059 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
5060 key.objectid, key.type, num_bytes);
5063 ptr += btrfs_extent_inline_ref_size(type);
5070 static int check_cache_range(struct btrfs_root *root,
5071 struct btrfs_block_group_cache *cache,
5072 u64 offset, u64 bytes)
5074 struct btrfs_free_space *entry;
5080 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5081 bytenr = btrfs_sb_offset(i);
5082 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5083 cache->key.objectid, bytenr, 0,
5084 &logical, &nr, &stripe_len);
5089 if (logical[nr] + stripe_len <= offset)
5091 if (offset + bytes <= logical[nr])
5093 if (logical[nr] == offset) {
5094 if (stripe_len >= bytes) {
5098 bytes -= stripe_len;
5099 offset += stripe_len;
5100 } else if (logical[nr] < offset) {
5101 if (logical[nr] + stripe_len >=
5106 bytes = (offset + bytes) -
5107 (logical[nr] + stripe_len);
5108 offset = logical[nr] + stripe_len;
5111 * Could be tricky, the super may land in the
5112 * middle of the area we're checking. First
5113 * check the easiest case, it's at the end.
5115 if (logical[nr] + stripe_len >=
5117 bytes = logical[nr] - offset;
5121 /* Check the left side */
5122 ret = check_cache_range(root, cache,
5124 logical[nr] - offset);
5130 /* Now we continue with the right side */
5131 bytes = (offset + bytes) -
5132 (logical[nr] + stripe_len);
5133 offset = logical[nr] + stripe_len;
5140 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5142 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5143 offset, offset+bytes);
5147 if (entry->offset != offset) {
5148 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5153 if (entry->bytes != bytes) {
5154 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5155 bytes, entry->bytes, offset);
5159 unlink_free_space(cache->free_space_ctl, entry);
5164 static int verify_space_cache(struct btrfs_root *root,
5165 struct btrfs_block_group_cache *cache)
5167 struct btrfs_path *path;
5168 struct extent_buffer *leaf;
5169 struct btrfs_key key;
5173 path = btrfs_alloc_path();
5177 root = root->fs_info->extent_root;
5179 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5181 key.objectid = last;
5183 key.type = BTRFS_EXTENT_ITEM_KEY;
5185 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5190 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5191 ret = btrfs_next_leaf(root, path);
5199 leaf = path->nodes[0];
5200 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5201 if (key.objectid >= cache->key.offset + cache->key.objectid)
5203 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5204 key.type != BTRFS_METADATA_ITEM_KEY) {
5209 if (last == key.objectid) {
5210 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5211 last = key.objectid + key.offset;
5213 last = key.objectid + root->leafsize;
5218 ret = check_cache_range(root, cache, last,
5219 key.objectid - last);
5222 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5223 last = key.objectid + key.offset;
5225 last = key.objectid + root->leafsize;
5229 if (last < cache->key.objectid + cache->key.offset)
5230 ret = check_cache_range(root, cache, last,
5231 cache->key.objectid +
5232 cache->key.offset - last);
5235 btrfs_free_path(path);
5238 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5239 fprintf(stderr, "There are still entries left in the space "
5247 static int check_space_cache(struct btrfs_root *root)
5249 struct btrfs_block_group_cache *cache;
5250 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5254 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5255 btrfs_super_generation(root->fs_info->super_copy) !=
5256 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5257 printf("cache and super generation don't match, space cache "
5258 "will be invalidated\n");
5263 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5267 start = cache->key.objectid + cache->key.offset;
5268 if (!cache->free_space_ctl) {
5269 if (btrfs_init_free_space_ctl(cache,
5270 root->sectorsize)) {
5275 btrfs_remove_free_space_cache(cache);
5278 ret = load_free_space_cache(root->fs_info, cache);
5282 ret = verify_space_cache(root, cache);
5284 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5285 cache->key.objectid);
5290 return error ? -EINVAL : 0;
5293 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5294 u64 num_bytes, unsigned long leaf_offset,
5295 struct extent_buffer *eb) {
5298 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5300 unsigned long csum_offset;
5304 u64 data_checked = 0;
5310 if (num_bytes % root->sectorsize)
5313 data = malloc(num_bytes);
5317 while (offset < num_bytes) {
5320 read_len = num_bytes - offset;
5321 /* read as much space once a time */
5322 ret = read_extent_data(root, data + offset,
5323 bytenr + offset, &read_len, mirror);
5327 /* verify every 4k data's checksum */
5328 while (data_checked < read_len) {
5330 tmp = offset + data_checked;
5332 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5333 csum, root->sectorsize);
5334 btrfs_csum_final(csum, (char *)&csum);
5336 csum_offset = leaf_offset +
5337 tmp / root->sectorsize * csum_size;
5338 read_extent_buffer(eb, (char *)&csum_expected,
5339 csum_offset, csum_size);
5340 /* try another mirror */
5341 if (csum != csum_expected) {
5342 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5343 mirror, bytenr + tmp,
5344 csum, csum_expected);
5345 num_copies = btrfs_num_copies(
5346 &root->fs_info->mapping_tree,
5348 if (mirror < num_copies - 1) {
5353 data_checked += root->sectorsize;
5362 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5365 struct btrfs_path *path;
5366 struct extent_buffer *leaf;
5367 struct btrfs_key key;
5370 path = btrfs_alloc_path();
5372 fprintf(stderr, "Error allocing path\n");
5376 key.objectid = bytenr;
5377 key.type = BTRFS_EXTENT_ITEM_KEY;
5378 key.offset = (u64)-1;
5381 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5384 fprintf(stderr, "Error looking up extent record %d\n", ret);
5385 btrfs_free_path(path);
5388 if (path->slots[0] > 0) {
5391 ret = btrfs_prev_leaf(root, path);
5394 } else if (ret > 0) {
5401 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5404 * Block group items come before extent items if they have the same
5405 * bytenr, so walk back one more just in case. Dear future traveler,
5406 * first congrats on mastering time travel. Now if it's not too much
5407 * trouble could you go back to 2006 and tell Chris to make the
5408 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5409 * EXTENT_ITEM_KEY please?
5411 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5412 if (path->slots[0] > 0) {
5415 ret = btrfs_prev_leaf(root, path);
5418 } else if (ret > 0) {
5423 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5427 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5428 ret = btrfs_next_leaf(root, path);
5430 fprintf(stderr, "Error going to next leaf "
5432 btrfs_free_path(path);
5438 leaf = path->nodes[0];
5439 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5440 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5444 if (key.objectid + key.offset < bytenr) {
5448 if (key.objectid > bytenr + num_bytes)
5451 if (key.objectid == bytenr) {
5452 if (key.offset >= num_bytes) {
5456 num_bytes -= key.offset;
5457 bytenr += key.offset;
5458 } else if (key.objectid < bytenr) {
5459 if (key.objectid + key.offset >= bytenr + num_bytes) {
5463 num_bytes = (bytenr + num_bytes) -
5464 (key.objectid + key.offset);
5465 bytenr = key.objectid + key.offset;
5467 if (key.objectid + key.offset < bytenr + num_bytes) {
5468 u64 new_start = key.objectid + key.offset;
5469 u64 new_bytes = bytenr + num_bytes - new_start;
5472 * Weird case, the extent is in the middle of
5473 * our range, we'll have to search one side
5474 * and then the other. Not sure if this happens
5475 * in real life, but no harm in coding it up
5476 * anyway just in case.
5478 btrfs_release_path(path);
5479 ret = check_extent_exists(root, new_start,
5482 fprintf(stderr, "Right section didn't "
5486 num_bytes = key.objectid - bytenr;
5489 num_bytes = key.objectid - bytenr;
5496 if (num_bytes && !ret) {
5497 fprintf(stderr, "There are no extents for csum range "
5498 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5502 btrfs_free_path(path);
5506 static int check_csums(struct btrfs_root *root)
5508 struct btrfs_path *path;
5509 struct extent_buffer *leaf;
5510 struct btrfs_key key;
5511 u64 offset = 0, num_bytes = 0;
5512 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5516 unsigned long leaf_offset;
5518 root = root->fs_info->csum_root;
5519 if (!extent_buffer_uptodate(root->node)) {
5520 fprintf(stderr, "No valid csum tree found\n");
5524 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5525 key.type = BTRFS_EXTENT_CSUM_KEY;
5528 path = btrfs_alloc_path();
5532 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5534 fprintf(stderr, "Error searching csum tree %d\n", ret);
5535 btrfs_free_path(path);
5539 if (ret > 0 && path->slots[0])
5544 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5545 ret = btrfs_next_leaf(root, path);
5547 fprintf(stderr, "Error going to next leaf "
5554 leaf = path->nodes[0];
5556 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5557 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5562 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5563 csum_size) * root->sectorsize;
5564 if (!check_data_csum)
5565 goto skip_csum_check;
5566 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5567 ret = check_extent_csums(root, key.offset, data_len,
5573 offset = key.offset;
5574 } else if (key.offset != offset + num_bytes) {
5575 ret = check_extent_exists(root, offset, num_bytes);
5577 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5578 "there is no extent record\n",
5579 offset, offset+num_bytes);
5582 offset = key.offset;
5585 num_bytes += data_len;
5589 btrfs_free_path(path);
5593 static int is_dropped_key(struct btrfs_key *key,
5594 struct btrfs_key *drop_key) {
5595 if (key->objectid < drop_key->objectid)
5597 else if (key->objectid == drop_key->objectid) {
5598 if (key->type < drop_key->type)
5600 else if (key->type == drop_key->type) {
5601 if (key->offset < drop_key->offset)
5609 * Here are the rules for FULL_BACKREF.
5611 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5612 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5614 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5615 * if it happened after the relocation occurred since we'll have dropped the
5616 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5617 * have no real way to know for sure.
5619 * We process the blocks one root at a time, and we start from the lowest root
5620 * objectid and go to the highest. So we can just lookup the owner backref for
5621 * the record and if we don't find it then we know it doesn't exist and we have
5624 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5625 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5626 * be set or not and then we can check later once we've gathered all the refs.
5628 static int calc_extent_flag(struct btrfs_root *root,
5629 struct cache_tree *extent_cache,
5630 struct extent_buffer *buf,
5631 struct root_item_record *ri,
5634 struct extent_record *rec;
5635 struct cache_extent *cache;
5636 struct tree_backref *tback;
5639 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5640 /* we have added this extent before */
5642 rec = container_of(cache, struct extent_record, cache);
5645 * Except file/reloc tree, we can not have
5648 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5653 if (buf->start == ri->bytenr)
5656 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5659 owner = btrfs_header_owner(buf);
5660 if (owner == ri->objectid)
5663 tback = find_tree_backref(rec, 0, owner);
5668 if (rec->flag_block_full_backref != -1 &&
5669 rec->flag_block_full_backref != 0)
5670 rec->bad_full_backref = 1;
5673 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5674 if (rec->flag_block_full_backref != -1 &&
5675 rec->flag_block_full_backref != 1)
5676 rec->bad_full_backref = 1;
5680 static int run_next_block(struct btrfs_root *root,
5681 struct block_info *bits,
5684 struct cache_tree *pending,
5685 struct cache_tree *seen,
5686 struct cache_tree *reada,
5687 struct cache_tree *nodes,
5688 struct cache_tree *extent_cache,
5689 struct cache_tree *chunk_cache,
5690 struct rb_root *dev_cache,
5691 struct block_group_tree *block_group_cache,
5692 struct device_extent_tree *dev_extent_cache,
5693 struct root_item_record *ri)
5695 struct extent_buffer *buf;
5696 struct extent_record *rec = NULL;
5707 struct btrfs_key key;
5708 struct cache_extent *cache;
5711 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5712 bits_nr, &reada_bits);
5717 for(i = 0; i < nritems; i++) {
5718 ret = add_cache_extent(reada, bits[i].start,
5723 /* fixme, get the parent transid */
5724 readahead_tree_block(root, bits[i].start,
5728 *last = bits[0].start;
5729 bytenr = bits[0].start;
5730 size = bits[0].size;
5732 cache = lookup_cache_extent(pending, bytenr, size);
5734 remove_cache_extent(pending, cache);
5737 cache = lookup_cache_extent(reada, bytenr, size);
5739 remove_cache_extent(reada, cache);
5742 cache = lookup_cache_extent(nodes, bytenr, size);
5744 remove_cache_extent(nodes, cache);
5747 cache = lookup_cache_extent(extent_cache, bytenr, size);
5749 rec = container_of(cache, struct extent_record, cache);
5750 gen = rec->parent_generation;
5753 /* fixme, get the real parent transid */
5754 buf = read_tree_block(root, bytenr, size, gen);
5755 if (!extent_buffer_uptodate(buf)) {
5756 record_bad_block_io(root->fs_info,
5757 extent_cache, bytenr, size);
5761 nritems = btrfs_header_nritems(buf);
5764 if (!init_extent_tree) {
5765 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5766 btrfs_header_level(buf), 1, NULL,
5769 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5771 fprintf(stderr, "Couldn't calc extent flags\n");
5772 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5777 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5779 fprintf(stderr, "Couldn't calc extent flags\n");
5780 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5784 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5786 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5787 ri->objectid == btrfs_header_owner(buf)) {
5789 * Ok we got to this block from it's original owner and
5790 * we have FULL_BACKREF set. Relocation can leave
5791 * converted blocks over so this is altogether possible,
5792 * however it's not possible if the generation > the
5793 * last snapshot, so check for this case.
5795 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5796 btrfs_header_generation(buf) > ri->last_snapshot) {
5797 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5798 rec->bad_full_backref = 1;
5803 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5804 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5805 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5806 rec->bad_full_backref = 1;
5810 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5811 rec->flag_block_full_backref = 1;
5815 rec->flag_block_full_backref = 0;
5817 owner = btrfs_header_owner(buf);
5820 ret = check_block(root, extent_cache, buf, flags);
5824 if (btrfs_is_leaf(buf)) {
5825 btree_space_waste += btrfs_leaf_free_space(root, buf);
5826 for (i = 0; i < nritems; i++) {
5827 struct btrfs_file_extent_item *fi;
5828 btrfs_item_key_to_cpu(buf, &key, i);
5829 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5830 process_extent_item(root, extent_cache, buf,
5834 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5835 process_extent_item(root, extent_cache, buf,
5839 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5841 btrfs_item_size_nr(buf, i);
5844 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5845 process_chunk_item(chunk_cache, &key, buf, i);
5848 if (key.type == BTRFS_DEV_ITEM_KEY) {
5849 process_device_item(dev_cache, &key, buf, i);
5852 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5853 process_block_group_item(block_group_cache,
5857 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5858 process_device_extent_item(dev_extent_cache,
5863 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5864 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5865 process_extent_ref_v0(extent_cache, buf, i);
5872 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5873 add_tree_backref(extent_cache, key.objectid, 0,
5877 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5878 add_tree_backref(extent_cache, key.objectid,
5882 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5883 struct btrfs_extent_data_ref *ref;
5884 ref = btrfs_item_ptr(buf, i,
5885 struct btrfs_extent_data_ref);
5886 add_data_backref(extent_cache,
5888 btrfs_extent_data_ref_root(buf, ref),
5889 btrfs_extent_data_ref_objectid(buf,
5891 btrfs_extent_data_ref_offset(buf, ref),
5892 btrfs_extent_data_ref_count(buf, ref),
5893 0, root->sectorsize);
5896 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5897 struct btrfs_shared_data_ref *ref;
5898 ref = btrfs_item_ptr(buf, i,
5899 struct btrfs_shared_data_ref);
5900 add_data_backref(extent_cache,
5901 key.objectid, key.offset, 0, 0, 0,
5902 btrfs_shared_data_ref_count(buf, ref),
5903 0, root->sectorsize);
5906 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5907 struct bad_item *bad;
5909 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5913 bad = malloc(sizeof(struct bad_item));
5916 INIT_LIST_HEAD(&bad->list);
5917 memcpy(&bad->key, &key,
5918 sizeof(struct btrfs_key));
5919 bad->root_id = owner;
5920 list_add_tail(&bad->list, &delete_items);
5923 if (key.type != BTRFS_EXTENT_DATA_KEY)
5925 fi = btrfs_item_ptr(buf, i,
5926 struct btrfs_file_extent_item);
5927 if (btrfs_file_extent_type(buf, fi) ==
5928 BTRFS_FILE_EXTENT_INLINE)
5930 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5933 data_bytes_allocated +=
5934 btrfs_file_extent_disk_num_bytes(buf, fi);
5935 if (data_bytes_allocated < root->sectorsize) {
5938 data_bytes_referenced +=
5939 btrfs_file_extent_num_bytes(buf, fi);
5940 add_data_backref(extent_cache,
5941 btrfs_file_extent_disk_bytenr(buf, fi),
5942 parent, owner, key.objectid, key.offset -
5943 btrfs_file_extent_offset(buf, fi), 1, 1,
5944 btrfs_file_extent_disk_num_bytes(buf, fi));
5948 struct btrfs_key first_key;
5950 first_key.objectid = 0;
5953 btrfs_item_key_to_cpu(buf, &first_key, 0);
5954 level = btrfs_header_level(buf);
5955 for (i = 0; i < nritems; i++) {
5956 ptr = btrfs_node_blockptr(buf, i);
5957 size = btrfs_level_size(root, level - 1);
5958 btrfs_node_key_to_cpu(buf, &key, i);
5960 if ((level == ri->drop_level)
5961 && is_dropped_key(&key, &ri->drop_key)) {
5965 ret = add_extent_rec(extent_cache, &key,
5966 btrfs_node_ptr_generation(buf, i),
5967 ptr, size, 0, 0, 1, 0, 1, 0,
5971 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5974 add_pending(nodes, seen, ptr, size);
5976 add_pending(pending, seen, ptr, size);
5979 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5980 nritems) * sizeof(struct btrfs_key_ptr);
5982 total_btree_bytes += buf->len;
5983 if (fs_root_objectid(btrfs_header_owner(buf)))
5984 total_fs_tree_bytes += buf->len;
5985 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5986 total_extent_tree_bytes += buf->len;
5987 if (!found_old_backref &&
5988 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5989 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5990 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5991 found_old_backref = 1;
5993 free_extent_buffer(buf);
5997 static int add_root_to_pending(struct extent_buffer *buf,
5998 struct cache_tree *extent_cache,
5999 struct cache_tree *pending,
6000 struct cache_tree *seen,
6001 struct cache_tree *nodes,
6004 if (btrfs_header_level(buf) > 0)
6005 add_pending(nodes, seen, buf->start, buf->len);
6007 add_pending(pending, seen, buf->start, buf->len);
6008 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
6009 0, 1, 1, 0, 1, 0, buf->len);
6011 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
6012 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
6013 add_tree_backref(extent_cache, buf->start, buf->start,
6016 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
6020 /* as we fix the tree, we might be deleting blocks that
6021 * we're tracking for repair. This hook makes sure we
6022 * remove any backrefs for blocks as we are fixing them.
6024 static int free_extent_hook(struct btrfs_trans_handle *trans,
6025 struct btrfs_root *root,
6026 u64 bytenr, u64 num_bytes, u64 parent,
6027 u64 root_objectid, u64 owner, u64 offset,
6030 struct extent_record *rec;
6031 struct cache_extent *cache;
6033 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6035 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6036 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6040 rec = container_of(cache, struct extent_record, cache);
6042 struct data_backref *back;
6043 back = find_data_backref(rec, parent, root_objectid, owner,
6044 offset, 1, bytenr, num_bytes);
6047 if (back->node.found_ref) {
6048 back->found_ref -= refs_to_drop;
6050 rec->refs -= refs_to_drop;
6052 if (back->node.found_extent_tree) {
6053 back->num_refs -= refs_to_drop;
6054 if (rec->extent_item_refs)
6055 rec->extent_item_refs -= refs_to_drop;
6057 if (back->found_ref == 0)
6058 back->node.found_ref = 0;
6059 if (back->num_refs == 0)
6060 back->node.found_extent_tree = 0;
6062 if (!back->node.found_extent_tree && back->node.found_ref) {
6063 list_del(&back->node.list);
6067 struct tree_backref *back;
6068 back = find_tree_backref(rec, parent, root_objectid);
6071 if (back->node.found_ref) {
6074 back->node.found_ref = 0;
6076 if (back->node.found_extent_tree) {
6077 if (rec->extent_item_refs)
6078 rec->extent_item_refs--;
6079 back->node.found_extent_tree = 0;
6081 if (!back->node.found_extent_tree && back->node.found_ref) {
6082 list_del(&back->node.list);
6086 maybe_free_extent_rec(extent_cache, rec);
6091 static int delete_extent_records(struct btrfs_trans_handle *trans,
6092 struct btrfs_root *root,
6093 struct btrfs_path *path,
6094 u64 bytenr, u64 new_len)
6096 struct btrfs_key key;
6097 struct btrfs_key found_key;
6098 struct extent_buffer *leaf;
6103 key.objectid = bytenr;
6105 key.offset = (u64)-1;
6108 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6115 if (path->slots[0] == 0)
6121 leaf = path->nodes[0];
6122 slot = path->slots[0];
6124 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6125 if (found_key.objectid != bytenr)
6128 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6129 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6130 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6131 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6132 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6133 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6134 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6135 btrfs_release_path(path);
6136 if (found_key.type == 0) {
6137 if (found_key.offset == 0)
6139 key.offset = found_key.offset - 1;
6140 key.type = found_key.type;
6142 key.type = found_key.type - 1;
6143 key.offset = (u64)-1;
6147 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6148 found_key.objectid, found_key.type, found_key.offset);
6150 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6153 btrfs_release_path(path);
6155 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6156 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6157 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6158 found_key.offset : root->leafsize;
6160 ret = btrfs_update_block_group(trans, root, bytenr,
6167 btrfs_release_path(path);
6172 * for a single backref, this will allocate a new extent
6173 * and add the backref to it.
6175 static int record_extent(struct btrfs_trans_handle *trans,
6176 struct btrfs_fs_info *info,
6177 struct btrfs_path *path,
6178 struct extent_record *rec,
6179 struct extent_backref *back,
6180 int allocated, u64 flags)
6183 struct btrfs_root *extent_root = info->extent_root;
6184 struct extent_buffer *leaf;
6185 struct btrfs_key ins_key;
6186 struct btrfs_extent_item *ei;
6187 struct tree_backref *tback;
6188 struct data_backref *dback;
6189 struct btrfs_tree_block_info *bi;
6192 rec->max_size = max_t(u64, rec->max_size,
6193 info->extent_root->leafsize);
6196 u32 item_size = sizeof(*ei);
6199 item_size += sizeof(*bi);
6201 ins_key.objectid = rec->start;
6202 ins_key.offset = rec->max_size;
6203 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6205 ret = btrfs_insert_empty_item(trans, extent_root, path,
6206 &ins_key, item_size);
6210 leaf = path->nodes[0];
6211 ei = btrfs_item_ptr(leaf, path->slots[0],
6212 struct btrfs_extent_item);
6214 btrfs_set_extent_refs(leaf, ei, 0);
6215 btrfs_set_extent_generation(leaf, ei, rec->generation);
6217 if (back->is_data) {
6218 btrfs_set_extent_flags(leaf, ei,
6219 BTRFS_EXTENT_FLAG_DATA);
6221 struct btrfs_disk_key copy_key;;
6223 tback = (struct tree_backref *)back;
6224 bi = (struct btrfs_tree_block_info *)(ei + 1);
6225 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6228 btrfs_set_disk_key_objectid(©_key,
6229 rec->info_objectid);
6230 btrfs_set_disk_key_type(©_key, 0);
6231 btrfs_set_disk_key_offset(©_key, 0);
6233 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6234 btrfs_set_tree_block_key(leaf, bi, ©_key);
6236 btrfs_set_extent_flags(leaf, ei,
6237 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6240 btrfs_mark_buffer_dirty(leaf);
6241 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6242 rec->max_size, 1, 0);
6245 btrfs_release_path(path);
6248 if (back->is_data) {
6252 dback = (struct data_backref *)back;
6253 if (back->full_backref)
6254 parent = dback->parent;
6258 for (i = 0; i < dback->found_ref; i++) {
6259 /* if parent != 0, we're doing a full backref
6260 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6261 * just makes the backref allocator create a data
6264 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6265 rec->start, rec->max_size,
6269 BTRFS_FIRST_FREE_OBJECTID :
6275 fprintf(stderr, "adding new data backref"
6276 " on %llu %s %llu owner %llu"
6277 " offset %llu found %d\n",
6278 (unsigned long long)rec->start,
6279 back->full_backref ?
6281 back->full_backref ?
6282 (unsigned long long)parent :
6283 (unsigned long long)dback->root,
6284 (unsigned long long)dback->owner,
6285 (unsigned long long)dback->offset,
6290 tback = (struct tree_backref *)back;
6291 if (back->full_backref)
6292 parent = tback->parent;
6296 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6297 rec->start, rec->max_size,
6298 parent, tback->root, 0, 0);
6299 fprintf(stderr, "adding new tree backref on "
6300 "start %llu len %llu parent %llu root %llu\n",
6301 rec->start, rec->max_size, parent, tback->root);
6306 btrfs_release_path(path);
6310 struct extent_entry {
6315 struct list_head list;
6318 static struct extent_entry *find_entry(struct list_head *entries,
6319 u64 bytenr, u64 bytes)
6321 struct extent_entry *entry = NULL;
6323 list_for_each_entry(entry, entries, list) {
6324 if (entry->bytenr == bytenr && entry->bytes == bytes)
6331 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6333 struct extent_entry *entry, *best = NULL, *prev = NULL;
6335 list_for_each_entry(entry, entries, list) {
6342 * If there are as many broken entries as entries then we know
6343 * not to trust this particular entry.
6345 if (entry->broken == entry->count)
6349 * If our current entry == best then we can't be sure our best
6350 * is really the best, so we need to keep searching.
6352 if (best && best->count == entry->count) {
6358 /* Prev == entry, not good enough, have to keep searching */
6359 if (!prev->broken && prev->count == entry->count)
6363 best = (prev->count > entry->count) ? prev : entry;
6364 else if (best->count < entry->count)
6372 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6373 struct data_backref *dback, struct extent_entry *entry)
6375 struct btrfs_trans_handle *trans;
6376 struct btrfs_root *root;
6377 struct btrfs_file_extent_item *fi;
6378 struct extent_buffer *leaf;
6379 struct btrfs_key key;
6383 key.objectid = dback->root;
6384 key.type = BTRFS_ROOT_ITEM_KEY;
6385 key.offset = (u64)-1;
6386 root = btrfs_read_fs_root(info, &key);
6388 fprintf(stderr, "Couldn't find root for our ref\n");
6393 * The backref points to the original offset of the extent if it was
6394 * split, so we need to search down to the offset we have and then walk
6395 * forward until we find the backref we're looking for.
6397 key.objectid = dback->owner;
6398 key.type = BTRFS_EXTENT_DATA_KEY;
6399 key.offset = dback->offset;
6400 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6402 fprintf(stderr, "Error looking up ref %d\n", ret);
6407 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6408 ret = btrfs_next_leaf(root, path);
6410 fprintf(stderr, "Couldn't find our ref, next\n");
6414 leaf = path->nodes[0];
6415 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6416 if (key.objectid != dback->owner ||
6417 key.type != BTRFS_EXTENT_DATA_KEY) {
6418 fprintf(stderr, "Couldn't find our ref, search\n");
6421 fi = btrfs_item_ptr(leaf, path->slots[0],
6422 struct btrfs_file_extent_item);
6423 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6424 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6426 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6431 btrfs_release_path(path);
6433 trans = btrfs_start_transaction(root, 1);
6435 return PTR_ERR(trans);
6438 * Ok we have the key of the file extent we want to fix, now we can cow
6439 * down to the thing and fix it.
6441 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6443 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6444 key.objectid, key.type, key.offset, ret);
6448 fprintf(stderr, "Well that's odd, we just found this key "
6449 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6454 leaf = path->nodes[0];
6455 fi = btrfs_item_ptr(leaf, path->slots[0],
6456 struct btrfs_file_extent_item);
6458 if (btrfs_file_extent_compression(leaf, fi) &&
6459 dback->disk_bytenr != entry->bytenr) {
6460 fprintf(stderr, "Ref doesn't match the record start and is "
6461 "compressed, please take a btrfs-image of this file "
6462 "system and send it to a btrfs developer so they can "
6463 "complete this functionality for bytenr %Lu\n",
6464 dback->disk_bytenr);
6469 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6470 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6471 } else if (dback->disk_bytenr > entry->bytenr) {
6472 u64 off_diff, offset;
6474 off_diff = dback->disk_bytenr - entry->bytenr;
6475 offset = btrfs_file_extent_offset(leaf, fi);
6476 if (dback->disk_bytenr + offset +
6477 btrfs_file_extent_num_bytes(leaf, fi) >
6478 entry->bytenr + entry->bytes) {
6479 fprintf(stderr, "Ref is past the entry end, please "
6480 "take a btrfs-image of this file system and "
6481 "send it to a btrfs developer, ref %Lu\n",
6482 dback->disk_bytenr);
6487 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6488 btrfs_set_file_extent_offset(leaf, fi, offset);
6489 } else if (dback->disk_bytenr < entry->bytenr) {
6492 offset = btrfs_file_extent_offset(leaf, fi);
6493 if (dback->disk_bytenr + offset < entry->bytenr) {
6494 fprintf(stderr, "Ref is before the entry start, please"
6495 " take a btrfs-image of this file system and "
6496 "send it to a btrfs developer, ref %Lu\n",
6497 dback->disk_bytenr);
6502 offset += dback->disk_bytenr;
6503 offset -= entry->bytenr;
6504 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6505 btrfs_set_file_extent_offset(leaf, fi, offset);
6508 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6511 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6512 * only do this if we aren't using compression, otherwise it's a
6515 if (!btrfs_file_extent_compression(leaf, fi))
6516 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6518 printf("ram bytes may be wrong?\n");
6519 btrfs_mark_buffer_dirty(leaf);
6521 err = btrfs_commit_transaction(trans, root);
6522 btrfs_release_path(path);
6523 return ret ? ret : err;
6526 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6527 struct extent_record *rec)
6529 struct extent_backref *back;
6530 struct data_backref *dback;
6531 struct extent_entry *entry, *best = NULL;
6534 int broken_entries = 0;
6539 * Metadata is easy and the backrefs should always agree on bytenr and
6540 * size, if not we've got bigger issues.
6545 list_for_each_entry(back, &rec->backrefs, list) {
6546 if (back->full_backref || !back->is_data)
6549 dback = (struct data_backref *)back;
6552 * We only pay attention to backrefs that we found a real
6555 if (dback->found_ref == 0)
6559 * For now we only catch when the bytes don't match, not the
6560 * bytenr. We can easily do this at the same time, but I want
6561 * to have a fs image to test on before we just add repair
6562 * functionality willy-nilly so we know we won't screw up the
6566 entry = find_entry(&entries, dback->disk_bytenr,
6569 entry = malloc(sizeof(struct extent_entry));
6574 memset(entry, 0, sizeof(*entry));
6575 entry->bytenr = dback->disk_bytenr;
6576 entry->bytes = dback->bytes;
6577 list_add_tail(&entry->list, &entries);
6582 * If we only have on entry we may think the entries agree when
6583 * in reality they don't so we have to do some extra checking.
6585 if (dback->disk_bytenr != rec->start ||
6586 dback->bytes != rec->nr || back->broken)
6597 /* Yay all the backrefs agree, carry on good sir */
6598 if (nr_entries <= 1 && !mismatch)
6601 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6602 "%Lu\n", rec->start);
6605 * First we want to see if the backrefs can agree amongst themselves who
6606 * is right, so figure out which one of the entries has the highest
6609 best = find_most_right_entry(&entries);
6612 * Ok so we may have an even split between what the backrefs think, so
6613 * this is where we use the extent ref to see what it thinks.
6616 entry = find_entry(&entries, rec->start, rec->nr);
6617 if (!entry && (!broken_entries || !rec->found_rec)) {
6618 fprintf(stderr, "Backrefs don't agree with each other "
6619 "and extent record doesn't agree with anybody,"
6620 " so we can't fix bytenr %Lu bytes %Lu\n",
6621 rec->start, rec->nr);
6624 } else if (!entry) {
6626 * Ok our backrefs were broken, we'll assume this is the
6627 * correct value and add an entry for this range.
6629 entry = malloc(sizeof(struct extent_entry));
6634 memset(entry, 0, sizeof(*entry));
6635 entry->bytenr = rec->start;
6636 entry->bytes = rec->nr;
6637 list_add_tail(&entry->list, &entries);
6641 best = find_most_right_entry(&entries);
6643 fprintf(stderr, "Backrefs and extent record evenly "
6644 "split on who is right, this is going to "
6645 "require user input to fix bytenr %Lu bytes "
6646 "%Lu\n", rec->start, rec->nr);
6653 * I don't think this can happen currently as we'll abort() if we catch
6654 * this case higher up, but in case somebody removes that we still can't
6655 * deal with it properly here yet, so just bail out of that's the case.
6657 if (best->bytenr != rec->start) {
6658 fprintf(stderr, "Extent start and backref starts don't match, "
6659 "please use btrfs-image on this file system and send "
6660 "it to a btrfs developer so they can make fsck fix "
6661 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6662 rec->start, rec->nr);
6668 * Ok great we all agreed on an extent record, let's go find the real
6669 * references and fix up the ones that don't match.
6671 list_for_each_entry(back, &rec->backrefs, list) {
6672 if (back->full_backref || !back->is_data)
6675 dback = (struct data_backref *)back;
6678 * Still ignoring backrefs that don't have a real ref attached
6681 if (dback->found_ref == 0)
6684 if (dback->bytes == best->bytes &&
6685 dback->disk_bytenr == best->bytenr)
6688 ret = repair_ref(info, path, dback, best);
6694 * Ok we messed with the actual refs, which means we need to drop our
6695 * entire cache and go back and rescan. I know this is a huge pain and
6696 * adds a lot of extra work, but it's the only way to be safe. Once all
6697 * the backrefs agree we may not need to do anything to the extent
6702 while (!list_empty(&entries)) {
6703 entry = list_entry(entries.next, struct extent_entry, list);
6704 list_del_init(&entry->list);
6710 static int process_duplicates(struct btrfs_root *root,
6711 struct cache_tree *extent_cache,
6712 struct extent_record *rec)
6714 struct extent_record *good, *tmp;
6715 struct cache_extent *cache;
6719 * If we found a extent record for this extent then return, or if we
6720 * have more than one duplicate we are likely going to need to delete
6723 if (rec->found_rec || rec->num_duplicates > 1)
6726 /* Shouldn't happen but just in case */
6727 BUG_ON(!rec->num_duplicates);
6730 * So this happens if we end up with a backref that doesn't match the
6731 * actual extent entry. So either the backref is bad or the extent
6732 * entry is bad. Either way we want to have the extent_record actually
6733 * reflect what we found in the extent_tree, so we need to take the
6734 * duplicate out and use that as the extent_record since the only way we
6735 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6737 remove_cache_extent(extent_cache, &rec->cache);
6739 good = list_entry(rec->dups.next, struct extent_record, list);
6740 list_del_init(&good->list);
6741 INIT_LIST_HEAD(&good->backrefs);
6742 INIT_LIST_HEAD(&good->dups);
6743 good->cache.start = good->start;
6744 good->cache.size = good->nr;
6745 good->content_checked = 0;
6746 good->owner_ref_checked = 0;
6747 good->num_duplicates = 0;
6748 good->refs = rec->refs;
6749 list_splice_init(&rec->backrefs, &good->backrefs);
6751 cache = lookup_cache_extent(extent_cache, good->start,
6755 tmp = container_of(cache, struct extent_record, cache);
6758 * If we find another overlapping extent and it's found_rec is
6759 * set then it's a duplicate and we need to try and delete
6762 if (tmp->found_rec || tmp->num_duplicates > 0) {
6763 if (list_empty(&good->list))
6764 list_add_tail(&good->list,
6765 &duplicate_extents);
6766 good->num_duplicates += tmp->num_duplicates + 1;
6767 list_splice_init(&tmp->dups, &good->dups);
6768 list_del_init(&tmp->list);
6769 list_add_tail(&tmp->list, &good->dups);
6770 remove_cache_extent(extent_cache, &tmp->cache);
6775 * Ok we have another non extent item backed extent rec, so lets
6776 * just add it to this extent and carry on like we did above.
6778 good->refs += tmp->refs;
6779 list_splice_init(&tmp->backrefs, &good->backrefs);
6780 remove_cache_extent(extent_cache, &tmp->cache);
6783 ret = insert_cache_extent(extent_cache, &good->cache);
6786 return good->num_duplicates ? 0 : 1;
6789 static int delete_duplicate_records(struct btrfs_root *root,
6790 struct extent_record *rec)
6792 struct btrfs_trans_handle *trans;
6793 LIST_HEAD(delete_list);
6794 struct btrfs_path *path;
6795 struct extent_record *tmp, *good, *n;
6798 struct btrfs_key key;
6800 path = btrfs_alloc_path();
6807 /* Find the record that covers all of the duplicates. */
6808 list_for_each_entry(tmp, &rec->dups, list) {
6809 if (good->start < tmp->start)
6811 if (good->nr > tmp->nr)
6814 if (tmp->start + tmp->nr < good->start + good->nr) {
6815 fprintf(stderr, "Ok we have overlapping extents that "
6816 "aren't completely covered by eachother, this "
6817 "is going to require more careful thought. "
6818 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6819 tmp->start, tmp->nr, good->start, good->nr);
6826 list_add_tail(&rec->list, &delete_list);
6828 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6831 list_move_tail(&tmp->list, &delete_list);
6834 root = root->fs_info->extent_root;
6835 trans = btrfs_start_transaction(root, 1);
6836 if (IS_ERR(trans)) {
6837 ret = PTR_ERR(trans);
6841 list_for_each_entry(tmp, &delete_list, list) {
6842 if (tmp->found_rec == 0)
6844 key.objectid = tmp->start;
6845 key.type = BTRFS_EXTENT_ITEM_KEY;
6846 key.offset = tmp->nr;
6848 /* Shouldn't happen but just in case */
6849 if (tmp->metadata) {
6850 fprintf(stderr, "Well this shouldn't happen, extent "
6851 "record overlaps but is metadata? "
6852 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6856 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6862 ret = btrfs_del_item(trans, root, path);
6865 btrfs_release_path(path);
6868 err = btrfs_commit_transaction(trans, root);
6872 while (!list_empty(&delete_list)) {
6873 tmp = list_entry(delete_list.next, struct extent_record, list);
6874 list_del_init(&tmp->list);
6880 while (!list_empty(&rec->dups)) {
6881 tmp = list_entry(rec->dups.next, struct extent_record, list);
6882 list_del_init(&tmp->list);
6886 btrfs_free_path(path);
6888 if (!ret && !nr_del)
6889 rec->num_duplicates = 0;
6891 return ret ? ret : nr_del;
6894 static int find_possible_backrefs(struct btrfs_fs_info *info,
6895 struct btrfs_path *path,
6896 struct cache_tree *extent_cache,
6897 struct extent_record *rec)
6899 struct btrfs_root *root;
6900 struct extent_backref *back;
6901 struct data_backref *dback;
6902 struct cache_extent *cache;
6903 struct btrfs_file_extent_item *fi;
6904 struct btrfs_key key;
6908 list_for_each_entry(back, &rec->backrefs, list) {
6909 /* Don't care about full backrefs (poor unloved backrefs) */
6910 if (back->full_backref || !back->is_data)
6913 dback = (struct data_backref *)back;
6915 /* We found this one, we don't need to do a lookup */
6916 if (dback->found_ref)
6919 key.objectid = dback->root;
6920 key.type = BTRFS_ROOT_ITEM_KEY;
6921 key.offset = (u64)-1;
6923 root = btrfs_read_fs_root(info, &key);
6925 /* No root, definitely a bad ref, skip */
6926 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6928 /* Other err, exit */
6930 return PTR_ERR(root);
6932 key.objectid = dback->owner;
6933 key.type = BTRFS_EXTENT_DATA_KEY;
6934 key.offset = dback->offset;
6935 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6937 btrfs_release_path(path);
6940 /* Didn't find it, we can carry on */
6945 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6946 struct btrfs_file_extent_item);
6947 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6948 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6949 btrfs_release_path(path);
6950 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6952 struct extent_record *tmp;
6953 tmp = container_of(cache, struct extent_record, cache);
6956 * If we found an extent record for the bytenr for this
6957 * particular backref then we can't add it to our
6958 * current extent record. We only want to add backrefs
6959 * that don't have a corresponding extent item in the
6960 * extent tree since they likely belong to this record
6961 * and we need to fix it if it doesn't match bytenrs.
6967 dback->found_ref += 1;
6968 dback->disk_bytenr = bytenr;
6969 dback->bytes = bytes;
6972 * Set this so the verify backref code knows not to trust the
6973 * values in this backref.
6982 * Record orphan data ref into corresponding root.
6984 * Return 0 if the extent item contains data ref and recorded.
6985 * Return 1 if the extent item contains no useful data ref
6986 * On that case, it may contains only shared_dataref or metadata backref
6987 * or the file extent exists(this should be handled by the extent bytenr
6989 * Return <0 if something goes wrong.
6991 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6992 struct extent_record *rec)
6994 struct btrfs_key key;
6995 struct btrfs_root *dest_root;
6996 struct extent_backref *back;
6997 struct data_backref *dback;
6998 struct orphan_data_extent *orphan;
6999 struct btrfs_path *path;
7000 int recorded_data_ref = 0;
7005 path = btrfs_alloc_path();
7008 list_for_each_entry(back, &rec->backrefs, list) {
7009 if (back->full_backref || !back->is_data ||
7010 !back->found_extent_tree)
7012 dback = (struct data_backref *)back;
7013 if (dback->found_ref)
7015 key.objectid = dback->root;
7016 key.type = BTRFS_ROOT_ITEM_KEY;
7017 key.offset = (u64)-1;
7019 dest_root = btrfs_read_fs_root(fs_info, &key);
7021 /* For non-exist root we just skip it */
7022 if (IS_ERR(dest_root) || !dest_root)
7025 key.objectid = dback->owner;
7026 key.type = BTRFS_EXTENT_DATA_KEY;
7027 key.offset = dback->offset;
7029 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7031 * For ret < 0, it's OK since the fs-tree may be corrupted,
7032 * we need to record it for inode/file extent rebuild.
7033 * For ret > 0, we record it only for file extent rebuild.
7034 * For ret == 0, the file extent exists but only bytenr
7035 * mismatch, let the original bytenr fix routine to handle,
7041 orphan = malloc(sizeof(*orphan));
7046 INIT_LIST_HEAD(&orphan->list);
7047 orphan->root = dback->root;
7048 orphan->objectid = dback->owner;
7049 orphan->offset = dback->offset;
7050 orphan->disk_bytenr = rec->cache.start;
7051 orphan->disk_len = rec->cache.size;
7052 list_add(&dest_root->orphan_data_extents, &orphan->list);
7053 recorded_data_ref = 1;
7056 btrfs_free_path(path);
7058 return !recorded_data_ref;
7064 * when an incorrect extent item is found, this will delete
7065 * all of the existing entries for it and recreate them
7066 * based on what the tree scan found.
7068 static int fixup_extent_refs(struct btrfs_fs_info *info,
7069 struct cache_tree *extent_cache,
7070 struct extent_record *rec)
7072 struct btrfs_trans_handle *trans = NULL;
7074 struct btrfs_path *path;
7075 struct list_head *cur = rec->backrefs.next;
7076 struct cache_extent *cache;
7077 struct extent_backref *back;
7081 if (rec->flag_block_full_backref)
7082 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7084 path = btrfs_alloc_path();
7088 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7090 * Sometimes the backrefs themselves are so broken they don't
7091 * get attached to any meaningful rec, so first go back and
7092 * check any of our backrefs that we couldn't find and throw
7093 * them into the list if we find the backref so that
7094 * verify_backrefs can figure out what to do.
7096 ret = find_possible_backrefs(info, path, extent_cache, rec);
7101 /* step one, make sure all of the backrefs agree */
7102 ret = verify_backrefs(info, path, rec);
7106 trans = btrfs_start_transaction(info->extent_root, 1);
7107 if (IS_ERR(trans)) {
7108 ret = PTR_ERR(trans);
7112 /* step two, delete all the existing records */
7113 ret = delete_extent_records(trans, info->extent_root, path,
7114 rec->start, rec->max_size);
7119 /* was this block corrupt? If so, don't add references to it */
7120 cache = lookup_cache_extent(info->corrupt_blocks,
7121 rec->start, rec->max_size);
7127 /* step three, recreate all the refs we did find */
7128 while(cur != &rec->backrefs) {
7129 back = list_entry(cur, struct extent_backref, list);
7133 * if we didn't find any references, don't create a
7136 if (!back->found_ref)
7139 rec->bad_full_backref = 0;
7140 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7148 int err = btrfs_commit_transaction(trans, info->extent_root);
7153 btrfs_free_path(path);
7157 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7158 struct extent_record *rec)
7160 struct btrfs_trans_handle *trans;
7161 struct btrfs_root *root = fs_info->extent_root;
7162 struct btrfs_path *path;
7163 struct btrfs_extent_item *ei;
7164 struct btrfs_key key;
7168 key.objectid = rec->start;
7169 if (rec->metadata) {
7170 key.type = BTRFS_METADATA_ITEM_KEY;
7171 key.offset = rec->info_level;
7173 key.type = BTRFS_EXTENT_ITEM_KEY;
7174 key.offset = rec->max_size;
7177 path = btrfs_alloc_path();
7181 trans = btrfs_start_transaction(root, 0);
7182 if (IS_ERR(trans)) {
7183 btrfs_free_path(path);
7184 return PTR_ERR(trans);
7187 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7189 btrfs_free_path(path);
7190 btrfs_commit_transaction(trans, root);
7193 fprintf(stderr, "Didn't find extent for %llu\n",
7194 (unsigned long long)rec->start);
7195 btrfs_free_path(path);
7196 btrfs_commit_transaction(trans, root);
7200 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7201 struct btrfs_extent_item);
7202 flags = btrfs_extent_flags(path->nodes[0], ei);
7203 if (rec->flag_block_full_backref) {
7204 fprintf(stderr, "setting full backref on %llu\n",
7205 (unsigned long long)key.objectid);
7206 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7208 fprintf(stderr, "clearing full backref on %llu\n",
7209 (unsigned long long)key.objectid);
7210 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7212 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7213 btrfs_mark_buffer_dirty(path->nodes[0]);
7214 btrfs_free_path(path);
7215 return btrfs_commit_transaction(trans, root);
7218 /* right now we only prune from the extent allocation tree */
7219 static int prune_one_block(struct btrfs_trans_handle *trans,
7220 struct btrfs_fs_info *info,
7221 struct btrfs_corrupt_block *corrupt)
7224 struct btrfs_path path;
7225 struct extent_buffer *eb;
7229 int level = corrupt->level + 1;
7231 btrfs_init_path(&path);
7233 /* we want to stop at the parent to our busted block */
7234 path.lowest_level = level;
7236 ret = btrfs_search_slot(trans, info->extent_root,
7237 &corrupt->key, &path, -1, 1);
7242 eb = path.nodes[level];
7249 * hopefully the search gave us the block we want to prune,
7250 * lets try that first
7252 slot = path.slots[level];
7253 found = btrfs_node_blockptr(eb, slot);
7254 if (found == corrupt->cache.start)
7257 nritems = btrfs_header_nritems(eb);
7259 /* the search failed, lets scan this node and hope we find it */
7260 for (slot = 0; slot < nritems; slot++) {
7261 found = btrfs_node_blockptr(eb, slot);
7262 if (found == corrupt->cache.start)
7266 * we couldn't find the bad block. TODO, search all the nodes for pointers
7269 if (eb == info->extent_root->node) {
7274 btrfs_release_path(&path);
7279 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7280 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7283 btrfs_release_path(&path);
7287 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7289 struct btrfs_trans_handle *trans = NULL;
7290 struct cache_extent *cache;
7291 struct btrfs_corrupt_block *corrupt;
7294 cache = search_cache_extent(info->corrupt_blocks, 0);
7298 trans = btrfs_start_transaction(info->extent_root, 1);
7300 return PTR_ERR(trans);
7302 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7303 prune_one_block(trans, info, corrupt);
7304 remove_cache_extent(info->corrupt_blocks, cache);
7307 return btrfs_commit_transaction(trans, info->extent_root);
7311 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7313 struct btrfs_block_group_cache *cache;
7318 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7319 &start, &end, EXTENT_DIRTY);
7322 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7328 cache = btrfs_lookup_first_block_group(fs_info, start);
7333 start = cache->key.objectid + cache->key.offset;
7337 static int check_extent_refs(struct btrfs_root *root,
7338 struct cache_tree *extent_cache)
7340 struct extent_record *rec;
7341 struct cache_extent *cache;
7350 * if we're doing a repair, we have to make sure
7351 * we don't allocate from the problem extents.
7352 * In the worst case, this will be all the
7355 cache = search_cache_extent(extent_cache, 0);
7357 rec = container_of(cache, struct extent_record, cache);
7358 set_extent_dirty(root->fs_info->excluded_extents,
7360 rec->start + rec->max_size - 1,
7362 cache = next_cache_extent(cache);
7365 /* pin down all the corrupted blocks too */
7366 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7368 set_extent_dirty(root->fs_info->excluded_extents,
7370 cache->start + cache->size - 1,
7372 cache = next_cache_extent(cache);
7374 prune_corrupt_blocks(root->fs_info);
7375 reset_cached_block_groups(root->fs_info);
7378 reset_cached_block_groups(root->fs_info);
7381 * We need to delete any duplicate entries we find first otherwise we
7382 * could mess up the extent tree when we have backrefs that actually
7383 * belong to a different extent item and not the weird duplicate one.
7385 while (repair && !list_empty(&duplicate_extents)) {
7386 rec = list_entry(duplicate_extents.next, struct extent_record,
7388 list_del_init(&rec->list);
7390 /* Sometimes we can find a backref before we find an actual
7391 * extent, so we need to process it a little bit to see if there
7392 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7393 * if this is a backref screwup. If we need to delete stuff
7394 * process_duplicates() will return 0, otherwise it will return
7397 if (process_duplicates(root, extent_cache, rec))
7399 ret = delete_duplicate_records(root, rec);
7403 * delete_duplicate_records will return the number of entries
7404 * deleted, so if it's greater than 0 then we know we actually
7405 * did something and we need to remove.
7419 cache = search_cache_extent(extent_cache, 0);
7422 rec = container_of(cache, struct extent_record, cache);
7423 if (rec->num_duplicates) {
7424 fprintf(stderr, "extent item %llu has multiple extent "
7425 "items\n", (unsigned long long)rec->start);
7430 if (rec->refs != rec->extent_item_refs) {
7431 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7432 (unsigned long long)rec->start,
7433 (unsigned long long)rec->nr);
7434 fprintf(stderr, "extent item %llu, found %llu\n",
7435 (unsigned long long)rec->extent_item_refs,
7436 (unsigned long long)rec->refs);
7437 ret = record_orphan_data_extents(root->fs_info, rec);
7444 * we can't use the extent to repair file
7445 * extent, let the fallback method handle it.
7447 if (!fixed && repair) {
7448 ret = fixup_extent_refs(
7459 if (all_backpointers_checked(rec, 1)) {
7460 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7461 (unsigned long long)rec->start,
7462 (unsigned long long)rec->nr);
7464 if (!fixed && !recorded && repair) {
7465 ret = fixup_extent_refs(root->fs_info,
7474 if (!rec->owner_ref_checked) {
7475 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7476 (unsigned long long)rec->start,
7477 (unsigned long long)rec->nr);
7478 if (!fixed && !recorded && repair) {
7479 ret = fixup_extent_refs(root->fs_info,
7488 if (rec->bad_full_backref) {
7489 fprintf(stderr, "bad full backref, on [%llu]\n",
7490 (unsigned long long)rec->start);
7492 ret = fixup_extent_flags(root->fs_info, rec);
7501 * Although it's not a extent ref's problem, we reuse this
7502 * routine for error reporting.
7503 * No repair function yet.
7505 if (rec->crossing_stripes) {
7507 "bad metadata [%llu, %llu) crossing stripe boundary\n",
7508 rec->start, rec->start + rec->max_size);
7513 remove_cache_extent(extent_cache, cache);
7514 free_all_extent_backrefs(rec);
7515 if (!init_extent_tree && repair && (!cur_err || fixed))
7516 clear_extent_dirty(root->fs_info->excluded_extents,
7518 rec->start + rec->max_size - 1,
7524 if (ret && ret != -EAGAIN) {
7525 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7528 struct btrfs_trans_handle *trans;
7530 root = root->fs_info->extent_root;
7531 trans = btrfs_start_transaction(root, 1);
7532 if (IS_ERR(trans)) {
7533 ret = PTR_ERR(trans);
7537 btrfs_fix_block_accounting(trans, root);
7538 ret = btrfs_commit_transaction(trans, root);
7543 fprintf(stderr, "repaired damaged extent references\n");
7549 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7553 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7554 stripe_size = length;
7555 stripe_size /= num_stripes;
7556 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7557 stripe_size = length * 2;
7558 stripe_size /= num_stripes;
7559 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7560 stripe_size = length;
7561 stripe_size /= (num_stripes - 1);
7562 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7563 stripe_size = length;
7564 stripe_size /= (num_stripes - 2);
7566 stripe_size = length;
7572 * Check the chunk with its block group/dev list ref:
7573 * Return 0 if all refs seems valid.
7574 * Return 1 if part of refs seems valid, need later check for rebuild ref
7575 * like missing block group and needs to search extent tree to rebuild them.
7576 * Return -1 if essential refs are missing and unable to rebuild.
7578 static int check_chunk_refs(struct chunk_record *chunk_rec,
7579 struct block_group_tree *block_group_cache,
7580 struct device_extent_tree *dev_extent_cache,
7583 struct cache_extent *block_group_item;
7584 struct block_group_record *block_group_rec;
7585 struct cache_extent *dev_extent_item;
7586 struct device_extent_record *dev_extent_rec;
7590 int metadump_v2 = 0;
7594 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7597 if (block_group_item) {
7598 block_group_rec = container_of(block_group_item,
7599 struct block_group_record,
7601 if (chunk_rec->length != block_group_rec->offset ||
7602 chunk_rec->offset != block_group_rec->objectid ||
7604 chunk_rec->type_flags != block_group_rec->flags)) {
7607 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7608 chunk_rec->objectid,
7613 chunk_rec->type_flags,
7614 block_group_rec->objectid,
7615 block_group_rec->type,
7616 block_group_rec->offset,
7617 block_group_rec->offset,
7618 block_group_rec->objectid,
7619 block_group_rec->flags);
7622 list_del_init(&block_group_rec->list);
7623 chunk_rec->bg_rec = block_group_rec;
7628 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7629 chunk_rec->objectid,
7634 chunk_rec->type_flags);
7641 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7642 chunk_rec->num_stripes);
7643 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7644 devid = chunk_rec->stripes[i].devid;
7645 offset = chunk_rec->stripes[i].offset;
7646 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7647 devid, offset, length);
7648 if (dev_extent_item) {
7649 dev_extent_rec = container_of(dev_extent_item,
7650 struct device_extent_record,
7652 if (dev_extent_rec->objectid != devid ||
7653 dev_extent_rec->offset != offset ||
7654 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7655 dev_extent_rec->length != length) {
7658 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7659 chunk_rec->objectid,
7662 chunk_rec->stripes[i].devid,
7663 chunk_rec->stripes[i].offset,
7664 dev_extent_rec->objectid,
7665 dev_extent_rec->offset,
7666 dev_extent_rec->length);
7669 list_move(&dev_extent_rec->chunk_list,
7670 &chunk_rec->dextents);
7675 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7676 chunk_rec->objectid,
7679 chunk_rec->stripes[i].devid,
7680 chunk_rec->stripes[i].offset);
7687 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7688 int check_chunks(struct cache_tree *chunk_cache,
7689 struct block_group_tree *block_group_cache,
7690 struct device_extent_tree *dev_extent_cache,
7691 struct list_head *good, struct list_head *bad,
7692 struct list_head *rebuild, int silent)
7694 struct cache_extent *chunk_item;
7695 struct chunk_record *chunk_rec;
7696 struct block_group_record *bg_rec;
7697 struct device_extent_record *dext_rec;
7701 chunk_item = first_cache_extent(chunk_cache);
7702 while (chunk_item) {
7703 chunk_rec = container_of(chunk_item, struct chunk_record,
7705 err = check_chunk_refs(chunk_rec, block_group_cache,
7706 dev_extent_cache, silent);
7709 if (err == 0 && good)
7710 list_add_tail(&chunk_rec->list, good);
7711 if (err > 0 && rebuild)
7712 list_add_tail(&chunk_rec->list, rebuild);
7714 list_add_tail(&chunk_rec->list, bad);
7715 chunk_item = next_cache_extent(chunk_item);
7718 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7721 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7729 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7733 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7744 static int check_device_used(struct device_record *dev_rec,
7745 struct device_extent_tree *dext_cache)
7747 struct cache_extent *cache;
7748 struct device_extent_record *dev_extent_rec;
7751 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7753 dev_extent_rec = container_of(cache,
7754 struct device_extent_record,
7756 if (dev_extent_rec->objectid != dev_rec->devid)
7759 list_del_init(&dev_extent_rec->device_list);
7760 total_byte += dev_extent_rec->length;
7761 cache = next_cache_extent(cache);
7764 if (total_byte != dev_rec->byte_used) {
7766 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7767 total_byte, dev_rec->byte_used, dev_rec->objectid,
7768 dev_rec->type, dev_rec->offset);
7775 /* check btrfs_dev_item -> btrfs_dev_extent */
7776 static int check_devices(struct rb_root *dev_cache,
7777 struct device_extent_tree *dev_extent_cache)
7779 struct rb_node *dev_node;
7780 struct device_record *dev_rec;
7781 struct device_extent_record *dext_rec;
7785 dev_node = rb_first(dev_cache);
7787 dev_rec = container_of(dev_node, struct device_record, node);
7788 err = check_device_used(dev_rec, dev_extent_cache);
7792 dev_node = rb_next(dev_node);
7794 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7797 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7798 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7805 static int add_root_item_to_list(struct list_head *head,
7806 u64 objectid, u64 bytenr, u64 last_snapshot,
7807 u8 level, u8 drop_level,
7808 int level_size, struct btrfs_key *drop_key)
7811 struct root_item_record *ri_rec;
7812 ri_rec = malloc(sizeof(*ri_rec));
7815 ri_rec->bytenr = bytenr;
7816 ri_rec->objectid = objectid;
7817 ri_rec->level = level;
7818 ri_rec->level_size = level_size;
7819 ri_rec->drop_level = drop_level;
7820 ri_rec->last_snapshot = last_snapshot;
7822 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7823 list_add_tail(&ri_rec->list, head);
7828 static void free_root_item_list(struct list_head *list)
7830 struct root_item_record *ri_rec;
7832 while (!list_empty(list)) {
7833 ri_rec = list_first_entry(list, struct root_item_record,
7835 list_del_init(&ri_rec->list);
7840 static int deal_root_from_list(struct list_head *list,
7841 struct btrfs_root *root,
7842 struct block_info *bits,
7844 struct cache_tree *pending,
7845 struct cache_tree *seen,
7846 struct cache_tree *reada,
7847 struct cache_tree *nodes,
7848 struct cache_tree *extent_cache,
7849 struct cache_tree *chunk_cache,
7850 struct rb_root *dev_cache,
7851 struct block_group_tree *block_group_cache,
7852 struct device_extent_tree *dev_extent_cache)
7857 while (!list_empty(list)) {
7858 struct root_item_record *rec;
7859 struct extent_buffer *buf;
7860 rec = list_entry(list->next,
7861 struct root_item_record, list);
7863 buf = read_tree_block(root->fs_info->tree_root,
7864 rec->bytenr, rec->level_size, 0);
7865 if (!extent_buffer_uptodate(buf)) {
7866 free_extent_buffer(buf);
7870 add_root_to_pending(buf, extent_cache, pending,
7871 seen, nodes, rec->objectid);
7873 * To rebuild extent tree, we need deal with snapshot
7874 * one by one, otherwise we deal with node firstly which
7875 * can maximize readahead.
7878 ret = run_next_block(root, bits, bits_nr, &last,
7879 pending, seen, reada, nodes,
7880 extent_cache, chunk_cache,
7881 dev_cache, block_group_cache,
7882 dev_extent_cache, rec);
7886 free_extent_buffer(buf);
7887 list_del(&rec->list);
7893 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7894 reada, nodes, extent_cache, chunk_cache,
7895 dev_cache, block_group_cache,
7896 dev_extent_cache, NULL);
7906 static int check_chunks_and_extents(struct btrfs_root *root)
7908 struct rb_root dev_cache;
7909 struct cache_tree chunk_cache;
7910 struct block_group_tree block_group_cache;
7911 struct device_extent_tree dev_extent_cache;
7912 struct cache_tree extent_cache;
7913 struct cache_tree seen;
7914 struct cache_tree pending;
7915 struct cache_tree reada;
7916 struct cache_tree nodes;
7917 struct extent_io_tree excluded_extents;
7918 struct cache_tree corrupt_blocks;
7919 struct btrfs_path path;
7920 struct btrfs_key key;
7921 struct btrfs_key found_key;
7923 struct block_info *bits;
7925 struct extent_buffer *leaf;
7927 struct btrfs_root_item ri;
7928 struct list_head dropping_trees;
7929 struct list_head normal_trees;
7930 struct btrfs_root *root1;
7935 dev_cache = RB_ROOT;
7936 cache_tree_init(&chunk_cache);
7937 block_group_tree_init(&block_group_cache);
7938 device_extent_tree_init(&dev_extent_cache);
7940 cache_tree_init(&extent_cache);
7941 cache_tree_init(&seen);
7942 cache_tree_init(&pending);
7943 cache_tree_init(&nodes);
7944 cache_tree_init(&reada);
7945 cache_tree_init(&corrupt_blocks);
7946 extent_io_tree_init(&excluded_extents);
7947 INIT_LIST_HEAD(&dropping_trees);
7948 INIT_LIST_HEAD(&normal_trees);
7951 root->fs_info->excluded_extents = &excluded_extents;
7952 root->fs_info->fsck_extent_cache = &extent_cache;
7953 root->fs_info->free_extent_hook = free_extent_hook;
7954 root->fs_info->corrupt_blocks = &corrupt_blocks;
7958 bits = malloc(bits_nr * sizeof(struct block_info));
7965 root1 = root->fs_info->tree_root;
7966 level = btrfs_header_level(root1->node);
7967 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7968 root1->node->start, 0, level, 0,
7969 btrfs_level_size(root1, level), NULL);
7972 root1 = root->fs_info->chunk_root;
7973 level = btrfs_header_level(root1->node);
7974 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7975 root1->node->start, 0, level, 0,
7976 btrfs_level_size(root1, level), NULL);
7979 btrfs_init_path(&path);
7982 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7983 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7988 leaf = path.nodes[0];
7989 slot = path.slots[0];
7990 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7991 ret = btrfs_next_leaf(root, &path);
7994 leaf = path.nodes[0];
7995 slot = path.slots[0];
7997 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7998 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7999 unsigned long offset;
8002 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
8003 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
8004 last_snapshot = btrfs_root_last_snapshot(&ri);
8005 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
8006 level = btrfs_root_level(&ri);
8007 level_size = btrfs_level_size(root, level);
8008 ret = add_root_item_to_list(&normal_trees,
8010 btrfs_root_bytenr(&ri),
8011 last_snapshot, level,
8012 0, level_size, NULL);
8016 level = btrfs_root_level(&ri);
8017 level_size = btrfs_level_size(root, level);
8018 objectid = found_key.objectid;
8019 btrfs_disk_key_to_cpu(&found_key,
8021 ret = add_root_item_to_list(&dropping_trees,
8023 btrfs_root_bytenr(&ri),
8024 last_snapshot, level,
8026 level_size, &found_key);
8033 btrfs_release_path(&path);
8036 * check_block can return -EAGAIN if it fixes something, please keep
8037 * this in mind when dealing with return values from these functions, if
8038 * we get -EAGAIN we want to fall through and restart the loop.
8040 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8041 &seen, &reada, &nodes, &extent_cache,
8042 &chunk_cache, &dev_cache, &block_group_cache,
8049 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8050 &pending, &seen, &reada, &nodes,
8051 &extent_cache, &chunk_cache, &dev_cache,
8052 &block_group_cache, &dev_extent_cache);
8059 err = check_chunks(&chunk_cache, &block_group_cache,
8060 &dev_extent_cache, NULL, NULL, NULL, 0);
8068 ret = check_extent_refs(root, &extent_cache);
8075 err = check_devices(&dev_cache, &dev_extent_cache);
8081 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8082 extent_io_tree_cleanup(&excluded_extents);
8083 root->fs_info->fsck_extent_cache = NULL;
8084 root->fs_info->free_extent_hook = NULL;
8085 root->fs_info->corrupt_blocks = NULL;
8086 root->fs_info->excluded_extents = NULL;
8089 free_chunk_cache_tree(&chunk_cache);
8090 free_device_cache_tree(&dev_cache);
8091 free_block_group_tree(&block_group_cache);
8092 free_device_extent_tree(&dev_extent_cache);
8093 free_extent_cache_tree(&seen);
8094 free_extent_cache_tree(&pending);
8095 free_extent_cache_tree(&reada);
8096 free_extent_cache_tree(&nodes);
8099 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8100 free_extent_cache_tree(&seen);
8101 free_extent_cache_tree(&pending);
8102 free_extent_cache_tree(&reada);
8103 free_extent_cache_tree(&nodes);
8104 free_chunk_cache_tree(&chunk_cache);
8105 free_block_group_tree(&block_group_cache);
8106 free_device_cache_tree(&dev_cache);
8107 free_device_extent_tree(&dev_extent_cache);
8108 free_extent_record_cache(root->fs_info, &extent_cache);
8109 free_root_item_list(&normal_trees);
8110 free_root_item_list(&dropping_trees);
8111 extent_io_tree_cleanup(&excluded_extents);
8115 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8116 struct btrfs_root *root, int overwrite)
8118 struct extent_buffer *c;
8119 struct extent_buffer *old = root->node;
8122 struct btrfs_disk_key disk_key = {0,0,0};
8128 extent_buffer_get(c);
8131 c = btrfs_alloc_free_block(trans, root,
8132 btrfs_level_size(root, 0),
8133 root->root_key.objectid,
8134 &disk_key, level, 0, 0);
8137 extent_buffer_get(c);
8141 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8142 btrfs_set_header_level(c, level);
8143 btrfs_set_header_bytenr(c, c->start);
8144 btrfs_set_header_generation(c, trans->transid);
8145 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8146 btrfs_set_header_owner(c, root->root_key.objectid);
8148 write_extent_buffer(c, root->fs_info->fsid,
8149 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8151 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8152 btrfs_header_chunk_tree_uuid(c),
8155 btrfs_mark_buffer_dirty(c);
8157 * this case can happen in the following case:
8159 * 1.overwrite previous root.
8161 * 2.reinit reloc data root, this is because we skip pin
8162 * down reloc data tree before which means we can allocate
8163 * same block bytenr here.
8165 if (old->start == c->start) {
8166 btrfs_set_root_generation(&root->root_item,
8168 root->root_item.level = btrfs_header_level(root->node);
8169 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8170 &root->root_key, &root->root_item);
8172 free_extent_buffer(c);
8176 free_extent_buffer(old);
8178 add_root_to_dirty_list(root);
8182 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8183 struct extent_buffer *eb, int tree_root)
8185 struct extent_buffer *tmp;
8186 struct btrfs_root_item *ri;
8187 struct btrfs_key key;
8190 int level = btrfs_header_level(eb);
8196 * If we have pinned this block before, don't pin it again.
8197 * This can not only avoid forever loop with broken filesystem
8198 * but also give us some speedups.
8200 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8201 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8204 btrfs_pin_extent(fs_info, eb->start, eb->len);
8206 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8207 nritems = btrfs_header_nritems(eb);
8208 for (i = 0; i < nritems; i++) {
8210 btrfs_item_key_to_cpu(eb, &key, i);
8211 if (key.type != BTRFS_ROOT_ITEM_KEY)
8213 /* Skip the extent root and reloc roots */
8214 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8215 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8216 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8218 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8219 bytenr = btrfs_disk_root_bytenr(eb, ri);
8222 * If at any point we start needing the real root we
8223 * will have to build a stump root for the root we are
8224 * in, but for now this doesn't actually use the root so
8225 * just pass in extent_root.
8227 tmp = read_tree_block(fs_info->extent_root, bytenr,
8229 if (!extent_buffer_uptodate(tmp)) {
8230 fprintf(stderr, "Error reading root block\n");
8233 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8234 free_extent_buffer(tmp);
8238 bytenr = btrfs_node_blockptr(eb, i);
8240 /* If we aren't the tree root don't read the block */
8241 if (level == 1 && !tree_root) {
8242 btrfs_pin_extent(fs_info, bytenr, leafsize);
8246 tmp = read_tree_block(fs_info->extent_root, bytenr,
8248 if (!extent_buffer_uptodate(tmp)) {
8249 fprintf(stderr, "Error reading tree block\n");
8252 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8253 free_extent_buffer(tmp);
8262 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8266 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8270 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8273 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8275 struct btrfs_block_group_cache *cache;
8276 struct btrfs_path *path;
8277 struct extent_buffer *leaf;
8278 struct btrfs_chunk *chunk;
8279 struct btrfs_key key;
8283 path = btrfs_alloc_path();
8288 key.type = BTRFS_CHUNK_ITEM_KEY;
8291 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8293 btrfs_free_path(path);
8298 * We do this in case the block groups were screwed up and had alloc
8299 * bits that aren't actually set on the chunks. This happens with
8300 * restored images every time and could happen in real life I guess.
8302 fs_info->avail_data_alloc_bits = 0;
8303 fs_info->avail_metadata_alloc_bits = 0;
8304 fs_info->avail_system_alloc_bits = 0;
8306 /* First we need to create the in-memory block groups */
8308 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8309 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8311 btrfs_free_path(path);
8319 leaf = path->nodes[0];
8320 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8321 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8326 chunk = btrfs_item_ptr(leaf, path->slots[0],
8327 struct btrfs_chunk);
8328 btrfs_add_block_group(fs_info, 0,
8329 btrfs_chunk_type(leaf, chunk),
8330 key.objectid, key.offset,
8331 btrfs_chunk_length(leaf, chunk));
8332 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8333 key.offset + btrfs_chunk_length(leaf, chunk),
8339 cache = btrfs_lookup_first_block_group(fs_info, start);
8343 start = cache->key.objectid + cache->key.offset;
8346 btrfs_free_path(path);
8350 static int reset_balance(struct btrfs_trans_handle *trans,
8351 struct btrfs_fs_info *fs_info)
8353 struct btrfs_root *root = fs_info->tree_root;
8354 struct btrfs_path *path;
8355 struct extent_buffer *leaf;
8356 struct btrfs_key key;
8357 int del_slot, del_nr = 0;
8361 path = btrfs_alloc_path();
8365 key.objectid = BTRFS_BALANCE_OBJECTID;
8366 key.type = BTRFS_BALANCE_ITEM_KEY;
8369 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8374 goto reinit_data_reloc;
8379 ret = btrfs_del_item(trans, root, path);
8382 btrfs_release_path(path);
8384 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8385 key.type = BTRFS_ROOT_ITEM_KEY;
8388 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8392 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8397 ret = btrfs_del_items(trans, root, path,
8404 btrfs_release_path(path);
8407 ret = btrfs_search_slot(trans, root, &key, path,
8414 leaf = path->nodes[0];
8415 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8416 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8418 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8423 del_slot = path->slots[0];
8432 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8436 btrfs_release_path(path);
8439 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8440 key.type = BTRFS_ROOT_ITEM_KEY;
8441 key.offset = (u64)-1;
8442 root = btrfs_read_fs_root(fs_info, &key);
8444 fprintf(stderr, "Error reading data reloc tree\n");
8445 ret = PTR_ERR(root);
8448 record_root_in_trans(trans, root);
8449 ret = btrfs_fsck_reinit_root(trans, root, 0);
8452 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8454 btrfs_free_path(path);
8458 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8459 struct btrfs_fs_info *fs_info)
8465 * The only reason we don't do this is because right now we're just
8466 * walking the trees we find and pinning down their bytes, we don't look
8467 * at any of the leaves. In order to do mixed groups we'd have to check
8468 * the leaves of any fs roots and pin down the bytes for any file
8469 * extents we find. Not hard but why do it if we don't have to?
8471 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8472 fprintf(stderr, "We don't support re-initing the extent tree "
8473 "for mixed block groups yet, please notify a btrfs "
8474 "developer you want to do this so they can add this "
8475 "functionality.\n");
8480 * first we need to walk all of the trees except the extent tree and pin
8481 * down the bytes that are in use so we don't overwrite any existing
8484 ret = pin_metadata_blocks(fs_info);
8486 fprintf(stderr, "error pinning down used bytes\n");
8491 * Need to drop all the block groups since we're going to recreate all
8494 btrfs_free_block_groups(fs_info);
8495 ret = reset_block_groups(fs_info);
8497 fprintf(stderr, "error resetting the block groups\n");
8501 /* Ok we can allocate now, reinit the extent root */
8502 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8504 fprintf(stderr, "extent root initialization failed\n");
8506 * When the transaction code is updated we should end the
8507 * transaction, but for now progs only knows about commit so
8508 * just return an error.
8514 * Now we have all the in-memory block groups setup so we can make
8515 * allocations properly, and the metadata we care about is safe since we
8516 * pinned all of it above.
8519 struct btrfs_block_group_cache *cache;
8521 cache = btrfs_lookup_first_block_group(fs_info, start);
8524 start = cache->key.objectid + cache->key.offset;
8525 ret = btrfs_insert_item(trans, fs_info->extent_root,
8526 &cache->key, &cache->item,
8527 sizeof(cache->item));
8529 fprintf(stderr, "Error adding block group\n");
8532 btrfs_extent_post_op(trans, fs_info->extent_root);
8535 ret = reset_balance(trans, fs_info);
8537 fprintf(stderr, "error reseting the pending balance\n");
8542 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8544 struct btrfs_path *path;
8545 struct btrfs_trans_handle *trans;
8546 struct btrfs_key key;
8549 printf("Recowing metadata block %llu\n", eb->start);
8550 key.objectid = btrfs_header_owner(eb);
8551 key.type = BTRFS_ROOT_ITEM_KEY;
8552 key.offset = (u64)-1;
8554 root = btrfs_read_fs_root(root->fs_info, &key);
8556 fprintf(stderr, "Couldn't find owner root %llu\n",
8558 return PTR_ERR(root);
8561 path = btrfs_alloc_path();
8565 trans = btrfs_start_transaction(root, 1);
8566 if (IS_ERR(trans)) {
8567 btrfs_free_path(path);
8568 return PTR_ERR(trans);
8571 path->lowest_level = btrfs_header_level(eb);
8572 if (path->lowest_level)
8573 btrfs_node_key_to_cpu(eb, &key, 0);
8575 btrfs_item_key_to_cpu(eb, &key, 0);
8577 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8578 btrfs_commit_transaction(trans, root);
8579 btrfs_free_path(path);
8583 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8585 struct btrfs_path *path;
8586 struct btrfs_trans_handle *trans;
8587 struct btrfs_key key;
8590 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8591 bad->key.type, bad->key.offset);
8592 key.objectid = bad->root_id;
8593 key.type = BTRFS_ROOT_ITEM_KEY;
8594 key.offset = (u64)-1;
8596 root = btrfs_read_fs_root(root->fs_info, &key);
8598 fprintf(stderr, "Couldn't find owner root %llu\n",
8600 return PTR_ERR(root);
8603 path = btrfs_alloc_path();
8607 trans = btrfs_start_transaction(root, 1);
8608 if (IS_ERR(trans)) {
8609 btrfs_free_path(path);
8610 return PTR_ERR(trans);
8613 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8619 ret = btrfs_del_item(trans, root, path);
8621 btrfs_commit_transaction(trans, root);
8622 btrfs_free_path(path);
8626 static int zero_log_tree(struct btrfs_root *root)
8628 struct btrfs_trans_handle *trans;
8631 trans = btrfs_start_transaction(root, 1);
8632 if (IS_ERR(trans)) {
8633 ret = PTR_ERR(trans);
8636 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8637 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8638 ret = btrfs_commit_transaction(trans, root);
8642 static int populate_csum(struct btrfs_trans_handle *trans,
8643 struct btrfs_root *csum_root, char *buf, u64 start,
8650 while (offset < len) {
8651 sectorsize = csum_root->sectorsize;
8652 ret = read_extent_data(csum_root, buf, start + offset,
8656 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8657 start + offset, buf, sectorsize);
8660 offset += sectorsize;
8665 static int fill_csum_tree_from_one_fs_root(struct btrfs_trans_handle *trans,
8666 struct btrfs_root *csum_root,
8667 struct btrfs_root *cur_root)
8669 struct btrfs_path *path;
8670 struct btrfs_key key;
8671 struct extent_buffer *node;
8672 struct btrfs_file_extent_item *fi;
8679 path = btrfs_alloc_path();
8682 buf = malloc(cur_root->fs_info->csum_root->sectorsize);
8692 ret = btrfs_search_slot(NULL, cur_root, &key, path, 0, 0);
8695 /* Iterate all regular file extents and fill its csum */
8697 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
8699 if (key.type != BTRFS_EXTENT_DATA_KEY)
8701 node = path->nodes[0];
8702 slot = path->slots[0];
8703 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
8704 if (btrfs_file_extent_type(node, fi) != BTRFS_FILE_EXTENT_REG)
8706 start = btrfs_file_extent_disk_bytenr(node, fi);
8707 len = btrfs_file_extent_disk_num_bytes(node, fi);
8709 ret = populate_csum(trans, csum_root, buf, start, len);
8716 * TODO: if next leaf is corrupted, jump to nearest next valid
8719 ret = btrfs_next_item(cur_root, path);
8729 btrfs_free_path(path);
8734 static int fill_csum_tree_from_fs(struct btrfs_trans_handle *trans,
8735 struct btrfs_root *csum_root)
8737 struct btrfs_fs_info *fs_info = csum_root->fs_info;
8738 struct btrfs_path *path;
8739 struct btrfs_root *tree_root = fs_info->tree_root;
8740 struct btrfs_root *cur_root;
8741 struct extent_buffer *node;
8742 struct btrfs_key key;
8746 path = btrfs_alloc_path();
8750 key.objectid = BTRFS_FS_TREE_OBJECTID;
8752 key.type = BTRFS_ROOT_ITEM_KEY;
8754 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
8763 node = path->nodes[0];
8764 slot = path->slots[0];
8765 btrfs_item_key_to_cpu(node, &key, slot);
8766 if (key.objectid > BTRFS_LAST_FREE_OBJECTID)
8768 if (key.type != BTRFS_ROOT_ITEM_KEY)
8770 if (!is_fstree(key.objectid))
8772 key.offset = (u64)-1;
8774 cur_root = btrfs_read_fs_root(fs_info, &key);
8775 if (IS_ERR(cur_root) || !cur_root) {
8776 fprintf(stderr, "Fail to read fs/subvol tree: %lld\n",
8780 ret = fill_csum_tree_from_one_fs_root(trans, csum_root,
8785 ret = btrfs_next_item(tree_root, path);
8795 btrfs_free_path(path);
8799 static int fill_csum_tree_from_extent(struct btrfs_trans_handle *trans,
8800 struct btrfs_root *csum_root)
8802 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8803 struct btrfs_path *path;
8804 struct btrfs_extent_item *ei;
8805 struct extent_buffer *leaf;
8807 struct btrfs_key key;
8810 path = btrfs_alloc_path();
8815 key.type = BTRFS_EXTENT_ITEM_KEY;
8818 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8820 btrfs_free_path(path);
8824 buf = malloc(csum_root->sectorsize);
8826 btrfs_free_path(path);
8831 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8832 ret = btrfs_next_leaf(extent_root, path);
8840 leaf = path->nodes[0];
8842 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8843 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8848 ei = btrfs_item_ptr(leaf, path->slots[0],
8849 struct btrfs_extent_item);
8850 if (!(btrfs_extent_flags(leaf, ei) &
8851 BTRFS_EXTENT_FLAG_DATA)) {
8856 ret = populate_csum(trans, csum_root, buf, key.objectid,
8863 btrfs_free_path(path);
8869 * Recalculate the csum and put it into the csum tree.
8871 * Extent tree init will wipe out all the extent info, so in that case, we
8872 * can't depend on extent tree, but use fs tree. If search_fs_tree is set, we
8873 * will use fs/subvol trees to init the csum tree.
8875 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8876 struct btrfs_root *csum_root,
8880 return fill_csum_tree_from_fs(trans, csum_root);
8882 return fill_csum_tree_from_extent(trans, csum_root);
8885 struct root_item_info {
8886 /* level of the root */
8888 /* number of nodes at this level, must be 1 for a root */
8892 struct cache_extent cache_extent;
8895 static struct cache_tree *roots_info_cache = NULL;
8897 static void free_roots_info_cache(void)
8899 if (!roots_info_cache)
8902 while (!cache_tree_empty(roots_info_cache)) {
8903 struct cache_extent *entry;
8904 struct root_item_info *rii;
8906 entry = first_cache_extent(roots_info_cache);
8909 remove_cache_extent(roots_info_cache, entry);
8910 rii = container_of(entry, struct root_item_info, cache_extent);
8914 free(roots_info_cache);
8915 roots_info_cache = NULL;
8918 static int build_roots_info_cache(struct btrfs_fs_info *info)
8921 struct btrfs_key key;
8922 struct extent_buffer *leaf;
8923 struct btrfs_path *path;
8925 if (!roots_info_cache) {
8926 roots_info_cache = malloc(sizeof(*roots_info_cache));
8927 if (!roots_info_cache)
8929 cache_tree_init(roots_info_cache);
8932 path = btrfs_alloc_path();
8937 key.type = BTRFS_EXTENT_ITEM_KEY;
8940 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8943 leaf = path->nodes[0];
8946 struct btrfs_key found_key;
8947 struct btrfs_extent_item *ei;
8948 struct btrfs_extent_inline_ref *iref;
8949 int slot = path->slots[0];
8954 struct cache_extent *entry;
8955 struct root_item_info *rii;
8957 if (slot >= btrfs_header_nritems(leaf)) {
8958 ret = btrfs_next_leaf(info->extent_root, path);
8965 leaf = path->nodes[0];
8966 slot = path->slots[0];
8969 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8971 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8972 found_key.type != BTRFS_METADATA_ITEM_KEY)
8975 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8976 flags = btrfs_extent_flags(leaf, ei);
8978 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8979 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8982 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8983 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8984 level = found_key.offset;
8986 struct btrfs_tree_block_info *info;
8988 info = (struct btrfs_tree_block_info *)(ei + 1);
8989 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8990 level = btrfs_tree_block_level(leaf, info);
8994 * For a root extent, it must be of the following type and the
8995 * first (and only one) iref in the item.
8997 type = btrfs_extent_inline_ref_type(leaf, iref);
8998 if (type != BTRFS_TREE_BLOCK_REF_KEY)
9001 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
9002 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9004 rii = malloc(sizeof(struct root_item_info));
9009 rii->cache_extent.start = root_id;
9010 rii->cache_extent.size = 1;
9011 rii->level = (u8)-1;
9012 entry = &rii->cache_extent;
9013 ret = insert_cache_extent(roots_info_cache, entry);
9016 rii = container_of(entry, struct root_item_info,
9020 ASSERT(rii->cache_extent.start == root_id);
9021 ASSERT(rii->cache_extent.size == 1);
9023 if (level > rii->level || rii->level == (u8)-1) {
9025 rii->bytenr = found_key.objectid;
9026 rii->gen = btrfs_extent_generation(leaf, ei);
9027 rii->node_count = 1;
9028 } else if (level == rii->level) {
9036 btrfs_free_path(path);
9041 static int maybe_repair_root_item(struct btrfs_fs_info *info,
9042 struct btrfs_path *path,
9043 const struct btrfs_key *root_key,
9044 const int read_only_mode)
9046 const u64 root_id = root_key->objectid;
9047 struct cache_extent *entry;
9048 struct root_item_info *rii;
9049 struct btrfs_root_item ri;
9050 unsigned long offset;
9052 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9055 "Error: could not find extent items for root %llu\n",
9056 root_key->objectid);
9060 rii = container_of(entry, struct root_item_info, cache_extent);
9061 ASSERT(rii->cache_extent.start == root_id);
9062 ASSERT(rii->cache_extent.size == 1);
9064 if (rii->node_count != 1) {
9066 "Error: could not find btree root extent for root %llu\n",
9071 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
9072 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
9074 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
9075 btrfs_root_level(&ri) != rii->level ||
9076 btrfs_root_generation(&ri) != rii->gen) {
9079 * If we're in repair mode but our caller told us to not update
9080 * the root item, i.e. just check if it needs to be updated, don't
9081 * print this message, since the caller will call us again shortly
9082 * for the same root item without read only mode (the caller will
9083 * open a transaction first).
9085 if (!(read_only_mode && repair))
9087 "%sroot item for root %llu,"
9088 " current bytenr %llu, current gen %llu, current level %u,"
9089 " new bytenr %llu, new gen %llu, new level %u\n",
9090 (read_only_mode ? "" : "fixing "),
9092 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
9093 btrfs_root_level(&ri),
9094 rii->bytenr, rii->gen, rii->level);
9096 if (btrfs_root_generation(&ri) > rii->gen) {
9098 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
9099 root_id, btrfs_root_generation(&ri), rii->gen);
9103 if (!read_only_mode) {
9104 btrfs_set_root_bytenr(&ri, rii->bytenr);
9105 btrfs_set_root_level(&ri, rii->level);
9106 btrfs_set_root_generation(&ri, rii->gen);
9107 write_extent_buffer(path->nodes[0], &ri,
9108 offset, sizeof(ri));
9118 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
9119 * caused read-only snapshots to be corrupted if they were created at a moment
9120 * when the source subvolume/snapshot had orphan items. The issue was that the
9121 * on-disk root items became incorrect, referring to the pre orphan cleanup root
9122 * node instead of the post orphan cleanup root node.
9123 * So this function, and its callees, just detects and fixes those cases. Even
9124 * though the regression was for read-only snapshots, this function applies to
9125 * any snapshot/subvolume root.
9126 * This must be run before any other repair code - not doing it so, makes other
9127 * repair code delete or modify backrefs in the extent tree for example, which
9128 * will result in an inconsistent fs after repairing the root items.
9130 static int repair_root_items(struct btrfs_fs_info *info)
9132 struct btrfs_path *path = NULL;
9133 struct btrfs_key key;
9134 struct extent_buffer *leaf;
9135 struct btrfs_trans_handle *trans = NULL;
9140 ret = build_roots_info_cache(info);
9144 path = btrfs_alloc_path();
9150 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
9151 key.type = BTRFS_ROOT_ITEM_KEY;
9156 * Avoid opening and committing transactions if a leaf doesn't have
9157 * any root items that need to be fixed, so that we avoid rotating
9158 * backup roots unnecessarily.
9161 trans = btrfs_start_transaction(info->tree_root, 1);
9162 if (IS_ERR(trans)) {
9163 ret = PTR_ERR(trans);
9168 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
9172 leaf = path->nodes[0];
9175 struct btrfs_key found_key;
9177 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
9178 int no_more_keys = find_next_key(path, &key);
9180 btrfs_release_path(path);
9182 ret = btrfs_commit_transaction(trans,
9194 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9196 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
9198 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9201 ret = maybe_repair_root_item(info, path, &found_key,
9206 if (!trans && repair) {
9209 btrfs_release_path(path);
9219 free_roots_info_cache();
9221 btrfs_free_path(path);
9223 btrfs_commit_transaction(trans, info->tree_root);
9230 const char * const cmd_check_usage[] = {
9231 "btrfs check [options] <device>",
9232 "Check an unmounted btrfs filesystem.",
9234 "-s|--super <superblock> use this superblock copy",
9235 "-b|--backup use the backup root copy",
9236 "--repair try to repair the filesystem",
9237 "--init-csum-tree create a new CRC tree",
9238 "--init-extent-tree create a new extent tree",
9239 "--check-data-csum verify checkums of data blocks",
9240 "--qgroup-report print a report on qgroup consistency",
9241 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9242 "--tree-root <bytenr> use the given bytenr for the tree root",
9246 int cmd_check(int argc, char **argv)
9248 struct cache_tree root_cache;
9249 struct btrfs_root *root;
9250 struct btrfs_fs_info *info;
9253 u64 tree_root_bytenr = 0;
9254 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9257 int init_csum_tree = 0;
9259 int qgroup_report = 0;
9260 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9264 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9265 OPT_CHECK_CSUM, OPT_READONLY };
9266 static const struct option long_options[] = {
9267 { "super", required_argument, NULL, 's' },
9268 { "repair", no_argument, NULL, OPT_REPAIR },
9269 { "readonly", no_argument, NULL, OPT_READONLY },
9270 { "init-csum-tree", no_argument, NULL, OPT_INIT_CSUM },
9271 { "init-extent-tree", no_argument, NULL, OPT_INIT_EXTENT },
9272 { "check-data-csum", no_argument, NULL, OPT_CHECK_CSUM },
9273 { "backup", no_argument, NULL, 'b' },
9274 { "subvol-extents", required_argument, NULL, 'E' },
9275 { "qgroup-report", no_argument, NULL, 'Q' },
9276 { "tree-root", required_argument, NULL, 'r' },
9280 c = getopt_long(argc, argv, "as:br:", long_options, NULL);
9284 case 'a': /* ignored */ break;
9286 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9289 num = arg_strtou64(optarg);
9290 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9292 "ERROR: super mirror should be less than: %d\n",
9293 BTRFS_SUPER_MIRROR_MAX);
9296 bytenr = btrfs_sb_offset(((int)num));
9297 printf("using SB copy %llu, bytenr %llu\n", num,
9298 (unsigned long long)bytenr);
9304 subvolid = arg_strtou64(optarg);
9307 tree_root_bytenr = arg_strtou64(optarg);
9311 usage(cmd_check_usage);
9313 printf("enabling repair mode\n");
9315 ctree_flags |= OPEN_CTREE_WRITES;
9321 printf("Creating a new CRC tree\n");
9324 ctree_flags |= OPEN_CTREE_WRITES;
9326 case OPT_INIT_EXTENT:
9327 init_extent_tree = 1;
9328 ctree_flags |= (OPEN_CTREE_WRITES |
9329 OPEN_CTREE_NO_BLOCK_GROUPS);
9332 case OPT_CHECK_CSUM:
9333 check_data_csum = 1;
9337 argc = argc - optind;
9339 if (check_argc_exact(argc, 1))
9340 usage(cmd_check_usage);
9342 /* This check is the only reason for --readonly to exist */
9343 if (readonly && repair) {
9344 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9349 cache_tree_init(&root_cache);
9351 if((ret = check_mounted(argv[optind])) < 0) {
9352 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9355 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9360 /* only allow partial opening under repair mode */
9362 ctree_flags |= OPEN_CTREE_PARTIAL;
9364 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9367 fprintf(stderr, "Couldn't open file system\n");
9372 root = info->fs_root;
9375 * repair mode will force us to commit transaction which
9376 * will make us fail to load log tree when mounting.
9378 if (repair && btrfs_super_log_root(info->super_copy)) {
9379 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9384 ret = zero_log_tree(root);
9386 fprintf(stderr, "fail to zero log tree\n");
9391 uuid_unparse(info->super_copy->fsid, uuidbuf);
9392 if (qgroup_report) {
9393 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9395 ret = qgroup_verify_all(info);
9397 print_qgroup_report(1);
9401 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9402 subvolid, argv[optind], uuidbuf);
9403 ret = print_extent_state(info, subvolid);
9406 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9408 if (!extent_buffer_uptodate(info->tree_root->node) ||
9409 !extent_buffer_uptodate(info->dev_root->node) ||
9410 !extent_buffer_uptodate(info->chunk_root->node)) {
9411 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9416 if (init_extent_tree || init_csum_tree) {
9417 struct btrfs_trans_handle *trans;
9419 trans = btrfs_start_transaction(info->extent_root, 0);
9420 if (IS_ERR(trans)) {
9421 fprintf(stderr, "Error starting transaction\n");
9422 ret = PTR_ERR(trans);
9426 if (init_extent_tree) {
9427 printf("Creating a new extent tree\n");
9428 ret = reinit_extent_tree(trans, info);
9433 if (init_csum_tree) {
9434 fprintf(stderr, "Reinit crc root\n");
9435 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9437 fprintf(stderr, "crc root initialization failed\n");
9442 ret = fill_csum_tree(trans, info->csum_root,
9445 fprintf(stderr, "crc refilling failed\n");
9450 * Ok now we commit and run the normal fsck, which will add
9451 * extent entries for all of the items it finds.
9453 ret = btrfs_commit_transaction(trans, info->extent_root);
9457 if (!extent_buffer_uptodate(info->extent_root->node)) {
9458 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9462 if (!extent_buffer_uptodate(info->csum_root->node)) {
9463 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9468 fprintf(stderr, "checking extents\n");
9469 ret = check_chunks_and_extents(root);
9471 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9473 ret = repair_root_items(info);
9477 fprintf(stderr, "Fixed %d roots.\n", ret);
9479 } else if (ret > 0) {
9481 "Found %d roots with an outdated root item.\n",
9484 "Please run a filesystem check with the option --repair to fix them.\n");
9489 fprintf(stderr, "checking free space cache\n");
9490 ret = check_space_cache(root);
9495 * We used to have to have these hole extents in between our real
9496 * extents so if we don't have this flag set we need to make sure there
9497 * are no gaps in the file extents for inodes, otherwise we can just
9498 * ignore it when this happens.
9500 no_holes = btrfs_fs_incompat(root->fs_info,
9501 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9502 fprintf(stderr, "checking fs roots\n");
9503 ret = check_fs_roots(root, &root_cache);
9507 fprintf(stderr, "checking csums\n");
9508 ret = check_csums(root);
9512 fprintf(stderr, "checking root refs\n");
9513 ret = check_root_refs(root, &root_cache);
9517 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9518 struct extent_buffer *eb;
9520 eb = list_first_entry(&root->fs_info->recow_ebs,
9521 struct extent_buffer, recow);
9522 list_del_init(&eb->recow);
9523 ret = recow_extent_buffer(root, eb);
9528 while (!list_empty(&delete_items)) {
9529 struct bad_item *bad;
9531 bad = list_first_entry(&delete_items, struct bad_item, list);
9532 list_del_init(&bad->list);
9534 ret = delete_bad_item(root, bad);
9538 if (info->quota_enabled) {
9540 fprintf(stderr, "checking quota groups\n");
9541 err = qgroup_verify_all(info);
9546 if (!list_empty(&root->fs_info->recow_ebs)) {
9547 fprintf(stderr, "Transid errors in file system\n");
9551 print_qgroup_report(0);
9552 if (found_old_backref) { /*
9553 * there was a disk format change when mixed
9554 * backref was in testing tree. The old format
9555 * existed about one week.
9557 printf("\n * Found old mixed backref format. "
9558 "The old format is not supported! *"
9559 "\n * Please mount the FS in readonly mode, "
9560 "backup data and re-format the FS. *\n\n");
9563 printf("found %llu bytes used err is %d\n",
9564 (unsigned long long)bytes_used, ret);
9565 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9566 printf("total tree bytes: %llu\n",
9567 (unsigned long long)total_btree_bytes);
9568 printf("total fs tree bytes: %llu\n",
9569 (unsigned long long)total_fs_tree_bytes);
9570 printf("total extent tree bytes: %llu\n",
9571 (unsigned long long)total_extent_tree_bytes);
9572 printf("btree space waste bytes: %llu\n",
9573 (unsigned long long)btree_space_waste);
9574 printf("file data blocks allocated: %llu\n referenced %llu\n",
9575 (unsigned long long)data_bytes_allocated,
9576 (unsigned long long)data_bytes_referenced);
9577 printf("%s\n", PACKAGE_STRING);
9579 free_root_recs_tree(&root_cache);