2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
23 #include <sys/types.h>
27 #include <uuid/uuid.h>
32 #include "print-tree.h"
33 #include "transaction.h"
36 #include "free-space-cache.h"
38 #include "qgroup-verify.h"
39 #include "rbtree-utils.h"
43 static u64 bytes_used = 0;
44 static u64 total_csum_bytes = 0;
45 static u64 total_btree_bytes = 0;
46 static u64 total_fs_tree_bytes = 0;
47 static u64 total_extent_tree_bytes = 0;
48 static u64 btree_space_waste = 0;
49 static u64 data_bytes_allocated = 0;
50 static u64 data_bytes_referenced = 0;
51 static int found_old_backref = 0;
52 static LIST_HEAD(duplicate_extents);
53 static LIST_HEAD(delete_items);
54 static int repair = 0;
55 static int no_holes = 0;
56 static int init_extent_tree = 0;
57 static int check_data_csum = 0;
59 struct extent_backref {
60 struct list_head list;
61 unsigned int is_data:1;
62 unsigned int found_extent_tree:1;
63 unsigned int full_backref:1;
64 unsigned int found_ref:1;
65 unsigned int broken:1;
69 struct extent_backref node;
84 * Much like data_backref, just removed the undetermined members
85 * and change it to use list_head.
86 * During extent scan, it is stored in root->orphan_data_extent.
87 * During fs tree scan, it is then moved to inode_rec->orphan_data_extents.
89 struct orphan_data_extent {
90 struct list_head list;
99 struct extent_backref node;
106 struct extent_record {
107 struct list_head backrefs;
108 struct list_head dups;
109 struct list_head list;
110 struct cache_extent cache;
111 struct btrfs_disk_key parent_key;
116 u64 extent_item_refs;
118 u64 parent_generation;
122 int flag_block_full_backref;
123 unsigned int found_rec:1;
124 unsigned int content_checked:1;
125 unsigned int owner_ref_checked:1;
126 unsigned int is_root:1;
127 unsigned int metadata:1;
128 unsigned int bad_full_backref:1;
131 struct inode_backref {
132 struct list_head list;
133 unsigned int found_dir_item:1;
134 unsigned int found_dir_index:1;
135 unsigned int found_inode_ref:1;
136 unsigned int filetype:8;
138 unsigned int ref_type;
145 struct root_item_record {
146 struct list_head list;
153 struct btrfs_key drop_key;
156 #define REF_ERR_NO_DIR_ITEM (1 << 0)
157 #define REF_ERR_NO_DIR_INDEX (1 << 1)
158 #define REF_ERR_NO_INODE_REF (1 << 2)
159 #define REF_ERR_DUP_DIR_ITEM (1 << 3)
160 #define REF_ERR_DUP_DIR_INDEX (1 << 4)
161 #define REF_ERR_DUP_INODE_REF (1 << 5)
162 #define REF_ERR_INDEX_UNMATCH (1 << 6)
163 #define REF_ERR_FILETYPE_UNMATCH (1 << 7)
164 #define REF_ERR_NAME_TOO_LONG (1 << 8) // 100
165 #define REF_ERR_NO_ROOT_REF (1 << 9)
166 #define REF_ERR_NO_ROOT_BACKREF (1 << 10)
167 #define REF_ERR_DUP_ROOT_REF (1 << 11)
168 #define REF_ERR_DUP_ROOT_BACKREF (1 << 12)
170 struct file_extent_hole {
176 /* Compatible function to allow reuse of old codes */
177 static u64 first_extent_gap(struct rb_root *holes)
179 struct file_extent_hole *hole;
181 if (RB_EMPTY_ROOT(holes))
184 hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
188 int compare_hole(struct rb_node *node1, struct rb_node *node2)
190 struct file_extent_hole *hole1;
191 struct file_extent_hole *hole2;
193 hole1 = rb_entry(node1, struct file_extent_hole, node);
194 hole2 = rb_entry(node2, struct file_extent_hole, node);
196 if (hole1->start > hole2->start)
198 if (hole1->start < hole2->start)
200 /* Now hole1->start == hole2->start */
201 if (hole1->len >= hole2->len)
203 * Hole 1 will be merge center
204 * Same hole will be merged later
207 /* Hole 2 will be merge center */
212 * Add a hole to the record
214 * This will do hole merge for copy_file_extent_holes(),
215 * which will ensure there won't be continuous holes.
217 static int add_file_extent_hole(struct rb_root *holes,
220 struct file_extent_hole *hole;
221 struct file_extent_hole *prev = NULL;
222 struct file_extent_hole *next = NULL;
224 hole = malloc(sizeof(*hole));
229 /* Since compare will not return 0, no -EEXIST will happen */
230 rb_insert(holes, &hole->node, compare_hole);
232 /* simple merge with previous hole */
233 if (rb_prev(&hole->node))
234 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
236 if (prev && prev->start + prev->len >= hole->start) {
237 hole->len = hole->start + hole->len - prev->start;
238 hole->start = prev->start;
239 rb_erase(&prev->node, holes);
244 /* iterate merge with next holes */
246 if (!rb_next(&hole->node))
248 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
250 if (hole->start + hole->len >= next->start) {
251 if (hole->start + hole->len <= next->start + next->len)
252 hole->len = next->start + next->len -
254 rb_erase(&next->node, holes);
263 static int compare_hole_range(struct rb_node *node, void *data)
265 struct file_extent_hole *hole;
268 hole = (struct file_extent_hole *)data;
271 hole = rb_entry(node, struct file_extent_hole, node);
272 if (start < hole->start)
274 if (start >= hole->start && start < hole->start + hole->len)
280 * Delete a hole in the record
282 * This will do the hole split and is much restrict than add.
284 static int del_file_extent_hole(struct rb_root *holes,
287 struct file_extent_hole *hole;
288 struct file_extent_hole tmp;
293 struct rb_node *node;
300 node = rb_search(holes, &tmp, compare_hole_range, NULL);
303 hole = rb_entry(node, struct file_extent_hole, node);
304 if (start + len > hole->start + hole->len)
308 * Now there will be no overflap, delete the hole and re-add the
309 * split(s) if they exists.
311 if (start > hole->start) {
312 prev_start = hole->start;
313 prev_len = start - hole->start;
316 if (hole->start + hole->len > start + len) {
317 next_start = start + len;
318 next_len = hole->start + hole->len - start - len;
321 rb_erase(node, holes);
324 ret = add_file_extent_hole(holes, prev_start, prev_len);
329 ret = add_file_extent_hole(holes, next_start, next_len);
336 static int copy_file_extent_holes(struct rb_root *dst,
339 struct file_extent_hole *hole;
340 struct rb_node *node;
343 node = rb_first(src);
345 hole = rb_entry(node, struct file_extent_hole, node);
346 ret = add_file_extent_hole(dst, hole->start, hole->len);
349 node = rb_next(node);
354 static void free_file_extent_holes(struct rb_root *holes)
356 struct rb_node *node;
357 struct file_extent_hole *hole;
359 node = rb_first(holes);
361 hole = rb_entry(node, struct file_extent_hole, node);
362 rb_erase(node, holes);
364 node = rb_first(holes);
368 struct inode_record {
369 struct list_head backrefs;
370 unsigned int checked:1;
371 unsigned int merging:1;
372 unsigned int found_inode_item:1;
373 unsigned int found_dir_item:1;
374 unsigned int found_file_extent:1;
375 unsigned int found_csum_item:1;
376 unsigned int some_csum_missing:1;
377 unsigned int nodatasum:1;
390 struct rb_root holes;
391 struct list_head orphan_extents;
396 #define I_ERR_NO_INODE_ITEM (1 << 0)
397 #define I_ERR_NO_ORPHAN_ITEM (1 << 1)
398 #define I_ERR_DUP_INODE_ITEM (1 << 2)
399 #define I_ERR_DUP_DIR_INDEX (1 << 3)
400 #define I_ERR_ODD_DIR_ITEM (1 << 4)
401 #define I_ERR_ODD_FILE_EXTENT (1 << 5)
402 #define I_ERR_BAD_FILE_EXTENT (1 << 6)
403 #define I_ERR_FILE_EXTENT_OVERLAP (1 << 7)
404 #define I_ERR_FILE_EXTENT_DISCOUNT (1 << 8) // 100
405 #define I_ERR_DIR_ISIZE_WRONG (1 << 9)
406 #define I_ERR_FILE_NBYTES_WRONG (1 << 10) // 400
407 #define I_ERR_ODD_CSUM_ITEM (1 << 11)
408 #define I_ERR_SOME_CSUM_MISSING (1 << 12)
409 #define I_ERR_LINK_COUNT_WRONG (1 << 13)
410 #define I_ERR_FILE_EXTENT_ORPHAN (1 << 14)
412 struct root_backref {
413 struct list_head list;
414 unsigned int found_dir_item:1;
415 unsigned int found_dir_index:1;
416 unsigned int found_back_ref:1;
417 unsigned int found_forward_ref:1;
418 unsigned int reachable:1;
428 struct list_head backrefs;
429 struct cache_extent cache;
430 unsigned int found_root_item:1;
436 struct cache_extent cache;
441 struct cache_extent cache;
442 struct cache_tree root_cache;
443 struct cache_tree inode_cache;
444 struct inode_record *current;
453 struct walk_control {
454 struct cache_tree shared;
455 struct shared_node *nodes[BTRFS_MAX_LEVEL];
461 struct btrfs_key key;
463 struct list_head list;
466 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
468 static void record_root_in_trans(struct btrfs_trans_handle *trans,
469 struct btrfs_root *root)
471 if (root->last_trans != trans->transid) {
472 root->track_dirty = 1;
473 root->last_trans = trans->transid;
474 root->commit_root = root->node;
475 extent_buffer_get(root->node);
479 static u8 imode_to_type(u32 imode)
482 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
483 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
484 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
485 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
486 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
487 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
488 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
489 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
492 return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
496 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
498 struct device_record *rec1;
499 struct device_record *rec2;
501 rec1 = rb_entry(node1, struct device_record, node);
502 rec2 = rb_entry(node2, struct device_record, node);
503 if (rec1->devid > rec2->devid)
505 else if (rec1->devid < rec2->devid)
511 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
513 struct inode_record *rec;
514 struct inode_backref *backref;
515 struct inode_backref *orig;
516 struct orphan_data_extent *src_orphan;
517 struct orphan_data_extent *dst_orphan;
520 rec = malloc(sizeof(*rec));
521 memcpy(rec, orig_rec, sizeof(*rec));
523 INIT_LIST_HEAD(&rec->backrefs);
524 INIT_LIST_HEAD(&rec->orphan_extents);
526 list_for_each_entry(orig, &orig_rec->backrefs, list) {
527 size = sizeof(*orig) + orig->namelen + 1;
528 backref = malloc(size);
529 memcpy(backref, orig, size);
530 list_add_tail(&backref->list, &rec->backrefs);
532 list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
533 dst_orphan = malloc(sizeof(*dst_orphan));
534 /* TODO: Fix all the HELL of un-catched -ENOMEM case */
536 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
537 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
542 static void print_orphan_data_extents(struct list_head *orphan_extents,
545 struct orphan_data_extent *orphan;
547 if (list_empty(orphan_extents))
549 printf("The following data extent is lost in tree %llu:\n",
551 list_for_each_entry(orphan, orphan_extents, list) {
552 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
553 orphan->objectid, orphan->offset, orphan->disk_bytenr,
558 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
560 u64 root_objectid = root->root_key.objectid;
561 int errors = rec->errors;
565 /* reloc root errors, we print its corresponding fs root objectid*/
566 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
567 root_objectid = root->root_key.offset;
568 fprintf(stderr, "reloc");
570 fprintf(stderr, "root %llu inode %llu errors %x",
571 (unsigned long long) root_objectid,
572 (unsigned long long) rec->ino, rec->errors);
574 if (errors & I_ERR_NO_INODE_ITEM)
575 fprintf(stderr, ", no inode item");
576 if (errors & I_ERR_NO_ORPHAN_ITEM)
577 fprintf(stderr, ", no orphan item");
578 if (errors & I_ERR_DUP_INODE_ITEM)
579 fprintf(stderr, ", dup inode item");
580 if (errors & I_ERR_DUP_DIR_INDEX)
581 fprintf(stderr, ", dup dir index");
582 if (errors & I_ERR_ODD_DIR_ITEM)
583 fprintf(stderr, ", odd dir item");
584 if (errors & I_ERR_ODD_FILE_EXTENT)
585 fprintf(stderr, ", odd file extent");
586 if (errors & I_ERR_BAD_FILE_EXTENT)
587 fprintf(stderr, ", bad file extent");
588 if (errors & I_ERR_FILE_EXTENT_OVERLAP)
589 fprintf(stderr, ", file extent overlap");
590 if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
591 fprintf(stderr, ", file extent discount");
592 if (errors & I_ERR_DIR_ISIZE_WRONG)
593 fprintf(stderr, ", dir isize wrong");
594 if (errors & I_ERR_FILE_NBYTES_WRONG)
595 fprintf(stderr, ", nbytes wrong");
596 if (errors & I_ERR_ODD_CSUM_ITEM)
597 fprintf(stderr, ", odd csum item");
598 if (errors & I_ERR_SOME_CSUM_MISSING)
599 fprintf(stderr, ", some csum missing");
600 if (errors & I_ERR_LINK_COUNT_WRONG)
601 fprintf(stderr, ", link count wrong");
602 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
603 fprintf(stderr, ", orphan file extent");
604 fprintf(stderr, "\n");
605 /* Print the orphan extents if needed */
606 if (errors & I_ERR_FILE_EXTENT_ORPHAN)
607 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
609 /* Print the holes if needed */
610 if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
611 struct file_extent_hole *hole;
612 struct rb_node *node;
614 node = rb_first(&rec->holes);
615 fprintf(stderr, "Found file extent holes:\n");
617 hole = rb_entry(node, struct file_extent_hole, node);
618 fprintf(stderr, "\tstart: %llu, len:%llu\n",
619 hole->start, hole->len);
620 node = rb_next(node);
625 static void print_ref_error(int errors)
627 if (errors & REF_ERR_NO_DIR_ITEM)
628 fprintf(stderr, ", no dir item");
629 if (errors & REF_ERR_NO_DIR_INDEX)
630 fprintf(stderr, ", no dir index");
631 if (errors & REF_ERR_NO_INODE_REF)
632 fprintf(stderr, ", no inode ref");
633 if (errors & REF_ERR_DUP_DIR_ITEM)
634 fprintf(stderr, ", dup dir item");
635 if (errors & REF_ERR_DUP_DIR_INDEX)
636 fprintf(stderr, ", dup dir index");
637 if (errors & REF_ERR_DUP_INODE_REF)
638 fprintf(stderr, ", dup inode ref");
639 if (errors & REF_ERR_INDEX_UNMATCH)
640 fprintf(stderr, ", index unmatch");
641 if (errors & REF_ERR_FILETYPE_UNMATCH)
642 fprintf(stderr, ", filetype unmatch");
643 if (errors & REF_ERR_NAME_TOO_LONG)
644 fprintf(stderr, ", name too long");
645 if (errors & REF_ERR_NO_ROOT_REF)
646 fprintf(stderr, ", no root ref");
647 if (errors & REF_ERR_NO_ROOT_BACKREF)
648 fprintf(stderr, ", no root backref");
649 if (errors & REF_ERR_DUP_ROOT_REF)
650 fprintf(stderr, ", dup root ref");
651 if (errors & REF_ERR_DUP_ROOT_BACKREF)
652 fprintf(stderr, ", dup root backref");
653 fprintf(stderr, "\n");
656 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
659 struct ptr_node *node;
660 struct cache_extent *cache;
661 struct inode_record *rec = NULL;
664 cache = lookup_cache_extent(inode_cache, ino, 1);
666 node = container_of(cache, struct ptr_node, cache);
668 if (mod && rec->refs > 1) {
669 node->data = clone_inode_rec(rec);
674 rec = calloc(1, sizeof(*rec));
676 rec->extent_start = (u64)-1;
678 INIT_LIST_HEAD(&rec->backrefs);
679 INIT_LIST_HEAD(&rec->orphan_extents);
680 rec->holes = RB_ROOT;
682 node = malloc(sizeof(*node));
683 node->cache.start = ino;
684 node->cache.size = 1;
687 if (ino == BTRFS_FREE_INO_OBJECTID)
690 ret = insert_cache_extent(inode_cache, &node->cache);
696 static void free_orphan_data_extents(struct list_head *orphan_extents)
698 struct orphan_data_extent *orphan;
700 while (!list_empty(orphan_extents)) {
701 orphan = list_entry(orphan_extents->next,
702 struct orphan_data_extent, list);
703 list_del(&orphan->list);
708 static void free_inode_rec(struct inode_record *rec)
710 struct inode_backref *backref;
715 while (!list_empty(&rec->backrefs)) {
716 backref = list_entry(rec->backrefs.next,
717 struct inode_backref, list);
718 list_del(&backref->list);
721 free_orphan_data_extents(&rec->orphan_extents);
722 free_file_extent_holes(&rec->holes);
726 static int can_free_inode_rec(struct inode_record *rec)
728 if (!rec->errors && rec->checked && rec->found_inode_item &&
729 rec->nlink == rec->found_link && list_empty(&rec->backrefs))
734 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
735 struct inode_record *rec)
737 struct cache_extent *cache;
738 struct inode_backref *tmp, *backref;
739 struct ptr_node *node;
740 unsigned char filetype;
742 if (!rec->found_inode_item)
745 filetype = imode_to_type(rec->imode);
746 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
747 if (backref->found_dir_item && backref->found_dir_index) {
748 if (backref->filetype != filetype)
749 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
750 if (!backref->errors && backref->found_inode_ref) {
751 list_del(&backref->list);
757 if (!rec->checked || rec->merging)
760 if (S_ISDIR(rec->imode)) {
761 if (rec->found_size != rec->isize)
762 rec->errors |= I_ERR_DIR_ISIZE_WRONG;
763 if (rec->found_file_extent)
764 rec->errors |= I_ERR_ODD_FILE_EXTENT;
765 } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
766 if (rec->found_dir_item)
767 rec->errors |= I_ERR_ODD_DIR_ITEM;
768 if (rec->found_size != rec->nbytes)
769 rec->errors |= I_ERR_FILE_NBYTES_WRONG;
770 if (rec->nlink > 0 && !no_holes &&
771 (rec->extent_end < rec->isize ||
772 first_extent_gap(&rec->holes) < rec->isize))
773 rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
776 if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
777 if (rec->found_csum_item && rec->nodatasum)
778 rec->errors |= I_ERR_ODD_CSUM_ITEM;
779 if (rec->some_csum_missing && !rec->nodatasum)
780 rec->errors |= I_ERR_SOME_CSUM_MISSING;
783 BUG_ON(rec->refs != 1);
784 if (can_free_inode_rec(rec)) {
785 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
786 node = container_of(cache, struct ptr_node, cache);
787 BUG_ON(node->data != rec);
788 remove_cache_extent(inode_cache, &node->cache);
794 static int check_orphan_item(struct btrfs_root *root, u64 ino)
796 struct btrfs_path path;
797 struct btrfs_key key;
800 key.objectid = BTRFS_ORPHAN_OBJECTID;
801 key.type = BTRFS_ORPHAN_ITEM_KEY;
804 btrfs_init_path(&path);
805 ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
806 btrfs_release_path(&path);
812 static int process_inode_item(struct extent_buffer *eb,
813 int slot, struct btrfs_key *key,
814 struct shared_node *active_node)
816 struct inode_record *rec;
817 struct btrfs_inode_item *item;
819 rec = active_node->current;
820 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
821 if (rec->found_inode_item) {
822 rec->errors |= I_ERR_DUP_INODE_ITEM;
825 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
826 rec->nlink = btrfs_inode_nlink(eb, item);
827 rec->isize = btrfs_inode_size(eb, item);
828 rec->nbytes = btrfs_inode_nbytes(eb, item);
829 rec->imode = btrfs_inode_mode(eb, item);
830 if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
832 rec->found_inode_item = 1;
834 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
835 maybe_free_inode_rec(&active_node->inode_cache, rec);
839 static struct inode_backref *get_inode_backref(struct inode_record *rec,
841 int namelen, u64 dir)
843 struct inode_backref *backref;
845 list_for_each_entry(backref, &rec->backrefs, list) {
846 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
848 if (backref->dir != dir || backref->namelen != namelen)
850 if (memcmp(name, backref->name, namelen))
855 backref = malloc(sizeof(*backref) + namelen + 1);
856 memset(backref, 0, sizeof(*backref));
858 backref->namelen = namelen;
859 memcpy(backref->name, name, namelen);
860 backref->name[namelen] = '\0';
861 list_add_tail(&backref->list, &rec->backrefs);
865 static int add_inode_backref(struct cache_tree *inode_cache,
866 u64 ino, u64 dir, u64 index,
867 const char *name, int namelen,
868 int filetype, int itemtype, int errors)
870 struct inode_record *rec;
871 struct inode_backref *backref;
873 rec = get_inode_rec(inode_cache, ino, 1);
874 backref = get_inode_backref(rec, name, namelen, dir);
876 backref->errors |= errors;
877 if (itemtype == BTRFS_DIR_INDEX_KEY) {
878 if (backref->found_dir_index)
879 backref->errors |= REF_ERR_DUP_DIR_INDEX;
880 if (backref->found_inode_ref && backref->index != index)
881 backref->errors |= REF_ERR_INDEX_UNMATCH;
882 if (backref->found_dir_item && backref->filetype != filetype)
883 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
885 backref->index = index;
886 backref->filetype = filetype;
887 backref->found_dir_index = 1;
888 } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
890 if (backref->found_dir_item)
891 backref->errors |= REF_ERR_DUP_DIR_ITEM;
892 if (backref->found_dir_index && backref->filetype != filetype)
893 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
895 backref->filetype = filetype;
896 backref->found_dir_item = 1;
897 } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
898 (itemtype == BTRFS_INODE_EXTREF_KEY)) {
899 if (backref->found_inode_ref)
900 backref->errors |= REF_ERR_DUP_INODE_REF;
901 if (backref->found_dir_index && backref->index != index)
902 backref->errors |= REF_ERR_INDEX_UNMATCH;
904 backref->index = index;
906 backref->ref_type = itemtype;
907 backref->found_inode_ref = 1;
912 maybe_free_inode_rec(inode_cache, rec);
916 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
917 struct cache_tree *dst_cache)
919 struct inode_backref *backref;
924 list_for_each_entry(backref, &src->backrefs, list) {
925 if (backref->found_dir_index) {
926 add_inode_backref(dst_cache, dst->ino, backref->dir,
927 backref->index, backref->name,
928 backref->namelen, backref->filetype,
929 BTRFS_DIR_INDEX_KEY, backref->errors);
931 if (backref->found_dir_item) {
933 add_inode_backref(dst_cache, dst->ino,
934 backref->dir, 0, backref->name,
935 backref->namelen, backref->filetype,
936 BTRFS_DIR_ITEM_KEY, backref->errors);
938 if (backref->found_inode_ref) {
939 add_inode_backref(dst_cache, dst->ino,
940 backref->dir, backref->index,
941 backref->name, backref->namelen, 0,
942 backref->ref_type, backref->errors);
946 if (src->found_dir_item)
947 dst->found_dir_item = 1;
948 if (src->found_file_extent)
949 dst->found_file_extent = 1;
950 if (src->found_csum_item)
951 dst->found_csum_item = 1;
952 if (src->some_csum_missing)
953 dst->some_csum_missing = 1;
954 if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
955 ret = copy_file_extent_holes(&dst->holes, &src->holes);
960 BUG_ON(src->found_link < dir_count);
961 dst->found_link += src->found_link - dir_count;
962 dst->found_size += src->found_size;
963 if (src->extent_start != (u64)-1) {
964 if (dst->extent_start == (u64)-1) {
965 dst->extent_start = src->extent_start;
966 dst->extent_end = src->extent_end;
968 if (dst->extent_end > src->extent_start)
969 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
970 else if (dst->extent_end < src->extent_start) {
971 ret = add_file_extent_hole(&dst->holes,
973 src->extent_start - dst->extent_end);
975 if (dst->extent_end < src->extent_end)
976 dst->extent_end = src->extent_end;
980 dst->errors |= src->errors;
981 if (src->found_inode_item) {
982 if (!dst->found_inode_item) {
983 dst->nlink = src->nlink;
984 dst->isize = src->isize;
985 dst->nbytes = src->nbytes;
986 dst->imode = src->imode;
987 dst->nodatasum = src->nodatasum;
988 dst->found_inode_item = 1;
990 dst->errors |= I_ERR_DUP_INODE_ITEM;
998 static int splice_shared_node(struct shared_node *src_node,
999 struct shared_node *dst_node)
1001 struct cache_extent *cache;
1002 struct ptr_node *node, *ins;
1003 struct cache_tree *src, *dst;
1004 struct inode_record *rec, *conflict;
1005 u64 current_ino = 0;
1009 if (--src_node->refs == 0)
1011 if (src_node->current)
1012 current_ino = src_node->current->ino;
1014 src = &src_node->root_cache;
1015 dst = &dst_node->root_cache;
1017 cache = search_cache_extent(src, 0);
1019 node = container_of(cache, struct ptr_node, cache);
1021 cache = next_cache_extent(cache);
1024 remove_cache_extent(src, &node->cache);
1027 ins = malloc(sizeof(*ins));
1028 ins->cache.start = node->cache.start;
1029 ins->cache.size = node->cache.size;
1033 ret = insert_cache_extent(dst, &ins->cache);
1034 if (ret == -EEXIST) {
1035 conflict = get_inode_rec(dst, rec->ino, 1);
1036 merge_inode_recs(rec, conflict, dst);
1038 conflict->checked = 1;
1039 if (dst_node->current == conflict)
1040 dst_node->current = NULL;
1042 maybe_free_inode_rec(dst, conflict);
1043 free_inode_rec(rec);
1050 if (src == &src_node->root_cache) {
1051 src = &src_node->inode_cache;
1052 dst = &dst_node->inode_cache;
1056 if (current_ino > 0 && (!dst_node->current ||
1057 current_ino > dst_node->current->ino)) {
1058 if (dst_node->current) {
1059 dst_node->current->checked = 1;
1060 maybe_free_inode_rec(dst, dst_node->current);
1062 dst_node->current = get_inode_rec(dst, current_ino, 1);
1067 static void free_inode_ptr(struct cache_extent *cache)
1069 struct ptr_node *node;
1070 struct inode_record *rec;
1072 node = container_of(cache, struct ptr_node, cache);
1074 free_inode_rec(rec);
1078 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1080 static struct shared_node *find_shared_node(struct cache_tree *shared,
1083 struct cache_extent *cache;
1084 struct shared_node *node;
1086 cache = lookup_cache_extent(shared, bytenr, 1);
1088 node = container_of(cache, struct shared_node, cache);
1094 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1097 struct shared_node *node;
1099 node = calloc(1, sizeof(*node));
1100 node->cache.start = bytenr;
1101 node->cache.size = 1;
1102 cache_tree_init(&node->root_cache);
1103 cache_tree_init(&node->inode_cache);
1106 ret = insert_cache_extent(shared, &node->cache);
1111 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1112 struct walk_control *wc, int level)
1114 struct shared_node *node;
1115 struct shared_node *dest;
1117 if (level == wc->active_node)
1120 BUG_ON(wc->active_node <= level);
1121 node = find_shared_node(&wc->shared, bytenr);
1123 add_shared_node(&wc->shared, bytenr, refs);
1124 node = find_shared_node(&wc->shared, bytenr);
1125 wc->nodes[level] = node;
1126 wc->active_node = level;
1130 if (wc->root_level == wc->active_node &&
1131 btrfs_root_refs(&root->root_item) == 0) {
1132 if (--node->refs == 0) {
1133 free_inode_recs_tree(&node->root_cache);
1134 free_inode_recs_tree(&node->inode_cache);
1135 remove_cache_extent(&wc->shared, &node->cache);
1141 dest = wc->nodes[wc->active_node];
1142 splice_shared_node(node, dest);
1143 if (node->refs == 0) {
1144 remove_cache_extent(&wc->shared, &node->cache);
1150 static int leave_shared_node(struct btrfs_root *root,
1151 struct walk_control *wc, int level)
1153 struct shared_node *node;
1154 struct shared_node *dest;
1157 if (level == wc->root_level)
1160 for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1164 BUG_ON(i >= BTRFS_MAX_LEVEL);
1166 node = wc->nodes[wc->active_node];
1167 wc->nodes[wc->active_node] = NULL;
1168 wc->active_node = i;
1170 dest = wc->nodes[wc->active_node];
1171 if (wc->active_node < wc->root_level ||
1172 btrfs_root_refs(&root->root_item) > 0) {
1173 BUG_ON(node->refs <= 1);
1174 splice_shared_node(node, dest);
1176 BUG_ON(node->refs < 2);
1185 * 1 - if the root with id child_root_id is a child of root parent_root_id
1186 * 0 - if the root child_root_id isn't a child of the root parent_root_id but
1187 * has other root(s) as parent(s)
1188 * 2 - if the root child_root_id doesn't have any parent roots
1190 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1193 struct btrfs_path path;
1194 struct btrfs_key key;
1195 struct extent_buffer *leaf;
1199 btrfs_init_path(&path);
1201 key.objectid = parent_root_id;
1202 key.type = BTRFS_ROOT_REF_KEY;
1203 key.offset = child_root_id;
1204 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1208 btrfs_release_path(&path);
1212 key.objectid = child_root_id;
1213 key.type = BTRFS_ROOT_BACKREF_KEY;
1215 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1221 leaf = path.nodes[0];
1222 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1223 ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1226 leaf = path.nodes[0];
1229 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1230 if (key.objectid != child_root_id ||
1231 key.type != BTRFS_ROOT_BACKREF_KEY)
1236 if (key.offset == parent_root_id) {
1237 btrfs_release_path(&path);
1244 btrfs_release_path(&path);
1247 return has_parent ? 0 : 2;
1250 static int process_dir_item(struct btrfs_root *root,
1251 struct extent_buffer *eb,
1252 int slot, struct btrfs_key *key,
1253 struct shared_node *active_node)
1263 struct btrfs_dir_item *di;
1264 struct inode_record *rec;
1265 struct cache_tree *root_cache;
1266 struct cache_tree *inode_cache;
1267 struct btrfs_key location;
1268 char namebuf[BTRFS_NAME_LEN];
1270 root_cache = &active_node->root_cache;
1271 inode_cache = &active_node->inode_cache;
1272 rec = active_node->current;
1273 rec->found_dir_item = 1;
1275 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1276 total = btrfs_item_size_nr(eb, slot);
1277 while (cur < total) {
1279 btrfs_dir_item_key_to_cpu(eb, di, &location);
1280 name_len = btrfs_dir_name_len(eb, di);
1281 data_len = btrfs_dir_data_len(eb, di);
1282 filetype = btrfs_dir_type(eb, di);
1284 rec->found_size += name_len;
1285 if (name_len <= BTRFS_NAME_LEN) {
1289 len = BTRFS_NAME_LEN;
1290 error = REF_ERR_NAME_TOO_LONG;
1292 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1294 if (location.type == BTRFS_INODE_ITEM_KEY) {
1295 add_inode_backref(inode_cache, location.objectid,
1296 key->objectid, key->offset, namebuf,
1297 len, filetype, key->type, error);
1298 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1299 add_inode_backref(root_cache, location.objectid,
1300 key->objectid, key->offset,
1301 namebuf, len, filetype,
1304 fprintf(stderr, "invalid location in dir item %u\n",
1306 add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1307 key->objectid, key->offset, namebuf,
1308 len, filetype, key->type, error);
1311 len = sizeof(*di) + name_len + data_len;
1312 di = (struct btrfs_dir_item *)((char *)di + len);
1315 if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1316 rec->errors |= I_ERR_DUP_DIR_INDEX;
1321 static int process_inode_ref(struct extent_buffer *eb,
1322 int slot, struct btrfs_key *key,
1323 struct shared_node *active_node)
1331 struct cache_tree *inode_cache;
1332 struct btrfs_inode_ref *ref;
1333 char namebuf[BTRFS_NAME_LEN];
1335 inode_cache = &active_node->inode_cache;
1337 ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1338 total = btrfs_item_size_nr(eb, slot);
1339 while (cur < total) {
1340 name_len = btrfs_inode_ref_name_len(eb, ref);
1341 index = btrfs_inode_ref_index(eb, ref);
1342 if (name_len <= BTRFS_NAME_LEN) {
1346 len = BTRFS_NAME_LEN;
1347 error = REF_ERR_NAME_TOO_LONG;
1349 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1350 add_inode_backref(inode_cache, key->objectid, key->offset,
1351 index, namebuf, len, 0, key->type, error);
1353 len = sizeof(*ref) + name_len;
1354 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1360 static int process_inode_extref(struct extent_buffer *eb,
1361 int slot, struct btrfs_key *key,
1362 struct shared_node *active_node)
1371 struct cache_tree *inode_cache;
1372 struct btrfs_inode_extref *extref;
1373 char namebuf[BTRFS_NAME_LEN];
1375 inode_cache = &active_node->inode_cache;
1377 extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1378 total = btrfs_item_size_nr(eb, slot);
1379 while (cur < total) {
1380 name_len = btrfs_inode_extref_name_len(eb, extref);
1381 index = btrfs_inode_extref_index(eb, extref);
1382 parent = btrfs_inode_extref_parent(eb, extref);
1383 if (name_len <= BTRFS_NAME_LEN) {
1387 len = BTRFS_NAME_LEN;
1388 error = REF_ERR_NAME_TOO_LONG;
1390 read_extent_buffer(eb, namebuf,
1391 (unsigned long)(extref + 1), len);
1392 add_inode_backref(inode_cache, key->objectid, parent,
1393 index, namebuf, len, 0, key->type, error);
1395 len = sizeof(*extref) + name_len;
1396 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1403 static int count_csum_range(struct btrfs_root *root, u64 start,
1404 u64 len, u64 *found)
1406 struct btrfs_key key;
1407 struct btrfs_path path;
1408 struct extent_buffer *leaf;
1413 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1415 btrfs_init_path(&path);
1417 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1419 key.type = BTRFS_EXTENT_CSUM_KEY;
1421 ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1425 if (ret > 0 && path.slots[0] > 0) {
1426 leaf = path.nodes[0];
1427 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1428 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1429 key.type == BTRFS_EXTENT_CSUM_KEY)
1434 leaf = path.nodes[0];
1435 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1436 ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1441 leaf = path.nodes[0];
1444 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1445 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1446 key.type != BTRFS_EXTENT_CSUM_KEY)
1449 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1450 if (key.offset >= start + len)
1453 if (key.offset > start)
1456 size = btrfs_item_size_nr(leaf, path.slots[0]);
1457 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1458 if (csum_end > start) {
1459 size = min(csum_end - start, len);
1468 btrfs_release_path(&path);
1474 static int process_file_extent(struct btrfs_root *root,
1475 struct extent_buffer *eb,
1476 int slot, struct btrfs_key *key,
1477 struct shared_node *active_node)
1479 struct inode_record *rec;
1480 struct btrfs_file_extent_item *fi;
1482 u64 disk_bytenr = 0;
1483 u64 extent_offset = 0;
1484 u64 mask = root->sectorsize - 1;
1488 rec = active_node->current;
1489 BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1490 rec->found_file_extent = 1;
1492 if (rec->extent_start == (u64)-1) {
1493 rec->extent_start = key->offset;
1494 rec->extent_end = key->offset;
1497 if (rec->extent_end > key->offset)
1498 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1499 else if (rec->extent_end < key->offset) {
1500 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1501 key->offset - rec->extent_end);
1506 fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1507 extent_type = btrfs_file_extent_type(eb, fi);
1509 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1510 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1512 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1513 rec->found_size += num_bytes;
1514 num_bytes = (num_bytes + mask) & ~mask;
1515 } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1516 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1517 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1518 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1519 extent_offset = btrfs_file_extent_offset(eb, fi);
1520 if (num_bytes == 0 || (num_bytes & mask))
1521 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1522 if (num_bytes + extent_offset >
1523 btrfs_file_extent_ram_bytes(eb, fi))
1524 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1525 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1526 (btrfs_file_extent_compression(eb, fi) ||
1527 btrfs_file_extent_encryption(eb, fi) ||
1528 btrfs_file_extent_other_encoding(eb, fi)))
1529 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1530 if (disk_bytenr > 0)
1531 rec->found_size += num_bytes;
1533 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1535 rec->extent_end = key->offset + num_bytes;
1538 * The data reloc tree will copy full extents into its inode and then
1539 * copy the corresponding csums. Because the extent it copied could be
1540 * a preallocated extent that hasn't been written to yet there may be no
1541 * csums to copy, ergo we won't have csums for our file extent. This is
1542 * ok so just don't bother checking csums if the inode belongs to the
1545 if (disk_bytenr > 0 &&
1546 btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1548 if (btrfs_file_extent_compression(eb, fi))
1549 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1551 disk_bytenr += extent_offset;
1553 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1556 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1558 rec->found_csum_item = 1;
1559 if (found < num_bytes)
1560 rec->some_csum_missing = 1;
1561 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1563 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1569 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1570 struct walk_control *wc)
1572 struct btrfs_key key;
1576 struct cache_tree *inode_cache;
1577 struct shared_node *active_node;
1579 if (wc->root_level == wc->active_node &&
1580 btrfs_root_refs(&root->root_item) == 0)
1583 active_node = wc->nodes[wc->active_node];
1584 inode_cache = &active_node->inode_cache;
1585 nritems = btrfs_header_nritems(eb);
1586 for (i = 0; i < nritems; i++) {
1587 btrfs_item_key_to_cpu(eb, &key, i);
1589 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1591 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1594 if (active_node->current == NULL ||
1595 active_node->current->ino < key.objectid) {
1596 if (active_node->current) {
1597 active_node->current->checked = 1;
1598 maybe_free_inode_rec(inode_cache,
1599 active_node->current);
1601 active_node->current = get_inode_rec(inode_cache,
1605 case BTRFS_DIR_ITEM_KEY:
1606 case BTRFS_DIR_INDEX_KEY:
1607 ret = process_dir_item(root, eb, i, &key, active_node);
1609 case BTRFS_INODE_REF_KEY:
1610 ret = process_inode_ref(eb, i, &key, active_node);
1612 case BTRFS_INODE_EXTREF_KEY:
1613 ret = process_inode_extref(eb, i, &key, active_node);
1615 case BTRFS_INODE_ITEM_KEY:
1616 ret = process_inode_item(eb, i, &key, active_node);
1618 case BTRFS_EXTENT_DATA_KEY:
1619 ret = process_file_extent(root, eb, i, &key,
1629 static void reada_walk_down(struct btrfs_root *root,
1630 struct extent_buffer *node, int slot)
1639 level = btrfs_header_level(node);
1643 nritems = btrfs_header_nritems(node);
1644 blocksize = btrfs_level_size(root, level - 1);
1645 for (i = slot; i < nritems; i++) {
1646 bytenr = btrfs_node_blockptr(node, i);
1647 ptr_gen = btrfs_node_ptr_generation(node, i);
1648 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1653 * Check the child node/leaf by the following condition:
1654 * 1. the first item key of the node/leaf should be the same with the one
1656 * 2. block in parent node should match the child node/leaf.
1657 * 3. generation of parent node and child's header should be consistent.
1659 * Or the child node/leaf pointed by the key in parent is not valid.
1661 * We hope to check leaf owner too, but since subvol may share leaves,
1662 * which makes leaf owner check not so strong, key check should be
1663 * sufficient enough for that case.
1665 static int check_child_node(struct btrfs_root *root,
1666 struct extent_buffer *parent, int slot,
1667 struct extent_buffer *child)
1669 struct btrfs_key parent_key;
1670 struct btrfs_key child_key;
1673 btrfs_node_key_to_cpu(parent, &parent_key, slot);
1674 if (btrfs_header_level(child) == 0)
1675 btrfs_item_key_to_cpu(child, &child_key, 0);
1677 btrfs_node_key_to_cpu(child, &child_key, 0);
1679 if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1682 "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1683 parent_key.objectid, parent_key.type, parent_key.offset,
1684 child_key.objectid, child_key.type, child_key.offset);
1686 if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1688 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1689 btrfs_node_blockptr(parent, slot),
1690 btrfs_header_bytenr(child));
1692 if (btrfs_node_ptr_generation(parent, slot) !=
1693 btrfs_header_generation(child)) {
1695 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1696 btrfs_header_generation(child),
1697 btrfs_node_ptr_generation(parent, slot));
1702 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1703 struct walk_control *wc, int *level)
1705 enum btrfs_tree_block_status status;
1708 struct extent_buffer *next;
1709 struct extent_buffer *cur;
1714 WARN_ON(*level < 0);
1715 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1716 ret = btrfs_lookup_extent_info(NULL, root,
1717 path->nodes[*level]->start,
1718 *level, 1, &refs, NULL);
1725 ret = enter_shared_node(root, path->nodes[*level]->start,
1733 while (*level >= 0) {
1734 WARN_ON(*level < 0);
1735 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1736 cur = path->nodes[*level];
1738 if (btrfs_header_level(cur) != *level)
1741 if (path->slots[*level] >= btrfs_header_nritems(cur))
1744 ret = process_one_leaf(root, cur, wc);
1749 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1750 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1751 blocksize = btrfs_level_size(root, *level - 1);
1752 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1758 ret = enter_shared_node(root, bytenr, refs,
1761 path->slots[*level]++;
1766 next = btrfs_find_tree_block(root, bytenr, blocksize);
1767 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1768 free_extent_buffer(next);
1769 reada_walk_down(root, cur, path->slots[*level]);
1770 next = read_tree_block(root, bytenr, blocksize,
1772 if (!extent_buffer_uptodate(next)) {
1773 struct btrfs_key node_key;
1775 btrfs_node_key_to_cpu(path->nodes[*level],
1777 path->slots[*level]);
1778 btrfs_add_corrupt_extent_record(root->fs_info,
1780 path->nodes[*level]->start,
1781 root->leafsize, *level);
1787 ret = check_child_node(root, cur, path->slots[*level], next);
1793 if (btrfs_is_leaf(next))
1794 status = btrfs_check_leaf(root, NULL, next);
1796 status = btrfs_check_node(root, NULL, next);
1797 if (status != BTRFS_TREE_BLOCK_CLEAN) {
1798 free_extent_buffer(next);
1803 *level = *level - 1;
1804 free_extent_buffer(path->nodes[*level]);
1805 path->nodes[*level] = next;
1806 path->slots[*level] = 0;
1809 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1813 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1814 struct walk_control *wc, int *level)
1817 struct extent_buffer *leaf;
1819 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1820 leaf = path->nodes[i];
1821 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1826 free_extent_buffer(path->nodes[*level]);
1827 path->nodes[*level] = NULL;
1828 BUG_ON(*level > wc->active_node);
1829 if (*level == wc->active_node)
1830 leave_shared_node(root, wc, *level);
1837 static int check_root_dir(struct inode_record *rec)
1839 struct inode_backref *backref;
1842 if (!rec->found_inode_item || rec->errors)
1844 if (rec->nlink != 1 || rec->found_link != 0)
1846 if (list_empty(&rec->backrefs))
1848 backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1849 if (!backref->found_inode_ref)
1851 if (backref->index != 0 || backref->namelen != 2 ||
1852 memcmp(backref->name, "..", 2))
1854 if (backref->found_dir_index || backref->found_dir_item)
1861 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1862 struct btrfs_root *root, struct btrfs_path *path,
1863 struct inode_record *rec)
1865 struct btrfs_inode_item *ei;
1866 struct btrfs_key key;
1869 key.objectid = rec->ino;
1870 key.type = BTRFS_INODE_ITEM_KEY;
1871 key.offset = (u64)-1;
1873 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1877 if (!path->slots[0]) {
1884 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1885 if (key.objectid != rec->ino) {
1890 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1891 struct btrfs_inode_item);
1892 btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1893 btrfs_mark_buffer_dirty(path->nodes[0]);
1894 rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1895 printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1896 root->root_key.objectid);
1898 btrfs_release_path(path);
1902 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1903 struct btrfs_root *root,
1904 struct btrfs_path *path,
1905 struct inode_record *rec)
1909 ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
1910 btrfs_release_path(path);
1912 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1916 static int add_missing_dir_index(struct btrfs_root *root,
1917 struct cache_tree *inode_cache,
1918 struct inode_record *rec,
1919 struct inode_backref *backref)
1921 struct btrfs_path *path;
1922 struct btrfs_trans_handle *trans;
1923 struct btrfs_dir_item *dir_item;
1924 struct extent_buffer *leaf;
1925 struct btrfs_key key;
1926 struct btrfs_disk_key disk_key;
1927 struct inode_record *dir_rec;
1928 unsigned long name_ptr;
1929 u32 data_size = sizeof(*dir_item) + backref->namelen;
1932 path = btrfs_alloc_path();
1936 trans = btrfs_start_transaction(root, 1);
1937 if (IS_ERR(trans)) {
1938 btrfs_free_path(path);
1939 return PTR_ERR(trans);
1942 fprintf(stderr, "repairing missing dir index item for inode %llu\n",
1943 (unsigned long long)rec->ino);
1944 key.objectid = backref->dir;
1945 key.type = BTRFS_DIR_INDEX_KEY;
1946 key.offset = backref->index;
1948 ret = btrfs_insert_empty_item(trans, root, path, &key, data_size);
1951 leaf = path->nodes[0];
1952 dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
1954 disk_key.objectid = cpu_to_le64(rec->ino);
1955 disk_key.type = BTRFS_INODE_ITEM_KEY;
1956 disk_key.offset = 0;
1958 btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
1959 btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
1960 btrfs_set_dir_data_len(leaf, dir_item, 0);
1961 btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
1962 name_ptr = (unsigned long)(dir_item + 1);
1963 write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
1964 btrfs_mark_buffer_dirty(leaf);
1965 btrfs_free_path(path);
1966 btrfs_commit_transaction(trans, root);
1968 backref->found_dir_index = 1;
1969 dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
1972 dir_rec->found_size += backref->namelen;
1973 if (dir_rec->found_size == dir_rec->isize &&
1974 (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
1975 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1976 if (dir_rec->found_size != dir_rec->isize)
1977 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
1982 static int delete_dir_index(struct btrfs_root *root,
1983 struct cache_tree *inode_cache,
1984 struct inode_record *rec,
1985 struct inode_backref *backref)
1987 struct btrfs_trans_handle *trans;
1988 struct btrfs_dir_item *di;
1989 struct btrfs_path *path;
1992 path = btrfs_alloc_path();
1996 trans = btrfs_start_transaction(root, 1);
1997 if (IS_ERR(trans)) {
1998 btrfs_free_path(path);
1999 return PTR_ERR(trans);
2003 fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2004 (unsigned long long)backref->dir,
2005 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2006 (unsigned long long)root->objectid);
2008 di = btrfs_lookup_dir_index(trans, root, path, backref->dir,
2009 backref->name, backref->namelen,
2010 backref->index, -1);
2013 btrfs_free_path(path);
2014 btrfs_commit_transaction(trans, root);
2021 ret = btrfs_del_item(trans, root, path);
2023 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2025 btrfs_free_path(path);
2026 btrfs_commit_transaction(trans, root);
2030 static int create_inode_item(struct btrfs_root *root,
2031 struct inode_record *rec,
2032 struct inode_backref *backref, int root_dir)
2034 struct btrfs_trans_handle *trans;
2035 struct btrfs_inode_item inode_item;
2036 time_t now = time(NULL);
2039 trans = btrfs_start_transaction(root, 1);
2040 if (IS_ERR(trans)) {
2041 ret = PTR_ERR(trans);
2045 fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2046 "be incomplete, please check permissions and content after "
2047 "the fsck completes.\n", (unsigned long long)root->objectid,
2048 (unsigned long long)rec->ino);
2050 memset(&inode_item, 0, sizeof(inode_item));
2051 btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2053 btrfs_set_stack_inode_nlink(&inode_item, 1);
2055 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2056 btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2057 if (rec->found_dir_item) {
2058 if (rec->found_file_extent)
2059 fprintf(stderr, "root %llu inode %llu has both a dir "
2060 "item and extents, unsure if it is a dir or a "
2061 "regular file so setting it as a directory\n",
2062 (unsigned long long)root->objectid,
2063 (unsigned long long)rec->ino);
2064 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2065 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2066 } else if (!rec->found_dir_item) {
2067 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2068 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2070 btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2071 btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2072 btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2073 btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2074 btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2075 btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2076 btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2077 btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2079 ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2081 btrfs_commit_transaction(trans, root);
2085 static int repair_inode_backrefs(struct btrfs_root *root,
2086 struct inode_record *rec,
2087 struct cache_tree *inode_cache,
2090 struct inode_backref *tmp, *backref;
2091 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2095 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2096 if (!delete && rec->ino == root_dirid) {
2097 if (!rec->found_inode_item) {
2098 ret = create_inode_item(root, rec, backref, 1);
2105 /* Index 0 for root dir's are special, don't mess with it */
2106 if (rec->ino == root_dirid && backref->index == 0)
2110 ((backref->found_dir_index && !backref->found_inode_ref) ||
2111 (backref->found_dir_index && backref->found_inode_ref &&
2112 (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2113 ret = delete_dir_index(root, inode_cache, rec, backref);
2117 list_del(&backref->list);
2121 if (!delete && !backref->found_dir_index &&
2122 backref->found_dir_item && backref->found_inode_ref) {
2123 ret = add_missing_dir_index(root, inode_cache, rec,
2128 if (backref->found_dir_item &&
2129 backref->found_dir_index &&
2130 backref->found_dir_index) {
2131 if (!backref->errors &&
2132 backref->found_inode_ref) {
2133 list_del(&backref->list);
2139 if (!delete && (!backref->found_dir_index &&
2140 !backref->found_dir_item &&
2141 backref->found_inode_ref)) {
2142 struct btrfs_trans_handle *trans;
2143 struct btrfs_key location;
2145 ret = check_dir_conflict(root, backref->name,
2151 * let nlink fixing routine to handle it,
2152 * which can do it better.
2157 location.objectid = rec->ino;
2158 location.type = BTRFS_INODE_ITEM_KEY;
2159 location.offset = 0;
2161 trans = btrfs_start_transaction(root, 1);
2162 if (IS_ERR(trans)) {
2163 ret = PTR_ERR(trans);
2166 fprintf(stderr, "adding missing dir index/item pair "
2168 (unsigned long long)rec->ino);
2169 ret = btrfs_insert_dir_item(trans, root, backref->name,
2171 backref->dir, &location,
2172 imode_to_type(rec->imode),
2175 btrfs_commit_transaction(trans, root);
2179 if (!delete && (backref->found_inode_ref &&
2180 backref->found_dir_index &&
2181 backref->found_dir_item &&
2182 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2183 !rec->found_inode_item)) {
2184 ret = create_inode_item(root, rec, backref, 0);
2191 return ret ? ret : repaired;
2195 * To determine the file type for nlink/inode_item repair
2197 * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2198 * Return -ENOENT if file type is not found.
2200 static int find_file_type(struct inode_record *rec, u8 *type)
2202 struct inode_backref *backref;
2204 /* For inode item recovered case */
2205 if (rec->found_inode_item) {
2206 *type = imode_to_type(rec->imode);
2210 list_for_each_entry(backref, &rec->backrefs, list) {
2211 if (backref->found_dir_index || backref->found_dir_item) {
2212 *type = backref->filetype;
2220 * To determine the file name for nlink repair
2222 * Return 0 if file name is found, set name and namelen.
2223 * Return -ENOENT if file name is not found.
2225 static int find_file_name(struct inode_record *rec,
2226 char *name, int *namelen)
2228 struct inode_backref *backref;
2230 list_for_each_entry(backref, &rec->backrefs, list) {
2231 if (backref->found_dir_index || backref->found_dir_item ||
2232 backref->found_inode_ref) {
2233 memcpy(name, backref->name, backref->namelen);
2234 *namelen = backref->namelen;
2241 /* Reset the nlink of the inode to the correct one */
2242 static int reset_nlink(struct btrfs_trans_handle *trans,
2243 struct btrfs_root *root,
2244 struct btrfs_path *path,
2245 struct inode_record *rec)
2247 struct inode_backref *backref;
2248 struct inode_backref *tmp;
2249 struct btrfs_key key;
2250 struct btrfs_inode_item *inode_item;
2253 /* We don't believe this either, reset it and iterate backref */
2254 rec->found_link = 0;
2256 /* Remove all backref including the valid ones */
2257 list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2258 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2259 backref->index, backref->name,
2260 backref->namelen, 0);
2264 /* remove invalid backref, so it won't be added back */
2265 if (!(backref->found_dir_index &&
2266 backref->found_dir_item &&
2267 backref->found_inode_ref)) {
2268 list_del(&backref->list);
2275 /* Set nlink to 0 */
2276 key.objectid = rec->ino;
2277 key.type = BTRFS_INODE_ITEM_KEY;
2279 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2286 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2287 struct btrfs_inode_item);
2288 btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2289 btrfs_mark_buffer_dirty(path->nodes[0]);
2290 btrfs_release_path(path);
2293 * Add back valid inode_ref/dir_item/dir_index,
2294 * add_link() will handle the nlink inc, so new nlink must be correct
2296 list_for_each_entry(backref, &rec->backrefs, list) {
2297 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2298 backref->name, backref->namelen,
2299 backref->ref_type, &backref->index, 1);
2304 btrfs_release_path(path);
2308 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2309 struct btrfs_root *root,
2310 struct btrfs_path *path,
2311 struct inode_record *rec)
2313 char *dir_name = "lost+found";
2314 char namebuf[BTRFS_NAME_LEN] = {0};
2319 int name_recovered = 0;
2320 int type_recovered = 0;
2324 * Get file name and type first before these invalid inode ref
2325 * are deleted by remove_all_invalid_backref()
2327 name_recovered = !find_file_name(rec, namebuf, &namelen);
2328 type_recovered = !find_file_type(rec, &type);
2330 if (!name_recovered) {
2331 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2332 rec->ino, rec->ino);
2333 namelen = count_digits(rec->ino);
2334 sprintf(namebuf, "%llu", rec->ino);
2337 if (!type_recovered) {
2338 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2340 type = BTRFS_FT_REG_FILE;
2344 ret = reset_nlink(trans, root, path, rec);
2347 "Failed to reset nlink for inode %llu: %s\n",
2348 rec->ino, strerror(-ret));
2352 if (rec->found_link == 0) {
2353 lost_found_ino = root->highest_inode;
2354 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2359 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2360 BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2363 fprintf(stderr, "Failed to create '%s' dir: %s",
2364 dir_name, strerror(-ret));
2367 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2368 namebuf, namelen, type, NULL, 1);
2370 * Add ".INO" suffix several times to handle case where
2371 * "FILENAME.INO" is already taken by another file.
2373 while (ret == -EEXIST) {
2375 * Conflicting file name, add ".INO" as suffix * +1 for '.'
2377 if (namelen + count_digits(rec->ino) + 1 >
2382 snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2384 namelen += count_digits(rec->ino) + 1;
2385 ret = btrfs_add_link(trans, root, rec->ino,
2386 lost_found_ino, namebuf,
2387 namelen, type, NULL, 1);
2391 "Failed to link the inode %llu to %s dir: %s",
2392 rec->ino, dir_name, strerror(-ret));
2396 * Just increase the found_link, don't actually add the
2397 * backref. This will make things easier and this inode
2398 * record will be freed after the repair is done.
2399 * So fsck will not report problem about this inode.
2402 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2403 namelen, namebuf, dir_name);
2405 printf("Fixed the nlink of inode %llu\n", rec->ino);
2408 * Clear the flag anyway, or we will loop forever for the same inode
2409 * as it will not be removed from the bad inode list and the dead loop
2412 rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2413 btrfs_release_path(path);
2418 * Check if there is any normal(reg or prealloc) file extent for given
2420 * This is used to determine the file type when neither its dir_index/item or
2421 * inode_item exists.
2423 * This will *NOT* report error, if any error happens, just consider it does
2424 * not have any normal file extent.
2426 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2428 struct btrfs_path *path;
2429 struct btrfs_key key;
2430 struct btrfs_key found_key;
2431 struct btrfs_file_extent_item *fi;
2435 path = btrfs_alloc_path();
2439 key.type = BTRFS_EXTENT_DATA_KEY;
2442 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2447 if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2448 ret = btrfs_next_leaf(root, path);
2455 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2457 if (found_key.objectid != ino ||
2458 found_key.type != BTRFS_EXTENT_DATA_KEY)
2460 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2461 struct btrfs_file_extent_item);
2462 type = btrfs_file_extent_type(path->nodes[0], fi);
2463 if (type != BTRFS_FILE_EXTENT_INLINE) {
2469 btrfs_free_path(path);
2473 static u32 btrfs_type_to_imode(u8 type)
2475 static u32 imode_by_btrfs_type[] = {
2476 [BTRFS_FT_REG_FILE] = S_IFREG,
2477 [BTRFS_FT_DIR] = S_IFDIR,
2478 [BTRFS_FT_CHRDEV] = S_IFCHR,
2479 [BTRFS_FT_BLKDEV] = S_IFBLK,
2480 [BTRFS_FT_FIFO] = S_IFIFO,
2481 [BTRFS_FT_SOCK] = S_IFSOCK,
2482 [BTRFS_FT_SYMLINK] = S_IFLNK,
2485 return imode_by_btrfs_type[(type)];
2488 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2489 struct btrfs_root *root,
2490 struct btrfs_path *path,
2491 struct inode_record *rec)
2495 int type_recovered = 0;
2498 printf("Trying to rebuild inode:%llu\n", rec->ino);
2500 type_recovered = !find_file_type(rec, &filetype);
2503 * Try to determine inode type if type not found.
2505 * For found regular file extent, it must be FILE.
2506 * For found dir_item/index, it must be DIR.
2508 * For undetermined one, use FILE as fallback.
2511 * 1. If found backref(inode_index/item is already handled) to it,
2513 * Need new inode-inode ref structure to allow search for that.
2515 if (!type_recovered) {
2516 if (rec->found_file_extent &&
2517 find_normal_file_extent(root, rec->ino)) {
2519 filetype = BTRFS_FT_REG_FILE;
2520 } else if (rec->found_dir_item) {
2522 filetype = BTRFS_FT_DIR;
2523 } else if (!list_empty(&rec->orphan_extents)) {
2525 filetype = BTRFS_FT_REG_FILE;
2527 printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2530 filetype = BTRFS_FT_REG_FILE;
2534 ret = btrfs_new_inode(trans, root, rec->ino,
2535 mode | btrfs_type_to_imode(filetype));
2540 * Here inode rebuild is done, we only rebuild the inode item,
2541 * don't repair the nlink(like move to lost+found).
2542 * That is the job of nlink repair.
2544 * We just fill the record and return
2546 rec->found_dir_item = 1;
2547 rec->imode = mode | btrfs_type_to_imode(filetype);
2549 rec->errors &= ~I_ERR_NO_INODE_ITEM;
2550 /* Ensure the inode_nlinks repair function will be called */
2551 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2556 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2557 struct btrfs_root *root,
2558 struct btrfs_path *path,
2559 struct inode_record *rec)
2561 struct orphan_data_extent *orphan;
2562 struct orphan_data_extent *tmp;
2565 list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2567 * Check for conflicting file extents
2569 * Here we don't know whether the extents is compressed or not,
2570 * so we can only assume it not compressed nor data offset,
2571 * and use its disk_len as extent length.
2573 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2574 orphan->offset, orphan->disk_len, 0);
2575 btrfs_release_path(path);
2580 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2581 orphan->disk_bytenr, orphan->disk_len);
2582 ret = btrfs_free_extent(trans,
2583 root->fs_info->extent_root,
2584 orphan->disk_bytenr, orphan->disk_len,
2585 0, root->objectid, orphan->objectid,
2590 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2591 orphan->offset, orphan->disk_bytenr,
2592 orphan->disk_len, orphan->disk_len);
2596 /* Update file size info */
2597 rec->found_size += orphan->disk_len;
2598 if (rec->found_size == rec->nbytes)
2599 rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2601 /* Update the file extent hole info too */
2602 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2606 if (RB_EMPTY_ROOT(&rec->holes))
2607 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2609 list_del(&orphan->list);
2612 rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2617 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2618 struct btrfs_root *root,
2619 struct btrfs_path *path,
2620 struct inode_record *rec)
2622 struct rb_node *node;
2623 struct file_extent_hole *hole;
2626 node = rb_first(&rec->holes);
2629 hole = rb_entry(node, struct file_extent_hole, node);
2630 ret = btrfs_punch_hole(trans, root, rec->ino,
2631 hole->start, hole->len);
2634 ret = del_file_extent_hole(&rec->holes, hole->start,
2638 if (RB_EMPTY_ROOT(&rec->holes))
2639 rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2640 node = rb_first(&rec->holes);
2642 printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2643 rec->ino, root->objectid);
2648 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2650 struct btrfs_trans_handle *trans;
2651 struct btrfs_path *path;
2654 if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2655 I_ERR_NO_ORPHAN_ITEM |
2656 I_ERR_LINK_COUNT_WRONG |
2657 I_ERR_NO_INODE_ITEM |
2658 I_ERR_FILE_EXTENT_ORPHAN |
2659 I_ERR_FILE_EXTENT_DISCOUNT)))
2662 path = btrfs_alloc_path();
2667 * For nlink repair, it may create a dir and add link, so
2668 * 2 for parent(256)'s dir_index and dir_item
2669 * 2 for lost+found dir's inode_item and inode_ref
2670 * 1 for the new inode_ref of the file
2671 * 2 for lost+found dir's dir_index and dir_item for the file
2673 trans = btrfs_start_transaction(root, 7);
2674 if (IS_ERR(trans)) {
2675 btrfs_free_path(path);
2676 return PTR_ERR(trans);
2679 if (rec->errors & I_ERR_NO_INODE_ITEM)
2680 ret = repair_inode_no_item(trans, root, path, rec);
2681 if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2682 ret = repair_inode_orphan_extent(trans, root, path, rec);
2683 if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2684 ret = repair_inode_discount_extent(trans, root, path, rec);
2685 if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2686 ret = repair_inode_isize(trans, root, path, rec);
2687 if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2688 ret = repair_inode_orphan_item(trans, root, path, rec);
2689 if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2690 ret = repair_inode_nlinks(trans, root, path, rec);
2691 btrfs_commit_transaction(trans, root);
2692 btrfs_free_path(path);
2696 static int check_inode_recs(struct btrfs_root *root,
2697 struct cache_tree *inode_cache)
2699 struct cache_extent *cache;
2700 struct ptr_node *node;
2701 struct inode_record *rec;
2702 struct inode_backref *backref;
2707 u64 root_dirid = btrfs_root_dirid(&root->root_item);
2709 if (btrfs_root_refs(&root->root_item) == 0) {
2710 if (!cache_tree_empty(inode_cache))
2711 fprintf(stderr, "warning line %d\n", __LINE__);
2716 * We need to record the highest inode number for later 'lost+found'
2718 * We must select a ino not used/refered by any existing inode, or
2719 * 'lost+found' ino may be a missing ino in a corrupted leaf,
2720 * this may cause 'lost+found' dir has wrong nlinks.
2722 cache = last_cache_extent(inode_cache);
2724 node = container_of(cache, struct ptr_node, cache);
2726 if (rec->ino > root->highest_inode)
2727 root->highest_inode = rec->ino;
2731 * We need to repair backrefs first because we could change some of the
2732 * errors in the inode recs.
2734 * We also need to go through and delete invalid backrefs first and then
2735 * add the correct ones second. We do this because we may get EEXIST
2736 * when adding back the correct index because we hadn't yet deleted the
2739 * For example, if we were missing a dir index then the directories
2740 * isize would be wrong, so if we fixed the isize to what we thought it
2741 * would be and then fixed the backref we'd still have a invalid fs, so
2742 * we need to add back the dir index and then check to see if the isize
2747 if (stage == 3 && !err)
2750 cache = search_cache_extent(inode_cache, 0);
2751 while (repair && cache) {
2752 node = container_of(cache, struct ptr_node, cache);
2754 cache = next_cache_extent(cache);
2756 /* Need to free everything up and rescan */
2758 remove_cache_extent(inode_cache, &node->cache);
2760 free_inode_rec(rec);
2764 if (list_empty(&rec->backrefs))
2767 ret = repair_inode_backrefs(root, rec, inode_cache,
2781 rec = get_inode_rec(inode_cache, root_dirid, 0);
2783 ret = check_root_dir(rec);
2785 fprintf(stderr, "root %llu root dir %llu error\n",
2786 (unsigned long long)root->root_key.objectid,
2787 (unsigned long long)root_dirid);
2788 print_inode_error(root, rec);
2793 struct btrfs_trans_handle *trans;
2795 trans = btrfs_start_transaction(root, 1);
2796 if (IS_ERR(trans)) {
2797 err = PTR_ERR(trans);
2802 "root %llu missing its root dir, recreating\n",
2803 (unsigned long long)root->objectid);
2805 ret = btrfs_make_root_dir(trans, root, root_dirid);
2808 btrfs_commit_transaction(trans, root);
2812 fprintf(stderr, "root %llu root dir %llu not found\n",
2813 (unsigned long long)root->root_key.objectid,
2814 (unsigned long long)root_dirid);
2818 cache = search_cache_extent(inode_cache, 0);
2821 node = container_of(cache, struct ptr_node, cache);
2823 remove_cache_extent(inode_cache, &node->cache);
2825 if (rec->ino == root_dirid ||
2826 rec->ino == BTRFS_ORPHAN_OBJECTID) {
2827 free_inode_rec(rec);
2831 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2832 ret = check_orphan_item(root, rec->ino);
2834 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2835 if (can_free_inode_rec(rec)) {
2836 free_inode_rec(rec);
2841 if (!rec->found_inode_item)
2842 rec->errors |= I_ERR_NO_INODE_ITEM;
2843 if (rec->found_link != rec->nlink)
2844 rec->errors |= I_ERR_LINK_COUNT_WRONG;
2846 ret = try_repair_inode(root, rec);
2847 if (ret == 0 && can_free_inode_rec(rec)) {
2848 free_inode_rec(rec);
2854 if (!(repair && ret == 0))
2856 print_inode_error(root, rec);
2857 list_for_each_entry(backref, &rec->backrefs, list) {
2858 if (!backref->found_dir_item)
2859 backref->errors |= REF_ERR_NO_DIR_ITEM;
2860 if (!backref->found_dir_index)
2861 backref->errors |= REF_ERR_NO_DIR_INDEX;
2862 if (!backref->found_inode_ref)
2863 backref->errors |= REF_ERR_NO_INODE_REF;
2864 fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2865 " namelen %u name %s filetype %d errors %x",
2866 (unsigned long long)backref->dir,
2867 (unsigned long long)backref->index,
2868 backref->namelen, backref->name,
2869 backref->filetype, backref->errors);
2870 print_ref_error(backref->errors);
2872 free_inode_rec(rec);
2874 return (error > 0) ? -1 : 0;
2877 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2880 struct cache_extent *cache;
2881 struct root_record *rec = NULL;
2884 cache = lookup_cache_extent(root_cache, objectid, 1);
2886 rec = container_of(cache, struct root_record, cache);
2888 rec = calloc(1, sizeof(*rec));
2889 rec->objectid = objectid;
2890 INIT_LIST_HEAD(&rec->backrefs);
2891 rec->cache.start = objectid;
2892 rec->cache.size = 1;
2894 ret = insert_cache_extent(root_cache, &rec->cache);
2900 static struct root_backref *get_root_backref(struct root_record *rec,
2901 u64 ref_root, u64 dir, u64 index,
2902 const char *name, int namelen)
2904 struct root_backref *backref;
2906 list_for_each_entry(backref, &rec->backrefs, list) {
2907 if (backref->ref_root != ref_root || backref->dir != dir ||
2908 backref->namelen != namelen)
2910 if (memcmp(name, backref->name, namelen))
2915 backref = malloc(sizeof(*backref) + namelen + 1);
2916 memset(backref, 0, sizeof(*backref));
2917 backref->ref_root = ref_root;
2919 backref->index = index;
2920 backref->namelen = namelen;
2921 memcpy(backref->name, name, namelen);
2922 backref->name[namelen] = '\0';
2923 list_add_tail(&backref->list, &rec->backrefs);
2927 static void free_root_record(struct cache_extent *cache)
2929 struct root_record *rec;
2930 struct root_backref *backref;
2932 rec = container_of(cache, struct root_record, cache);
2933 while (!list_empty(&rec->backrefs)) {
2934 backref = list_entry(rec->backrefs.next,
2935 struct root_backref, list);
2936 list_del(&backref->list);
2943 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2945 static int add_root_backref(struct cache_tree *root_cache,
2946 u64 root_id, u64 ref_root, u64 dir, u64 index,
2947 const char *name, int namelen,
2948 int item_type, int errors)
2950 struct root_record *rec;
2951 struct root_backref *backref;
2953 rec = get_root_rec(root_cache, root_id);
2954 backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2956 backref->errors |= errors;
2958 if (item_type != BTRFS_DIR_ITEM_KEY) {
2959 if (backref->found_dir_index || backref->found_back_ref ||
2960 backref->found_forward_ref) {
2961 if (backref->index != index)
2962 backref->errors |= REF_ERR_INDEX_UNMATCH;
2964 backref->index = index;
2968 if (item_type == BTRFS_DIR_ITEM_KEY) {
2969 if (backref->found_forward_ref)
2971 backref->found_dir_item = 1;
2972 } else if (item_type == BTRFS_DIR_INDEX_KEY) {
2973 backref->found_dir_index = 1;
2974 } else if (item_type == BTRFS_ROOT_REF_KEY) {
2975 if (backref->found_forward_ref)
2976 backref->errors |= REF_ERR_DUP_ROOT_REF;
2977 else if (backref->found_dir_item)
2979 backref->found_forward_ref = 1;
2980 } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
2981 if (backref->found_back_ref)
2982 backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
2983 backref->found_back_ref = 1;
2988 if (backref->found_forward_ref && backref->found_dir_item)
2989 backref->reachable = 1;
2993 static int merge_root_recs(struct btrfs_root *root,
2994 struct cache_tree *src_cache,
2995 struct cache_tree *dst_cache)
2997 struct cache_extent *cache;
2998 struct ptr_node *node;
2999 struct inode_record *rec;
3000 struct inode_backref *backref;
3003 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3004 free_inode_recs_tree(src_cache);
3009 cache = search_cache_extent(src_cache, 0);
3012 node = container_of(cache, struct ptr_node, cache);
3014 remove_cache_extent(src_cache, &node->cache);
3017 ret = is_child_root(root, root->objectid, rec->ino);
3023 list_for_each_entry(backref, &rec->backrefs, list) {
3024 BUG_ON(backref->found_inode_ref);
3025 if (backref->found_dir_item)
3026 add_root_backref(dst_cache, rec->ino,
3027 root->root_key.objectid, backref->dir,
3028 backref->index, backref->name,
3029 backref->namelen, BTRFS_DIR_ITEM_KEY,
3031 if (backref->found_dir_index)
3032 add_root_backref(dst_cache, rec->ino,
3033 root->root_key.objectid, backref->dir,
3034 backref->index, backref->name,
3035 backref->namelen, BTRFS_DIR_INDEX_KEY,
3039 free_inode_rec(rec);
3046 static int check_root_refs(struct btrfs_root *root,
3047 struct cache_tree *root_cache)
3049 struct root_record *rec;
3050 struct root_record *ref_root;
3051 struct root_backref *backref;
3052 struct cache_extent *cache;
3058 rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3061 /* fixme: this can not detect circular references */
3064 cache = search_cache_extent(root_cache, 0);
3068 rec = container_of(cache, struct root_record, cache);
3069 cache = next_cache_extent(cache);
3071 if (rec->found_ref == 0)
3074 list_for_each_entry(backref, &rec->backrefs, list) {
3075 if (!backref->reachable)
3078 ref_root = get_root_rec(root_cache,
3080 if (ref_root->found_ref > 0)
3083 backref->reachable = 0;
3085 if (rec->found_ref == 0)
3091 cache = search_cache_extent(root_cache, 0);
3095 rec = container_of(cache, struct root_record, cache);
3096 cache = next_cache_extent(cache);
3098 if (rec->found_ref == 0 &&
3099 rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3100 rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3101 ret = check_orphan_item(root->fs_info->tree_root,
3107 * If we don't have a root item then we likely just have
3108 * a dir item in a snapshot for this root but no actual
3109 * ref key or anything so it's meaningless.
3111 if (!rec->found_root_item)
3114 fprintf(stderr, "fs tree %llu not referenced\n",
3115 (unsigned long long)rec->objectid);
3119 if (rec->found_ref > 0 && !rec->found_root_item)
3121 list_for_each_entry(backref, &rec->backrefs, list) {
3122 if (!backref->found_dir_item)
3123 backref->errors |= REF_ERR_NO_DIR_ITEM;
3124 if (!backref->found_dir_index)
3125 backref->errors |= REF_ERR_NO_DIR_INDEX;
3126 if (!backref->found_back_ref)
3127 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3128 if (!backref->found_forward_ref)
3129 backref->errors |= REF_ERR_NO_ROOT_REF;
3130 if (backref->reachable && backref->errors)
3137 fprintf(stderr, "fs tree %llu refs %u %s\n",
3138 (unsigned long long)rec->objectid, rec->found_ref,
3139 rec->found_root_item ? "" : "not found");
3141 list_for_each_entry(backref, &rec->backrefs, list) {
3142 if (!backref->reachable)
3144 if (!backref->errors && rec->found_root_item)
3146 fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3147 " index %llu namelen %u name %s errors %x\n",
3148 (unsigned long long)backref->ref_root,
3149 (unsigned long long)backref->dir,
3150 (unsigned long long)backref->index,
3151 backref->namelen, backref->name,
3153 print_ref_error(backref->errors);
3156 return errors > 0 ? 1 : 0;
3159 static int process_root_ref(struct extent_buffer *eb, int slot,
3160 struct btrfs_key *key,
3161 struct cache_tree *root_cache)
3167 struct btrfs_root_ref *ref;
3168 char namebuf[BTRFS_NAME_LEN];
3171 ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3173 dirid = btrfs_root_ref_dirid(eb, ref);
3174 index = btrfs_root_ref_sequence(eb, ref);
3175 name_len = btrfs_root_ref_name_len(eb, ref);
3177 if (name_len <= BTRFS_NAME_LEN) {
3181 len = BTRFS_NAME_LEN;
3182 error = REF_ERR_NAME_TOO_LONG;
3184 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3186 if (key->type == BTRFS_ROOT_REF_KEY) {
3187 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3188 index, namebuf, len, key->type, error);
3190 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3191 index, namebuf, len, key->type, error);
3196 static void free_corrupt_block(struct cache_extent *cache)
3198 struct btrfs_corrupt_block *corrupt;
3200 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3204 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3207 * Repair the btree of the given root.
3209 * The fix is to remove the node key in corrupt_blocks cache_tree.
3210 * and rebalance the tree.
3211 * After the fix, the btree should be writeable.
3213 static int repair_btree(struct btrfs_root *root,
3214 struct cache_tree *corrupt_blocks)
3216 struct btrfs_trans_handle *trans;
3217 struct btrfs_path *path;
3218 struct btrfs_corrupt_block *corrupt;
3219 struct cache_extent *cache;
3220 struct btrfs_key key;
3225 if (cache_tree_empty(corrupt_blocks))
3228 path = btrfs_alloc_path();
3232 trans = btrfs_start_transaction(root, 1);
3233 if (IS_ERR(trans)) {
3234 ret = PTR_ERR(trans);
3235 fprintf(stderr, "Error starting transaction: %s\n",
3239 cache = first_cache_extent(corrupt_blocks);
3241 corrupt = container_of(cache, struct btrfs_corrupt_block,
3243 level = corrupt->level;
3244 path->lowest_level = level;
3245 key.objectid = corrupt->key.objectid;
3246 key.type = corrupt->key.type;
3247 key.offset = corrupt->key.offset;
3250 * Here we don't want to do any tree balance, since it may
3251 * cause a balance with corrupted brother leaf/node,
3252 * so ins_len set to 0 here.
3253 * Balance will be done after all corrupt node/leaf is deleted.
3255 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3258 offset = btrfs_node_blockptr(path->nodes[level],
3259 path->slots[level]);
3261 /* Remove the ptr */
3262 ret = btrfs_del_ptr(trans, root, path, level,
3263 path->slots[level]);
3267 * Remove the corresponding extent
3268 * return value is not concerned.
3270 btrfs_release_path(path);
3271 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3272 0, root->root_key.objectid,
3274 cache = next_cache_extent(cache);
3277 /* Balance the btree using btrfs_search_slot() */
3278 cache = first_cache_extent(corrupt_blocks);
3280 corrupt = container_of(cache, struct btrfs_corrupt_block,
3282 memcpy(&key, &corrupt->key, sizeof(key));
3283 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3286 /* return will always >0 since it won't find the item */
3288 btrfs_release_path(path);
3289 cache = next_cache_extent(cache);
3292 btrfs_commit_transaction(trans, root);
3294 btrfs_free_path(path);
3298 static int check_fs_root(struct btrfs_root *root,
3299 struct cache_tree *root_cache,
3300 struct walk_control *wc)
3306 struct btrfs_path path;
3307 struct shared_node root_node;
3308 struct root_record *rec;
3309 struct btrfs_root_item *root_item = &root->root_item;
3310 struct cache_tree corrupt_blocks;
3311 struct orphan_data_extent *orphan;
3312 struct orphan_data_extent *tmp;
3313 enum btrfs_tree_block_status status;
3316 * Reuse the corrupt_block cache tree to record corrupted tree block
3318 * Unlike the usage in extent tree check, here we do it in a per
3319 * fs/subvol tree base.
3321 cache_tree_init(&corrupt_blocks);
3322 root->fs_info->corrupt_blocks = &corrupt_blocks;
3324 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3325 rec = get_root_rec(root_cache, root->root_key.objectid);
3326 if (btrfs_root_refs(root_item) > 0)
3327 rec->found_root_item = 1;
3330 btrfs_init_path(&path);
3331 memset(&root_node, 0, sizeof(root_node));
3332 cache_tree_init(&root_node.root_cache);
3333 cache_tree_init(&root_node.inode_cache);
3335 /* Move the orphan extent record to corresponding inode_record */
3336 list_for_each_entry_safe(orphan, tmp,
3337 &root->orphan_data_extents, list) {
3338 struct inode_record *inode;
3340 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3342 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3343 list_move(&orphan->list, &inode->orphan_extents);
3346 level = btrfs_header_level(root->node);
3347 memset(wc->nodes, 0, sizeof(wc->nodes));
3348 wc->nodes[level] = &root_node;
3349 wc->active_node = level;
3350 wc->root_level = level;
3352 /* We may not have checked the root block, lets do that now */
3353 if (btrfs_is_leaf(root->node))
3354 status = btrfs_check_leaf(root, NULL, root->node);
3356 status = btrfs_check_node(root, NULL, root->node);
3357 if (status != BTRFS_TREE_BLOCK_CLEAN)
3360 if (btrfs_root_refs(root_item) > 0 ||
3361 btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3362 path.nodes[level] = root->node;
3363 extent_buffer_get(root->node);
3364 path.slots[level] = 0;
3366 struct btrfs_key key;
3367 struct btrfs_disk_key found_key;
3369 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3370 level = root_item->drop_level;
3371 path.lowest_level = level;
3372 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3375 btrfs_node_key(path.nodes[level], &found_key,
3377 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3378 sizeof(found_key)));
3382 wret = walk_down_tree(root, &path, wc, &level);
3388 wret = walk_up_tree(root, &path, wc, &level);
3395 btrfs_release_path(&path);
3397 if (!cache_tree_empty(&corrupt_blocks)) {
3398 struct cache_extent *cache;
3399 struct btrfs_corrupt_block *corrupt;
3401 printf("The following tree block(s) is corrupted in tree %llu:\n",
3402 root->root_key.objectid);
3403 cache = first_cache_extent(&corrupt_blocks);
3405 corrupt = container_of(cache,
3406 struct btrfs_corrupt_block,
3408 printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3409 cache->start, corrupt->level,
3410 corrupt->key.objectid, corrupt->key.type,
3411 corrupt->key.offset);
3412 cache = next_cache_extent(cache);
3415 printf("Try to repair the btree for root %llu\n",
3416 root->root_key.objectid);
3417 ret = repair_btree(root, &corrupt_blocks);
3419 fprintf(stderr, "Failed to repair btree: %s\n",
3422 printf("Btree for root %llu is fixed\n",
3423 root->root_key.objectid);
3427 err = merge_root_recs(root, &root_node.root_cache, root_cache);
3431 if (root_node.current) {
3432 root_node.current->checked = 1;
3433 maybe_free_inode_rec(&root_node.inode_cache,
3437 err = check_inode_recs(root, &root_node.inode_cache);
3441 free_corrupt_blocks_tree(&corrupt_blocks);
3442 root->fs_info->corrupt_blocks = NULL;
3443 free_orphan_data_extents(&root->orphan_data_extents);
3447 static int fs_root_objectid(u64 objectid)
3449 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3450 objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3452 return is_fstree(objectid);
3455 static int check_fs_roots(struct btrfs_root *root,
3456 struct cache_tree *root_cache)
3458 struct btrfs_path path;
3459 struct btrfs_key key;
3460 struct walk_control wc;
3461 struct extent_buffer *leaf, *tree_node;
3462 struct btrfs_root *tmp_root;
3463 struct btrfs_root *tree_root = root->fs_info->tree_root;
3468 * Just in case we made any changes to the extent tree that weren't
3469 * reflected into the free space cache yet.
3472 reset_cached_block_groups(root->fs_info);
3473 memset(&wc, 0, sizeof(wc));
3474 cache_tree_init(&wc.shared);
3475 btrfs_init_path(&path);
3480 key.type = BTRFS_ROOT_ITEM_KEY;
3481 ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3486 tree_node = tree_root->node;
3488 if (tree_node != tree_root->node) {
3489 free_root_recs_tree(root_cache);
3490 btrfs_release_path(&path);
3493 leaf = path.nodes[0];
3494 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3495 ret = btrfs_next_leaf(tree_root, &path);
3501 leaf = path.nodes[0];
3503 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3504 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3505 fs_root_objectid(key.objectid)) {
3506 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3507 tmp_root = btrfs_read_fs_root_no_cache(
3508 root->fs_info, &key);
3510 key.offset = (u64)-1;
3511 tmp_root = btrfs_read_fs_root(
3512 root->fs_info, &key);
3514 if (IS_ERR(tmp_root)) {
3518 ret = check_fs_root(tmp_root, root_cache, &wc);
3519 if (ret == -EAGAIN) {
3520 free_root_recs_tree(root_cache);
3521 btrfs_release_path(&path);
3526 if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3527 btrfs_free_fs_root(tmp_root);
3528 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3529 key.type == BTRFS_ROOT_BACKREF_KEY) {
3530 process_root_ref(leaf, path.slots[0], &key,
3537 btrfs_release_path(&path);
3539 free_extent_cache_tree(&wc.shared);
3540 if (!cache_tree_empty(&wc.shared))
3541 fprintf(stderr, "warning line %d\n", __LINE__);
3546 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3548 struct list_head *cur = rec->backrefs.next;
3549 struct extent_backref *back;
3550 struct tree_backref *tback;
3551 struct data_backref *dback;
3555 while(cur != &rec->backrefs) {
3556 back = list_entry(cur, struct extent_backref, list);
3558 if (!back->found_extent_tree) {
3562 if (back->is_data) {
3563 dback = (struct data_backref *)back;
3564 fprintf(stderr, "Backref %llu %s %llu"
3565 " owner %llu offset %llu num_refs %lu"
3566 " not found in extent tree\n",
3567 (unsigned long long)rec->start,
3568 back->full_backref ?
3570 back->full_backref ?
3571 (unsigned long long)dback->parent:
3572 (unsigned long long)dback->root,
3573 (unsigned long long)dback->owner,
3574 (unsigned long long)dback->offset,
3575 (unsigned long)dback->num_refs);
3577 tback = (struct tree_backref *)back;
3578 fprintf(stderr, "Backref %llu parent %llu"
3579 " root %llu not found in extent tree\n",
3580 (unsigned long long)rec->start,
3581 (unsigned long long)tback->parent,
3582 (unsigned long long)tback->root);
3585 if (!back->is_data && !back->found_ref) {
3589 tback = (struct tree_backref *)back;
3590 fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3591 (unsigned long long)rec->start,
3592 back->full_backref ? "parent" : "root",
3593 back->full_backref ?
3594 (unsigned long long)tback->parent :
3595 (unsigned long long)tback->root, back);
3597 if (back->is_data) {
3598 dback = (struct data_backref *)back;
3599 if (dback->found_ref != dback->num_refs) {
3603 fprintf(stderr, "Incorrect local backref count"
3604 " on %llu %s %llu owner %llu"
3605 " offset %llu found %u wanted %u back %p\n",
3606 (unsigned long long)rec->start,
3607 back->full_backref ?
3609 back->full_backref ?
3610 (unsigned long long)dback->parent:
3611 (unsigned long long)dback->root,
3612 (unsigned long long)dback->owner,
3613 (unsigned long long)dback->offset,
3614 dback->found_ref, dback->num_refs, back);
3616 if (dback->disk_bytenr != rec->start) {
3620 fprintf(stderr, "Backref disk bytenr does not"
3621 " match extent record, bytenr=%llu, "
3622 "ref bytenr=%llu\n",
3623 (unsigned long long)rec->start,
3624 (unsigned long long)dback->disk_bytenr);
3627 if (dback->bytes != rec->nr) {
3631 fprintf(stderr, "Backref bytes do not match "
3632 "extent backref, bytenr=%llu, ref "
3633 "bytes=%llu, backref bytes=%llu\n",
3634 (unsigned long long)rec->start,
3635 (unsigned long long)rec->nr,
3636 (unsigned long long)dback->bytes);
3639 if (!back->is_data) {
3642 dback = (struct data_backref *)back;
3643 found += dback->found_ref;
3646 if (found != rec->refs) {
3650 fprintf(stderr, "Incorrect global backref count "
3651 "on %llu found %llu wanted %llu\n",
3652 (unsigned long long)rec->start,
3653 (unsigned long long)found,
3654 (unsigned long long)rec->refs);
3660 static int free_all_extent_backrefs(struct extent_record *rec)
3662 struct extent_backref *back;
3663 struct list_head *cur;
3664 while (!list_empty(&rec->backrefs)) {
3665 cur = rec->backrefs.next;
3666 back = list_entry(cur, struct extent_backref, list);
3673 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3674 struct cache_tree *extent_cache)
3676 struct cache_extent *cache;
3677 struct extent_record *rec;
3680 cache = first_cache_extent(extent_cache);
3683 rec = container_of(cache, struct extent_record, cache);
3684 remove_cache_extent(extent_cache, cache);
3685 free_all_extent_backrefs(rec);
3690 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3691 struct extent_record *rec)
3693 if (rec->content_checked && rec->owner_ref_checked &&
3694 rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3695 rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3696 !rec->bad_full_backref) {
3697 remove_cache_extent(extent_cache, &rec->cache);
3698 free_all_extent_backrefs(rec);
3699 list_del_init(&rec->list);
3705 static int check_owner_ref(struct btrfs_root *root,
3706 struct extent_record *rec,
3707 struct extent_buffer *buf)
3709 struct extent_backref *node;
3710 struct tree_backref *back;
3711 struct btrfs_root *ref_root;
3712 struct btrfs_key key;
3713 struct btrfs_path path;
3714 struct extent_buffer *parent;
3719 list_for_each_entry(node, &rec->backrefs, list) {
3722 if (!node->found_ref)
3724 if (node->full_backref)
3726 back = (struct tree_backref *)node;
3727 if (btrfs_header_owner(buf) == back->root)
3730 BUG_ON(rec->is_root);
3732 /* try to find the block by search corresponding fs tree */
3733 key.objectid = btrfs_header_owner(buf);
3734 key.type = BTRFS_ROOT_ITEM_KEY;
3735 key.offset = (u64)-1;
3737 ref_root = btrfs_read_fs_root(root->fs_info, &key);
3738 if (IS_ERR(ref_root))
3741 level = btrfs_header_level(buf);
3743 btrfs_item_key_to_cpu(buf, &key, 0);
3745 btrfs_node_key_to_cpu(buf, &key, 0);
3747 btrfs_init_path(&path);
3748 path.lowest_level = level + 1;
3749 ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3753 parent = path.nodes[level + 1];
3754 if (parent && buf->start == btrfs_node_blockptr(parent,
3755 path.slots[level + 1]))
3758 btrfs_release_path(&path);
3759 return found ? 0 : 1;
3762 static int is_extent_tree_record(struct extent_record *rec)
3764 struct list_head *cur = rec->backrefs.next;
3765 struct extent_backref *node;
3766 struct tree_backref *back;
3769 while(cur != &rec->backrefs) {
3770 node = list_entry(cur, struct extent_backref, list);
3774 back = (struct tree_backref *)node;
3775 if (node->full_backref)
3777 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3784 static int record_bad_block_io(struct btrfs_fs_info *info,
3785 struct cache_tree *extent_cache,
3788 struct extent_record *rec;
3789 struct cache_extent *cache;
3790 struct btrfs_key key;
3792 cache = lookup_cache_extent(extent_cache, start, len);
3796 rec = container_of(cache, struct extent_record, cache);
3797 if (!is_extent_tree_record(rec))
3800 btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3801 return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3804 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3805 struct extent_buffer *buf, int slot)
3807 if (btrfs_header_level(buf)) {
3808 struct btrfs_key_ptr ptr1, ptr2;
3810 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3811 sizeof(struct btrfs_key_ptr));
3812 read_extent_buffer(buf, &ptr2,
3813 btrfs_node_key_ptr_offset(slot + 1),
3814 sizeof(struct btrfs_key_ptr));
3815 write_extent_buffer(buf, &ptr1,
3816 btrfs_node_key_ptr_offset(slot + 1),
3817 sizeof(struct btrfs_key_ptr));
3818 write_extent_buffer(buf, &ptr2,
3819 btrfs_node_key_ptr_offset(slot),
3820 sizeof(struct btrfs_key_ptr));
3822 struct btrfs_disk_key key;
3823 btrfs_node_key(buf, &key, 0);
3824 btrfs_fixup_low_keys(root, path, &key,
3825 btrfs_header_level(buf) + 1);
3828 struct btrfs_item *item1, *item2;
3829 struct btrfs_key k1, k2;
3830 char *item1_data, *item2_data;
3831 u32 item1_offset, item2_offset, item1_size, item2_size;
3833 item1 = btrfs_item_nr(slot);
3834 item2 = btrfs_item_nr(slot + 1);
3835 btrfs_item_key_to_cpu(buf, &k1, slot);
3836 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3837 item1_offset = btrfs_item_offset(buf, item1);
3838 item2_offset = btrfs_item_offset(buf, item2);
3839 item1_size = btrfs_item_size(buf, item1);
3840 item2_size = btrfs_item_size(buf, item2);
3842 item1_data = malloc(item1_size);
3845 item2_data = malloc(item2_size);
3851 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3852 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3854 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3855 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3859 btrfs_set_item_offset(buf, item1, item2_offset);
3860 btrfs_set_item_offset(buf, item2, item1_offset);
3861 btrfs_set_item_size(buf, item1, item2_size);
3862 btrfs_set_item_size(buf, item2, item1_size);
3864 path->slots[0] = slot;
3865 btrfs_set_item_key_unsafe(root, path, &k2);
3866 path->slots[0] = slot + 1;
3867 btrfs_set_item_key_unsafe(root, path, &k1);
3872 static int fix_key_order(struct btrfs_trans_handle *trans,
3873 struct btrfs_root *root,
3874 struct btrfs_path *path)
3876 struct extent_buffer *buf;
3877 struct btrfs_key k1, k2;
3879 int level = path->lowest_level;
3882 buf = path->nodes[level];
3883 for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3885 btrfs_node_key_to_cpu(buf, &k1, i);
3886 btrfs_node_key_to_cpu(buf, &k2, i + 1);
3888 btrfs_item_key_to_cpu(buf, &k1, i);
3889 btrfs_item_key_to_cpu(buf, &k2, i + 1);
3891 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3893 ret = swap_values(root, path, buf, i);
3896 btrfs_mark_buffer_dirty(buf);
3902 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3903 struct btrfs_root *root,
3904 struct btrfs_path *path,
3905 struct extent_buffer *buf, int slot)
3907 struct btrfs_key key;
3908 int nritems = btrfs_header_nritems(buf);
3910 btrfs_item_key_to_cpu(buf, &key, slot);
3912 /* These are all the keys we can deal with missing. */
3913 if (key.type != BTRFS_DIR_INDEX_KEY &&
3914 key.type != BTRFS_EXTENT_ITEM_KEY &&
3915 key.type != BTRFS_METADATA_ITEM_KEY &&
3916 key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3917 key.type != BTRFS_EXTENT_DATA_REF_KEY)
3920 printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3921 (unsigned long long)key.objectid, key.type,
3922 (unsigned long long)key.offset, slot, buf->start);
3923 memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3924 btrfs_item_nr_offset(slot + 1),
3925 sizeof(struct btrfs_item) *
3926 (nritems - slot - 1));
3927 btrfs_set_header_nritems(buf, nritems - 1);
3929 struct btrfs_disk_key disk_key;
3931 btrfs_item_key(buf, &disk_key, 0);
3932 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3934 btrfs_mark_buffer_dirty(buf);
3938 static int fix_item_offset(struct btrfs_trans_handle *trans,
3939 struct btrfs_root *root,
3940 struct btrfs_path *path)
3942 struct extent_buffer *buf;
3946 /* We should only get this for leaves */
3947 BUG_ON(path->lowest_level);
3948 buf = path->nodes[0];
3950 for (i = 0; i < btrfs_header_nritems(buf); i++) {
3951 unsigned int shift = 0, offset;
3953 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3954 BTRFS_LEAF_DATA_SIZE(root)) {
3955 if (btrfs_item_end_nr(buf, i) >
3956 BTRFS_LEAF_DATA_SIZE(root)) {
3957 ret = delete_bogus_item(trans, root, path,
3961 fprintf(stderr, "item is off the end of the "
3962 "leaf, can't fix\n");
3966 shift = BTRFS_LEAF_DATA_SIZE(root) -
3967 btrfs_item_end_nr(buf, i);
3968 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
3969 btrfs_item_offset_nr(buf, i - 1)) {
3970 if (btrfs_item_end_nr(buf, i) >
3971 btrfs_item_offset_nr(buf, i - 1)) {
3972 ret = delete_bogus_item(trans, root, path,
3976 fprintf(stderr, "items overlap, can't fix\n");
3980 shift = btrfs_item_offset_nr(buf, i - 1) -
3981 btrfs_item_end_nr(buf, i);
3986 printf("Shifting item nr %d by %u bytes in block %llu\n",
3987 i, shift, (unsigned long long)buf->start);
3988 offset = btrfs_item_offset_nr(buf, i);
3989 memmove_extent_buffer(buf,
3990 btrfs_leaf_data(buf) + offset + shift,
3991 btrfs_leaf_data(buf) + offset,
3992 btrfs_item_size_nr(buf, i));
3993 btrfs_set_item_offset(buf, btrfs_item_nr(i),
3995 btrfs_mark_buffer_dirty(buf);
3999 * We may have moved things, in which case we want to exit so we don't
4000 * write those changes out. Once we have proper abort functionality in
4001 * progs this can be changed to something nicer.
4008 * Attempt to fix basic block failures. If we can't fix it for whatever reason
4009 * then just return -EIO.
4011 static int try_to_fix_bad_block(struct btrfs_root *root,
4012 struct extent_buffer *buf,
4013 enum btrfs_tree_block_status status)
4015 struct btrfs_trans_handle *trans;
4016 struct ulist *roots;
4017 struct ulist_node *node;
4018 struct btrfs_root *search_root;
4019 struct btrfs_path *path;
4020 struct ulist_iterator iter;
4021 struct btrfs_key root_key, key;
4024 if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4025 status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4028 path = btrfs_alloc_path();
4032 ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start,
4035 btrfs_free_path(path);
4039 ULIST_ITER_INIT(&iter);
4040 while ((node = ulist_next(roots, &iter))) {
4041 root_key.objectid = node->val;
4042 root_key.type = BTRFS_ROOT_ITEM_KEY;
4043 root_key.offset = (u64)-1;
4045 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4052 trans = btrfs_start_transaction(search_root, 0);
4053 if (IS_ERR(trans)) {
4054 ret = PTR_ERR(trans);
4058 path->lowest_level = btrfs_header_level(buf);
4059 path->skip_check_block = 1;
4060 if (path->lowest_level)
4061 btrfs_node_key_to_cpu(buf, &key, 0);
4063 btrfs_item_key_to_cpu(buf, &key, 0);
4064 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
4067 btrfs_commit_transaction(trans, search_root);
4070 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4071 ret = fix_key_order(trans, search_root, path);
4072 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4073 ret = fix_item_offset(trans, search_root, path);
4075 btrfs_commit_transaction(trans, search_root);
4078 btrfs_release_path(path);
4079 btrfs_commit_transaction(trans, search_root);
4082 btrfs_free_path(path);
4086 static int check_block(struct btrfs_root *root,
4087 struct cache_tree *extent_cache,
4088 struct extent_buffer *buf, u64 flags)
4090 struct extent_record *rec;
4091 struct cache_extent *cache;
4092 struct btrfs_key key;
4093 enum btrfs_tree_block_status status;
4097 cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4100 rec = container_of(cache, struct extent_record, cache);
4101 rec->generation = btrfs_header_generation(buf);
4103 level = btrfs_header_level(buf);
4104 if (btrfs_header_nritems(buf) > 0) {
4107 btrfs_item_key_to_cpu(buf, &key, 0);
4109 btrfs_node_key_to_cpu(buf, &key, 0);
4111 rec->info_objectid = key.objectid;
4113 rec->info_level = level;
4115 if (btrfs_is_leaf(buf))
4116 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4118 status = btrfs_check_node(root, &rec->parent_key, buf);
4120 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4122 status = try_to_fix_bad_block(root, buf, status);
4123 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4125 fprintf(stderr, "bad block %llu\n",
4126 (unsigned long long)buf->start);
4129 * Signal to callers we need to start the scan over
4130 * again since we'll have cow'ed blocks.
4135 rec->content_checked = 1;
4136 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4137 rec->owner_ref_checked = 1;
4139 ret = check_owner_ref(root, rec, buf);
4141 rec->owner_ref_checked = 1;
4145 maybe_free_extent_rec(extent_cache, rec);
4149 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4150 u64 parent, u64 root)
4152 struct list_head *cur = rec->backrefs.next;
4153 struct extent_backref *node;
4154 struct tree_backref *back;
4156 while(cur != &rec->backrefs) {
4157 node = list_entry(cur, struct extent_backref, list);
4161 back = (struct tree_backref *)node;
4163 if (!node->full_backref)
4165 if (parent == back->parent)
4168 if (node->full_backref)
4170 if (back->root == root)
4177 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4178 u64 parent, u64 root)
4180 struct tree_backref *ref = malloc(sizeof(*ref));
4181 memset(&ref->node, 0, sizeof(ref->node));
4183 ref->parent = parent;
4184 ref->node.full_backref = 1;
4187 ref->node.full_backref = 0;
4189 list_add_tail(&ref->node.list, &rec->backrefs);
4194 static struct data_backref *find_data_backref(struct extent_record *rec,
4195 u64 parent, u64 root,
4196 u64 owner, u64 offset,
4198 u64 disk_bytenr, u64 bytes)
4200 struct list_head *cur = rec->backrefs.next;
4201 struct extent_backref *node;
4202 struct data_backref *back;
4204 while(cur != &rec->backrefs) {
4205 node = list_entry(cur, struct extent_backref, list);
4209 back = (struct data_backref *)node;
4211 if (!node->full_backref)
4213 if (parent == back->parent)
4216 if (node->full_backref)
4218 if (back->root == root && back->owner == owner &&
4219 back->offset == offset) {
4220 if (found_ref && node->found_ref &&
4221 (back->bytes != bytes ||
4222 back->disk_bytenr != disk_bytenr))
4231 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4232 u64 parent, u64 root,
4233 u64 owner, u64 offset,
4236 struct data_backref *ref = malloc(sizeof(*ref));
4237 memset(&ref->node, 0, sizeof(ref->node));
4238 ref->node.is_data = 1;
4241 ref->parent = parent;
4244 ref->node.full_backref = 1;
4248 ref->offset = offset;
4249 ref->node.full_backref = 0;
4251 ref->bytes = max_size;
4254 list_add_tail(&ref->node.list, &rec->backrefs);
4255 if (max_size > rec->max_size)
4256 rec->max_size = max_size;
4260 static int add_extent_rec(struct cache_tree *extent_cache,
4261 struct btrfs_key *parent_key, u64 parent_gen,
4262 u64 start, u64 nr, u64 extent_item_refs,
4263 int is_root, int inc_ref, int set_checked,
4264 int metadata, int extent_rec, u64 max_size)
4266 struct extent_record *rec;
4267 struct cache_extent *cache;
4271 cache = lookup_cache_extent(extent_cache, start, nr);
4273 rec = container_of(cache, struct extent_record, cache);
4277 rec->nr = max(nr, max_size);
4280 * We need to make sure to reset nr to whatever the extent
4281 * record says was the real size, this way we can compare it to
4285 if (start != rec->start || rec->found_rec) {
4286 struct extent_record *tmp;
4289 if (list_empty(&rec->list))
4290 list_add_tail(&rec->list,
4291 &duplicate_extents);
4294 * We have to do this song and dance in case we
4295 * find an extent record that falls inside of
4296 * our current extent record but does not have
4297 * the same objectid.
4299 tmp = malloc(sizeof(*tmp));
4303 tmp->max_size = max_size;
4306 tmp->metadata = metadata;
4307 tmp->extent_item_refs = extent_item_refs;
4308 INIT_LIST_HEAD(&tmp->list);
4309 list_add_tail(&tmp->list, &rec->dups);
4310 rec->num_duplicates++;
4317 if (extent_item_refs && !dup) {
4318 if (rec->extent_item_refs) {
4319 fprintf(stderr, "block %llu rec "
4320 "extent_item_refs %llu, passed %llu\n",
4321 (unsigned long long)start,
4322 (unsigned long long)
4323 rec->extent_item_refs,
4324 (unsigned long long)extent_item_refs);
4326 rec->extent_item_refs = extent_item_refs;
4331 rec->content_checked = 1;
4332 rec->owner_ref_checked = 1;
4336 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4338 rec->parent_generation = parent_gen;
4340 if (rec->max_size < max_size)
4341 rec->max_size = max_size;
4343 maybe_free_extent_rec(extent_cache, rec);
4346 rec = malloc(sizeof(*rec));
4348 rec->max_size = max_size;
4349 rec->nr = max(nr, max_size);
4350 rec->found_rec = !!extent_rec;
4351 rec->content_checked = 0;
4352 rec->owner_ref_checked = 0;
4353 rec->num_duplicates = 0;
4354 rec->metadata = metadata;
4355 rec->flag_block_full_backref = -1;
4356 rec->bad_full_backref = 0;
4357 INIT_LIST_HEAD(&rec->backrefs);
4358 INIT_LIST_HEAD(&rec->dups);
4359 INIT_LIST_HEAD(&rec->list);
4371 if (extent_item_refs)
4372 rec->extent_item_refs = extent_item_refs;
4374 rec->extent_item_refs = 0;
4377 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
4379 memset(&rec->parent_key, 0, sizeof(*parent_key));
4382 rec->parent_generation = parent_gen;
4384 rec->parent_generation = 0;
4386 rec->cache.start = start;
4387 rec->cache.size = nr;
4388 ret = insert_cache_extent(extent_cache, &rec->cache);
4392 rec->content_checked = 1;
4393 rec->owner_ref_checked = 1;
4398 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4399 u64 parent, u64 root, int found_ref)
4401 struct extent_record *rec;
4402 struct tree_backref *back;
4403 struct cache_extent *cache;
4405 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4407 add_extent_rec(extent_cache, NULL, 0, bytenr,
4408 1, 0, 0, 0, 0, 1, 0, 0);
4409 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4414 rec = container_of(cache, struct extent_record, cache);
4415 if (rec->start != bytenr) {
4419 back = find_tree_backref(rec, parent, root);
4421 back = alloc_tree_backref(rec, parent, root);
4424 if (back->node.found_ref) {
4425 fprintf(stderr, "Extent back ref already exists "
4426 "for %llu parent %llu root %llu \n",
4427 (unsigned long long)bytenr,
4428 (unsigned long long)parent,
4429 (unsigned long long)root);
4431 back->node.found_ref = 1;
4433 if (back->node.found_extent_tree) {
4434 fprintf(stderr, "Extent back ref already exists "
4435 "for %llu parent %llu root %llu \n",
4436 (unsigned long long)bytenr,
4437 (unsigned long long)parent,
4438 (unsigned long long)root);
4440 back->node.found_extent_tree = 1;
4442 maybe_free_extent_rec(extent_cache, rec);
4446 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4447 u64 parent, u64 root, u64 owner, u64 offset,
4448 u32 num_refs, int found_ref, u64 max_size)
4450 struct extent_record *rec;
4451 struct data_backref *back;
4452 struct cache_extent *cache;
4454 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4456 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4458 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4463 rec = container_of(cache, struct extent_record, cache);
4464 if (rec->max_size < max_size)
4465 rec->max_size = max_size;
4468 * If found_ref is set then max_size is the real size and must match the
4469 * existing refs. So if we have already found a ref then we need to
4470 * make sure that this ref matches the existing one, otherwise we need
4471 * to add a new backref so we can notice that the backrefs don't match
4472 * and we need to figure out who is telling the truth. This is to
4473 * account for that awful fsync bug I introduced where we'd end up with
4474 * a btrfs_file_extent_item that would have its length include multiple
4475 * prealloc extents or point inside of a prealloc extent.
4477 back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4480 back = alloc_data_backref(rec, parent, root, owner, offset,
4484 BUG_ON(num_refs != 1);
4485 if (back->node.found_ref)
4486 BUG_ON(back->bytes != max_size);
4487 back->node.found_ref = 1;
4488 back->found_ref += 1;
4489 back->bytes = max_size;
4490 back->disk_bytenr = bytenr;
4492 rec->content_checked = 1;
4493 rec->owner_ref_checked = 1;
4495 if (back->node.found_extent_tree) {
4496 fprintf(stderr, "Extent back ref already exists "
4497 "for %llu parent %llu root %llu "
4498 "owner %llu offset %llu num_refs %lu\n",
4499 (unsigned long long)bytenr,
4500 (unsigned long long)parent,
4501 (unsigned long long)root,
4502 (unsigned long long)owner,
4503 (unsigned long long)offset,
4504 (unsigned long)num_refs);
4506 back->num_refs = num_refs;
4507 back->node.found_extent_tree = 1;
4509 maybe_free_extent_rec(extent_cache, rec);
4513 static int add_pending(struct cache_tree *pending,
4514 struct cache_tree *seen, u64 bytenr, u32 size)
4517 ret = add_cache_extent(seen, bytenr, size);
4520 add_cache_extent(pending, bytenr, size);
4524 static int pick_next_pending(struct cache_tree *pending,
4525 struct cache_tree *reada,
4526 struct cache_tree *nodes,
4527 u64 last, struct block_info *bits, int bits_nr,
4530 unsigned long node_start = last;
4531 struct cache_extent *cache;
4534 cache = search_cache_extent(reada, 0);
4536 bits[0].start = cache->start;
4537 bits[0].size = cache->size;
4542 if (node_start > 32768)
4543 node_start -= 32768;
4545 cache = search_cache_extent(nodes, node_start);
4547 cache = search_cache_extent(nodes, 0);
4550 cache = search_cache_extent(pending, 0);
4555 bits[ret].start = cache->start;
4556 bits[ret].size = cache->size;
4557 cache = next_cache_extent(cache);
4559 } while (cache && ret < bits_nr);
4565 bits[ret].start = cache->start;
4566 bits[ret].size = cache->size;
4567 cache = next_cache_extent(cache);
4569 } while (cache && ret < bits_nr);
4571 if (bits_nr - ret > 8) {
4572 u64 lookup = bits[0].start + bits[0].size;
4573 struct cache_extent *next;
4574 next = search_cache_extent(pending, lookup);
4576 if (next->start - lookup > 32768)
4578 bits[ret].start = next->start;
4579 bits[ret].size = next->size;
4580 lookup = next->start + next->size;
4584 next = next_cache_extent(next);
4592 static void free_chunk_record(struct cache_extent *cache)
4594 struct chunk_record *rec;
4596 rec = container_of(cache, struct chunk_record, cache);
4597 list_del_init(&rec->list);
4598 list_del_init(&rec->dextents);
4602 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4604 cache_tree_free_extents(chunk_cache, free_chunk_record);
4607 static void free_device_record(struct rb_node *node)
4609 struct device_record *rec;
4611 rec = container_of(node, struct device_record, node);
4615 FREE_RB_BASED_TREE(device_cache, free_device_record);
4617 int insert_block_group_record(struct block_group_tree *tree,
4618 struct block_group_record *bg_rec)
4622 ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4626 list_add_tail(&bg_rec->list, &tree->block_groups);
4630 static void free_block_group_record(struct cache_extent *cache)
4632 struct block_group_record *rec;
4634 rec = container_of(cache, struct block_group_record, cache);
4635 list_del_init(&rec->list);
4639 void free_block_group_tree(struct block_group_tree *tree)
4641 cache_tree_free_extents(&tree->tree, free_block_group_record);
4644 int insert_device_extent_record(struct device_extent_tree *tree,
4645 struct device_extent_record *de_rec)
4650 * Device extent is a bit different from the other extents, because
4651 * the extents which belong to the different devices may have the
4652 * same start and size, so we need use the special extent cache
4653 * search/insert functions.
4655 ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4659 list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4660 list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4664 static void free_device_extent_record(struct cache_extent *cache)
4666 struct device_extent_record *rec;
4668 rec = container_of(cache, struct device_extent_record, cache);
4669 if (!list_empty(&rec->chunk_list))
4670 list_del_init(&rec->chunk_list);
4671 if (!list_empty(&rec->device_list))
4672 list_del_init(&rec->device_list);
4676 void free_device_extent_tree(struct device_extent_tree *tree)
4678 cache_tree_free_extents(&tree->tree, free_device_extent_record);
4681 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4682 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4683 struct extent_buffer *leaf, int slot)
4685 struct btrfs_extent_ref_v0 *ref0;
4686 struct btrfs_key key;
4688 btrfs_item_key_to_cpu(leaf, &key, slot);
4689 ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4690 if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4691 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4693 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4694 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4700 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4701 struct btrfs_key *key,
4704 struct btrfs_chunk *ptr;
4705 struct chunk_record *rec;
4708 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4709 num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4711 rec = malloc(btrfs_chunk_record_size(num_stripes));
4713 fprintf(stderr, "memory allocation failed\n");
4717 memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4719 INIT_LIST_HEAD(&rec->list);
4720 INIT_LIST_HEAD(&rec->dextents);
4723 rec->cache.start = key->offset;
4724 rec->cache.size = btrfs_chunk_length(leaf, ptr);
4726 rec->generation = btrfs_header_generation(leaf);
4728 rec->objectid = key->objectid;
4729 rec->type = key->type;
4730 rec->offset = key->offset;
4732 rec->length = rec->cache.size;
4733 rec->owner = btrfs_chunk_owner(leaf, ptr);
4734 rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4735 rec->type_flags = btrfs_chunk_type(leaf, ptr);
4736 rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4737 rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4738 rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4739 rec->num_stripes = num_stripes;
4740 rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4742 for (i = 0; i < rec->num_stripes; ++i) {
4743 rec->stripes[i].devid =
4744 btrfs_stripe_devid_nr(leaf, ptr, i);
4745 rec->stripes[i].offset =
4746 btrfs_stripe_offset_nr(leaf, ptr, i);
4747 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4748 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4755 static int process_chunk_item(struct cache_tree *chunk_cache,
4756 struct btrfs_key *key, struct extent_buffer *eb,
4759 struct chunk_record *rec;
4762 rec = btrfs_new_chunk_record(eb, key, slot);
4763 ret = insert_cache_extent(chunk_cache, &rec->cache);
4765 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4766 rec->offset, rec->length);
4773 static int process_device_item(struct rb_root *dev_cache,
4774 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4776 struct btrfs_dev_item *ptr;
4777 struct device_record *rec;
4780 ptr = btrfs_item_ptr(eb,
4781 slot, struct btrfs_dev_item);
4783 rec = malloc(sizeof(*rec));
4785 fprintf(stderr, "memory allocation failed\n");
4789 rec->devid = key->offset;
4790 rec->generation = btrfs_header_generation(eb);
4792 rec->objectid = key->objectid;
4793 rec->type = key->type;
4794 rec->offset = key->offset;
4796 rec->devid = btrfs_device_id(eb, ptr);
4797 rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4798 rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4800 ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4802 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4809 struct block_group_record *
4810 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4813 struct btrfs_block_group_item *ptr;
4814 struct block_group_record *rec;
4816 rec = malloc(sizeof(*rec));
4818 fprintf(stderr, "memory allocation failed\n");
4821 memset(rec, 0, sizeof(*rec));
4823 rec->cache.start = key->objectid;
4824 rec->cache.size = key->offset;
4826 rec->generation = btrfs_header_generation(leaf);
4828 rec->objectid = key->objectid;
4829 rec->type = key->type;
4830 rec->offset = key->offset;
4832 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4833 rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4835 INIT_LIST_HEAD(&rec->list);
4840 static int process_block_group_item(struct block_group_tree *block_group_cache,
4841 struct btrfs_key *key,
4842 struct extent_buffer *eb, int slot)
4844 struct block_group_record *rec;
4847 rec = btrfs_new_block_group_record(eb, key, slot);
4848 ret = insert_block_group_record(block_group_cache, rec);
4850 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4851 rec->objectid, rec->offset);
4858 struct device_extent_record *
4859 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4860 struct btrfs_key *key, int slot)
4862 struct device_extent_record *rec;
4863 struct btrfs_dev_extent *ptr;
4865 rec = malloc(sizeof(*rec));
4867 fprintf(stderr, "memory allocation failed\n");
4870 memset(rec, 0, sizeof(*rec));
4872 rec->cache.objectid = key->objectid;
4873 rec->cache.start = key->offset;
4875 rec->generation = btrfs_header_generation(leaf);
4877 rec->objectid = key->objectid;
4878 rec->type = key->type;
4879 rec->offset = key->offset;
4881 ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4882 rec->chunk_objecteid =
4883 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4885 btrfs_dev_extent_chunk_offset(leaf, ptr);
4886 rec->length = btrfs_dev_extent_length(leaf, ptr);
4887 rec->cache.size = rec->length;
4889 INIT_LIST_HEAD(&rec->chunk_list);
4890 INIT_LIST_HEAD(&rec->device_list);
4896 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4897 struct btrfs_key *key, struct extent_buffer *eb,
4900 struct device_extent_record *rec;
4903 rec = btrfs_new_device_extent_record(eb, key, slot);
4904 ret = insert_device_extent_record(dev_extent_cache, rec);
4907 "Device extent[%llu, %llu, %llu] existed.\n",
4908 rec->objectid, rec->offset, rec->length);
4915 static int process_extent_item(struct btrfs_root *root,
4916 struct cache_tree *extent_cache,
4917 struct extent_buffer *eb, int slot)
4919 struct btrfs_extent_item *ei;
4920 struct btrfs_extent_inline_ref *iref;
4921 struct btrfs_extent_data_ref *dref;
4922 struct btrfs_shared_data_ref *sref;
4923 struct btrfs_key key;
4927 u32 item_size = btrfs_item_size_nr(eb, slot);
4933 btrfs_item_key_to_cpu(eb, &key, slot);
4935 if (key.type == BTRFS_METADATA_ITEM_KEY) {
4937 num_bytes = root->leafsize;
4939 num_bytes = key.offset;
4942 if (item_size < sizeof(*ei)) {
4943 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4944 struct btrfs_extent_item_v0 *ei0;
4945 BUG_ON(item_size != sizeof(*ei0));
4946 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4947 refs = btrfs_extent_refs_v0(eb, ei0);
4951 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4952 num_bytes, refs, 0, 0, 0, metadata, 1,
4956 ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4957 refs = btrfs_extent_refs(eb, ei);
4959 add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
4960 refs, 0, 0, 0, metadata, 1, num_bytes);
4962 ptr = (unsigned long)(ei + 1);
4963 if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
4964 key.type == BTRFS_EXTENT_ITEM_KEY)
4965 ptr += sizeof(struct btrfs_tree_block_info);
4967 end = (unsigned long)ei + item_size;
4969 iref = (struct btrfs_extent_inline_ref *)ptr;
4970 type = btrfs_extent_inline_ref_type(eb, iref);
4971 offset = btrfs_extent_inline_ref_offset(eb, iref);
4973 case BTRFS_TREE_BLOCK_REF_KEY:
4974 add_tree_backref(extent_cache, key.objectid,
4977 case BTRFS_SHARED_BLOCK_REF_KEY:
4978 add_tree_backref(extent_cache, key.objectid,
4981 case BTRFS_EXTENT_DATA_REF_KEY:
4982 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
4983 add_data_backref(extent_cache, key.objectid, 0,
4984 btrfs_extent_data_ref_root(eb, dref),
4985 btrfs_extent_data_ref_objectid(eb,
4987 btrfs_extent_data_ref_offset(eb, dref),
4988 btrfs_extent_data_ref_count(eb, dref),
4991 case BTRFS_SHARED_DATA_REF_KEY:
4992 sref = (struct btrfs_shared_data_ref *)(iref + 1);
4993 add_data_backref(extent_cache, key.objectid, offset,
4995 btrfs_shared_data_ref_count(eb, sref),
4999 fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
5000 key.objectid, key.type, num_bytes);
5003 ptr += btrfs_extent_inline_ref_size(type);
5010 static int check_cache_range(struct btrfs_root *root,
5011 struct btrfs_block_group_cache *cache,
5012 u64 offset, u64 bytes)
5014 struct btrfs_free_space *entry;
5020 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5021 bytenr = btrfs_sb_offset(i);
5022 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5023 cache->key.objectid, bytenr, 0,
5024 &logical, &nr, &stripe_len);
5029 if (logical[nr] + stripe_len <= offset)
5031 if (offset + bytes <= logical[nr])
5033 if (logical[nr] == offset) {
5034 if (stripe_len >= bytes) {
5038 bytes -= stripe_len;
5039 offset += stripe_len;
5040 } else if (logical[nr] < offset) {
5041 if (logical[nr] + stripe_len >=
5046 bytes = (offset + bytes) -
5047 (logical[nr] + stripe_len);
5048 offset = logical[nr] + stripe_len;
5051 * Could be tricky, the super may land in the
5052 * middle of the area we're checking. First
5053 * check the easiest case, it's at the end.
5055 if (logical[nr] + stripe_len >=
5057 bytes = logical[nr] - offset;
5061 /* Check the left side */
5062 ret = check_cache_range(root, cache,
5064 logical[nr] - offset);
5070 /* Now we continue with the right side */
5071 bytes = (offset + bytes) -
5072 (logical[nr] + stripe_len);
5073 offset = logical[nr] + stripe_len;
5080 entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5082 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5083 offset, offset+bytes);
5087 if (entry->offset != offset) {
5088 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5093 if (entry->bytes != bytes) {
5094 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5095 bytes, entry->bytes, offset);
5099 unlink_free_space(cache->free_space_ctl, entry);
5104 static int verify_space_cache(struct btrfs_root *root,
5105 struct btrfs_block_group_cache *cache)
5107 struct btrfs_path *path;
5108 struct extent_buffer *leaf;
5109 struct btrfs_key key;
5113 path = btrfs_alloc_path();
5117 root = root->fs_info->extent_root;
5119 last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5121 key.objectid = last;
5123 key.type = BTRFS_EXTENT_ITEM_KEY;
5125 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5130 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5131 ret = btrfs_next_leaf(root, path);
5139 leaf = path->nodes[0];
5140 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5141 if (key.objectid >= cache->key.offset + cache->key.objectid)
5143 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5144 key.type != BTRFS_METADATA_ITEM_KEY) {
5149 if (last == key.objectid) {
5150 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5151 last = key.objectid + key.offset;
5153 last = key.objectid + root->leafsize;
5158 ret = check_cache_range(root, cache, last,
5159 key.objectid - last);
5162 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5163 last = key.objectid + key.offset;
5165 last = key.objectid + root->leafsize;
5169 if (last < cache->key.objectid + cache->key.offset)
5170 ret = check_cache_range(root, cache, last,
5171 cache->key.objectid +
5172 cache->key.offset - last);
5175 btrfs_free_path(path);
5178 !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5179 fprintf(stderr, "There are still entries left in the space "
5187 static int check_space_cache(struct btrfs_root *root)
5189 struct btrfs_block_group_cache *cache;
5190 u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5194 if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5195 btrfs_super_generation(root->fs_info->super_copy) !=
5196 btrfs_super_cache_generation(root->fs_info->super_copy)) {
5197 printf("cache and super generation don't match, space cache "
5198 "will be invalidated\n");
5203 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5207 start = cache->key.objectid + cache->key.offset;
5208 if (!cache->free_space_ctl) {
5209 if (btrfs_init_free_space_ctl(cache,
5210 root->sectorsize)) {
5215 btrfs_remove_free_space_cache(cache);
5218 ret = load_free_space_cache(root->fs_info, cache);
5222 ret = verify_space_cache(root, cache);
5224 fprintf(stderr, "cache appears valid but isnt %Lu\n",
5225 cache->key.objectid);
5230 return error ? -EINVAL : 0;
5233 static int read_extent_data(struct btrfs_root *root, char *data,
5234 u64 logical, u64 *len, int mirror)
5237 struct btrfs_multi_bio *multi = NULL;
5238 struct btrfs_fs_info *info = root->fs_info;
5239 struct btrfs_device *device;
5243 ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
5244 &multi, mirror, NULL);
5246 fprintf(stderr, "Couldn't map the block %llu\n",
5250 device = multi->stripes[0].dev;
5252 if (device->fd == 0)
5257 ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
5267 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5268 u64 num_bytes, unsigned long leaf_offset,
5269 struct extent_buffer *eb) {
5272 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5274 unsigned long csum_offset;
5278 u64 data_checked = 0;
5284 if (num_bytes % root->sectorsize)
5287 data = malloc(num_bytes);
5291 while (offset < num_bytes) {
5294 read_len = num_bytes - offset;
5295 /* read as much space once a time */
5296 ret = read_extent_data(root, data + offset,
5297 bytenr + offset, &read_len, mirror);
5301 /* verify every 4k data's checksum */
5302 while (data_checked < read_len) {
5304 tmp = offset + data_checked;
5306 csum = btrfs_csum_data(NULL, (char *)data + tmp,
5307 csum, root->sectorsize);
5308 btrfs_csum_final(csum, (char *)&csum);
5310 csum_offset = leaf_offset +
5311 tmp / root->sectorsize * csum_size;
5312 read_extent_buffer(eb, (char *)&csum_expected,
5313 csum_offset, csum_size);
5314 /* try another mirror */
5315 if (csum != csum_expected) {
5316 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5317 mirror, bytenr + tmp,
5318 csum, csum_expected);
5319 num_copies = btrfs_num_copies(
5320 &root->fs_info->mapping_tree,
5322 if (mirror < num_copies - 1) {
5327 data_checked += root->sectorsize;
5336 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5339 struct btrfs_path *path;
5340 struct extent_buffer *leaf;
5341 struct btrfs_key key;
5344 path = btrfs_alloc_path();
5346 fprintf(stderr, "Error allocing path\n");
5350 key.objectid = bytenr;
5351 key.type = BTRFS_EXTENT_ITEM_KEY;
5352 key.offset = (u64)-1;
5355 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
5358 fprintf(stderr, "Error looking up extent record %d\n", ret);
5359 btrfs_free_path(path);
5362 if (path->slots[0] > 0) {
5365 ret = btrfs_prev_leaf(root, path);
5368 } else if (ret > 0) {
5375 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5378 * Block group items come before extent items if they have the same
5379 * bytenr, so walk back one more just in case. Dear future traveler,
5380 * first congrats on mastering time travel. Now if it's not too much
5381 * trouble could you go back to 2006 and tell Chris to make the
5382 * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5383 * EXTENT_ITEM_KEY please?
5385 while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5386 if (path->slots[0] > 0) {
5389 ret = btrfs_prev_leaf(root, path);
5392 } else if (ret > 0) {
5397 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5401 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5402 ret = btrfs_next_leaf(root, path);
5404 fprintf(stderr, "Error going to next leaf "
5406 btrfs_free_path(path);
5412 leaf = path->nodes[0];
5413 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5414 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5418 if (key.objectid + key.offset < bytenr) {
5422 if (key.objectid > bytenr + num_bytes)
5425 if (key.objectid == bytenr) {
5426 if (key.offset >= num_bytes) {
5430 num_bytes -= key.offset;
5431 bytenr += key.offset;
5432 } else if (key.objectid < bytenr) {
5433 if (key.objectid + key.offset >= bytenr + num_bytes) {
5437 num_bytes = (bytenr + num_bytes) -
5438 (key.objectid + key.offset);
5439 bytenr = key.objectid + key.offset;
5441 if (key.objectid + key.offset < bytenr + num_bytes) {
5442 u64 new_start = key.objectid + key.offset;
5443 u64 new_bytes = bytenr + num_bytes - new_start;
5446 * Weird case, the extent is in the middle of
5447 * our range, we'll have to search one side
5448 * and then the other. Not sure if this happens
5449 * in real life, but no harm in coding it up
5450 * anyway just in case.
5452 btrfs_release_path(path);
5453 ret = check_extent_exists(root, new_start,
5456 fprintf(stderr, "Right section didn't "
5460 num_bytes = key.objectid - bytenr;
5463 num_bytes = key.objectid - bytenr;
5470 if (num_bytes && !ret) {
5471 fprintf(stderr, "There are no extents for csum range "
5472 "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5476 btrfs_free_path(path);
5480 static int check_csums(struct btrfs_root *root)
5482 struct btrfs_path *path;
5483 struct extent_buffer *leaf;
5484 struct btrfs_key key;
5485 u64 offset = 0, num_bytes = 0;
5486 u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5490 unsigned long leaf_offset;
5492 root = root->fs_info->csum_root;
5493 if (!extent_buffer_uptodate(root->node)) {
5494 fprintf(stderr, "No valid csum tree found\n");
5498 key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5499 key.type = BTRFS_EXTENT_CSUM_KEY;
5502 path = btrfs_alloc_path();
5506 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5508 fprintf(stderr, "Error searching csum tree %d\n", ret);
5509 btrfs_free_path(path);
5513 if (ret > 0 && path->slots[0])
5518 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5519 ret = btrfs_next_leaf(root, path);
5521 fprintf(stderr, "Error going to next leaf "
5528 leaf = path->nodes[0];
5530 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5531 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5536 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5537 csum_size) * root->sectorsize;
5538 if (!check_data_csum)
5539 goto skip_csum_check;
5540 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5541 ret = check_extent_csums(root, key.offset, data_len,
5547 offset = key.offset;
5548 } else if (key.offset != offset + num_bytes) {
5549 ret = check_extent_exists(root, offset, num_bytes);
5551 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5552 "there is no extent record\n",
5553 offset, offset+num_bytes);
5556 offset = key.offset;
5559 num_bytes += data_len;
5563 btrfs_free_path(path);
5567 static int is_dropped_key(struct btrfs_key *key,
5568 struct btrfs_key *drop_key) {
5569 if (key->objectid < drop_key->objectid)
5571 else if (key->objectid == drop_key->objectid) {
5572 if (key->type < drop_key->type)
5574 else if (key->type == drop_key->type) {
5575 if (key->offset < drop_key->offset)
5583 * Here are the rules for FULL_BACKREF.
5585 * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
5586 * 2) If btrfs_header_owner(buf) no longer points to buf then we have
5588 * 3) We cow'ed the block walking down a reloc tree. This is impossible to tell
5589 * if it happened after the relocation occurred since we'll have dropped the
5590 * reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
5591 * have no real way to know for sure.
5593 * We process the blocks one root at a time, and we start from the lowest root
5594 * objectid and go to the highest. So we can just lookup the owner backref for
5595 * the record and if we don't find it then we know it doesn't exist and we have
5598 * FIXME: if we ever start reclaiming root objectid's then we need to fix this
5599 * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
5600 * be set or not and then we can check later once we've gathered all the refs.
5602 static int calc_extent_flag(struct btrfs_root *root,
5603 struct cache_tree *extent_cache,
5604 struct extent_buffer *buf,
5605 struct root_item_record *ri,
5608 struct extent_record *rec;
5609 struct cache_extent *cache;
5610 struct tree_backref *tback;
5613 cache = lookup_cache_extent(extent_cache, buf->start, 1);
5614 /* we have added this extent before */
5616 rec = container_of(cache, struct extent_record, cache);
5619 * Except file/reloc tree, we can not have
5622 if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5627 if (buf->start == ri->bytenr)
5630 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5633 owner = btrfs_header_owner(buf);
5634 if (owner == ri->objectid)
5637 tback = find_tree_backref(rec, 0, owner);
5642 if (rec->flag_block_full_backref != -1 &&
5643 rec->flag_block_full_backref != 0)
5644 rec->bad_full_backref = 1;
5647 *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5648 if (rec->flag_block_full_backref != -1 &&
5649 rec->flag_block_full_backref != 1)
5650 rec->bad_full_backref = 1;
5654 static int run_next_block(struct btrfs_root *root,
5655 struct block_info *bits,
5658 struct cache_tree *pending,
5659 struct cache_tree *seen,
5660 struct cache_tree *reada,
5661 struct cache_tree *nodes,
5662 struct cache_tree *extent_cache,
5663 struct cache_tree *chunk_cache,
5664 struct rb_root *dev_cache,
5665 struct block_group_tree *block_group_cache,
5666 struct device_extent_tree *dev_extent_cache,
5667 struct root_item_record *ri)
5669 struct extent_buffer *buf;
5670 struct extent_record *rec = NULL;
5681 struct btrfs_key key;
5682 struct cache_extent *cache;
5685 nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5686 bits_nr, &reada_bits);
5691 for(i = 0; i < nritems; i++) {
5692 ret = add_cache_extent(reada, bits[i].start,
5697 /* fixme, get the parent transid */
5698 readahead_tree_block(root, bits[i].start,
5702 *last = bits[0].start;
5703 bytenr = bits[0].start;
5704 size = bits[0].size;
5706 cache = lookup_cache_extent(pending, bytenr, size);
5708 remove_cache_extent(pending, cache);
5711 cache = lookup_cache_extent(reada, bytenr, size);
5713 remove_cache_extent(reada, cache);
5716 cache = lookup_cache_extent(nodes, bytenr, size);
5718 remove_cache_extent(nodes, cache);
5721 cache = lookup_cache_extent(extent_cache, bytenr, size);
5723 rec = container_of(cache, struct extent_record, cache);
5724 gen = rec->parent_generation;
5727 /* fixme, get the real parent transid */
5728 buf = read_tree_block(root, bytenr, size, gen);
5729 if (!extent_buffer_uptodate(buf)) {
5730 record_bad_block_io(root->fs_info,
5731 extent_cache, bytenr, size);
5735 nritems = btrfs_header_nritems(buf);
5738 if (!init_extent_tree) {
5739 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5740 btrfs_header_level(buf), 1, NULL,
5743 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5745 fprintf(stderr, "Couldn't calc extent flags\n");
5746 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5751 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5753 fprintf(stderr, "Couldn't calc extent flags\n");
5754 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5758 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5760 ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
5761 ri->objectid == btrfs_header_owner(buf)) {
5763 * Ok we got to this block from it's original owner and
5764 * we have FULL_BACKREF set. Relocation can leave
5765 * converted blocks over so this is altogether possible,
5766 * however it's not possible if the generation > the
5767 * last snapshot, so check for this case.
5769 if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
5770 btrfs_header_generation(buf) > ri->last_snapshot) {
5771 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
5772 rec->bad_full_backref = 1;
5777 (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
5778 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
5779 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5780 rec->bad_full_backref = 1;
5784 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5785 rec->flag_block_full_backref = 1;
5789 rec->flag_block_full_backref = 0;
5791 owner = btrfs_header_owner(buf);
5794 ret = check_block(root, extent_cache, buf, flags);
5798 if (btrfs_is_leaf(buf)) {
5799 btree_space_waste += btrfs_leaf_free_space(root, buf);
5800 for (i = 0; i < nritems; i++) {
5801 struct btrfs_file_extent_item *fi;
5802 btrfs_item_key_to_cpu(buf, &key, i);
5803 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5804 process_extent_item(root, extent_cache, buf,
5808 if (key.type == BTRFS_METADATA_ITEM_KEY) {
5809 process_extent_item(root, extent_cache, buf,
5813 if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5815 btrfs_item_size_nr(buf, i);
5818 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5819 process_chunk_item(chunk_cache, &key, buf, i);
5822 if (key.type == BTRFS_DEV_ITEM_KEY) {
5823 process_device_item(dev_cache, &key, buf, i);
5826 if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5827 process_block_group_item(block_group_cache,
5831 if (key.type == BTRFS_DEV_EXTENT_KEY) {
5832 process_device_extent_item(dev_extent_cache,
5837 if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5838 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5839 process_extent_ref_v0(extent_cache, buf, i);
5846 if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5847 add_tree_backref(extent_cache, key.objectid, 0,
5851 if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5852 add_tree_backref(extent_cache, key.objectid,
5856 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5857 struct btrfs_extent_data_ref *ref;
5858 ref = btrfs_item_ptr(buf, i,
5859 struct btrfs_extent_data_ref);
5860 add_data_backref(extent_cache,
5862 btrfs_extent_data_ref_root(buf, ref),
5863 btrfs_extent_data_ref_objectid(buf,
5865 btrfs_extent_data_ref_offset(buf, ref),
5866 btrfs_extent_data_ref_count(buf, ref),
5867 0, root->sectorsize);
5870 if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5871 struct btrfs_shared_data_ref *ref;
5872 ref = btrfs_item_ptr(buf, i,
5873 struct btrfs_shared_data_ref);
5874 add_data_backref(extent_cache,
5875 key.objectid, key.offset, 0, 0, 0,
5876 btrfs_shared_data_ref_count(buf, ref),
5877 0, root->sectorsize);
5880 if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5881 struct bad_item *bad;
5883 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5887 bad = malloc(sizeof(struct bad_item));
5890 INIT_LIST_HEAD(&bad->list);
5891 memcpy(&bad->key, &key,
5892 sizeof(struct btrfs_key));
5893 bad->root_id = owner;
5894 list_add_tail(&bad->list, &delete_items);
5897 if (key.type != BTRFS_EXTENT_DATA_KEY)
5899 fi = btrfs_item_ptr(buf, i,
5900 struct btrfs_file_extent_item);
5901 if (btrfs_file_extent_type(buf, fi) ==
5902 BTRFS_FILE_EXTENT_INLINE)
5904 if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5907 data_bytes_allocated +=
5908 btrfs_file_extent_disk_num_bytes(buf, fi);
5909 if (data_bytes_allocated < root->sectorsize) {
5912 data_bytes_referenced +=
5913 btrfs_file_extent_num_bytes(buf, fi);
5914 add_data_backref(extent_cache,
5915 btrfs_file_extent_disk_bytenr(buf, fi),
5916 parent, owner, key.objectid, key.offset -
5917 btrfs_file_extent_offset(buf, fi), 1, 1,
5918 btrfs_file_extent_disk_num_bytes(buf, fi));
5922 struct btrfs_key first_key;
5924 first_key.objectid = 0;
5927 btrfs_item_key_to_cpu(buf, &first_key, 0);
5928 level = btrfs_header_level(buf);
5929 for (i = 0; i < nritems; i++) {
5930 ptr = btrfs_node_blockptr(buf, i);
5931 size = btrfs_level_size(root, level - 1);
5932 btrfs_node_key_to_cpu(buf, &key, i);
5934 if ((level == ri->drop_level)
5935 && is_dropped_key(&key, &ri->drop_key)) {
5939 ret = add_extent_rec(extent_cache, &key,
5940 btrfs_node_ptr_generation(buf, i),
5941 ptr, size, 0, 0, 1, 0, 1, 0,
5945 add_tree_backref(extent_cache, ptr, parent, owner, 1);
5948 add_pending(nodes, seen, ptr, size);
5950 add_pending(pending, seen, ptr, size);
5953 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5954 nritems) * sizeof(struct btrfs_key_ptr);
5956 total_btree_bytes += buf->len;
5957 if (fs_root_objectid(btrfs_header_owner(buf)))
5958 total_fs_tree_bytes += buf->len;
5959 if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5960 total_extent_tree_bytes += buf->len;
5961 if (!found_old_backref &&
5962 btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5963 btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5964 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5965 found_old_backref = 1;
5967 free_extent_buffer(buf);
5971 static int add_root_to_pending(struct extent_buffer *buf,
5972 struct cache_tree *extent_cache,
5973 struct cache_tree *pending,
5974 struct cache_tree *seen,
5975 struct cache_tree *nodes,
5978 if (btrfs_header_level(buf) > 0)
5979 add_pending(nodes, seen, buf->start, buf->len);
5981 add_pending(pending, seen, buf->start, buf->len);
5982 add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5983 0, 1, 1, 0, 1, 0, buf->len);
5985 if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5986 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5987 add_tree_backref(extent_cache, buf->start, buf->start,
5990 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
5994 /* as we fix the tree, we might be deleting blocks that
5995 * we're tracking for repair. This hook makes sure we
5996 * remove any backrefs for blocks as we are fixing them.
5998 static int free_extent_hook(struct btrfs_trans_handle *trans,
5999 struct btrfs_root *root,
6000 u64 bytenr, u64 num_bytes, u64 parent,
6001 u64 root_objectid, u64 owner, u64 offset,
6004 struct extent_record *rec;
6005 struct cache_extent *cache;
6007 struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6009 is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6010 cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6014 rec = container_of(cache, struct extent_record, cache);
6016 struct data_backref *back;
6017 back = find_data_backref(rec, parent, root_objectid, owner,
6018 offset, 1, bytenr, num_bytes);
6021 if (back->node.found_ref) {
6022 back->found_ref -= refs_to_drop;
6024 rec->refs -= refs_to_drop;
6026 if (back->node.found_extent_tree) {
6027 back->num_refs -= refs_to_drop;
6028 if (rec->extent_item_refs)
6029 rec->extent_item_refs -= refs_to_drop;
6031 if (back->found_ref == 0)
6032 back->node.found_ref = 0;
6033 if (back->num_refs == 0)
6034 back->node.found_extent_tree = 0;
6036 if (!back->node.found_extent_tree && back->node.found_ref) {
6037 list_del(&back->node.list);
6041 struct tree_backref *back;
6042 back = find_tree_backref(rec, parent, root_objectid);
6045 if (back->node.found_ref) {
6048 back->node.found_ref = 0;
6050 if (back->node.found_extent_tree) {
6051 if (rec->extent_item_refs)
6052 rec->extent_item_refs--;
6053 back->node.found_extent_tree = 0;
6055 if (!back->node.found_extent_tree && back->node.found_ref) {
6056 list_del(&back->node.list);
6060 maybe_free_extent_rec(extent_cache, rec);
6065 static int delete_extent_records(struct btrfs_trans_handle *trans,
6066 struct btrfs_root *root,
6067 struct btrfs_path *path,
6068 u64 bytenr, u64 new_len)
6070 struct btrfs_key key;
6071 struct btrfs_key found_key;
6072 struct extent_buffer *leaf;
6077 key.objectid = bytenr;
6079 key.offset = (u64)-1;
6082 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6089 if (path->slots[0] == 0)
6095 leaf = path->nodes[0];
6096 slot = path->slots[0];
6098 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6099 if (found_key.objectid != bytenr)
6102 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6103 found_key.type != BTRFS_METADATA_ITEM_KEY &&
6104 found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6105 found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6106 found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6107 found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6108 found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6109 btrfs_release_path(path);
6110 if (found_key.type == 0) {
6111 if (found_key.offset == 0)
6113 key.offset = found_key.offset - 1;
6114 key.type = found_key.type;
6116 key.type = found_key.type - 1;
6117 key.offset = (u64)-1;
6121 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6122 found_key.objectid, found_key.type, found_key.offset);
6124 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6127 btrfs_release_path(path);
6129 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6130 found_key.type == BTRFS_METADATA_ITEM_KEY) {
6131 u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6132 found_key.offset : root->leafsize;
6134 ret = btrfs_update_block_group(trans, root, bytenr,
6141 btrfs_release_path(path);
6146 * for a single backref, this will allocate a new extent
6147 * and add the backref to it.
6149 static int record_extent(struct btrfs_trans_handle *trans,
6150 struct btrfs_fs_info *info,
6151 struct btrfs_path *path,
6152 struct extent_record *rec,
6153 struct extent_backref *back,
6154 int allocated, u64 flags)
6157 struct btrfs_root *extent_root = info->extent_root;
6158 struct extent_buffer *leaf;
6159 struct btrfs_key ins_key;
6160 struct btrfs_extent_item *ei;
6161 struct tree_backref *tback;
6162 struct data_backref *dback;
6163 struct btrfs_tree_block_info *bi;
6166 rec->max_size = max_t(u64, rec->max_size,
6167 info->extent_root->leafsize);
6170 u32 item_size = sizeof(*ei);
6173 item_size += sizeof(*bi);
6175 ins_key.objectid = rec->start;
6176 ins_key.offset = rec->max_size;
6177 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6179 ret = btrfs_insert_empty_item(trans, extent_root, path,
6180 &ins_key, item_size);
6184 leaf = path->nodes[0];
6185 ei = btrfs_item_ptr(leaf, path->slots[0],
6186 struct btrfs_extent_item);
6188 btrfs_set_extent_refs(leaf, ei, 0);
6189 btrfs_set_extent_generation(leaf, ei, rec->generation);
6191 if (back->is_data) {
6192 btrfs_set_extent_flags(leaf, ei,
6193 BTRFS_EXTENT_FLAG_DATA);
6195 struct btrfs_disk_key copy_key;;
6197 tback = (struct tree_backref *)back;
6198 bi = (struct btrfs_tree_block_info *)(ei + 1);
6199 memset_extent_buffer(leaf, 0, (unsigned long)bi,
6202 btrfs_set_disk_key_objectid(©_key,
6203 rec->info_objectid);
6204 btrfs_set_disk_key_type(©_key, 0);
6205 btrfs_set_disk_key_offset(©_key, 0);
6207 btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6208 btrfs_set_tree_block_key(leaf, bi, ©_key);
6210 btrfs_set_extent_flags(leaf, ei,
6211 BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6214 btrfs_mark_buffer_dirty(leaf);
6215 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6216 rec->max_size, 1, 0);
6219 btrfs_release_path(path);
6222 if (back->is_data) {
6226 dback = (struct data_backref *)back;
6227 if (back->full_backref)
6228 parent = dback->parent;
6232 for (i = 0; i < dback->found_ref; i++) {
6233 /* if parent != 0, we're doing a full backref
6234 * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6235 * just makes the backref allocator create a data
6238 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6239 rec->start, rec->max_size,
6243 BTRFS_FIRST_FREE_OBJECTID :
6249 fprintf(stderr, "adding new data backref"
6250 " on %llu %s %llu owner %llu"
6251 " offset %llu found %d\n",
6252 (unsigned long long)rec->start,
6253 back->full_backref ?
6255 back->full_backref ?
6256 (unsigned long long)parent :
6257 (unsigned long long)dback->root,
6258 (unsigned long long)dback->owner,
6259 (unsigned long long)dback->offset,
6264 tback = (struct tree_backref *)back;
6265 if (back->full_backref)
6266 parent = tback->parent;
6270 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6271 rec->start, rec->max_size,
6272 parent, tback->root, 0, 0);
6273 fprintf(stderr, "adding new tree backref on "
6274 "start %llu len %llu parent %llu root %llu\n",
6275 rec->start, rec->max_size, parent, tback->root);
6280 btrfs_release_path(path);
6284 struct extent_entry {
6289 struct list_head list;
6292 static struct extent_entry *find_entry(struct list_head *entries,
6293 u64 bytenr, u64 bytes)
6295 struct extent_entry *entry = NULL;
6297 list_for_each_entry(entry, entries, list) {
6298 if (entry->bytenr == bytenr && entry->bytes == bytes)
6305 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6307 struct extent_entry *entry, *best = NULL, *prev = NULL;
6309 list_for_each_entry(entry, entries, list) {
6316 * If there are as many broken entries as entries then we know
6317 * not to trust this particular entry.
6319 if (entry->broken == entry->count)
6323 * If our current entry == best then we can't be sure our best
6324 * is really the best, so we need to keep searching.
6326 if (best && best->count == entry->count) {
6332 /* Prev == entry, not good enough, have to keep searching */
6333 if (!prev->broken && prev->count == entry->count)
6337 best = (prev->count > entry->count) ? prev : entry;
6338 else if (best->count < entry->count)
6346 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6347 struct data_backref *dback, struct extent_entry *entry)
6349 struct btrfs_trans_handle *trans;
6350 struct btrfs_root *root;
6351 struct btrfs_file_extent_item *fi;
6352 struct extent_buffer *leaf;
6353 struct btrfs_key key;
6357 key.objectid = dback->root;
6358 key.type = BTRFS_ROOT_ITEM_KEY;
6359 key.offset = (u64)-1;
6360 root = btrfs_read_fs_root(info, &key);
6362 fprintf(stderr, "Couldn't find root for our ref\n");
6367 * The backref points to the original offset of the extent if it was
6368 * split, so we need to search down to the offset we have and then walk
6369 * forward until we find the backref we're looking for.
6371 key.objectid = dback->owner;
6372 key.type = BTRFS_EXTENT_DATA_KEY;
6373 key.offset = dback->offset;
6374 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6376 fprintf(stderr, "Error looking up ref %d\n", ret);
6381 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6382 ret = btrfs_next_leaf(root, path);
6384 fprintf(stderr, "Couldn't find our ref, next\n");
6388 leaf = path->nodes[0];
6389 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6390 if (key.objectid != dback->owner ||
6391 key.type != BTRFS_EXTENT_DATA_KEY) {
6392 fprintf(stderr, "Couldn't find our ref, search\n");
6395 fi = btrfs_item_ptr(leaf, path->slots[0],
6396 struct btrfs_file_extent_item);
6397 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6398 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6400 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6405 btrfs_release_path(path);
6407 trans = btrfs_start_transaction(root, 1);
6409 return PTR_ERR(trans);
6412 * Ok we have the key of the file extent we want to fix, now we can cow
6413 * down to the thing and fix it.
6415 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6417 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6418 key.objectid, key.type, key.offset, ret);
6422 fprintf(stderr, "Well that's odd, we just found this key "
6423 "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6428 leaf = path->nodes[0];
6429 fi = btrfs_item_ptr(leaf, path->slots[0],
6430 struct btrfs_file_extent_item);
6432 if (btrfs_file_extent_compression(leaf, fi) &&
6433 dback->disk_bytenr != entry->bytenr) {
6434 fprintf(stderr, "Ref doesn't match the record start and is "
6435 "compressed, please take a btrfs-image of this file "
6436 "system and send it to a btrfs developer so they can "
6437 "complete this functionality for bytenr %Lu\n",
6438 dback->disk_bytenr);
6443 if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6444 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6445 } else if (dback->disk_bytenr > entry->bytenr) {
6446 u64 off_diff, offset;
6448 off_diff = dback->disk_bytenr - entry->bytenr;
6449 offset = btrfs_file_extent_offset(leaf, fi);
6450 if (dback->disk_bytenr + offset +
6451 btrfs_file_extent_num_bytes(leaf, fi) >
6452 entry->bytenr + entry->bytes) {
6453 fprintf(stderr, "Ref is past the entry end, please "
6454 "take a btrfs-image of this file system and "
6455 "send it to a btrfs developer, ref %Lu\n",
6456 dback->disk_bytenr);
6461 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6462 btrfs_set_file_extent_offset(leaf, fi, offset);
6463 } else if (dback->disk_bytenr < entry->bytenr) {
6466 offset = btrfs_file_extent_offset(leaf, fi);
6467 if (dback->disk_bytenr + offset < entry->bytenr) {
6468 fprintf(stderr, "Ref is before the entry start, please"
6469 " take a btrfs-image of this file system and "
6470 "send it to a btrfs developer, ref %Lu\n",
6471 dback->disk_bytenr);
6476 offset += dback->disk_bytenr;
6477 offset -= entry->bytenr;
6478 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6479 btrfs_set_file_extent_offset(leaf, fi, offset);
6482 btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6485 * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6486 * only do this if we aren't using compression, otherwise it's a
6489 if (!btrfs_file_extent_compression(leaf, fi))
6490 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6492 printf("ram bytes may be wrong?\n");
6493 btrfs_mark_buffer_dirty(leaf);
6495 err = btrfs_commit_transaction(trans, root);
6496 btrfs_release_path(path);
6497 return ret ? ret : err;
6500 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
6501 struct extent_record *rec)
6503 struct extent_backref *back;
6504 struct data_backref *dback;
6505 struct extent_entry *entry, *best = NULL;
6508 int broken_entries = 0;
6513 * Metadata is easy and the backrefs should always agree on bytenr and
6514 * size, if not we've got bigger issues.
6519 list_for_each_entry(back, &rec->backrefs, list) {
6520 if (back->full_backref || !back->is_data)
6523 dback = (struct data_backref *)back;
6526 * We only pay attention to backrefs that we found a real
6529 if (dback->found_ref == 0)
6533 * For now we only catch when the bytes don't match, not the
6534 * bytenr. We can easily do this at the same time, but I want
6535 * to have a fs image to test on before we just add repair
6536 * functionality willy-nilly so we know we won't screw up the
6540 entry = find_entry(&entries, dback->disk_bytenr,
6543 entry = malloc(sizeof(struct extent_entry));
6548 memset(entry, 0, sizeof(*entry));
6549 entry->bytenr = dback->disk_bytenr;
6550 entry->bytes = dback->bytes;
6551 list_add_tail(&entry->list, &entries);
6556 * If we only have on entry we may think the entries agree when
6557 * in reality they don't so we have to do some extra checking.
6559 if (dback->disk_bytenr != rec->start ||
6560 dback->bytes != rec->nr || back->broken)
6571 /* Yay all the backrefs agree, carry on good sir */
6572 if (nr_entries <= 1 && !mismatch)
6575 fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6576 "%Lu\n", rec->start);
6579 * First we want to see if the backrefs can agree amongst themselves who
6580 * is right, so figure out which one of the entries has the highest
6583 best = find_most_right_entry(&entries);
6586 * Ok so we may have an even split between what the backrefs think, so
6587 * this is where we use the extent ref to see what it thinks.
6590 entry = find_entry(&entries, rec->start, rec->nr);
6591 if (!entry && (!broken_entries || !rec->found_rec)) {
6592 fprintf(stderr, "Backrefs don't agree with each other "
6593 "and extent record doesn't agree with anybody,"
6594 " so we can't fix bytenr %Lu bytes %Lu\n",
6595 rec->start, rec->nr);
6598 } else if (!entry) {
6600 * Ok our backrefs were broken, we'll assume this is the
6601 * correct value and add an entry for this range.
6603 entry = malloc(sizeof(struct extent_entry));
6608 memset(entry, 0, sizeof(*entry));
6609 entry->bytenr = rec->start;
6610 entry->bytes = rec->nr;
6611 list_add_tail(&entry->list, &entries);
6615 best = find_most_right_entry(&entries);
6617 fprintf(stderr, "Backrefs and extent record evenly "
6618 "split on who is right, this is going to "
6619 "require user input to fix bytenr %Lu bytes "
6620 "%Lu\n", rec->start, rec->nr);
6627 * I don't think this can happen currently as we'll abort() if we catch
6628 * this case higher up, but in case somebody removes that we still can't
6629 * deal with it properly here yet, so just bail out of that's the case.
6631 if (best->bytenr != rec->start) {
6632 fprintf(stderr, "Extent start and backref starts don't match, "
6633 "please use btrfs-image on this file system and send "
6634 "it to a btrfs developer so they can make fsck fix "
6635 "this particular case. bytenr is %Lu, bytes is %Lu\n",
6636 rec->start, rec->nr);
6642 * Ok great we all agreed on an extent record, let's go find the real
6643 * references and fix up the ones that don't match.
6645 list_for_each_entry(back, &rec->backrefs, list) {
6646 if (back->full_backref || !back->is_data)
6649 dback = (struct data_backref *)back;
6652 * Still ignoring backrefs that don't have a real ref attached
6655 if (dback->found_ref == 0)
6658 if (dback->bytes == best->bytes &&
6659 dback->disk_bytenr == best->bytenr)
6662 ret = repair_ref(info, path, dback, best);
6668 * Ok we messed with the actual refs, which means we need to drop our
6669 * entire cache and go back and rescan. I know this is a huge pain and
6670 * adds a lot of extra work, but it's the only way to be safe. Once all
6671 * the backrefs agree we may not need to do anything to the extent
6676 while (!list_empty(&entries)) {
6677 entry = list_entry(entries.next, struct extent_entry, list);
6678 list_del_init(&entry->list);
6684 static int process_duplicates(struct btrfs_root *root,
6685 struct cache_tree *extent_cache,
6686 struct extent_record *rec)
6688 struct extent_record *good, *tmp;
6689 struct cache_extent *cache;
6693 * If we found a extent record for this extent then return, or if we
6694 * have more than one duplicate we are likely going to need to delete
6697 if (rec->found_rec || rec->num_duplicates > 1)
6700 /* Shouldn't happen but just in case */
6701 BUG_ON(!rec->num_duplicates);
6704 * So this happens if we end up with a backref that doesn't match the
6705 * actual extent entry. So either the backref is bad or the extent
6706 * entry is bad. Either way we want to have the extent_record actually
6707 * reflect what we found in the extent_tree, so we need to take the
6708 * duplicate out and use that as the extent_record since the only way we
6709 * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6711 remove_cache_extent(extent_cache, &rec->cache);
6713 good = list_entry(rec->dups.next, struct extent_record, list);
6714 list_del_init(&good->list);
6715 INIT_LIST_HEAD(&good->backrefs);
6716 INIT_LIST_HEAD(&good->dups);
6717 good->cache.start = good->start;
6718 good->cache.size = good->nr;
6719 good->content_checked = 0;
6720 good->owner_ref_checked = 0;
6721 good->num_duplicates = 0;
6722 good->refs = rec->refs;
6723 list_splice_init(&rec->backrefs, &good->backrefs);
6725 cache = lookup_cache_extent(extent_cache, good->start,
6729 tmp = container_of(cache, struct extent_record, cache);
6732 * If we find another overlapping extent and it's found_rec is
6733 * set then it's a duplicate and we need to try and delete
6736 if (tmp->found_rec || tmp->num_duplicates > 0) {
6737 if (list_empty(&good->list))
6738 list_add_tail(&good->list,
6739 &duplicate_extents);
6740 good->num_duplicates += tmp->num_duplicates + 1;
6741 list_splice_init(&tmp->dups, &good->dups);
6742 list_del_init(&tmp->list);
6743 list_add_tail(&tmp->list, &good->dups);
6744 remove_cache_extent(extent_cache, &tmp->cache);
6749 * Ok we have another non extent item backed extent rec, so lets
6750 * just add it to this extent and carry on like we did above.
6752 good->refs += tmp->refs;
6753 list_splice_init(&tmp->backrefs, &good->backrefs);
6754 remove_cache_extent(extent_cache, &tmp->cache);
6757 ret = insert_cache_extent(extent_cache, &good->cache);
6760 return good->num_duplicates ? 0 : 1;
6763 static int delete_duplicate_records(struct btrfs_root *root,
6764 struct extent_record *rec)
6766 struct btrfs_trans_handle *trans;
6767 LIST_HEAD(delete_list);
6768 struct btrfs_path *path;
6769 struct extent_record *tmp, *good, *n;
6772 struct btrfs_key key;
6774 path = btrfs_alloc_path();
6781 /* Find the record that covers all of the duplicates. */
6782 list_for_each_entry(tmp, &rec->dups, list) {
6783 if (good->start < tmp->start)
6785 if (good->nr > tmp->nr)
6788 if (tmp->start + tmp->nr < good->start + good->nr) {
6789 fprintf(stderr, "Ok we have overlapping extents that "
6790 "aren't completely covered by eachother, this "
6791 "is going to require more careful thought. "
6792 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6793 tmp->start, tmp->nr, good->start, good->nr);
6800 list_add_tail(&rec->list, &delete_list);
6802 list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6805 list_move_tail(&tmp->list, &delete_list);
6808 root = root->fs_info->extent_root;
6809 trans = btrfs_start_transaction(root, 1);
6810 if (IS_ERR(trans)) {
6811 ret = PTR_ERR(trans);
6815 list_for_each_entry(tmp, &delete_list, list) {
6816 if (tmp->found_rec == 0)
6818 key.objectid = tmp->start;
6819 key.type = BTRFS_EXTENT_ITEM_KEY;
6820 key.offset = tmp->nr;
6822 /* Shouldn't happen but just in case */
6823 if (tmp->metadata) {
6824 fprintf(stderr, "Well this shouldn't happen, extent "
6825 "record overlaps but is metadata? "
6826 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6830 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6836 ret = btrfs_del_item(trans, root, path);
6839 btrfs_release_path(path);
6842 err = btrfs_commit_transaction(trans, root);
6846 while (!list_empty(&delete_list)) {
6847 tmp = list_entry(delete_list.next, struct extent_record, list);
6848 list_del_init(&tmp->list);
6854 while (!list_empty(&rec->dups)) {
6855 tmp = list_entry(rec->dups.next, struct extent_record, list);
6856 list_del_init(&tmp->list);
6860 btrfs_free_path(path);
6862 if (!ret && !nr_del)
6863 rec->num_duplicates = 0;
6865 return ret ? ret : nr_del;
6868 static int find_possible_backrefs(struct btrfs_fs_info *info,
6869 struct btrfs_path *path,
6870 struct cache_tree *extent_cache,
6871 struct extent_record *rec)
6873 struct btrfs_root *root;
6874 struct extent_backref *back;
6875 struct data_backref *dback;
6876 struct cache_extent *cache;
6877 struct btrfs_file_extent_item *fi;
6878 struct btrfs_key key;
6882 list_for_each_entry(back, &rec->backrefs, list) {
6883 /* Don't care about full backrefs (poor unloved backrefs) */
6884 if (back->full_backref || !back->is_data)
6887 dback = (struct data_backref *)back;
6889 /* We found this one, we don't need to do a lookup */
6890 if (dback->found_ref)
6893 key.objectid = dback->root;
6894 key.type = BTRFS_ROOT_ITEM_KEY;
6895 key.offset = (u64)-1;
6897 root = btrfs_read_fs_root(info, &key);
6899 /* No root, definitely a bad ref, skip */
6900 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6902 /* Other err, exit */
6904 return PTR_ERR(root);
6906 key.objectid = dback->owner;
6907 key.type = BTRFS_EXTENT_DATA_KEY;
6908 key.offset = dback->offset;
6909 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6911 btrfs_release_path(path);
6914 /* Didn't find it, we can carry on */
6919 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6920 struct btrfs_file_extent_item);
6921 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6922 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6923 btrfs_release_path(path);
6924 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6926 struct extent_record *tmp;
6927 tmp = container_of(cache, struct extent_record, cache);
6930 * If we found an extent record for the bytenr for this
6931 * particular backref then we can't add it to our
6932 * current extent record. We only want to add backrefs
6933 * that don't have a corresponding extent item in the
6934 * extent tree since they likely belong to this record
6935 * and we need to fix it if it doesn't match bytenrs.
6941 dback->found_ref += 1;
6942 dback->disk_bytenr = bytenr;
6943 dback->bytes = bytes;
6946 * Set this so the verify backref code knows not to trust the
6947 * values in this backref.
6956 * Record orphan data ref into corresponding root.
6958 * Return 0 if the extent item contains data ref and recorded.
6959 * Return 1 if the extent item contains no useful data ref
6960 * On that case, it may contains only shared_dataref or metadata backref
6961 * or the file extent exists(this should be handled by the extent bytenr
6963 * Return <0 if something goes wrong.
6965 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
6966 struct extent_record *rec)
6968 struct btrfs_key key;
6969 struct btrfs_root *dest_root;
6970 struct extent_backref *back;
6971 struct data_backref *dback;
6972 struct orphan_data_extent *orphan;
6973 struct btrfs_path *path;
6974 int recorded_data_ref = 0;
6979 path = btrfs_alloc_path();
6982 list_for_each_entry(back, &rec->backrefs, list) {
6983 if (back->full_backref || !back->is_data ||
6984 !back->found_extent_tree)
6986 dback = (struct data_backref *)back;
6987 if (dback->found_ref)
6989 key.objectid = dback->root;
6990 key.type = BTRFS_ROOT_ITEM_KEY;
6991 key.offset = (u64)-1;
6993 dest_root = btrfs_read_fs_root(fs_info, &key);
6995 /* For non-exist root we just skip it */
6996 if (IS_ERR(dest_root) || !dest_root)
6999 key.objectid = dback->owner;
7000 key.type = BTRFS_EXTENT_DATA_KEY;
7001 key.offset = dback->offset;
7003 ret = btrfs_search_slot(NULL, dest_root, &key, path, 0, 0);
7005 * For ret < 0, it's OK since the fs-tree may be corrupted,
7006 * we need to record it for inode/file extent rebuild.
7007 * For ret > 0, we record it only for file extent rebuild.
7008 * For ret == 0, the file extent exists but only bytenr
7009 * mismatch, let the original bytenr fix routine to handle,
7015 orphan = malloc(sizeof(*orphan));
7020 INIT_LIST_HEAD(&orphan->list);
7021 orphan->root = dback->root;
7022 orphan->objectid = dback->owner;
7023 orphan->offset = dback->offset;
7024 orphan->disk_bytenr = rec->cache.start;
7025 orphan->disk_len = rec->cache.size;
7026 list_add(&dest_root->orphan_data_extents, &orphan->list);
7027 recorded_data_ref = 1;
7030 btrfs_free_path(path);
7032 return !recorded_data_ref;
7038 * when an incorrect extent item is found, this will delete
7039 * all of the existing entries for it and recreate them
7040 * based on what the tree scan found.
7042 static int fixup_extent_refs(struct btrfs_fs_info *info,
7043 struct cache_tree *extent_cache,
7044 struct extent_record *rec)
7046 struct btrfs_trans_handle *trans = NULL;
7048 struct btrfs_path *path;
7049 struct list_head *cur = rec->backrefs.next;
7050 struct cache_extent *cache;
7051 struct extent_backref *back;
7055 if (rec->flag_block_full_backref)
7056 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7058 path = btrfs_alloc_path();
7062 if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7064 * Sometimes the backrefs themselves are so broken they don't
7065 * get attached to any meaningful rec, so first go back and
7066 * check any of our backrefs that we couldn't find and throw
7067 * them into the list if we find the backref so that
7068 * verify_backrefs can figure out what to do.
7070 ret = find_possible_backrefs(info, path, extent_cache, rec);
7075 /* step one, make sure all of the backrefs agree */
7076 ret = verify_backrefs(info, path, rec);
7080 trans = btrfs_start_transaction(info->extent_root, 1);
7081 if (IS_ERR(trans)) {
7082 ret = PTR_ERR(trans);
7086 /* step two, delete all the existing records */
7087 ret = delete_extent_records(trans, info->extent_root, path,
7088 rec->start, rec->max_size);
7093 /* was this block corrupt? If so, don't add references to it */
7094 cache = lookup_cache_extent(info->corrupt_blocks,
7095 rec->start, rec->max_size);
7101 /* step three, recreate all the refs we did find */
7102 while(cur != &rec->backrefs) {
7103 back = list_entry(cur, struct extent_backref, list);
7107 * if we didn't find any references, don't create a
7110 if (!back->found_ref)
7113 rec->bad_full_backref = 0;
7114 ret = record_extent(trans, info, path, rec, back, allocated, flags);
7122 int err = btrfs_commit_transaction(trans, info->extent_root);
7127 btrfs_free_path(path);
7131 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7132 struct extent_record *rec)
7134 struct btrfs_trans_handle *trans;
7135 struct btrfs_root *root = fs_info->extent_root;
7136 struct btrfs_path *path;
7137 struct btrfs_extent_item *ei;
7138 struct btrfs_key key;
7142 key.objectid = rec->start;
7143 if (rec->metadata) {
7144 key.type = BTRFS_METADATA_ITEM_KEY;
7145 key.offset = rec->info_level;
7147 key.type = BTRFS_EXTENT_ITEM_KEY;
7148 key.offset = rec->max_size;
7151 path = btrfs_alloc_path();
7155 trans = btrfs_start_transaction(root, 0);
7156 if (IS_ERR(trans)) {
7157 btrfs_free_path(path);
7158 return PTR_ERR(trans);
7161 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7163 btrfs_free_path(path);
7164 btrfs_commit_transaction(trans, root);
7167 fprintf(stderr, "Didn't find extent for %llu\n",
7168 (unsigned long long)rec->start);
7169 btrfs_free_path(path);
7170 btrfs_commit_transaction(trans, root);
7174 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7175 struct btrfs_extent_item);
7176 flags = btrfs_extent_flags(path->nodes[0], ei);
7177 if (rec->flag_block_full_backref) {
7178 fprintf(stderr, "setting full backref on %llu\n",
7179 (unsigned long long)key.objectid);
7180 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7182 fprintf(stderr, "clearing full backref on %llu\n",
7183 (unsigned long long)key.objectid);
7184 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7186 btrfs_set_extent_flags(path->nodes[0], ei, flags);
7187 btrfs_mark_buffer_dirty(path->nodes[0]);
7188 btrfs_free_path(path);
7189 return btrfs_commit_transaction(trans, root);
7192 /* right now we only prune from the extent allocation tree */
7193 static int prune_one_block(struct btrfs_trans_handle *trans,
7194 struct btrfs_fs_info *info,
7195 struct btrfs_corrupt_block *corrupt)
7198 struct btrfs_path path;
7199 struct extent_buffer *eb;
7203 int level = corrupt->level + 1;
7205 btrfs_init_path(&path);
7207 /* we want to stop at the parent to our busted block */
7208 path.lowest_level = level;
7210 ret = btrfs_search_slot(trans, info->extent_root,
7211 &corrupt->key, &path, -1, 1);
7216 eb = path.nodes[level];
7223 * hopefully the search gave us the block we want to prune,
7224 * lets try that first
7226 slot = path.slots[level];
7227 found = btrfs_node_blockptr(eb, slot);
7228 if (found == corrupt->cache.start)
7231 nritems = btrfs_header_nritems(eb);
7233 /* the search failed, lets scan this node and hope we find it */
7234 for (slot = 0; slot < nritems; slot++) {
7235 found = btrfs_node_blockptr(eb, slot);
7236 if (found == corrupt->cache.start)
7240 * we couldn't find the bad block. TODO, search all the nodes for pointers
7243 if (eb == info->extent_root->node) {
7248 btrfs_release_path(&path);
7253 printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7254 ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7257 btrfs_release_path(&path);
7261 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7263 struct btrfs_trans_handle *trans = NULL;
7264 struct cache_extent *cache;
7265 struct btrfs_corrupt_block *corrupt;
7268 cache = search_cache_extent(info->corrupt_blocks, 0);
7272 trans = btrfs_start_transaction(info->extent_root, 1);
7274 return PTR_ERR(trans);
7276 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7277 prune_one_block(trans, info, corrupt);
7278 remove_cache_extent(info->corrupt_blocks, cache);
7281 return btrfs_commit_transaction(trans, info->extent_root);
7285 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7287 struct btrfs_block_group_cache *cache;
7292 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7293 &start, &end, EXTENT_DIRTY);
7296 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7302 cache = btrfs_lookup_first_block_group(fs_info, start);
7307 start = cache->key.objectid + cache->key.offset;
7311 static int check_extent_refs(struct btrfs_root *root,
7312 struct cache_tree *extent_cache)
7314 struct extent_record *rec;
7315 struct cache_extent *cache;
7324 * if we're doing a repair, we have to make sure
7325 * we don't allocate from the problem extents.
7326 * In the worst case, this will be all the
7329 cache = search_cache_extent(extent_cache, 0);
7331 rec = container_of(cache, struct extent_record, cache);
7332 set_extent_dirty(root->fs_info->excluded_extents,
7334 rec->start + rec->max_size - 1,
7336 cache = next_cache_extent(cache);
7339 /* pin down all the corrupted blocks too */
7340 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7342 set_extent_dirty(root->fs_info->excluded_extents,
7344 cache->start + cache->size - 1,
7346 cache = next_cache_extent(cache);
7348 prune_corrupt_blocks(root->fs_info);
7349 reset_cached_block_groups(root->fs_info);
7352 reset_cached_block_groups(root->fs_info);
7355 * We need to delete any duplicate entries we find first otherwise we
7356 * could mess up the extent tree when we have backrefs that actually
7357 * belong to a different extent item and not the weird duplicate one.
7359 while (repair && !list_empty(&duplicate_extents)) {
7360 rec = list_entry(duplicate_extents.next, struct extent_record,
7362 list_del_init(&rec->list);
7364 /* Sometimes we can find a backref before we find an actual
7365 * extent, so we need to process it a little bit to see if there
7366 * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7367 * if this is a backref screwup. If we need to delete stuff
7368 * process_duplicates() will return 0, otherwise it will return
7371 if (process_duplicates(root, extent_cache, rec))
7373 ret = delete_duplicate_records(root, rec);
7377 * delete_duplicate_records will return the number of entries
7378 * deleted, so if it's greater than 0 then we know we actually
7379 * did something and we need to remove.
7393 cache = search_cache_extent(extent_cache, 0);
7396 rec = container_of(cache, struct extent_record, cache);
7397 if (rec->num_duplicates) {
7398 fprintf(stderr, "extent item %llu has multiple extent "
7399 "items\n", (unsigned long long)rec->start);
7404 if (rec->refs != rec->extent_item_refs) {
7405 fprintf(stderr, "ref mismatch on [%llu %llu] ",
7406 (unsigned long long)rec->start,
7407 (unsigned long long)rec->nr);
7408 fprintf(stderr, "extent item %llu, found %llu\n",
7409 (unsigned long long)rec->extent_item_refs,
7410 (unsigned long long)rec->refs);
7411 ret = record_orphan_data_extents(root->fs_info, rec);
7418 * we can't use the extent to repair file
7419 * extent, let the fallback method handle it.
7421 if (!fixed && repair) {
7422 ret = fixup_extent_refs(
7433 if (all_backpointers_checked(rec, 1)) {
7434 fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7435 (unsigned long long)rec->start,
7436 (unsigned long long)rec->nr);
7438 if (!fixed && !recorded && repair) {
7439 ret = fixup_extent_refs(root->fs_info,
7448 if (!rec->owner_ref_checked) {
7449 fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7450 (unsigned long long)rec->start,
7451 (unsigned long long)rec->nr);
7452 if (!fixed && !recorded && repair) {
7453 ret = fixup_extent_refs(root->fs_info,
7462 if (rec->bad_full_backref) {
7463 fprintf(stderr, "bad full backref, on [%llu]\n",
7464 (unsigned long long)rec->start);
7466 ret = fixup_extent_flags(root->fs_info, rec);
7475 remove_cache_extent(extent_cache, cache);
7476 free_all_extent_backrefs(rec);
7477 if (!init_extent_tree && repair && (!cur_err || fixed))
7478 clear_extent_dirty(root->fs_info->excluded_extents,
7480 rec->start + rec->max_size - 1,
7486 if (ret && ret != -EAGAIN) {
7487 fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
7490 struct btrfs_trans_handle *trans;
7492 root = root->fs_info->extent_root;
7493 trans = btrfs_start_transaction(root, 1);
7494 if (IS_ERR(trans)) {
7495 ret = PTR_ERR(trans);
7499 btrfs_fix_block_accounting(trans, root);
7500 ret = btrfs_commit_transaction(trans, root);
7505 fprintf(stderr, "repaired damaged extent references\n");
7511 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
7515 if (type & BTRFS_BLOCK_GROUP_RAID0) {
7516 stripe_size = length;
7517 stripe_size /= num_stripes;
7518 } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
7519 stripe_size = length * 2;
7520 stripe_size /= num_stripes;
7521 } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
7522 stripe_size = length;
7523 stripe_size /= (num_stripes - 1);
7524 } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
7525 stripe_size = length;
7526 stripe_size /= (num_stripes - 2);
7528 stripe_size = length;
7534 * Check the chunk with its block group/dev list ref:
7535 * Return 0 if all refs seems valid.
7536 * Return 1 if part of refs seems valid, need later check for rebuild ref
7537 * like missing block group and needs to search extent tree to rebuild them.
7538 * Return -1 if essential refs are missing and unable to rebuild.
7540 static int check_chunk_refs(struct chunk_record *chunk_rec,
7541 struct block_group_tree *block_group_cache,
7542 struct device_extent_tree *dev_extent_cache,
7545 struct cache_extent *block_group_item;
7546 struct block_group_record *block_group_rec;
7547 struct cache_extent *dev_extent_item;
7548 struct device_extent_record *dev_extent_rec;
7552 int metadump_v2 = 0;
7556 block_group_item = lookup_cache_extent(&block_group_cache->tree,
7559 if (block_group_item) {
7560 block_group_rec = container_of(block_group_item,
7561 struct block_group_record,
7563 if (chunk_rec->length != block_group_rec->offset ||
7564 chunk_rec->offset != block_group_rec->objectid ||
7566 chunk_rec->type_flags != block_group_rec->flags)) {
7569 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
7570 chunk_rec->objectid,
7575 chunk_rec->type_flags,
7576 block_group_rec->objectid,
7577 block_group_rec->type,
7578 block_group_rec->offset,
7579 block_group_rec->offset,
7580 block_group_rec->objectid,
7581 block_group_rec->flags);
7584 list_del_init(&block_group_rec->list);
7585 chunk_rec->bg_rec = block_group_rec;
7590 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
7591 chunk_rec->objectid,
7596 chunk_rec->type_flags);
7603 length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
7604 chunk_rec->num_stripes);
7605 for (i = 0; i < chunk_rec->num_stripes; ++i) {
7606 devid = chunk_rec->stripes[i].devid;
7607 offset = chunk_rec->stripes[i].offset;
7608 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
7609 devid, offset, length);
7610 if (dev_extent_item) {
7611 dev_extent_rec = container_of(dev_extent_item,
7612 struct device_extent_record,
7614 if (dev_extent_rec->objectid != devid ||
7615 dev_extent_rec->offset != offset ||
7616 dev_extent_rec->chunk_offset != chunk_rec->offset ||
7617 dev_extent_rec->length != length) {
7620 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7621 chunk_rec->objectid,
7624 chunk_rec->stripes[i].devid,
7625 chunk_rec->stripes[i].offset,
7626 dev_extent_rec->objectid,
7627 dev_extent_rec->offset,
7628 dev_extent_rec->length);
7631 list_move(&dev_extent_rec->chunk_list,
7632 &chunk_rec->dextents);
7637 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7638 chunk_rec->objectid,
7641 chunk_rec->stripes[i].devid,
7642 chunk_rec->stripes[i].offset);
7649 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7650 int check_chunks(struct cache_tree *chunk_cache,
7651 struct block_group_tree *block_group_cache,
7652 struct device_extent_tree *dev_extent_cache,
7653 struct list_head *good, struct list_head *bad,
7654 struct list_head *rebuild, int silent)
7656 struct cache_extent *chunk_item;
7657 struct chunk_record *chunk_rec;
7658 struct block_group_record *bg_rec;
7659 struct device_extent_record *dext_rec;
7663 chunk_item = first_cache_extent(chunk_cache);
7664 while (chunk_item) {
7665 chunk_rec = container_of(chunk_item, struct chunk_record,
7667 err = check_chunk_refs(chunk_rec, block_group_cache,
7668 dev_extent_cache, silent);
7671 if (err == 0 && good)
7672 list_add_tail(&chunk_rec->list, good);
7673 if (err > 0 && rebuild)
7674 list_add_tail(&chunk_rec->list, rebuild);
7676 list_add_tail(&chunk_rec->list, bad);
7677 chunk_item = next_cache_extent(chunk_item);
7680 list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7683 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7691 list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7695 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7706 static int check_device_used(struct device_record *dev_rec,
7707 struct device_extent_tree *dext_cache)
7709 struct cache_extent *cache;
7710 struct device_extent_record *dev_extent_rec;
7713 cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7715 dev_extent_rec = container_of(cache,
7716 struct device_extent_record,
7718 if (dev_extent_rec->objectid != dev_rec->devid)
7721 list_del_init(&dev_extent_rec->device_list);
7722 total_byte += dev_extent_rec->length;
7723 cache = next_cache_extent(cache);
7726 if (total_byte != dev_rec->byte_used) {
7728 "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7729 total_byte, dev_rec->byte_used, dev_rec->objectid,
7730 dev_rec->type, dev_rec->offset);
7737 /* check btrfs_dev_item -> btrfs_dev_extent */
7738 static int check_devices(struct rb_root *dev_cache,
7739 struct device_extent_tree *dev_extent_cache)
7741 struct rb_node *dev_node;
7742 struct device_record *dev_rec;
7743 struct device_extent_record *dext_rec;
7747 dev_node = rb_first(dev_cache);
7749 dev_rec = container_of(dev_node, struct device_record, node);
7750 err = check_device_used(dev_rec, dev_extent_cache);
7754 dev_node = rb_next(dev_node);
7756 list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7759 "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7760 dext_rec->objectid, dext_rec->offset, dext_rec->length);
7767 static int add_root_item_to_list(struct list_head *head,
7768 u64 objectid, u64 bytenr, u64 last_snapshot,
7769 u8 level, u8 drop_level,
7770 int level_size, struct btrfs_key *drop_key)
7773 struct root_item_record *ri_rec;
7774 ri_rec = malloc(sizeof(*ri_rec));
7777 ri_rec->bytenr = bytenr;
7778 ri_rec->objectid = objectid;
7779 ri_rec->level = level;
7780 ri_rec->level_size = level_size;
7781 ri_rec->drop_level = drop_level;
7782 ri_rec->last_snapshot = last_snapshot;
7784 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7785 list_add_tail(&ri_rec->list, head);
7790 static void free_root_item_list(struct list_head *list)
7792 struct root_item_record *ri_rec;
7794 while (!list_empty(list)) {
7795 ri_rec = list_first_entry(list, struct root_item_record,
7797 list_del_init(&ri_rec->list);
7802 static int deal_root_from_list(struct list_head *list,
7803 struct btrfs_root *root,
7804 struct block_info *bits,
7806 struct cache_tree *pending,
7807 struct cache_tree *seen,
7808 struct cache_tree *reada,
7809 struct cache_tree *nodes,
7810 struct cache_tree *extent_cache,
7811 struct cache_tree *chunk_cache,
7812 struct rb_root *dev_cache,
7813 struct block_group_tree *block_group_cache,
7814 struct device_extent_tree *dev_extent_cache)
7819 while (!list_empty(list)) {
7820 struct root_item_record *rec;
7821 struct extent_buffer *buf;
7822 rec = list_entry(list->next,
7823 struct root_item_record, list);
7825 buf = read_tree_block(root->fs_info->tree_root,
7826 rec->bytenr, rec->level_size, 0);
7827 if (!extent_buffer_uptodate(buf)) {
7828 free_extent_buffer(buf);
7832 add_root_to_pending(buf, extent_cache, pending,
7833 seen, nodes, rec->objectid);
7835 * To rebuild extent tree, we need deal with snapshot
7836 * one by one, otherwise we deal with node firstly which
7837 * can maximize readahead.
7840 ret = run_next_block(root, bits, bits_nr, &last,
7841 pending, seen, reada, nodes,
7842 extent_cache, chunk_cache,
7843 dev_cache, block_group_cache,
7844 dev_extent_cache, rec);
7848 free_extent_buffer(buf);
7849 list_del(&rec->list);
7855 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
7856 reada, nodes, extent_cache, chunk_cache,
7857 dev_cache, block_group_cache,
7858 dev_extent_cache, NULL);
7868 static int check_chunks_and_extents(struct btrfs_root *root)
7870 struct rb_root dev_cache;
7871 struct cache_tree chunk_cache;
7872 struct block_group_tree block_group_cache;
7873 struct device_extent_tree dev_extent_cache;
7874 struct cache_tree extent_cache;
7875 struct cache_tree seen;
7876 struct cache_tree pending;
7877 struct cache_tree reada;
7878 struct cache_tree nodes;
7879 struct extent_io_tree excluded_extents;
7880 struct cache_tree corrupt_blocks;
7881 struct btrfs_path path;
7882 struct btrfs_key key;
7883 struct btrfs_key found_key;
7885 struct block_info *bits;
7887 struct extent_buffer *leaf;
7889 struct btrfs_root_item ri;
7890 struct list_head dropping_trees;
7891 struct list_head normal_trees;
7892 struct btrfs_root *root1;
7897 dev_cache = RB_ROOT;
7898 cache_tree_init(&chunk_cache);
7899 block_group_tree_init(&block_group_cache);
7900 device_extent_tree_init(&dev_extent_cache);
7902 cache_tree_init(&extent_cache);
7903 cache_tree_init(&seen);
7904 cache_tree_init(&pending);
7905 cache_tree_init(&nodes);
7906 cache_tree_init(&reada);
7907 cache_tree_init(&corrupt_blocks);
7908 extent_io_tree_init(&excluded_extents);
7909 INIT_LIST_HEAD(&dropping_trees);
7910 INIT_LIST_HEAD(&normal_trees);
7913 root->fs_info->excluded_extents = &excluded_extents;
7914 root->fs_info->fsck_extent_cache = &extent_cache;
7915 root->fs_info->free_extent_hook = free_extent_hook;
7916 root->fs_info->corrupt_blocks = &corrupt_blocks;
7920 bits = malloc(bits_nr * sizeof(struct block_info));
7927 root1 = root->fs_info->tree_root;
7928 level = btrfs_header_level(root1->node);
7929 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7930 root1->node->start, 0, level, 0,
7931 btrfs_level_size(root1, level), NULL);
7934 root1 = root->fs_info->chunk_root;
7935 level = btrfs_header_level(root1->node);
7936 ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7937 root1->node->start, 0, level, 0,
7938 btrfs_level_size(root1, level), NULL);
7941 btrfs_init_path(&path);
7944 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7945 ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7950 leaf = path.nodes[0];
7951 slot = path.slots[0];
7952 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7953 ret = btrfs_next_leaf(root, &path);
7956 leaf = path.nodes[0];
7957 slot = path.slots[0];
7959 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7960 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7961 unsigned long offset;
7964 offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7965 read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7966 last_snapshot = btrfs_root_last_snapshot(&ri);
7967 if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7968 level = btrfs_root_level(&ri);
7969 level_size = btrfs_level_size(root, level);
7970 ret = add_root_item_to_list(&normal_trees,
7972 btrfs_root_bytenr(&ri),
7973 last_snapshot, level,
7974 0, level_size, NULL);
7978 level = btrfs_root_level(&ri);
7979 level_size = btrfs_level_size(root, level);
7980 objectid = found_key.objectid;
7981 btrfs_disk_key_to_cpu(&found_key,
7983 ret = add_root_item_to_list(&dropping_trees,
7985 btrfs_root_bytenr(&ri),
7986 last_snapshot, level,
7988 level_size, &found_key);
7995 btrfs_release_path(&path);
7998 * check_block can return -EAGAIN if it fixes something, please keep
7999 * this in mind when dealing with return values from these functions, if
8000 * we get -EAGAIN we want to fall through and restart the loop.
8002 ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8003 &seen, &reada, &nodes, &extent_cache,
8004 &chunk_cache, &dev_cache, &block_group_cache,
8011 ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8012 &pending, &seen, &reada, &nodes,
8013 &extent_cache, &chunk_cache, &dev_cache,
8014 &block_group_cache, &dev_extent_cache);
8021 err = check_chunks(&chunk_cache, &block_group_cache,
8022 &dev_extent_cache, NULL, NULL, NULL, 0);
8030 ret = check_extent_refs(root, &extent_cache);
8037 err = check_devices(&dev_cache, &dev_extent_cache);
8043 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8044 extent_io_tree_cleanup(&excluded_extents);
8045 root->fs_info->fsck_extent_cache = NULL;
8046 root->fs_info->free_extent_hook = NULL;
8047 root->fs_info->corrupt_blocks = NULL;
8048 root->fs_info->excluded_extents = NULL;
8051 free_chunk_cache_tree(&chunk_cache);
8052 free_device_cache_tree(&dev_cache);
8053 free_block_group_tree(&block_group_cache);
8054 free_device_extent_tree(&dev_extent_cache);
8055 free_extent_cache_tree(&seen);
8056 free_extent_cache_tree(&pending);
8057 free_extent_cache_tree(&reada);
8058 free_extent_cache_tree(&nodes);
8061 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8062 free_extent_cache_tree(&seen);
8063 free_extent_cache_tree(&pending);
8064 free_extent_cache_tree(&reada);
8065 free_extent_cache_tree(&nodes);
8066 free_chunk_cache_tree(&chunk_cache);
8067 free_block_group_tree(&block_group_cache);
8068 free_device_cache_tree(&dev_cache);
8069 free_device_extent_tree(&dev_extent_cache);
8070 free_extent_record_cache(root->fs_info, &extent_cache);
8071 free_root_item_list(&normal_trees);
8072 free_root_item_list(&dropping_trees);
8073 extent_io_tree_cleanup(&excluded_extents);
8077 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
8078 struct btrfs_root *root, int overwrite)
8080 struct extent_buffer *c;
8081 struct extent_buffer *old = root->node;
8084 struct btrfs_disk_key disk_key = {0,0,0};
8090 extent_buffer_get(c);
8093 c = btrfs_alloc_free_block(trans, root,
8094 btrfs_level_size(root, 0),
8095 root->root_key.objectid,
8096 &disk_key, level, 0, 0);
8099 extent_buffer_get(c);
8103 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
8104 btrfs_set_header_level(c, level);
8105 btrfs_set_header_bytenr(c, c->start);
8106 btrfs_set_header_generation(c, trans->transid);
8107 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
8108 btrfs_set_header_owner(c, root->root_key.objectid);
8110 write_extent_buffer(c, root->fs_info->fsid,
8111 btrfs_header_fsid(), BTRFS_FSID_SIZE);
8113 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
8114 btrfs_header_chunk_tree_uuid(c),
8117 btrfs_mark_buffer_dirty(c);
8119 * this case can happen in the following case:
8121 * 1.overwrite previous root.
8123 * 2.reinit reloc data root, this is because we skip pin
8124 * down reloc data tree before which means we can allocate
8125 * same block bytenr here.
8127 if (old->start == c->start) {
8128 btrfs_set_root_generation(&root->root_item,
8130 root->root_item.level = btrfs_header_level(root->node);
8131 ret = btrfs_update_root(trans, root->fs_info->tree_root,
8132 &root->root_key, &root->root_item);
8134 free_extent_buffer(c);
8138 free_extent_buffer(old);
8140 add_root_to_dirty_list(root);
8144 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
8145 struct extent_buffer *eb, int tree_root)
8147 struct extent_buffer *tmp;
8148 struct btrfs_root_item *ri;
8149 struct btrfs_key key;
8152 int level = btrfs_header_level(eb);
8158 * If we have pinned this block before, don't pin it again.
8159 * This can not only avoid forever loop with broken filesystem
8160 * but also give us some speedups.
8162 if (test_range_bit(&fs_info->pinned_extents, eb->start,
8163 eb->start + eb->len - 1, EXTENT_DIRTY, 0))
8166 btrfs_pin_extent(fs_info, eb->start, eb->len);
8168 leafsize = btrfs_super_leafsize(fs_info->super_copy);
8169 nritems = btrfs_header_nritems(eb);
8170 for (i = 0; i < nritems; i++) {
8172 btrfs_item_key_to_cpu(eb, &key, i);
8173 if (key.type != BTRFS_ROOT_ITEM_KEY)
8175 /* Skip the extent root and reloc roots */
8176 if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
8177 key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
8178 key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
8180 ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
8181 bytenr = btrfs_disk_root_bytenr(eb, ri);
8184 * If at any point we start needing the real root we
8185 * will have to build a stump root for the root we are
8186 * in, but for now this doesn't actually use the root so
8187 * just pass in extent_root.
8189 tmp = read_tree_block(fs_info->extent_root, bytenr,
8191 if (!extent_buffer_uptodate(tmp)) {
8192 fprintf(stderr, "Error reading root block\n");
8195 ret = pin_down_tree_blocks(fs_info, tmp, 0);
8196 free_extent_buffer(tmp);
8200 bytenr = btrfs_node_blockptr(eb, i);
8202 /* If we aren't the tree root don't read the block */
8203 if (level == 1 && !tree_root) {
8204 btrfs_pin_extent(fs_info, bytenr, leafsize);
8208 tmp = read_tree_block(fs_info->extent_root, bytenr,
8210 if (!extent_buffer_uptodate(tmp)) {
8211 fprintf(stderr, "Error reading tree block\n");
8214 ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
8215 free_extent_buffer(tmp);
8224 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
8228 ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
8232 return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
8235 static int reset_block_groups(struct btrfs_fs_info *fs_info)
8237 struct btrfs_block_group_cache *cache;
8238 struct btrfs_path *path;
8239 struct extent_buffer *leaf;
8240 struct btrfs_chunk *chunk;
8241 struct btrfs_key key;
8245 path = btrfs_alloc_path();
8250 key.type = BTRFS_CHUNK_ITEM_KEY;
8253 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
8255 btrfs_free_path(path);
8260 * We do this in case the block groups were screwed up and had alloc
8261 * bits that aren't actually set on the chunks. This happens with
8262 * restored images every time and could happen in real life I guess.
8264 fs_info->avail_data_alloc_bits = 0;
8265 fs_info->avail_metadata_alloc_bits = 0;
8266 fs_info->avail_system_alloc_bits = 0;
8268 /* First we need to create the in-memory block groups */
8270 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8271 ret = btrfs_next_leaf(fs_info->chunk_root, path);
8273 btrfs_free_path(path);
8281 leaf = path->nodes[0];
8282 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8283 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
8288 chunk = btrfs_item_ptr(leaf, path->slots[0],
8289 struct btrfs_chunk);
8290 btrfs_add_block_group(fs_info, 0,
8291 btrfs_chunk_type(leaf, chunk),
8292 key.objectid, key.offset,
8293 btrfs_chunk_length(leaf, chunk));
8294 set_extent_dirty(&fs_info->free_space_cache, key.offset,
8295 key.offset + btrfs_chunk_length(leaf, chunk),
8301 cache = btrfs_lookup_first_block_group(fs_info, start);
8305 start = cache->key.objectid + cache->key.offset;
8308 btrfs_free_path(path);
8312 static int reset_balance(struct btrfs_trans_handle *trans,
8313 struct btrfs_fs_info *fs_info)
8315 struct btrfs_root *root = fs_info->tree_root;
8316 struct btrfs_path *path;
8317 struct extent_buffer *leaf;
8318 struct btrfs_key key;
8319 int del_slot, del_nr = 0;
8323 path = btrfs_alloc_path();
8327 key.objectid = BTRFS_BALANCE_OBJECTID;
8328 key.type = BTRFS_BALANCE_ITEM_KEY;
8331 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8336 goto reinit_data_reloc;
8341 ret = btrfs_del_item(trans, root, path);
8344 btrfs_release_path(path);
8346 key.objectid = BTRFS_TREE_RELOC_OBJECTID;
8347 key.type = BTRFS_ROOT_ITEM_KEY;
8350 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8354 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8359 ret = btrfs_del_items(trans, root, path,
8366 btrfs_release_path(path);
8369 ret = btrfs_search_slot(trans, root, &key, path,
8376 leaf = path->nodes[0];
8377 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8378 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
8380 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8385 del_slot = path->slots[0];
8394 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
8398 btrfs_release_path(path);
8401 key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
8402 key.type = BTRFS_ROOT_ITEM_KEY;
8403 key.offset = (u64)-1;
8404 root = btrfs_read_fs_root(fs_info, &key);
8406 fprintf(stderr, "Error reading data reloc tree\n");
8407 ret = PTR_ERR(root);
8410 record_root_in_trans(trans, root);
8411 ret = btrfs_fsck_reinit_root(trans, root, 0);
8414 ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
8416 btrfs_free_path(path);
8420 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
8421 struct btrfs_fs_info *fs_info)
8427 * The only reason we don't do this is because right now we're just
8428 * walking the trees we find and pinning down their bytes, we don't look
8429 * at any of the leaves. In order to do mixed groups we'd have to check
8430 * the leaves of any fs roots and pin down the bytes for any file
8431 * extents we find. Not hard but why do it if we don't have to?
8433 if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
8434 fprintf(stderr, "We don't support re-initing the extent tree "
8435 "for mixed block groups yet, please notify a btrfs "
8436 "developer you want to do this so they can add this "
8437 "functionality.\n");
8442 * first we need to walk all of the trees except the extent tree and pin
8443 * down the bytes that are in use so we don't overwrite any existing
8446 ret = pin_metadata_blocks(fs_info);
8448 fprintf(stderr, "error pinning down used bytes\n");
8453 * Need to drop all the block groups since we're going to recreate all
8456 btrfs_free_block_groups(fs_info);
8457 ret = reset_block_groups(fs_info);
8459 fprintf(stderr, "error resetting the block groups\n");
8463 /* Ok we can allocate now, reinit the extent root */
8464 ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
8466 fprintf(stderr, "extent root initialization failed\n");
8468 * When the transaction code is updated we should end the
8469 * transaction, but for now progs only knows about commit so
8470 * just return an error.
8476 * Now we have all the in-memory block groups setup so we can make
8477 * allocations properly, and the metadata we care about is safe since we
8478 * pinned all of it above.
8481 struct btrfs_block_group_cache *cache;
8483 cache = btrfs_lookup_first_block_group(fs_info, start);
8486 start = cache->key.objectid + cache->key.offset;
8487 ret = btrfs_insert_item(trans, fs_info->extent_root,
8488 &cache->key, &cache->item,
8489 sizeof(cache->item));
8491 fprintf(stderr, "Error adding block group\n");
8494 btrfs_extent_post_op(trans, fs_info->extent_root);
8497 ret = reset_balance(trans, fs_info);
8499 fprintf(stderr, "error reseting the pending balance\n");
8504 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
8506 struct btrfs_path *path;
8507 struct btrfs_trans_handle *trans;
8508 struct btrfs_key key;
8511 printf("Recowing metadata block %llu\n", eb->start);
8512 key.objectid = btrfs_header_owner(eb);
8513 key.type = BTRFS_ROOT_ITEM_KEY;
8514 key.offset = (u64)-1;
8516 root = btrfs_read_fs_root(root->fs_info, &key);
8518 fprintf(stderr, "Couldn't find owner root %llu\n",
8520 return PTR_ERR(root);
8523 path = btrfs_alloc_path();
8527 trans = btrfs_start_transaction(root, 1);
8528 if (IS_ERR(trans)) {
8529 btrfs_free_path(path);
8530 return PTR_ERR(trans);
8533 path->lowest_level = btrfs_header_level(eb);
8534 if (path->lowest_level)
8535 btrfs_node_key_to_cpu(eb, &key, 0);
8537 btrfs_item_key_to_cpu(eb, &key, 0);
8539 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
8540 btrfs_commit_transaction(trans, root);
8541 btrfs_free_path(path);
8545 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
8547 struct btrfs_path *path;
8548 struct btrfs_trans_handle *trans;
8549 struct btrfs_key key;
8552 printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
8553 bad->key.type, bad->key.offset);
8554 key.objectid = bad->root_id;
8555 key.type = BTRFS_ROOT_ITEM_KEY;
8556 key.offset = (u64)-1;
8558 root = btrfs_read_fs_root(root->fs_info, &key);
8560 fprintf(stderr, "Couldn't find owner root %llu\n",
8562 return PTR_ERR(root);
8565 path = btrfs_alloc_path();
8569 trans = btrfs_start_transaction(root, 1);
8570 if (IS_ERR(trans)) {
8571 btrfs_free_path(path);
8572 return PTR_ERR(trans);
8575 ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
8581 ret = btrfs_del_item(trans, root, path);
8583 btrfs_commit_transaction(trans, root);
8584 btrfs_free_path(path);
8588 static int zero_log_tree(struct btrfs_root *root)
8590 struct btrfs_trans_handle *trans;
8593 trans = btrfs_start_transaction(root, 1);
8594 if (IS_ERR(trans)) {
8595 ret = PTR_ERR(trans);
8598 btrfs_set_super_log_root(root->fs_info->super_copy, 0);
8599 btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
8600 ret = btrfs_commit_transaction(trans, root);
8604 static int populate_csum(struct btrfs_trans_handle *trans,
8605 struct btrfs_root *csum_root, char *buf, u64 start,
8612 while (offset < len) {
8613 sectorsize = csum_root->sectorsize;
8614 ret = read_extent_data(csum_root, buf, start + offset,
8618 ret = btrfs_csum_file_block(trans, csum_root, start + len,
8619 start + offset, buf, sectorsize);
8622 offset += sectorsize;
8627 static int fill_csum_tree_from_one_fs_root(struct btrfs_trans_handle *trans,
8628 struct btrfs_root *csum_root,
8629 struct btrfs_root *cur_root)
8631 struct btrfs_path *path;
8632 struct btrfs_key key;
8633 struct extent_buffer *node;
8634 struct btrfs_file_extent_item *fi;
8641 path = btrfs_alloc_path();
8644 buf = malloc(cur_root->fs_info->csum_root->sectorsize);
8654 ret = btrfs_search_slot(NULL, cur_root, &key, path, 0, 0);
8657 /* Iterate all regular file extents and fill its csum */
8659 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
8661 if (key.type != BTRFS_EXTENT_DATA_KEY)
8663 node = path->nodes[0];
8664 slot = path->slots[0];
8665 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
8666 if (btrfs_file_extent_type(node, fi) != BTRFS_FILE_EXTENT_REG)
8668 start = btrfs_file_extent_disk_bytenr(node, fi);
8669 len = btrfs_file_extent_disk_num_bytes(node, fi);
8671 ret = populate_csum(trans, csum_root, buf, start, len);
8678 * TODO: if next leaf is corrupted, jump to nearest next valid
8681 ret = btrfs_next_item(cur_root, path);
8691 btrfs_free_path(path);
8696 static int fill_csum_tree_from_fs(struct btrfs_trans_handle *trans,
8697 struct btrfs_root *csum_root)
8699 struct btrfs_fs_info *fs_info = csum_root->fs_info;
8700 struct btrfs_path *path;
8701 struct btrfs_root *tree_root = fs_info->tree_root;
8702 struct btrfs_root *cur_root;
8703 struct extent_buffer *node;
8704 struct btrfs_key key;
8708 path = btrfs_alloc_path();
8712 key.objectid = BTRFS_FS_TREE_OBJECTID;
8714 key.type = BTRFS_ROOT_ITEM_KEY;
8716 ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
8725 node = path->nodes[0];
8726 slot = path->slots[0];
8727 btrfs_item_key_to_cpu(node, &key, slot);
8728 if (key.objectid > BTRFS_LAST_FREE_OBJECTID)
8730 if (key.type != BTRFS_ROOT_ITEM_KEY)
8732 if (!is_fstree(key.objectid))
8734 key.offset = (u64)-1;
8736 cur_root = btrfs_read_fs_root(fs_info, &key);
8737 if (IS_ERR(cur_root) || !cur_root) {
8738 fprintf(stderr, "Fail to read fs/subvol tree: %lld\n",
8742 ret = fill_csum_tree_from_one_fs_root(trans, csum_root,
8747 ret = btrfs_next_item(tree_root, path);
8757 btrfs_free_path(path);
8761 static int fill_csum_tree_from_extent(struct btrfs_trans_handle *trans,
8762 struct btrfs_root *csum_root)
8764 struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
8765 struct btrfs_path *path;
8766 struct btrfs_extent_item *ei;
8767 struct extent_buffer *leaf;
8769 struct btrfs_key key;
8772 path = btrfs_alloc_path();
8777 key.type = BTRFS_EXTENT_ITEM_KEY;
8780 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8782 btrfs_free_path(path);
8786 buf = malloc(csum_root->sectorsize);
8788 btrfs_free_path(path);
8793 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8794 ret = btrfs_next_leaf(extent_root, path);
8802 leaf = path->nodes[0];
8804 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8805 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8810 ei = btrfs_item_ptr(leaf, path->slots[0],
8811 struct btrfs_extent_item);
8812 if (!(btrfs_extent_flags(leaf, ei) &
8813 BTRFS_EXTENT_FLAG_DATA)) {
8818 ret = populate_csum(trans, csum_root, buf, key.objectid,
8825 btrfs_free_path(path);
8831 * Recalculate the csum and put it into the csum tree.
8833 * Extent tree init will wipe out all the extent info, so in that case, we
8834 * can't depend on extent tree, but use fs tree. If search_fs_tree is set, we
8835 * will use fs/subvol trees to init the csum tree.
8837 static int fill_csum_tree(struct btrfs_trans_handle *trans,
8838 struct btrfs_root *csum_root,
8842 return fill_csum_tree_from_fs(trans, csum_root);
8844 return fill_csum_tree_from_extent(trans, csum_root);
8847 struct root_item_info {
8848 /* level of the root */
8850 /* number of nodes at this level, must be 1 for a root */
8854 struct cache_extent cache_extent;
8857 static struct cache_tree *roots_info_cache = NULL;
8859 static void free_roots_info_cache(void)
8861 if (!roots_info_cache)
8864 while (!cache_tree_empty(roots_info_cache)) {
8865 struct cache_extent *entry;
8866 struct root_item_info *rii;
8868 entry = first_cache_extent(roots_info_cache);
8871 remove_cache_extent(roots_info_cache, entry);
8872 rii = container_of(entry, struct root_item_info, cache_extent);
8876 free(roots_info_cache);
8877 roots_info_cache = NULL;
8880 static int build_roots_info_cache(struct btrfs_fs_info *info)
8883 struct btrfs_key key;
8884 struct extent_buffer *leaf;
8885 struct btrfs_path *path;
8887 if (!roots_info_cache) {
8888 roots_info_cache = malloc(sizeof(*roots_info_cache));
8889 if (!roots_info_cache)
8891 cache_tree_init(roots_info_cache);
8894 path = btrfs_alloc_path();
8899 key.type = BTRFS_EXTENT_ITEM_KEY;
8902 ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8905 leaf = path->nodes[0];
8908 struct btrfs_key found_key;
8909 struct btrfs_extent_item *ei;
8910 struct btrfs_extent_inline_ref *iref;
8911 int slot = path->slots[0];
8916 struct cache_extent *entry;
8917 struct root_item_info *rii;
8919 if (slot >= btrfs_header_nritems(leaf)) {
8920 ret = btrfs_next_leaf(info->extent_root, path);
8927 leaf = path->nodes[0];
8928 slot = path->slots[0];
8931 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8933 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8934 found_key.type != BTRFS_METADATA_ITEM_KEY)
8937 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8938 flags = btrfs_extent_flags(leaf, ei);
8940 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8941 !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8944 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8945 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8946 level = found_key.offset;
8948 struct btrfs_tree_block_info *info;
8950 info = (struct btrfs_tree_block_info *)(ei + 1);
8951 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8952 level = btrfs_tree_block_level(leaf, info);
8956 * For a root extent, it must be of the following type and the
8957 * first (and only one) iref in the item.
8959 type = btrfs_extent_inline_ref_type(leaf, iref);
8960 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8963 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8964 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8966 rii = malloc(sizeof(struct root_item_info));
8971 rii->cache_extent.start = root_id;
8972 rii->cache_extent.size = 1;
8973 rii->level = (u8)-1;
8974 entry = &rii->cache_extent;
8975 ret = insert_cache_extent(roots_info_cache, entry);
8978 rii = container_of(entry, struct root_item_info,
8982 ASSERT(rii->cache_extent.start == root_id);
8983 ASSERT(rii->cache_extent.size == 1);
8985 if (level > rii->level || rii->level == (u8)-1) {
8987 rii->bytenr = found_key.objectid;
8988 rii->gen = btrfs_extent_generation(leaf, ei);
8989 rii->node_count = 1;
8990 } else if (level == rii->level) {
8998 btrfs_free_path(path);
9003 static int maybe_repair_root_item(struct btrfs_fs_info *info,
9004 struct btrfs_path *path,
9005 const struct btrfs_key *root_key,
9006 const int read_only_mode)
9008 const u64 root_id = root_key->objectid;
9009 struct cache_extent *entry;
9010 struct root_item_info *rii;
9011 struct btrfs_root_item ri;
9012 unsigned long offset;
9014 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
9017 "Error: could not find extent items for root %llu\n",
9018 root_key->objectid);
9022 rii = container_of(entry, struct root_item_info, cache_extent);
9023 ASSERT(rii->cache_extent.start == root_id);
9024 ASSERT(rii->cache_extent.size == 1);
9026 if (rii->node_count != 1) {
9028 "Error: could not find btree root extent for root %llu\n",
9033 offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
9034 read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
9036 if (btrfs_root_bytenr(&ri) != rii->bytenr ||
9037 btrfs_root_level(&ri) != rii->level ||
9038 btrfs_root_generation(&ri) != rii->gen) {
9041 * If we're in repair mode but our caller told us to not update
9042 * the root item, i.e. just check if it needs to be updated, don't
9043 * print this message, since the caller will call us again shortly
9044 * for the same root item without read only mode (the caller will
9045 * open a transaction first).
9047 if (!(read_only_mode && repair))
9049 "%sroot item for root %llu,"
9050 " current bytenr %llu, current gen %llu, current level %u,"
9051 " new bytenr %llu, new gen %llu, new level %u\n",
9052 (read_only_mode ? "" : "fixing "),
9054 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
9055 btrfs_root_level(&ri),
9056 rii->bytenr, rii->gen, rii->level);
9058 if (btrfs_root_generation(&ri) > rii->gen) {
9060 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
9061 root_id, btrfs_root_generation(&ri), rii->gen);
9065 if (!read_only_mode) {
9066 btrfs_set_root_bytenr(&ri, rii->bytenr);
9067 btrfs_set_root_level(&ri, rii->level);
9068 btrfs_set_root_generation(&ri, rii->gen);
9069 write_extent_buffer(path->nodes[0], &ri,
9070 offset, sizeof(ri));
9080 * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
9081 * caused read-only snapshots to be corrupted if they were created at a moment
9082 * when the source subvolume/snapshot had orphan items. The issue was that the
9083 * on-disk root items became incorrect, referring to the pre orphan cleanup root
9084 * node instead of the post orphan cleanup root node.
9085 * So this function, and its callees, just detects and fixes those cases. Even
9086 * though the regression was for read-only snapshots, this function applies to
9087 * any snapshot/subvolume root.
9088 * This must be run before any other repair code - not doing it so, makes other
9089 * repair code delete or modify backrefs in the extent tree for example, which
9090 * will result in an inconsistent fs after repairing the root items.
9092 static int repair_root_items(struct btrfs_fs_info *info)
9094 struct btrfs_path *path = NULL;
9095 struct btrfs_key key;
9096 struct extent_buffer *leaf;
9097 struct btrfs_trans_handle *trans = NULL;
9102 ret = build_roots_info_cache(info);
9106 path = btrfs_alloc_path();
9112 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
9113 key.type = BTRFS_ROOT_ITEM_KEY;
9118 * Avoid opening and committing transactions if a leaf doesn't have
9119 * any root items that need to be fixed, so that we avoid rotating
9120 * backup roots unnecessarily.
9123 trans = btrfs_start_transaction(info->tree_root, 1);
9124 if (IS_ERR(trans)) {
9125 ret = PTR_ERR(trans);
9130 ret = btrfs_search_slot(trans, info->tree_root, &key, path,
9134 leaf = path->nodes[0];
9137 struct btrfs_key found_key;
9139 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
9140 int no_more_keys = find_next_key(path, &key);
9142 btrfs_release_path(path);
9144 ret = btrfs_commit_transaction(trans,
9156 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9158 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
9160 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
9163 ret = maybe_repair_root_item(info, path, &found_key,
9168 if (!trans && repair) {
9171 btrfs_release_path(path);
9181 free_roots_info_cache();
9183 btrfs_free_path(path);
9185 btrfs_commit_transaction(trans, info->tree_root);
9192 const char * const cmd_check_usage[] = {
9193 "btrfs check [options] <device>",
9194 "Check an unmounted btrfs filesystem.",
9196 "-s|--super <superblock> use this superblock copy",
9197 "-b|--backup use the backup root copy",
9198 "--repair try to repair the filesystem",
9199 "--init-csum-tree create a new CRC tree",
9200 "--init-extent-tree create a new extent tree",
9201 "--check-data-csum verify checkums of data blocks",
9202 "--qgroup-report print a report on qgroup consistency",
9203 "--subvol-extents <subvolid> print subvolume extents and sharing state",
9204 "--tree-root <bytenr> use the given bytenr for the tree root",
9208 int cmd_check(int argc, char **argv)
9210 struct cache_tree root_cache;
9211 struct btrfs_root *root;
9212 struct btrfs_fs_info *info;
9215 u64 tree_root_bytenr = 0;
9216 char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
9219 int init_csum_tree = 0;
9221 int qgroup_report = 0;
9222 enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
9226 enum { OPT_REPAIR = 257, OPT_INIT_CSUM, OPT_INIT_EXTENT,
9227 OPT_CHECK_CSUM, OPT_READONLY };
9228 static const struct option long_options[] = {
9229 { "super", required_argument, NULL, 's' },
9230 { "repair", no_argument, NULL, OPT_REPAIR },
9231 { "readonly", no_argument, NULL, OPT_READONLY },
9232 { "init-csum-tree", no_argument, NULL, OPT_INIT_CSUM },
9233 { "init-extent-tree", no_argument, NULL, OPT_INIT_EXTENT },
9234 { "check-data-csum", no_argument, NULL, OPT_CHECK_CSUM },
9235 { "backup", no_argument, NULL, 'b' },
9236 { "subvol-extents", required_argument, NULL, 'E' },
9237 { "qgroup-report", no_argument, NULL, 'Q' },
9238 { "tree-root", required_argument, NULL, 'r' },
9242 c = getopt_long(argc, argv, "as:br:", long_options, NULL);
9246 case 'a': /* ignored */ break;
9248 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
9251 num = arg_strtou64(optarg);
9252 if (num >= BTRFS_SUPER_MIRROR_MAX) {
9254 "ERROR: super mirror should be less than: %d\n",
9255 BTRFS_SUPER_MIRROR_MAX);
9258 bytenr = btrfs_sb_offset(((int)num));
9259 printf("using SB copy %llu, bytenr %llu\n", num,
9260 (unsigned long long)bytenr);
9266 subvolid = arg_strtou64(optarg);
9269 tree_root_bytenr = arg_strtou64(optarg);
9273 usage(cmd_check_usage);
9275 printf("enabling repair mode\n");
9277 ctree_flags |= OPEN_CTREE_WRITES;
9283 printf("Creating a new CRC tree\n");
9286 ctree_flags |= OPEN_CTREE_WRITES;
9288 case OPT_INIT_EXTENT:
9289 init_extent_tree = 1;
9290 ctree_flags |= (OPEN_CTREE_WRITES |
9291 OPEN_CTREE_NO_BLOCK_GROUPS);
9294 case OPT_CHECK_CSUM:
9295 check_data_csum = 1;
9299 argc = argc - optind;
9301 if (check_argc_exact(argc, 1))
9302 usage(cmd_check_usage);
9304 /* This check is the only reason for --readonly to exist */
9305 if (readonly && repair) {
9306 fprintf(stderr, "Repair options are not compatible with --readonly\n");
9311 cache_tree_init(&root_cache);
9313 if((ret = check_mounted(argv[optind])) < 0) {
9314 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
9317 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
9322 /* only allow partial opening under repair mode */
9324 ctree_flags |= OPEN_CTREE_PARTIAL;
9326 info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
9329 fprintf(stderr, "Couldn't open file system\n");
9334 root = info->fs_root;
9337 * repair mode will force us to commit transaction which
9338 * will make us fail to load log tree when mounting.
9340 if (repair && btrfs_super_log_root(info->super_copy)) {
9341 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
9346 ret = zero_log_tree(root);
9348 fprintf(stderr, "fail to zero log tree\n");
9353 uuid_unparse(info->super_copy->fsid, uuidbuf);
9354 if (qgroup_report) {
9355 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
9357 ret = qgroup_verify_all(info);
9359 print_qgroup_report(1);
9363 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
9364 subvolid, argv[optind], uuidbuf);
9365 ret = print_extent_state(info, subvolid);
9368 printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
9370 if (!extent_buffer_uptodate(info->tree_root->node) ||
9371 !extent_buffer_uptodate(info->dev_root->node) ||
9372 !extent_buffer_uptodate(info->chunk_root->node)) {
9373 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9378 if (init_extent_tree || init_csum_tree) {
9379 struct btrfs_trans_handle *trans;
9381 trans = btrfs_start_transaction(info->extent_root, 0);
9382 if (IS_ERR(trans)) {
9383 fprintf(stderr, "Error starting transaction\n");
9384 ret = PTR_ERR(trans);
9388 if (init_extent_tree) {
9389 printf("Creating a new extent tree\n");
9390 ret = reinit_extent_tree(trans, info);
9395 if (init_csum_tree) {
9396 fprintf(stderr, "Reinit crc root\n");
9397 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
9399 fprintf(stderr, "crc root initialization failed\n");
9404 ret = fill_csum_tree(trans, info->csum_root,
9407 fprintf(stderr, "crc refilling failed\n");
9412 * Ok now we commit and run the normal fsck, which will add
9413 * extent entries for all of the items it finds.
9415 ret = btrfs_commit_transaction(trans, info->extent_root);
9419 if (!extent_buffer_uptodate(info->extent_root->node)) {
9420 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
9424 if (!extent_buffer_uptodate(info->csum_root->node)) {
9425 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
9430 fprintf(stderr, "checking extents\n");
9431 ret = check_chunks_and_extents(root);
9433 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
9435 ret = repair_root_items(info);
9439 fprintf(stderr, "Fixed %d roots.\n", ret);
9441 } else if (ret > 0) {
9443 "Found %d roots with an outdated root item.\n",
9446 "Please run a filesystem check with the option --repair to fix them.\n");
9451 fprintf(stderr, "checking free space cache\n");
9452 ret = check_space_cache(root);
9457 * We used to have to have these hole extents in between our real
9458 * extents so if we don't have this flag set we need to make sure there
9459 * are no gaps in the file extents for inodes, otherwise we can just
9460 * ignore it when this happens.
9462 no_holes = btrfs_fs_incompat(root->fs_info,
9463 BTRFS_FEATURE_INCOMPAT_NO_HOLES);
9464 fprintf(stderr, "checking fs roots\n");
9465 ret = check_fs_roots(root, &root_cache);
9469 fprintf(stderr, "checking csums\n");
9470 ret = check_csums(root);
9474 fprintf(stderr, "checking root refs\n");
9475 ret = check_root_refs(root, &root_cache);
9479 while (repair && !list_empty(&root->fs_info->recow_ebs)) {
9480 struct extent_buffer *eb;
9482 eb = list_first_entry(&root->fs_info->recow_ebs,
9483 struct extent_buffer, recow);
9484 list_del_init(&eb->recow);
9485 ret = recow_extent_buffer(root, eb);
9490 while (!list_empty(&delete_items)) {
9491 struct bad_item *bad;
9493 bad = list_first_entry(&delete_items, struct bad_item, list);
9494 list_del_init(&bad->list);
9496 ret = delete_bad_item(root, bad);
9500 if (info->quota_enabled) {
9502 fprintf(stderr, "checking quota groups\n");
9503 err = qgroup_verify_all(info);
9508 if (!list_empty(&root->fs_info->recow_ebs)) {
9509 fprintf(stderr, "Transid errors in file system\n");
9513 print_qgroup_report(0);
9514 if (found_old_backref) { /*
9515 * there was a disk format change when mixed
9516 * backref was in testing tree. The old format
9517 * existed about one week.
9519 printf("\n * Found old mixed backref format. "
9520 "The old format is not supported! *"
9521 "\n * Please mount the FS in readonly mode, "
9522 "backup data and re-format the FS. *\n\n");
9525 printf("found %llu bytes used err is %d\n",
9526 (unsigned long long)bytes_used, ret);
9527 printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
9528 printf("total tree bytes: %llu\n",
9529 (unsigned long long)total_btree_bytes);
9530 printf("total fs tree bytes: %llu\n",
9531 (unsigned long long)total_fs_tree_bytes);
9532 printf("total extent tree bytes: %llu\n",
9533 (unsigned long long)total_extent_tree_bytes);
9534 printf("btree space waste bytes: %llu\n",
9535 (unsigned long long)btree_space_waste);
9536 printf("file data blocks allocated: %llu\n referenced %llu\n",
9537 (unsigned long long)data_bytes_allocated,
9538 (unsigned long long)data_bytes_referenced);
9539 printf("%s\n", PACKAGE_STRING);
9541 free_root_recs_tree(&root_cache);