btrfs-progs: check: use on-stack path buffer in fixup_extent_refs
[platform/upstream/btrfs-progs.git] / cmds-check.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
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.
7  *
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.
12  *
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.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <getopt.h>
27 #include <uuid/uuid.h>
28 #include "ctree.h"
29 #include "volumes.h"
30 #include "repair.h"
31 #include "disk-io.h"
32 #include "print-tree.h"
33 #include "task-utils.h"
34 #include "transaction.h"
35 #include "utils.h"
36 #include "commands.h"
37 #include "free-space-cache.h"
38 #include "free-space-tree.h"
39 #include "btrfsck.h"
40 #include "qgroup-verify.h"
41 #include "rbtree-utils.h"
42 #include "backref.h"
43 #include "ulist.h"
44
45 enum task_position {
46         TASK_EXTENTS,
47         TASK_FREE_SPACE,
48         TASK_FS_ROOTS,
49         TASK_NOTHING, /* have to be the last element */
50 };
51
52 struct task_ctx {
53         int progress_enabled;
54         enum task_position tp;
55
56         struct task_info *info;
57 };
58
59 static u64 bytes_used = 0;
60 static u64 total_csum_bytes = 0;
61 static u64 total_btree_bytes = 0;
62 static u64 total_fs_tree_bytes = 0;
63 static u64 total_extent_tree_bytes = 0;
64 static u64 btree_space_waste = 0;
65 static u64 data_bytes_allocated = 0;
66 static u64 data_bytes_referenced = 0;
67 static int found_old_backref = 0;
68 static LIST_HEAD(duplicate_extents);
69 static LIST_HEAD(delete_items);
70 static int no_holes = 0;
71 static int init_extent_tree = 0;
72 static int check_data_csum = 0;
73 static struct btrfs_fs_info *global_info;
74 static struct task_ctx ctx = { 0 };
75 static struct cache_tree *roots_info_cache = NULL;
76
77 enum btrfs_check_mode {
78         CHECK_MODE_ORIGINAL,
79         CHECK_MODE_LOWMEM,
80         CHECK_MODE_UNKNOWN,
81         CHECK_MODE_DEFAULT = CHECK_MODE_ORIGINAL
82 };
83
84 static enum btrfs_check_mode check_mode = CHECK_MODE_DEFAULT;
85
86 struct extent_backref {
87         struct list_head list;
88         unsigned int is_data:1;
89         unsigned int found_extent_tree:1;
90         unsigned int full_backref:1;
91         unsigned int found_ref:1;
92         unsigned int broken:1;
93 };
94
95 static inline struct extent_backref* to_extent_backref(struct list_head *entry)
96 {
97         return list_entry(entry, struct extent_backref, list);
98 }
99
100 struct data_backref {
101         struct extent_backref node;
102         union {
103                 u64 parent;
104                 u64 root;
105         };
106         u64 owner;
107         u64 offset;
108         u64 disk_bytenr;
109         u64 bytes;
110         u64 ram_bytes;
111         u32 num_refs;
112         u32 found_ref;
113 };
114
115 static inline struct data_backref* to_data_backref(struct extent_backref *back)
116 {
117         return container_of(back, struct data_backref, node);
118 }
119
120 /*
121  * Much like data_backref, just removed the undetermined members
122  * and change it to use list_head.
123  * During extent scan, it is stored in root->orphan_data_extent.
124  * During fs tree scan, it is then moved to inode_rec->orphan_data_extents.
125  */
126 struct orphan_data_extent {
127         struct list_head list;
128         u64 root;
129         u64 objectid;
130         u64 offset;
131         u64 disk_bytenr;
132         u64 disk_len;
133 };
134
135 struct tree_backref {
136         struct extent_backref node;
137         union {
138                 u64 parent;
139                 u64 root;
140         };
141 };
142
143 static inline struct tree_backref* to_tree_backref(struct extent_backref *back)
144 {
145         return container_of(back, struct tree_backref, node);
146 }
147
148 /* Explicit initialization for extent_record::flag_block_full_backref */
149 enum { FLAG_UNSET = 2 };
150
151 struct extent_record {
152         struct list_head backrefs;
153         struct list_head dups;
154         struct list_head list;
155         struct cache_extent cache;
156         struct btrfs_disk_key parent_key;
157         u64 start;
158         u64 max_size;
159         u64 nr;
160         u64 refs;
161         u64 extent_item_refs;
162         u64 generation;
163         u64 parent_generation;
164         u64 info_objectid;
165         u32 num_duplicates;
166         u8 info_level;
167         unsigned int flag_block_full_backref:2;
168         unsigned int found_rec:1;
169         unsigned int content_checked:1;
170         unsigned int owner_ref_checked:1;
171         unsigned int is_root:1;
172         unsigned int metadata:1;
173         unsigned int bad_full_backref:1;
174         unsigned int crossing_stripes:1;
175         unsigned int wrong_chunk_type:1;
176 };
177
178 static inline struct extent_record* to_extent_record(struct list_head *entry)
179 {
180         return container_of(entry, struct extent_record, list);
181 }
182
183 struct inode_backref {
184         struct list_head list;
185         unsigned int found_dir_item:1;
186         unsigned int found_dir_index:1;
187         unsigned int found_inode_ref:1;
188         u8 filetype;
189         u8 ref_type;
190         int errors;
191         u64 dir;
192         u64 index;
193         u16 namelen;
194         char name[0];
195 };
196
197 static inline struct inode_backref* to_inode_backref(struct list_head *entry)
198 {
199         return list_entry(entry, struct inode_backref, list);
200 }
201
202 struct root_item_record {
203         struct list_head list;
204         u64 objectid;
205         u64 bytenr;
206         u64 last_snapshot;
207         u8 level;
208         u8 drop_level;
209         int level_size;
210         struct btrfs_key drop_key;
211 };
212
213 #define REF_ERR_NO_DIR_ITEM             (1 << 0)
214 #define REF_ERR_NO_DIR_INDEX            (1 << 1)
215 #define REF_ERR_NO_INODE_REF            (1 << 2)
216 #define REF_ERR_DUP_DIR_ITEM            (1 << 3)
217 #define REF_ERR_DUP_DIR_INDEX           (1 << 4)
218 #define REF_ERR_DUP_INODE_REF           (1 << 5)
219 #define REF_ERR_INDEX_UNMATCH           (1 << 6)
220 #define REF_ERR_FILETYPE_UNMATCH        (1 << 7)
221 #define REF_ERR_NAME_TOO_LONG           (1 << 8) // 100
222 #define REF_ERR_NO_ROOT_REF             (1 << 9)
223 #define REF_ERR_NO_ROOT_BACKREF         (1 << 10)
224 #define REF_ERR_DUP_ROOT_REF            (1 << 11)
225 #define REF_ERR_DUP_ROOT_BACKREF        (1 << 12)
226
227 struct file_extent_hole {
228         struct rb_node node;
229         u64 start;
230         u64 len;
231 };
232
233 struct inode_record {
234         struct list_head backrefs;
235         unsigned int checked:1;
236         unsigned int merging:1;
237         unsigned int found_inode_item:1;
238         unsigned int found_dir_item:1;
239         unsigned int found_file_extent:1;
240         unsigned int found_csum_item:1;
241         unsigned int some_csum_missing:1;
242         unsigned int nodatasum:1;
243         int errors;
244
245         u64 ino;
246         u32 nlink;
247         u32 imode;
248         u64 isize;
249         u64 nbytes;
250
251         u32 found_link;
252         u64 found_size;
253         u64 extent_start;
254         u64 extent_end;
255         struct rb_root holes;
256         struct list_head orphan_extents;
257
258         u32 refs;
259 };
260
261 #define I_ERR_NO_INODE_ITEM             (1 << 0)
262 #define I_ERR_NO_ORPHAN_ITEM            (1 << 1)
263 #define I_ERR_DUP_INODE_ITEM            (1 << 2)
264 #define I_ERR_DUP_DIR_INDEX             (1 << 3)
265 #define I_ERR_ODD_DIR_ITEM              (1 << 4)
266 #define I_ERR_ODD_FILE_EXTENT           (1 << 5)
267 #define I_ERR_BAD_FILE_EXTENT           (1 << 6)
268 #define I_ERR_FILE_EXTENT_OVERLAP       (1 << 7)
269 #define I_ERR_FILE_EXTENT_DISCOUNT      (1 << 8) // 100
270 #define I_ERR_DIR_ISIZE_WRONG           (1 << 9)
271 #define I_ERR_FILE_NBYTES_WRONG         (1 << 10) // 400
272 #define I_ERR_ODD_CSUM_ITEM             (1 << 11)
273 #define I_ERR_SOME_CSUM_MISSING         (1 << 12)
274 #define I_ERR_LINK_COUNT_WRONG          (1 << 13)
275 #define I_ERR_FILE_EXTENT_ORPHAN        (1 << 14)
276
277 struct root_backref {
278         struct list_head list;
279         unsigned int found_dir_item:1;
280         unsigned int found_dir_index:1;
281         unsigned int found_back_ref:1;
282         unsigned int found_forward_ref:1;
283         unsigned int reachable:1;
284         int errors;
285         u64 ref_root;
286         u64 dir;
287         u64 index;
288         u16 namelen;
289         char name[0];
290 };
291
292 static inline struct root_backref* to_root_backref(struct list_head *entry)
293 {
294         return list_entry(entry, struct root_backref, list);
295 }
296
297 struct root_record {
298         struct list_head backrefs;
299         struct cache_extent cache;
300         unsigned int found_root_item:1;
301         u64 objectid;
302         u32 found_ref;
303 };
304
305 struct ptr_node {
306         struct cache_extent cache;
307         void *data;
308 };
309
310 struct shared_node {
311         struct cache_extent cache;
312         struct cache_tree root_cache;
313         struct cache_tree inode_cache;
314         struct inode_record *current;
315         u32 refs;
316 };
317
318 struct block_info {
319         u64 start;
320         u32 size;
321 };
322
323 struct walk_control {
324         struct cache_tree shared;
325         struct shared_node *nodes[BTRFS_MAX_LEVEL];
326         int active_node;
327         int root_level;
328 };
329
330 struct bad_item {
331         struct btrfs_key key;
332         u64 root_id;
333         struct list_head list;
334 };
335
336 struct extent_entry {
337         u64 bytenr;
338         u64 bytes;
339         int count;
340         int broken;
341         struct list_head list;
342 };
343
344 struct root_item_info {
345         /* level of the root */
346         u8 level;
347         /* number of nodes at this level, must be 1 for a root */
348         int node_count;
349         u64 bytenr;
350         u64 gen;
351         struct cache_extent cache_extent;
352 };
353
354 /*
355  * Error bit for low memory mode check.
356  *
357  * Currently no caller cares about it yet.  Just internal use for error
358  * classification.
359  */
360 #define BACKREF_MISSING         (1 << 0) /* Backref missing in extent tree */
361 #define BACKREF_MISMATCH        (1 << 1) /* Backref exists but does not match */
362 #define BYTES_UNALIGNED         (1 << 2) /* Some bytes are not aligned */
363 #define REFERENCER_MISSING      (1 << 3) /* Referencer not found */
364 #define REFERENCER_MISMATCH     (1 << 4) /* Referenceer found but does not match */
365 #define CROSSING_STRIPE_BOUNDARY (1 << 4) /* For kernel scrub workaround */
366 #define ITEM_SIZE_MISMATCH      (1 << 5) /* Bad item size */
367 #define UNKNOWN_TYPE            (1 << 6) /* Unknown type */
368 #define ACCOUNTING_MISMATCH     (1 << 7) /* Used space accounting error */
369 #define CHUNK_TYPE_MISMATCH     (1 << 8)
370
371 static void *print_status_check(void *p)
372 {
373         struct task_ctx *priv = p;
374         const char work_indicator[] = { '.', 'o', 'O', 'o' };
375         uint32_t count = 0;
376         static char *task_position_string[] = {
377                 "checking extents",
378                 "checking free space cache",
379                 "checking fs roots",
380         };
381
382         task_period_start(priv->info, 1000 /* 1s */);
383
384         if (priv->tp == TASK_NOTHING)
385                 return NULL;
386
387         while (1) {
388                 printf("%s [%c]\r", task_position_string[priv->tp],
389                                 work_indicator[count % 4]);
390                 count++;
391                 fflush(stdout);
392                 task_period_wait(priv->info);
393         }
394         return NULL;
395 }
396
397 static int print_status_return(void *p)
398 {
399         printf("\n");
400         fflush(stdout);
401
402         return 0;
403 }
404
405 static enum btrfs_check_mode parse_check_mode(const char *str)
406 {
407         if (strcmp(str, "lowmem") == 0)
408                 return CHECK_MODE_LOWMEM;
409         if (strcmp(str, "orig") == 0)
410                 return CHECK_MODE_ORIGINAL;
411         if (strcmp(str, "original") == 0)
412                 return CHECK_MODE_ORIGINAL;
413
414         return CHECK_MODE_UNKNOWN;
415 }
416
417 /* Compatible function to allow reuse of old codes */
418 static u64 first_extent_gap(struct rb_root *holes)
419 {
420         struct file_extent_hole *hole;
421
422         if (RB_EMPTY_ROOT(holes))
423                 return (u64)-1;
424
425         hole = rb_entry(rb_first(holes), struct file_extent_hole, node);
426         return hole->start;
427 }
428
429 static int compare_hole(struct rb_node *node1, struct rb_node *node2)
430 {
431         struct file_extent_hole *hole1;
432         struct file_extent_hole *hole2;
433
434         hole1 = rb_entry(node1, struct file_extent_hole, node);
435         hole2 = rb_entry(node2, struct file_extent_hole, node);
436
437         if (hole1->start > hole2->start)
438                 return -1;
439         if (hole1->start < hole2->start)
440                 return 1;
441         /* Now hole1->start == hole2->start */
442         if (hole1->len >= hole2->len)
443                 /*
444                  * Hole 1 will be merge center
445                  * Same hole will be merged later
446                  */
447                 return -1;
448         /* Hole 2 will be merge center */
449         return 1;
450 }
451
452 /*
453  * Add a hole to the record
454  *
455  * This will do hole merge for copy_file_extent_holes(),
456  * which will ensure there won't be continuous holes.
457  */
458 static int add_file_extent_hole(struct rb_root *holes,
459                                 u64 start, u64 len)
460 {
461         struct file_extent_hole *hole;
462         struct file_extent_hole *prev = NULL;
463         struct file_extent_hole *next = NULL;
464
465         hole = malloc(sizeof(*hole));
466         if (!hole)
467                 return -ENOMEM;
468         hole->start = start;
469         hole->len = len;
470         /* Since compare will not return 0, no -EEXIST will happen */
471         rb_insert(holes, &hole->node, compare_hole);
472
473         /* simple merge with previous hole */
474         if (rb_prev(&hole->node))
475                 prev = rb_entry(rb_prev(&hole->node), struct file_extent_hole,
476                                 node);
477         if (prev && prev->start + prev->len >= hole->start) {
478                 hole->len = hole->start + hole->len - prev->start;
479                 hole->start = prev->start;
480                 rb_erase(&prev->node, holes);
481                 free(prev);
482                 prev = NULL;
483         }
484
485         /* iterate merge with next holes */
486         while (1) {
487                 if (!rb_next(&hole->node))
488                         break;
489                 next = rb_entry(rb_next(&hole->node), struct file_extent_hole,
490                                         node);
491                 if (hole->start + hole->len >= next->start) {
492                         if (hole->start + hole->len <= next->start + next->len)
493                                 hole->len = next->start + next->len -
494                                             hole->start;
495                         rb_erase(&next->node, holes);
496                         free(next);
497                         next = NULL;
498                 } else
499                         break;
500         }
501         return 0;
502 }
503
504 static int compare_hole_range(struct rb_node *node, void *data)
505 {
506         struct file_extent_hole *hole;
507         u64 start;
508
509         hole = (struct file_extent_hole *)data;
510         start = hole->start;
511
512         hole = rb_entry(node, struct file_extent_hole, node);
513         if (start < hole->start)
514                 return -1;
515         if (start >= hole->start && start < hole->start + hole->len)
516                 return 0;
517         return 1;
518 }
519
520 /*
521  * Delete a hole in the record
522  *
523  * This will do the hole split and is much restrict than add.
524  */
525 static int del_file_extent_hole(struct rb_root *holes,
526                                 u64 start, u64 len)
527 {
528         struct file_extent_hole *hole;
529         struct file_extent_hole tmp;
530         u64 prev_start = 0;
531         u64 prev_len = 0;
532         u64 next_start = 0;
533         u64 next_len = 0;
534         struct rb_node *node;
535         int have_prev = 0;
536         int have_next = 0;
537         int ret = 0;
538
539         tmp.start = start;
540         tmp.len = len;
541         node = rb_search(holes, &tmp, compare_hole_range, NULL);
542         if (!node)
543                 return -EEXIST;
544         hole = rb_entry(node, struct file_extent_hole, node);
545         if (start + len > hole->start + hole->len)
546                 return -EEXIST;
547
548         /*
549          * Now there will be no overlap, delete the hole and re-add the
550          * split(s) if they exists.
551          */
552         if (start > hole->start) {
553                 prev_start = hole->start;
554                 prev_len = start - hole->start;
555                 have_prev = 1;
556         }
557         if (hole->start + hole->len > start + len) {
558                 next_start = start + len;
559                 next_len = hole->start + hole->len - start - len;
560                 have_next = 1;
561         }
562         rb_erase(node, holes);
563         free(hole);
564         if (have_prev) {
565                 ret = add_file_extent_hole(holes, prev_start, prev_len);
566                 if (ret < 0)
567                         return ret;
568         }
569         if (have_next) {
570                 ret = add_file_extent_hole(holes, next_start, next_len);
571                 if (ret < 0)
572                         return ret;
573         }
574         return 0;
575 }
576
577 static int copy_file_extent_holes(struct rb_root *dst,
578                                   struct rb_root *src)
579 {
580         struct file_extent_hole *hole;
581         struct rb_node *node;
582         int ret = 0;
583
584         node = rb_first(src);
585         while (node) {
586                 hole = rb_entry(node, struct file_extent_hole, node);
587                 ret = add_file_extent_hole(dst, hole->start, hole->len);
588                 if (ret)
589                         break;
590                 node = rb_next(node);
591         }
592         return ret;
593 }
594
595 static void free_file_extent_holes(struct rb_root *holes)
596 {
597         struct rb_node *node;
598         struct file_extent_hole *hole;
599
600         node = rb_first(holes);
601         while (node) {
602                 hole = rb_entry(node, struct file_extent_hole, node);
603                 rb_erase(node, holes);
604                 free(hole);
605                 node = rb_first(holes);
606         }
607 }
608
609 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
610
611 static void record_root_in_trans(struct btrfs_trans_handle *trans,
612                                  struct btrfs_root *root)
613 {
614         if (root->last_trans != trans->transid) {
615                 root->track_dirty = 1;
616                 root->last_trans = trans->transid;
617                 root->commit_root = root->node;
618                 extent_buffer_get(root->node);
619         }
620 }
621
622 static u8 imode_to_type(u32 imode)
623 {
624 #define S_SHIFT 12
625         static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
626                 [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
627                 [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
628                 [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
629                 [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
630                 [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
631                 [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
632                 [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
633         };
634
635         return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
636 #undef S_SHIFT
637 }
638
639 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
640 {
641         struct device_record *rec1;
642         struct device_record *rec2;
643
644         rec1 = rb_entry(node1, struct device_record, node);
645         rec2 = rb_entry(node2, struct device_record, node);
646         if (rec1->devid > rec2->devid)
647                 return -1;
648         else if (rec1->devid < rec2->devid)
649                 return 1;
650         else
651                 return 0;
652 }
653
654 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
655 {
656         struct inode_record *rec;
657         struct inode_backref *backref;
658         struct inode_backref *orig;
659         struct inode_backref *tmp;
660         struct orphan_data_extent *src_orphan;
661         struct orphan_data_extent *dst_orphan;
662         struct rb_node *rb;
663         size_t size;
664         int ret;
665
666         rec = malloc(sizeof(*rec));
667         if (!rec)
668                 return ERR_PTR(-ENOMEM);
669         memcpy(rec, orig_rec, sizeof(*rec));
670         rec->refs = 1;
671         INIT_LIST_HEAD(&rec->backrefs);
672         INIT_LIST_HEAD(&rec->orphan_extents);
673         rec->holes = RB_ROOT;
674
675         list_for_each_entry(orig, &orig_rec->backrefs, list) {
676                 size = sizeof(*orig) + orig->namelen + 1;
677                 backref = malloc(size);
678                 if (!backref) {
679                         ret = -ENOMEM;
680                         goto cleanup;
681                 }
682                 memcpy(backref, orig, size);
683                 list_add_tail(&backref->list, &rec->backrefs);
684         }
685         list_for_each_entry(src_orphan, &orig_rec->orphan_extents, list) {
686                 dst_orphan = malloc(sizeof(*dst_orphan));
687                 if (!dst_orphan) {
688                         ret = -ENOMEM;
689                         goto cleanup;
690                 }
691                 memcpy(dst_orphan, src_orphan, sizeof(*src_orphan));
692                 list_add_tail(&dst_orphan->list, &rec->orphan_extents);
693         }
694         ret = copy_file_extent_holes(&rec->holes, &orig_rec->holes);
695         if (ret < 0)
696                 goto cleanup_rb;
697
698         return rec;
699
700 cleanup_rb:
701         rb = rb_first(&rec->holes);
702         while (rb) {
703                 struct file_extent_hole *hole;
704
705                 hole = rb_entry(rb, struct file_extent_hole, node);
706                 rb = rb_next(rb);
707                 free(hole);
708         }
709
710 cleanup:
711         if (!list_empty(&rec->backrefs))
712                 list_for_each_entry_safe(orig, tmp, &rec->backrefs, list) {
713                         list_del(&orig->list);
714                         free(orig);
715                 }
716
717         if (!list_empty(&rec->orphan_extents))
718                 list_for_each_entry_safe(orig, tmp, &rec->orphan_extents, list) {
719                         list_del(&orig->list);
720                         free(orig);
721                 }
722
723         free(rec);
724
725         return ERR_PTR(ret);
726 }
727
728 static void print_orphan_data_extents(struct list_head *orphan_extents,
729                                       u64 objectid)
730 {
731         struct orphan_data_extent *orphan;
732
733         if (list_empty(orphan_extents))
734                 return;
735         printf("The following data extent is lost in tree %llu:\n",
736                objectid);
737         list_for_each_entry(orphan, orphan_extents, list) {
738                 printf("\tinode: %llu, offset:%llu, disk_bytenr: %llu, disk_len: %llu\n",
739                        orphan->objectid, orphan->offset, orphan->disk_bytenr,
740                        orphan->disk_len);
741         }
742 }
743
744 static void print_inode_error(struct btrfs_root *root, struct inode_record *rec)
745 {
746         u64 root_objectid = root->root_key.objectid;
747         int errors = rec->errors;
748
749         if (!errors)
750                 return;
751         /* reloc root errors, we print its corresponding fs root objectid*/
752         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
753                 root_objectid = root->root_key.offset;
754                 fprintf(stderr, "reloc");
755         }
756         fprintf(stderr, "root %llu inode %llu errors %x",
757                 (unsigned long long) root_objectid,
758                 (unsigned long long) rec->ino, rec->errors);
759
760         if (errors & I_ERR_NO_INODE_ITEM)
761                 fprintf(stderr, ", no inode item");
762         if (errors & I_ERR_NO_ORPHAN_ITEM)
763                 fprintf(stderr, ", no orphan item");
764         if (errors & I_ERR_DUP_INODE_ITEM)
765                 fprintf(stderr, ", dup inode item");
766         if (errors & I_ERR_DUP_DIR_INDEX)
767                 fprintf(stderr, ", dup dir index");
768         if (errors & I_ERR_ODD_DIR_ITEM)
769                 fprintf(stderr, ", odd dir item");
770         if (errors & I_ERR_ODD_FILE_EXTENT)
771                 fprintf(stderr, ", odd file extent");
772         if (errors & I_ERR_BAD_FILE_EXTENT)
773                 fprintf(stderr, ", bad file extent");
774         if (errors & I_ERR_FILE_EXTENT_OVERLAP)
775                 fprintf(stderr, ", file extent overlap");
776         if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
777                 fprintf(stderr, ", file extent discount");
778         if (errors & I_ERR_DIR_ISIZE_WRONG)
779                 fprintf(stderr, ", dir isize wrong");
780         if (errors & I_ERR_FILE_NBYTES_WRONG)
781                 fprintf(stderr, ", nbytes wrong");
782         if (errors & I_ERR_ODD_CSUM_ITEM)
783                 fprintf(stderr, ", odd csum item");
784         if (errors & I_ERR_SOME_CSUM_MISSING)
785                 fprintf(stderr, ", some csum missing");
786         if (errors & I_ERR_LINK_COUNT_WRONG)
787                 fprintf(stderr, ", link count wrong");
788         if (errors & I_ERR_FILE_EXTENT_ORPHAN)
789                 fprintf(stderr, ", orphan file extent");
790         fprintf(stderr, "\n");
791         /* Print the orphan extents if needed */
792         if (errors & I_ERR_FILE_EXTENT_ORPHAN)
793                 print_orphan_data_extents(&rec->orphan_extents, root->objectid);
794
795         /* Print the holes if needed */
796         if (errors & I_ERR_FILE_EXTENT_DISCOUNT) {
797                 struct file_extent_hole *hole;
798                 struct rb_node *node;
799                 int found = 0;
800
801                 node = rb_first(&rec->holes);
802                 fprintf(stderr, "Found file extent holes:\n");
803                 while (node) {
804                         found = 1;
805                         hole = rb_entry(node, struct file_extent_hole, node);
806                         fprintf(stderr, "\tstart: %llu, len: %llu\n",
807                                 hole->start, hole->len);
808                         node = rb_next(node);
809                 }
810                 if (!found)
811                         fprintf(stderr, "\tstart: 0, len: %llu\n",
812                                 round_up(rec->isize, root->sectorsize));
813         }
814 }
815
816 static void print_ref_error(int errors)
817 {
818         if (errors & REF_ERR_NO_DIR_ITEM)
819                 fprintf(stderr, ", no dir item");
820         if (errors & REF_ERR_NO_DIR_INDEX)
821                 fprintf(stderr, ", no dir index");
822         if (errors & REF_ERR_NO_INODE_REF)
823                 fprintf(stderr, ", no inode ref");
824         if (errors & REF_ERR_DUP_DIR_ITEM)
825                 fprintf(stderr, ", dup dir item");
826         if (errors & REF_ERR_DUP_DIR_INDEX)
827                 fprintf(stderr, ", dup dir index");
828         if (errors & REF_ERR_DUP_INODE_REF)
829                 fprintf(stderr, ", dup inode ref");
830         if (errors & REF_ERR_INDEX_UNMATCH)
831                 fprintf(stderr, ", index mismatch");
832         if (errors & REF_ERR_FILETYPE_UNMATCH)
833                 fprintf(stderr, ", filetype mismatch");
834         if (errors & REF_ERR_NAME_TOO_LONG)
835                 fprintf(stderr, ", name too long");
836         if (errors & REF_ERR_NO_ROOT_REF)
837                 fprintf(stderr, ", no root ref");
838         if (errors & REF_ERR_NO_ROOT_BACKREF)
839                 fprintf(stderr, ", no root backref");
840         if (errors & REF_ERR_DUP_ROOT_REF)
841                 fprintf(stderr, ", dup root ref");
842         if (errors & REF_ERR_DUP_ROOT_BACKREF)
843                 fprintf(stderr, ", dup root backref");
844         fprintf(stderr, "\n");
845 }
846
847 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
848                                           u64 ino, int mod)
849 {
850         struct ptr_node *node;
851         struct cache_extent *cache;
852         struct inode_record *rec = NULL;
853         int ret;
854
855         cache = lookup_cache_extent(inode_cache, ino, 1);
856         if (cache) {
857                 node = container_of(cache, struct ptr_node, cache);
858                 rec = node->data;
859                 if (mod && rec->refs > 1) {
860                         node->data = clone_inode_rec(rec);
861                         if (IS_ERR(node->data))
862                                 return node->data;
863                         rec->refs--;
864                         rec = node->data;
865                 }
866         } else if (mod) {
867                 rec = calloc(1, sizeof(*rec));
868                 if (!rec)
869                         return ERR_PTR(-ENOMEM);
870                 rec->ino = ino;
871                 rec->extent_start = (u64)-1;
872                 rec->refs = 1;
873                 INIT_LIST_HEAD(&rec->backrefs);
874                 INIT_LIST_HEAD(&rec->orphan_extents);
875                 rec->holes = RB_ROOT;
876
877                 node = malloc(sizeof(*node));
878                 if (!node) {
879                         free(rec);
880                         return ERR_PTR(-ENOMEM);
881                 }
882                 node->cache.start = ino;
883                 node->cache.size = 1;
884                 node->data = rec;
885
886                 if (ino == BTRFS_FREE_INO_OBJECTID)
887                         rec->found_link = 1;
888
889                 ret = insert_cache_extent(inode_cache, &node->cache);
890                 if (ret)
891                         return ERR_PTR(-EEXIST);
892         }
893         return rec;
894 }
895
896 static void free_orphan_data_extents(struct list_head *orphan_extents)
897 {
898         struct orphan_data_extent *orphan;
899
900         while (!list_empty(orphan_extents)) {
901                 orphan = list_entry(orphan_extents->next,
902                                     struct orphan_data_extent, list);
903                 list_del(&orphan->list);
904                 free(orphan);
905         }
906 }
907
908 static void free_inode_rec(struct inode_record *rec)
909 {
910         struct inode_backref *backref;
911
912         if (--rec->refs > 0)
913                 return;
914
915         while (!list_empty(&rec->backrefs)) {
916                 backref = to_inode_backref(rec->backrefs.next);
917                 list_del(&backref->list);
918                 free(backref);
919         }
920         free_orphan_data_extents(&rec->orphan_extents);
921         free_file_extent_holes(&rec->holes);
922         free(rec);
923 }
924
925 static int can_free_inode_rec(struct inode_record *rec)
926 {
927         if (!rec->errors && rec->checked && rec->found_inode_item &&
928             rec->nlink == rec->found_link && list_empty(&rec->backrefs))
929                 return 1;
930         return 0;
931 }
932
933 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
934                                  struct inode_record *rec)
935 {
936         struct cache_extent *cache;
937         struct inode_backref *tmp, *backref;
938         struct ptr_node *node;
939         u8 filetype;
940
941         if (!rec->found_inode_item)
942                 return;
943
944         filetype = imode_to_type(rec->imode);
945         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
946                 if (backref->found_dir_item && backref->found_dir_index) {
947                         if (backref->filetype != filetype)
948                                 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
949                         if (!backref->errors && backref->found_inode_ref &&
950                             rec->nlink == rec->found_link) {
951                                 list_del(&backref->list);
952                                 free(backref);
953                         }
954                 }
955         }
956
957         if (!rec->checked || rec->merging)
958                 return;
959
960         if (S_ISDIR(rec->imode)) {
961                 if (rec->found_size != rec->isize)
962                         rec->errors |= I_ERR_DIR_ISIZE_WRONG;
963                 if (rec->found_file_extent)
964                         rec->errors |= I_ERR_ODD_FILE_EXTENT;
965         } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
966                 if (rec->found_dir_item)
967                         rec->errors |= I_ERR_ODD_DIR_ITEM;
968                 if (rec->found_size != rec->nbytes)
969                         rec->errors |= I_ERR_FILE_NBYTES_WRONG;
970                 if (rec->nlink > 0 && !no_holes &&
971                     (rec->extent_end < rec->isize ||
972                      first_extent_gap(&rec->holes) < rec->isize))
973                         rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
974         }
975
976         if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
977                 if (rec->found_csum_item && rec->nodatasum)
978                         rec->errors |= I_ERR_ODD_CSUM_ITEM;
979                 if (rec->some_csum_missing && !rec->nodatasum)
980                         rec->errors |= I_ERR_SOME_CSUM_MISSING;
981         }
982
983         BUG_ON(rec->refs != 1);
984         if (can_free_inode_rec(rec)) {
985                 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
986                 node = container_of(cache, struct ptr_node, cache);
987                 BUG_ON(node->data != rec);
988                 remove_cache_extent(inode_cache, &node->cache);
989                 free(node);
990                 free_inode_rec(rec);
991         }
992 }
993
994 static int check_orphan_item(struct btrfs_root *root, u64 ino)
995 {
996         struct btrfs_path path;
997         struct btrfs_key key;
998         int ret;
999
1000         key.objectid = BTRFS_ORPHAN_OBJECTID;
1001         key.type = BTRFS_ORPHAN_ITEM_KEY;
1002         key.offset = ino;
1003
1004         btrfs_init_path(&path);
1005         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1006         btrfs_release_path(&path);
1007         if (ret > 0)
1008                 ret = -ENOENT;
1009         return ret;
1010 }
1011
1012 static int process_inode_item(struct extent_buffer *eb,
1013                               int slot, struct btrfs_key *key,
1014                               struct shared_node *active_node)
1015 {
1016         struct inode_record *rec;
1017         struct btrfs_inode_item *item;
1018
1019         rec = active_node->current;
1020         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1021         if (rec->found_inode_item) {
1022                 rec->errors |= I_ERR_DUP_INODE_ITEM;
1023                 return 1;
1024         }
1025         item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
1026         rec->nlink = btrfs_inode_nlink(eb, item);
1027         rec->isize = btrfs_inode_size(eb, item);
1028         rec->nbytes = btrfs_inode_nbytes(eb, item);
1029         rec->imode = btrfs_inode_mode(eb, item);
1030         if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
1031                 rec->nodatasum = 1;
1032         rec->found_inode_item = 1;
1033         if (rec->nlink == 0)
1034                 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
1035         maybe_free_inode_rec(&active_node->inode_cache, rec);
1036         return 0;
1037 }
1038
1039 static struct inode_backref *get_inode_backref(struct inode_record *rec,
1040                                                 const char *name,
1041                                                 int namelen, u64 dir)
1042 {
1043         struct inode_backref *backref;
1044
1045         list_for_each_entry(backref, &rec->backrefs, list) {
1046                 if (rec->ino == BTRFS_MULTIPLE_OBJECTIDS)
1047                         break;
1048                 if (backref->dir != dir || backref->namelen != namelen)
1049                         continue;
1050                 if (memcmp(name, backref->name, namelen))
1051                         continue;
1052                 return backref;
1053         }
1054
1055         backref = malloc(sizeof(*backref) + namelen + 1);
1056         if (!backref)
1057                 return NULL;
1058         memset(backref, 0, sizeof(*backref));
1059         backref->dir = dir;
1060         backref->namelen = namelen;
1061         memcpy(backref->name, name, namelen);
1062         backref->name[namelen] = '\0';
1063         list_add_tail(&backref->list, &rec->backrefs);
1064         return backref;
1065 }
1066
1067 static int add_inode_backref(struct cache_tree *inode_cache,
1068                              u64 ino, u64 dir, u64 index,
1069                              const char *name, int namelen,
1070                              u8 filetype, u8 itemtype, int errors)
1071 {
1072         struct inode_record *rec;
1073         struct inode_backref *backref;
1074
1075         rec = get_inode_rec(inode_cache, ino, 1);
1076         BUG_ON(IS_ERR(rec));
1077         backref = get_inode_backref(rec, name, namelen, dir);
1078         BUG_ON(!backref);
1079         if (errors)
1080                 backref->errors |= errors;
1081         if (itemtype == BTRFS_DIR_INDEX_KEY) {
1082                 if (backref->found_dir_index)
1083                         backref->errors |= REF_ERR_DUP_DIR_INDEX;
1084                 if (backref->found_inode_ref && backref->index != index)
1085                         backref->errors |= REF_ERR_INDEX_UNMATCH;
1086                 if (backref->found_dir_item && backref->filetype != filetype)
1087                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
1088
1089                 backref->index = index;
1090                 backref->filetype = filetype;
1091                 backref->found_dir_index = 1;
1092         } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
1093                 rec->found_link++;
1094                 if (backref->found_dir_item)
1095                         backref->errors |= REF_ERR_DUP_DIR_ITEM;
1096                 if (backref->found_dir_index && backref->filetype != filetype)
1097                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
1098
1099                 backref->filetype = filetype;
1100                 backref->found_dir_item = 1;
1101         } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
1102                    (itemtype == BTRFS_INODE_EXTREF_KEY)) {
1103                 if (backref->found_inode_ref)
1104                         backref->errors |= REF_ERR_DUP_INODE_REF;
1105                 if (backref->found_dir_index && backref->index != index)
1106                         backref->errors |= REF_ERR_INDEX_UNMATCH;
1107                 else
1108                         backref->index = index;
1109
1110                 backref->ref_type = itemtype;
1111                 backref->found_inode_ref = 1;
1112         } else {
1113                 BUG_ON(1);
1114         }
1115
1116         maybe_free_inode_rec(inode_cache, rec);
1117         return 0;
1118 }
1119
1120 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
1121                             struct cache_tree *dst_cache)
1122 {
1123         struct inode_backref *backref;
1124         u32 dir_count = 0;
1125         int ret = 0;
1126
1127         dst->merging = 1;
1128         list_for_each_entry(backref, &src->backrefs, list) {
1129                 if (backref->found_dir_index) {
1130                         add_inode_backref(dst_cache, dst->ino, backref->dir,
1131                                         backref->index, backref->name,
1132                                         backref->namelen, backref->filetype,
1133                                         BTRFS_DIR_INDEX_KEY, backref->errors);
1134                 }
1135                 if (backref->found_dir_item) {
1136                         dir_count++;
1137                         add_inode_backref(dst_cache, dst->ino,
1138                                         backref->dir, 0, backref->name,
1139                                         backref->namelen, backref->filetype,
1140                                         BTRFS_DIR_ITEM_KEY, backref->errors);
1141                 }
1142                 if (backref->found_inode_ref) {
1143                         add_inode_backref(dst_cache, dst->ino,
1144                                         backref->dir, backref->index,
1145                                         backref->name, backref->namelen, 0,
1146                                         backref->ref_type, backref->errors);
1147                 }
1148         }
1149
1150         if (src->found_dir_item)
1151                 dst->found_dir_item = 1;
1152         if (src->found_file_extent)
1153                 dst->found_file_extent = 1;
1154         if (src->found_csum_item)
1155                 dst->found_csum_item = 1;
1156         if (src->some_csum_missing)
1157                 dst->some_csum_missing = 1;
1158         if (first_extent_gap(&dst->holes) > first_extent_gap(&src->holes)) {
1159                 ret = copy_file_extent_holes(&dst->holes, &src->holes);
1160                 if (ret < 0)
1161                         return ret;
1162         }
1163
1164         BUG_ON(src->found_link < dir_count);
1165         dst->found_link += src->found_link - dir_count;
1166         dst->found_size += src->found_size;
1167         if (src->extent_start != (u64)-1) {
1168                 if (dst->extent_start == (u64)-1) {
1169                         dst->extent_start = src->extent_start;
1170                         dst->extent_end = src->extent_end;
1171                 } else {
1172                         if (dst->extent_end > src->extent_start)
1173                                 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1174                         else if (dst->extent_end < src->extent_start) {
1175                                 ret = add_file_extent_hole(&dst->holes,
1176                                         dst->extent_end,
1177                                         src->extent_start - dst->extent_end);
1178                         }
1179                         if (dst->extent_end < src->extent_end)
1180                                 dst->extent_end = src->extent_end;
1181                 }
1182         }
1183
1184         dst->errors |= src->errors;
1185         if (src->found_inode_item) {
1186                 if (!dst->found_inode_item) {
1187                         dst->nlink = src->nlink;
1188                         dst->isize = src->isize;
1189                         dst->nbytes = src->nbytes;
1190                         dst->imode = src->imode;
1191                         dst->nodatasum = src->nodatasum;
1192                         dst->found_inode_item = 1;
1193                 } else {
1194                         dst->errors |= I_ERR_DUP_INODE_ITEM;
1195                 }
1196         }
1197         dst->merging = 0;
1198
1199         return 0;
1200 }
1201
1202 static int splice_shared_node(struct shared_node *src_node,
1203                               struct shared_node *dst_node)
1204 {
1205         struct cache_extent *cache;
1206         struct ptr_node *node, *ins;
1207         struct cache_tree *src, *dst;
1208         struct inode_record *rec, *conflict;
1209         u64 current_ino = 0;
1210         int splice = 0;
1211         int ret;
1212
1213         if (--src_node->refs == 0)
1214                 splice = 1;
1215         if (src_node->current)
1216                 current_ino = src_node->current->ino;
1217
1218         src = &src_node->root_cache;
1219         dst = &dst_node->root_cache;
1220 again:
1221         cache = search_cache_extent(src, 0);
1222         while (cache) {
1223                 node = container_of(cache, struct ptr_node, cache);
1224                 rec = node->data;
1225                 cache = next_cache_extent(cache);
1226
1227                 if (splice) {
1228                         remove_cache_extent(src, &node->cache);
1229                         ins = node;
1230                 } else {
1231                         ins = malloc(sizeof(*ins));
1232                         BUG_ON(!ins);
1233                         ins->cache.start = node->cache.start;
1234                         ins->cache.size = node->cache.size;
1235                         ins->data = rec;
1236                         rec->refs++;
1237                 }
1238                 ret = insert_cache_extent(dst, &ins->cache);
1239                 if (ret == -EEXIST) {
1240                         conflict = get_inode_rec(dst, rec->ino, 1);
1241                         BUG_ON(IS_ERR(conflict));
1242                         merge_inode_recs(rec, conflict, dst);
1243                         if (rec->checked) {
1244                                 conflict->checked = 1;
1245                                 if (dst_node->current == conflict)
1246                                         dst_node->current = NULL;
1247                         }
1248                         maybe_free_inode_rec(dst, conflict);
1249                         free_inode_rec(rec);
1250                         free(ins);
1251                 } else {
1252                         BUG_ON(ret);
1253                 }
1254         }
1255
1256         if (src == &src_node->root_cache) {
1257                 src = &src_node->inode_cache;
1258                 dst = &dst_node->inode_cache;
1259                 goto again;
1260         }
1261
1262         if (current_ino > 0 && (!dst_node->current ||
1263             current_ino > dst_node->current->ino)) {
1264                 if (dst_node->current) {
1265                         dst_node->current->checked = 1;
1266                         maybe_free_inode_rec(dst, dst_node->current);
1267                 }
1268                 dst_node->current = get_inode_rec(dst, current_ino, 1);
1269                 BUG_ON(IS_ERR(dst_node->current));
1270         }
1271         return 0;
1272 }
1273
1274 static void free_inode_ptr(struct cache_extent *cache)
1275 {
1276         struct ptr_node *node;
1277         struct inode_record *rec;
1278
1279         node = container_of(cache, struct ptr_node, cache);
1280         rec = node->data;
1281         free_inode_rec(rec);
1282         free(node);
1283 }
1284
1285 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
1286
1287 static struct shared_node *find_shared_node(struct cache_tree *shared,
1288                                             u64 bytenr)
1289 {
1290         struct cache_extent *cache;
1291         struct shared_node *node;
1292
1293         cache = lookup_cache_extent(shared, bytenr, 1);
1294         if (cache) {
1295                 node = container_of(cache, struct shared_node, cache);
1296                 return node;
1297         }
1298         return NULL;
1299 }
1300
1301 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
1302 {
1303         int ret;
1304         struct shared_node *node;
1305
1306         node = calloc(1, sizeof(*node));
1307         if (!node)
1308                 return -ENOMEM;
1309         node->cache.start = bytenr;
1310         node->cache.size = 1;
1311         cache_tree_init(&node->root_cache);
1312         cache_tree_init(&node->inode_cache);
1313         node->refs = refs;
1314
1315         ret = insert_cache_extent(shared, &node->cache);
1316
1317         return ret;
1318 }
1319
1320 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
1321                              struct walk_control *wc, int level)
1322 {
1323         struct shared_node *node;
1324         struct shared_node *dest;
1325         int ret;
1326
1327         if (level == wc->active_node)
1328                 return 0;
1329
1330         BUG_ON(wc->active_node <= level);
1331         node = find_shared_node(&wc->shared, bytenr);
1332         if (!node) {
1333                 ret = add_shared_node(&wc->shared, bytenr, refs);
1334                 BUG_ON(ret);
1335                 node = find_shared_node(&wc->shared, bytenr);
1336                 wc->nodes[level] = node;
1337                 wc->active_node = level;
1338                 return 0;
1339         }
1340
1341         if (wc->root_level == wc->active_node &&
1342             btrfs_root_refs(&root->root_item) == 0) {
1343                 if (--node->refs == 0) {
1344                         free_inode_recs_tree(&node->root_cache);
1345                         free_inode_recs_tree(&node->inode_cache);
1346                         remove_cache_extent(&wc->shared, &node->cache);
1347                         free(node);
1348                 }
1349                 return 1;
1350         }
1351
1352         dest = wc->nodes[wc->active_node];
1353         splice_shared_node(node, dest);
1354         if (node->refs == 0) {
1355                 remove_cache_extent(&wc->shared, &node->cache);
1356                 free(node);
1357         }
1358         return 1;
1359 }
1360
1361 static int leave_shared_node(struct btrfs_root *root,
1362                              struct walk_control *wc, int level)
1363 {
1364         struct shared_node *node;
1365         struct shared_node *dest;
1366         int i;
1367
1368         if (level == wc->root_level)
1369                 return 0;
1370
1371         for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
1372                 if (wc->nodes[i])
1373                         break;
1374         }
1375         BUG_ON(i >= BTRFS_MAX_LEVEL);
1376
1377         node = wc->nodes[wc->active_node];
1378         wc->nodes[wc->active_node] = NULL;
1379         wc->active_node = i;
1380
1381         dest = wc->nodes[wc->active_node];
1382         if (wc->active_node < wc->root_level ||
1383             btrfs_root_refs(&root->root_item) > 0) {
1384                 BUG_ON(node->refs <= 1);
1385                 splice_shared_node(node, dest);
1386         } else {
1387                 BUG_ON(node->refs < 2);
1388                 node->refs--;
1389         }
1390         return 0;
1391 }
1392
1393 /*
1394  * Returns:
1395  * < 0 - on error
1396  * 1   - if the root with id child_root_id is a child of root parent_root_id
1397  * 0   - if the root child_root_id isn't a child of the root parent_root_id but
1398  *       has other root(s) as parent(s)
1399  * 2   - if the root child_root_id doesn't have any parent roots
1400  */
1401 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
1402                          u64 child_root_id)
1403 {
1404         struct btrfs_path path;
1405         struct btrfs_key key;
1406         struct extent_buffer *leaf;
1407         int has_parent = 0;
1408         int ret;
1409
1410         btrfs_init_path(&path);
1411
1412         key.objectid = parent_root_id;
1413         key.type = BTRFS_ROOT_REF_KEY;
1414         key.offset = child_root_id;
1415         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1416                                 0, 0);
1417         if (ret < 0)
1418                 return ret;
1419         btrfs_release_path(&path);
1420         if (!ret)
1421                 return 1;
1422
1423         key.objectid = child_root_id;
1424         key.type = BTRFS_ROOT_BACKREF_KEY;
1425         key.offset = 0;
1426         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
1427                                 0, 0);
1428         if (ret < 0)
1429                 goto out;
1430
1431         while (1) {
1432                 leaf = path.nodes[0];
1433                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1434                         ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
1435                         if (ret)
1436                                 break;
1437                         leaf = path.nodes[0];
1438                 }
1439
1440                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1441                 if (key.objectid != child_root_id ||
1442                     key.type != BTRFS_ROOT_BACKREF_KEY)
1443                         break;
1444
1445                 has_parent = 1;
1446
1447                 if (key.offset == parent_root_id) {
1448                         btrfs_release_path(&path);
1449                         return 1;
1450                 }
1451
1452                 path.slots[0]++;
1453         }
1454 out:
1455         btrfs_release_path(&path);
1456         if (ret < 0)
1457                 return ret;
1458         return has_parent ? 0 : 2;
1459 }
1460
1461 static int process_dir_item(struct btrfs_root *root,
1462                             struct extent_buffer *eb,
1463                             int slot, struct btrfs_key *key,
1464                             struct shared_node *active_node)
1465 {
1466         u32 total;
1467         u32 cur = 0;
1468         u32 len;
1469         u32 name_len;
1470         u32 data_len;
1471         int error;
1472         int nritems = 0;
1473         u8 filetype;
1474         struct btrfs_dir_item *di;
1475         struct inode_record *rec;
1476         struct cache_tree *root_cache;
1477         struct cache_tree *inode_cache;
1478         struct btrfs_key location;
1479         char namebuf[BTRFS_NAME_LEN];
1480
1481         root_cache = &active_node->root_cache;
1482         inode_cache = &active_node->inode_cache;
1483         rec = active_node->current;
1484         rec->found_dir_item = 1;
1485
1486         di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1487         total = btrfs_item_size_nr(eb, slot);
1488         while (cur < total) {
1489                 nritems++;
1490                 btrfs_dir_item_key_to_cpu(eb, di, &location);
1491                 name_len = btrfs_dir_name_len(eb, di);
1492                 data_len = btrfs_dir_data_len(eb, di);
1493                 filetype = btrfs_dir_type(eb, di);
1494
1495                 rec->found_size += name_len;
1496                 if (name_len <= BTRFS_NAME_LEN) {
1497                         len = name_len;
1498                         error = 0;
1499                 } else {
1500                         len = BTRFS_NAME_LEN;
1501                         error = REF_ERR_NAME_TOO_LONG;
1502                 }
1503                 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
1504
1505                 if (location.type == BTRFS_INODE_ITEM_KEY) {
1506                         add_inode_backref(inode_cache, location.objectid,
1507                                           key->objectid, key->offset, namebuf,
1508                                           len, filetype, key->type, error);
1509                 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
1510                         add_inode_backref(root_cache, location.objectid,
1511                                           key->objectid, key->offset,
1512                                           namebuf, len, filetype,
1513                                           key->type, error);
1514                 } else {
1515                         fprintf(stderr, "invalid location in dir item %u\n",
1516                                 location.type);
1517                         add_inode_backref(inode_cache, BTRFS_MULTIPLE_OBJECTIDS,
1518                                           key->objectid, key->offset, namebuf,
1519                                           len, filetype, key->type, error);
1520                 }
1521
1522                 len = sizeof(*di) + name_len + data_len;
1523                 di = (struct btrfs_dir_item *)((char *)di + len);
1524                 cur += len;
1525         }
1526         if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
1527                 rec->errors |= I_ERR_DUP_DIR_INDEX;
1528
1529         return 0;
1530 }
1531
1532 static int process_inode_ref(struct extent_buffer *eb,
1533                              int slot, struct btrfs_key *key,
1534                              struct shared_node *active_node)
1535 {
1536         u32 total;
1537         u32 cur = 0;
1538         u32 len;
1539         u32 name_len;
1540         u64 index;
1541         int error;
1542         struct cache_tree *inode_cache;
1543         struct btrfs_inode_ref *ref;
1544         char namebuf[BTRFS_NAME_LEN];
1545
1546         inode_cache = &active_node->inode_cache;
1547
1548         ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1549         total = btrfs_item_size_nr(eb, slot);
1550         while (cur < total) {
1551                 name_len = btrfs_inode_ref_name_len(eb, ref);
1552                 index = btrfs_inode_ref_index(eb, ref);
1553                 if (name_len <= BTRFS_NAME_LEN) {
1554                         len = name_len;
1555                         error = 0;
1556                 } else {
1557                         len = BTRFS_NAME_LEN;
1558                         error = REF_ERR_NAME_TOO_LONG;
1559                 }
1560                 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1561                 add_inode_backref(inode_cache, key->objectid, key->offset,
1562                                   index, namebuf, len, 0, key->type, error);
1563
1564                 len = sizeof(*ref) + name_len;
1565                 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1566                 cur += len;
1567         }
1568         return 0;
1569 }
1570
1571 static int process_inode_extref(struct extent_buffer *eb,
1572                                 int slot, struct btrfs_key *key,
1573                                 struct shared_node *active_node)
1574 {
1575         u32 total;
1576         u32 cur = 0;
1577         u32 len;
1578         u32 name_len;
1579         u64 index;
1580         u64 parent;
1581         int error;
1582         struct cache_tree *inode_cache;
1583         struct btrfs_inode_extref *extref;
1584         char namebuf[BTRFS_NAME_LEN];
1585
1586         inode_cache = &active_node->inode_cache;
1587
1588         extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1589         total = btrfs_item_size_nr(eb, slot);
1590         while (cur < total) {
1591                 name_len = btrfs_inode_extref_name_len(eb, extref);
1592                 index = btrfs_inode_extref_index(eb, extref);
1593                 parent = btrfs_inode_extref_parent(eb, extref);
1594                 if (name_len <= BTRFS_NAME_LEN) {
1595                         len = name_len;
1596                         error = 0;
1597                 } else {
1598                         len = BTRFS_NAME_LEN;
1599                         error = REF_ERR_NAME_TOO_LONG;
1600                 }
1601                 read_extent_buffer(eb, namebuf,
1602                                    (unsigned long)(extref + 1), len);
1603                 add_inode_backref(inode_cache, key->objectid, parent,
1604                                   index, namebuf, len, 0, key->type, error);
1605
1606                 len = sizeof(*extref) + name_len;
1607                 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1608                 cur += len;
1609         }
1610         return 0;
1611
1612 }
1613
1614 static int count_csum_range(struct btrfs_root *root, u64 start,
1615                             u64 len, u64 *found)
1616 {
1617         struct btrfs_key key;
1618         struct btrfs_path path;
1619         struct extent_buffer *leaf;
1620         int ret;
1621         size_t size;
1622         *found = 0;
1623         u64 csum_end;
1624         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1625
1626         btrfs_init_path(&path);
1627
1628         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1629         key.offset = start;
1630         key.type = BTRFS_EXTENT_CSUM_KEY;
1631
1632         ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1633                                 &key, &path, 0, 0);
1634         if (ret < 0)
1635                 goto out;
1636         if (ret > 0 && path.slots[0] > 0) {
1637                 leaf = path.nodes[0];
1638                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1639                 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1640                     key.type == BTRFS_EXTENT_CSUM_KEY)
1641                         path.slots[0]--;
1642         }
1643
1644         while (len > 0) {
1645                 leaf = path.nodes[0];
1646                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1647                         ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1648                         if (ret > 0)
1649                                 break;
1650                         else if (ret < 0)
1651                                 goto out;
1652                         leaf = path.nodes[0];
1653                 }
1654
1655                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1656                 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1657                     key.type != BTRFS_EXTENT_CSUM_KEY)
1658                         break;
1659
1660                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1661                 if (key.offset >= start + len)
1662                         break;
1663
1664                 if (key.offset > start)
1665                         start = key.offset;
1666
1667                 size = btrfs_item_size_nr(leaf, path.slots[0]);
1668                 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1669                 if (csum_end > start) {
1670                         size = min(csum_end - start, len);
1671                         len -= size;
1672                         start += size;
1673                         *found += size;
1674                 }
1675
1676                 path.slots[0]++;
1677         }
1678 out:
1679         btrfs_release_path(&path);
1680         if (ret < 0)
1681                 return ret;
1682         return 0;
1683 }
1684
1685 static int process_file_extent(struct btrfs_root *root,
1686                                 struct extent_buffer *eb,
1687                                 int slot, struct btrfs_key *key,
1688                                 struct shared_node *active_node)
1689 {
1690         struct inode_record *rec;
1691         struct btrfs_file_extent_item *fi;
1692         u64 num_bytes = 0;
1693         u64 disk_bytenr = 0;
1694         u64 extent_offset = 0;
1695         u64 mask = root->sectorsize - 1;
1696         int extent_type;
1697         int ret;
1698
1699         rec = active_node->current;
1700         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1701         rec->found_file_extent = 1;
1702
1703         if (rec->extent_start == (u64)-1) {
1704                 rec->extent_start = key->offset;
1705                 rec->extent_end = key->offset;
1706         }
1707
1708         if (rec->extent_end > key->offset)
1709                 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1710         else if (rec->extent_end < key->offset) {
1711                 ret = add_file_extent_hole(&rec->holes, rec->extent_end,
1712                                            key->offset - rec->extent_end);
1713                 if (ret < 0)
1714                         return ret;
1715         }
1716
1717         fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1718         extent_type = btrfs_file_extent_type(eb, fi);
1719
1720         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1721                 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1722                 if (num_bytes == 0)
1723                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1724                 rec->found_size += num_bytes;
1725                 num_bytes = (num_bytes + mask) & ~mask;
1726         } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1727                    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1728                 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1729                 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1730                 extent_offset = btrfs_file_extent_offset(eb, fi);
1731                 if (num_bytes == 0 || (num_bytes & mask))
1732                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1733                 if (num_bytes + extent_offset >
1734                     btrfs_file_extent_ram_bytes(eb, fi))
1735                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1736                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1737                     (btrfs_file_extent_compression(eb, fi) ||
1738                      btrfs_file_extent_encryption(eb, fi) ||
1739                      btrfs_file_extent_other_encoding(eb, fi)))
1740                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1741                 if (disk_bytenr > 0)
1742                         rec->found_size += num_bytes;
1743         } else {
1744                 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1745         }
1746         rec->extent_end = key->offset + num_bytes;
1747
1748         /*
1749          * The data reloc tree will copy full extents into its inode and then
1750          * copy the corresponding csums.  Because the extent it copied could be
1751          * a preallocated extent that hasn't been written to yet there may be no
1752          * csums to copy, ergo we won't have csums for our file extent.  This is
1753          * ok so just don't bother checking csums if the inode belongs to the
1754          * data reloc tree.
1755          */
1756         if (disk_bytenr > 0 &&
1757             btrfs_header_owner(eb) != BTRFS_DATA_RELOC_TREE_OBJECTID) {
1758                 u64 found;
1759                 if (btrfs_file_extent_compression(eb, fi))
1760                         num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1761                 else
1762                         disk_bytenr += extent_offset;
1763
1764                 ret = count_csum_range(root, disk_bytenr, num_bytes, &found);
1765                 if (ret < 0)
1766                         return ret;
1767                 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1768                         if (found > 0)
1769                                 rec->found_csum_item = 1;
1770                         if (found < num_bytes)
1771                                 rec->some_csum_missing = 1;
1772                 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1773                         if (found > 0)
1774                                 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1775                 }
1776         }
1777         return 0;
1778 }
1779
1780 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1781                             struct walk_control *wc)
1782 {
1783         struct btrfs_key key;
1784         u32 nritems;
1785         int i;
1786         int ret = 0;
1787         struct cache_tree *inode_cache;
1788         struct shared_node *active_node;
1789
1790         if (wc->root_level == wc->active_node &&
1791             btrfs_root_refs(&root->root_item) == 0)
1792                 return 0;
1793
1794         active_node = wc->nodes[wc->active_node];
1795         inode_cache = &active_node->inode_cache;
1796         nritems = btrfs_header_nritems(eb);
1797         for (i = 0; i < nritems; i++) {
1798                 btrfs_item_key_to_cpu(eb, &key, i);
1799
1800                 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1801                         continue;
1802                 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1803                         continue;
1804
1805                 if (active_node->current == NULL ||
1806                     active_node->current->ino < key.objectid) {
1807                         if (active_node->current) {
1808                                 active_node->current->checked = 1;
1809                                 maybe_free_inode_rec(inode_cache,
1810                                                      active_node->current);
1811                         }
1812                         active_node->current = get_inode_rec(inode_cache,
1813                                                              key.objectid, 1);
1814                         BUG_ON(IS_ERR(active_node->current));
1815                 }
1816                 switch (key.type) {
1817                 case BTRFS_DIR_ITEM_KEY:
1818                 case BTRFS_DIR_INDEX_KEY:
1819                         ret = process_dir_item(root, eb, i, &key, active_node);
1820                         break;
1821                 case BTRFS_INODE_REF_KEY:
1822                         ret = process_inode_ref(eb, i, &key, active_node);
1823                         break;
1824                 case BTRFS_INODE_EXTREF_KEY:
1825                         ret = process_inode_extref(eb, i, &key, active_node);
1826                         break;
1827                 case BTRFS_INODE_ITEM_KEY:
1828                         ret = process_inode_item(eb, i, &key, active_node);
1829                         break;
1830                 case BTRFS_EXTENT_DATA_KEY:
1831                         ret = process_file_extent(root, eb, i, &key,
1832                                                   active_node);
1833                         break;
1834                 default:
1835                         break;
1836                 };
1837         }
1838         return ret;
1839 }
1840
1841 static void reada_walk_down(struct btrfs_root *root,
1842                             struct extent_buffer *node, int slot)
1843 {
1844         u64 bytenr;
1845         u64 ptr_gen;
1846         u32 nritems;
1847         u32 blocksize;
1848         int i;
1849         int level;
1850
1851         level = btrfs_header_level(node);
1852         if (level != 1)
1853                 return;
1854
1855         nritems = btrfs_header_nritems(node);
1856         blocksize = root->nodesize;
1857         for (i = slot; i < nritems; i++) {
1858                 bytenr = btrfs_node_blockptr(node, i);
1859                 ptr_gen = btrfs_node_ptr_generation(node, i);
1860                 readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1861         }
1862 }
1863
1864 /*
1865  * Check the child node/leaf by the following condition:
1866  * 1. the first item key of the node/leaf should be the same with the one
1867  *    in parent.
1868  * 2. block in parent node should match the child node/leaf.
1869  * 3. generation of parent node and child's header should be consistent.
1870  *
1871  * Or the child node/leaf pointed by the key in parent is not valid.
1872  *
1873  * We hope to check leaf owner too, but since subvol may share leaves,
1874  * which makes leaf owner check not so strong, key check should be
1875  * sufficient enough for that case.
1876  */
1877 static int check_child_node(struct btrfs_root *root,
1878                             struct extent_buffer *parent, int slot,
1879                             struct extent_buffer *child)
1880 {
1881         struct btrfs_key parent_key;
1882         struct btrfs_key child_key;
1883         int ret = 0;
1884
1885         btrfs_node_key_to_cpu(parent, &parent_key, slot);
1886         if (btrfs_header_level(child) == 0)
1887                 btrfs_item_key_to_cpu(child, &child_key, 0);
1888         else
1889                 btrfs_node_key_to_cpu(child, &child_key, 0);
1890
1891         if (memcmp(&parent_key, &child_key, sizeof(parent_key))) {
1892                 ret = -EINVAL;
1893                 fprintf(stderr,
1894                         "Wrong key of child node/leaf, wanted: (%llu, %u, %llu), have: (%llu, %u, %llu)\n",
1895                         parent_key.objectid, parent_key.type, parent_key.offset,
1896                         child_key.objectid, child_key.type, child_key.offset);
1897         }
1898         if (btrfs_header_bytenr(child) != btrfs_node_blockptr(parent, slot)) {
1899                 ret = -EINVAL;
1900                 fprintf(stderr, "Wrong block of child node/leaf, wanted: %llu, have: %llu\n",
1901                         btrfs_node_blockptr(parent, slot),
1902                         btrfs_header_bytenr(child));
1903         }
1904         if (btrfs_node_ptr_generation(parent, slot) !=
1905             btrfs_header_generation(child)) {
1906                 ret = -EINVAL;
1907                 fprintf(stderr, "Wrong generation of child node/leaf, wanted: %llu, have: %llu\n",
1908                         btrfs_header_generation(child),
1909                         btrfs_node_ptr_generation(parent, slot));
1910         }
1911         return ret;
1912 }
1913
1914 struct node_refs {
1915         u64 bytenr[BTRFS_MAX_LEVEL];
1916         u64 refs[BTRFS_MAX_LEVEL];
1917 };
1918
1919 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1920                           struct walk_control *wc, int *level,
1921                           struct node_refs *nrefs)
1922 {
1923         enum btrfs_tree_block_status status;
1924         u64 bytenr;
1925         u64 ptr_gen;
1926         struct extent_buffer *next;
1927         struct extent_buffer *cur;
1928         u32 blocksize;
1929         int ret, err = 0;
1930         u64 refs;
1931
1932         WARN_ON(*level < 0);
1933         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1934
1935         if (path->nodes[*level]->start == nrefs->bytenr[*level]) {
1936                 refs = nrefs->refs[*level];
1937                 ret = 0;
1938         } else {
1939                 ret = btrfs_lookup_extent_info(NULL, root,
1940                                        path->nodes[*level]->start,
1941                                        *level, 1, &refs, NULL);
1942                 if (ret < 0) {
1943                         err = ret;
1944                         goto out;
1945                 }
1946                 nrefs->bytenr[*level] = path->nodes[*level]->start;
1947                 nrefs->refs[*level] = refs;
1948         }
1949
1950         if (refs > 1) {
1951                 ret = enter_shared_node(root, path->nodes[*level]->start,
1952                                         refs, wc, *level);
1953                 if (ret > 0) {
1954                         err = ret;
1955                         goto out;
1956                 }
1957         }
1958
1959         while (*level >= 0) {
1960                 WARN_ON(*level < 0);
1961                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1962                 cur = path->nodes[*level];
1963
1964                 if (btrfs_header_level(cur) != *level)
1965                         WARN_ON(1);
1966
1967                 if (path->slots[*level] >= btrfs_header_nritems(cur))
1968                         break;
1969                 if (*level == 0) {
1970                         ret = process_one_leaf(root, cur, wc);
1971                         if (ret < 0)
1972                                 err = ret;
1973                         break;
1974                 }
1975                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1976                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1977                 blocksize = root->nodesize;
1978
1979                 if (bytenr == nrefs->bytenr[*level - 1]) {
1980                         refs = nrefs->refs[*level - 1];
1981                 } else {
1982                         ret = btrfs_lookup_extent_info(NULL, root, bytenr,
1983                                         *level - 1, 1, &refs, NULL);
1984                         if (ret < 0) {
1985                                 refs = 0;
1986                         } else {
1987                                 nrefs->bytenr[*level - 1] = bytenr;
1988                                 nrefs->refs[*level - 1] = refs;
1989                         }
1990                 }
1991
1992                 if (refs > 1) {
1993                         ret = enter_shared_node(root, bytenr, refs,
1994                                                 wc, *level - 1);
1995                         if (ret > 0) {
1996                                 path->slots[*level]++;
1997                                 continue;
1998                         }
1999                 }
2000
2001                 next = btrfs_find_tree_block(root, bytenr, blocksize);
2002                 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
2003                         free_extent_buffer(next);
2004                         reada_walk_down(root, cur, path->slots[*level]);
2005                         next = read_tree_block(root, bytenr, blocksize,
2006                                                ptr_gen);
2007                         if (!extent_buffer_uptodate(next)) {
2008                                 struct btrfs_key node_key;
2009
2010                                 btrfs_node_key_to_cpu(path->nodes[*level],
2011                                                       &node_key,
2012                                                       path->slots[*level]);
2013                                 btrfs_add_corrupt_extent_record(root->fs_info,
2014                                                 &node_key,
2015                                                 path->nodes[*level]->start,
2016                                                 root->nodesize, *level);
2017                                 err = -EIO;
2018                                 goto out;
2019                         }
2020                 }
2021
2022                 ret = check_child_node(root, cur, path->slots[*level], next);
2023                 if (ret) {
2024                         err = ret;
2025                         goto out;
2026                 }
2027
2028                 if (btrfs_is_leaf(next))
2029                         status = btrfs_check_leaf(root, NULL, next);
2030                 else
2031                         status = btrfs_check_node(root, NULL, next);
2032                 if (status != BTRFS_TREE_BLOCK_CLEAN) {
2033                         free_extent_buffer(next);
2034                         err = -EIO;
2035                         goto out;
2036                 }
2037
2038                 *level = *level - 1;
2039                 free_extent_buffer(path->nodes[*level]);
2040                 path->nodes[*level] = next;
2041                 path->slots[*level] = 0;
2042         }
2043 out:
2044         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2045         return err;
2046 }
2047
2048 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
2049                         struct walk_control *wc, int *level)
2050 {
2051         int i;
2052         struct extent_buffer *leaf;
2053
2054         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2055                 leaf = path->nodes[i];
2056                 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
2057                         path->slots[i]++;
2058                         *level = i;
2059                         return 0;
2060                 } else {
2061                         free_extent_buffer(path->nodes[*level]);
2062                         path->nodes[*level] = NULL;
2063                         BUG_ON(*level > wc->active_node);
2064                         if (*level == wc->active_node)
2065                                 leave_shared_node(root, wc, *level);
2066                         *level = i + 1;
2067                 }
2068         }
2069         return 1;
2070 }
2071
2072 static int check_root_dir(struct inode_record *rec)
2073 {
2074         struct inode_backref *backref;
2075         int ret = -1;
2076
2077         if (!rec->found_inode_item || rec->errors)
2078                 goto out;
2079         if (rec->nlink != 1 || rec->found_link != 0)
2080                 goto out;
2081         if (list_empty(&rec->backrefs))
2082                 goto out;
2083         backref = to_inode_backref(rec->backrefs.next);
2084         if (!backref->found_inode_ref)
2085                 goto out;
2086         if (backref->index != 0 || backref->namelen != 2 ||
2087             memcmp(backref->name, "..", 2))
2088                 goto out;
2089         if (backref->found_dir_index || backref->found_dir_item)
2090                 goto out;
2091         ret = 0;
2092 out:
2093         return ret;
2094 }
2095
2096 static int repair_inode_isize(struct btrfs_trans_handle *trans,
2097                               struct btrfs_root *root, struct btrfs_path *path,
2098                               struct inode_record *rec)
2099 {
2100         struct btrfs_inode_item *ei;
2101         struct btrfs_key key;
2102         int ret;
2103
2104         key.objectid = rec->ino;
2105         key.type = BTRFS_INODE_ITEM_KEY;
2106         key.offset = (u64)-1;
2107
2108         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2109         if (ret < 0)
2110                 goto out;
2111         if (ret) {
2112                 if (!path->slots[0]) {
2113                         ret = -ENOENT;
2114                         goto out;
2115                 }
2116                 path->slots[0]--;
2117                 ret = 0;
2118         }
2119         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2120         if (key.objectid != rec->ino) {
2121                 ret = -ENOENT;
2122                 goto out;
2123         }
2124
2125         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2126                             struct btrfs_inode_item);
2127         btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
2128         btrfs_mark_buffer_dirty(path->nodes[0]);
2129         rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
2130         printf("reset isize for dir %Lu root %Lu\n", rec->ino,
2131                root->root_key.objectid);
2132 out:
2133         btrfs_release_path(path);
2134         return ret;
2135 }
2136
2137 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
2138                                     struct btrfs_root *root,
2139                                     struct btrfs_path *path,
2140                                     struct inode_record *rec)
2141 {
2142         int ret;
2143
2144         ret = btrfs_add_orphan_item(trans, root, path, rec->ino);
2145         btrfs_release_path(path);
2146         if (!ret)
2147                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2148         return ret;
2149 }
2150
2151 static int repair_inode_nbytes(struct btrfs_trans_handle *trans,
2152                                struct btrfs_root *root,
2153                                struct btrfs_path *path,
2154                                struct inode_record *rec)
2155 {
2156         struct btrfs_inode_item *ei;
2157         struct btrfs_key key;
2158         int ret = 0;
2159
2160         key.objectid = rec->ino;
2161         key.type = BTRFS_INODE_ITEM_KEY;
2162         key.offset = 0;
2163
2164         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2165         if (ret) {
2166                 if (ret > 0)
2167                         ret = -ENOENT;
2168                 goto out;
2169         }
2170
2171         /* Since ret == 0, no need to check anything */
2172         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
2173                             struct btrfs_inode_item);
2174         btrfs_set_inode_nbytes(path->nodes[0], ei, rec->found_size);
2175         btrfs_mark_buffer_dirty(path->nodes[0]);
2176         rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2177         printf("reset nbytes for ino %llu root %llu\n",
2178                rec->ino, root->root_key.objectid);
2179 out:
2180         btrfs_release_path(path);
2181         return ret;
2182 }
2183
2184 static int add_missing_dir_index(struct btrfs_root *root,
2185                                  struct cache_tree *inode_cache,
2186                                  struct inode_record *rec,
2187                                  struct inode_backref *backref)
2188 {
2189         struct btrfs_path path;
2190         struct btrfs_trans_handle *trans;
2191         struct btrfs_dir_item *dir_item;
2192         struct extent_buffer *leaf;
2193         struct btrfs_key key;
2194         struct btrfs_disk_key disk_key;
2195         struct inode_record *dir_rec;
2196         unsigned long name_ptr;
2197         u32 data_size = sizeof(*dir_item) + backref->namelen;
2198         int ret;
2199
2200         trans = btrfs_start_transaction(root, 1);
2201         if (IS_ERR(trans))
2202                 return PTR_ERR(trans);
2203
2204         fprintf(stderr, "repairing missing dir index item for inode %llu\n",
2205                 (unsigned long long)rec->ino);
2206
2207         btrfs_init_path(&path);
2208         key.objectid = backref->dir;
2209         key.type = BTRFS_DIR_INDEX_KEY;
2210         key.offset = backref->index;
2211         ret = btrfs_insert_empty_item(trans, root, &path, &key, data_size);
2212         BUG_ON(ret);
2213
2214         leaf = path.nodes[0];
2215         dir_item = btrfs_item_ptr(leaf, path.slots[0], struct btrfs_dir_item);
2216
2217         disk_key.objectid = cpu_to_le64(rec->ino);
2218         disk_key.type = BTRFS_INODE_ITEM_KEY;
2219         disk_key.offset = 0;
2220
2221         btrfs_set_dir_item_key(leaf, dir_item, &disk_key);
2222         btrfs_set_dir_type(leaf, dir_item, imode_to_type(rec->imode));
2223         btrfs_set_dir_data_len(leaf, dir_item, 0);
2224         btrfs_set_dir_name_len(leaf, dir_item, backref->namelen);
2225         name_ptr = (unsigned long)(dir_item + 1);
2226         write_extent_buffer(leaf, backref->name, name_ptr, backref->namelen);
2227         btrfs_mark_buffer_dirty(leaf);
2228         btrfs_release_path(&path);
2229         btrfs_commit_transaction(trans, root);
2230
2231         backref->found_dir_index = 1;
2232         dir_rec = get_inode_rec(inode_cache, backref->dir, 0);
2233         BUG_ON(IS_ERR(dir_rec));
2234         if (!dir_rec)
2235                 return 0;
2236         dir_rec->found_size += backref->namelen;
2237         if (dir_rec->found_size == dir_rec->isize &&
2238             (dir_rec->errors & I_ERR_DIR_ISIZE_WRONG))
2239                 dir_rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
2240         if (dir_rec->found_size != dir_rec->isize)
2241                 dir_rec->errors |= I_ERR_DIR_ISIZE_WRONG;
2242
2243         return 0;
2244 }
2245
2246 static int delete_dir_index(struct btrfs_root *root,
2247                             struct cache_tree *inode_cache,
2248                             struct inode_record *rec,
2249                             struct inode_backref *backref)
2250 {
2251         struct btrfs_trans_handle *trans;
2252         struct btrfs_dir_item *di;
2253         struct btrfs_path path;
2254         int ret = 0;
2255
2256         trans = btrfs_start_transaction(root, 1);
2257         if (IS_ERR(trans))
2258                 return PTR_ERR(trans);
2259
2260         fprintf(stderr, "Deleting bad dir index [%llu,%u,%llu] root %llu\n",
2261                 (unsigned long long)backref->dir,
2262                 BTRFS_DIR_INDEX_KEY, (unsigned long long)backref->index,
2263                 (unsigned long long)root->objectid);
2264
2265         btrfs_init_path(&path);
2266         di = btrfs_lookup_dir_index(trans, root, &path, backref->dir,
2267                                     backref->name, backref->namelen,
2268                                     backref->index, -1);
2269         if (IS_ERR(di)) {
2270                 ret = PTR_ERR(di);
2271                 btrfs_release_path(&path);
2272                 btrfs_commit_transaction(trans, root);
2273                 if (ret == -ENOENT)
2274                         return 0;
2275                 return ret;
2276         }
2277
2278         if (!di)
2279                 ret = btrfs_del_item(trans, root, &path);
2280         else
2281                 ret = btrfs_delete_one_dir_name(trans, root, &path, di);
2282         BUG_ON(ret);
2283         btrfs_release_path(&path);
2284         btrfs_commit_transaction(trans, root);
2285         return ret;
2286 }
2287
2288 static int create_inode_item(struct btrfs_root *root,
2289                              struct inode_record *rec,
2290                              struct inode_backref *backref, int root_dir)
2291 {
2292         struct btrfs_trans_handle *trans;
2293         struct btrfs_inode_item inode_item;
2294         time_t now = time(NULL);
2295         int ret;
2296
2297         trans = btrfs_start_transaction(root, 1);
2298         if (IS_ERR(trans)) {
2299                 ret = PTR_ERR(trans);
2300                 return ret;
2301         }
2302
2303         fprintf(stderr, "root %llu inode %llu recreating inode item, this may "
2304                 "be incomplete, please check permissions and content after "
2305                 "the fsck completes.\n", (unsigned long long)root->objectid,
2306                 (unsigned long long)rec->ino);
2307
2308         memset(&inode_item, 0, sizeof(inode_item));
2309         btrfs_set_stack_inode_generation(&inode_item, trans->transid);
2310         if (root_dir)
2311                 btrfs_set_stack_inode_nlink(&inode_item, 1);
2312         else
2313                 btrfs_set_stack_inode_nlink(&inode_item, rec->found_link);
2314         btrfs_set_stack_inode_nbytes(&inode_item, rec->found_size);
2315         if (rec->found_dir_item) {
2316                 if (rec->found_file_extent)
2317                         fprintf(stderr, "root %llu inode %llu has both a dir "
2318                                 "item and extents, unsure if it is a dir or a "
2319                                 "regular file so setting it as a directory\n",
2320                                 (unsigned long long)root->objectid,
2321                                 (unsigned long long)rec->ino);
2322                 btrfs_set_stack_inode_mode(&inode_item, S_IFDIR | 0755);
2323                 btrfs_set_stack_inode_size(&inode_item, rec->found_size);
2324         } else if (!rec->found_dir_item) {
2325                 btrfs_set_stack_inode_size(&inode_item, rec->extent_end);
2326                 btrfs_set_stack_inode_mode(&inode_item, S_IFREG | 0755);
2327         }
2328         btrfs_set_stack_timespec_sec(&inode_item.atime, now);
2329         btrfs_set_stack_timespec_nsec(&inode_item.atime, 0);
2330         btrfs_set_stack_timespec_sec(&inode_item.ctime, now);
2331         btrfs_set_stack_timespec_nsec(&inode_item.ctime, 0);
2332         btrfs_set_stack_timespec_sec(&inode_item.mtime, now);
2333         btrfs_set_stack_timespec_nsec(&inode_item.mtime, 0);
2334         btrfs_set_stack_timespec_sec(&inode_item.otime, 0);
2335         btrfs_set_stack_timespec_nsec(&inode_item.otime, 0);
2336
2337         ret = btrfs_insert_inode(trans, root, rec->ino, &inode_item);
2338         BUG_ON(ret);
2339         btrfs_commit_transaction(trans, root);
2340         return 0;
2341 }
2342
2343 static int repair_inode_backrefs(struct btrfs_root *root,
2344                                  struct inode_record *rec,
2345                                  struct cache_tree *inode_cache,
2346                                  int delete)
2347 {
2348         struct inode_backref *tmp, *backref;
2349         u64 root_dirid = btrfs_root_dirid(&root->root_item);
2350         int ret = 0;
2351         int repaired = 0;
2352
2353         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2354                 if (!delete && rec->ino == root_dirid) {
2355                         if (!rec->found_inode_item) {
2356                                 ret = create_inode_item(root, rec, backref, 1);
2357                                 if (ret)
2358                                         break;
2359                                 repaired++;
2360                         }
2361                 }
2362
2363                 /* Index 0 for root dir's are special, don't mess with it */
2364                 if (rec->ino == root_dirid && backref->index == 0)
2365                         continue;
2366
2367                 if (delete &&
2368                     ((backref->found_dir_index && !backref->found_inode_ref) ||
2369                      (backref->found_dir_index && backref->found_inode_ref &&
2370                       (backref->errors & REF_ERR_INDEX_UNMATCH)))) {
2371                         ret = delete_dir_index(root, inode_cache, rec, backref);
2372                         if (ret)
2373                                 break;
2374                         repaired++;
2375                         list_del(&backref->list);
2376                         free(backref);
2377                 }
2378
2379                 if (!delete && !backref->found_dir_index &&
2380                     backref->found_dir_item && backref->found_inode_ref) {
2381                         ret = add_missing_dir_index(root, inode_cache, rec,
2382                                                     backref);
2383                         if (ret)
2384                                 break;
2385                         repaired++;
2386                         if (backref->found_dir_item &&
2387                             backref->found_dir_index &&
2388                             backref->found_dir_index) {
2389                                 if (!backref->errors &&
2390                                     backref->found_inode_ref) {
2391                                         list_del(&backref->list);
2392                                         free(backref);
2393                                 }
2394                         }
2395                 }
2396
2397                 if (!delete && (!backref->found_dir_index &&
2398                                 !backref->found_dir_item &&
2399                                 backref->found_inode_ref)) {
2400                         struct btrfs_trans_handle *trans;
2401                         struct btrfs_key location;
2402
2403                         ret = check_dir_conflict(root, backref->name,
2404                                                  backref->namelen,
2405                                                  backref->dir,
2406                                                  backref->index);
2407                         if (ret) {
2408                                 /*
2409                                  * let nlink fixing routine to handle it,
2410                                  * which can do it better.
2411                                  */
2412                                 ret = 0;
2413                                 break;
2414                         }
2415                         location.objectid = rec->ino;
2416                         location.type = BTRFS_INODE_ITEM_KEY;
2417                         location.offset = 0;
2418
2419                         trans = btrfs_start_transaction(root, 1);
2420                         if (IS_ERR(trans)) {
2421                                 ret = PTR_ERR(trans);
2422                                 break;
2423                         }
2424                         fprintf(stderr, "adding missing dir index/item pair "
2425                                 "for inode %llu\n",
2426                                 (unsigned long long)rec->ino);
2427                         ret = btrfs_insert_dir_item(trans, root, backref->name,
2428                                                     backref->namelen,
2429                                                     backref->dir, &location,
2430                                                     imode_to_type(rec->imode),
2431                                                     backref->index);
2432                         BUG_ON(ret);
2433                         btrfs_commit_transaction(trans, root);
2434                         repaired++;
2435                 }
2436
2437                 if (!delete && (backref->found_inode_ref &&
2438                                 backref->found_dir_index &&
2439                                 backref->found_dir_item &&
2440                                 !(backref->errors & REF_ERR_INDEX_UNMATCH) &&
2441                                 !rec->found_inode_item)) {
2442                         ret = create_inode_item(root, rec, backref, 0);
2443                         if (ret)
2444                                 break;
2445                         repaired++;
2446                 }
2447
2448         }
2449         return ret ? ret : repaired;
2450 }
2451
2452 /*
2453  * To determine the file type for nlink/inode_item repair
2454  *
2455  * Return 0 if file type is found and BTRFS_FT_* is stored into type.
2456  * Return -ENOENT if file type is not found.
2457  */
2458 static int find_file_type(struct inode_record *rec, u8 *type)
2459 {
2460         struct inode_backref *backref;
2461
2462         /* For inode item recovered case */
2463         if (rec->found_inode_item) {
2464                 *type = imode_to_type(rec->imode);
2465                 return 0;
2466         }
2467
2468         list_for_each_entry(backref, &rec->backrefs, list) {
2469                 if (backref->found_dir_index || backref->found_dir_item) {
2470                         *type = backref->filetype;
2471                         return 0;
2472                 }
2473         }
2474         return -ENOENT;
2475 }
2476
2477 /*
2478  * To determine the file name for nlink repair
2479  *
2480  * Return 0 if file name is found, set name and namelen.
2481  * Return -ENOENT if file name is not found.
2482  */
2483 static int find_file_name(struct inode_record *rec,
2484                           char *name, int *namelen)
2485 {
2486         struct inode_backref *backref;
2487
2488         list_for_each_entry(backref, &rec->backrefs, list) {
2489                 if (backref->found_dir_index || backref->found_dir_item ||
2490                     backref->found_inode_ref) {
2491                         memcpy(name, backref->name, backref->namelen);
2492                         *namelen = backref->namelen;
2493                         return 0;
2494                 }
2495         }
2496         return -ENOENT;
2497 }
2498
2499 /* Reset the nlink of the inode to the correct one */
2500 static int reset_nlink(struct btrfs_trans_handle *trans,
2501                        struct btrfs_root *root,
2502                        struct btrfs_path *path,
2503                        struct inode_record *rec)
2504 {
2505         struct inode_backref *backref;
2506         struct inode_backref *tmp;
2507         struct btrfs_key key;
2508         struct btrfs_inode_item *inode_item;
2509         int ret = 0;
2510
2511         /* We don't believe this either, reset it and iterate backref */
2512         rec->found_link = 0;
2513
2514         /* Remove all backref including the valid ones */
2515         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
2516                 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
2517                                    backref->index, backref->name,
2518                                    backref->namelen, 0);
2519                 if (ret < 0)
2520                         goto out;
2521
2522                 /* remove invalid backref, so it won't be added back */
2523                 if (!(backref->found_dir_index &&
2524                       backref->found_dir_item &&
2525                       backref->found_inode_ref)) {
2526                         list_del(&backref->list);
2527                         free(backref);
2528                 } else {
2529                         rec->found_link++;
2530                 }
2531         }
2532
2533         /* Set nlink to 0 */
2534         key.objectid = rec->ino;
2535         key.type = BTRFS_INODE_ITEM_KEY;
2536         key.offset = 0;
2537         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2538         if (ret < 0)
2539                 goto out;
2540         if (ret > 0) {
2541                 ret = -ENOENT;
2542                 goto out;
2543         }
2544         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2545                                     struct btrfs_inode_item);
2546         btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
2547         btrfs_mark_buffer_dirty(path->nodes[0]);
2548         btrfs_release_path(path);
2549
2550         /*
2551          * Add back valid inode_ref/dir_item/dir_index,
2552          * add_link() will handle the nlink inc, so new nlink must be correct
2553          */
2554         list_for_each_entry(backref, &rec->backrefs, list) {
2555                 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2556                                      backref->name, backref->namelen,
2557                                      backref->filetype, &backref->index, 1);
2558                 if (ret < 0)
2559                         goto out;
2560         }
2561 out:
2562         btrfs_release_path(path);
2563         return ret;
2564 }
2565
2566 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2567                                struct btrfs_root *root,
2568                                struct btrfs_path *path,
2569                                struct inode_record *rec)
2570 {
2571         char *dir_name = "lost+found";
2572         char namebuf[BTRFS_NAME_LEN] = {0};
2573         u64 lost_found_ino;
2574         u32 mode = 0700;
2575         u8 type = 0;
2576         int namelen = 0;
2577         int name_recovered = 0;
2578         int type_recovered = 0;
2579         int ret = 0;
2580
2581         /*
2582          * Get file name and type first before these invalid inode ref
2583          * are deleted by remove_all_invalid_backref()
2584          */
2585         name_recovered = !find_file_name(rec, namebuf, &namelen);
2586         type_recovered = !find_file_type(rec, &type);
2587
2588         if (!name_recovered) {
2589                 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2590                        rec->ino, rec->ino);
2591                 namelen = count_digits(rec->ino);
2592                 sprintf(namebuf, "%llu", rec->ino);
2593                 name_recovered = 1;
2594         }
2595         if (!type_recovered) {
2596                 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2597                        rec->ino);
2598                 type = BTRFS_FT_REG_FILE;
2599                 type_recovered = 1;
2600         }
2601
2602         ret = reset_nlink(trans, root, path, rec);
2603         if (ret < 0) {
2604                 fprintf(stderr,
2605                         "Failed to reset nlink for inode %llu: %s\n",
2606                         rec->ino, strerror(-ret));
2607                 goto out;
2608         }
2609
2610         if (rec->found_link == 0) {
2611                 lost_found_ino = root->highest_inode;
2612                 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2613                         ret = -EOVERFLOW;
2614                         goto out;
2615                 }
2616                 lost_found_ino++;
2617                 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2618                                   BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2619                                   mode);
2620                 if (ret < 0) {
2621                         fprintf(stderr, "Failed to create '%s' dir: %s\n",
2622                                 dir_name, strerror(-ret));
2623                         goto out;
2624                 }
2625                 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2626                                      namebuf, namelen, type, NULL, 1);
2627                 /*
2628                  * Add ".INO" suffix several times to handle case where
2629                  * "FILENAME.INO" is already taken by another file.
2630                  */
2631                 while (ret == -EEXIST) {
2632                         /*
2633                          * Conflicting file name, add ".INO" as suffix * +1 for '.'
2634                          */
2635                         if (namelen + count_digits(rec->ino) + 1 >
2636                             BTRFS_NAME_LEN) {
2637                                 ret = -EFBIG;
2638                                 goto out;
2639                         }
2640                         snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2641                                  ".%llu", rec->ino);
2642                         namelen += count_digits(rec->ino) + 1;
2643                         ret = btrfs_add_link(trans, root, rec->ino,
2644                                              lost_found_ino, namebuf,
2645                                              namelen, type, NULL, 1);
2646                 }
2647                 if (ret < 0) {
2648                         fprintf(stderr,
2649                                 "Failed to link the inode %llu to %s dir: %s\n",
2650                                 rec->ino, dir_name, strerror(-ret));
2651                         goto out;
2652                 }
2653                 /*
2654                  * Just increase the found_link, don't actually add the
2655                  * backref. This will make things easier and this inode
2656                  * record will be freed after the repair is done.
2657                  * So fsck will not report problem about this inode.
2658                  */
2659                 rec->found_link++;
2660                 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2661                        namelen, namebuf, dir_name);
2662         }
2663         printf("Fixed the nlink of inode %llu\n", rec->ino);
2664 out:
2665         /*
2666          * Clear the flag anyway, or we will loop forever for the same inode
2667          * as it will not be removed from the bad inode list and the dead loop
2668          * happens.
2669          */
2670         rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2671         btrfs_release_path(path);
2672         return ret;
2673 }
2674
2675 /*
2676  * Check if there is any normal(reg or prealloc) file extent for given
2677  * ino.
2678  * This is used to determine the file type when neither its dir_index/item or
2679  * inode_item exists.
2680  *
2681  * This will *NOT* report error, if any error happens, just consider it does
2682  * not have any normal file extent.
2683  */
2684 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2685 {
2686         struct btrfs_path path;
2687         struct btrfs_key key;
2688         struct btrfs_key found_key;
2689         struct btrfs_file_extent_item *fi;
2690         u8 type;
2691         int ret = 0;
2692
2693         btrfs_init_path(&path);
2694         key.objectid = ino;
2695         key.type = BTRFS_EXTENT_DATA_KEY;
2696         key.offset = 0;
2697
2698         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
2699         if (ret < 0) {
2700                 ret = 0;
2701                 goto out;
2702         }
2703         if (ret && path.slots[0] >= btrfs_header_nritems(path.nodes[0])) {
2704                 ret = btrfs_next_leaf(root, &path);
2705                 if (ret) {
2706                         ret = 0;
2707                         goto out;
2708                 }
2709         }
2710         while (1) {
2711                 btrfs_item_key_to_cpu(path.nodes[0], &found_key,
2712                                       path.slots[0]);
2713                 if (found_key.objectid != ino ||
2714                     found_key.type != BTRFS_EXTENT_DATA_KEY)
2715                         break;
2716                 fi = btrfs_item_ptr(path.nodes[0], path.slots[0],
2717                                     struct btrfs_file_extent_item);
2718                 type = btrfs_file_extent_type(path.nodes[0], fi);
2719                 if (type != BTRFS_FILE_EXTENT_INLINE) {
2720                         ret = 1;
2721                         goto out;
2722                 }
2723         }
2724 out:
2725         btrfs_release_path(&path);
2726         return ret;
2727 }
2728
2729 static u32 btrfs_type_to_imode(u8 type)
2730 {
2731         static u32 imode_by_btrfs_type[] = {
2732                 [BTRFS_FT_REG_FILE]     = S_IFREG,
2733                 [BTRFS_FT_DIR]          = S_IFDIR,
2734                 [BTRFS_FT_CHRDEV]       = S_IFCHR,
2735                 [BTRFS_FT_BLKDEV]       = S_IFBLK,
2736                 [BTRFS_FT_FIFO]         = S_IFIFO,
2737                 [BTRFS_FT_SOCK]         = S_IFSOCK,
2738                 [BTRFS_FT_SYMLINK]      = S_IFLNK,
2739         };
2740
2741         return imode_by_btrfs_type[(type)];
2742 }
2743
2744 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2745                                 struct btrfs_root *root,
2746                                 struct btrfs_path *path,
2747                                 struct inode_record *rec)
2748 {
2749         u8 filetype;
2750         u32 mode = 0700;
2751         int type_recovered = 0;
2752         int ret = 0;
2753
2754         printf("Trying to rebuild inode:%llu\n", rec->ino);
2755
2756         type_recovered = !find_file_type(rec, &filetype);
2757
2758         /*
2759          * Try to determine inode type if type not found.
2760          *
2761          * For found regular file extent, it must be FILE.
2762          * For found dir_item/index, it must be DIR.
2763          *
2764          * For undetermined one, use FILE as fallback.
2765          *
2766          * TODO:
2767          * 1. If found backref(inode_index/item is already handled) to it,
2768          *    it must be DIR.
2769          *    Need new inode-inode ref structure to allow search for that.
2770          */
2771         if (!type_recovered) {
2772                 if (rec->found_file_extent &&
2773                     find_normal_file_extent(root, rec->ino)) {
2774                         type_recovered = 1;
2775                         filetype = BTRFS_FT_REG_FILE;
2776                 } else if (rec->found_dir_item) {
2777                         type_recovered = 1;
2778                         filetype = BTRFS_FT_DIR;
2779                 } else if (!list_empty(&rec->orphan_extents)) {
2780                         type_recovered = 1;
2781                         filetype = BTRFS_FT_REG_FILE;
2782                 } else{
2783                         printf("Can't determine the filetype for inode %llu, assume it is a normal file\n",
2784                                rec->ino);
2785                         type_recovered = 1;
2786                         filetype = BTRFS_FT_REG_FILE;
2787                 }
2788         }
2789
2790         ret = btrfs_new_inode(trans, root, rec->ino,
2791                               mode | btrfs_type_to_imode(filetype));
2792         if (ret < 0)
2793                 goto out;
2794
2795         /*
2796          * Here inode rebuild is done, we only rebuild the inode item,
2797          * don't repair the nlink(like move to lost+found).
2798          * That is the job of nlink repair.
2799          *
2800          * We just fill the record and return
2801          */
2802         rec->found_dir_item = 1;
2803         rec->imode = mode | btrfs_type_to_imode(filetype);
2804         rec->nlink = 0;
2805         rec->errors &= ~I_ERR_NO_INODE_ITEM;
2806         /* Ensure the inode_nlinks repair function will be called */
2807         rec->errors |= I_ERR_LINK_COUNT_WRONG;
2808 out:
2809         return ret;
2810 }
2811
2812 static int repair_inode_orphan_extent(struct btrfs_trans_handle *trans,
2813                                       struct btrfs_root *root,
2814                                       struct btrfs_path *path,
2815                                       struct inode_record *rec)
2816 {
2817         struct orphan_data_extent *orphan;
2818         struct orphan_data_extent *tmp;
2819         int ret = 0;
2820
2821         list_for_each_entry_safe(orphan, tmp, &rec->orphan_extents, list) {
2822                 /*
2823                  * Check for conflicting file extents
2824                  *
2825                  * Here we don't know whether the extents is compressed or not,
2826                  * so we can only assume it not compressed nor data offset,
2827                  * and use its disk_len as extent length.
2828                  */
2829                 ret = btrfs_get_extent(NULL, root, path, orphan->objectid,
2830                                        orphan->offset, orphan->disk_len, 0);
2831                 btrfs_release_path(path);
2832                 if (ret < 0)
2833                         goto out;
2834                 if (!ret) {
2835                         fprintf(stderr,
2836                                 "orphan extent (%llu, %llu) conflicts, delete the orphan\n",
2837                                 orphan->disk_bytenr, orphan->disk_len);
2838                         ret = btrfs_free_extent(trans,
2839                                         root->fs_info->extent_root,
2840                                         orphan->disk_bytenr, orphan->disk_len,
2841                                         0, root->objectid, orphan->objectid,
2842                                         orphan->offset);
2843                         if (ret < 0)
2844                                 goto out;
2845                 }
2846                 ret = btrfs_insert_file_extent(trans, root, orphan->objectid,
2847                                 orphan->offset, orphan->disk_bytenr,
2848                                 orphan->disk_len, orphan->disk_len);
2849                 if (ret < 0)
2850                         goto out;
2851
2852                 /* Update file size info */
2853                 rec->found_size += orphan->disk_len;
2854                 if (rec->found_size == rec->nbytes)
2855                         rec->errors &= ~I_ERR_FILE_NBYTES_WRONG;
2856
2857                 /* Update the file extent hole info too */
2858                 ret = del_file_extent_hole(&rec->holes, orphan->offset,
2859                                            orphan->disk_len);
2860                 if (ret < 0)
2861                         goto out;
2862                 if (RB_EMPTY_ROOT(&rec->holes))
2863                         rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2864
2865                 list_del(&orphan->list);
2866                 free(orphan);
2867         }
2868         rec->errors &= ~I_ERR_FILE_EXTENT_ORPHAN;
2869 out:
2870         return ret;
2871 }
2872
2873 static int repair_inode_discount_extent(struct btrfs_trans_handle *trans,
2874                                         struct btrfs_root *root,
2875                                         struct btrfs_path *path,
2876                                         struct inode_record *rec)
2877 {
2878         struct rb_node *node;
2879         struct file_extent_hole *hole;
2880         int found = 0;
2881         int ret = 0;
2882
2883         node = rb_first(&rec->holes);
2884
2885         while (node) {
2886                 found = 1;
2887                 hole = rb_entry(node, struct file_extent_hole, node);
2888                 ret = btrfs_punch_hole(trans, root, rec->ino,
2889                                        hole->start, hole->len);
2890                 if (ret < 0)
2891                         goto out;
2892                 ret = del_file_extent_hole(&rec->holes, hole->start,
2893                                            hole->len);
2894                 if (ret < 0)
2895                         goto out;
2896                 if (RB_EMPTY_ROOT(&rec->holes))
2897                         rec->errors &= ~I_ERR_FILE_EXTENT_DISCOUNT;
2898                 node = rb_first(&rec->holes);
2899         }
2900         /* special case for a file losing all its file extent */
2901         if (!found) {
2902                 ret = btrfs_punch_hole(trans, root, rec->ino, 0,
2903                                        round_up(rec->isize, root->sectorsize));
2904                 if (ret < 0)
2905                         goto out;
2906         }
2907         printf("Fixed discount file extents for inode: %llu in root: %llu\n",
2908                rec->ino, root->objectid);
2909 out:
2910         return ret;
2911 }
2912
2913 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2914 {
2915         struct btrfs_trans_handle *trans;
2916         struct btrfs_path path;
2917         int ret = 0;
2918
2919         if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2920                              I_ERR_NO_ORPHAN_ITEM |
2921                              I_ERR_LINK_COUNT_WRONG |
2922                              I_ERR_NO_INODE_ITEM |
2923                              I_ERR_FILE_EXTENT_ORPHAN |
2924                              I_ERR_FILE_EXTENT_DISCOUNT|
2925                              I_ERR_FILE_NBYTES_WRONG)))
2926                 return rec->errors;
2927
2928         /*
2929          * For nlink repair, it may create a dir and add link, so
2930          * 2 for parent(256)'s dir_index and dir_item
2931          * 2 for lost+found dir's inode_item and inode_ref
2932          * 1 for the new inode_ref of the file
2933          * 2 for lost+found dir's dir_index and dir_item for the file
2934          */
2935         trans = btrfs_start_transaction(root, 7);
2936         if (IS_ERR(trans))
2937                 return PTR_ERR(trans);
2938
2939         btrfs_init_path(&path);
2940         if (rec->errors & I_ERR_NO_INODE_ITEM)
2941                 ret = repair_inode_no_item(trans, root, &path, rec);
2942         if (!ret && rec->errors & I_ERR_FILE_EXTENT_ORPHAN)
2943                 ret = repair_inode_orphan_extent(trans, root, &path, rec);
2944         if (!ret && rec->errors & I_ERR_FILE_EXTENT_DISCOUNT)
2945                 ret = repair_inode_discount_extent(trans, root, &path, rec);
2946         if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2947                 ret = repair_inode_isize(trans, root, &path, rec);
2948         if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2949                 ret = repair_inode_orphan_item(trans, root, &path, rec);
2950         if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2951                 ret = repair_inode_nlinks(trans, root, &path, rec);
2952         if (!ret && rec->errors & I_ERR_FILE_NBYTES_WRONG)
2953                 ret = repair_inode_nbytes(trans, root, &path, rec);
2954         btrfs_commit_transaction(trans, root);
2955         btrfs_release_path(&path);
2956         return ret;
2957 }
2958
2959 static int check_inode_recs(struct btrfs_root *root,
2960                             struct cache_tree *inode_cache)
2961 {
2962         struct cache_extent *cache;
2963         struct ptr_node *node;
2964         struct inode_record *rec;
2965         struct inode_backref *backref;
2966         int stage = 0;
2967         int ret = 0;
2968         int err = 0;
2969         u64 error = 0;
2970         u64 root_dirid = btrfs_root_dirid(&root->root_item);
2971
2972         if (btrfs_root_refs(&root->root_item) == 0) {
2973                 if (!cache_tree_empty(inode_cache))
2974                         fprintf(stderr, "warning line %d\n", __LINE__);
2975                 return 0;
2976         }
2977
2978         /*
2979          * We need to record the highest inode number for later 'lost+found'
2980          * dir creation.
2981          * We must select an ino not used/referred by any existing inode, or
2982          * 'lost+found' ino may be a missing ino in a corrupted leaf,
2983          * this may cause 'lost+found' dir has wrong nlinks.
2984          */
2985         cache = last_cache_extent(inode_cache);
2986         if (cache) {
2987                 node = container_of(cache, struct ptr_node, cache);
2988                 rec = node->data;
2989                 if (rec->ino > root->highest_inode)
2990                         root->highest_inode = rec->ino;
2991         }
2992
2993         /*
2994          * We need to repair backrefs first because we could change some of the
2995          * errors in the inode recs.
2996          *
2997          * We also need to go through and delete invalid backrefs first and then
2998          * add the correct ones second.  We do this because we may get EEXIST
2999          * when adding back the correct index because we hadn't yet deleted the
3000          * invalid index.
3001          *
3002          * For example, if we were missing a dir index then the directories
3003          * isize would be wrong, so if we fixed the isize to what we thought it
3004          * would be and then fixed the backref we'd still have a invalid fs, so
3005          * we need to add back the dir index and then check to see if the isize
3006          * is still wrong.
3007          */
3008         while (stage < 3) {
3009                 stage++;
3010                 if (stage == 3 && !err)
3011                         break;
3012
3013                 cache = search_cache_extent(inode_cache, 0);
3014                 while (repair && cache) {
3015                         node = container_of(cache, struct ptr_node, cache);
3016                         rec = node->data;
3017                         cache = next_cache_extent(cache);
3018
3019                         /* Need to free everything up and rescan */
3020                         if (stage == 3) {
3021                                 remove_cache_extent(inode_cache, &node->cache);
3022                                 free(node);
3023                                 free_inode_rec(rec);
3024                                 continue;
3025                         }
3026
3027                         if (list_empty(&rec->backrefs))
3028                                 continue;
3029
3030                         ret = repair_inode_backrefs(root, rec, inode_cache,
3031                                                     stage == 1);
3032                         if (ret < 0) {
3033                                 err = ret;
3034                                 stage = 2;
3035                                 break;
3036                         } if (ret > 0) {
3037                                 err = -EAGAIN;
3038                         }
3039                 }
3040         }
3041         if (err)
3042                 return err;
3043
3044         rec = get_inode_rec(inode_cache, root_dirid, 0);
3045         BUG_ON(IS_ERR(rec));
3046         if (rec) {
3047                 ret = check_root_dir(rec);
3048                 if (ret) {
3049                         fprintf(stderr, "root %llu root dir %llu error\n",
3050                                 (unsigned long long)root->root_key.objectid,
3051                                 (unsigned long long)root_dirid);
3052                         print_inode_error(root, rec);
3053                         error++;
3054                 }
3055         } else {
3056                 if (repair) {
3057                         struct btrfs_trans_handle *trans;
3058
3059                         trans = btrfs_start_transaction(root, 1);
3060                         if (IS_ERR(trans)) {
3061                                 err = PTR_ERR(trans);
3062                                 return err;
3063                         }
3064
3065                         fprintf(stderr,
3066                                 "root %llu missing its root dir, recreating\n",
3067                                 (unsigned long long)root->objectid);
3068
3069                         ret = btrfs_make_root_dir(trans, root, root_dirid);
3070                         BUG_ON(ret);
3071
3072                         btrfs_commit_transaction(trans, root);
3073                         return -EAGAIN;
3074                 }
3075
3076                 fprintf(stderr, "root %llu root dir %llu not found\n",
3077                         (unsigned long long)root->root_key.objectid,
3078                         (unsigned long long)root_dirid);
3079         }
3080
3081         while (1) {
3082                 cache = search_cache_extent(inode_cache, 0);
3083                 if (!cache)
3084                         break;
3085                 node = container_of(cache, struct ptr_node, cache);
3086                 rec = node->data;
3087                 remove_cache_extent(inode_cache, &node->cache);
3088                 free(node);
3089                 if (rec->ino == root_dirid ||
3090                     rec->ino == BTRFS_ORPHAN_OBJECTID) {
3091                         free_inode_rec(rec);
3092                         continue;
3093                 }
3094
3095                 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
3096                         ret = check_orphan_item(root, rec->ino);
3097                         if (ret == 0)
3098                                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
3099                         if (can_free_inode_rec(rec)) {
3100                                 free_inode_rec(rec);
3101                                 continue;
3102                         }
3103                 }
3104
3105                 if (!rec->found_inode_item)
3106                         rec->errors |= I_ERR_NO_INODE_ITEM;
3107                 if (rec->found_link != rec->nlink)
3108                         rec->errors |= I_ERR_LINK_COUNT_WRONG;
3109                 if (repair) {
3110                         ret = try_repair_inode(root, rec);
3111                         if (ret == 0 && can_free_inode_rec(rec)) {
3112                                 free_inode_rec(rec);
3113                                 continue;
3114                         }
3115                         ret = 0;
3116                 }
3117
3118                 if (!(repair && ret == 0))
3119                         error++;
3120                 print_inode_error(root, rec);
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_inode_ref)
3127                                 backref->errors |= REF_ERR_NO_INODE_REF;
3128                         fprintf(stderr, "\tunresolved ref dir %llu index %llu"
3129                                 " namelen %u name %s filetype %d errors %x",
3130                                 (unsigned long long)backref->dir,
3131                                 (unsigned long long)backref->index,
3132                                 backref->namelen, backref->name,
3133                                 backref->filetype, backref->errors);
3134                         print_ref_error(backref->errors);
3135                 }
3136                 free_inode_rec(rec);
3137         }
3138         return (error > 0) ? -1 : 0;
3139 }
3140
3141 static struct root_record *get_root_rec(struct cache_tree *root_cache,
3142                                         u64 objectid)
3143 {
3144         struct cache_extent *cache;
3145         struct root_record *rec = NULL;
3146         int ret;
3147
3148         cache = lookup_cache_extent(root_cache, objectid, 1);
3149         if (cache) {
3150                 rec = container_of(cache, struct root_record, cache);
3151         } else {
3152                 rec = calloc(1, sizeof(*rec));
3153                 if (!rec)
3154                         return ERR_PTR(-ENOMEM);
3155                 rec->objectid = objectid;
3156                 INIT_LIST_HEAD(&rec->backrefs);
3157                 rec->cache.start = objectid;
3158                 rec->cache.size = 1;
3159
3160                 ret = insert_cache_extent(root_cache, &rec->cache);
3161                 if (ret)
3162                         return ERR_PTR(-EEXIST);
3163         }
3164         return rec;
3165 }
3166
3167 static struct root_backref *get_root_backref(struct root_record *rec,
3168                                              u64 ref_root, u64 dir, u64 index,
3169                                              const char *name, int namelen)
3170 {
3171         struct root_backref *backref;
3172
3173         list_for_each_entry(backref, &rec->backrefs, list) {
3174                 if (backref->ref_root != ref_root || backref->dir != dir ||
3175                     backref->namelen != namelen)
3176                         continue;
3177                 if (memcmp(name, backref->name, namelen))
3178                         continue;
3179                 return backref;
3180         }
3181
3182         backref = calloc(1, sizeof(*backref) + namelen + 1);
3183         if (!backref)
3184                 return NULL;
3185         backref->ref_root = ref_root;
3186         backref->dir = dir;
3187         backref->index = index;
3188         backref->namelen = namelen;
3189         memcpy(backref->name, name, namelen);
3190         backref->name[namelen] = '\0';
3191         list_add_tail(&backref->list, &rec->backrefs);
3192         return backref;
3193 }
3194
3195 static void free_root_record(struct cache_extent *cache)
3196 {
3197         struct root_record *rec;
3198         struct root_backref *backref;
3199
3200         rec = container_of(cache, struct root_record, cache);
3201         while (!list_empty(&rec->backrefs)) {
3202                 backref = to_root_backref(rec->backrefs.next);
3203                 list_del(&backref->list);
3204                 free(backref);
3205         }
3206
3207         free(rec);
3208 }
3209
3210 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
3211
3212 static int add_root_backref(struct cache_tree *root_cache,
3213                             u64 root_id, u64 ref_root, u64 dir, u64 index,
3214                             const char *name, int namelen,
3215                             int item_type, int errors)
3216 {
3217         struct root_record *rec;
3218         struct root_backref *backref;
3219
3220         rec = get_root_rec(root_cache, root_id);
3221         BUG_ON(IS_ERR(rec));
3222         backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
3223         BUG_ON(!backref);
3224
3225         backref->errors |= errors;
3226
3227         if (item_type != BTRFS_DIR_ITEM_KEY) {
3228                 if (backref->found_dir_index || backref->found_back_ref ||
3229                     backref->found_forward_ref) {
3230                         if (backref->index != index)
3231                                 backref->errors |= REF_ERR_INDEX_UNMATCH;
3232                 } else {
3233                         backref->index = index;
3234                 }
3235         }
3236
3237         if (item_type == BTRFS_DIR_ITEM_KEY) {
3238                 if (backref->found_forward_ref)
3239                         rec->found_ref++;
3240                 backref->found_dir_item = 1;
3241         } else if (item_type == BTRFS_DIR_INDEX_KEY) {
3242                 backref->found_dir_index = 1;
3243         } else if (item_type == BTRFS_ROOT_REF_KEY) {
3244                 if (backref->found_forward_ref)
3245                         backref->errors |= REF_ERR_DUP_ROOT_REF;
3246                 else if (backref->found_dir_item)
3247                         rec->found_ref++;
3248                 backref->found_forward_ref = 1;
3249         } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
3250                 if (backref->found_back_ref)
3251                         backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
3252                 backref->found_back_ref = 1;
3253         } else {
3254                 BUG_ON(1);
3255         }
3256
3257         if (backref->found_forward_ref && backref->found_dir_item)
3258                 backref->reachable = 1;
3259         return 0;
3260 }
3261
3262 static int merge_root_recs(struct btrfs_root *root,
3263                            struct cache_tree *src_cache,
3264                            struct cache_tree *dst_cache)
3265 {
3266         struct cache_extent *cache;
3267         struct ptr_node *node;
3268         struct inode_record *rec;
3269         struct inode_backref *backref;
3270         int ret = 0;
3271
3272         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3273                 free_inode_recs_tree(src_cache);
3274                 return 0;
3275         }
3276
3277         while (1) {
3278                 cache = search_cache_extent(src_cache, 0);
3279                 if (!cache)
3280                         break;
3281                 node = container_of(cache, struct ptr_node, cache);
3282                 rec = node->data;
3283                 remove_cache_extent(src_cache, &node->cache);
3284                 free(node);
3285
3286                 ret = is_child_root(root, root->objectid, rec->ino);
3287                 if (ret < 0)
3288                         break;
3289                 else if (ret == 0)
3290                         goto skip;
3291
3292                 list_for_each_entry(backref, &rec->backrefs, list) {
3293                         BUG_ON(backref->found_inode_ref);
3294                         if (backref->found_dir_item)
3295                                 add_root_backref(dst_cache, rec->ino,
3296                                         root->root_key.objectid, backref->dir,
3297                                         backref->index, backref->name,
3298                                         backref->namelen, BTRFS_DIR_ITEM_KEY,
3299                                         backref->errors);
3300                         if (backref->found_dir_index)
3301                                 add_root_backref(dst_cache, rec->ino,
3302                                         root->root_key.objectid, backref->dir,
3303                                         backref->index, backref->name,
3304                                         backref->namelen, BTRFS_DIR_INDEX_KEY,
3305                                         backref->errors);
3306                 }
3307 skip:
3308                 free_inode_rec(rec);
3309         }
3310         if (ret < 0)
3311                 return ret;
3312         return 0;
3313 }
3314
3315 static int check_root_refs(struct btrfs_root *root,
3316                            struct cache_tree *root_cache)
3317 {
3318         struct root_record *rec;
3319         struct root_record *ref_root;
3320         struct root_backref *backref;
3321         struct cache_extent *cache;
3322         int loop = 1;
3323         int ret;
3324         int error;
3325         int errors = 0;
3326
3327         rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
3328         BUG_ON(IS_ERR(rec));
3329         rec->found_ref = 1;
3330
3331         /* fixme: this can not detect circular references */
3332         while (loop) {
3333                 loop = 0;
3334                 cache = search_cache_extent(root_cache, 0);
3335                 while (1) {
3336                         if (!cache)
3337                                 break;
3338                         rec = container_of(cache, struct root_record, cache);
3339                         cache = next_cache_extent(cache);
3340
3341                         if (rec->found_ref == 0)
3342                                 continue;
3343
3344                         list_for_each_entry(backref, &rec->backrefs, list) {
3345                                 if (!backref->reachable)
3346                                         continue;
3347
3348                                 ref_root = get_root_rec(root_cache,
3349                                                         backref->ref_root);
3350                                 BUG_ON(IS_ERR(ref_root));
3351                                 if (ref_root->found_ref > 0)
3352                                         continue;
3353
3354                                 backref->reachable = 0;
3355                                 rec->found_ref--;
3356                                 if (rec->found_ref == 0)
3357                                         loop = 1;
3358                         }
3359                 }
3360         }
3361
3362         cache = search_cache_extent(root_cache, 0);
3363         while (1) {
3364                 if (!cache)
3365                         break;
3366                 rec = container_of(cache, struct root_record, cache);
3367                 cache = next_cache_extent(cache);
3368
3369                 if (rec->found_ref == 0 &&
3370                     rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
3371                     rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
3372                         ret = check_orphan_item(root->fs_info->tree_root,
3373                                                 rec->objectid);
3374                         if (ret == 0)
3375                                 continue;
3376
3377                         /*
3378                          * If we don't have a root item then we likely just have
3379                          * a dir item in a snapshot for this root but no actual
3380                          * ref key or anything so it's meaningless.
3381                          */
3382                         if (!rec->found_root_item)
3383                                 continue;
3384                         errors++;
3385                         fprintf(stderr, "fs tree %llu not referenced\n",
3386                                 (unsigned long long)rec->objectid);
3387                 }
3388
3389                 error = 0;
3390                 if (rec->found_ref > 0 && !rec->found_root_item)
3391                         error = 1;
3392                 list_for_each_entry(backref, &rec->backrefs, list) {
3393                         if (!backref->found_dir_item)
3394                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
3395                         if (!backref->found_dir_index)
3396                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
3397                         if (!backref->found_back_ref)
3398                                 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
3399                         if (!backref->found_forward_ref)
3400                                 backref->errors |= REF_ERR_NO_ROOT_REF;
3401                         if (backref->reachable && backref->errors)
3402                                 error = 1;
3403                 }
3404                 if (!error)
3405                         continue;
3406
3407                 errors++;
3408                 fprintf(stderr, "fs tree %llu refs %u %s\n",
3409                         (unsigned long long)rec->objectid, rec->found_ref,
3410                          rec->found_root_item ? "" : "not found");
3411
3412                 list_for_each_entry(backref, &rec->backrefs, list) {
3413                         if (!backref->reachable)
3414                                 continue;
3415                         if (!backref->errors && rec->found_root_item)
3416                                 continue;
3417                         fprintf(stderr, "\tunresolved ref root %llu dir %llu"
3418                                 " index %llu namelen %u name %s errors %x\n",
3419                                 (unsigned long long)backref->ref_root,
3420                                 (unsigned long long)backref->dir,
3421                                 (unsigned long long)backref->index,
3422                                 backref->namelen, backref->name,
3423                                 backref->errors);
3424                         print_ref_error(backref->errors);
3425                 }
3426         }
3427         return errors > 0 ? 1 : 0;
3428 }
3429
3430 static int process_root_ref(struct extent_buffer *eb, int slot,
3431                             struct btrfs_key *key,
3432                             struct cache_tree *root_cache)
3433 {
3434         u64 dirid;
3435         u64 index;
3436         u32 len;
3437         u32 name_len;
3438         struct btrfs_root_ref *ref;
3439         char namebuf[BTRFS_NAME_LEN];
3440         int error;
3441
3442         ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
3443
3444         dirid = btrfs_root_ref_dirid(eb, ref);
3445         index = btrfs_root_ref_sequence(eb, ref);
3446         name_len = btrfs_root_ref_name_len(eb, ref);
3447
3448         if (name_len <= BTRFS_NAME_LEN) {
3449                 len = name_len;
3450                 error = 0;
3451         } else {
3452                 len = BTRFS_NAME_LEN;
3453                 error = REF_ERR_NAME_TOO_LONG;
3454         }
3455         read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
3456
3457         if (key->type == BTRFS_ROOT_REF_KEY) {
3458                 add_root_backref(root_cache, key->offset, key->objectid, dirid,
3459                                  index, namebuf, len, key->type, error);
3460         } else {
3461                 add_root_backref(root_cache, key->objectid, key->offset, dirid,
3462                                  index, namebuf, len, key->type, error);
3463         }
3464         return 0;
3465 }
3466
3467 static void free_corrupt_block(struct cache_extent *cache)
3468 {
3469         struct btrfs_corrupt_block *corrupt;
3470
3471         corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
3472         free(corrupt);
3473 }
3474
3475 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
3476
3477 /*
3478  * Repair the btree of the given root.
3479  *
3480  * The fix is to remove the node key in corrupt_blocks cache_tree.
3481  * and rebalance the tree.
3482  * After the fix, the btree should be writeable.
3483  */
3484 static int repair_btree(struct btrfs_root *root,
3485                         struct cache_tree *corrupt_blocks)
3486 {
3487         struct btrfs_trans_handle *trans;
3488         struct btrfs_path path;
3489         struct btrfs_corrupt_block *corrupt;
3490         struct cache_extent *cache;
3491         struct btrfs_key key;
3492         u64 offset;
3493         int level;
3494         int ret = 0;
3495
3496         if (cache_tree_empty(corrupt_blocks))
3497                 return 0;
3498
3499         trans = btrfs_start_transaction(root, 1);
3500         if (IS_ERR(trans)) {
3501                 ret = PTR_ERR(trans);
3502                 fprintf(stderr, "Error starting transaction: %s\n",
3503                         strerror(-ret));
3504                 return ret;
3505         }
3506         btrfs_init_path(&path);
3507         cache = first_cache_extent(corrupt_blocks);
3508         while (cache) {
3509                 corrupt = container_of(cache, struct btrfs_corrupt_block,
3510                                        cache);
3511                 level = corrupt->level;
3512                 path.lowest_level = level;
3513                 key.objectid = corrupt->key.objectid;
3514                 key.type = corrupt->key.type;
3515                 key.offset = corrupt->key.offset;
3516
3517                 /*
3518                  * Here we don't want to do any tree balance, since it may
3519                  * cause a balance with corrupted brother leaf/node,
3520                  * so ins_len set to 0 here.
3521                  * Balance will be done after all corrupt node/leaf is deleted.
3522                  */
3523                 ret = btrfs_search_slot(trans, root, &key, &path, 0, 1);
3524                 if (ret < 0)
3525                         goto out;
3526                 offset = btrfs_node_blockptr(path.nodes[level],
3527                                              path.slots[level]);
3528
3529                 /* Remove the ptr */
3530                 ret = btrfs_del_ptr(trans, root, &path, level,
3531                                     path.slots[level]);
3532                 if (ret < 0)
3533                         goto out;
3534                 /*
3535                  * Remove the corresponding extent
3536                  * return value is not concerned.
3537                  */
3538                 btrfs_release_path(&path);
3539                 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
3540                                         0, root->root_key.objectid,
3541                                         level - 1, 0);
3542                 cache = next_cache_extent(cache);
3543         }
3544
3545         /* Balance the btree using btrfs_search_slot() */
3546         cache = first_cache_extent(corrupt_blocks);
3547         while (cache) {
3548                 corrupt = container_of(cache, struct btrfs_corrupt_block,
3549                                        cache);
3550                 memcpy(&key, &corrupt->key, sizeof(key));
3551                 ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
3552                 if (ret < 0)
3553                         goto out;
3554                 /* return will always >0 since it won't find the item */
3555                 ret = 0;
3556                 btrfs_release_path(&path);
3557                 cache = next_cache_extent(cache);
3558         }
3559 out:
3560         btrfs_commit_transaction(trans, root);
3561         btrfs_release_path(&path);
3562         return ret;
3563 }
3564
3565 static int check_fs_root(struct btrfs_root *root,
3566                          struct cache_tree *root_cache,
3567                          struct walk_control *wc)
3568 {
3569         int ret = 0;
3570         int err = 0;
3571         int wret;
3572         int level;
3573         struct btrfs_path path;
3574         struct shared_node root_node;
3575         struct root_record *rec;
3576         struct btrfs_root_item *root_item = &root->root_item;
3577         struct cache_tree corrupt_blocks;
3578         struct orphan_data_extent *orphan;
3579         struct orphan_data_extent *tmp;
3580         enum btrfs_tree_block_status status;
3581         struct node_refs nrefs;
3582
3583         /*
3584          * Reuse the corrupt_block cache tree to record corrupted tree block
3585          *
3586          * Unlike the usage in extent tree check, here we do it in a per
3587          * fs/subvol tree base.
3588          */
3589         cache_tree_init(&corrupt_blocks);
3590         root->fs_info->corrupt_blocks = &corrupt_blocks;
3591
3592         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
3593                 rec = get_root_rec(root_cache, root->root_key.objectid);
3594                 BUG_ON(IS_ERR(rec));
3595                 if (btrfs_root_refs(root_item) > 0)
3596                         rec->found_root_item = 1;
3597         }
3598
3599         btrfs_init_path(&path);
3600         memset(&root_node, 0, sizeof(root_node));
3601         cache_tree_init(&root_node.root_cache);
3602         cache_tree_init(&root_node.inode_cache);
3603         memset(&nrefs, 0, sizeof(nrefs));
3604
3605         /* Move the orphan extent record to corresponding inode_record */
3606         list_for_each_entry_safe(orphan, tmp,
3607                                  &root->orphan_data_extents, list) {
3608                 struct inode_record *inode;
3609
3610                 inode = get_inode_rec(&root_node.inode_cache, orphan->objectid,
3611                                       1);
3612                 BUG_ON(IS_ERR(inode));
3613                 inode->errors |= I_ERR_FILE_EXTENT_ORPHAN;
3614                 list_move(&orphan->list, &inode->orphan_extents);
3615         }
3616
3617         level = btrfs_header_level(root->node);
3618         memset(wc->nodes, 0, sizeof(wc->nodes));
3619         wc->nodes[level] = &root_node;
3620         wc->active_node = level;
3621         wc->root_level = level;
3622
3623         /* We may not have checked the root block, lets do that now */
3624         if (btrfs_is_leaf(root->node))
3625                 status = btrfs_check_leaf(root, NULL, root->node);
3626         else
3627                 status = btrfs_check_node(root, NULL, root->node);
3628         if (status != BTRFS_TREE_BLOCK_CLEAN)
3629                 return -EIO;
3630
3631         if (btrfs_root_refs(root_item) > 0 ||
3632             btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3633                 path.nodes[level] = root->node;
3634                 extent_buffer_get(root->node);
3635                 path.slots[level] = 0;
3636         } else {
3637                 struct btrfs_key key;
3638                 struct btrfs_disk_key found_key;
3639
3640                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
3641                 level = root_item->drop_level;
3642                 path.lowest_level = level;
3643                 if (level > btrfs_header_level(root->node) ||
3644                     level >= BTRFS_MAX_LEVEL) {
3645                         error("ignoring invalid drop level: %u", level);
3646                         goto skip_walking;
3647                 }
3648                 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
3649                 if (wret < 0)
3650                         goto skip_walking;
3651                 btrfs_node_key(path.nodes[level], &found_key,
3652                                 path.slots[level]);
3653                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3654                                         sizeof(found_key)));
3655         }
3656
3657         while (1) {
3658                 wret = walk_down_tree(root, &path, wc, &level, &nrefs);
3659                 if (wret < 0)
3660                         ret = wret;
3661                 if (wret != 0)
3662                         break;
3663
3664                 wret = walk_up_tree(root, &path, wc, &level);
3665                 if (wret < 0)
3666                         ret = wret;
3667                 if (wret != 0)
3668                         break;
3669         }
3670 skip_walking:
3671         btrfs_release_path(&path);
3672
3673         if (!cache_tree_empty(&corrupt_blocks)) {
3674                 struct cache_extent *cache;
3675                 struct btrfs_corrupt_block *corrupt;
3676
3677                 printf("The following tree block(s) is corrupted in tree %llu:\n",
3678                        root->root_key.objectid);
3679                 cache = first_cache_extent(&corrupt_blocks);
3680                 while (cache) {
3681                         corrupt = container_of(cache,
3682                                                struct btrfs_corrupt_block,
3683                                                cache);
3684                         printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3685                                cache->start, corrupt->level,
3686                                corrupt->key.objectid, corrupt->key.type,
3687                                corrupt->key.offset);
3688                         cache = next_cache_extent(cache);
3689                 }
3690                 if (repair) {
3691                         printf("Try to repair the btree for root %llu\n",
3692                                root->root_key.objectid);
3693                         ret = repair_btree(root, &corrupt_blocks);
3694                         if (ret < 0)
3695                                 fprintf(stderr, "Failed to repair btree: %s\n",
3696                                         strerror(-ret));
3697                         if (!ret)
3698                                 printf("Btree for root %llu is fixed\n",
3699                                        root->root_key.objectid);
3700                 }
3701         }
3702
3703         err = merge_root_recs(root, &root_node.root_cache, root_cache);
3704         if (err < 0)
3705                 ret = err;
3706
3707         if (root_node.current) {
3708                 root_node.current->checked = 1;
3709                 maybe_free_inode_rec(&root_node.inode_cache,
3710                                 root_node.current);
3711         }
3712
3713         err = check_inode_recs(root, &root_node.inode_cache);
3714         if (!ret)
3715                 ret = err;
3716
3717         free_corrupt_blocks_tree(&corrupt_blocks);
3718         root->fs_info->corrupt_blocks = NULL;
3719         free_orphan_data_extents(&root->orphan_data_extents);
3720         return ret;
3721 }
3722
3723 static int fs_root_objectid(u64 objectid)
3724 {
3725         if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3726             objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3727                 return 1;
3728         return is_fstree(objectid);
3729 }
3730
3731 static int check_fs_roots(struct btrfs_root *root,
3732                           struct cache_tree *root_cache)
3733 {
3734         struct btrfs_path path;
3735         struct btrfs_key key;
3736         struct walk_control wc;
3737         struct extent_buffer *leaf, *tree_node;
3738         struct btrfs_root *tmp_root;
3739         struct btrfs_root *tree_root = root->fs_info->tree_root;
3740         int ret;
3741         int err = 0;
3742
3743         if (ctx.progress_enabled) {
3744                 ctx.tp = TASK_FS_ROOTS;
3745                 task_start(ctx.info);
3746         }
3747
3748         /*
3749          * Just in case we made any changes to the extent tree that weren't
3750          * reflected into the free space cache yet.
3751          */
3752         if (repair)
3753                 reset_cached_block_groups(root->fs_info);
3754         memset(&wc, 0, sizeof(wc));
3755         cache_tree_init(&wc.shared);
3756         btrfs_init_path(&path);
3757
3758 again:
3759         key.offset = 0;
3760         key.objectid = 0;
3761         key.type = BTRFS_ROOT_ITEM_KEY;
3762         ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3763         if (ret < 0) {
3764                 err = 1;
3765                 goto out;
3766         }
3767         tree_node = tree_root->node;
3768         while (1) {
3769                 if (tree_node != tree_root->node) {
3770                         free_root_recs_tree(root_cache);
3771                         btrfs_release_path(&path);
3772                         goto again;
3773                 }
3774                 leaf = path.nodes[0];
3775                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3776                         ret = btrfs_next_leaf(tree_root, &path);
3777                         if (ret) {
3778                                 if (ret < 0)
3779                                         err = 1;
3780                                 break;
3781                         }
3782                         leaf = path.nodes[0];
3783                 }
3784                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3785                 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3786                     fs_root_objectid(key.objectid)) {
3787                         if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3788                                 tmp_root = btrfs_read_fs_root_no_cache(
3789                                                 root->fs_info, &key);
3790                         } else {
3791                                 key.offset = (u64)-1;
3792                                 tmp_root = btrfs_read_fs_root(
3793                                                 root->fs_info, &key);
3794                         }
3795                         if (IS_ERR(tmp_root)) {
3796                                 err = 1;
3797                                 goto next;
3798                         }
3799                         ret = check_fs_root(tmp_root, root_cache, &wc);
3800                         if (ret == -EAGAIN) {
3801                                 free_root_recs_tree(root_cache);
3802                                 btrfs_release_path(&path);
3803                                 goto again;
3804                         }
3805                         if (ret)
3806                                 err = 1;
3807                         if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3808                                 btrfs_free_fs_root(tmp_root);
3809                 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3810                            key.type == BTRFS_ROOT_BACKREF_KEY) {
3811                         process_root_ref(leaf, path.slots[0], &key,
3812                                          root_cache);
3813                 }
3814 next:
3815                 path.slots[0]++;
3816         }
3817 out:
3818         btrfs_release_path(&path);
3819         if (err)
3820                 free_extent_cache_tree(&wc.shared);
3821         if (!cache_tree_empty(&wc.shared))
3822                 fprintf(stderr, "warning line %d\n", __LINE__);
3823
3824         task_stop(ctx.info);
3825
3826         return err;
3827 }
3828
3829 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3830 {
3831         struct list_head *cur = rec->backrefs.next;
3832         struct extent_backref *back;
3833         struct tree_backref *tback;
3834         struct data_backref *dback;
3835         u64 found = 0;
3836         int err = 0;
3837
3838         while(cur != &rec->backrefs) {
3839                 back = to_extent_backref(cur);
3840                 cur = cur->next;
3841                 if (!back->found_extent_tree) {
3842                         err = 1;
3843                         if (!print_errs)
3844                                 goto out;
3845                         if (back->is_data) {
3846                                 dback = to_data_backref(back);
3847                                 fprintf(stderr, "Backref %llu %s %llu"
3848                                         " owner %llu offset %llu num_refs %lu"
3849                                         " not found in extent tree\n",
3850                                         (unsigned long long)rec->start,
3851                                         back->full_backref ?
3852                                         "parent" : "root",
3853                                         back->full_backref ?
3854                                         (unsigned long long)dback->parent:
3855                                         (unsigned long long)dback->root,
3856                                         (unsigned long long)dback->owner,
3857                                         (unsigned long long)dback->offset,
3858                                         (unsigned long)dback->num_refs);
3859                         } else {
3860                                 tback = to_tree_backref(back);
3861                                 fprintf(stderr, "Backref %llu parent %llu"
3862                                         " root %llu not found in extent tree\n",
3863                                         (unsigned long long)rec->start,
3864                                         (unsigned long long)tback->parent,
3865                                         (unsigned long long)tback->root);
3866                         }
3867                 }
3868                 if (!back->is_data && !back->found_ref) {
3869                         err = 1;
3870                         if (!print_errs)
3871                                 goto out;
3872                         tback = to_tree_backref(back);
3873                         fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3874                                 (unsigned long long)rec->start,
3875                                 back->full_backref ? "parent" : "root",
3876                                 back->full_backref ?
3877                                 (unsigned long long)tback->parent :
3878                                 (unsigned long long)tback->root, back);
3879                 }
3880                 if (back->is_data) {
3881                         dback = to_data_backref(back);
3882                         if (dback->found_ref != dback->num_refs) {
3883                                 err = 1;
3884                                 if (!print_errs)
3885                                         goto out;
3886                                 fprintf(stderr, "Incorrect local backref count"
3887                                         " on %llu %s %llu owner %llu"
3888                                         " offset %llu found %u wanted %u back %p\n",
3889                                         (unsigned long long)rec->start,
3890                                         back->full_backref ?
3891                                         "parent" : "root",
3892                                         back->full_backref ?
3893                                         (unsigned long long)dback->parent:
3894                                         (unsigned long long)dback->root,
3895                                         (unsigned long long)dback->owner,
3896                                         (unsigned long long)dback->offset,
3897                                         dback->found_ref, dback->num_refs, back);
3898                         }
3899                         if (dback->disk_bytenr != rec->start) {
3900                                 err = 1;
3901                                 if (!print_errs)
3902                                         goto out;
3903                                 fprintf(stderr, "Backref disk bytenr does not"
3904                                         " match extent record, bytenr=%llu, "
3905                                         "ref bytenr=%llu\n",
3906                                         (unsigned long long)rec->start,
3907                                         (unsigned long long)dback->disk_bytenr);
3908                         }
3909
3910                         if (dback->bytes != rec->nr) {
3911                                 err = 1;
3912                                 if (!print_errs)
3913                                         goto out;
3914                                 fprintf(stderr, "Backref bytes do not match "
3915                                         "extent backref, bytenr=%llu, ref "
3916                                         "bytes=%llu, backref bytes=%llu\n",
3917                                         (unsigned long long)rec->start,
3918                                         (unsigned long long)rec->nr,
3919                                         (unsigned long long)dback->bytes);
3920                         }
3921                 }
3922                 if (!back->is_data) {
3923                         found += 1;
3924                 } else {
3925                         dback = to_data_backref(back);
3926                         found += dback->found_ref;
3927                 }
3928         }
3929         if (found != rec->refs) {
3930                 err = 1;
3931                 if (!print_errs)
3932                         goto out;
3933                 fprintf(stderr, "Incorrect global backref count "
3934                         "on %llu found %llu wanted %llu\n",
3935                         (unsigned long long)rec->start,
3936                         (unsigned long long)found,
3937                         (unsigned long long)rec->refs);
3938         }
3939 out:
3940         return err;
3941 }
3942
3943 static int free_all_extent_backrefs(struct extent_record *rec)
3944 {
3945         struct extent_backref *back;
3946         struct list_head *cur;
3947         while (!list_empty(&rec->backrefs)) {
3948                 cur = rec->backrefs.next;
3949                 back = to_extent_backref(cur);
3950                 list_del(cur);
3951                 free(back);
3952         }
3953         return 0;
3954 }
3955
3956 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3957                                      struct cache_tree *extent_cache)
3958 {
3959         struct cache_extent *cache;
3960         struct extent_record *rec;
3961
3962         while (1) {
3963                 cache = first_cache_extent(extent_cache);
3964                 if (!cache)
3965                         break;
3966                 rec = container_of(cache, struct extent_record, cache);
3967                 remove_cache_extent(extent_cache, cache);
3968                 free_all_extent_backrefs(rec);
3969                 free(rec);
3970         }
3971 }
3972
3973 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3974                                  struct extent_record *rec)
3975 {
3976         if (rec->content_checked && rec->owner_ref_checked &&
3977             rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3978             rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0) &&
3979             !rec->bad_full_backref && !rec->crossing_stripes &&
3980             !rec->wrong_chunk_type) {
3981                 remove_cache_extent(extent_cache, &rec->cache);
3982                 free_all_extent_backrefs(rec);
3983                 list_del_init(&rec->list);
3984                 free(rec);
3985         }
3986         return 0;
3987 }
3988
3989 static int check_owner_ref(struct btrfs_root *root,
3990                             struct extent_record *rec,
3991                             struct extent_buffer *buf)
3992 {
3993         struct extent_backref *node;
3994         struct tree_backref *back;
3995         struct btrfs_root *ref_root;
3996         struct btrfs_key key;
3997         struct btrfs_path path;
3998         struct extent_buffer *parent;
3999         int level;
4000         int found = 0;
4001         int ret;
4002
4003         list_for_each_entry(node, &rec->backrefs, list) {
4004                 if (node->is_data)
4005                         continue;
4006                 if (!node->found_ref)
4007                         continue;
4008                 if (node->full_backref)
4009                         continue;
4010                 back = to_tree_backref(node);
4011                 if (btrfs_header_owner(buf) == back->root)
4012                         return 0;
4013         }
4014         BUG_ON(rec->is_root);
4015
4016         /* try to find the block by search corresponding fs tree */
4017         key.objectid = btrfs_header_owner(buf);
4018         key.type = BTRFS_ROOT_ITEM_KEY;
4019         key.offset = (u64)-1;
4020
4021         ref_root = btrfs_read_fs_root(root->fs_info, &key);
4022         if (IS_ERR(ref_root))
4023                 return 1;
4024
4025         level = btrfs_header_level(buf);
4026         if (level == 0)
4027                 btrfs_item_key_to_cpu(buf, &key, 0);
4028         else
4029                 btrfs_node_key_to_cpu(buf, &key, 0);
4030
4031         btrfs_init_path(&path);
4032         path.lowest_level = level + 1;
4033         ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
4034         if (ret < 0)
4035                 return 0;
4036
4037         parent = path.nodes[level + 1];
4038         if (parent && buf->start == btrfs_node_blockptr(parent,
4039                                                         path.slots[level + 1]))
4040                 found = 1;
4041
4042         btrfs_release_path(&path);
4043         return found ? 0 : 1;
4044 }
4045
4046 static int is_extent_tree_record(struct extent_record *rec)
4047 {
4048         struct list_head *cur = rec->backrefs.next;
4049         struct extent_backref *node;
4050         struct tree_backref *back;
4051         int is_extent = 0;
4052
4053         while(cur != &rec->backrefs) {
4054                 node = to_extent_backref(cur);
4055                 cur = cur->next;
4056                 if (node->is_data)
4057                         return 0;
4058                 back = to_tree_backref(node);
4059                 if (node->full_backref)
4060                         return 0;
4061                 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
4062                         is_extent = 1;
4063         }
4064         return is_extent;
4065 }
4066
4067
4068 static int record_bad_block_io(struct btrfs_fs_info *info,
4069                                struct cache_tree *extent_cache,
4070                                u64 start, u64 len)
4071 {
4072         struct extent_record *rec;
4073         struct cache_extent *cache;
4074         struct btrfs_key key;
4075
4076         cache = lookup_cache_extent(extent_cache, start, len);
4077         if (!cache)
4078                 return 0;
4079
4080         rec = container_of(cache, struct extent_record, cache);
4081         if (!is_extent_tree_record(rec))
4082                 return 0;
4083
4084         btrfs_disk_key_to_cpu(&key, &rec->parent_key);
4085         return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
4086 }
4087
4088 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
4089                        struct extent_buffer *buf, int slot)
4090 {
4091         if (btrfs_header_level(buf)) {
4092                 struct btrfs_key_ptr ptr1, ptr2;
4093
4094                 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
4095                                    sizeof(struct btrfs_key_ptr));
4096                 read_extent_buffer(buf, &ptr2,
4097                                    btrfs_node_key_ptr_offset(slot + 1),
4098                                    sizeof(struct btrfs_key_ptr));
4099                 write_extent_buffer(buf, &ptr1,
4100                                     btrfs_node_key_ptr_offset(slot + 1),
4101                                     sizeof(struct btrfs_key_ptr));
4102                 write_extent_buffer(buf, &ptr2,
4103                                     btrfs_node_key_ptr_offset(slot),
4104                                     sizeof(struct btrfs_key_ptr));
4105                 if (slot == 0) {
4106                         struct btrfs_disk_key key;
4107                         btrfs_node_key(buf, &key, 0);
4108                         btrfs_fixup_low_keys(root, path, &key,
4109                                              btrfs_header_level(buf) + 1);
4110                 }
4111         } else {
4112                 struct btrfs_item *item1, *item2;
4113                 struct btrfs_key k1, k2;
4114                 char *item1_data, *item2_data;
4115                 u32 item1_offset, item2_offset, item1_size, item2_size;
4116
4117                 item1 = btrfs_item_nr(slot);
4118                 item2 = btrfs_item_nr(slot + 1);
4119                 btrfs_item_key_to_cpu(buf, &k1, slot);
4120                 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
4121                 item1_offset = btrfs_item_offset(buf, item1);
4122                 item2_offset = btrfs_item_offset(buf, item2);
4123                 item1_size = btrfs_item_size(buf, item1);
4124                 item2_size = btrfs_item_size(buf, item2);
4125
4126                 item1_data = malloc(item1_size);
4127                 if (!item1_data)
4128                         return -ENOMEM;
4129                 item2_data = malloc(item2_size);
4130                 if (!item2_data) {
4131                         free(item1_data);
4132                         return -ENOMEM;
4133                 }
4134
4135                 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
4136                 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
4137
4138                 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
4139                 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
4140                 free(item1_data);
4141                 free(item2_data);
4142
4143                 btrfs_set_item_offset(buf, item1, item2_offset);
4144                 btrfs_set_item_offset(buf, item2, item1_offset);
4145                 btrfs_set_item_size(buf, item1, item2_size);
4146                 btrfs_set_item_size(buf, item2, item1_size);
4147
4148                 path->slots[0] = slot;
4149                 btrfs_set_item_key_unsafe(root, path, &k2);
4150                 path->slots[0] = slot + 1;
4151                 btrfs_set_item_key_unsafe(root, path, &k1);
4152         }
4153         return 0;
4154 }
4155
4156 static int fix_key_order(struct btrfs_trans_handle *trans,
4157                          struct btrfs_root *root,
4158                          struct btrfs_path *path)
4159 {
4160         struct extent_buffer *buf;
4161         struct btrfs_key k1, k2;
4162         int i;
4163         int level = path->lowest_level;
4164         int ret = -EIO;
4165
4166         buf = path->nodes[level];
4167         for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
4168                 if (level) {
4169                         btrfs_node_key_to_cpu(buf, &k1, i);
4170                         btrfs_node_key_to_cpu(buf, &k2, i + 1);
4171                 } else {
4172                         btrfs_item_key_to_cpu(buf, &k1, i);
4173                         btrfs_item_key_to_cpu(buf, &k2, i + 1);
4174                 }
4175                 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
4176                         continue;
4177                 ret = swap_values(root, path, buf, i);
4178                 if (ret)
4179                         break;
4180                 btrfs_mark_buffer_dirty(buf);
4181                 i = 0;
4182         }
4183         return ret;
4184 }
4185
4186 static int delete_bogus_item(struct btrfs_trans_handle *trans,
4187                              struct btrfs_root *root,
4188                              struct btrfs_path *path,
4189                              struct extent_buffer *buf, int slot)
4190 {
4191         struct btrfs_key key;
4192         int nritems = btrfs_header_nritems(buf);
4193
4194         btrfs_item_key_to_cpu(buf, &key, slot);
4195
4196         /* These are all the keys we can deal with missing. */
4197         if (key.type != BTRFS_DIR_INDEX_KEY &&
4198             key.type != BTRFS_EXTENT_ITEM_KEY &&
4199             key.type != BTRFS_METADATA_ITEM_KEY &&
4200             key.type != BTRFS_TREE_BLOCK_REF_KEY &&
4201             key.type != BTRFS_EXTENT_DATA_REF_KEY)
4202                 return -1;
4203
4204         printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
4205                (unsigned long long)key.objectid, key.type,
4206                (unsigned long long)key.offset, slot, buf->start);
4207         memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
4208                               btrfs_item_nr_offset(slot + 1),
4209                               sizeof(struct btrfs_item) *
4210                               (nritems - slot - 1));
4211         btrfs_set_header_nritems(buf, nritems - 1);
4212         if (slot == 0) {
4213                 struct btrfs_disk_key disk_key;
4214
4215                 btrfs_item_key(buf, &disk_key, 0);
4216                 btrfs_fixup_low_keys(root, path, &disk_key, 1);
4217         }
4218         btrfs_mark_buffer_dirty(buf);
4219         return 0;
4220 }
4221
4222 static int fix_item_offset(struct btrfs_trans_handle *trans,
4223                            struct btrfs_root *root,
4224                            struct btrfs_path *path)
4225 {
4226         struct extent_buffer *buf;
4227         int i;
4228         int ret = 0;
4229
4230         /* We should only get this for leaves */
4231         BUG_ON(path->lowest_level);
4232         buf = path->nodes[0];
4233 again:
4234         for (i = 0; i < btrfs_header_nritems(buf); i++) {
4235                 unsigned int shift = 0, offset;
4236
4237                 if (i == 0 && btrfs_item_end_nr(buf, i) !=
4238                     BTRFS_LEAF_DATA_SIZE(root)) {
4239                         if (btrfs_item_end_nr(buf, i) >
4240                             BTRFS_LEAF_DATA_SIZE(root)) {
4241                                 ret = delete_bogus_item(trans, root, path,
4242                                                         buf, i);
4243                                 if (!ret)
4244                                         goto again;
4245                                 fprintf(stderr, "item is off the end of the "
4246                                         "leaf, can't fix\n");
4247                                 ret = -EIO;
4248                                 break;
4249                         }
4250                         shift = BTRFS_LEAF_DATA_SIZE(root) -
4251                                 btrfs_item_end_nr(buf, i);
4252                 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
4253                            btrfs_item_offset_nr(buf, i - 1)) {
4254                         if (btrfs_item_end_nr(buf, i) >
4255                             btrfs_item_offset_nr(buf, i - 1)) {
4256                                 ret = delete_bogus_item(trans, root, path,
4257                                                         buf, i);
4258                                 if (!ret)
4259                                         goto again;
4260                                 fprintf(stderr, "items overlap, can't fix\n");
4261                                 ret = -EIO;
4262                                 break;
4263                         }
4264                         shift = btrfs_item_offset_nr(buf, i - 1) -
4265                                 btrfs_item_end_nr(buf, i);
4266                 }
4267                 if (!shift)
4268                         continue;
4269
4270                 printf("Shifting item nr %d by %u bytes in block %llu\n",
4271                        i, shift, (unsigned long long)buf->start);
4272                 offset = btrfs_item_offset_nr(buf, i);
4273                 memmove_extent_buffer(buf,
4274                                       btrfs_leaf_data(buf) + offset + shift,
4275                                       btrfs_leaf_data(buf) + offset,
4276                                       btrfs_item_size_nr(buf, i));
4277                 btrfs_set_item_offset(buf, btrfs_item_nr(i),
4278                                       offset + shift);
4279                 btrfs_mark_buffer_dirty(buf);
4280         }
4281
4282         /*
4283          * We may have moved things, in which case we want to exit so we don't
4284          * write those changes out.  Once we have proper abort functionality in
4285          * progs this can be changed to something nicer.
4286          */
4287         BUG_ON(ret);
4288         return ret;
4289 }
4290
4291 /*
4292  * Attempt to fix basic block failures.  If we can't fix it for whatever reason
4293  * then just return -EIO.
4294  */
4295 static int try_to_fix_bad_block(struct btrfs_root *root,
4296                                 struct extent_buffer *buf,
4297                                 enum btrfs_tree_block_status status)
4298 {
4299         struct btrfs_trans_handle *trans;
4300         struct ulist *roots;
4301         struct ulist_node *node;
4302         struct btrfs_root *search_root;
4303         struct btrfs_path path;
4304         struct ulist_iterator iter;
4305         struct btrfs_key root_key, key;
4306         int ret;
4307
4308         if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
4309             status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4310                 return -EIO;
4311
4312         ret = btrfs_find_all_roots(NULL, root->fs_info, buf->start, 0, &roots);
4313         if (ret)
4314                 return -EIO;
4315
4316         btrfs_init_path(&path);
4317         ULIST_ITER_INIT(&iter);
4318         while ((node = ulist_next(roots, &iter))) {
4319                 root_key.objectid = node->val;
4320                 root_key.type = BTRFS_ROOT_ITEM_KEY;
4321                 root_key.offset = (u64)-1;
4322
4323                 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
4324                 if (IS_ERR(root)) {
4325                         ret = -EIO;
4326                         break;
4327                 }
4328
4329
4330                 trans = btrfs_start_transaction(search_root, 0);
4331                 if (IS_ERR(trans)) {
4332                         ret = PTR_ERR(trans);
4333                         break;
4334                 }
4335
4336                 path.lowest_level = btrfs_header_level(buf);
4337                 path.skip_check_block = 1;
4338                 if (path.lowest_level)
4339                         btrfs_node_key_to_cpu(buf, &key, 0);
4340                 else
4341                         btrfs_item_key_to_cpu(buf, &key, 0);
4342                 ret = btrfs_search_slot(trans, search_root, &key, &path, 0, 1);
4343                 if (ret) {
4344                         ret = -EIO;
4345                         btrfs_commit_transaction(trans, search_root);
4346                         break;
4347                 }
4348                 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
4349                         ret = fix_key_order(trans, search_root, &path);
4350                 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
4351                         ret = fix_item_offset(trans, search_root, &path);
4352                 if (ret) {
4353                         btrfs_commit_transaction(trans, search_root);
4354                         break;
4355                 }
4356                 btrfs_release_path(&path);
4357                 btrfs_commit_transaction(trans, search_root);
4358         }
4359         ulist_free(roots);
4360         btrfs_release_path(&path);
4361         return ret;
4362 }
4363
4364 static int check_block(struct btrfs_root *root,
4365                        struct cache_tree *extent_cache,
4366                        struct extent_buffer *buf, u64 flags)
4367 {
4368         struct extent_record *rec;
4369         struct cache_extent *cache;
4370         struct btrfs_key key;
4371         enum btrfs_tree_block_status status;
4372         int ret = 0;
4373         int level;
4374
4375         cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
4376         if (!cache)
4377                 return 1;
4378         rec = container_of(cache, struct extent_record, cache);
4379         rec->generation = btrfs_header_generation(buf);
4380
4381         level = btrfs_header_level(buf);
4382         if (btrfs_header_nritems(buf) > 0) {
4383
4384                 if (level == 0)
4385                         btrfs_item_key_to_cpu(buf, &key, 0);
4386                 else
4387                         btrfs_node_key_to_cpu(buf, &key, 0);
4388
4389                 rec->info_objectid = key.objectid;
4390         }
4391         rec->info_level = level;
4392
4393         if (btrfs_is_leaf(buf))
4394                 status = btrfs_check_leaf(root, &rec->parent_key, buf);
4395         else
4396                 status = btrfs_check_node(root, &rec->parent_key, buf);
4397
4398         if (status != BTRFS_TREE_BLOCK_CLEAN) {
4399                 if (repair)
4400                         status = try_to_fix_bad_block(root, buf, status);
4401                 if (status != BTRFS_TREE_BLOCK_CLEAN) {
4402                         ret = -EIO;
4403                         fprintf(stderr, "bad block %llu\n",
4404                                 (unsigned long long)buf->start);
4405                 } else {
4406                         /*
4407                          * Signal to callers we need to start the scan over
4408                          * again since we'll have cowed blocks.
4409                          */
4410                         ret = -EAGAIN;
4411                 }
4412         } else {
4413                 rec->content_checked = 1;
4414                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
4415                         rec->owner_ref_checked = 1;
4416                 else {
4417                         ret = check_owner_ref(root, rec, buf);
4418                         if (!ret)
4419                                 rec->owner_ref_checked = 1;
4420                 }
4421         }
4422         if (!ret)
4423                 maybe_free_extent_rec(extent_cache, rec);
4424         return ret;
4425 }
4426
4427 static struct tree_backref *find_tree_backref(struct extent_record *rec,
4428                                                 u64 parent, u64 root)
4429 {
4430         struct list_head *cur = rec->backrefs.next;
4431         struct extent_backref *node;
4432         struct tree_backref *back;
4433
4434         while(cur != &rec->backrefs) {
4435                 node = to_extent_backref(cur);
4436                 cur = cur->next;
4437                 if (node->is_data)
4438                         continue;
4439                 back = to_tree_backref(node);
4440                 if (parent > 0) {
4441                         if (!node->full_backref)
4442                                 continue;
4443                         if (parent == back->parent)
4444                                 return back;
4445                 } else {
4446                         if (node->full_backref)
4447                                 continue;
4448                         if (back->root == root)
4449                                 return back;
4450                 }
4451         }
4452         return NULL;
4453 }
4454
4455 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
4456                                                 u64 parent, u64 root)
4457 {
4458         struct tree_backref *ref = malloc(sizeof(*ref));
4459
4460         if (!ref)
4461                 return NULL;
4462         memset(&ref->node, 0, sizeof(ref->node));
4463         if (parent > 0) {
4464                 ref->parent = parent;
4465                 ref->node.full_backref = 1;
4466         } else {
4467                 ref->root = root;
4468                 ref->node.full_backref = 0;
4469         }
4470         list_add_tail(&ref->node.list, &rec->backrefs);
4471
4472         return ref;
4473 }
4474
4475 static struct data_backref *find_data_backref(struct extent_record *rec,
4476                                                 u64 parent, u64 root,
4477                                                 u64 owner, u64 offset,
4478                                                 int found_ref,
4479                                                 u64 disk_bytenr, u64 bytes)
4480 {
4481         struct list_head *cur = rec->backrefs.next;
4482         struct extent_backref *node;
4483         struct data_backref *back;
4484
4485         while(cur != &rec->backrefs) {
4486                 node = to_extent_backref(cur);
4487                 cur = cur->next;
4488                 if (!node->is_data)
4489                         continue;
4490                 back = to_data_backref(node);
4491                 if (parent > 0) {
4492                         if (!node->full_backref)
4493                                 continue;
4494                         if (parent == back->parent)
4495                                 return back;
4496                 } else {
4497                         if (node->full_backref)
4498                                 continue;
4499                         if (back->root == root && back->owner == owner &&
4500                             back->offset == offset) {
4501                                 if (found_ref && node->found_ref &&
4502                                     (back->bytes != bytes ||
4503                                     back->disk_bytenr != disk_bytenr))
4504                                         continue;
4505                                 return back;
4506                         }
4507                 }
4508         }
4509         return NULL;
4510 }
4511
4512 static struct data_backref *alloc_data_backref(struct extent_record *rec,
4513                                                 u64 parent, u64 root,
4514                                                 u64 owner, u64 offset,
4515                                                 u64 max_size)
4516 {
4517         struct data_backref *ref = malloc(sizeof(*ref));
4518
4519         if (!ref)
4520                 return NULL;
4521         memset(&ref->node, 0, sizeof(ref->node));
4522         ref->node.is_data = 1;
4523
4524         if (parent > 0) {
4525                 ref->parent = parent;
4526                 ref->owner = 0;
4527                 ref->offset = 0;
4528                 ref->node.full_backref = 1;
4529         } else {
4530                 ref->root = root;
4531                 ref->owner = owner;
4532                 ref->offset = offset;
4533                 ref->node.full_backref = 0;
4534         }
4535         ref->bytes = max_size;
4536         ref->found_ref = 0;
4537         ref->num_refs = 0;
4538         list_add_tail(&ref->node.list, &rec->backrefs);
4539         if (max_size > rec->max_size)
4540                 rec->max_size = max_size;
4541         return ref;
4542 }
4543
4544 /* Check if the type of extent matches with its chunk */
4545 static void check_extent_type(struct extent_record *rec)
4546 {
4547         struct btrfs_block_group_cache *bg_cache;
4548
4549         bg_cache = btrfs_lookup_first_block_group(global_info, rec->start);
4550         if (!bg_cache)
4551                 return;
4552
4553         /* data extent, check chunk directly*/
4554         if (!rec->metadata) {
4555                 if (!(bg_cache->flags & BTRFS_BLOCK_GROUP_DATA))
4556                         rec->wrong_chunk_type = 1;
4557                 return;
4558         }
4559
4560         /* metadata extent, check the obvious case first */
4561         if (!(bg_cache->flags & (BTRFS_BLOCK_GROUP_SYSTEM |
4562                                  BTRFS_BLOCK_GROUP_METADATA))) {
4563                 rec->wrong_chunk_type = 1;
4564                 return;
4565         }
4566
4567         /*
4568          * Check SYSTEM extent, as it's also marked as metadata, we can only
4569          * make sure it's a SYSTEM extent by its backref
4570          */
4571         if (!list_empty(&rec->backrefs)) {
4572                 struct extent_backref *node;
4573                 struct tree_backref *tback;
4574                 u64 bg_type;
4575
4576                 node = to_extent_backref(rec->backrefs.next);
4577                 if (node->is_data) {
4578                         /* tree block shouldn't have data backref */
4579                         rec->wrong_chunk_type = 1;
4580                         return;
4581                 }
4582                 tback = container_of(node, struct tree_backref, node);
4583
4584                 if (tback->root == BTRFS_CHUNK_TREE_OBJECTID)
4585                         bg_type = BTRFS_BLOCK_GROUP_SYSTEM;
4586                 else
4587                         bg_type = BTRFS_BLOCK_GROUP_METADATA;
4588                 if (!(bg_cache->flags & bg_type))
4589                         rec->wrong_chunk_type = 1;
4590         }
4591 }
4592
4593 /*
4594  * Allocate a new extent record, fill default values from @tmpl and insert int
4595  * @extent_cache. Caller is supposed to make sure the [start,nr) is not in
4596  * the cache, otherwise it fails.
4597  */
4598 static int add_extent_rec_nolookup(struct cache_tree *extent_cache,
4599                 struct extent_record *tmpl)
4600 {
4601         struct extent_record *rec;
4602         int ret = 0;
4603
4604         rec = malloc(sizeof(*rec));
4605         if (!rec)
4606                 return -ENOMEM;
4607         rec->start = tmpl->start;
4608         rec->max_size = tmpl->max_size;
4609         rec->nr = max(tmpl->nr, tmpl->max_size);
4610         rec->found_rec = tmpl->found_rec;
4611         rec->content_checked = tmpl->content_checked;
4612         rec->owner_ref_checked = tmpl->owner_ref_checked;
4613         rec->num_duplicates = 0;
4614         rec->metadata = tmpl->metadata;
4615         rec->flag_block_full_backref = FLAG_UNSET;
4616         rec->bad_full_backref = 0;
4617         rec->crossing_stripes = 0;
4618         rec->wrong_chunk_type = 0;
4619         rec->is_root = tmpl->is_root;
4620         rec->refs = tmpl->refs;
4621         rec->extent_item_refs = tmpl->extent_item_refs;
4622         rec->parent_generation = tmpl->parent_generation;
4623         INIT_LIST_HEAD(&rec->backrefs);
4624         INIT_LIST_HEAD(&rec->dups);
4625         INIT_LIST_HEAD(&rec->list);
4626         memcpy(&rec->parent_key, &tmpl->parent_key, sizeof(tmpl->parent_key));
4627         rec->cache.start = tmpl->start;
4628         rec->cache.size = tmpl->nr;
4629         ret = insert_cache_extent(extent_cache, &rec->cache);
4630         if (ret) {
4631                 free(rec);
4632                 return ret;
4633         }
4634         bytes_used += rec->nr;
4635
4636         if (tmpl->metadata)
4637                 rec->crossing_stripes = check_crossing_stripes(global_info,
4638                                 rec->start, global_info->tree_root->nodesize);
4639         check_extent_type(rec);
4640         return ret;
4641 }
4642
4643 /*
4644  * Lookup and modify an extent, some values of @tmpl are interpreted verbatim,
4645  * some are hints:
4646  * - refs              - if found, increase refs
4647  * - is_root           - if found, set
4648  * - content_checked   - if found, set
4649  * - owner_ref_checked - if found, set
4650  *
4651  * If not found, create a new one, initialize and insert.
4652  */
4653 static int add_extent_rec(struct cache_tree *extent_cache,
4654                 struct extent_record *tmpl)
4655 {
4656         struct extent_record *rec;
4657         struct cache_extent *cache;
4658         int ret = 0;
4659         int dup = 0;
4660
4661         cache = lookup_cache_extent(extent_cache, tmpl->start, tmpl->nr);
4662         if (cache) {
4663                 rec = container_of(cache, struct extent_record, cache);
4664                 if (tmpl->refs)
4665                         rec->refs++;
4666                 if (rec->nr == 1)
4667                         rec->nr = max(tmpl->nr, tmpl->max_size);
4668
4669                 /*
4670                  * We need to make sure to reset nr to whatever the extent
4671                  * record says was the real size, this way we can compare it to
4672                  * the backrefs.
4673                  */
4674                 if (tmpl->found_rec) {
4675                         if (tmpl->start != rec->start || rec->found_rec) {
4676                                 struct extent_record *tmp;
4677
4678                                 dup = 1;
4679                                 if (list_empty(&rec->list))
4680                                         list_add_tail(&rec->list,
4681                                                       &duplicate_extents);
4682
4683                                 /*
4684                                  * We have to do this song and dance in case we
4685                                  * find an extent record that falls inside of
4686                                  * our current extent record but does not have
4687                                  * the same objectid.
4688                                  */
4689                                 tmp = malloc(sizeof(*tmp));
4690                                 if (!tmp)
4691                                         return -ENOMEM;
4692                                 tmp->start = tmpl->start;
4693                                 tmp->max_size = tmpl->max_size;
4694                                 tmp->nr = tmpl->nr;
4695                                 tmp->found_rec = 1;
4696                                 tmp->metadata = tmpl->metadata;
4697                                 tmp->extent_item_refs = tmpl->extent_item_refs;
4698                                 INIT_LIST_HEAD(&tmp->list);
4699                                 list_add_tail(&tmp->list, &rec->dups);
4700                                 rec->num_duplicates++;
4701                         } else {
4702                                 rec->nr = tmpl->nr;
4703                                 rec->found_rec = 1;
4704                         }
4705                 }
4706
4707                 if (tmpl->extent_item_refs && !dup) {
4708                         if (rec->extent_item_refs) {
4709                                 fprintf(stderr, "block %llu rec "
4710                                         "extent_item_refs %llu, passed %llu\n",
4711                                         (unsigned long long)tmpl->start,
4712                                         (unsigned long long)
4713                                                         rec->extent_item_refs,
4714                                         (unsigned long long)tmpl->extent_item_refs);
4715                         }
4716                         rec->extent_item_refs = tmpl->extent_item_refs;
4717                 }
4718                 if (tmpl->is_root)
4719                         rec->is_root = 1;
4720                 if (tmpl->content_checked)
4721                         rec->content_checked = 1;
4722                 if (tmpl->owner_ref_checked)
4723                         rec->owner_ref_checked = 1;
4724                 memcpy(&rec->parent_key, &tmpl->parent_key,
4725                                 sizeof(tmpl->parent_key));
4726                 if (tmpl->parent_generation)
4727                         rec->parent_generation = tmpl->parent_generation;
4728                 if (rec->max_size < tmpl->max_size)
4729                         rec->max_size = tmpl->max_size;
4730
4731                 /*
4732                  * A metadata extent can't cross stripe_len boundary, otherwise
4733                  * kernel scrub won't be able to handle it.
4734                  * As now stripe_len is fixed to BTRFS_STRIPE_LEN, just check
4735                  * it.
4736                  */
4737                 if (tmpl->metadata)
4738                         rec->crossing_stripes = check_crossing_stripes(
4739                                         global_info, rec->start,
4740                                         global_info->tree_root->nodesize);
4741                 check_extent_type(rec);
4742                 maybe_free_extent_rec(extent_cache, rec);
4743                 return ret;
4744         }
4745
4746         ret = add_extent_rec_nolookup(extent_cache, tmpl);
4747
4748         return ret;
4749 }
4750
4751 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
4752                             u64 parent, u64 root, int found_ref)
4753 {
4754         struct extent_record *rec;
4755         struct tree_backref *back;
4756         struct cache_extent *cache;
4757         int ret;
4758
4759         cache = lookup_cache_extent(extent_cache, bytenr, 1);
4760         if (!cache) {
4761                 struct extent_record tmpl;
4762
4763                 memset(&tmpl, 0, sizeof(tmpl));
4764                 tmpl.start = bytenr;
4765                 tmpl.nr = 1;
4766                 tmpl.metadata = 1;
4767
4768                 ret = add_extent_rec_nolookup(extent_cache, &tmpl);
4769                 if (ret)
4770                         return ret;
4771
4772                 /* really a bug in cache_extent implement now */
4773                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4774                 if (!cache)
4775                         return -ENOENT;
4776         }
4777
4778         rec = container_of(cache, struct extent_record, cache);
4779         if (rec->start != bytenr) {
4780                 /*
4781                  * Several cause, from unaligned bytenr to over lapping extents
4782                  */
4783                 return -EEXIST;
4784         }
4785
4786         back = find_tree_backref(rec, parent, root);
4787         if (!back) {
4788                 back = alloc_tree_backref(rec, parent, root);
4789                 if (!back)
4790                         return -ENOMEM;
4791         }
4792
4793         if (found_ref) {
4794                 if (back->node.found_ref) {
4795                         fprintf(stderr, "Extent back ref already exists "
4796                                 "for %llu parent %llu root %llu \n",
4797                                 (unsigned long long)bytenr,
4798                                 (unsigned long long)parent,
4799                                 (unsigned long long)root);
4800                 }
4801                 back->node.found_ref = 1;
4802         } else {
4803                 if (back->node.found_extent_tree) {
4804                         fprintf(stderr, "Extent back ref already exists "
4805                                 "for %llu parent %llu root %llu \n",
4806                                 (unsigned long long)bytenr,
4807                                 (unsigned long long)parent,
4808                                 (unsigned long long)root);
4809                 }
4810                 back->node.found_extent_tree = 1;
4811         }
4812         check_extent_type(rec);
4813         maybe_free_extent_rec(extent_cache, rec);
4814         return 0;
4815 }
4816
4817 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4818                             u64 parent, u64 root, u64 owner, u64 offset,
4819                             u32 num_refs, int found_ref, u64 max_size)
4820 {
4821         struct extent_record *rec;
4822         struct data_backref *back;
4823         struct cache_extent *cache;
4824         int ret;
4825
4826         cache = lookup_cache_extent(extent_cache, bytenr, 1);
4827         if (!cache) {
4828                 struct extent_record tmpl;
4829
4830                 memset(&tmpl, 0, sizeof(tmpl));
4831                 tmpl.start = bytenr;
4832                 tmpl.nr = 1;
4833                 tmpl.max_size = max_size;
4834
4835                 ret = add_extent_rec_nolookup(extent_cache, &tmpl);
4836                 if (ret)
4837                         return ret;
4838
4839                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4840                 if (!cache)
4841                         abort();
4842         }
4843
4844         rec = container_of(cache, struct extent_record, cache);
4845         if (rec->max_size < max_size)
4846                 rec->max_size = max_size;
4847
4848         /*
4849          * If found_ref is set then max_size is the real size and must match the
4850          * existing refs.  So if we have already found a ref then we need to
4851          * make sure that this ref matches the existing one, otherwise we need
4852          * to add a new backref so we can notice that the backrefs don't match
4853          * and we need to figure out who is telling the truth.  This is to
4854          * account for that awful fsync bug I introduced where we'd end up with
4855          * a btrfs_file_extent_item that would have its length include multiple
4856          * prealloc extents or point inside of a prealloc extent.
4857          */
4858         back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4859                                  bytenr, max_size);
4860         if (!back) {
4861                 back = alloc_data_backref(rec, parent, root, owner, offset,
4862                                           max_size);
4863                 BUG_ON(!back);
4864         }
4865
4866         if (found_ref) {
4867                 BUG_ON(num_refs != 1);
4868                 if (back->node.found_ref)
4869                         BUG_ON(back->bytes != max_size);
4870                 back->node.found_ref = 1;
4871                 back->found_ref += 1;
4872                 back->bytes = max_size;
4873                 back->disk_bytenr = bytenr;
4874                 rec->refs += 1;
4875                 rec->content_checked = 1;
4876                 rec->owner_ref_checked = 1;
4877         } else {
4878                 if (back->node.found_extent_tree) {
4879                         fprintf(stderr, "Extent back ref already exists "
4880                                 "for %llu parent %llu root %llu "
4881                                 "owner %llu offset %llu num_refs %lu\n",
4882                                 (unsigned long long)bytenr,
4883                                 (unsigned long long)parent,
4884                                 (unsigned long long)root,
4885                                 (unsigned long long)owner,
4886                                 (unsigned long long)offset,
4887                                 (unsigned long)num_refs);
4888                 }
4889                 back->num_refs = num_refs;
4890                 back->node.found_extent_tree = 1;
4891         }
4892         maybe_free_extent_rec(extent_cache, rec);
4893         return 0;
4894 }
4895
4896 static int add_pending(struct cache_tree *pending,
4897                        struct cache_tree *seen, u64 bytenr, u32 size)
4898 {
4899         int ret;
4900         ret = add_cache_extent(seen, bytenr, size);
4901         if (ret)
4902                 return ret;
4903         add_cache_extent(pending, bytenr, size);
4904         return 0;
4905 }
4906
4907 static int pick_next_pending(struct cache_tree *pending,
4908                         struct cache_tree *reada,
4909                         struct cache_tree *nodes,
4910                         u64 last, struct block_info *bits, int bits_nr,
4911                         int *reada_bits)
4912 {
4913         unsigned long node_start = last;
4914         struct cache_extent *cache;
4915         int ret;
4916
4917         cache = search_cache_extent(reada, 0);
4918         if (cache) {
4919                 bits[0].start = cache->start;
4920                 bits[0].size = cache->size;
4921                 *reada_bits = 1;
4922                 return 1;
4923         }
4924         *reada_bits = 0;
4925         if (node_start > 32768)
4926                 node_start -= 32768;
4927
4928         cache = search_cache_extent(nodes, node_start);
4929         if (!cache)
4930                 cache = search_cache_extent(nodes, 0);
4931
4932         if (!cache) {
4933                  cache = search_cache_extent(pending, 0);
4934                  if (!cache)
4935                          return 0;
4936                  ret = 0;
4937                  do {
4938                          bits[ret].start = cache->start;
4939                          bits[ret].size = cache->size;
4940                          cache = next_cache_extent(cache);
4941                          ret++;
4942                  } while (cache && ret < bits_nr);
4943                  return ret;
4944         }
4945
4946         ret = 0;
4947         do {
4948                 bits[ret].start = cache->start;
4949                 bits[ret].size = cache->size;
4950                 cache = next_cache_extent(cache);
4951                 ret++;
4952         } while (cache && ret < bits_nr);
4953
4954         if (bits_nr - ret > 8) {
4955                 u64 lookup = bits[0].start + bits[0].size;
4956                 struct cache_extent *next;
4957                 next = search_cache_extent(pending, lookup);
4958                 while(next) {
4959                         if (next->start - lookup > 32768)
4960                                 break;
4961                         bits[ret].start = next->start;
4962                         bits[ret].size = next->size;
4963                         lookup = next->start + next->size;
4964                         ret++;
4965                         if (ret == bits_nr)
4966                                 break;
4967                         next = next_cache_extent(next);
4968                         if (!next)
4969                                 break;
4970                 }
4971         }
4972         return ret;
4973 }
4974
4975 static void free_chunk_record(struct cache_extent *cache)
4976 {
4977         struct chunk_record *rec;
4978
4979         rec = container_of(cache, struct chunk_record, cache);
4980         list_del_init(&rec->list);
4981         list_del_init(&rec->dextents);
4982         free(rec);
4983 }
4984
4985 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4986 {
4987         cache_tree_free_extents(chunk_cache, free_chunk_record);
4988 }
4989
4990 static void free_device_record(struct rb_node *node)
4991 {
4992         struct device_record *rec;
4993
4994         rec = container_of(node, struct device_record, node);
4995         free(rec);
4996 }
4997
4998 FREE_RB_BASED_TREE(device_cache, free_device_record);
4999
5000 int insert_block_group_record(struct block_group_tree *tree,
5001                               struct block_group_record *bg_rec)
5002 {
5003         int ret;
5004
5005         ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
5006         if (ret)
5007                 return ret;
5008
5009         list_add_tail(&bg_rec->list, &tree->block_groups);
5010         return 0;
5011 }
5012
5013 static void free_block_group_record(struct cache_extent *cache)
5014 {
5015         struct block_group_record *rec;
5016
5017         rec = container_of(cache, struct block_group_record, cache);
5018         list_del_init(&rec->list);
5019         free(rec);
5020 }
5021
5022 void free_block_group_tree(struct block_group_tree *tree)
5023 {
5024         cache_tree_free_extents(&tree->tree, free_block_group_record);
5025 }
5026
5027 int insert_device_extent_record(struct device_extent_tree *tree,
5028                                 struct device_extent_record *de_rec)
5029 {
5030         int ret;
5031
5032         /*
5033          * Device extent is a bit different from the other extents, because
5034          * the extents which belong to the different devices may have the
5035          * same start and size, so we need use the special extent cache
5036          * search/insert functions.
5037          */
5038         ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
5039         if (ret)
5040                 return ret;
5041
5042         list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
5043         list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
5044         return 0;
5045 }
5046
5047 static void free_device_extent_record(struct cache_extent *cache)
5048 {
5049         struct device_extent_record *rec;
5050
5051         rec = container_of(cache, struct device_extent_record, cache);
5052         if (!list_empty(&rec->chunk_list))
5053                 list_del_init(&rec->chunk_list);
5054         if (!list_empty(&rec->device_list))
5055                 list_del_init(&rec->device_list);
5056         free(rec);
5057 }
5058
5059 void free_device_extent_tree(struct device_extent_tree *tree)
5060 {
5061         cache_tree_free_extents(&tree->tree, free_device_extent_record);
5062 }
5063
5064 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5065 static int process_extent_ref_v0(struct cache_tree *extent_cache,
5066                                  struct extent_buffer *leaf, int slot)
5067 {
5068         struct btrfs_extent_ref_v0 *ref0;
5069         struct btrfs_key key;
5070         int ret;
5071
5072         btrfs_item_key_to_cpu(leaf, &key, slot);
5073         ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
5074         if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
5075                 ret = add_tree_backref(extent_cache, key.objectid, key.offset,
5076                                 0, 0);
5077         } else {
5078                 ret = add_data_backref(extent_cache, key.objectid, key.offset,
5079                                 0, 0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
5080         }
5081         return ret;
5082 }
5083 #endif
5084
5085 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
5086                                             struct btrfs_key *key,
5087                                             int slot)
5088 {
5089         struct btrfs_chunk *ptr;
5090         struct chunk_record *rec;
5091         int num_stripes, i;
5092
5093         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
5094         num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
5095
5096         rec = calloc(1, btrfs_chunk_record_size(num_stripes));
5097         if (!rec) {
5098                 fprintf(stderr, "memory allocation failed\n");
5099                 exit(-1);
5100         }
5101
5102         INIT_LIST_HEAD(&rec->list);
5103         INIT_LIST_HEAD(&rec->dextents);
5104         rec->bg_rec = NULL;
5105
5106         rec->cache.start = key->offset;
5107         rec->cache.size = btrfs_chunk_length(leaf, ptr);
5108
5109         rec->generation = btrfs_header_generation(leaf);
5110
5111         rec->objectid = key->objectid;
5112         rec->type = key->type;
5113         rec->offset = key->offset;
5114
5115         rec->length = rec->cache.size;
5116         rec->owner = btrfs_chunk_owner(leaf, ptr);
5117         rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
5118         rec->type_flags = btrfs_chunk_type(leaf, ptr);
5119         rec->io_width = btrfs_chunk_io_width(leaf, ptr);
5120         rec->io_align = btrfs_chunk_io_align(leaf, ptr);
5121         rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
5122         rec->num_stripes = num_stripes;
5123         rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
5124
5125         for (i = 0; i < rec->num_stripes; ++i) {
5126                 rec->stripes[i].devid =
5127                         btrfs_stripe_devid_nr(leaf, ptr, i);
5128                 rec->stripes[i].offset =
5129                         btrfs_stripe_offset_nr(leaf, ptr, i);
5130                 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
5131                                 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
5132                                 BTRFS_UUID_SIZE);
5133         }
5134
5135         return rec;
5136 }
5137
5138 static int process_chunk_item(struct cache_tree *chunk_cache,
5139                               struct btrfs_key *key, struct extent_buffer *eb,
5140                               int slot)
5141 {
5142         struct chunk_record *rec;
5143         struct btrfs_chunk *chunk;
5144         int ret = 0;
5145
5146         chunk = btrfs_item_ptr(eb, slot, struct btrfs_chunk);
5147         /*
5148          * Do extra check for this chunk item,
5149          *
5150          * It's still possible one can craft a leaf with CHUNK_ITEM, with
5151          * wrong onwer(3) out of chunk tree, to pass both chunk tree check
5152          * and owner<->key_type check.
5153          */
5154         ret = btrfs_check_chunk_valid(global_info->tree_root, eb, chunk, slot,
5155                                       key->offset);
5156         if (ret < 0) {
5157                 error("chunk(%llu, %llu) is not valid, ignore it",
5158                       key->offset, btrfs_chunk_length(eb, chunk));
5159                 return 0;
5160         }
5161         rec = btrfs_new_chunk_record(eb, key, slot);
5162         ret = insert_cache_extent(chunk_cache, &rec->cache);
5163         if (ret) {
5164                 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
5165                         rec->offset, rec->length);
5166                 free(rec);
5167         }
5168
5169         return ret;
5170 }
5171
5172 static int process_device_item(struct rb_root *dev_cache,
5173                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
5174 {
5175         struct btrfs_dev_item *ptr;
5176         struct device_record *rec;
5177         int ret = 0;
5178
5179         ptr = btrfs_item_ptr(eb,
5180                 slot, struct btrfs_dev_item);
5181
5182         rec = malloc(sizeof(*rec));
5183         if (!rec) {
5184                 fprintf(stderr, "memory allocation failed\n");
5185                 return -ENOMEM;
5186         }
5187
5188         rec->devid = key->offset;
5189         rec->generation = btrfs_header_generation(eb);
5190
5191         rec->objectid = key->objectid;
5192         rec->type = key->type;
5193         rec->offset = key->offset;
5194
5195         rec->devid = btrfs_device_id(eb, ptr);
5196         rec->total_byte = btrfs_device_total_bytes(eb, ptr);
5197         rec->byte_used = btrfs_device_bytes_used(eb, ptr);
5198
5199         ret = rb_insert(dev_cache, &rec->node, device_record_compare);
5200         if (ret) {
5201                 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
5202                 free(rec);
5203         }
5204
5205         return ret;
5206 }
5207
5208 struct block_group_record *
5209 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
5210                              int slot)
5211 {
5212         struct btrfs_block_group_item *ptr;
5213         struct block_group_record *rec;
5214
5215         rec = calloc(1, sizeof(*rec));
5216         if (!rec) {
5217                 fprintf(stderr, "memory allocation failed\n");
5218                 exit(-1);
5219         }
5220
5221         rec->cache.start = key->objectid;
5222         rec->cache.size = key->offset;
5223
5224         rec->generation = btrfs_header_generation(leaf);
5225
5226         rec->objectid = key->objectid;
5227         rec->type = key->type;
5228         rec->offset = key->offset;
5229
5230         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
5231         rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
5232
5233         INIT_LIST_HEAD(&rec->list);
5234
5235         return rec;
5236 }
5237
5238 static int process_block_group_item(struct block_group_tree *block_group_cache,
5239                                     struct btrfs_key *key,
5240                                     struct extent_buffer *eb, int slot)
5241 {
5242         struct block_group_record *rec;
5243         int ret = 0;
5244
5245         rec = btrfs_new_block_group_record(eb, key, slot);
5246         ret = insert_block_group_record(block_group_cache, rec);
5247         if (ret) {
5248                 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
5249                         rec->objectid, rec->offset);
5250                 free(rec);
5251         }
5252
5253         return ret;
5254 }
5255
5256 struct device_extent_record *
5257 btrfs_new_device_extent_record(struct extent_buffer *leaf,
5258                                struct btrfs_key *key, int slot)
5259 {
5260         struct device_extent_record *rec;
5261         struct btrfs_dev_extent *ptr;
5262
5263         rec = calloc(1, sizeof(*rec));
5264         if (!rec) {
5265                 fprintf(stderr, "memory allocation failed\n");
5266                 exit(-1);
5267         }
5268
5269         rec->cache.objectid = key->objectid;
5270         rec->cache.start = key->offset;
5271
5272         rec->generation = btrfs_header_generation(leaf);
5273
5274         rec->objectid = key->objectid;
5275         rec->type = key->type;
5276         rec->offset = key->offset;
5277
5278         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
5279         rec->chunk_objecteid =
5280                 btrfs_dev_extent_chunk_objectid(leaf, ptr);
5281         rec->chunk_offset =
5282                 btrfs_dev_extent_chunk_offset(leaf, ptr);
5283         rec->length = btrfs_dev_extent_length(leaf, ptr);
5284         rec->cache.size = rec->length;
5285
5286         INIT_LIST_HEAD(&rec->chunk_list);
5287         INIT_LIST_HEAD(&rec->device_list);
5288
5289         return rec;
5290 }
5291
5292 static int
5293 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
5294                            struct btrfs_key *key, struct extent_buffer *eb,
5295                            int slot)
5296 {
5297         struct device_extent_record *rec;
5298         int ret;
5299
5300         rec = btrfs_new_device_extent_record(eb, key, slot);
5301         ret = insert_device_extent_record(dev_extent_cache, rec);
5302         if (ret) {
5303                 fprintf(stderr,
5304                         "Device extent[%llu, %llu, %llu] existed.\n",
5305                         rec->objectid, rec->offset, rec->length);
5306                 free(rec);
5307         }
5308
5309         return ret;
5310 }
5311
5312 static int process_extent_item(struct btrfs_root *root,
5313                                struct cache_tree *extent_cache,
5314                                struct extent_buffer *eb, int slot)
5315 {
5316         struct btrfs_extent_item *ei;
5317         struct btrfs_extent_inline_ref *iref;
5318         struct btrfs_extent_data_ref *dref;
5319         struct btrfs_shared_data_ref *sref;
5320         struct btrfs_key key;
5321         struct extent_record tmpl;
5322         unsigned long end;
5323         unsigned long ptr;
5324         int ret;
5325         int type;
5326         u32 item_size = btrfs_item_size_nr(eb, slot);
5327         u64 refs = 0;
5328         u64 offset;
5329         u64 num_bytes;
5330         int metadata = 0;
5331
5332         btrfs_item_key_to_cpu(eb, &key, slot);
5333
5334         if (key.type == BTRFS_METADATA_ITEM_KEY) {
5335                 metadata = 1;
5336                 num_bytes = root->nodesize;
5337         } else {
5338                 num_bytes = key.offset;
5339         }
5340
5341         if (!IS_ALIGNED(key.objectid, root->sectorsize)) {
5342                 error("ignoring invalid extent, bytenr %llu is not aligned to %u",
5343                       key.objectid, root->sectorsize);
5344                 return -EIO;
5345         }
5346         if (item_size < sizeof(*ei)) {
5347 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5348                 struct btrfs_extent_item_v0 *ei0;
5349                 BUG_ON(item_size != sizeof(*ei0));
5350                 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
5351                 refs = btrfs_extent_refs_v0(eb, ei0);
5352 #else
5353                 BUG();
5354 #endif
5355                 memset(&tmpl, 0, sizeof(tmpl));
5356                 tmpl.start = key.objectid;
5357                 tmpl.nr = num_bytes;
5358                 tmpl.extent_item_refs = refs;
5359                 tmpl.metadata = metadata;
5360                 tmpl.found_rec = 1;
5361                 tmpl.max_size = num_bytes;
5362
5363                 return add_extent_rec(extent_cache, &tmpl);
5364         }
5365
5366         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
5367         refs = btrfs_extent_refs(eb, ei);
5368         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK)
5369                 metadata = 1;
5370         else
5371                 metadata = 0;
5372         if (metadata && num_bytes != root->nodesize) {
5373                 error("ignore invalid metadata extent, length %llu does not equal to %u",
5374                       num_bytes, root->nodesize);
5375                 return -EIO;
5376         }
5377         if (!metadata && !IS_ALIGNED(num_bytes, root->sectorsize)) {
5378                 error("ignore invalid data extent, length %llu is not aligned to %u",
5379                       num_bytes, root->sectorsize);
5380                 return -EIO;
5381         }
5382
5383         memset(&tmpl, 0, sizeof(tmpl));
5384         tmpl.start = key.objectid;
5385         tmpl.nr = num_bytes;
5386         tmpl.extent_item_refs = refs;
5387         tmpl.metadata = metadata;
5388         tmpl.found_rec = 1;
5389         tmpl.max_size = num_bytes;
5390         add_extent_rec(extent_cache, &tmpl);
5391
5392         ptr = (unsigned long)(ei + 1);
5393         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
5394             key.type == BTRFS_EXTENT_ITEM_KEY)
5395                 ptr += sizeof(struct btrfs_tree_block_info);
5396
5397         end = (unsigned long)ei + item_size;
5398         while (ptr < end) {
5399                 iref = (struct btrfs_extent_inline_ref *)ptr;
5400                 type = btrfs_extent_inline_ref_type(eb, iref);
5401                 offset = btrfs_extent_inline_ref_offset(eb, iref);
5402                 switch (type) {
5403                 case BTRFS_TREE_BLOCK_REF_KEY:
5404                         ret = add_tree_backref(extent_cache, key.objectid,
5405                                         0, offset, 0);
5406                         if (ret < 0)
5407                                 error("add_tree_backref failed: %s",
5408                                       strerror(-ret));
5409                         break;
5410                 case BTRFS_SHARED_BLOCK_REF_KEY:
5411                         ret = add_tree_backref(extent_cache, key.objectid,
5412                                         offset, 0, 0);
5413                         if (ret < 0)
5414                                 error("add_tree_backref failed: %s",
5415                                       strerror(-ret));
5416                         break;
5417                 case BTRFS_EXTENT_DATA_REF_KEY:
5418                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
5419                         add_data_backref(extent_cache, key.objectid, 0,
5420                                         btrfs_extent_data_ref_root(eb, dref),
5421                                         btrfs_extent_data_ref_objectid(eb,
5422                                                                        dref),
5423                                         btrfs_extent_data_ref_offset(eb, dref),
5424                                         btrfs_extent_data_ref_count(eb, dref),
5425                                         0, num_bytes);
5426                         break;
5427                 case BTRFS_SHARED_DATA_REF_KEY:
5428                         sref = (struct btrfs_shared_data_ref *)(iref + 1);
5429                         add_data_backref(extent_cache, key.objectid, offset,
5430                                         0, 0, 0,
5431                                         btrfs_shared_data_ref_count(eb, sref),
5432                                         0, num_bytes);
5433                         break;
5434                 default:
5435                         fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
5436                                 key.objectid, key.type, num_bytes);
5437                         goto out;
5438                 }
5439                 ptr += btrfs_extent_inline_ref_size(type);
5440         }
5441         WARN_ON(ptr > end);
5442 out:
5443         return 0;
5444 }
5445
5446 static int check_cache_range(struct btrfs_root *root,
5447                              struct btrfs_block_group_cache *cache,
5448                              u64 offset, u64 bytes)
5449 {
5450         struct btrfs_free_space *entry;
5451         u64 *logical;
5452         u64 bytenr;
5453         int stripe_len;
5454         int i, nr, ret;
5455
5456         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
5457                 bytenr = btrfs_sb_offset(i);
5458                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
5459                                        cache->key.objectid, bytenr, 0,
5460                                        &logical, &nr, &stripe_len);
5461                 if (ret)
5462                         return ret;
5463
5464                 while (nr--) {
5465                         if (logical[nr] + stripe_len <= offset)
5466                                 continue;
5467                         if (offset + bytes <= logical[nr])
5468                                 continue;
5469                         if (logical[nr] == offset) {
5470                                 if (stripe_len >= bytes) {
5471                                         free(logical);
5472                                         return 0;
5473                                 }
5474                                 bytes -= stripe_len;
5475                                 offset += stripe_len;
5476                         } else if (logical[nr] < offset) {
5477                                 if (logical[nr] + stripe_len >=
5478                                     offset + bytes) {
5479                                         free(logical);
5480                                         return 0;
5481                                 }
5482                                 bytes = (offset + bytes) -
5483                                         (logical[nr] + stripe_len);
5484                                 offset = logical[nr] + stripe_len;
5485                         } else {
5486                                 /*
5487                                  * Could be tricky, the super may land in the
5488                                  * middle of the area we're checking.  First
5489                                  * check the easiest case, it's at the end.
5490                                  */
5491                                 if (logical[nr] + stripe_len >=
5492                                     bytes + offset) {
5493                                         bytes = logical[nr] - offset;
5494                                         continue;
5495                                 }
5496
5497                                 /* Check the left side */
5498                                 ret = check_cache_range(root, cache,
5499                                                         offset,
5500                                                         logical[nr] - offset);
5501                                 if (ret) {
5502                                         free(logical);
5503                                         return ret;
5504                                 }
5505
5506                                 /* Now we continue with the right side */
5507                                 bytes = (offset + bytes) -
5508                                         (logical[nr] + stripe_len);
5509                                 offset = logical[nr] + stripe_len;
5510                         }
5511                 }
5512
5513                 free(logical);
5514         }
5515
5516         entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
5517         if (!entry) {
5518                 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
5519                         offset, offset+bytes);
5520                 return -EINVAL;
5521         }
5522
5523         if (entry->offset != offset) {
5524                 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
5525                         entry->offset);
5526                 return -EINVAL;
5527         }
5528
5529         if (entry->bytes != bytes) {
5530                 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
5531                         bytes, entry->bytes, offset);
5532                 return -EINVAL;
5533         }
5534
5535         unlink_free_space(cache->free_space_ctl, entry);
5536         free(entry);
5537         return 0;
5538 }
5539
5540 static int verify_space_cache(struct btrfs_root *root,
5541                               struct btrfs_block_group_cache *cache)
5542 {
5543         struct btrfs_path path;
5544         struct extent_buffer *leaf;
5545         struct btrfs_key key;
5546         u64 last;
5547         int ret = 0;
5548
5549         root = root->fs_info->extent_root;
5550
5551         last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
5552
5553         btrfs_init_path(&path);
5554         key.objectid = last;
5555         key.offset = 0;
5556         key.type = BTRFS_EXTENT_ITEM_KEY;
5557         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
5558         if (ret < 0)
5559                 goto out;
5560         ret = 0;
5561         while (1) {
5562                 if (path.slots[0] >= btrfs_header_nritems(path.nodes[0])) {
5563                         ret = btrfs_next_leaf(root, &path);
5564                         if (ret < 0)
5565                                 goto out;
5566                         if (ret > 0) {
5567                                 ret = 0;
5568                                 break;
5569                         }
5570                 }
5571                 leaf = path.nodes[0];
5572                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
5573                 if (key.objectid >= cache->key.offset + cache->key.objectid)
5574                         break;
5575                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
5576                     key.type != BTRFS_METADATA_ITEM_KEY) {
5577                         path.slots[0]++;
5578                         continue;
5579                 }
5580
5581                 if (last == key.objectid) {
5582                         if (key.type == BTRFS_EXTENT_ITEM_KEY)
5583                                 last = key.objectid + key.offset;
5584                         else
5585                                 last = key.objectid + root->nodesize;
5586                         path.slots[0]++;
5587                         continue;
5588                 }
5589
5590                 ret = check_cache_range(root, cache, last,
5591                                         key.objectid - last);
5592                 if (ret)
5593                         break;
5594                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
5595                         last = key.objectid + key.offset;
5596                 else
5597                         last = key.objectid + root->nodesize;
5598                 path.slots[0]++;
5599         }
5600
5601         if (last < cache->key.objectid + cache->key.offset)
5602                 ret = check_cache_range(root, cache, last,
5603                                         cache->key.objectid +
5604                                         cache->key.offset - last);
5605
5606 out:
5607         btrfs_release_path(&path);
5608
5609         if (!ret &&
5610             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
5611                 fprintf(stderr, "There are still entries left in the space "
5612                         "cache\n");
5613                 ret = -EINVAL;
5614         }
5615
5616         return ret;
5617 }
5618
5619 static int check_space_cache(struct btrfs_root *root)
5620 {
5621         struct btrfs_block_group_cache *cache;
5622         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
5623         int ret;
5624         int error = 0;
5625
5626         if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
5627             btrfs_super_generation(root->fs_info->super_copy) !=
5628             btrfs_super_cache_generation(root->fs_info->super_copy)) {
5629                 printf("cache and super generation don't match, space cache "
5630                        "will be invalidated\n");
5631                 return 0;
5632         }
5633
5634         if (ctx.progress_enabled) {
5635                 ctx.tp = TASK_FREE_SPACE;
5636                 task_start(ctx.info);
5637         }
5638
5639         while (1) {
5640                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
5641                 if (!cache)
5642                         break;
5643
5644                 start = cache->key.objectid + cache->key.offset;
5645                 if (!cache->free_space_ctl) {
5646                         if (btrfs_init_free_space_ctl(cache,
5647                                                       root->sectorsize)) {
5648                                 ret = -ENOMEM;
5649                                 break;
5650                         }
5651                 } else {
5652                         btrfs_remove_free_space_cache(cache);
5653                 }
5654
5655                 if (btrfs_fs_compat_ro(root->fs_info,
5656                                        BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE)) {
5657                         ret = exclude_super_stripes(root, cache);
5658                         if (ret) {
5659                                 fprintf(stderr, "could not exclude super stripes: %s\n",
5660                                         strerror(-ret));
5661                                 error++;
5662                                 continue;
5663                         }
5664                         ret = load_free_space_tree(root->fs_info, cache);
5665                         free_excluded_extents(root, cache);
5666                         if (ret < 0) {
5667                                 fprintf(stderr, "could not load free space tree: %s\n",
5668                                         strerror(-ret));
5669                                 error++;
5670                                 continue;
5671                         }
5672                         error += ret;
5673                 } else {
5674                         ret = load_free_space_cache(root->fs_info, cache);
5675                         if (!ret)
5676                                 continue;
5677                 }
5678
5679                 ret = verify_space_cache(root, cache);
5680                 if (ret) {
5681                         fprintf(stderr, "cache appears valid but isn't %Lu\n",
5682                                 cache->key.objectid);
5683                         error++;
5684                 }
5685         }
5686
5687         task_stop(ctx.info);
5688
5689         return error ? -EINVAL : 0;
5690 }
5691
5692 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
5693                         u64 num_bytes, unsigned long leaf_offset,
5694                         struct extent_buffer *eb) {
5695
5696         u64 offset = 0;
5697         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5698         char *data;
5699         unsigned long csum_offset;
5700         u32 csum;
5701         u32 csum_expected;
5702         u64 read_len;
5703         u64 data_checked = 0;
5704         u64 tmp;
5705         int ret = 0;
5706         int mirror;
5707         int num_copies;
5708
5709         if (num_bytes % root->sectorsize)
5710                 return -EINVAL;
5711
5712         data = malloc(num_bytes);
5713         if (!data)
5714                 return -ENOMEM;
5715
5716         while (offset < num_bytes) {
5717                 mirror = 0;
5718 again:
5719                 read_len = num_bytes - offset;
5720                 /* read as much space once a time */
5721                 ret = read_extent_data(root, data + offset,
5722                                 bytenr + offset, &read_len, mirror);
5723                 if (ret)
5724                         goto out;
5725                 data_checked = 0;
5726                 /* verify every 4k data's checksum */
5727                 while (data_checked < read_len) {
5728                         csum = ~(u32)0;
5729                         tmp = offset + data_checked;
5730
5731                         csum = btrfs_csum_data(NULL, (char *)data + tmp,
5732                                                csum, root->sectorsize);
5733                         btrfs_csum_final(csum, (u8 *)&csum);
5734
5735                         csum_offset = leaf_offset +
5736                                  tmp / root->sectorsize * csum_size;
5737                         read_extent_buffer(eb, (char *)&csum_expected,
5738                                            csum_offset, csum_size);
5739                         /* try another mirror */
5740                         if (csum != csum_expected) {
5741                                 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
5742                                                 mirror, bytenr + tmp,
5743                                                 csum, csum_expected);
5744                                 num_copies = btrfs_num_copies(
5745                                                 &root->fs_info->mapping_tree,
5746                                                 bytenr, num_bytes);
5747                                 if (mirror < num_copies - 1) {
5748                                         mirror += 1;
5749                                         goto again;
5750                                 }
5751                         }
5752                         data_checked += root->sectorsize;
5753                 }
5754                 offset += read_len;
5755         }
5756 out:
5757         free(data);
5758         return ret;
5759 }
5760
5761 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
5762                                u64 num_bytes)
5763 {
5764         struct btrfs_path path;
5765         struct extent_buffer *leaf;
5766         struct btrfs_key key;
5767         int ret;
5768
5769         btrfs_init_path(&path);
5770         key.objectid = bytenr;
5771         key.type = BTRFS_EXTENT_ITEM_KEY;
5772         key.offset = (u64)-1;
5773
5774 again:
5775         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, &path,
5776                                 0, 0);
5777         if (ret < 0) {
5778                 fprintf(stderr, "Error looking up extent record %d\n", ret);
5779                 btrfs_release_path(&path);
5780                 return ret;
5781         } else if (ret) {
5782                 if (path.slots[0] > 0) {
5783                         path.slots[0]--;
5784                 } else {
5785                         ret = btrfs_prev_leaf(root, &path);
5786                         if (ret < 0) {
5787                                 goto out;
5788                         } else if (ret > 0) {
5789                                 ret = 0;
5790                                 goto out;
5791                         }
5792                 }
5793         }
5794
5795         btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
5796
5797         /*
5798          * Block group items come before extent items if they have the same
5799          * bytenr, so walk back one more just in case.  Dear future traveller,
5800          * first congrats on mastering time travel.  Now if it's not too much
5801          * trouble could you go back to 2006 and tell Chris to make the
5802          * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
5803          * EXTENT_ITEM_KEY please?
5804          */
5805         while (key.type > BTRFS_EXTENT_ITEM_KEY) {
5806                 if (path.slots[0] > 0) {
5807                         path.slots[0]--;
5808                 } else {
5809                         ret = btrfs_prev_leaf(root, &path);
5810                         if (ret < 0) {
5811                                 goto out;
5812                         } else if (ret > 0) {
5813                                 ret = 0;
5814                                 goto out;
5815                         }
5816                 }
5817                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
5818         }
5819
5820         while (num_bytes) {
5821                 if (path.slots[0] >= btrfs_header_nritems(path.nodes[0])) {
5822                         ret = btrfs_next_leaf(root, &path);
5823                         if (ret < 0) {
5824                                 fprintf(stderr, "Error going to next leaf "
5825                                         "%d\n", ret);
5826                                 btrfs_release_path(&path);
5827                                 return ret;
5828                         } else if (ret) {
5829                                 break;
5830                         }
5831                 }
5832                 leaf = path.nodes[0];
5833                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
5834                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
5835                         path.slots[0]++;
5836                         continue;
5837                 }
5838                 if (key.objectid + key.offset < bytenr) {
5839                         path.slots[0]++;
5840                         continue;
5841                 }
5842                 if (key.objectid > bytenr + num_bytes)
5843                         break;
5844
5845                 if (key.objectid == bytenr) {
5846                         if (key.offset >= num_bytes) {
5847                                 num_bytes = 0;
5848                                 break;
5849                         }
5850                         num_bytes -= key.offset;
5851                         bytenr += key.offset;
5852                 } else if (key.objectid < bytenr) {
5853                         if (key.objectid + key.offset >= bytenr + num_bytes) {
5854                                 num_bytes = 0;
5855                                 break;
5856                         }
5857                         num_bytes = (bytenr + num_bytes) -
5858                                 (key.objectid + key.offset);
5859                         bytenr = key.objectid + key.offset;
5860                 } else {
5861                         if (key.objectid + key.offset < bytenr + num_bytes) {
5862                                 u64 new_start = key.objectid + key.offset;
5863                                 u64 new_bytes = bytenr + num_bytes - new_start;
5864
5865                                 /*
5866                                  * Weird case, the extent is in the middle of
5867                                  * our range, we'll have to search one side
5868                                  * and then the other.  Not sure if this happens
5869                                  * in real life, but no harm in coding it up
5870                                  * anyway just in case.
5871                                  */
5872                                 btrfs_release_path(&path);
5873                                 ret = check_extent_exists(root, new_start,
5874                                                           new_bytes);
5875                                 if (ret) {
5876                                         fprintf(stderr, "Right section didn't "
5877                                                 "have a record\n");
5878                                         break;
5879                                 }
5880                                 num_bytes = key.objectid - bytenr;
5881                                 goto again;
5882                         }
5883                         num_bytes = key.objectid - bytenr;
5884                 }
5885                 path.slots[0]++;
5886         }
5887         ret = 0;
5888
5889 out:
5890         if (num_bytes && !ret) {
5891                 fprintf(stderr, "There are no extents for csum range "
5892                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5893                 ret = 1;
5894         }
5895
5896         btrfs_release_path(&path);
5897         return ret;
5898 }
5899
5900 static int check_csums(struct btrfs_root *root)
5901 {
5902         struct btrfs_path path;
5903         struct extent_buffer *leaf;
5904         struct btrfs_key key;
5905         u64 offset = 0, num_bytes = 0;
5906         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5907         int errors = 0;
5908         int ret;
5909         u64 data_len;
5910         unsigned long leaf_offset;
5911
5912         root = root->fs_info->csum_root;
5913         if (!extent_buffer_uptodate(root->node)) {
5914                 fprintf(stderr, "No valid csum tree found\n");
5915                 return -ENOENT;
5916         }
5917
5918         btrfs_init_path(&path);
5919         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5920         key.type = BTRFS_EXTENT_CSUM_KEY;
5921         key.offset = 0;
5922         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
5923         if (ret < 0) {
5924                 fprintf(stderr, "Error searching csum tree %d\n", ret);
5925                 btrfs_release_path(&path);
5926                 return ret;
5927         }
5928
5929         if (ret > 0 && path.slots[0])
5930                 path.slots[0]--;
5931         ret = 0;
5932
5933         while (1) {
5934                 if (path.slots[0] >= btrfs_header_nritems(path.nodes[0])) {
5935                         ret = btrfs_next_leaf(root, &path);
5936                         if (ret < 0) {
5937                                 fprintf(stderr, "Error going to next leaf "
5938                                         "%d\n", ret);
5939                                 break;
5940                         }
5941                         if (ret)
5942                                 break;
5943                 }
5944                 leaf = path.nodes[0];
5945
5946                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
5947                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5948                         path.slots[0]++;
5949                         continue;
5950                 }
5951
5952                 data_len = (btrfs_item_size_nr(leaf, path.slots[0]) /
5953                               csum_size) * root->sectorsize;
5954                 if (!check_data_csum)
5955                         goto skip_csum_check;
5956                 leaf_offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
5957                 ret = check_extent_csums(root, key.offset, data_len,
5958                                          leaf_offset, leaf);
5959                 if (ret)
5960                         break;
5961 skip_csum_check:
5962                 if (!num_bytes) {
5963                         offset = key.offset;
5964                 } else if (key.offset != offset + num_bytes) {
5965                         ret = check_extent_exists(root, offset, num_bytes);
5966                         if (ret) {
5967                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5968                                         "there is no extent record\n",
5969                                         offset, offset+num_bytes);
5970                                 errors++;
5971                         }
5972                         offset = key.offset;
5973                         num_bytes = 0;
5974                 }
5975                 num_bytes += data_len;
5976                 path.slots[0]++;
5977         }
5978
5979         btrfs_release_path(&path);
5980         return errors;
5981 }
5982
5983 static int is_dropped_key(struct btrfs_key *key,
5984                           struct btrfs_key *drop_key) {
5985         if (key->objectid < drop_key->objectid)
5986                 return 1;
5987         else if (key->objectid == drop_key->objectid) {
5988                 if (key->type < drop_key->type)
5989                         return 1;
5990                 else if (key->type == drop_key->type) {
5991                         if (key->offset < drop_key->offset)
5992                                 return 1;
5993                 }
5994         }
5995         return 0;
5996 }
5997
5998 /*
5999  * Here are the rules for FULL_BACKREF.
6000  *
6001  * 1) If BTRFS_HEADER_FLAG_RELOC is set then we have FULL_BACKREF set.
6002  * 2) If btrfs_header_owner(buf) no longer points to buf then we have
6003  *      FULL_BACKREF set.
6004  * 3) We cowed the block walking down a reloc tree.  This is impossible to tell
6005  *    if it happened after the relocation occurred since we'll have dropped the
6006  *    reloc root, so it's entirely possible to have FULL_BACKREF set on buf and
6007  *    have no real way to know for sure.
6008  *
6009  * We process the blocks one root at a time, and we start from the lowest root
6010  * objectid and go to the highest.  So we can just lookup the owner backref for
6011  * the record and if we don't find it then we know it doesn't exist and we have
6012  * a FULL BACKREF.
6013  *
6014  * FIXME: if we ever start reclaiming root objectid's then we need to fix this
6015  * assumption and simply indicate that we _think_ that the FULL BACKREF needs to
6016  * be set or not and then we can check later once we've gathered all the refs.
6017  */
6018 static int calc_extent_flag(struct btrfs_root *root,
6019                            struct cache_tree *extent_cache,
6020                            struct extent_buffer *buf,
6021                            struct root_item_record *ri,
6022                            u64 *flags)
6023 {
6024         struct extent_record *rec;
6025         struct cache_extent *cache;
6026         struct tree_backref *tback;
6027         u64 owner = 0;
6028
6029         cache = lookup_cache_extent(extent_cache, buf->start, 1);
6030         /* we have added this extent before */
6031         if (!cache)
6032                 return -ENOENT;
6033
6034         rec = container_of(cache, struct extent_record, cache);
6035
6036         /*
6037          * Except file/reloc tree, we can not have
6038          * FULL BACKREF MODE
6039          */
6040         if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
6041                 goto normal;
6042         /*
6043          * root node
6044          */
6045         if (buf->start == ri->bytenr)
6046                 goto normal;
6047
6048         if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
6049                 goto full_backref;
6050
6051         owner = btrfs_header_owner(buf);
6052         if (owner == ri->objectid)
6053                 goto normal;
6054
6055         tback = find_tree_backref(rec, 0, owner);
6056         if (!tback)
6057                 goto full_backref;
6058 normal:
6059         *flags = 0;
6060         if (rec->flag_block_full_backref != FLAG_UNSET &&
6061             rec->flag_block_full_backref != 0)
6062                 rec->bad_full_backref = 1;
6063         return 0;
6064 full_backref:
6065         *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6066         if (rec->flag_block_full_backref != FLAG_UNSET &&
6067             rec->flag_block_full_backref != 1)
6068                 rec->bad_full_backref = 1;
6069         return 0;
6070 }
6071
6072 static void report_mismatch_key_root(u8 key_type, u64 rootid)
6073 {
6074         fprintf(stderr, "Invalid key type(");
6075         print_key_type(stderr, 0, key_type);
6076         fprintf(stderr, ") found in root(");
6077         print_objectid(stderr, rootid, 0);
6078         fprintf(stderr, ")\n");
6079 }
6080
6081 /*
6082  * Check if the key is valid with its extent buffer.
6083  *
6084  * This is a early check in case invalid key exists in a extent buffer
6085  * This is not comprehensive yet, but should prevent wrong key/item passed
6086  * further
6087  */
6088 static int check_type_with_root(u64 rootid, u8 key_type)
6089 {
6090         switch (key_type) {
6091         /* Only valid in chunk tree */
6092         case BTRFS_DEV_ITEM_KEY:
6093         case BTRFS_CHUNK_ITEM_KEY:
6094                 if (rootid != BTRFS_CHUNK_TREE_OBJECTID)
6095                         goto err;
6096                 break;
6097         /* valid in csum and log tree */
6098         case BTRFS_CSUM_TREE_OBJECTID:
6099                 if (!(rootid == BTRFS_TREE_LOG_OBJECTID ||
6100                       is_fstree(rootid)))
6101                         goto err;
6102                 break;
6103         case BTRFS_EXTENT_ITEM_KEY:
6104         case BTRFS_METADATA_ITEM_KEY:
6105         case BTRFS_BLOCK_GROUP_ITEM_KEY:
6106                 if (rootid != BTRFS_EXTENT_TREE_OBJECTID)
6107                         goto err;
6108                 break;
6109         case BTRFS_ROOT_ITEM_KEY:
6110                 if (rootid != BTRFS_ROOT_TREE_OBJECTID)
6111                         goto err;
6112                 break;
6113         case BTRFS_DEV_EXTENT_KEY:
6114                 if (rootid != BTRFS_DEV_TREE_OBJECTID)
6115                         goto err;
6116                 break;
6117         }
6118         return 0;
6119 err:
6120         report_mismatch_key_root(key_type, rootid);
6121         return -EINVAL;
6122 }
6123
6124 static int run_next_block(struct btrfs_root *root,
6125                           struct block_info *bits,
6126                           int bits_nr,
6127                           u64 *last,
6128                           struct cache_tree *pending,
6129                           struct cache_tree *seen,
6130                           struct cache_tree *reada,
6131                           struct cache_tree *nodes,
6132                           struct cache_tree *extent_cache,
6133                           struct cache_tree *chunk_cache,
6134                           struct rb_root *dev_cache,
6135                           struct block_group_tree *block_group_cache,
6136                           struct device_extent_tree *dev_extent_cache,
6137                           struct root_item_record *ri)
6138 {
6139         struct extent_buffer *buf;
6140         struct extent_record *rec = NULL;
6141         u64 bytenr;
6142         u32 size;
6143         u64 parent;
6144         u64 owner;
6145         u64 flags;
6146         u64 ptr;
6147         u64 gen = 0;
6148         int ret = 0;
6149         int i;
6150         int nritems;
6151         struct btrfs_key key;
6152         struct cache_extent *cache;
6153         int reada_bits;
6154
6155         nritems = pick_next_pending(pending, reada, nodes, *last, bits,
6156                                     bits_nr, &reada_bits);
6157         if (nritems == 0)
6158                 return 1;
6159
6160         if (!reada_bits) {
6161                 for(i = 0; i < nritems; i++) {
6162                         ret = add_cache_extent(reada, bits[i].start,
6163                                                bits[i].size);
6164                         if (ret == -EEXIST)
6165                                 continue;
6166
6167                         /* fixme, get the parent transid */
6168                         readahead_tree_block(root, bits[i].start,
6169                                              bits[i].size, 0);
6170                 }
6171         }
6172         *last = bits[0].start;
6173         bytenr = bits[0].start;
6174         size = bits[0].size;
6175
6176         cache = lookup_cache_extent(pending, bytenr, size);
6177         if (cache) {
6178                 remove_cache_extent(pending, cache);
6179                 free(cache);
6180         }
6181         cache = lookup_cache_extent(reada, bytenr, size);
6182         if (cache) {
6183                 remove_cache_extent(reada, cache);
6184                 free(cache);
6185         }
6186         cache = lookup_cache_extent(nodes, bytenr, size);
6187         if (cache) {
6188                 remove_cache_extent(nodes, cache);
6189                 free(cache);
6190         }
6191         cache = lookup_cache_extent(extent_cache, bytenr, size);
6192         if (cache) {
6193                 rec = container_of(cache, struct extent_record, cache);
6194                 gen = rec->parent_generation;
6195         }
6196
6197         /* fixme, get the real parent transid */
6198         buf = read_tree_block(root, bytenr, size, gen);
6199         if (!extent_buffer_uptodate(buf)) {
6200                 record_bad_block_io(root->fs_info,
6201                                     extent_cache, bytenr, size);
6202                 goto out;
6203         }
6204
6205         nritems = btrfs_header_nritems(buf);
6206
6207         flags = 0;
6208         if (!init_extent_tree) {
6209                 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
6210                                        btrfs_header_level(buf), 1, NULL,
6211                                        &flags);
6212                 if (ret < 0) {
6213                         ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
6214                         if (ret < 0) {
6215                                 fprintf(stderr, "Couldn't calc extent flags\n");
6216                                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6217                         }
6218                 }
6219         } else {
6220                 flags = 0;
6221                 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
6222                 if (ret < 0) {
6223                         fprintf(stderr, "Couldn't calc extent flags\n");
6224                         flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6225                 }
6226         }
6227
6228         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6229                 if (ri != NULL &&
6230                     ri->objectid != BTRFS_TREE_RELOC_OBJECTID &&
6231                     ri->objectid == btrfs_header_owner(buf)) {
6232                         /*
6233                          * Ok we got to this block from it's original owner and
6234                          * we have FULL_BACKREF set.  Relocation can leave
6235                          * converted blocks over so this is altogether possible,
6236                          * however it's not possible if the generation > the
6237                          * last snapshot, so check for this case.
6238                          */
6239                         if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC) &&
6240                             btrfs_header_generation(buf) > ri->last_snapshot) {
6241                                 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
6242                                 rec->bad_full_backref = 1;
6243                         }
6244                 }
6245         } else {
6246                 if (ri != NULL &&
6247                     (ri->objectid == BTRFS_TREE_RELOC_OBJECTID ||
6248                      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))) {
6249                         flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6250                         rec->bad_full_backref = 1;
6251                 }
6252         }
6253
6254         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6255                 rec->flag_block_full_backref = 1;
6256                 parent = bytenr;
6257                 owner = 0;
6258         } else {
6259                 rec->flag_block_full_backref = 0;
6260                 parent = 0;
6261                 owner = btrfs_header_owner(buf);
6262         }
6263
6264         ret = check_block(root, extent_cache, buf, flags);
6265         if (ret)
6266                 goto out;
6267
6268         if (btrfs_is_leaf(buf)) {
6269                 btree_space_waste += btrfs_leaf_free_space(root, buf);
6270                 for (i = 0; i < nritems; i++) {
6271                         struct btrfs_file_extent_item *fi;
6272                         btrfs_item_key_to_cpu(buf, &key, i);
6273                         /*
6274                          * Check key type against the leaf owner.
6275                          * Could filter quite a lot of early error if
6276                          * owner is correct
6277                          */
6278                         if (check_type_with_root(btrfs_header_owner(buf),
6279                                                  key.type)) {
6280                                 fprintf(stderr, "ignoring invalid key\n");
6281                                 continue;
6282                         }
6283                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
6284                                 process_extent_item(root, extent_cache, buf,
6285                                                     i);
6286                                 continue;
6287                         }
6288                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
6289                                 process_extent_item(root, extent_cache, buf,
6290                                                     i);
6291                                 continue;
6292                         }
6293                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
6294                                 total_csum_bytes +=
6295                                         btrfs_item_size_nr(buf, i);
6296                                 continue;
6297                         }
6298                         if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6299                                 process_chunk_item(chunk_cache, &key, buf, i);
6300                                 continue;
6301                         }
6302                         if (key.type == BTRFS_DEV_ITEM_KEY) {
6303                                 process_device_item(dev_cache, &key, buf, i);
6304                                 continue;
6305                         }
6306                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
6307                                 process_block_group_item(block_group_cache,
6308                                         &key, buf, i);
6309                                 continue;
6310                         }
6311                         if (key.type == BTRFS_DEV_EXTENT_KEY) {
6312                                 process_device_extent_item(dev_extent_cache,
6313                                         &key, buf, i);
6314                                 continue;
6315
6316                         }
6317                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
6318 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6319                                 process_extent_ref_v0(extent_cache, buf, i);
6320 #else
6321                                 BUG();
6322 #endif
6323                                 continue;
6324                         }
6325
6326                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
6327                                 ret = add_tree_backref(extent_cache,
6328                                                 key.objectid, 0, key.offset, 0);
6329                                 if (ret < 0)
6330                                         error("add_tree_backref failed: %s",
6331                                               strerror(-ret));
6332                                 continue;
6333                         }
6334                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
6335                                 ret = add_tree_backref(extent_cache,
6336                                                 key.objectid, key.offset, 0, 0);
6337                                 if (ret < 0)
6338                                         error("add_tree_backref failed: %s",
6339                                               strerror(-ret));
6340                                 continue;
6341                         }
6342                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
6343                                 struct btrfs_extent_data_ref *ref;
6344                                 ref = btrfs_item_ptr(buf, i,
6345                                                 struct btrfs_extent_data_ref);
6346                                 add_data_backref(extent_cache,
6347                                         key.objectid, 0,
6348                                         btrfs_extent_data_ref_root(buf, ref),
6349                                         btrfs_extent_data_ref_objectid(buf,
6350                                                                        ref),
6351                                         btrfs_extent_data_ref_offset(buf, ref),
6352                                         btrfs_extent_data_ref_count(buf, ref),
6353                                         0, root->sectorsize);
6354                                 continue;
6355                         }
6356                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
6357                                 struct btrfs_shared_data_ref *ref;
6358                                 ref = btrfs_item_ptr(buf, i,
6359                                                 struct btrfs_shared_data_ref);
6360                                 add_data_backref(extent_cache,
6361                                         key.objectid, key.offset, 0, 0, 0,
6362                                         btrfs_shared_data_ref_count(buf, ref),
6363                                         0, root->sectorsize);
6364                                 continue;
6365                         }
6366                         if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
6367                                 struct bad_item *bad;
6368
6369                                 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
6370                                         continue;
6371                                 if (!owner)
6372                                         continue;
6373                                 bad = malloc(sizeof(struct bad_item));
6374                                 if (!bad)
6375                                         continue;
6376                                 INIT_LIST_HEAD(&bad->list);
6377                                 memcpy(&bad->key, &key,
6378                                        sizeof(struct btrfs_key));
6379                                 bad->root_id = owner;
6380                                 list_add_tail(&bad->list, &delete_items);
6381                                 continue;
6382                         }
6383                         if (key.type != BTRFS_EXTENT_DATA_KEY)
6384                                 continue;
6385                         fi = btrfs_item_ptr(buf, i,
6386                                             struct btrfs_file_extent_item);
6387                         if (btrfs_file_extent_type(buf, fi) ==
6388                             BTRFS_FILE_EXTENT_INLINE)
6389                                 continue;
6390                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
6391                                 continue;
6392
6393                         data_bytes_allocated +=
6394                                 btrfs_file_extent_disk_num_bytes(buf, fi);
6395                         if (data_bytes_allocated < root->sectorsize) {
6396                                 abort();
6397                         }
6398                         data_bytes_referenced +=
6399                                 btrfs_file_extent_num_bytes(buf, fi);
6400                         add_data_backref(extent_cache,
6401                                 btrfs_file_extent_disk_bytenr(buf, fi),
6402                                 parent, owner, key.objectid, key.offset -
6403                                 btrfs_file_extent_offset(buf, fi), 1, 1,
6404                                 btrfs_file_extent_disk_num_bytes(buf, fi));
6405                 }
6406         } else {
6407                 int level;
6408                 struct btrfs_key first_key;
6409
6410                 first_key.objectid = 0;
6411
6412                 if (nritems > 0)
6413                         btrfs_item_key_to_cpu(buf, &first_key, 0);
6414                 level = btrfs_header_level(buf);
6415                 for (i = 0; i < nritems; i++) {
6416                         struct extent_record tmpl;
6417
6418                         ptr = btrfs_node_blockptr(buf, i);
6419                         size = root->nodesize;
6420                         btrfs_node_key_to_cpu(buf, &key, i);
6421                         if (ri != NULL) {
6422                                 if ((level == ri->drop_level)
6423                                     && is_dropped_key(&key, &ri->drop_key)) {
6424                                         continue;
6425                                 }
6426                         }
6427
6428                         memset(&tmpl, 0, sizeof(tmpl));
6429                         btrfs_cpu_key_to_disk(&tmpl.parent_key, &key);
6430                         tmpl.parent_generation = btrfs_node_ptr_generation(buf, i);
6431                         tmpl.start = ptr;
6432                         tmpl.nr = size;
6433                         tmpl.refs = 1;
6434                         tmpl.metadata = 1;
6435                         tmpl.max_size = size;
6436                         ret = add_extent_rec(extent_cache, &tmpl);
6437                         if (ret < 0)
6438                                 goto out;
6439
6440                         ret = add_tree_backref(extent_cache, ptr, parent,
6441                                         owner, 1);
6442                         if (ret < 0) {
6443                                 error("add_tree_backref failed: %s",
6444                                       strerror(-ret));
6445                                 continue;
6446                         }
6447
6448                         if (level > 1) {
6449                                 add_pending(nodes, seen, ptr, size);
6450                         } else {
6451                                 add_pending(pending, seen, ptr, size);
6452                         }
6453                 }
6454                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
6455                                       nritems) * sizeof(struct btrfs_key_ptr);
6456         }
6457         total_btree_bytes += buf->len;
6458         if (fs_root_objectid(btrfs_header_owner(buf)))
6459                 total_fs_tree_bytes += buf->len;
6460         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
6461                 total_extent_tree_bytes += buf->len;
6462         if (!found_old_backref &&
6463             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
6464             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
6465             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
6466                 found_old_backref = 1;
6467 out:
6468         free_extent_buffer(buf);
6469         return ret;
6470 }
6471
6472 static int add_root_to_pending(struct extent_buffer *buf,
6473                                struct cache_tree *extent_cache,
6474                                struct cache_tree *pending,
6475                                struct cache_tree *seen,
6476                                struct cache_tree *nodes,
6477                                u64 objectid)
6478 {
6479         struct extent_record tmpl;
6480         int ret;
6481
6482         if (btrfs_header_level(buf) > 0)
6483                 add_pending(nodes, seen, buf->start, buf->len);
6484         else
6485                 add_pending(pending, seen, buf->start, buf->len);
6486
6487         memset(&tmpl, 0, sizeof(tmpl));
6488         tmpl.start = buf->start;
6489         tmpl.nr = buf->len;
6490         tmpl.is_root = 1;
6491         tmpl.refs = 1;
6492         tmpl.metadata = 1;
6493         tmpl.max_size = buf->len;
6494         add_extent_rec(extent_cache, &tmpl);
6495
6496         if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
6497             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
6498                 ret = add_tree_backref(extent_cache, buf->start, buf->start,
6499                                 0, 1);
6500         else
6501                 ret = add_tree_backref(extent_cache, buf->start, 0, objectid,
6502                                 1);
6503         return ret;
6504 }
6505
6506 /* as we fix the tree, we might be deleting blocks that
6507  * we're tracking for repair.  This hook makes sure we
6508  * remove any backrefs for blocks as we are fixing them.
6509  */
6510 static int free_extent_hook(struct btrfs_trans_handle *trans,
6511                             struct btrfs_root *root,
6512                             u64 bytenr, u64 num_bytes, u64 parent,
6513                             u64 root_objectid, u64 owner, u64 offset,
6514                             int refs_to_drop)
6515 {
6516         struct extent_record *rec;
6517         struct cache_extent *cache;
6518         int is_data;
6519         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
6520
6521         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
6522         cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
6523         if (!cache)
6524                 return 0;
6525
6526         rec = container_of(cache, struct extent_record, cache);
6527         if (is_data) {
6528                 struct data_backref *back;
6529                 back = find_data_backref(rec, parent, root_objectid, owner,
6530                                          offset, 1, bytenr, num_bytes);
6531                 if (!back)
6532                         goto out;
6533                 if (back->node.found_ref) {
6534                         back->found_ref -= refs_to_drop;
6535                         if (rec->refs)
6536                                 rec->refs -= refs_to_drop;
6537                 }
6538                 if (back->node.found_extent_tree) {
6539                         back->num_refs -= refs_to_drop;
6540                         if (rec->extent_item_refs)
6541                                 rec->extent_item_refs -= refs_to_drop;
6542                 }
6543                 if (back->found_ref == 0)
6544                         back->node.found_ref = 0;
6545                 if (back->num_refs == 0)
6546                         back->node.found_extent_tree = 0;
6547
6548                 if (!back->node.found_extent_tree && back->node.found_ref) {
6549                         list_del(&back->node.list);
6550                         free(back);
6551                 }
6552         } else {
6553                 struct tree_backref *back;
6554                 back = find_tree_backref(rec, parent, root_objectid);
6555                 if (!back)
6556                         goto out;
6557                 if (back->node.found_ref) {
6558                         if (rec->refs)
6559                                 rec->refs--;
6560                         back->node.found_ref = 0;
6561                 }
6562                 if (back->node.found_extent_tree) {
6563                         if (rec->extent_item_refs)
6564                                 rec->extent_item_refs--;
6565                         back->node.found_extent_tree = 0;
6566                 }
6567                 if (!back->node.found_extent_tree && back->node.found_ref) {
6568                         list_del(&back->node.list);
6569                         free(back);
6570                 }
6571         }
6572         maybe_free_extent_rec(extent_cache, rec);
6573 out:
6574         return 0;
6575 }
6576
6577 static int delete_extent_records(struct btrfs_trans_handle *trans,
6578                                  struct btrfs_root *root,
6579                                  struct btrfs_path *path,
6580                                  u64 bytenr, u64 new_len)
6581 {
6582         struct btrfs_key key;
6583         struct btrfs_key found_key;
6584         struct extent_buffer *leaf;
6585         int ret;
6586         int slot;
6587
6588
6589         key.objectid = bytenr;
6590         key.type = (u8)-1;
6591         key.offset = (u64)-1;
6592
6593         while(1) {
6594                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
6595                                         &key, path, 0, 1);
6596                 if (ret < 0)
6597                         break;
6598
6599                 if (ret > 0) {
6600                         ret = 0;
6601                         if (path->slots[0] == 0)
6602                                 break;
6603                         path->slots[0]--;
6604                 }
6605                 ret = 0;
6606
6607                 leaf = path->nodes[0];
6608                 slot = path->slots[0];
6609
6610                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6611                 if (found_key.objectid != bytenr)
6612                         break;
6613
6614                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
6615                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
6616                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
6617                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
6618                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
6619                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
6620                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
6621                         btrfs_release_path(path);
6622                         if (found_key.type == 0) {
6623                                 if (found_key.offset == 0)
6624                                         break;
6625                                 key.offset = found_key.offset - 1;
6626                                 key.type = found_key.type;
6627                         }
6628                         key.type = found_key.type - 1;
6629                         key.offset = (u64)-1;
6630                         continue;
6631                 }
6632
6633                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
6634                         found_key.objectid, found_key.type, found_key.offset);
6635
6636                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
6637                 if (ret)
6638                         break;
6639                 btrfs_release_path(path);
6640
6641                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
6642                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
6643                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
6644                                 found_key.offset : root->nodesize;
6645
6646                         ret = btrfs_update_block_group(trans, root, bytenr,
6647                                                        bytes, 0, 0);
6648                         if (ret)
6649                                 break;
6650                 }
6651         }
6652
6653         btrfs_release_path(path);
6654         return ret;
6655 }
6656
6657 /*
6658  * for a single backref, this will allocate a new extent
6659  * and add the backref to it.
6660  */
6661 static int record_extent(struct btrfs_trans_handle *trans,
6662                          struct btrfs_fs_info *info,
6663                          struct btrfs_path *path,
6664                          struct extent_record *rec,
6665                          struct extent_backref *back,
6666                          int allocated, u64 flags)
6667 {
6668         int ret;
6669         struct btrfs_root *extent_root = info->extent_root;
6670         struct extent_buffer *leaf;
6671         struct btrfs_key ins_key;
6672         struct btrfs_extent_item *ei;
6673         struct tree_backref *tback;
6674         struct data_backref *dback;
6675         struct btrfs_tree_block_info *bi;
6676
6677         if (!back->is_data)
6678                 rec->max_size = max_t(u64, rec->max_size,
6679                                     info->extent_root->nodesize);
6680
6681         if (!allocated) {
6682                 u32 item_size = sizeof(*ei);
6683
6684                 if (!back->is_data)
6685                         item_size += sizeof(*bi);
6686
6687                 ins_key.objectid = rec->start;
6688                 ins_key.offset = rec->max_size;
6689                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
6690
6691                 ret = btrfs_insert_empty_item(trans, extent_root, path,
6692                                         &ins_key, item_size);
6693                 if (ret)
6694                         goto fail;
6695
6696                 leaf = path->nodes[0];
6697                 ei = btrfs_item_ptr(leaf, path->slots[0],
6698                                     struct btrfs_extent_item);
6699
6700                 btrfs_set_extent_refs(leaf, ei, 0);
6701                 btrfs_set_extent_generation(leaf, ei, rec->generation);
6702
6703                 if (back->is_data) {
6704                         btrfs_set_extent_flags(leaf, ei,
6705                                                BTRFS_EXTENT_FLAG_DATA);
6706                 } else {
6707                         struct btrfs_disk_key copy_key;;
6708
6709                         tback = to_tree_backref(back);
6710                         bi = (struct btrfs_tree_block_info *)(ei + 1);
6711                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
6712                                              sizeof(*bi));
6713
6714                         btrfs_set_disk_key_objectid(&copy_key,
6715                                                     rec->info_objectid);
6716                         btrfs_set_disk_key_type(&copy_key, 0);
6717                         btrfs_set_disk_key_offset(&copy_key, 0);
6718
6719                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
6720                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
6721
6722                         btrfs_set_extent_flags(leaf, ei,
6723                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
6724                 }
6725
6726                 btrfs_mark_buffer_dirty(leaf);
6727                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
6728                                                rec->max_size, 1, 0);
6729                 if (ret)
6730                         goto fail;
6731                 btrfs_release_path(path);
6732         }
6733
6734         if (back->is_data) {
6735                 u64 parent;
6736                 int i;
6737
6738                 dback = to_data_backref(back);
6739                 if (back->full_backref)
6740                         parent = dback->parent;
6741                 else
6742                         parent = 0;
6743
6744                 for (i = 0; i < dback->found_ref; i++) {
6745                         /* if parent != 0, we're doing a full backref
6746                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
6747                          * just makes the backref allocator create a data
6748                          * backref
6749                          */
6750                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
6751                                                    rec->start, rec->max_size,
6752                                                    parent,
6753                                                    dback->root,
6754                                                    parent ?
6755                                                    BTRFS_FIRST_FREE_OBJECTID :
6756                                                    dback->owner,
6757                                                    dback->offset);
6758                         if (ret)
6759                                 break;
6760                 }
6761                 fprintf(stderr, "adding new data backref"
6762                                 " on %llu %s %llu owner %llu"
6763                                 " offset %llu found %d\n",
6764                                 (unsigned long long)rec->start,
6765                                 back->full_backref ?
6766                                 "parent" : "root",
6767                                 back->full_backref ?
6768                                 (unsigned long long)parent :
6769                                 (unsigned long long)dback->root,
6770                                 (unsigned long long)dback->owner,
6771                                 (unsigned long long)dback->offset,
6772                                 dback->found_ref);
6773         } else {
6774                 u64 parent;
6775
6776                 tback = to_tree_backref(back);
6777                 if (back->full_backref)
6778                         parent = tback->parent;
6779                 else
6780                         parent = 0;
6781
6782                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
6783                                            rec->start, rec->max_size,
6784                                            parent, tback->root, 0, 0);
6785                 fprintf(stderr, "adding new tree backref on "
6786                         "start %llu len %llu parent %llu root %llu\n",
6787                         rec->start, rec->max_size, parent, tback->root);
6788         }
6789 fail:
6790         btrfs_release_path(path);
6791         return ret;
6792 }
6793
6794 static struct extent_entry *find_entry(struct list_head *entries,
6795                                        u64 bytenr, u64 bytes)
6796 {
6797         struct extent_entry *entry = NULL;
6798
6799         list_for_each_entry(entry, entries, list) {
6800                 if (entry->bytenr == bytenr && entry->bytes == bytes)
6801                         return entry;
6802         }
6803
6804         return NULL;
6805 }
6806
6807 static struct extent_entry *find_most_right_entry(struct list_head *entries)
6808 {
6809         struct extent_entry *entry, *best = NULL, *prev = NULL;
6810
6811         list_for_each_entry(entry, entries, list) {
6812                 if (!prev) {
6813                         prev = entry;
6814                         continue;
6815                 }
6816
6817                 /*
6818                  * If there are as many broken entries as entries then we know
6819                  * not to trust this particular entry.
6820                  */
6821                 if (entry->broken == entry->count)
6822                         continue;
6823
6824                 /*
6825                  * If our current entry == best then we can't be sure our best
6826                  * is really the best, so we need to keep searching.
6827                  */
6828                 if (best && best->count == entry->count) {
6829                         prev = entry;
6830                         best = NULL;
6831                         continue;
6832                 }
6833
6834                 /* Prev == entry, not good enough, have to keep searching */
6835                 if (!prev->broken && prev->count == entry->count)
6836                         continue;
6837
6838                 if (!best)
6839                         best = (prev->count > entry->count) ? prev : entry;
6840                 else if (best->count < entry->count)
6841                         best = entry;
6842                 prev = entry;
6843         }
6844
6845         return best;
6846 }
6847
6848 static int repair_ref(struct btrfs_fs_info *info, struct btrfs_path *path,
6849                       struct data_backref *dback, struct extent_entry *entry)
6850 {
6851         struct btrfs_trans_handle *trans;
6852         struct btrfs_root *root;
6853         struct btrfs_file_extent_item *fi;
6854         struct extent_buffer *leaf;
6855         struct btrfs_key key;
6856         u64 bytenr, bytes;
6857         int ret, err;
6858
6859         key.objectid = dback->root;
6860         key.type = BTRFS_ROOT_ITEM_KEY;
6861         key.offset = (u64)-1;
6862         root = btrfs_read_fs_root(info, &key);
6863         if (IS_ERR(root)) {
6864                 fprintf(stderr, "Couldn't find root for our ref\n");
6865                 return -EINVAL;
6866         }
6867
6868         /*
6869          * The backref points to the original offset of the extent if it was
6870          * split, so we need to search down to the offset we have and then walk
6871          * forward until we find the backref we're looking for.
6872          */
6873         key.objectid = dback->owner;
6874         key.type = BTRFS_EXTENT_DATA_KEY;
6875         key.offset = dback->offset;
6876         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6877         if (ret < 0) {
6878                 fprintf(stderr, "Error looking up ref %d\n", ret);
6879                 return ret;
6880         }
6881
6882         while (1) {
6883                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6884                         ret = btrfs_next_leaf(root, path);
6885                         if (ret) {
6886                                 fprintf(stderr, "Couldn't find our ref, next\n");
6887                                 return -EINVAL;
6888                         }
6889                 }
6890                 leaf = path->nodes[0];
6891                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6892                 if (key.objectid != dback->owner ||
6893                     key.type != BTRFS_EXTENT_DATA_KEY) {
6894                         fprintf(stderr, "Couldn't find our ref, search\n");
6895                         return -EINVAL;
6896                 }
6897                 fi = btrfs_item_ptr(leaf, path->slots[0],
6898                                     struct btrfs_file_extent_item);
6899                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6900                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6901
6902                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6903                         break;
6904                 path->slots[0]++;
6905         }
6906
6907         btrfs_release_path(path);
6908
6909         trans = btrfs_start_transaction(root, 1);
6910         if (IS_ERR(trans))
6911                 return PTR_ERR(trans);
6912
6913         /*
6914          * Ok we have the key of the file extent we want to fix, now we can cow
6915          * down to the thing and fix it.
6916          */
6917         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6918         if (ret < 0) {
6919                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6920                         key.objectid, key.type, key.offset, ret);
6921                 goto out;
6922         }
6923         if (ret > 0) {
6924                 fprintf(stderr, "Well that's odd, we just found this key "
6925                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6926                         key.offset);
6927                 ret = -EINVAL;
6928                 goto out;
6929         }
6930         leaf = path->nodes[0];
6931         fi = btrfs_item_ptr(leaf, path->slots[0],
6932                             struct btrfs_file_extent_item);
6933
6934         if (btrfs_file_extent_compression(leaf, fi) &&
6935             dback->disk_bytenr != entry->bytenr) {
6936                 fprintf(stderr, "Ref doesn't match the record start and is "
6937                         "compressed, please take a btrfs-image of this file "
6938                         "system and send it to a btrfs developer so they can "
6939                         "complete this functionality for bytenr %Lu\n",
6940                         dback->disk_bytenr);
6941                 ret = -EINVAL;
6942                 goto out;
6943         }
6944
6945         if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6946                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6947         } else if (dback->disk_bytenr > entry->bytenr) {
6948                 u64 off_diff, offset;
6949
6950                 off_diff = dback->disk_bytenr - entry->bytenr;
6951                 offset = btrfs_file_extent_offset(leaf, fi);
6952                 if (dback->disk_bytenr + offset +
6953                     btrfs_file_extent_num_bytes(leaf, fi) >
6954                     entry->bytenr + entry->bytes) {
6955                         fprintf(stderr, "Ref is past the entry end, please "
6956                                 "take a btrfs-image of this file system and "
6957                                 "send it to a btrfs developer, ref %Lu\n",
6958                                 dback->disk_bytenr);
6959                         ret = -EINVAL;
6960                         goto out;
6961                 }
6962                 offset += off_diff;
6963                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6964                 btrfs_set_file_extent_offset(leaf, fi, offset);
6965         } else if (dback->disk_bytenr < entry->bytenr) {
6966                 u64 offset;
6967
6968                 offset = btrfs_file_extent_offset(leaf, fi);
6969                 if (dback->disk_bytenr + offset < entry->bytenr) {
6970                         fprintf(stderr, "Ref is before the entry start, please"
6971                                 " take a btrfs-image of this file system and "
6972                                 "send it to a btrfs developer, ref %Lu\n",
6973                                 dback->disk_bytenr);
6974                         ret = -EINVAL;
6975                         goto out;
6976                 }
6977
6978                 offset += dback->disk_bytenr;
6979                 offset -= entry->bytenr;
6980                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6981                 btrfs_set_file_extent_offset(leaf, fi, offset);
6982         }
6983
6984         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6985
6986         /*
6987          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6988          * only do this if we aren't using compression, otherwise it's a
6989          * trickier case.
6990          */
6991         if (!btrfs_file_extent_compression(leaf, fi))
6992                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6993         else
6994                 printf("ram bytes may be wrong?\n");
6995         btrfs_mark_buffer_dirty(leaf);
6996 out:
6997         err = btrfs_commit_transaction(trans, root);
6998         btrfs_release_path(path);
6999         return ret ? ret : err;
7000 }
7001
7002 static int verify_backrefs(struct btrfs_fs_info *info, struct btrfs_path *path,
7003                            struct extent_record *rec)
7004 {
7005         struct extent_backref *back;
7006         struct data_backref *dback;
7007         struct extent_entry *entry, *best = NULL;
7008         LIST_HEAD(entries);
7009         int nr_entries = 0;
7010         int broken_entries = 0;
7011         int ret = 0;
7012         short mismatch = 0;
7013
7014         /*
7015          * Metadata is easy and the backrefs should always agree on bytenr and
7016          * size, if not we've got bigger issues.
7017          */
7018         if (rec->metadata)
7019                 return 0;
7020
7021         list_for_each_entry(back, &rec->backrefs, list) {
7022                 if (back->full_backref || !back->is_data)
7023                         continue;
7024
7025                 dback = to_data_backref(back);
7026
7027                 /*
7028                  * We only pay attention to backrefs that we found a real
7029                  * backref for.
7030                  */
7031                 if (dback->found_ref == 0)
7032                         continue;
7033
7034                 /*
7035                  * For now we only catch when the bytes don't match, not the
7036                  * bytenr.  We can easily do this at the same time, but I want
7037                  * to have a fs image to test on before we just add repair
7038                  * functionality willy-nilly so we know we won't screw up the
7039                  * repair.
7040                  */
7041
7042                 entry = find_entry(&entries, dback->disk_bytenr,
7043                                    dback->bytes);
7044                 if (!entry) {
7045                         entry = malloc(sizeof(struct extent_entry));
7046                         if (!entry) {
7047                                 ret = -ENOMEM;
7048                                 goto out;
7049                         }
7050                         memset(entry, 0, sizeof(*entry));
7051                         entry->bytenr = dback->disk_bytenr;
7052                         entry->bytes = dback->bytes;
7053                         list_add_tail(&entry->list, &entries);
7054                         nr_entries++;
7055                 }
7056
7057                 /*
7058                  * If we only have on entry we may think the entries agree when
7059                  * in reality they don't so we have to do some extra checking.
7060                  */
7061                 if (dback->disk_bytenr != rec->start ||
7062                     dback->bytes != rec->nr || back->broken)
7063                         mismatch = 1;
7064
7065                 if (back->broken) {
7066                         entry->broken++;
7067                         broken_entries++;
7068                 }
7069
7070                 entry->count++;
7071         }
7072
7073         /* Yay all the backrefs agree, carry on good sir */
7074         if (nr_entries <= 1 && !mismatch)
7075                 goto out;
7076
7077         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
7078                 "%Lu\n", rec->start);
7079
7080         /*
7081          * First we want to see if the backrefs can agree amongst themselves who
7082          * is right, so figure out which one of the entries has the highest
7083          * count.
7084          */
7085         best = find_most_right_entry(&entries);
7086
7087         /*
7088          * Ok so we may have an even split between what the backrefs think, so
7089          * this is where we use the extent ref to see what it thinks.
7090          */
7091         if (!best) {
7092                 entry = find_entry(&entries, rec->start, rec->nr);
7093                 if (!entry && (!broken_entries || !rec->found_rec)) {
7094                         fprintf(stderr, "Backrefs don't agree with each other "
7095                                 "and extent record doesn't agree with anybody,"
7096                                 " so we can't fix bytenr %Lu bytes %Lu\n",
7097                                 rec->start, rec->nr);
7098                         ret = -EINVAL;
7099                         goto out;
7100                 } else if (!entry) {
7101                         /*
7102                          * Ok our backrefs were broken, we'll assume this is the
7103                          * correct value and add an entry for this range.
7104                          */
7105                         entry = malloc(sizeof(struct extent_entry));
7106                         if (!entry) {
7107                                 ret = -ENOMEM;
7108                                 goto out;
7109                         }
7110                         memset(entry, 0, sizeof(*entry));
7111                         entry->bytenr = rec->start;
7112                         entry->bytes = rec->nr;
7113                         list_add_tail(&entry->list, &entries);
7114                         nr_entries++;
7115                 }
7116                 entry->count++;
7117                 best = find_most_right_entry(&entries);
7118                 if (!best) {
7119                         fprintf(stderr, "Backrefs and extent record evenly "
7120                                 "split on who is right, this is going to "
7121                                 "require user input to fix bytenr %Lu bytes "
7122                                 "%Lu\n", rec->start, rec->nr);
7123                         ret = -EINVAL;
7124                         goto out;
7125                 }
7126         }
7127
7128         /*
7129          * I don't think this can happen currently as we'll abort() if we catch
7130          * this case higher up, but in case somebody removes that we still can't
7131          * deal with it properly here yet, so just bail out of that's the case.
7132          */
7133         if (best->bytenr != rec->start) {
7134                 fprintf(stderr, "Extent start and backref starts don't match, "
7135                         "please use btrfs-image on this file system and send "
7136                         "it to a btrfs developer so they can make fsck fix "
7137                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
7138                         rec->start, rec->nr);
7139                 ret = -EINVAL;
7140                 goto out;
7141         }
7142
7143         /*
7144          * Ok great we all agreed on an extent record, let's go find the real
7145          * references and fix up the ones that don't match.
7146          */
7147         list_for_each_entry(back, &rec->backrefs, list) {
7148                 if (back->full_backref || !back->is_data)
7149                         continue;
7150
7151                 dback = to_data_backref(back);
7152
7153                 /*
7154                  * Still ignoring backrefs that don't have a real ref attached
7155                  * to them.
7156                  */
7157                 if (dback->found_ref == 0)
7158                         continue;
7159
7160                 if (dback->bytes == best->bytes &&
7161                     dback->disk_bytenr == best->bytenr)
7162                         continue;
7163
7164                 ret = repair_ref(info, path, dback, best);
7165                 if (ret)
7166                         goto out;
7167         }
7168
7169         /*
7170          * Ok we messed with the actual refs, which means we need to drop our
7171          * entire cache and go back and rescan.  I know this is a huge pain and
7172          * adds a lot of extra work, but it's the only way to be safe.  Once all
7173          * the backrefs agree we may not need to do anything to the extent
7174          * record itself.
7175          */
7176         ret = -EAGAIN;
7177 out:
7178         while (!list_empty(&entries)) {
7179                 entry = list_entry(entries.next, struct extent_entry, list);
7180                 list_del_init(&entry->list);
7181                 free(entry);
7182         }
7183         return ret;
7184 }
7185
7186 static int process_duplicates(struct btrfs_root *root,
7187                               struct cache_tree *extent_cache,
7188                               struct extent_record *rec)
7189 {
7190         struct extent_record *good, *tmp;
7191         struct cache_extent *cache;
7192         int ret;
7193
7194         /*
7195          * If we found a extent record for this extent then return, or if we
7196          * have more than one duplicate we are likely going to need to delete
7197          * something.
7198          */
7199         if (rec->found_rec || rec->num_duplicates > 1)
7200                 return 0;
7201
7202         /* Shouldn't happen but just in case */
7203         BUG_ON(!rec->num_duplicates);
7204
7205         /*
7206          * So this happens if we end up with a backref that doesn't match the
7207          * actual extent entry.  So either the backref is bad or the extent
7208          * entry is bad.  Either way we want to have the extent_record actually
7209          * reflect what we found in the extent_tree, so we need to take the
7210          * duplicate out and use that as the extent_record since the only way we
7211          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
7212          */
7213         remove_cache_extent(extent_cache, &rec->cache);
7214
7215         good = to_extent_record(rec->dups.next);
7216         list_del_init(&good->list);
7217         INIT_LIST_HEAD(&good->backrefs);
7218         INIT_LIST_HEAD(&good->dups);
7219         good->cache.start = good->start;
7220         good->cache.size = good->nr;
7221         good->content_checked = 0;
7222         good->owner_ref_checked = 0;
7223         good->num_duplicates = 0;
7224         good->refs = rec->refs;
7225         list_splice_init(&rec->backrefs, &good->backrefs);
7226         while (1) {
7227                 cache = lookup_cache_extent(extent_cache, good->start,
7228                                             good->nr);
7229                 if (!cache)
7230                         break;
7231                 tmp = container_of(cache, struct extent_record, cache);
7232
7233                 /*
7234                  * If we find another overlapping extent and it's found_rec is
7235                  * set then it's a duplicate and we need to try and delete
7236                  * something.
7237                  */
7238                 if (tmp->found_rec || tmp->num_duplicates > 0) {
7239                         if (list_empty(&good->list))
7240                                 list_add_tail(&good->list,
7241                                               &duplicate_extents);
7242                         good->num_duplicates += tmp->num_duplicates + 1;
7243                         list_splice_init(&tmp->dups, &good->dups);
7244                         list_del_init(&tmp->list);
7245                         list_add_tail(&tmp->list, &good->dups);
7246                         remove_cache_extent(extent_cache, &tmp->cache);
7247                         continue;
7248                 }
7249
7250                 /*
7251                  * Ok we have another non extent item backed extent rec, so lets
7252                  * just add it to this extent and carry on like we did above.
7253                  */
7254                 good->refs += tmp->refs;
7255                 list_splice_init(&tmp->backrefs, &good->backrefs);
7256                 remove_cache_extent(extent_cache, &tmp->cache);
7257                 free(tmp);
7258         }
7259         ret = insert_cache_extent(extent_cache, &good->cache);
7260         BUG_ON(ret);
7261         free(rec);
7262         return good->num_duplicates ? 0 : 1;
7263 }
7264
7265 static int delete_duplicate_records(struct btrfs_root *root,
7266                                     struct extent_record *rec)
7267 {
7268         struct btrfs_trans_handle *trans;
7269         LIST_HEAD(delete_list);
7270         struct btrfs_path path;
7271         struct extent_record *tmp, *good, *n;
7272         int nr_del = 0;
7273         int ret = 0, err;
7274         struct btrfs_key key;
7275
7276         btrfs_init_path(&path);
7277
7278         good = rec;
7279         /* Find the record that covers all of the duplicates. */
7280         list_for_each_entry(tmp, &rec->dups, list) {
7281                 if (good->start < tmp->start)
7282                         continue;
7283                 if (good->nr > tmp->nr)
7284                         continue;
7285
7286                 if (tmp->start + tmp->nr < good->start + good->nr) {
7287                         fprintf(stderr, "Ok we have overlapping extents that "
7288                                 "aren't completely covered by each other, this "
7289                                 "is going to require more careful thought.  "
7290                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
7291                                 tmp->start, tmp->nr, good->start, good->nr);
7292                         abort();
7293                 }
7294                 good = tmp;
7295         }
7296
7297         if (good != rec)
7298                 list_add_tail(&rec->list, &delete_list);
7299
7300         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
7301                 if (tmp == good)
7302                         continue;
7303                 list_move_tail(&tmp->list, &delete_list);
7304         }
7305
7306         root = root->fs_info->extent_root;
7307         trans = btrfs_start_transaction(root, 1);
7308         if (IS_ERR(trans)) {
7309                 ret = PTR_ERR(trans);
7310                 goto out;
7311         }
7312
7313         list_for_each_entry(tmp, &delete_list, list) {
7314                 if (tmp->found_rec == 0)
7315                         continue;
7316                 key.objectid = tmp->start;
7317                 key.type = BTRFS_EXTENT_ITEM_KEY;
7318                 key.offset = tmp->nr;
7319
7320                 /* Shouldn't happen but just in case */
7321                 if (tmp->metadata) {
7322                         fprintf(stderr, "Well this shouldn't happen, extent "
7323                                 "record overlaps but is metadata? "
7324                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
7325                         abort();
7326                 }
7327
7328                 ret = btrfs_search_slot(trans, root, &key, &path, -1, 1);
7329                 if (ret) {
7330                         if (ret > 0)
7331                                 ret = -EINVAL;
7332                         break;
7333                 }
7334                 ret = btrfs_del_item(trans, root, &path);
7335                 if (ret)
7336                         break;
7337                 btrfs_release_path(&path);
7338                 nr_del++;
7339         }
7340         err = btrfs_commit_transaction(trans, root);
7341         if (err && !ret)
7342                 ret = err;
7343 out:
7344         while (!list_empty(&delete_list)) {
7345                 tmp = to_extent_record(delete_list.next);
7346                 list_del_init(&tmp->list);
7347                 if (tmp == rec)
7348                         continue;
7349                 free(tmp);
7350         }
7351
7352         while (!list_empty(&rec->dups)) {
7353                 tmp = to_extent_record(rec->dups.next);
7354                 list_del_init(&tmp->list);
7355                 free(tmp);
7356         }
7357
7358         btrfs_release_path(&path);
7359
7360         if (!ret && !nr_del)
7361                 rec->num_duplicates = 0;
7362
7363         return ret ? ret : nr_del;
7364 }
7365
7366 static int find_possible_backrefs(struct btrfs_fs_info *info,
7367                                   struct btrfs_path *path,
7368                                   struct cache_tree *extent_cache,
7369                                   struct extent_record *rec)
7370 {
7371         struct btrfs_root *root;
7372         struct extent_backref *back;
7373         struct data_backref *dback;
7374         struct cache_extent *cache;
7375         struct btrfs_file_extent_item *fi;
7376         struct btrfs_key key;
7377         u64 bytenr, bytes;
7378         int ret;
7379
7380         list_for_each_entry(back, &rec->backrefs, list) {
7381                 /* Don't care about full backrefs (poor unloved backrefs) */
7382                 if (back->full_backref || !back->is_data)
7383                         continue;
7384
7385                 dback = to_data_backref(back);
7386
7387                 /* We found this one, we don't need to do a lookup */
7388                 if (dback->found_ref)
7389                         continue;
7390
7391                 key.objectid = dback->root;
7392                 key.type = BTRFS_ROOT_ITEM_KEY;
7393                 key.offset = (u64)-1;
7394
7395                 root = btrfs_read_fs_root(info, &key);
7396
7397                 /* No root, definitely a bad ref, skip */
7398                 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
7399                         continue;
7400                 /* Other err, exit */
7401                 if (IS_ERR(root))
7402                         return PTR_ERR(root);
7403
7404                 key.objectid = dback->owner;
7405                 key.type = BTRFS_EXTENT_DATA_KEY;
7406                 key.offset = dback->offset;
7407                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7408                 if (ret) {
7409                         btrfs_release_path(path);
7410                         if (ret < 0)
7411                                 return ret;
7412                         /* Didn't find it, we can carry on */
7413                         ret = 0;
7414                         continue;
7415                 }
7416
7417                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
7418                                     struct btrfs_file_extent_item);
7419                 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
7420                 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
7421                 btrfs_release_path(path);
7422                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
7423                 if (cache) {
7424                         struct extent_record *tmp;
7425                         tmp = container_of(cache, struct extent_record, cache);
7426
7427                         /*
7428                          * If we found an extent record for the bytenr for this
7429                          * particular backref then we can't add it to our
7430                          * current extent record.  We only want to add backrefs
7431                          * that don't have a corresponding extent item in the
7432                          * extent tree since they likely belong to this record
7433                          * and we need to fix it if it doesn't match bytenrs.
7434                          */
7435                         if  (tmp->found_rec)
7436                                 continue;
7437                 }
7438
7439                 dback->found_ref += 1;
7440                 dback->disk_bytenr = bytenr;
7441                 dback->bytes = bytes;
7442
7443                 /*
7444                  * Set this so the verify backref code knows not to trust the
7445                  * values in this backref.
7446                  */
7447                 back->broken = 1;
7448         }
7449
7450         return 0;
7451 }
7452
7453 /*
7454  * Record orphan data ref into corresponding root.
7455  *
7456  * Return 0 if the extent item contains data ref and recorded.
7457  * Return 1 if the extent item contains no useful data ref
7458  *   On that case, it may contains only shared_dataref or metadata backref
7459  *   or the file extent exists(this should be handled by the extent bytenr
7460  *   recovery routine)
7461  * Return <0 if something goes wrong.
7462  */
7463 static int record_orphan_data_extents(struct btrfs_fs_info *fs_info,
7464                                       struct extent_record *rec)
7465 {
7466         struct btrfs_key key;
7467         struct btrfs_root *dest_root;
7468         struct extent_backref *back;
7469         struct data_backref *dback;
7470         struct orphan_data_extent *orphan;
7471         struct btrfs_path path;
7472         int recorded_data_ref = 0;
7473         int ret = 0;
7474
7475         if (rec->metadata)
7476                 return 1;
7477         btrfs_init_path(&path);
7478         list_for_each_entry(back, &rec->backrefs, list) {
7479                 if (back->full_backref || !back->is_data ||
7480                     !back->found_extent_tree)
7481                         continue;
7482                 dback = to_data_backref(back);
7483                 if (dback->found_ref)
7484                         continue;
7485                 key.objectid = dback->root;
7486                 key.type = BTRFS_ROOT_ITEM_KEY;
7487                 key.offset = (u64)-1;
7488
7489                 dest_root = btrfs_read_fs_root(fs_info, &key);
7490
7491                 /* For non-exist root we just skip it */
7492                 if (IS_ERR(dest_root) || !dest_root)
7493                         continue;
7494
7495                 key.objectid = dback->owner;
7496                 key.type = BTRFS_EXTENT_DATA_KEY;
7497                 key.offset = dback->offset;
7498
7499                 ret = btrfs_search_slot(NULL, dest_root, &key, &path, 0, 0);
7500                 btrfs_release_path(&path);
7501                 /*
7502                  * For ret < 0, it's OK since the fs-tree may be corrupted,
7503                  * we need to record it for inode/file extent rebuild.
7504                  * For ret > 0, we record it only for file extent rebuild.
7505                  * For ret == 0, the file extent exists but only bytenr
7506                  * mismatch, let the original bytenr fix routine to handle,
7507                  * don't record it.
7508                  */
7509                 if (ret == 0)
7510                         continue;
7511                 ret = 0;
7512                 orphan = malloc(sizeof(*orphan));
7513                 if (!orphan) {
7514                         ret = -ENOMEM;
7515                         goto out;
7516                 }
7517                 INIT_LIST_HEAD(&orphan->list);
7518                 orphan->root = dback->root;
7519                 orphan->objectid = dback->owner;
7520                 orphan->offset = dback->offset;
7521                 orphan->disk_bytenr = rec->cache.start;
7522                 orphan->disk_len = rec->cache.size;
7523                 list_add(&dest_root->orphan_data_extents, &orphan->list);
7524                 recorded_data_ref = 1;
7525         }
7526 out:
7527         btrfs_release_path(&path);
7528         if (!ret)
7529                 return !recorded_data_ref;
7530         else
7531                 return ret;
7532 }
7533
7534 /*
7535  * when an incorrect extent item is found, this will delete
7536  * all of the existing entries for it and recreate them
7537  * based on what the tree scan found.
7538  */
7539 static int fixup_extent_refs(struct btrfs_fs_info *info,
7540                              struct cache_tree *extent_cache,
7541                              struct extent_record *rec)
7542 {
7543         struct btrfs_trans_handle *trans = NULL;
7544         int ret;
7545         struct btrfs_path path;
7546         struct list_head *cur = rec->backrefs.next;
7547         struct cache_extent *cache;
7548         struct extent_backref *back;
7549         int allocated = 0;
7550         u64 flags = 0;
7551
7552         if (rec->flag_block_full_backref)
7553                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7554
7555         btrfs_init_path(&path);
7556         if (rec->refs != rec->extent_item_refs && !rec->metadata) {
7557                 /*
7558                  * Sometimes the backrefs themselves are so broken they don't
7559                  * get attached to any meaningful rec, so first go back and
7560                  * check any of our backrefs that we couldn't find and throw
7561                  * them into the list if we find the backref so that
7562                  * verify_backrefs can figure out what to do.
7563                  */
7564                 ret = find_possible_backrefs(info, &path, extent_cache, rec);
7565                 if (ret < 0)
7566                         goto out;
7567         }
7568
7569         /* step one, make sure all of the backrefs agree */
7570         ret = verify_backrefs(info, &path, rec);
7571         if (ret < 0)
7572                 goto out;
7573
7574         trans = btrfs_start_transaction(info->extent_root, 1);
7575         if (IS_ERR(trans)) {
7576                 ret = PTR_ERR(trans);
7577                 goto out;
7578         }
7579
7580         /* step two, delete all the existing records */
7581         ret = delete_extent_records(trans, info->extent_root, &path,
7582                                     rec->start, rec->max_size);
7583
7584         if (ret < 0)
7585                 goto out;
7586
7587         /* was this block corrupt?  If so, don't add references to it */
7588         cache = lookup_cache_extent(info->corrupt_blocks,
7589                                     rec->start, rec->max_size);
7590         if (cache) {
7591                 ret = 0;
7592                 goto out;
7593         }
7594
7595         /* step three, recreate all the refs we did find */
7596         while(cur != &rec->backrefs) {
7597                 back = to_extent_backref(cur);
7598                 cur = cur->next;
7599
7600                 /*
7601                  * if we didn't find any references, don't create a
7602                  * new extent record
7603                  */
7604                 if (!back->found_ref)
7605                         continue;
7606
7607                 rec->bad_full_backref = 0;
7608                 ret = record_extent(trans, info, &path, rec, back, allocated, flags);
7609                 allocated = 1;
7610
7611                 if (ret)
7612                         goto out;
7613         }
7614 out:
7615         if (trans) {
7616                 int err = btrfs_commit_transaction(trans, info->extent_root);
7617                 if (!ret)
7618                         ret = err;
7619         }
7620
7621         btrfs_release_path(&path);
7622         return ret;
7623 }
7624
7625 static int fixup_extent_flags(struct btrfs_fs_info *fs_info,
7626                               struct extent_record *rec)
7627 {
7628         struct btrfs_trans_handle *trans;
7629         struct btrfs_root *root = fs_info->extent_root;
7630         struct btrfs_path *path;
7631         struct btrfs_extent_item *ei;
7632         struct btrfs_key key;
7633         u64 flags;
7634         int ret = 0;
7635
7636         key.objectid = rec->start;
7637         if (rec->metadata) {
7638                 key.type = BTRFS_METADATA_ITEM_KEY;
7639                 key.offset = rec->info_level;
7640         } else {
7641                 key.type = BTRFS_EXTENT_ITEM_KEY;
7642                 key.offset = rec->max_size;
7643         }
7644
7645         path = btrfs_alloc_path();
7646         if (!path)
7647                 return -ENOMEM;
7648
7649         trans = btrfs_start_transaction(root, 0);
7650         if (IS_ERR(trans)) {
7651                 btrfs_free_path(path);
7652                 return PTR_ERR(trans);
7653         }
7654
7655         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7656         if (ret < 0) {
7657                 btrfs_free_path(path);
7658                 btrfs_commit_transaction(trans, root);
7659                 return ret;
7660         } else if (ret) {
7661                 fprintf(stderr, "Didn't find extent for %llu\n",
7662                         (unsigned long long)rec->start);
7663                 btrfs_free_path(path);
7664                 btrfs_commit_transaction(trans, root);
7665                 return -ENOENT;
7666         }
7667
7668         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
7669                             struct btrfs_extent_item);
7670         flags = btrfs_extent_flags(path->nodes[0], ei);
7671         if (rec->flag_block_full_backref) {
7672                 fprintf(stderr, "setting full backref on %llu\n",
7673                         (unsigned long long)key.objectid);
7674                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7675         } else {
7676                 fprintf(stderr, "clearing full backref on %llu\n",
7677                         (unsigned long long)key.objectid);
7678                 flags &= ~BTRFS_BLOCK_FLAG_FULL_BACKREF;
7679         }
7680         btrfs_set_extent_flags(path->nodes[0], ei, flags);
7681         btrfs_mark_buffer_dirty(path->nodes[0]);
7682         btrfs_free_path(path);
7683         return btrfs_commit_transaction(trans, root);
7684 }
7685
7686 /* right now we only prune from the extent allocation tree */
7687 static int prune_one_block(struct btrfs_trans_handle *trans,
7688                            struct btrfs_fs_info *info,
7689                            struct btrfs_corrupt_block *corrupt)
7690 {
7691         int ret;
7692         struct btrfs_path path;
7693         struct extent_buffer *eb;
7694         u64 found;
7695         int slot;
7696         int nritems;
7697         int level = corrupt->level + 1;
7698
7699         btrfs_init_path(&path);
7700 again:
7701         /* we want to stop at the parent to our busted block */
7702         path.lowest_level = level;
7703
7704         ret = btrfs_search_slot(trans, info->extent_root,
7705                                 &corrupt->key, &path, -1, 1);
7706
7707         if (ret < 0)
7708                 goto out;
7709
7710         eb = path.nodes[level];
7711         if (!eb) {
7712                 ret = -ENOENT;
7713                 goto out;
7714         }
7715
7716         /*
7717          * hopefully the search gave us the block we want to prune,
7718          * lets try that first
7719          */
7720         slot = path.slots[level];
7721         found =  btrfs_node_blockptr(eb, slot);
7722         if (found == corrupt->cache.start)
7723                 goto del_ptr;
7724
7725         nritems = btrfs_header_nritems(eb);
7726
7727         /* the search failed, lets scan this node and hope we find it */
7728         for (slot = 0; slot < nritems; slot++) {
7729                 found =  btrfs_node_blockptr(eb, slot);
7730                 if (found == corrupt->cache.start)
7731                         goto del_ptr;
7732         }
7733         /*
7734          * we couldn't find the bad block.  TODO, search all the nodes for pointers
7735          * to this block
7736          */
7737         if (eb == info->extent_root->node) {
7738                 ret = -ENOENT;
7739                 goto out;
7740         } else {
7741                 level++;
7742                 btrfs_release_path(&path);
7743                 goto again;
7744         }
7745
7746 del_ptr:
7747         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
7748         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
7749
7750 out:
7751         btrfs_release_path(&path);
7752         return ret;
7753 }
7754
7755 static int prune_corrupt_blocks(struct btrfs_fs_info *info)
7756 {
7757         struct btrfs_trans_handle *trans = NULL;
7758         struct cache_extent *cache;
7759         struct btrfs_corrupt_block *corrupt;
7760
7761         while (1) {
7762                 cache = search_cache_extent(info->corrupt_blocks, 0);
7763                 if (!cache)
7764                         break;
7765                 if (!trans) {
7766                         trans = btrfs_start_transaction(info->extent_root, 1);
7767                         if (IS_ERR(trans))
7768                                 return PTR_ERR(trans);
7769                 }
7770                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
7771                 prune_one_block(trans, info, corrupt);
7772                 remove_cache_extent(info->corrupt_blocks, cache);
7773         }
7774         if (trans)
7775                 return btrfs_commit_transaction(trans, info->extent_root);
7776         return 0;
7777 }
7778
7779 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
7780 {
7781         struct btrfs_block_group_cache *cache;
7782         u64 start, end;
7783         int ret;
7784
7785         while (1) {
7786                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
7787                                             &start, &end, EXTENT_DIRTY);
7788                 if (ret)
7789                         break;
7790                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
7791                                    GFP_NOFS);
7792         }
7793
7794         start = 0;
7795         while (1) {
7796                 cache = btrfs_lookup_first_block_group(fs_info, start);
7797                 if (!cache)
7798                         break;
7799                 if (cache->cached)
7800                         cache->cached = 0;
7801                 start = cache->key.objectid + cache->key.offset;
7802         }
7803 }
7804
7805 static int check_extent_refs(struct btrfs_root *root,
7806                              struct cache_tree *extent_cache)
7807 {
7808         struct extent_record *rec;
7809         struct cache_extent *cache;
7810         int err = 0;
7811         int ret = 0;
7812         int fixed = 0;
7813         int had_dups = 0;
7814         int recorded = 0;
7815
7816         if (repair) {
7817                 /*
7818                  * if we're doing a repair, we have to make sure
7819                  * we don't allocate from the problem extents.
7820                  * In the worst case, this will be all the
7821                  * extents in the FS
7822                  */
7823                 cache = search_cache_extent(extent_cache, 0);
7824                 while(cache) {
7825                         rec = container_of(cache, struct extent_record, cache);
7826                         set_extent_dirty(root->fs_info->excluded_extents,
7827                                          rec->start,
7828                                          rec->start + rec->max_size - 1,
7829                                          GFP_NOFS);
7830                         cache = next_cache_extent(cache);
7831                 }
7832
7833                 /* pin down all the corrupted blocks too */
7834                 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
7835                 while(cache) {
7836                         set_extent_dirty(root->fs_info->excluded_extents,
7837                                          cache->start,
7838                                          cache->start + cache->size - 1,
7839                                          GFP_NOFS);
7840                         cache = next_cache_extent(cache);
7841                 }
7842                 prune_corrupt_blocks(root->fs_info);
7843                 reset_cached_block_groups(root->fs_info);
7844         }
7845
7846         reset_cached_block_groups(root->fs_info);
7847
7848         /*
7849          * We need to delete any duplicate entries we find first otherwise we
7850          * could mess up the extent tree when we have backrefs that actually
7851          * belong to a different extent item and not the weird duplicate one.
7852          */
7853         while (repair && !list_empty(&duplicate_extents)) {
7854                 rec = to_extent_record(duplicate_extents.next);
7855                 list_del_init(&rec->list);
7856
7857                 /* Sometimes we can find a backref before we find an actual
7858                  * extent, so we need to process it a little bit to see if there
7859                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
7860                  * if this is a backref screwup.  If we need to delete stuff
7861                  * process_duplicates() will return 0, otherwise it will return
7862                  * 1 and we
7863                  */
7864                 if (process_duplicates(root, extent_cache, rec))
7865                         continue;
7866                 ret = delete_duplicate_records(root, rec);
7867                 if (ret < 0)
7868                         return ret;
7869                 /*
7870                  * delete_duplicate_records will return the number of entries
7871                  * deleted, so if it's greater than 0 then we know we actually
7872                  * did something and we need to remove.
7873                  */
7874                 if (ret)
7875                         had_dups = 1;
7876         }
7877
7878         if (had_dups)
7879                 return -EAGAIN;
7880
7881         while(1) {
7882                 int cur_err = 0;
7883
7884                 fixed = 0;
7885                 recorded = 0;
7886                 cache = search_cache_extent(extent_cache, 0);
7887                 if (!cache)
7888                         break;
7889                 rec = container_of(cache, struct extent_record, cache);
7890                 if (rec->num_duplicates) {
7891                         fprintf(stderr, "extent item %llu has multiple extent "
7892                                 "items\n", (unsigned long long)rec->start);
7893                         err = 1;
7894                         cur_err = 1;
7895                 }
7896
7897                 if (rec->refs != rec->extent_item_refs) {
7898                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
7899                                 (unsigned long long)rec->start,
7900                                 (unsigned long long)rec->nr);
7901                         fprintf(stderr, "extent item %llu, found %llu\n",
7902                                 (unsigned long long)rec->extent_item_refs,
7903                                 (unsigned long long)rec->refs);
7904                         ret = record_orphan_data_extents(root->fs_info, rec);
7905                         if (ret < 0)
7906                                 goto repair_abort;
7907                         if (ret == 0) {
7908                                 recorded = 1;
7909                         } else {
7910                                 /*
7911                                  * we can't use the extent to repair file
7912                                  * extent, let the fallback method handle it.
7913                                  */
7914                                 if (!fixed && repair) {
7915                                         ret = fixup_extent_refs(
7916                                                         root->fs_info,
7917                                                         extent_cache, rec);
7918                                         if (ret)
7919                                                 goto repair_abort;
7920                                         fixed = 1;
7921                                 }
7922                         }
7923                         err = 1;
7924                         cur_err = 1;
7925                 }
7926                 if (all_backpointers_checked(rec, 1)) {
7927                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
7928                                 (unsigned long long)rec->start,
7929                                 (unsigned long long)rec->nr);
7930
7931                         if (!fixed && !recorded && repair) {
7932                                 ret = fixup_extent_refs(root->fs_info,
7933                                                         extent_cache, rec);
7934                                 if (ret)
7935                                         goto repair_abort;
7936                                 fixed = 1;
7937                         }
7938                         cur_err = 1;
7939                         err = 1;
7940                 }
7941                 if (!rec->owner_ref_checked) {
7942                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
7943                                 (unsigned long long)rec->start,
7944                                 (unsigned long long)rec->nr);
7945                         if (!fixed && !recorded && repair) {
7946                                 ret = fixup_extent_refs(root->fs_info,
7947                                                         extent_cache, rec);
7948                                 if (ret)
7949                                         goto repair_abort;
7950                                 fixed = 1;
7951                         }
7952                         err = 1;
7953                         cur_err = 1;
7954                 }
7955                 if (rec->bad_full_backref) {
7956                         fprintf(stderr, "bad full backref, on [%llu]\n",
7957                                 (unsigned long long)rec->start);
7958                         if (repair) {
7959                                 ret = fixup_extent_flags(root->fs_info, rec);
7960                                 if (ret)
7961                                         goto repair_abort;
7962                                 fixed = 1;
7963                         }
7964                         err = 1;
7965                         cur_err = 1;
7966                 }
7967                 /*
7968                  * Although it's not a extent ref's problem, we reuse this
7969                  * routine for error reporting.
7970                  * No repair function yet.
7971                  */
7972                 if (rec->crossing_stripes) {
7973                         fprintf(stderr,
7974                                 "bad metadata [%llu, %llu) crossing stripe boundary\n",
7975                                 rec->start, rec->start + rec->max_size);
7976                         err = 1;
7977                         cur_err = 1;
7978                 }
7979
7980                 if (rec->wrong_chunk_type) {
7981                         fprintf(stderr,
7982                                 "bad extent [%llu, %llu), type mismatch with chunk\n",
7983                                 rec->start, rec->start + rec->max_size);
7984                         err = 1;
7985                         cur_err = 1;
7986                 }
7987
7988                 remove_cache_extent(extent_cache, cache);
7989                 free_all_extent_backrefs(rec);
7990                 if (!init_extent_tree && repair && (!cur_err || fixed))
7991                         clear_extent_dirty(root->fs_info->excluded_extents,
7992                                            rec->start,
7993                                            rec->start + rec->max_size - 1,
7994                                            GFP_NOFS);
7995                 free(rec);
7996         }
7997 repair_abort:
7998         if (repair) {
7999                 if (ret && ret != -EAGAIN) {
8000                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
8001                         exit(1);
8002                 } else if (!ret) {
8003                         struct btrfs_trans_handle *trans;
8004
8005                         root = root->fs_info->extent_root;
8006                         trans = btrfs_start_transaction(root, 1);
8007                         if (IS_ERR(trans)) {
8008                                 ret = PTR_ERR(trans);
8009                                 goto repair_abort;
8010                         }
8011
8012                         btrfs_fix_block_accounting(trans, root);
8013                         ret = btrfs_commit_transaction(trans, root);
8014                         if (ret)
8015                                 goto repair_abort;
8016                 }
8017                 if (err)
8018                         fprintf(stderr, "repaired damaged extent references\n");
8019                 return ret;
8020         }
8021         return err;
8022 }
8023
8024 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
8025 {
8026         u64 stripe_size;
8027
8028         if (type & BTRFS_BLOCK_GROUP_RAID0) {
8029                 stripe_size = length;
8030                 stripe_size /= num_stripes;
8031         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
8032                 stripe_size = length * 2;
8033                 stripe_size /= num_stripes;
8034         } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
8035                 stripe_size = length;
8036                 stripe_size /= (num_stripes - 1);
8037         } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
8038                 stripe_size = length;
8039                 stripe_size /= (num_stripes - 2);
8040         } else {
8041                 stripe_size = length;
8042         }
8043         return stripe_size;
8044 }
8045
8046 /*
8047  * Check the chunk with its block group/dev list ref:
8048  * Return 0 if all refs seems valid.
8049  * Return 1 if part of refs seems valid, need later check for rebuild ref
8050  * like missing block group and needs to search extent tree to rebuild them.
8051  * Return -1 if essential refs are missing and unable to rebuild.
8052  */
8053 static int check_chunk_refs(struct chunk_record *chunk_rec,
8054                             struct block_group_tree *block_group_cache,
8055                             struct device_extent_tree *dev_extent_cache,
8056                             int silent)
8057 {
8058         struct cache_extent *block_group_item;
8059         struct block_group_record *block_group_rec;
8060         struct cache_extent *dev_extent_item;
8061         struct device_extent_record *dev_extent_rec;
8062         u64 devid;
8063         u64 offset;
8064         u64 length;
8065         int metadump_v2 = 0;
8066         int i;
8067         int ret = 0;
8068
8069         block_group_item = lookup_cache_extent(&block_group_cache->tree,
8070                                                chunk_rec->offset,
8071                                                chunk_rec->length);
8072         if (block_group_item) {
8073                 block_group_rec = container_of(block_group_item,
8074                                                struct block_group_record,
8075                                                cache);
8076                 if (chunk_rec->length != block_group_rec->offset ||
8077                     chunk_rec->offset != block_group_rec->objectid ||
8078                     (!metadump_v2 &&
8079                      chunk_rec->type_flags != block_group_rec->flags)) {
8080                         if (!silent)
8081                                 fprintf(stderr,
8082                                         "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
8083                                         chunk_rec->objectid,
8084                                         chunk_rec->type,
8085                                         chunk_rec->offset,
8086                                         chunk_rec->length,
8087                                         chunk_rec->offset,
8088                                         chunk_rec->type_flags,
8089                                         block_group_rec->objectid,
8090                                         block_group_rec->type,
8091                                         block_group_rec->offset,
8092                                         block_group_rec->offset,
8093                                         block_group_rec->objectid,
8094                                         block_group_rec->flags);
8095                         ret = -1;
8096                 } else {
8097                         list_del_init(&block_group_rec->list);
8098                         chunk_rec->bg_rec = block_group_rec;
8099                 }
8100         } else {
8101                 if (!silent)
8102                         fprintf(stderr,
8103                                 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
8104                                 chunk_rec->objectid,
8105                                 chunk_rec->type,
8106                                 chunk_rec->offset,
8107                                 chunk_rec->length,
8108                                 chunk_rec->offset,
8109                                 chunk_rec->type_flags);
8110                 ret = 1;
8111         }
8112
8113         if (metadump_v2)
8114                 return ret;
8115
8116         length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
8117                                     chunk_rec->num_stripes);
8118         for (i = 0; i < chunk_rec->num_stripes; ++i) {
8119                 devid = chunk_rec->stripes[i].devid;
8120                 offset = chunk_rec->stripes[i].offset;
8121                 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
8122                                                        devid, offset, length);
8123                 if (dev_extent_item) {
8124                         dev_extent_rec = container_of(dev_extent_item,
8125                                                 struct device_extent_record,
8126                                                 cache);
8127                         if (dev_extent_rec->objectid != devid ||
8128                             dev_extent_rec->offset != offset ||
8129                             dev_extent_rec->chunk_offset != chunk_rec->offset ||
8130                             dev_extent_rec->length != length) {
8131                                 if (!silent)
8132                                         fprintf(stderr,
8133                                                 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
8134                                                 chunk_rec->objectid,
8135                                                 chunk_rec->type,
8136                                                 chunk_rec->offset,
8137                                                 chunk_rec->stripes[i].devid,
8138                                                 chunk_rec->stripes[i].offset,
8139                                                 dev_extent_rec->objectid,
8140                                                 dev_extent_rec->offset,
8141                                                 dev_extent_rec->length);
8142                                 ret = -1;
8143                         } else {
8144                                 list_move(&dev_extent_rec->chunk_list,
8145                                           &chunk_rec->dextents);
8146                         }
8147                 } else {
8148                         if (!silent)
8149                                 fprintf(stderr,
8150                                         "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
8151                                         chunk_rec->objectid,
8152                                         chunk_rec->type,
8153                                         chunk_rec->offset,
8154                                         chunk_rec->stripes[i].devid,
8155                                         chunk_rec->stripes[i].offset);
8156                         ret = -1;
8157                 }
8158         }
8159         return ret;
8160 }
8161
8162 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
8163 int check_chunks(struct cache_tree *chunk_cache,
8164                  struct block_group_tree *block_group_cache,
8165                  struct device_extent_tree *dev_extent_cache,
8166                  struct list_head *good, struct list_head *bad,
8167                  struct list_head *rebuild, int silent)
8168 {
8169         struct cache_extent *chunk_item;
8170         struct chunk_record *chunk_rec;
8171         struct block_group_record *bg_rec;
8172         struct device_extent_record *dext_rec;
8173         int err;
8174         int ret = 0;
8175
8176         chunk_item = first_cache_extent(chunk_cache);
8177         while (chunk_item) {
8178                 chunk_rec = container_of(chunk_item, struct chunk_record,
8179                                          cache);
8180                 err = check_chunk_refs(chunk_rec, block_group_cache,
8181                                        dev_extent_cache, silent);
8182                 if (err < 0)
8183                         ret = err;
8184                 if (err == 0 && good)
8185                         list_add_tail(&chunk_rec->list, good);
8186                 if (err > 0 && rebuild)
8187                         list_add_tail(&chunk_rec->list, rebuild);
8188                 if (err < 0 && bad)
8189                         list_add_tail(&chunk_rec->list, bad);
8190                 chunk_item = next_cache_extent(chunk_item);
8191         }
8192
8193         list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
8194                 if (!silent)
8195                         fprintf(stderr,
8196                                 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
8197                                 bg_rec->objectid,
8198                                 bg_rec->offset,
8199                                 bg_rec->flags);
8200                 if (!ret)
8201                         ret = 1;
8202         }
8203
8204         list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
8205                             chunk_list) {
8206                 if (!silent)
8207                         fprintf(stderr,
8208                                 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
8209                                 dext_rec->objectid,
8210                                 dext_rec->offset,
8211                                 dext_rec->length);
8212                 if (!ret)
8213                         ret = 1;
8214         }
8215         return ret;
8216 }
8217
8218
8219 static int check_device_used(struct device_record *dev_rec,
8220                              struct device_extent_tree *dext_cache)
8221 {
8222         struct cache_extent *cache;
8223         struct device_extent_record *dev_extent_rec;
8224         u64 total_byte = 0;
8225
8226         cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
8227         while (cache) {
8228                 dev_extent_rec = container_of(cache,
8229                                               struct device_extent_record,
8230                                               cache);
8231                 if (dev_extent_rec->objectid != dev_rec->devid)
8232                         break;
8233
8234                 list_del_init(&dev_extent_rec->device_list);
8235                 total_byte += dev_extent_rec->length;
8236                 cache = next_cache_extent(cache);
8237         }
8238
8239         if (total_byte != dev_rec->byte_used) {
8240                 fprintf(stderr,
8241                         "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
8242                         total_byte, dev_rec->byte_used, dev_rec->objectid,
8243                         dev_rec->type, dev_rec->offset);
8244                 return -1;
8245         } else {
8246                 return 0;
8247         }
8248 }
8249
8250 /* check btrfs_dev_item -> btrfs_dev_extent */
8251 static int check_devices(struct rb_root *dev_cache,
8252                          struct device_extent_tree *dev_extent_cache)
8253 {
8254         struct rb_node *dev_node;
8255         struct device_record *dev_rec;
8256         struct device_extent_record *dext_rec;
8257         int err;
8258         int ret = 0;
8259
8260         dev_node = rb_first(dev_cache);
8261         while (dev_node) {
8262                 dev_rec = container_of(dev_node, struct device_record, node);
8263                 err = check_device_used(dev_rec, dev_extent_cache);
8264                 if (err)
8265                         ret = err;
8266
8267                 dev_node = rb_next(dev_node);
8268         }
8269         list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
8270                             device_list) {
8271                 fprintf(stderr,
8272                         "Device extent[%llu, %llu, %llu] didn't find its device.\n",
8273                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
8274                 if (!ret)
8275                         ret = 1;
8276         }
8277         return ret;
8278 }
8279
8280 static int add_root_item_to_list(struct list_head *head,
8281                                   u64 objectid, u64 bytenr, u64 last_snapshot,
8282                                   u8 level, u8 drop_level,
8283                                   int level_size, struct btrfs_key *drop_key)
8284 {
8285
8286         struct root_item_record *ri_rec;
8287         ri_rec = malloc(sizeof(*ri_rec));
8288         if (!ri_rec)
8289                 return -ENOMEM;
8290         ri_rec->bytenr = bytenr;
8291         ri_rec->objectid = objectid;
8292         ri_rec->level = level;
8293         ri_rec->level_size = level_size;
8294         ri_rec->drop_level = drop_level;
8295         ri_rec->last_snapshot = last_snapshot;
8296         if (drop_key)
8297                 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
8298         list_add_tail(&ri_rec->list, head);
8299
8300         return 0;
8301 }
8302
8303 static void free_root_item_list(struct list_head *list)
8304 {
8305         struct root_item_record *ri_rec;
8306
8307         while (!list_empty(list)) {
8308                 ri_rec = list_first_entry(list, struct root_item_record,
8309                                           list);
8310                 list_del_init(&ri_rec->list);
8311                 free(ri_rec);
8312         }
8313 }
8314
8315 static int deal_root_from_list(struct list_head *list,
8316                                struct btrfs_root *root,
8317                                struct block_info *bits,
8318                                int bits_nr,
8319                                struct cache_tree *pending,
8320                                struct cache_tree *seen,
8321                                struct cache_tree *reada,
8322                                struct cache_tree *nodes,
8323                                struct cache_tree *extent_cache,
8324                                struct cache_tree *chunk_cache,
8325                                struct rb_root *dev_cache,
8326                                struct block_group_tree *block_group_cache,
8327                                struct device_extent_tree *dev_extent_cache)
8328 {
8329         int ret = 0;
8330         u64 last;
8331
8332         while (!list_empty(list)) {
8333                 struct root_item_record *rec;
8334                 struct extent_buffer *buf;
8335                 rec = list_entry(list->next,
8336                                  struct root_item_record, list);
8337                 last = 0;
8338                 buf = read_tree_block(root->fs_info->tree_root,
8339                                       rec->bytenr, rec->level_size, 0);
8340                 if (!extent_buffer_uptodate(buf)) {
8341                         free_extent_buffer(buf);
8342                         ret = -EIO;
8343                         break;
8344                 }
8345                 ret = add_root_to_pending(buf, extent_cache, pending,
8346                                     seen, nodes, rec->objectid);
8347                 if (ret < 0)
8348                         break;
8349                 /*
8350                  * To rebuild extent tree, we need deal with snapshot
8351                  * one by one, otherwise we deal with node firstly which
8352                  * can maximize readahead.
8353                  */
8354                 while (1) {
8355                         ret = run_next_block(root, bits, bits_nr, &last,
8356                                              pending, seen, reada, nodes,
8357                                              extent_cache, chunk_cache,
8358                                              dev_cache, block_group_cache,
8359                                              dev_extent_cache, rec);
8360                         if (ret != 0)
8361                                 break;
8362                 }
8363                 free_extent_buffer(buf);
8364                 list_del(&rec->list);
8365                 free(rec);
8366                 if (ret < 0)
8367                         break;
8368         }
8369         while (ret >= 0) {
8370                 ret = run_next_block(root, bits, bits_nr, &last, pending, seen,
8371                                      reada, nodes, extent_cache, chunk_cache,
8372                                      dev_cache, block_group_cache,
8373                                      dev_extent_cache, NULL);
8374                 if (ret != 0) {
8375                         if (ret > 0)
8376                                 ret = 0;
8377                         break;
8378                 }
8379         }
8380         return ret;
8381 }
8382
8383 static int check_chunks_and_extents(struct btrfs_root *root)
8384 {
8385         struct rb_root dev_cache;
8386         struct cache_tree chunk_cache;
8387         struct block_group_tree block_group_cache;
8388         struct device_extent_tree dev_extent_cache;
8389         struct cache_tree extent_cache;
8390         struct cache_tree seen;
8391         struct cache_tree pending;
8392         struct cache_tree reada;
8393         struct cache_tree nodes;
8394         struct extent_io_tree excluded_extents;
8395         struct cache_tree corrupt_blocks;
8396         struct btrfs_path path;
8397         struct btrfs_key key;
8398         struct btrfs_key found_key;
8399         int ret, err = 0;
8400         struct block_info *bits;
8401         int bits_nr;
8402         struct extent_buffer *leaf;
8403         int slot;
8404         struct btrfs_root_item ri;
8405         struct list_head dropping_trees;
8406         struct list_head normal_trees;
8407         struct btrfs_root *root1;
8408         u64 objectid;
8409         u32 level_size;
8410         u8 level;
8411
8412         dev_cache = RB_ROOT;
8413         cache_tree_init(&chunk_cache);
8414         block_group_tree_init(&block_group_cache);
8415         device_extent_tree_init(&dev_extent_cache);
8416
8417         cache_tree_init(&extent_cache);
8418         cache_tree_init(&seen);
8419         cache_tree_init(&pending);
8420         cache_tree_init(&nodes);
8421         cache_tree_init(&reada);
8422         cache_tree_init(&corrupt_blocks);
8423         extent_io_tree_init(&excluded_extents);
8424         INIT_LIST_HEAD(&dropping_trees);
8425         INIT_LIST_HEAD(&normal_trees);
8426
8427         if (repair) {
8428                 root->fs_info->excluded_extents = &excluded_extents;
8429                 root->fs_info->fsck_extent_cache = &extent_cache;
8430                 root->fs_info->free_extent_hook = free_extent_hook;
8431                 root->fs_info->corrupt_blocks = &corrupt_blocks;
8432         }
8433
8434         bits_nr = 1024;
8435         bits = malloc(bits_nr * sizeof(struct block_info));
8436         if (!bits) {
8437                 perror("malloc");
8438                 exit(1);
8439         }
8440
8441         if (ctx.progress_enabled) {
8442                 ctx.tp = TASK_EXTENTS;
8443                 task_start(ctx.info);
8444         }
8445
8446 again:
8447         root1 = root->fs_info->tree_root;
8448         level = btrfs_header_level(root1->node);
8449         ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
8450                                     root1->node->start, 0, level, 0,
8451                                     root1->nodesize, NULL);
8452         if (ret < 0)
8453                 goto out;
8454         root1 = root->fs_info->chunk_root;
8455         level = btrfs_header_level(root1->node);
8456         ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
8457                                     root1->node->start, 0, level, 0,
8458                                     root1->nodesize, NULL);
8459         if (ret < 0)
8460                 goto out;
8461         btrfs_init_path(&path);
8462         key.offset = 0;
8463         key.objectid = 0;
8464         key.type = BTRFS_ROOT_ITEM_KEY;
8465         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
8466                                         &key, &path, 0, 0);
8467         if (ret < 0)
8468                 goto out;
8469         while(1) {
8470                 leaf = path.nodes[0];
8471                 slot = path.slots[0];
8472                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
8473                         ret = btrfs_next_leaf(root, &path);
8474                         if (ret != 0)
8475                                 break;
8476                         leaf = path.nodes[0];
8477                         slot = path.slots[0];
8478                 }
8479                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
8480                 if (found_key.type == BTRFS_ROOT_ITEM_KEY) {
8481                         unsigned long offset;
8482                         u64 last_snapshot;
8483
8484                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
8485                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
8486                         last_snapshot = btrfs_root_last_snapshot(&ri);
8487                         if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
8488                                 level = btrfs_root_level(&ri);
8489                                 level_size = root->nodesize;
8490                                 ret = add_root_item_to_list(&normal_trees,
8491                                                 found_key.objectid,
8492                                                 btrfs_root_bytenr(&ri),
8493                                                 last_snapshot, level,
8494                                                 0, level_size, NULL);
8495                                 if (ret < 0)
8496                                         goto out;
8497                         } else {
8498                                 level = btrfs_root_level(&ri);
8499                                 level_size = root->nodesize;
8500                                 objectid = found_key.objectid;
8501                                 btrfs_disk_key_to_cpu(&found_key,
8502                                                       &ri.drop_progress);
8503                                 ret = add_root_item_to_list(&dropping_trees,
8504                                                 objectid,
8505                                                 btrfs_root_bytenr(&ri),
8506                                                 last_snapshot, level,
8507                                                 ri.drop_level,
8508                                                 level_size, &found_key);
8509                                 if (ret < 0)
8510                                         goto out;
8511                         }
8512                 }
8513                 path.slots[0]++;
8514         }
8515         btrfs_release_path(&path);
8516
8517         /*
8518          * check_block can return -EAGAIN if it fixes something, please keep
8519          * this in mind when dealing with return values from these functions, if
8520          * we get -EAGAIN we want to fall through and restart the loop.
8521          */
8522         ret = deal_root_from_list(&normal_trees, root, bits, bits_nr, &pending,
8523                                   &seen, &reada, &nodes, &extent_cache,
8524                                   &chunk_cache, &dev_cache, &block_group_cache,
8525                                   &dev_extent_cache);
8526         if (ret < 0) {
8527                 if (ret == -EAGAIN)
8528                         goto loop;
8529                 goto out;
8530         }
8531         ret = deal_root_from_list(&dropping_trees, root, bits, bits_nr,
8532                                   &pending, &seen, &reada, &nodes,
8533                                   &extent_cache, &chunk_cache, &dev_cache,
8534                                   &block_group_cache, &dev_extent_cache);
8535         if (ret < 0) {
8536                 if (ret == -EAGAIN)
8537                         goto loop;
8538                 goto out;
8539         }
8540
8541         ret = check_chunks(&chunk_cache, &block_group_cache,
8542                            &dev_extent_cache, NULL, NULL, NULL, 0);
8543         if (ret) {
8544                 if (ret == -EAGAIN)
8545                         goto loop;
8546                 err = ret;
8547         }
8548
8549         ret = check_extent_refs(root, &extent_cache);
8550         if (ret < 0) {
8551                 if (ret == -EAGAIN)
8552                         goto loop;
8553                 goto out;
8554         }
8555
8556         ret = check_devices(&dev_cache, &dev_extent_cache);
8557         if (ret && err)
8558                 ret = err;
8559
8560 out:
8561         task_stop(ctx.info);
8562         if (repair) {
8563                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8564                 extent_io_tree_cleanup(&excluded_extents);
8565                 root->fs_info->fsck_extent_cache = NULL;
8566                 root->fs_info->free_extent_hook = NULL;
8567                 root->fs_info->corrupt_blocks = NULL;
8568                 root->fs_info->excluded_extents = NULL;
8569         }
8570         free(bits);
8571         free_chunk_cache_tree(&chunk_cache);
8572         free_device_cache_tree(&dev_cache);
8573         free_block_group_tree(&block_group_cache);
8574         free_device_extent_tree(&dev_extent_cache);
8575         free_extent_cache_tree(&seen);
8576         free_extent_cache_tree(&pending);
8577         free_extent_cache_tree(&reada);
8578         free_extent_cache_tree(&nodes);
8579         return ret;
8580 loop:
8581         free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
8582         free_extent_cache_tree(&seen);
8583         free_extent_cache_tree(&pending);
8584         free_extent_cache_tree(&reada);
8585         free_extent_cache_tree(&nodes);
8586         free_chunk_cache_tree(&chunk_cache);
8587         free_block_group_tree(&block_group_cache);
8588         free_device_cache_tree(&dev_cache);
8589         free_device_extent_tree(&dev_extent_cache);
8590         free_extent_record_cache(root->fs_info, &extent_cache);
8591         free_root_item_list(&normal_trees);
8592         free_root_item_list(&dropping_trees);
8593         extent_io_tree_cleanup(&excluded_extents);
8594         goto again;
8595 }
8596
8597 /*
8598  * Check backrefs of a tree block given by @bytenr or @eb.
8599  *
8600  * @root:       the root containing the @bytenr or @eb
8601  * @eb:         tree block extent buffer, can be NULL
8602  * @bytenr:     bytenr of the tree block to search
8603  * @level:      tree level of the tree block
8604  * @owner:      owner of the tree block
8605  *
8606  * Return >0 for any error found and output error message
8607  * Return 0 for no error found
8608  */
8609 static int check_tree_block_ref(struct btrfs_root *root,
8610                                 struct extent_buffer *eb, u64 bytenr,
8611                                 int level, u64 owner)
8612 {
8613         struct btrfs_key key;
8614         struct btrfs_root *extent_root = root->fs_info->extent_root;
8615         struct btrfs_path path;
8616         struct btrfs_extent_item *ei;
8617         struct btrfs_extent_inline_ref *iref;
8618         struct extent_buffer *leaf;
8619         unsigned long end;
8620         unsigned long ptr;
8621         int slot;
8622         int skinny_level;
8623         int type;
8624         u32 nodesize = root->nodesize;
8625         u32 item_size;
8626         u64 offset;
8627         int found_ref = 0;
8628         int err = 0;
8629         int ret;
8630
8631         btrfs_init_path(&path);
8632         key.objectid = bytenr;
8633         if (btrfs_fs_incompat(root->fs_info,
8634                               BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA))
8635                 key.type = BTRFS_METADATA_ITEM_KEY;
8636         else
8637                 key.type = BTRFS_EXTENT_ITEM_KEY;
8638         key.offset = (u64)-1;
8639
8640         /* Search for the backref in extent tree */
8641         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
8642         if (ret < 0) {
8643                 err |= BACKREF_MISSING;
8644                 goto out;
8645         }
8646         ret = btrfs_previous_extent_item(extent_root, &path, bytenr);
8647         if (ret) {
8648                 err |= BACKREF_MISSING;
8649                 goto out;
8650         }
8651
8652         leaf = path.nodes[0];
8653         slot = path.slots[0];
8654         btrfs_item_key_to_cpu(leaf, &key, slot);
8655
8656         ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8657
8658         if (key.type == BTRFS_METADATA_ITEM_KEY) {
8659                 skinny_level = (int)key.offset;
8660                 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8661         } else {
8662                 struct btrfs_tree_block_info *info;
8663
8664                 info = (struct btrfs_tree_block_info *)(ei + 1);
8665                 skinny_level = btrfs_tree_block_level(leaf, info);
8666                 iref = (struct btrfs_extent_inline_ref *)(info + 1);
8667         }
8668
8669         if (eb) {
8670                 u64 header_gen;
8671                 u64 extent_gen;
8672
8673                 if (!(btrfs_extent_flags(leaf, ei) &
8674                       BTRFS_EXTENT_FLAG_TREE_BLOCK)) {
8675                         error(
8676                 "extent[%llu %u] backref type mismatch, missing bit: %llx",
8677                                 key.objectid, nodesize,
8678                                 BTRFS_EXTENT_FLAG_TREE_BLOCK);
8679                         err = BACKREF_MISMATCH;
8680                 }
8681                 header_gen = btrfs_header_generation(eb);
8682                 extent_gen = btrfs_extent_generation(leaf, ei);
8683                 if (header_gen != extent_gen) {
8684                         error(
8685         "extent[%llu %u] backref generation mismatch, wanted: %llu, have: %llu",
8686                                 key.objectid, nodesize, header_gen,
8687                                 extent_gen);
8688                         err = BACKREF_MISMATCH;
8689                 }
8690                 if (level != skinny_level) {
8691                         error(
8692                         "extent[%llu %u] level mismatch, wanted: %u, have: %u",
8693                                 key.objectid, nodesize, level, skinny_level);
8694                         err = BACKREF_MISMATCH;
8695                 }
8696                 if (!is_fstree(owner) && btrfs_extent_refs(leaf, ei) != 1) {
8697                         error(
8698                         "extent[%llu %u] is referred by other roots than %llu",
8699                                 key.objectid, nodesize, root->objectid);
8700                         err = BACKREF_MISMATCH;
8701                 }
8702         }
8703
8704         /*
8705          * Iterate the extent/metadata item to find the exact backref
8706          */
8707         item_size = btrfs_item_size_nr(leaf, slot);
8708         ptr = (unsigned long)iref;
8709         end = (unsigned long)ei + item_size;
8710         while (ptr < end) {
8711                 iref = (struct btrfs_extent_inline_ref *)ptr;
8712                 type = btrfs_extent_inline_ref_type(leaf, iref);
8713                 offset = btrfs_extent_inline_ref_offset(leaf, iref);
8714
8715                 if (type == BTRFS_TREE_BLOCK_REF_KEY &&
8716                         (offset == root->objectid || offset == owner)) {
8717                         found_ref = 1;
8718                 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
8719                         /* Check if the backref points to valid referencer */
8720                         found_ref = !check_tree_block_ref(root, NULL, offset,
8721                                                           level + 1, owner);
8722                 }
8723
8724                 if (found_ref)
8725                         break;
8726                 ptr += btrfs_extent_inline_ref_size(type);
8727         }
8728
8729         /*
8730          * Inlined extent item doesn't have what we need, check
8731          * TREE_BLOCK_REF_KEY
8732          */
8733         if (!found_ref) {
8734                 btrfs_release_path(&path);
8735                 key.objectid = bytenr;
8736                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
8737                 key.offset = root->objectid;
8738
8739                 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
8740                 if (!ret)
8741                         found_ref = 1;
8742         }
8743         if (!found_ref)
8744                 err |= BACKREF_MISSING;
8745 out:
8746         btrfs_release_path(&path);
8747         if (eb && (err & BACKREF_MISSING))
8748                 error("extent[%llu %u] backref lost (owner: %llu, level: %u)",
8749                         bytenr, nodesize, owner, level);
8750         return err;
8751 }
8752
8753 /*
8754  * Check EXTENT_DATA item, mainly for its dbackref in extent tree
8755  *
8756  * Return >0 any error found and output error message
8757  * Return 0 for no error found
8758  */
8759 static int check_extent_data_item(struct btrfs_root *root,
8760                                   struct extent_buffer *eb, int slot)
8761 {
8762         struct btrfs_file_extent_item *fi;
8763         struct btrfs_path path;
8764         struct btrfs_root *extent_root = root->fs_info->extent_root;
8765         struct btrfs_key fi_key;
8766         struct btrfs_key dbref_key;
8767         struct extent_buffer *leaf;
8768         struct btrfs_extent_item *ei;
8769         struct btrfs_extent_inline_ref *iref;
8770         struct btrfs_extent_data_ref *dref;
8771         u64 owner;
8772         u64 file_extent_gen;
8773         u64 disk_bytenr;
8774         u64 disk_num_bytes;
8775         u64 extent_num_bytes;
8776         u64 extent_flags;
8777         u64 extent_gen;
8778         u32 item_size;
8779         unsigned long end;
8780         unsigned long ptr;
8781         int type;
8782         u64 ref_root;
8783         int found_dbackref = 0;
8784         int err = 0;
8785         int ret;
8786
8787         btrfs_item_key_to_cpu(eb, &fi_key, slot);
8788         fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
8789         file_extent_gen = btrfs_file_extent_generation(eb, fi);
8790
8791         /* Nothing to check for hole and inline data extents */
8792         if (btrfs_file_extent_type(eb, fi) == BTRFS_FILE_EXTENT_INLINE ||
8793             btrfs_file_extent_disk_bytenr(eb, fi) == 0)
8794                 return 0;
8795
8796         disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
8797         disk_num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
8798         extent_num_bytes = btrfs_file_extent_num_bytes(eb, fi);
8799
8800         /* Check unaligned disk_num_bytes and num_bytes */
8801         if (!IS_ALIGNED(disk_num_bytes, root->sectorsize)) {
8802                 error(
8803 "file extent [%llu, %llu] has unaligned disk num bytes: %llu, should be aligned to %u",
8804                         fi_key.objectid, fi_key.offset, disk_num_bytes,
8805                         root->sectorsize);
8806                 err |= BYTES_UNALIGNED;
8807         } else {
8808                 data_bytes_allocated += disk_num_bytes;
8809         }
8810         if (!IS_ALIGNED(extent_num_bytes, root->sectorsize)) {
8811                 error(
8812 "file extent [%llu, %llu] has unaligned num bytes: %llu, should be aligned to %u",
8813                         fi_key.objectid, fi_key.offset, extent_num_bytes,
8814                         root->sectorsize);
8815                 err |= BYTES_UNALIGNED;
8816         } else {
8817                 data_bytes_referenced += extent_num_bytes;
8818         }
8819         owner = btrfs_header_owner(eb);
8820
8821         /* Check the extent item of the file extent in extent tree */
8822         btrfs_init_path(&path);
8823         dbref_key.objectid = btrfs_file_extent_disk_bytenr(eb, fi);
8824         dbref_key.type = BTRFS_EXTENT_ITEM_KEY;
8825         dbref_key.offset = btrfs_file_extent_disk_num_bytes(eb, fi);
8826
8827         ret = btrfs_search_slot(NULL, extent_root, &dbref_key, &path, 0, 0);
8828         if (ret) {
8829                 err |= BACKREF_MISSING;
8830                 goto error;
8831         }
8832
8833         leaf = path.nodes[0];
8834         slot = path.slots[0];
8835         ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8836
8837         extent_flags = btrfs_extent_flags(leaf, ei);
8838         extent_gen = btrfs_extent_generation(leaf, ei);
8839
8840         if (!(extent_flags & BTRFS_EXTENT_FLAG_DATA)) {
8841                 error(
8842                     "extent[%llu %llu] backref type mismatch, wanted bit: %llx",
8843                     disk_bytenr, disk_num_bytes,
8844                     BTRFS_EXTENT_FLAG_DATA);
8845                 err |= BACKREF_MISMATCH;
8846         }
8847
8848         if (file_extent_gen < extent_gen) {
8849                 error(
8850 "extent[%llu %llu] backref generation mismatch, wanted: <=%llu, have: %llu",
8851                         disk_bytenr, disk_num_bytes, file_extent_gen,
8852                         extent_gen);
8853                 err |= BACKREF_MISMATCH;
8854         }
8855
8856         /* Check data backref inside that extent item */
8857         item_size = btrfs_item_size_nr(leaf, path.slots[0]);
8858         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8859         ptr = (unsigned long)iref;
8860         end = (unsigned long)ei + item_size;
8861         while (ptr < end) {
8862                 iref = (struct btrfs_extent_inline_ref *)ptr;
8863                 type = btrfs_extent_inline_ref_type(leaf, iref);
8864                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
8865
8866                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
8867                         ref_root = btrfs_extent_data_ref_root(leaf, dref);
8868                         if (ref_root == owner || ref_root == root->objectid)
8869                                 found_dbackref = 1;
8870                 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
8871                         found_dbackref = !check_tree_block_ref(root, NULL,
8872                                 btrfs_extent_inline_ref_offset(leaf, iref),
8873                                 0, owner);
8874                 }
8875
8876                 if (found_dbackref)
8877                         break;
8878                 ptr += btrfs_extent_inline_ref_size(type);
8879         }
8880
8881         /* Didn't found inlined data backref, try EXTENT_DATA_REF_KEY */
8882         if (!found_dbackref) {
8883                 btrfs_release_path(&path);
8884
8885                 btrfs_init_path(&path);
8886                 dbref_key.objectid = btrfs_file_extent_disk_bytenr(eb, fi);
8887                 dbref_key.type = BTRFS_EXTENT_DATA_REF_KEY;
8888                 dbref_key.offset = hash_extent_data_ref(root->objectid,
8889                                 fi_key.objectid, fi_key.offset);
8890
8891                 ret = btrfs_search_slot(NULL, root->fs_info->extent_root,
8892                                         &dbref_key, &path, 0, 0);
8893                 if (!ret)
8894                         found_dbackref = 1;
8895         }
8896
8897         if (!found_dbackref)
8898                 err |= BACKREF_MISSING;
8899 error:
8900         btrfs_release_path(&path);
8901         if (err & BACKREF_MISSING) {
8902                 error("data extent[%llu %llu] backref lost",
8903                       disk_bytenr, disk_num_bytes);
8904         }
8905         return err;
8906 }
8907
8908 /*
8909  * Get real tree block level for the case like shared block
8910  * Return >= 0 as tree level
8911  * Return <0 for error
8912  */
8913 static int query_tree_block_level(struct btrfs_fs_info *fs_info, u64 bytenr)
8914 {
8915         struct extent_buffer *eb;
8916         struct btrfs_path path;
8917         struct btrfs_key key;
8918         struct btrfs_extent_item *ei;
8919         u64 flags;
8920         u64 transid;
8921         u32 nodesize = btrfs_super_nodesize(fs_info->super_copy);
8922         u8 backref_level;
8923         u8 header_level;
8924         int ret;
8925
8926         /* Search extent tree for extent generation and level */
8927         key.objectid = bytenr;
8928         key.type = BTRFS_METADATA_ITEM_KEY;
8929         key.offset = (u64)-1;
8930
8931         btrfs_init_path(&path);
8932         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, &path, 0, 0);
8933         if (ret < 0)
8934                 goto release_out;
8935         ret = btrfs_previous_extent_item(fs_info->extent_root, &path, bytenr);
8936         if (ret < 0)
8937                 goto release_out;
8938         if (ret > 0) {
8939                 ret = -ENOENT;
8940                 goto release_out;
8941         }
8942
8943         btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
8944         ei = btrfs_item_ptr(path.nodes[0], path.slots[0],
8945                             struct btrfs_extent_item);
8946         flags = btrfs_extent_flags(path.nodes[0], ei);
8947         if (!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)) {
8948                 ret = -ENOENT;
8949                 goto release_out;
8950         }
8951
8952         /* Get transid for later read_tree_block() check */
8953         transid = btrfs_extent_generation(path.nodes[0], ei);
8954
8955         /* Get backref level as one source */
8956         if (key.type == BTRFS_METADATA_ITEM_KEY) {
8957                 backref_level = key.offset;
8958         } else {
8959                 struct btrfs_tree_block_info *info;
8960
8961                 info = (struct btrfs_tree_block_info *)(ei + 1);
8962                 backref_level = btrfs_tree_block_level(path.nodes[0], info);
8963         }
8964         btrfs_release_path(&path);
8965
8966         /* Get level from tree block as an alternative source */
8967         eb = read_tree_block_fs_info(fs_info, bytenr, nodesize, transid);
8968         if (!extent_buffer_uptodate(eb)) {
8969                 free_extent_buffer(eb);
8970                 return -EIO;
8971         }
8972         header_level = btrfs_header_level(eb);
8973         free_extent_buffer(eb);
8974
8975         if (header_level != backref_level)
8976                 return -EIO;
8977         return header_level;
8978
8979 release_out:
8980         btrfs_release_path(&path);
8981         return ret;
8982 }
8983
8984 /*
8985  * Check if a tree block backref is valid (points to a valid tree block)
8986  * if level == -1, level will be resolved
8987  * Return >0 for any error found and print error message
8988  */
8989 static int check_tree_block_backref(struct btrfs_fs_info *fs_info, u64 root_id,
8990                                     u64 bytenr, int level)
8991 {
8992         struct btrfs_root *root;
8993         struct btrfs_key key;
8994         struct btrfs_path path;
8995         struct extent_buffer *eb;
8996         struct extent_buffer *node;
8997         u32 nodesize = btrfs_super_nodesize(fs_info->super_copy);
8998         int err = 0;
8999         int ret;
9000
9001         /* Query level for level == -1 special case */
9002         if (level == -1)
9003                 level = query_tree_block_level(fs_info, bytenr);
9004         if (level < 0) {
9005                 err |= REFERENCER_MISSING;
9006                 goto out;
9007         }
9008
9009         key.objectid = root_id;
9010         key.type = BTRFS_ROOT_ITEM_KEY;
9011         key.offset = (u64)-1;
9012
9013         root = btrfs_read_fs_root(fs_info, &key);
9014         if (IS_ERR(root)) {
9015                 err |= REFERENCER_MISSING;
9016                 goto out;
9017         }
9018
9019         /* Read out the tree block to get item/node key */
9020         eb = read_tree_block(root, bytenr, root->nodesize, 0);
9021         if (!extent_buffer_uptodate(eb)) {
9022                 err |= REFERENCER_MISSING;
9023                 free_extent_buffer(eb);
9024                 goto out;
9025         }
9026
9027         /* Empty tree, no need to check key */
9028         if (!btrfs_header_nritems(eb) && !level) {
9029                 free_extent_buffer(eb);
9030                 goto out;
9031         }
9032
9033         if (level)
9034                 btrfs_node_key_to_cpu(eb, &key, 0);
9035         else
9036                 btrfs_item_key_to_cpu(eb, &key, 0);
9037
9038         free_extent_buffer(eb);
9039
9040         btrfs_init_path(&path);
9041         path.lowest_level = level;
9042         /* Search with the first key, to ensure we can reach it */
9043         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
9044         if (ret < 0) {
9045                 err |= REFERENCER_MISSING;
9046                 goto release_out;
9047         }
9048
9049         node = path.nodes[level];
9050         if (btrfs_header_bytenr(node) != bytenr) {
9051                 error(
9052         "extent [%llu %d] referencer bytenr mismatch, wanted: %llu, have: %llu",
9053                         bytenr, nodesize, bytenr,
9054                         btrfs_header_bytenr(node));
9055                 err |= REFERENCER_MISMATCH;
9056         }
9057         if (btrfs_header_level(node) != level) {
9058                 error(
9059         "extent [%llu %d] referencer level mismatch, wanted: %d, have: %d",
9060                         bytenr, nodesize, level,
9061                         btrfs_header_level(node));
9062                 err |= REFERENCER_MISMATCH;
9063         }
9064
9065 release_out:
9066         btrfs_release_path(&path);
9067 out:
9068         if (err & REFERENCER_MISSING) {
9069                 if (level < 0)
9070                         error("extent [%llu %d] lost referencer (owner: %llu)",
9071                                 bytenr, nodesize, root_id);
9072                 else
9073                         error(
9074                 "extent [%llu %d] lost referencer (owner: %llu, level: %u)",
9075                                 bytenr, nodesize, root_id, level);
9076         }
9077
9078         return err;
9079 }
9080
9081 /*
9082  * Check referencer for shared block backref
9083  * If level == -1, this function will resolve the level.
9084  */
9085 static int check_shared_block_backref(struct btrfs_fs_info *fs_info,
9086                                      u64 parent, u64 bytenr, int level)
9087 {
9088         struct extent_buffer *eb;
9089         u32 nodesize = btrfs_super_nodesize(fs_info->super_copy);
9090         u32 nr;
9091         int found_parent = 0;
9092         int i;
9093
9094         eb = read_tree_block_fs_info(fs_info, parent, nodesize, 0);
9095         if (!extent_buffer_uptodate(eb))
9096                 goto out;
9097
9098         if (level == -1)
9099                 level = query_tree_block_level(fs_info, bytenr);
9100         if (level < 0)
9101                 goto out;
9102
9103         if (level + 1 != btrfs_header_level(eb))
9104                 goto out;
9105
9106         nr = btrfs_header_nritems(eb);
9107         for (i = 0; i < nr; i++) {
9108                 if (bytenr == btrfs_node_blockptr(eb, i)) {
9109                         found_parent = 1;
9110                         break;
9111                 }
9112         }
9113 out:
9114         free_extent_buffer(eb);
9115         if (!found_parent) {
9116                 error(
9117         "shared extent[%llu %u] lost its parent (parent: %llu, level: %u)",
9118                         bytenr, nodesize, parent, level);
9119                 return REFERENCER_MISSING;
9120         }
9121         return 0;
9122 }
9123
9124 /*
9125  * Check referencer for normal (inlined) data ref
9126  * If len == 0, it will be resolved by searching in extent tree
9127  */
9128 static int check_extent_data_backref(struct btrfs_fs_info *fs_info,
9129                                      u64 root_id, u64 objectid, u64 offset,
9130                                      u64 bytenr, u64 len, u32 count)
9131 {
9132         struct btrfs_root *root;
9133         struct btrfs_root *extent_root = fs_info->extent_root;
9134         struct btrfs_key key;
9135         struct btrfs_path path;
9136         struct extent_buffer *leaf;
9137         struct btrfs_file_extent_item *fi;
9138         u32 found_count = 0;
9139         int slot;
9140         int ret = 0;
9141
9142         if (!len) {
9143                 key.objectid = bytenr;
9144                 key.type = BTRFS_EXTENT_ITEM_KEY;
9145                 key.offset = (u64)-1;
9146
9147                 btrfs_init_path(&path);
9148                 ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
9149                 if (ret < 0)
9150                         goto out;
9151                 ret = btrfs_previous_extent_item(extent_root, &path, bytenr);
9152                 if (ret)
9153                         goto out;
9154                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
9155                 if (key.objectid != bytenr ||
9156                     key.type != BTRFS_EXTENT_ITEM_KEY)
9157                         goto out;
9158                 len = key.offset;
9159                 btrfs_release_path(&path);
9160         }
9161         key.objectid = root_id;
9162         key.type = BTRFS_ROOT_ITEM_KEY;
9163         key.offset = (u64)-1;
9164         btrfs_init_path(&path);
9165
9166         root = btrfs_read_fs_root(fs_info, &key);
9167         if (IS_ERR(root))
9168                 goto out;
9169
9170         key.objectid = objectid;
9171         key.type = BTRFS_EXTENT_DATA_KEY;
9172         /*
9173          * It can be nasty as data backref offset is
9174          * file offset - file extent offset, which is smaller or
9175          * equal to original backref offset.  The only special case is
9176          * overflow.  So we need to special check and do further search.
9177          */
9178         key.offset = offset & (1ULL << 63) ? 0 : offset;
9179
9180         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
9181         if (ret < 0)
9182                 goto out;
9183
9184         /*
9185          * Search afterwards to get correct one
9186          * NOTE: As we must do a comprehensive check on the data backref to
9187          * make sure the dref count also matches, we must iterate all file
9188          * extents for that inode.
9189          */
9190         while (1) {
9191                 leaf = path.nodes[0];
9192                 slot = path.slots[0];
9193
9194                 btrfs_item_key_to_cpu(leaf, &key, slot);
9195                 if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
9196                         break;
9197                 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
9198                 /*
9199                  * Except normal disk bytenr and disk num bytes, we still
9200                  * need to do extra check on dbackref offset as
9201                  * dbackref offset = file_offset - file_extent_offset
9202                  */
9203                 if (btrfs_file_extent_disk_bytenr(leaf, fi) == bytenr &&
9204                     btrfs_file_extent_disk_num_bytes(leaf, fi) == len &&
9205                     (u64)(key.offset - btrfs_file_extent_offset(leaf, fi)) ==
9206                     offset)
9207                         found_count++;
9208
9209                 ret = btrfs_next_item(root, &path);
9210                 if (ret)
9211                         break;
9212         }
9213 out:
9214         btrfs_release_path(&path);
9215         if (found_count != count) {
9216                 error(
9217 "extent[%llu, %llu] referencer count mismatch (root: %llu, owner: %llu, offset: %llu) wanted: %u, have: %u",
9218                         bytenr, len, root_id, objectid, offset, count, found_count);
9219                 return REFERENCER_MISSING;
9220         }
9221         return 0;
9222 }
9223
9224 /*
9225  * Check if the referencer of a shared data backref exists
9226  */
9227 static int check_shared_data_backref(struct btrfs_fs_info *fs_info,
9228                                      u64 parent, u64 bytenr)
9229 {
9230         struct extent_buffer *eb;
9231         struct btrfs_key key;
9232         struct btrfs_file_extent_item *fi;
9233         u32 nodesize = btrfs_super_nodesize(fs_info->super_copy);
9234         u32 nr;
9235         int found_parent = 0;
9236         int i;
9237
9238         eb = read_tree_block_fs_info(fs_info, parent, nodesize, 0);
9239         if (!extent_buffer_uptodate(eb))
9240                 goto out;
9241
9242         nr = btrfs_header_nritems(eb);
9243         for (i = 0; i < nr; i++) {
9244                 btrfs_item_key_to_cpu(eb, &key, i);
9245                 if (key.type != BTRFS_EXTENT_DATA_KEY)
9246                         continue;
9247
9248                 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
9249                 if (btrfs_file_extent_type(eb, fi) == BTRFS_FILE_EXTENT_INLINE)
9250                         continue;
9251
9252                 if (btrfs_file_extent_disk_bytenr(eb, fi) == bytenr) {
9253                         found_parent = 1;
9254                         break;
9255                 }
9256         }
9257
9258 out:
9259         free_extent_buffer(eb);
9260         if (!found_parent) {
9261                 error("shared extent %llu referencer lost (parent: %llu)",
9262                         bytenr, parent);
9263                 return REFERENCER_MISSING;
9264         }
9265         return 0;
9266 }
9267
9268 /*
9269  * This function will check a given extent item, including its backref and
9270  * itself (like crossing stripe boundary and type)
9271  *
9272  * Since we don't use extent_record anymore, introduce new error bit
9273  */
9274 static int check_extent_item(struct btrfs_fs_info *fs_info,
9275                              struct extent_buffer *eb, int slot)
9276 {
9277         struct btrfs_extent_item *ei;
9278         struct btrfs_extent_inline_ref *iref;
9279         struct btrfs_extent_data_ref *dref;
9280         unsigned long end;
9281         unsigned long ptr;
9282         int type;
9283         u32 nodesize = btrfs_super_nodesize(fs_info->super_copy);
9284         u32 item_size = btrfs_item_size_nr(eb, slot);
9285         u64 flags;
9286         u64 offset;
9287         int metadata = 0;
9288         int level;
9289         struct btrfs_key key;
9290         int ret;
9291         int err = 0;
9292
9293         btrfs_item_key_to_cpu(eb, &key, slot);
9294         if (key.type == BTRFS_EXTENT_ITEM_KEY)
9295                 bytes_used += key.offset;
9296         else
9297                 bytes_used += nodesize;
9298
9299         if (item_size < sizeof(*ei)) {
9300                 /*
9301                  * COMPAT_EXTENT_TREE_V0 case, but it's already a super
9302                  * old thing when on disk format is still un-determined.
9303                  * No need to care about it anymore
9304                  */
9305                 error("unsupported COMPAT_EXTENT_TREE_V0 detected");
9306                 return -ENOTTY;
9307         }
9308
9309         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
9310         flags = btrfs_extent_flags(eb, ei);
9311
9312         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
9313                 metadata = 1;
9314         if (metadata && check_crossing_stripes(global_info, key.objectid,
9315                                                eb->len)) {
9316                 error("bad metadata [%llu, %llu) crossing stripe boundary",
9317                       key.objectid, key.objectid + nodesize);
9318                 err |= CROSSING_STRIPE_BOUNDARY;
9319         }
9320
9321         ptr = (unsigned long)(ei + 1);
9322
9323         if (metadata && key.type == BTRFS_EXTENT_ITEM_KEY) {
9324                 /* Old EXTENT_ITEM metadata */
9325                 struct btrfs_tree_block_info *info;
9326
9327                 info = (struct btrfs_tree_block_info *)ptr;
9328                 level = btrfs_tree_block_level(eb, info);
9329                 ptr += sizeof(struct btrfs_tree_block_info);
9330         } else {
9331                 /* New METADATA_ITEM */
9332                 level = key.offset;
9333         }
9334         end = (unsigned long)ei + item_size;
9335
9336         if (ptr >= end) {
9337                 err |= ITEM_SIZE_MISMATCH;
9338                 goto out;
9339         }
9340
9341         /* Now check every backref in this extent item */
9342 next:
9343         iref = (struct btrfs_extent_inline_ref *)ptr;
9344         type = btrfs_extent_inline_ref_type(eb, iref);
9345         offset = btrfs_extent_inline_ref_offset(eb, iref);
9346         switch (type) {
9347         case BTRFS_TREE_BLOCK_REF_KEY:
9348                 ret = check_tree_block_backref(fs_info, offset, key.objectid,
9349                                                level);
9350                 err |= ret;
9351                 break;
9352         case BTRFS_SHARED_BLOCK_REF_KEY:
9353                 ret = check_shared_block_backref(fs_info, offset, key.objectid,
9354                                                  level);
9355                 err |= ret;
9356                 break;
9357         case BTRFS_EXTENT_DATA_REF_KEY:
9358                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
9359                 ret = check_extent_data_backref(fs_info,
9360                                 btrfs_extent_data_ref_root(eb, dref),
9361                                 btrfs_extent_data_ref_objectid(eb, dref),
9362                                 btrfs_extent_data_ref_offset(eb, dref),
9363                                 key.objectid, key.offset,
9364                                 btrfs_extent_data_ref_count(eb, dref));
9365                 err |= ret;
9366                 break;
9367         case BTRFS_SHARED_DATA_REF_KEY:
9368                 ret = check_shared_data_backref(fs_info, offset, key.objectid);
9369                 err |= ret;
9370                 break;
9371         default:
9372                 error("extent[%llu %d %llu] has unknown ref type: %d",
9373                         key.objectid, key.type, key.offset, type);
9374                 err |= UNKNOWN_TYPE;
9375                 goto out;
9376         }
9377
9378         ptr += btrfs_extent_inline_ref_size(type);
9379         if (ptr < end)
9380                 goto next;
9381
9382 out:
9383         return err;
9384 }
9385
9386 /*
9387  * Check if a dev extent item is referred correctly by its chunk
9388  */
9389 static int check_dev_extent_item(struct btrfs_fs_info *fs_info,
9390                                  struct extent_buffer *eb, int slot)
9391 {
9392         struct btrfs_root *chunk_root = fs_info->chunk_root;
9393         struct btrfs_dev_extent *ptr;
9394         struct btrfs_path path;
9395         struct btrfs_key chunk_key;
9396         struct btrfs_key devext_key;
9397         struct btrfs_chunk *chunk;
9398         struct extent_buffer *l;
9399         int num_stripes;
9400         u64 length;
9401         int i;
9402         int found_chunk = 0;
9403         int ret;
9404
9405         btrfs_item_key_to_cpu(eb, &devext_key, slot);
9406         ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_extent);
9407         length = btrfs_dev_extent_length(eb, ptr);
9408
9409         chunk_key.objectid = btrfs_dev_extent_chunk_objectid(eb, ptr);
9410         chunk_key.type = BTRFS_CHUNK_ITEM_KEY;
9411         chunk_key.offset = btrfs_dev_extent_chunk_offset(eb, ptr);
9412
9413         btrfs_init_path(&path);
9414         ret = btrfs_search_slot(NULL, chunk_root, &chunk_key, &path, 0, 0);
9415         if (ret)
9416                 goto out;
9417
9418         l = path.nodes[0];
9419         chunk = btrfs_item_ptr(l, path.slots[0], struct btrfs_chunk);
9420         if (btrfs_chunk_length(l, chunk) != length)
9421                 goto out;
9422
9423         num_stripes = btrfs_chunk_num_stripes(l, chunk);
9424         for (i = 0; i < num_stripes; i++) {
9425                 u64 devid = btrfs_stripe_devid_nr(l, chunk, i);
9426                 u64 offset = btrfs_stripe_offset_nr(l, chunk, i);
9427
9428                 if (devid == devext_key.objectid &&
9429                     offset == devext_key.offset) {
9430                         found_chunk = 1;
9431                         break;
9432                 }
9433         }
9434 out:
9435         btrfs_release_path(&path);
9436         if (!found_chunk) {
9437                 error(
9438                 "device extent[%llu, %llu, %llu] did not find the related chunk",
9439                         devext_key.objectid, devext_key.offset, length);
9440                 return REFERENCER_MISSING;
9441         }
9442         return 0;
9443 }
9444
9445 /*
9446  * Check if the used space is correct with the dev item
9447  */
9448 static int check_dev_item(struct btrfs_fs_info *fs_info,
9449                           struct extent_buffer *eb, int slot)
9450 {
9451         struct btrfs_root *dev_root = fs_info->dev_root;
9452         struct btrfs_dev_item *dev_item;
9453         struct btrfs_path path;
9454         struct btrfs_key key;
9455         struct btrfs_dev_extent *ptr;
9456         u64 dev_id;
9457         u64 used;
9458         u64 total = 0;
9459         int ret;
9460
9461         dev_item = btrfs_item_ptr(eb, slot, struct btrfs_dev_item);
9462         dev_id = btrfs_device_id(eb, dev_item);
9463         used = btrfs_device_bytes_used(eb, dev_item);
9464
9465         key.objectid = dev_id;
9466         key.type = BTRFS_DEV_EXTENT_KEY;
9467         key.offset = 0;
9468
9469         btrfs_init_path(&path);
9470         ret = btrfs_search_slot(NULL, dev_root, &key, &path, 0, 0);
9471         if (ret < 0) {
9472                 btrfs_item_key_to_cpu(eb, &key, slot);
9473                 error("cannot find any related dev extent for dev[%llu, %u, %llu]",
9474                         key.objectid, key.type, key.offset);
9475                 btrfs_release_path(&path);
9476                 return REFERENCER_MISSING;
9477         }
9478
9479         /* Iterate dev_extents to calculate the used space of a device */
9480         while (1) {
9481                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
9482
9483                 if (key.objectid > dev_id)
9484                         break;
9485                 if (key.type != BTRFS_DEV_EXTENT_KEY || key.objectid != dev_id)
9486                         goto next;
9487
9488                 ptr = btrfs_item_ptr(path.nodes[0], path.slots[0],
9489                                      struct btrfs_dev_extent);
9490                 total += btrfs_dev_extent_length(path.nodes[0], ptr);
9491 next:
9492                 ret = btrfs_next_item(dev_root, &path);
9493                 if (ret)
9494                         break;
9495         }
9496         btrfs_release_path(&path);
9497
9498         if (used != total) {
9499                 btrfs_item_key_to_cpu(eb, &key, slot);
9500                 error(
9501 "Dev extent's total-byte %llu is not equal to bytes-used %llu in dev[%llu, %u, %llu]",
9502                         total, used, BTRFS_ROOT_TREE_OBJECTID,
9503                         BTRFS_DEV_EXTENT_KEY, dev_id);
9504                 return ACCOUNTING_MISMATCH;
9505         }
9506         return 0;
9507 }
9508
9509 /*
9510  * Check a block group item with its referener (chunk) and its used space
9511  * with extent/metadata item
9512  */
9513 static int check_block_group_item(struct btrfs_fs_info *fs_info,
9514                                   struct extent_buffer *eb, int slot)
9515 {
9516         struct btrfs_root *extent_root = fs_info->extent_root;
9517         struct btrfs_root *chunk_root = fs_info->chunk_root;
9518         struct btrfs_block_group_item *bi;
9519         struct btrfs_block_group_item bg_item;
9520         struct btrfs_path path;
9521         struct btrfs_key bg_key;
9522         struct btrfs_key chunk_key;
9523         struct btrfs_key extent_key;
9524         struct btrfs_chunk *chunk;
9525         struct extent_buffer *leaf;
9526         struct btrfs_extent_item *ei;
9527         u32 nodesize = btrfs_super_nodesize(fs_info->super_copy);
9528         u64 flags;
9529         u64 bg_flags;
9530         u64 used;
9531         u64 total = 0;
9532         int ret;
9533         int err = 0;
9534
9535         btrfs_item_key_to_cpu(eb, &bg_key, slot);
9536         bi = btrfs_item_ptr(eb, slot, struct btrfs_block_group_item);
9537         read_extent_buffer(eb, &bg_item, (unsigned long)bi, sizeof(bg_item));
9538         used = btrfs_block_group_used(&bg_item);
9539         bg_flags = btrfs_block_group_flags(&bg_item);
9540
9541         chunk_key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
9542         chunk_key.type = BTRFS_CHUNK_ITEM_KEY;
9543         chunk_key.offset = bg_key.objectid;
9544
9545         btrfs_init_path(&path);
9546         /* Search for the referencer chunk */
9547         ret = btrfs_search_slot(NULL, chunk_root, &chunk_key, &path, 0, 0);
9548         if (ret) {
9549                 error(
9550                 "block group[%llu %llu] did not find the related chunk item",
9551                         bg_key.objectid, bg_key.offset);
9552                 err |= REFERENCER_MISSING;
9553         } else {
9554                 chunk = btrfs_item_ptr(path.nodes[0], path.slots[0],
9555                                         struct btrfs_chunk);
9556                 if (btrfs_chunk_length(path.nodes[0], chunk) !=
9557                                                 bg_key.offset) {
9558                         error(
9559         "block group[%llu %llu] related chunk item length does not match",
9560                                 bg_key.objectid, bg_key.offset);
9561                         err |= REFERENCER_MISMATCH;
9562                 }
9563         }
9564         btrfs_release_path(&path);
9565
9566         /* Search from the block group bytenr */
9567         extent_key.objectid = bg_key.objectid;
9568         extent_key.type = 0;
9569         extent_key.offset = 0;
9570
9571         btrfs_init_path(&path);
9572         ret = btrfs_search_slot(NULL, extent_root, &extent_key, &path, 0, 0);
9573         if (ret < 0)
9574                 goto out;
9575
9576         /* Iterate extent tree to account used space */
9577         while (1) {
9578                 leaf = path.nodes[0];
9579                 btrfs_item_key_to_cpu(leaf, &extent_key, path.slots[0]);
9580                 if (extent_key.objectid >= bg_key.objectid + bg_key.offset)
9581                         break;
9582
9583                 if (extent_key.type != BTRFS_METADATA_ITEM_KEY &&
9584                     extent_key.type != BTRFS_EXTENT_ITEM_KEY)
9585                         goto next;
9586                 if (extent_key.objectid < bg_key.objectid)
9587                         goto next;
9588
9589                 if (extent_key.type == BTRFS_METADATA_ITEM_KEY)
9590                         total += nodesize;
9591                 else
9592                         total += extent_key.offset;
9593
9594                 ei = btrfs_item_ptr(leaf, path.slots[0],
9595                                     struct btrfs_extent_item);
9596                 flags = btrfs_extent_flags(leaf, ei);
9597                 if (flags & BTRFS_EXTENT_FLAG_DATA) {
9598                         if (!(bg_flags & BTRFS_BLOCK_GROUP_DATA)) {
9599                                 error(
9600                         "bad extent[%llu, %llu) type mismatch with chunk",
9601                                         extent_key.objectid,
9602                                         extent_key.objectid + extent_key.offset);
9603                                 err |= CHUNK_TYPE_MISMATCH;
9604                         }
9605                 } else if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
9606                         if (!(bg_flags & (BTRFS_BLOCK_GROUP_SYSTEM |
9607                                     BTRFS_BLOCK_GROUP_METADATA))) {
9608                                 error(
9609                         "bad extent[%llu, %llu) type mismatch with chunk",
9610                                         extent_key.objectid,
9611                                         extent_key.objectid + nodesize);
9612                                 err |= CHUNK_TYPE_MISMATCH;
9613                         }
9614                 }
9615 next:
9616                 ret = btrfs_next_item(extent_root, &path);
9617                 if (ret)
9618                         break;
9619         }
9620
9621 out:
9622         btrfs_release_path(&path);
9623
9624         if (total != used) {
9625                 error(
9626                 "block group[%llu %llu] used %llu but extent items used %llu",
9627                         bg_key.objectid, bg_key.offset, used, total);
9628                 err |= ACCOUNTING_MISMATCH;
9629         }
9630         return err;
9631 }
9632
9633 /*
9634  * Check a chunk item.
9635  * Including checking all referred dev_extents and block group
9636  */
9637 static int check_chunk_item(struct btrfs_fs_info *fs_info,
9638                             struct extent_buffer *eb, int slot)
9639 {
9640         struct btrfs_root *extent_root = fs_info->extent_root;
9641         struct btrfs_root *dev_root = fs_info->dev_root;
9642         struct btrfs_path path;
9643         struct btrfs_key chunk_key;
9644         struct btrfs_key bg_key;
9645         struct btrfs_key devext_key;
9646         struct btrfs_chunk *chunk;
9647         struct extent_buffer *leaf;
9648         struct btrfs_block_group_item *bi;
9649         struct btrfs_block_group_item bg_item;
9650         struct btrfs_dev_extent *ptr;
9651         u32 sectorsize = btrfs_super_sectorsize(fs_info->super_copy);
9652         u64 length;
9653         u64 chunk_end;
9654         u64 type;
9655         u64 profile;
9656         int num_stripes;
9657         u64 offset;
9658         u64 objectid;
9659         int i;
9660         int ret;
9661         int err = 0;
9662
9663         btrfs_item_key_to_cpu(eb, &chunk_key, slot);
9664         chunk = btrfs_item_ptr(eb, slot, struct btrfs_chunk);
9665         length = btrfs_chunk_length(eb, chunk);
9666         chunk_end = chunk_key.offset + length;
9667         if (!IS_ALIGNED(length, sectorsize)) {
9668                 error("chunk[%llu %llu) not aligned to %u",
9669                         chunk_key.offset, chunk_end, sectorsize);
9670                 err |= BYTES_UNALIGNED;
9671                 goto out;
9672         }
9673
9674         type = btrfs_chunk_type(eb, chunk);
9675         profile = type & BTRFS_BLOCK_GROUP_PROFILE_MASK;
9676         if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9677                 error("chunk[%llu %llu) has no chunk type",
9678                         chunk_key.offset, chunk_end);
9679                 err |= UNKNOWN_TYPE;
9680         }
9681         if (profile && (profile & (profile - 1))) {
9682                 error("chunk[%llu %llu) multiple profiles detected: %llx",
9683                         chunk_key.offset, chunk_end, profile);
9684                 err |= UNKNOWN_TYPE;
9685         }
9686
9687         bg_key.objectid = chunk_key.offset;
9688         bg_key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9689         bg_key.offset = length;
9690
9691         btrfs_init_path(&path);
9692         ret = btrfs_search_slot(NULL, extent_root, &bg_key, &path, 0, 0);
9693         if (ret) {
9694                 error(
9695                 "chunk[%llu %llu) did not find the related block group item",
9696                         chunk_key.offset, chunk_end);
9697                 err |= REFERENCER_MISSING;
9698         } else{
9699                 leaf = path.nodes[0];
9700                 bi = btrfs_item_ptr(leaf, path.slots[0],
9701                                     struct btrfs_block_group_item);
9702                 read_extent_buffer(leaf, &bg_item, (unsigned long)bi,
9703                                    sizeof(bg_item));
9704                 if (btrfs_block_group_flags(&bg_item) != type) {
9705                         error(
9706 "chunk[%llu %llu) related block group item flags mismatch, wanted: %llu, have: %llu",
9707                                 chunk_key.offset, chunk_end, type,
9708                                 btrfs_block_group_flags(&bg_item));
9709                         err |= REFERENCER_MISSING;
9710                 }
9711         }
9712
9713         num_stripes = btrfs_chunk_num_stripes(eb, chunk);
9714         for (i = 0; i < num_stripes; i++) {
9715                 btrfs_release_path(&path);
9716                 btrfs_init_path(&path);
9717                 devext_key.objectid = btrfs_stripe_devid_nr(eb, chunk, i);
9718                 devext_key.type = BTRFS_DEV_EXTENT_KEY;
9719                 devext_key.offset = btrfs_stripe_offset_nr(eb, chunk, i);
9720
9721                 ret = btrfs_search_slot(NULL, dev_root, &devext_key, &path,
9722                                         0, 0);
9723                 if (ret)
9724                         goto not_match_dev;
9725
9726                 leaf = path.nodes[0];
9727                 ptr = btrfs_item_ptr(leaf, path.slots[0],
9728                                      struct btrfs_dev_extent);
9729                 objectid = btrfs_dev_extent_chunk_objectid(leaf, ptr);
9730                 offset = btrfs_dev_extent_chunk_offset(leaf, ptr);
9731                 if (objectid != chunk_key.objectid ||
9732                     offset != chunk_key.offset ||
9733                     btrfs_dev_extent_length(leaf, ptr) != length)
9734                         goto not_match_dev;
9735                 continue;
9736 not_match_dev:
9737                 err |= BACKREF_MISSING;
9738                 error(
9739                 "chunk[%llu %llu) stripe %d did not find the related dev extent",
9740                         chunk_key.objectid, chunk_end, i);
9741                 continue;
9742         }
9743         btrfs_release_path(&path);
9744 out:
9745         return err;
9746 }
9747
9748 /*
9749  * Main entry function to check known items and update related accounting info
9750  */
9751 static int check_leaf_items(struct btrfs_root *root, struct extent_buffer *eb)
9752 {
9753         struct btrfs_fs_info *fs_info = root->fs_info;
9754         struct btrfs_key key;
9755         int slot = 0;
9756         int type;
9757         struct btrfs_extent_data_ref *dref;
9758         int ret;
9759         int err = 0;
9760
9761 next:
9762         btrfs_item_key_to_cpu(eb, &key, slot);
9763         type = key.type;
9764
9765         switch (type) {
9766         case BTRFS_EXTENT_DATA_KEY:
9767                 ret = check_extent_data_item(root, eb, slot);
9768                 err |= ret;
9769                 break;
9770         case BTRFS_BLOCK_GROUP_ITEM_KEY:
9771                 ret = check_block_group_item(fs_info, eb, slot);
9772                 err |= ret;
9773                 break;
9774         case BTRFS_DEV_ITEM_KEY:
9775                 ret = check_dev_item(fs_info, eb, slot);
9776                 err |= ret;
9777                 break;
9778         case BTRFS_CHUNK_ITEM_KEY:
9779                 ret = check_chunk_item(fs_info, eb, slot);
9780                 err |= ret;
9781                 break;
9782         case BTRFS_DEV_EXTENT_KEY:
9783                 ret = check_dev_extent_item(fs_info, eb, slot);
9784                 err |= ret;
9785                 break;
9786         case BTRFS_EXTENT_ITEM_KEY:
9787         case BTRFS_METADATA_ITEM_KEY:
9788                 ret = check_extent_item(fs_info, eb, slot);
9789                 err |= ret;
9790                 break;
9791         case BTRFS_EXTENT_CSUM_KEY:
9792                 total_csum_bytes += btrfs_item_size_nr(eb, slot);
9793                 break;
9794         case BTRFS_TREE_BLOCK_REF_KEY:
9795                 ret = check_tree_block_backref(fs_info, key.offset,
9796                                                key.objectid, -1);
9797                 err |= ret;
9798                 break;
9799         case BTRFS_EXTENT_DATA_REF_KEY:
9800                 dref = btrfs_item_ptr(eb, slot, struct btrfs_extent_data_ref);
9801                 ret = check_extent_data_backref(fs_info,
9802                                 btrfs_extent_data_ref_root(eb, dref),
9803                                 btrfs_extent_data_ref_objectid(eb, dref),
9804                                 btrfs_extent_data_ref_offset(eb, dref),
9805                                 key.objectid, 0,
9806                                 btrfs_extent_data_ref_count(eb, dref));
9807                 err |= ret;
9808                 break;
9809         case BTRFS_SHARED_BLOCK_REF_KEY:
9810                 ret = check_shared_block_backref(fs_info, key.offset,
9811                                                  key.objectid, -1);
9812                 err |= ret;
9813                 break;
9814         case BTRFS_SHARED_DATA_REF_KEY:
9815                 ret = check_shared_data_backref(fs_info, key.offset,
9816                                                 key.objectid);
9817                 err |= ret;
9818                 break;
9819         default:
9820                 break;
9821         }
9822
9823         if (++slot < btrfs_header_nritems(eb))
9824                 goto next;
9825
9826         return err;
9827 }
9828
9829 /*
9830  * Helper function for later fs/subvol tree check.  To determine if a tree
9831  * block should be checked.
9832  * This function will ensure only the direct referencer with lowest rootid to
9833  * check a fs/subvolume tree block.
9834  *
9835  * Backref check at extent tree would detect errors like missing subvolume
9836  * tree, so we can do aggressive check to reduce duplicated checks.
9837  */
9838 static int should_check(struct btrfs_root *root, struct extent_buffer *eb)
9839 {
9840         struct btrfs_root *extent_root = root->fs_info->extent_root;
9841         struct btrfs_key key;
9842         struct btrfs_path path;
9843         struct extent_buffer *leaf;
9844         int slot;
9845         struct btrfs_extent_item *ei;
9846         unsigned long ptr;
9847         unsigned long end;
9848         int type;
9849         u32 item_size;
9850         u64 offset;
9851         struct btrfs_extent_inline_ref *iref;
9852         int ret;
9853
9854         btrfs_init_path(&path);
9855         key.objectid = btrfs_header_bytenr(eb);
9856         key.type = BTRFS_METADATA_ITEM_KEY;
9857         key.offset = (u64)-1;
9858
9859         /*
9860          * Any failure in backref resolving means we can't determine
9861          * whom the tree block belongs to.
9862          * So in that case, we need to check that tree block
9863          */
9864         ret = btrfs_search_slot(NULL, extent_root, &key, &path, 0, 0);
9865         if (ret < 0)
9866                 goto need_check;
9867
9868         ret = btrfs_previous_extent_item(extent_root, &path,
9869                                          btrfs_header_bytenr(eb));
9870         if (ret)
9871                 goto need_check;
9872
9873         leaf = path.nodes[0];
9874         slot = path.slots[0];
9875         btrfs_item_key_to_cpu(leaf, &key, slot);
9876         ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
9877
9878         if (key.type == BTRFS_METADATA_ITEM_KEY) {
9879                 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
9880         } else {
9881                 struct btrfs_tree_block_info *info;
9882
9883                 info = (struct btrfs_tree_block_info *)(ei + 1);
9884                 iref = (struct btrfs_extent_inline_ref *)(info + 1);
9885         }
9886
9887         item_size = btrfs_item_size_nr(leaf, slot);
9888         ptr = (unsigned long)iref;
9889         end = (unsigned long)ei + item_size;
9890         while (ptr < end) {
9891                 iref = (struct btrfs_extent_inline_ref *)ptr;
9892                 type = btrfs_extent_inline_ref_type(leaf, iref);
9893                 offset = btrfs_extent_inline_ref_offset(leaf, iref);
9894
9895                 /*
9896                  * We only check the tree block if current root is
9897                  * the lowest referencer of it.
9898                  */
9899                 if (type == BTRFS_TREE_BLOCK_REF_KEY &&
9900                     offset < root->objectid) {
9901                         btrfs_release_path(&path);
9902                         return 0;
9903                 }
9904
9905                 ptr += btrfs_extent_inline_ref_size(type);
9906         }
9907         /*
9908          * Normally we should also check keyed tree block ref, but that may be
9909          * very time consuming.  Inlined ref should already make us skip a lot
9910          * of refs now.  So skip search keyed tree block ref.
9911          */
9912
9913 need_check:
9914         btrfs_release_path(&path);
9915         return 1;
9916 }
9917
9918 /*
9919  * Traversal function for tree block. We will do:
9920  * 1) Skip shared fs/subvolume tree blocks
9921  * 2) Update related bytes accounting
9922  * 3) Pre-order traversal
9923  */
9924 static int traverse_tree_block(struct btrfs_root *root,
9925                                 struct extent_buffer *node)
9926 {
9927         struct extent_buffer *eb;
9928         struct btrfs_key key;
9929         struct btrfs_key drop_key;
9930         int level;
9931         u64 nr;
9932         int i;
9933         int err = 0;
9934         int ret;
9935
9936         /*
9937          * Skip shared fs/subvolume tree block, in that case they will
9938          * be checked by referencer with lowest rootid
9939          */
9940         if (is_fstree(root->objectid) && !should_check(root, node))
9941                 return 0;
9942
9943         /* Update bytes accounting */
9944         total_btree_bytes += node->len;
9945         if (fs_root_objectid(btrfs_header_owner(node)))
9946                 total_fs_tree_bytes += node->len;
9947         if (btrfs_header_owner(node) == BTRFS_EXTENT_TREE_OBJECTID)
9948                 total_extent_tree_bytes += node->len;
9949         if (!found_old_backref &&
9950             btrfs_header_owner(node) == BTRFS_TREE_RELOC_OBJECTID &&
9951             btrfs_header_backref_rev(node) == BTRFS_MIXED_BACKREF_REV &&
9952             !btrfs_header_flag(node, BTRFS_HEADER_FLAG_RELOC))
9953                 found_old_backref = 1;
9954
9955         /* pre-order tranversal, check itself first */
9956         level = btrfs_header_level(node);
9957         ret = check_tree_block_ref(root, node, btrfs_header_bytenr(node),
9958                                    btrfs_header_level(node),
9959                                    btrfs_header_owner(node));
9960         err |= ret;
9961         if (err)
9962                 error(
9963         "check %s failed root %llu bytenr %llu level %d, force continue check",
9964                         level ? "node":"leaf", root->objectid,
9965                         btrfs_header_bytenr(node), btrfs_header_level(node));
9966
9967         if (!level) {
9968                 btree_space_waste += btrfs_leaf_free_space(root, node);
9969                 ret = check_leaf_items(root, node);
9970                 err |= ret;
9971                 return err;
9972         }
9973
9974         nr = btrfs_header_nritems(node);
9975         btrfs_disk_key_to_cpu(&drop_key, &root->root_item.drop_progress);
9976         btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) - nr) *
9977                 sizeof(struct btrfs_key_ptr);
9978
9979         /* Then check all its children */
9980         for (i = 0; i < nr; i++) {
9981                 u64 blocknr = btrfs_node_blockptr(node, i);
9982
9983                 btrfs_node_key_to_cpu(node, &key, i);
9984                 if (level == root->root_item.drop_level &&
9985                     is_dropped_key(&key, &drop_key))
9986                         continue;
9987
9988                 /*
9989                  * As a btrfs tree has most 8 levels (0..7), so it's quite safe
9990                  * to call the function itself.
9991                  */
9992                 eb = read_tree_block(root, blocknr, root->nodesize, 0);
9993                 if (extent_buffer_uptodate(eb)) {
9994                         ret = traverse_tree_block(root, eb);
9995                         err |= ret;
9996                 }
9997                 free_extent_buffer(eb);
9998         }
9999
10000         return err;
10001 }
10002
10003 /*
10004  * Low memory usage version check_chunks_and_extents.
10005  */
10006 static int check_chunks_and_extents_v2(struct btrfs_root *root)
10007 {
10008         struct btrfs_path path;
10009         struct btrfs_key key;
10010         struct btrfs_root *root1;
10011         struct btrfs_root *cur_root;
10012         int err = 0;
10013         int ret;
10014
10015         root1 = root->fs_info->chunk_root;
10016         ret = traverse_tree_block(root1, root1->node);
10017         err |= ret;
10018
10019         root1 = root->fs_info->tree_root;
10020         ret = traverse_tree_block(root1, root1->node);
10021         err |= ret;
10022
10023         btrfs_init_path(&path);
10024         key.objectid = BTRFS_EXTENT_TREE_OBJECTID;
10025         key.offset = 0;
10026         key.type = BTRFS_ROOT_ITEM_KEY;
10027
10028         ret = btrfs_search_slot(NULL, root1, &key, &path, 0, 0);
10029         if (ret) {
10030                 error("cannot find extent treet in tree_root");
10031                 goto out;
10032         }
10033
10034         while (1) {
10035                 btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
10036                 if (key.type != BTRFS_ROOT_ITEM_KEY)
10037                         goto next;
10038                 key.offset = (u64)-1;
10039
10040                 cur_root = btrfs_read_fs_root(root->fs_info, &key);
10041                 if (IS_ERR(cur_root) || !cur_root) {
10042                         error("failed to read tree: %lld", key.objectid);
10043                         goto next;
10044                 }
10045
10046                 ret = traverse_tree_block(cur_root, cur_root->node);
10047                 err |= ret;
10048
10049 next:
10050                 ret = btrfs_next_item(root1, &path);
10051                 if (ret)
10052                         goto out;
10053         }
10054
10055 out:
10056         btrfs_release_path(&path);
10057         return err;
10058 }
10059
10060 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
10061                            struct btrfs_root *root, int overwrite)
10062 {
10063         struct extent_buffer *c;
10064         struct extent_buffer *old = root->node;
10065         int level;
10066         int ret;
10067         struct btrfs_disk_key disk_key = {0,0,0};
10068
10069         level = 0;
10070
10071         if (overwrite) {
10072                 c = old;
10073                 extent_buffer_get(c);
10074                 goto init;
10075         }
10076         c = btrfs_alloc_free_block(trans, root,
10077                                    root->nodesize,
10078                                    root->root_key.objectid,
10079                                    &disk_key, level, 0, 0);
10080         if (IS_ERR(c)) {
10081                 c = old;
10082                 extent_buffer_get(c);
10083                 overwrite = 1;
10084         }
10085 init:
10086         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
10087         btrfs_set_header_level(c, level);
10088         btrfs_set_header_bytenr(c, c->start);
10089         btrfs_set_header_generation(c, trans->transid);
10090         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
10091         btrfs_set_header_owner(c, root->root_key.objectid);
10092
10093         write_extent_buffer(c, root->fs_info->fsid,
10094                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
10095
10096         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
10097                             btrfs_header_chunk_tree_uuid(c),
10098                             BTRFS_UUID_SIZE);
10099
10100         btrfs_mark_buffer_dirty(c);
10101         /*
10102          * this case can happen in the following case:
10103          *
10104          * 1.overwrite previous root.
10105          *
10106          * 2.reinit reloc data root, this is because we skip pin
10107          * down reloc data tree before which means we can allocate
10108          * same block bytenr here.
10109          */
10110         if (old->start == c->start) {
10111                 btrfs_set_root_generation(&root->root_item,
10112                                           trans->transid);
10113                 root->root_item.level = btrfs_header_level(root->node);
10114                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
10115                                         &root->root_key, &root->root_item);
10116                 if (ret) {
10117                         free_extent_buffer(c);
10118                         return ret;
10119                 }
10120         }
10121         free_extent_buffer(old);
10122         root->node = c;
10123         add_root_to_dirty_list(root);
10124         return 0;
10125 }
10126
10127 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
10128                                 struct extent_buffer *eb, int tree_root)
10129 {
10130         struct extent_buffer *tmp;
10131         struct btrfs_root_item *ri;
10132         struct btrfs_key key;
10133         u64 bytenr;
10134         u32 nodesize;
10135         int level = btrfs_header_level(eb);
10136         int nritems;
10137         int ret;
10138         int i;
10139
10140         /*
10141          * If we have pinned this block before, don't pin it again.
10142          * This can not only avoid forever loop with broken filesystem
10143          * but also give us some speedups.
10144          */
10145         if (test_range_bit(&fs_info->pinned_extents, eb->start,
10146                            eb->start + eb->len - 1, EXTENT_DIRTY, 0))
10147                 return 0;
10148
10149         btrfs_pin_extent(fs_info, eb->start, eb->len);
10150
10151         nodesize = btrfs_super_nodesize(fs_info->super_copy);
10152         nritems = btrfs_header_nritems(eb);
10153         for (i = 0; i < nritems; i++) {
10154                 if (level == 0) {
10155                         btrfs_item_key_to_cpu(eb, &key, i);
10156                         if (key.type != BTRFS_ROOT_ITEM_KEY)
10157                                 continue;
10158                         /* Skip the extent root and reloc roots */
10159                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
10160                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
10161                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
10162                                 continue;
10163                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
10164                         bytenr = btrfs_disk_root_bytenr(eb, ri);
10165
10166                         /*
10167                          * If at any point we start needing the real root we
10168                          * will have to build a stump root for the root we are
10169                          * in, but for now this doesn't actually use the root so
10170                          * just pass in extent_root.
10171                          */
10172                         tmp = read_tree_block(fs_info->extent_root, bytenr,
10173                                               nodesize, 0);
10174                         if (!extent_buffer_uptodate(tmp)) {
10175                                 fprintf(stderr, "Error reading root block\n");
10176                                 return -EIO;
10177                         }
10178                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
10179                         free_extent_buffer(tmp);
10180                         if (ret)
10181                                 return ret;
10182                 } else {
10183                         bytenr = btrfs_node_blockptr(eb, i);
10184
10185                         /* If we aren't the tree root don't read the block */
10186                         if (level == 1 && !tree_root) {
10187                                 btrfs_pin_extent(fs_info, bytenr, nodesize);
10188                                 continue;
10189                         }
10190
10191                         tmp = read_tree_block(fs_info->extent_root, bytenr,
10192                                               nodesize, 0);
10193                         if (!extent_buffer_uptodate(tmp)) {
10194                                 fprintf(stderr, "Error reading tree block\n");
10195                                 return -EIO;
10196                         }
10197                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
10198                         free_extent_buffer(tmp);
10199                         if (ret)
10200                                 return ret;
10201                 }
10202         }
10203
10204         return 0;
10205 }
10206
10207 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
10208 {
10209         int ret;
10210
10211         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
10212         if (ret)
10213                 return ret;
10214
10215         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
10216 }
10217
10218 static int reset_block_groups(struct btrfs_fs_info *fs_info)
10219 {
10220         struct btrfs_block_group_cache *cache;
10221         struct btrfs_path *path;
10222         struct extent_buffer *leaf;
10223         struct btrfs_chunk *chunk;
10224         struct btrfs_key key;
10225         int ret;
10226         u64 start;
10227
10228         path = btrfs_alloc_path();
10229         if (!path)
10230                 return -ENOMEM;
10231
10232         key.objectid = 0;
10233         key.type = BTRFS_CHUNK_ITEM_KEY;
10234         key.offset = 0;
10235
10236         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
10237         if (ret < 0) {
10238                 btrfs_free_path(path);
10239                 return ret;
10240         }
10241
10242         /*
10243          * We do this in case the block groups were screwed up and had alloc
10244          * bits that aren't actually set on the chunks.  This happens with
10245          * restored images every time and could happen in real life I guess.
10246          */
10247         fs_info->avail_data_alloc_bits = 0;
10248         fs_info->avail_metadata_alloc_bits = 0;
10249         fs_info->avail_system_alloc_bits = 0;
10250
10251         /* First we need to create the in-memory block groups */
10252         while (1) {
10253                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
10254                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
10255                         if (ret < 0) {
10256                                 btrfs_free_path(path);
10257                                 return ret;
10258                         }
10259                         if (ret) {
10260                                 ret = 0;
10261                                 break;
10262                         }
10263                 }
10264                 leaf = path->nodes[0];
10265                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
10266                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
10267                         path->slots[0]++;
10268                         continue;
10269                 }
10270
10271                 chunk = btrfs_item_ptr(leaf, path->slots[0],
10272                                        struct btrfs_chunk);
10273                 btrfs_add_block_group(fs_info, 0,
10274                                       btrfs_chunk_type(leaf, chunk),
10275                                       key.objectid, key.offset,
10276                                       btrfs_chunk_length(leaf, chunk));
10277                 set_extent_dirty(&fs_info->free_space_cache, key.offset,
10278                                  key.offset + btrfs_chunk_length(leaf, chunk),
10279                                  GFP_NOFS);
10280                 path->slots[0]++;
10281         }
10282         start = 0;
10283         while (1) {
10284                 cache = btrfs_lookup_first_block_group(fs_info, start);
10285                 if (!cache)
10286                         break;
10287                 cache->cached = 1;
10288                 start = cache->key.objectid + cache->key.offset;
10289         }
10290
10291         btrfs_free_path(path);
10292         return 0;
10293 }
10294
10295 static int reset_balance(struct btrfs_trans_handle *trans,
10296                          struct btrfs_fs_info *fs_info)
10297 {
10298         struct btrfs_root *root = fs_info->tree_root;
10299         struct btrfs_path *path;
10300         struct extent_buffer *leaf;
10301         struct btrfs_key key;
10302         int del_slot, del_nr = 0;
10303         int ret;
10304         int found = 0;
10305
10306         path = btrfs_alloc_path();
10307         if (!path)
10308                 return -ENOMEM;
10309
10310         key.objectid = BTRFS_BALANCE_OBJECTID;
10311         key.type = BTRFS_BALANCE_ITEM_KEY;
10312         key.offset = 0;
10313
10314         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10315         if (ret) {
10316                 if (ret > 0)
10317                         ret = 0;
10318                 if (!ret)
10319                         goto reinit_data_reloc;
10320                 else
10321                         goto out;
10322         }
10323
10324         ret = btrfs_del_item(trans, root, path);
10325         if (ret)
10326                 goto out;
10327         btrfs_release_path(path);
10328
10329         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
10330         key.type = BTRFS_ROOT_ITEM_KEY;
10331         key.offset = 0;
10332
10333         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10334         if (ret < 0)
10335                 goto out;
10336         while (1) {
10337                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
10338                         if (!found)
10339                                 break;
10340
10341                         if (del_nr) {
10342                                 ret = btrfs_del_items(trans, root, path,
10343                                                       del_slot, del_nr);
10344                                 del_nr = 0;
10345                                 if (ret)
10346                                         goto out;
10347                         }
10348                         key.offset++;
10349                         btrfs_release_path(path);
10350
10351                         found = 0;
10352                         ret = btrfs_search_slot(trans, root, &key, path,
10353                                                 -1, 1);
10354                         if (ret < 0)
10355                                 goto out;
10356                         continue;
10357                 }
10358                 found = 1;
10359                 leaf = path->nodes[0];
10360                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
10361                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
10362                         break;
10363                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
10364                         path->slots[0]++;
10365                         continue;
10366                 }
10367                 if (!del_nr) {
10368                         del_slot = path->slots[0];
10369                         del_nr = 1;
10370                 } else {
10371                         del_nr++;
10372                 }
10373                 path->slots[0]++;
10374         }
10375
10376         if (del_nr) {
10377                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
10378                 if (ret)
10379                         goto out;
10380         }
10381         btrfs_release_path(path);
10382
10383 reinit_data_reloc:
10384         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
10385         key.type = BTRFS_ROOT_ITEM_KEY;
10386         key.offset = (u64)-1;
10387         root = btrfs_read_fs_root(fs_info, &key);
10388         if (IS_ERR(root)) {
10389                 fprintf(stderr, "Error reading data reloc tree\n");
10390                 ret = PTR_ERR(root);
10391                 goto out;
10392         }
10393         record_root_in_trans(trans, root);
10394         ret = btrfs_fsck_reinit_root(trans, root, 0);
10395         if (ret)
10396                 goto out;
10397         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
10398 out:
10399         btrfs_free_path(path);
10400         return ret;
10401 }
10402
10403 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
10404                               struct btrfs_fs_info *fs_info)
10405 {
10406         u64 start = 0;
10407         int ret;
10408
10409         /*
10410          * The only reason we don't do this is because right now we're just
10411          * walking the trees we find and pinning down their bytes, we don't look
10412          * at any of the leaves.  In order to do mixed groups we'd have to check
10413          * the leaves of any fs roots and pin down the bytes for any file
10414          * extents we find.  Not hard but why do it if we don't have to?
10415          */
10416         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
10417                 fprintf(stderr, "We don't support re-initing the extent tree "
10418                         "for mixed block groups yet, please notify a btrfs "
10419                         "developer you want to do this so they can add this "
10420                         "functionality.\n");
10421                 return -EINVAL;
10422         }
10423
10424         /*
10425          * first we need to walk all of the trees except the extent tree and pin
10426          * down the bytes that are in use so we don't overwrite any existing
10427          * metadata.
10428          */
10429         ret = pin_metadata_blocks(fs_info);
10430         if (ret) {
10431                 fprintf(stderr, "error pinning down used bytes\n");
10432                 return ret;
10433         }
10434
10435         /*
10436          * Need to drop all the block groups since we're going to recreate all
10437          * of them again.
10438          */
10439         btrfs_free_block_groups(fs_info);
10440         ret = reset_block_groups(fs_info);
10441         if (ret) {
10442                 fprintf(stderr, "error resetting the block groups\n");
10443                 return ret;
10444         }
10445
10446         /* Ok we can allocate now, reinit the extent root */
10447         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
10448         if (ret) {
10449                 fprintf(stderr, "extent root initialization failed\n");
10450                 /*
10451                  * When the transaction code is updated we should end the
10452                  * transaction, but for now progs only knows about commit so
10453                  * just return an error.
10454                  */
10455                 return ret;
10456         }
10457
10458         /*
10459          * Now we have all the in-memory block groups setup so we can make
10460          * allocations properly, and the metadata we care about is safe since we
10461          * pinned all of it above.
10462          */
10463         while (1) {
10464                 struct btrfs_block_group_cache *cache;
10465
10466                 cache = btrfs_lookup_first_block_group(fs_info, start);
10467                 if (!cache)
10468                         break;
10469                 start = cache->key.objectid + cache->key.offset;
10470                 ret = btrfs_insert_item(trans, fs_info->extent_root,
10471                                         &cache->key, &cache->item,
10472                                         sizeof(cache->item));
10473                 if (ret) {
10474                         fprintf(stderr, "Error adding block group\n");
10475                         return ret;
10476                 }
10477                 btrfs_extent_post_op(trans, fs_info->extent_root);
10478         }
10479
10480         ret = reset_balance(trans, fs_info);
10481         if (ret)
10482                 fprintf(stderr, "error resetting the pending balance\n");
10483
10484         return ret;
10485 }
10486
10487 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
10488 {
10489         struct btrfs_path *path;
10490         struct btrfs_trans_handle *trans;
10491         struct btrfs_key key;
10492         int ret;
10493
10494         printf("Recowing metadata block %llu\n", eb->start);
10495         key.objectid = btrfs_header_owner(eb);
10496         key.type = BTRFS_ROOT_ITEM_KEY;
10497         key.offset = (u64)-1;
10498
10499         root = btrfs_read_fs_root(root->fs_info, &key);
10500         if (IS_ERR(root)) {
10501                 fprintf(stderr, "Couldn't find owner root %llu\n",
10502                         key.objectid);
10503                 return PTR_ERR(root);
10504         }
10505
10506         path = btrfs_alloc_path();
10507         if (!path)
10508                 return -ENOMEM;
10509
10510         trans = btrfs_start_transaction(root, 1);
10511         if (IS_ERR(trans)) {
10512                 btrfs_free_path(path);
10513                 return PTR_ERR(trans);
10514         }
10515
10516         path->lowest_level = btrfs_header_level(eb);
10517         if (path->lowest_level)
10518                 btrfs_node_key_to_cpu(eb, &key, 0);
10519         else
10520                 btrfs_item_key_to_cpu(eb, &key, 0);
10521
10522         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
10523         btrfs_commit_transaction(trans, root);
10524         btrfs_free_path(path);
10525         return ret;
10526 }
10527
10528 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
10529 {
10530         struct btrfs_path *path;
10531         struct btrfs_trans_handle *trans;
10532         struct btrfs_key key;
10533         int ret;
10534
10535         printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
10536                bad->key.type, bad->key.offset);
10537         key.objectid = bad->root_id;
10538         key.type = BTRFS_ROOT_ITEM_KEY;
10539         key.offset = (u64)-1;
10540
10541         root = btrfs_read_fs_root(root->fs_info, &key);
10542         if (IS_ERR(root)) {
10543                 fprintf(stderr, "Couldn't find owner root %llu\n",
10544                         key.objectid);
10545                 return PTR_ERR(root);
10546         }
10547
10548         path = btrfs_alloc_path();
10549         if (!path)
10550                 return -ENOMEM;
10551
10552         trans = btrfs_start_transaction(root, 1);
10553         if (IS_ERR(trans)) {
10554                 btrfs_free_path(path);
10555                 return PTR_ERR(trans);
10556         }
10557
10558         ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
10559         if (ret) {
10560                 if (ret > 0)
10561                         ret = 0;
10562                 goto out;
10563         }
10564         ret = btrfs_del_item(trans, root, path);
10565 out:
10566         btrfs_commit_transaction(trans, root);
10567         btrfs_free_path(path);
10568         return ret;
10569 }
10570
10571 static int zero_log_tree(struct btrfs_root *root)
10572 {
10573         struct btrfs_trans_handle *trans;
10574         int ret;
10575
10576         trans = btrfs_start_transaction(root, 1);
10577         if (IS_ERR(trans)) {
10578                 ret = PTR_ERR(trans);
10579                 return ret;
10580         }
10581         btrfs_set_super_log_root(root->fs_info->super_copy, 0);
10582         btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
10583         ret = btrfs_commit_transaction(trans, root);
10584         return ret;
10585 }
10586
10587 static int populate_csum(struct btrfs_trans_handle *trans,
10588                          struct btrfs_root *csum_root, char *buf, u64 start,
10589                          u64 len)
10590 {
10591         u64 offset = 0;
10592         u64 sectorsize;
10593         int ret = 0;
10594
10595         while (offset < len) {
10596                 sectorsize = csum_root->sectorsize;
10597                 ret = read_extent_data(csum_root, buf, start + offset,
10598                                        &sectorsize, 0);
10599                 if (ret)
10600                         break;
10601                 ret = btrfs_csum_file_block(trans, csum_root, start + len,
10602                                             start + offset, buf, sectorsize);
10603                 if (ret)
10604                         break;
10605                 offset += sectorsize;
10606         }
10607         return ret;
10608 }
10609
10610 static int fill_csum_tree_from_one_fs_root(struct btrfs_trans_handle *trans,
10611                                       struct btrfs_root *csum_root,
10612                                       struct btrfs_root *cur_root)
10613 {
10614         struct btrfs_path *path;
10615         struct btrfs_key key;
10616         struct extent_buffer *node;
10617         struct btrfs_file_extent_item *fi;
10618         char *buf = NULL;
10619         u64 start = 0;
10620         u64 len = 0;
10621         int slot = 0;
10622         int ret = 0;
10623
10624         path = btrfs_alloc_path();
10625         if (!path)
10626                 return -ENOMEM;
10627         buf = malloc(cur_root->fs_info->csum_root->sectorsize);
10628         if (!buf) {
10629                 ret = -ENOMEM;
10630                 goto out;
10631         }
10632
10633         key.objectid = 0;
10634         key.offset = 0;
10635         key.type = 0;
10636
10637         ret = btrfs_search_slot(NULL, cur_root, &key, path, 0, 0);
10638         if (ret < 0)
10639                 goto out;
10640         /* Iterate all regular file extents and fill its csum */
10641         while (1) {
10642                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
10643
10644                 if (key.type != BTRFS_EXTENT_DATA_KEY)
10645                         goto next;
10646                 node = path->nodes[0];
10647                 slot = path->slots[0];
10648                 fi = btrfs_item_ptr(node, slot, struct btrfs_file_extent_item);
10649                 if (btrfs_file_extent_type(node, fi) != BTRFS_FILE_EXTENT_REG)
10650                         goto next;
10651                 start = btrfs_file_extent_disk_bytenr(node, fi);
10652                 len = btrfs_file_extent_disk_num_bytes(node, fi);
10653
10654                 ret = populate_csum(trans, csum_root, buf, start, len);
10655                 if (ret == -EEXIST)
10656                         ret = 0;
10657                 if (ret < 0)
10658                         goto out;
10659 next:
10660                 /*
10661                  * TODO: if next leaf is corrupted, jump to nearest next valid
10662                  * leaf.
10663                  */
10664                 ret = btrfs_next_item(cur_root, path);
10665                 if (ret < 0)
10666                         goto out;
10667                 if (ret > 0) {
10668                         ret = 0;
10669                         goto out;
10670                 }
10671         }
10672
10673 out:
10674         btrfs_free_path(path);
10675         free(buf);
10676         return ret;
10677 }
10678
10679 static int fill_csum_tree_from_fs(struct btrfs_trans_handle *trans,
10680                                   struct btrfs_root *csum_root)
10681 {
10682         struct btrfs_fs_info *fs_info = csum_root->fs_info;
10683         struct btrfs_path *path;
10684         struct btrfs_root *tree_root = fs_info->tree_root;
10685         struct btrfs_root *cur_root;
10686         struct extent_buffer *node;
10687         struct btrfs_key key;
10688         int slot = 0;
10689         int ret = 0;
10690
10691         path = btrfs_alloc_path();
10692         if (!path)
10693                 return -ENOMEM;
10694
10695         key.objectid = BTRFS_FS_TREE_OBJECTID;
10696         key.offset = 0;
10697         key.type = BTRFS_ROOT_ITEM_KEY;
10698
10699         ret = btrfs_search_slot(NULL, tree_root, &key, path, 0, 0);
10700         if (ret < 0)
10701                 goto out;
10702         if (ret > 0) {
10703                 ret = -ENOENT;
10704                 goto out;
10705         }
10706
10707         while (1) {
10708                 node = path->nodes[0];
10709                 slot = path->slots[0];
10710                 btrfs_item_key_to_cpu(node, &key, slot);
10711                 if (key.objectid > BTRFS_LAST_FREE_OBJECTID)
10712                         goto out;
10713                 if (key.type != BTRFS_ROOT_ITEM_KEY)
10714                         goto next;
10715                 if (!is_fstree(key.objectid))
10716                         goto next;
10717                 key.offset = (u64)-1;
10718
10719                 cur_root = btrfs_read_fs_root(fs_info, &key);
10720                 if (IS_ERR(cur_root) || !cur_root) {
10721                         fprintf(stderr, "Fail to read fs/subvol tree: %lld\n",
10722                                 key.objectid);
10723                         goto out;
10724                 }
10725                 ret = fill_csum_tree_from_one_fs_root(trans, csum_root,
10726                                 cur_root);
10727                 if (ret < 0)
10728                         goto out;
10729 next:
10730                 ret = btrfs_next_item(tree_root, path);
10731                 if (ret > 0) {
10732                         ret = 0;
10733                         goto out;
10734                 }
10735                 if (ret < 0)
10736                         goto out;
10737         }
10738
10739 out:
10740         btrfs_free_path(path);
10741         return ret;
10742 }
10743
10744 static int fill_csum_tree_from_extent(struct btrfs_trans_handle *trans,
10745                                       struct btrfs_root *csum_root)
10746 {
10747         struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
10748         struct btrfs_path *path;
10749         struct btrfs_extent_item *ei;
10750         struct extent_buffer *leaf;
10751         char *buf;
10752         struct btrfs_key key;
10753         int ret;
10754
10755         path = btrfs_alloc_path();
10756         if (!path)
10757                 return -ENOMEM;
10758
10759         key.objectid = 0;
10760         key.type = BTRFS_EXTENT_ITEM_KEY;
10761         key.offset = 0;
10762
10763         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
10764         if (ret < 0) {
10765                 btrfs_free_path(path);
10766                 return ret;
10767         }
10768
10769         buf = malloc(csum_root->sectorsize);
10770         if (!buf) {
10771                 btrfs_free_path(path);
10772                 return -ENOMEM;
10773         }
10774
10775         while (1) {
10776                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
10777                         ret = btrfs_next_leaf(extent_root, path);
10778                         if (ret < 0)
10779                                 break;
10780                         if (ret) {
10781                                 ret = 0;
10782                                 break;
10783                         }
10784                 }
10785                 leaf = path->nodes[0];
10786
10787                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
10788                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
10789                         path->slots[0]++;
10790                         continue;
10791                 }
10792
10793                 ei = btrfs_item_ptr(leaf, path->slots[0],
10794                                     struct btrfs_extent_item);
10795                 if (!(btrfs_extent_flags(leaf, ei) &
10796                       BTRFS_EXTENT_FLAG_DATA)) {
10797                         path->slots[0]++;
10798                         continue;
10799                 }
10800
10801                 ret = populate_csum(trans, csum_root, buf, key.objectid,
10802                                     key.offset);
10803                 if (ret)
10804                         break;
10805                 path->slots[0]++;
10806         }
10807
10808         btrfs_free_path(path);
10809         free(buf);
10810         return ret;
10811 }
10812
10813 /*
10814  * Recalculate the csum and put it into the csum tree.
10815  *
10816  * Extent tree init will wipe out all the extent info, so in that case, we
10817  * can't depend on extent tree, but use fs tree.  If search_fs_tree is set, we
10818  * will use fs/subvol trees to init the csum tree.
10819  */
10820 static int fill_csum_tree(struct btrfs_trans_handle *trans,
10821                           struct btrfs_root *csum_root,
10822                           int search_fs_tree)
10823 {
10824         if (search_fs_tree)
10825                 return fill_csum_tree_from_fs(trans, csum_root);
10826         else
10827                 return fill_csum_tree_from_extent(trans, csum_root);
10828 }
10829
10830 static void free_roots_info_cache(void)
10831 {
10832         if (!roots_info_cache)
10833                 return;
10834
10835         while (!cache_tree_empty(roots_info_cache)) {
10836                 struct cache_extent *entry;
10837                 struct root_item_info *rii;
10838
10839                 entry = first_cache_extent(roots_info_cache);
10840                 if (!entry)
10841                         break;
10842                 remove_cache_extent(roots_info_cache, entry);
10843                 rii = container_of(entry, struct root_item_info, cache_extent);
10844                 free(rii);
10845         }
10846
10847         free(roots_info_cache);
10848         roots_info_cache = NULL;
10849 }
10850
10851 static int build_roots_info_cache(struct btrfs_fs_info *info)
10852 {
10853         int ret = 0;
10854         struct btrfs_key key;
10855         struct extent_buffer *leaf;
10856         struct btrfs_path *path;
10857
10858         if (!roots_info_cache) {
10859                 roots_info_cache = malloc(sizeof(*roots_info_cache));
10860                 if (!roots_info_cache)
10861                         return -ENOMEM;
10862                 cache_tree_init(roots_info_cache);
10863         }
10864
10865         path = btrfs_alloc_path();
10866         if (!path)
10867                 return -ENOMEM;
10868
10869         key.objectid = 0;
10870         key.type = BTRFS_EXTENT_ITEM_KEY;
10871         key.offset = 0;
10872
10873         ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
10874         if (ret < 0)
10875                 goto out;
10876         leaf = path->nodes[0];
10877
10878         while (1) {
10879                 struct btrfs_key found_key;
10880                 struct btrfs_extent_item *ei;
10881                 struct btrfs_extent_inline_ref *iref;
10882                 int slot = path->slots[0];
10883                 int type;
10884                 u64 flags;
10885                 u64 root_id;
10886                 u8 level;
10887                 struct cache_extent *entry;
10888                 struct root_item_info *rii;
10889
10890                 if (slot >= btrfs_header_nritems(leaf)) {
10891                         ret = btrfs_next_leaf(info->extent_root, path);
10892                         if (ret < 0) {
10893                                 break;
10894                         } else if (ret) {
10895                                 ret = 0;
10896                                 break;
10897                         }
10898                         leaf = path->nodes[0];
10899                         slot = path->slots[0];
10900                 }
10901
10902                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
10903
10904                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
10905                     found_key.type != BTRFS_METADATA_ITEM_KEY)
10906                         goto next;
10907
10908                 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
10909                 flags = btrfs_extent_flags(leaf, ei);
10910
10911                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
10912                     !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
10913                         goto next;
10914
10915                 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
10916                         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
10917                         level = found_key.offset;
10918                 } else {
10919                         struct btrfs_tree_block_info *binfo;
10920
10921                         binfo = (struct btrfs_tree_block_info *)(ei + 1);
10922                         iref = (struct btrfs_extent_inline_ref *)(binfo + 1);
10923                         level = btrfs_tree_block_level(leaf, binfo);
10924                 }
10925
10926                 /*
10927                  * For a root extent, it must be of the following type and the
10928                  * first (and only one) iref in the item.
10929                  */
10930                 type = btrfs_extent_inline_ref_type(leaf, iref);
10931                 if (type != BTRFS_TREE_BLOCK_REF_KEY)
10932                         goto next;
10933
10934                 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
10935                 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
10936                 if (!entry) {
10937                         rii = malloc(sizeof(struct root_item_info));
10938                         if (!rii) {
10939                                 ret = -ENOMEM;
10940                                 goto out;
10941                         }
10942                         rii->cache_extent.start = root_id;
10943                         rii->cache_extent.size = 1;
10944                         rii->level = (u8)-1;
10945                         entry = &rii->cache_extent;
10946                         ret = insert_cache_extent(roots_info_cache, entry);
10947                         ASSERT(ret == 0);
10948                 } else {
10949                         rii = container_of(entry, struct root_item_info,
10950                                            cache_extent);
10951                 }
10952
10953                 ASSERT(rii->cache_extent.start == root_id);
10954                 ASSERT(rii->cache_extent.size == 1);
10955
10956                 if (level > rii->level || rii->level == (u8)-1) {
10957                         rii->level = level;
10958                         rii->bytenr = found_key.objectid;
10959                         rii->gen = btrfs_extent_generation(leaf, ei);
10960                         rii->node_count = 1;
10961                 } else if (level == rii->level) {
10962                         rii->node_count++;
10963                 }
10964 next:
10965                 path->slots[0]++;
10966         }
10967
10968 out:
10969         btrfs_free_path(path);
10970
10971         return ret;
10972 }
10973
10974 static int maybe_repair_root_item(struct btrfs_fs_info *info,
10975                                   struct btrfs_path *path,
10976                                   const struct btrfs_key *root_key,
10977                                   const int read_only_mode)
10978 {
10979         const u64 root_id = root_key->objectid;
10980         struct cache_extent *entry;
10981         struct root_item_info *rii;
10982         struct btrfs_root_item ri;
10983         unsigned long offset;
10984
10985         entry = lookup_cache_extent(roots_info_cache, root_id, 1);
10986         if (!entry) {
10987                 fprintf(stderr,
10988                         "Error: could not find extent items for root %llu\n",
10989                         root_key->objectid);
10990                 return -ENOENT;
10991         }
10992
10993         rii = container_of(entry, struct root_item_info, cache_extent);
10994         ASSERT(rii->cache_extent.start == root_id);
10995         ASSERT(rii->cache_extent.size == 1);
10996
10997         if (rii->node_count != 1) {
10998                 fprintf(stderr,
10999                         "Error: could not find btree root extent for root %llu\n",
11000                         root_id);
11001                 return -ENOENT;
11002         }
11003
11004         offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
11005         read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
11006
11007         if (btrfs_root_bytenr(&ri) != rii->bytenr ||
11008             btrfs_root_level(&ri) != rii->level ||
11009             btrfs_root_generation(&ri) != rii->gen) {
11010
11011                 /*
11012                  * If we're in repair mode but our caller told us to not update
11013                  * the root item, i.e. just check if it needs to be updated, don't
11014                  * print this message, since the caller will call us again shortly
11015                  * for the same root item without read only mode (the caller will
11016                  * open a transaction first).
11017                  */
11018                 if (!(read_only_mode && repair))
11019                         fprintf(stderr,
11020                                 "%sroot item for root %llu,"
11021                                 " current bytenr %llu, current gen %llu, current level %u,"
11022                                 " new bytenr %llu, new gen %llu, new level %u\n",
11023                                 (read_only_mode ? "" : "fixing "),
11024                                 root_id,
11025                                 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
11026                                 btrfs_root_level(&ri),
11027                                 rii->bytenr, rii->gen, rii->level);
11028
11029                 if (btrfs_root_generation(&ri) > rii->gen) {
11030                         fprintf(stderr,
11031                                 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
11032                                 root_id, btrfs_root_generation(&ri), rii->gen);
11033                         return -EINVAL;
11034                 }
11035
11036                 if (!read_only_mode) {
11037                         btrfs_set_root_bytenr(&ri, rii->bytenr);
11038                         btrfs_set_root_level(&ri, rii->level);
11039                         btrfs_set_root_generation(&ri, rii->gen);
11040                         write_extent_buffer(path->nodes[0], &ri,
11041                                             offset, sizeof(ri));
11042                 }
11043
11044                 return 1;
11045         }
11046
11047         return 0;
11048 }
11049
11050 /*
11051  * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
11052  * caused read-only snapshots to be corrupted if they were created at a moment
11053  * when the source subvolume/snapshot had orphan items. The issue was that the
11054  * on-disk root items became incorrect, referring to the pre orphan cleanup root
11055  * node instead of the post orphan cleanup root node.
11056  * So this function, and its callees, just detects and fixes those cases. Even
11057  * though the regression was for read-only snapshots, this function applies to
11058  * any snapshot/subvolume root.
11059  * This must be run before any other repair code - not doing it so, makes other
11060  * repair code delete or modify backrefs in the extent tree for example, which
11061  * will result in an inconsistent fs after repairing the root items.
11062  */
11063 static int repair_root_items(struct btrfs_fs_info *info)
11064 {
11065         struct btrfs_path *path = NULL;
11066         struct btrfs_key key;
11067         struct extent_buffer *leaf;
11068         struct btrfs_trans_handle *trans = NULL;
11069         int ret = 0;
11070         int bad_roots = 0;
11071         int need_trans = 0;
11072
11073         ret = build_roots_info_cache(info);
11074         if (ret)
11075                 goto out;
11076
11077         path = btrfs_alloc_path();
11078         if (!path) {
11079                 ret = -ENOMEM;
11080                 goto out;
11081         }
11082
11083         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
11084         key.type = BTRFS_ROOT_ITEM_KEY;
11085         key.offset = 0;
11086
11087 again:
11088         /*
11089          * Avoid opening and committing transactions if a leaf doesn't have
11090          * any root items that need to be fixed, so that we avoid rotating
11091          * backup roots unnecessarily.
11092          */
11093         if (need_trans) {
11094                 trans = btrfs_start_transaction(info->tree_root, 1);
11095                 if (IS_ERR(trans)) {
11096                         ret = PTR_ERR(trans);
11097                         goto out;
11098                 }
11099         }
11100
11101         ret = btrfs_search_slot(trans, info->tree_root, &key, path,
11102                                 0, trans ? 1 : 0);
11103         if (ret < 0)
11104                 goto out;
11105         leaf = path->nodes[0];
11106
11107         while (1) {
11108                 struct btrfs_key found_key;
11109
11110                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
11111                         int no_more_keys = find_next_key(path, &key);
11112
11113                         btrfs_release_path(path);
11114                         if (trans) {
11115                                 ret = btrfs_commit_transaction(trans,
11116                                                                info->tree_root);
11117                                 trans = NULL;
11118                                 if (ret < 0)
11119                                         goto out;
11120                         }
11121                         need_trans = 0;
11122                         if (no_more_keys)
11123                                 break;
11124                         goto again;
11125                 }
11126
11127                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
11128
11129                 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
11130                         goto next;
11131                 if (found_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
11132                         goto next;
11133
11134                 ret = maybe_repair_root_item(info, path, &found_key,
11135                                              trans ? 0 : 1);
11136                 if (ret < 0)
11137                         goto out;
11138                 if (ret) {
11139                         if (!trans && repair) {
11140                                 need_trans = 1;
11141                                 key = found_key;
11142                                 btrfs_release_path(path);
11143                                 goto again;
11144                         }
11145                         bad_roots++;
11146                 }
11147 next:
11148                 path->slots[0]++;
11149         }
11150         ret = 0;
11151 out:
11152         free_roots_info_cache();
11153         btrfs_free_path(path);
11154         if (trans)
11155                 btrfs_commit_transaction(trans, info->tree_root);
11156         if (ret < 0)
11157                 return ret;
11158
11159         return bad_roots;
11160 }
11161
11162 static int clear_free_space_cache(struct btrfs_fs_info *fs_info)
11163 {
11164         struct btrfs_trans_handle *trans;
11165         struct btrfs_block_group_cache *bg_cache;
11166         u64 current = 0;
11167         int ret = 0;
11168
11169         /* Clear all free space cache inodes and its extent data */
11170         while (1) {
11171                 bg_cache = btrfs_lookup_first_block_group(fs_info, current);
11172                 if (!bg_cache)
11173                         break;
11174                 ret = btrfs_clear_free_space_cache(fs_info, bg_cache);
11175                 if (ret < 0)
11176                         return ret;
11177                 current = bg_cache->key.objectid + bg_cache->key.offset;
11178         }
11179
11180         /* Don't forget to set cache_generation to -1 */
11181         trans = btrfs_start_transaction(fs_info->tree_root, 0);
11182         if (IS_ERR(trans)) {
11183                 error("failed to update super block cache generation");
11184                 return PTR_ERR(trans);
11185         }
11186         btrfs_set_super_cache_generation(fs_info->super_copy, (u64)-1);
11187         btrfs_commit_transaction(trans, fs_info->tree_root);
11188
11189         return ret;
11190 }
11191
11192 const char * const cmd_check_usage[] = {
11193         "btrfs check [options] <device>",
11194         "Check structural integrity of a filesystem (unmounted).",
11195         "Check structural integrity of an unmounted filesystem. Verify internal",
11196         "trees' consistency and item connectivity. In the repair mode try to",
11197         "fix the problems found. ",
11198         "WARNING: the repair mode is considered dangerous",
11199         "",
11200         "-s|--super <superblock>     use this superblock copy",
11201         "-b|--backup                 use the first valid backup root copy",
11202         "--repair                    try to repair the filesystem",
11203         "--readonly                  run in read-only mode (default)",
11204         "--init-csum-tree            create a new CRC tree",
11205         "--init-extent-tree          create a new extent tree",
11206         "--mode <MODE>               allows choice of memory/IO trade-offs",
11207         "                            where MODE is one of:",
11208         "                            original - read inodes and extents to memory (requires",
11209         "                                       more memory, does less IO)",
11210         "                            lowmem   - try to use less memory but read blocks again",
11211         "                                       when needed",
11212         "--check-data-csum           verify checksums of data blocks",
11213         "-Q|--qgroup-report          print a report on qgroup consistency",
11214         "-E|--subvol-extents <subvolid>",
11215         "                            print subvolume extents and sharing state",
11216         "-r|--tree-root <bytenr>     use the given bytenr for the tree root",
11217         "--chunk-root <bytenr>       use the given bytenr for the chunk tree root",
11218         "-p|--progress               indicate progress",
11219         "--clear-space-cache v1|v2   clear space cache for v1 or v2",
11220         "                            NOTE: v1 support implemented",
11221         NULL
11222 };
11223
11224 int cmd_check(int argc, char **argv)
11225 {
11226         struct cache_tree root_cache;
11227         struct btrfs_root *root;
11228         struct btrfs_fs_info *info;
11229         u64 bytenr = 0;
11230         u64 subvolid = 0;
11231         u64 tree_root_bytenr = 0;
11232         u64 chunk_root_bytenr = 0;
11233         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
11234         int ret;
11235         u64 num;
11236         int init_csum_tree = 0;
11237         int readonly = 0;
11238         int clear_space_cache = 0;
11239         int qgroup_report = 0;
11240         int qgroups_repaired = 0;
11241         unsigned ctree_flags = OPEN_CTREE_EXCLUSIVE;
11242
11243         while(1) {
11244                 int c;
11245                 enum { GETOPT_VAL_REPAIR = 257, GETOPT_VAL_INIT_CSUM,
11246                         GETOPT_VAL_INIT_EXTENT, GETOPT_VAL_CHECK_CSUM,
11247                         GETOPT_VAL_READONLY, GETOPT_VAL_CHUNK_TREE,
11248                         GETOPT_VAL_MODE, GETOPT_VAL_CLEAR_SPACE_CACHE };
11249                 static const struct option long_options[] = {
11250                         { "super", required_argument, NULL, 's' },
11251                         { "repair", no_argument, NULL, GETOPT_VAL_REPAIR },
11252                         { "readonly", no_argument, NULL, GETOPT_VAL_READONLY },
11253                         { "init-csum-tree", no_argument, NULL,
11254                                 GETOPT_VAL_INIT_CSUM },
11255                         { "init-extent-tree", no_argument, NULL,
11256                                 GETOPT_VAL_INIT_EXTENT },
11257                         { "check-data-csum", no_argument, NULL,
11258                                 GETOPT_VAL_CHECK_CSUM },
11259                         { "backup", no_argument, NULL, 'b' },
11260                         { "subvol-extents", required_argument, NULL, 'E' },
11261                         { "qgroup-report", no_argument, NULL, 'Q' },
11262                         { "tree-root", required_argument, NULL, 'r' },
11263                         { "chunk-root", required_argument, NULL,
11264                                 GETOPT_VAL_CHUNK_TREE },
11265                         { "progress", no_argument, NULL, 'p' },
11266                         { "mode", required_argument, NULL,
11267                                 GETOPT_VAL_MODE },
11268                         { "clear-space-cache", required_argument, NULL,
11269                                 GETOPT_VAL_CLEAR_SPACE_CACHE},
11270                         { NULL, 0, NULL, 0}
11271                 };
11272
11273                 c = getopt_long(argc, argv, "as:br:p", long_options, NULL);
11274                 if (c < 0)
11275                         break;
11276                 switch(c) {
11277                         case 'a': /* ignored */ break;
11278                         case 'b':
11279                                 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
11280                                 break;
11281                         case 's':
11282                                 num = arg_strtou64(optarg);
11283                                 if (num >= BTRFS_SUPER_MIRROR_MAX) {
11284                                         error(
11285                                         "super mirror should be less than %d",
11286                                                 BTRFS_SUPER_MIRROR_MAX);
11287                                         exit(1);
11288                                 }
11289                                 bytenr = btrfs_sb_offset(((int)num));
11290                                 printf("using SB copy %llu, bytenr %llu\n", num,
11291                                        (unsigned long long)bytenr);
11292                                 break;
11293                         case 'Q':
11294                                 qgroup_report = 1;
11295                                 break;
11296                         case 'E':
11297                                 subvolid = arg_strtou64(optarg);
11298                                 break;
11299                         case 'r':
11300                                 tree_root_bytenr = arg_strtou64(optarg);
11301                                 break;
11302                         case GETOPT_VAL_CHUNK_TREE:
11303                                 chunk_root_bytenr = arg_strtou64(optarg);
11304                                 break;
11305                         case 'p':
11306                                 ctx.progress_enabled = true;
11307                                 break;
11308                         case '?':
11309                         case 'h':
11310                                 usage(cmd_check_usage);
11311                         case GETOPT_VAL_REPAIR:
11312                                 printf("enabling repair mode\n");
11313                                 repair = 1;
11314                                 ctree_flags |= OPEN_CTREE_WRITES;
11315                                 break;
11316                         case GETOPT_VAL_READONLY:
11317                                 readonly = 1;
11318                                 break;
11319                         case GETOPT_VAL_INIT_CSUM:
11320                                 printf("Creating a new CRC tree\n");
11321                                 init_csum_tree = 1;
11322                                 repair = 1;
11323                                 ctree_flags |= OPEN_CTREE_WRITES;
11324                                 break;
11325                         case GETOPT_VAL_INIT_EXTENT:
11326                                 init_extent_tree = 1;
11327                                 ctree_flags |= (OPEN_CTREE_WRITES |
11328                                                 OPEN_CTREE_NO_BLOCK_GROUPS);
11329                                 repair = 1;
11330                                 break;
11331                         case GETOPT_VAL_CHECK_CSUM:
11332                                 check_data_csum = 1;
11333                                 break;
11334                         case GETOPT_VAL_MODE:
11335                                 check_mode = parse_check_mode(optarg);
11336                                 if (check_mode == CHECK_MODE_UNKNOWN) {
11337                                         error("unknown mode: %s", optarg);
11338                                         exit(1);
11339                                 }
11340                                 break;
11341                         case GETOPT_VAL_CLEAR_SPACE_CACHE:
11342                                 if (strcmp(optarg, "v1") != 0) {
11343                                         error(
11344                         "only v1 support implmented, unrecognized value %s",
11345                         optarg);
11346                                         exit(1);
11347                                 }
11348                                 clear_space_cache = 1;
11349                                 ctree_flags |= OPEN_CTREE_WRITES;
11350                                 break;
11351                 }
11352         }
11353
11354         if (check_argc_exact(argc - optind, 1))
11355                 usage(cmd_check_usage);
11356
11357         if (ctx.progress_enabled) {
11358                 ctx.tp = TASK_NOTHING;
11359                 ctx.info = task_init(print_status_check, print_status_return, &ctx);
11360         }
11361
11362         /* This check is the only reason for --readonly to exist */
11363         if (readonly && repair) {
11364                 error("repair options are not compatible with --readonly");
11365                 exit(1);
11366         }
11367
11368         /*
11369          * Not supported yet
11370          */
11371         if (repair && check_mode == CHECK_MODE_LOWMEM) {
11372                 error("low memory mode doesn't support repair yet");
11373                 exit(1);
11374         }
11375
11376         radix_tree_init();
11377         cache_tree_init(&root_cache);
11378
11379         if((ret = check_mounted(argv[optind])) < 0) {
11380                 error("could not check mount status: %s", strerror(-ret));
11381                 goto err_out;
11382         } else if(ret) {
11383                 error("%s is currently mounted, aborting", argv[optind]);
11384                 ret = -EBUSY;
11385                 goto err_out;
11386         }
11387
11388         /* only allow partial opening under repair mode */
11389         if (repair)
11390                 ctree_flags |= OPEN_CTREE_PARTIAL;
11391
11392         info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
11393                                   chunk_root_bytenr, ctree_flags);
11394         if (!info) {
11395                 error("cannot open file system");
11396                 ret = -EIO;
11397                 goto err_out;
11398         }
11399
11400         global_info = info;
11401         root = info->fs_root;
11402         if (clear_space_cache) {
11403                 if (btrfs_fs_compat_ro(info,
11404                                 BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE)) {
11405                         error(
11406                         "free space cache v2 detected, clearing not implemented");
11407                         ret = 1;
11408                         goto close_out;
11409                 }
11410                 printf("Clearing free space cache\n");
11411                 ret = clear_free_space_cache(info);
11412                 if (ret) {
11413                         error("failed to clear free space cache");
11414                         ret = 1;
11415                 } else {
11416                         printf("Free space cache cleared\n");
11417                 }
11418                 goto close_out;
11419         }
11420
11421         /*
11422          * repair mode will force us to commit transaction which
11423          * will make us fail to load log tree when mounting.
11424          */
11425         if (repair && btrfs_super_log_root(info->super_copy)) {
11426                 ret = ask_user("repair mode will force to clear out log tree, are you sure?");
11427                 if (!ret) {
11428                         ret = 1;
11429                         goto close_out;
11430                 }
11431                 ret = zero_log_tree(root);
11432                 if (ret) {
11433                         error("failed to zero log tree: %d", ret);
11434                         goto close_out;
11435                 }
11436         }
11437
11438         uuid_unparse(info->super_copy->fsid, uuidbuf);
11439         if (qgroup_report) {
11440                 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
11441                        uuidbuf);
11442                 ret = qgroup_verify_all(info);
11443                 if (ret == 0)
11444                         report_qgroups(1);
11445                 goto close_out;
11446         }
11447         if (subvolid) {
11448                 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
11449                        subvolid, argv[optind], uuidbuf);
11450                 ret = print_extent_state(info, subvolid);
11451                 goto close_out;
11452         }
11453         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
11454
11455         if (!extent_buffer_uptodate(info->tree_root->node) ||
11456             !extent_buffer_uptodate(info->dev_root->node) ||
11457             !extent_buffer_uptodate(info->chunk_root->node)) {
11458                 error("critical roots corrupted, unable to check the filesystem");
11459                 ret = -EIO;
11460                 goto close_out;
11461         }
11462
11463         if (init_extent_tree || init_csum_tree) {
11464                 struct btrfs_trans_handle *trans;
11465
11466                 trans = btrfs_start_transaction(info->extent_root, 0);
11467                 if (IS_ERR(trans)) {
11468                         error("error starting transaction");
11469                         ret = PTR_ERR(trans);
11470                         goto close_out;
11471                 }
11472
11473                 if (init_extent_tree) {
11474                         printf("Creating a new extent tree\n");
11475                         ret = reinit_extent_tree(trans, info);
11476                         if (ret)
11477                                 goto close_out;
11478                 }
11479
11480                 if (init_csum_tree) {
11481                         printf("Reinitialize checksum tree\n");
11482                         ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
11483                         if (ret) {
11484                                 error("checksum tree initialization failed: %d",
11485                                                 ret);
11486                                 ret = -EIO;
11487                                 goto close_out;
11488                         }
11489
11490                         ret = fill_csum_tree(trans, info->csum_root,
11491                                              init_extent_tree);
11492                         if (ret) {
11493                                 error("checksum tree refilling failed: %d", ret);
11494                                 return -EIO;
11495                         }
11496                 }
11497                 /*
11498                  * Ok now we commit and run the normal fsck, which will add
11499                  * extent entries for all of the items it finds.
11500                  */
11501                 ret = btrfs_commit_transaction(trans, info->extent_root);
11502                 if (ret)
11503                         goto close_out;
11504         }
11505         if (!extent_buffer_uptodate(info->extent_root->node)) {
11506                 error("critical: extent_root, unable to check the filesystem");
11507                 ret = -EIO;
11508                 goto close_out;
11509         }
11510         if (!extent_buffer_uptodate(info->csum_root->node)) {
11511                 error("critical: csum_root, unable to check the filesystem");
11512                 ret = -EIO;
11513                 goto close_out;
11514         }
11515
11516         if (!ctx.progress_enabled)
11517                 printf("checking extents");
11518         if (check_mode == CHECK_MODE_LOWMEM)
11519                 ret = check_chunks_and_extents_v2(root);
11520         else
11521                 ret = check_chunks_and_extents(root);
11522         if (ret)
11523                 printf("Errors found in extent allocation tree or chunk allocation");
11524
11525         ret = repair_root_items(info);
11526         if (ret < 0)
11527                 goto close_out;
11528         if (repair) {
11529                 fprintf(stderr, "Fixed %d roots.\n", ret);
11530                 ret = 0;
11531         } else if (ret > 0) {
11532                 fprintf(stderr,
11533                        "Found %d roots with an outdated root item.\n",
11534                        ret);
11535                 fprintf(stderr,
11536                         "Please run a filesystem check with the option --repair to fix them.\n");
11537                 ret = 1;
11538                 goto close_out;
11539         }
11540
11541         if (!ctx.progress_enabled) {
11542                 if (btrfs_fs_compat_ro(info, BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE))
11543                         fprintf(stderr, "checking free space tree\n");
11544                 else
11545                         fprintf(stderr, "checking free space cache\n");
11546         }
11547         ret = check_space_cache(root);
11548         if (ret)
11549                 goto out;
11550
11551         /*
11552          * We used to have to have these hole extents in between our real
11553          * extents so if we don't have this flag set we need to make sure there
11554          * are no gaps in the file extents for inodes, otherwise we can just
11555          * ignore it when this happens.
11556          */
11557         no_holes = btrfs_fs_incompat(root->fs_info,
11558                                      BTRFS_FEATURE_INCOMPAT_NO_HOLES);
11559         if (!ctx.progress_enabled)
11560                 fprintf(stderr, "checking fs roots\n");
11561         ret = check_fs_roots(root, &root_cache);
11562         if (ret)
11563                 goto out;
11564
11565         fprintf(stderr, "checking csums\n");
11566         ret = check_csums(root);
11567         if (ret)
11568                 goto out;
11569
11570         fprintf(stderr, "checking root refs\n");
11571         ret = check_root_refs(root, &root_cache);
11572         if (ret)
11573                 goto out;
11574
11575         while (repair && !list_empty(&root->fs_info->recow_ebs)) {
11576                 struct extent_buffer *eb;
11577
11578                 eb = list_first_entry(&root->fs_info->recow_ebs,
11579                                       struct extent_buffer, recow);
11580                 list_del_init(&eb->recow);
11581                 ret = recow_extent_buffer(root, eb);
11582                 if (ret)
11583                         break;
11584         }
11585
11586         while (!list_empty(&delete_items)) {
11587                 struct bad_item *bad;
11588
11589                 bad = list_first_entry(&delete_items, struct bad_item, list);
11590                 list_del_init(&bad->list);
11591                 if (repair)
11592                         ret = delete_bad_item(root, bad);
11593                 free(bad);
11594         }
11595
11596         if (info->quota_enabled) {
11597                 int err;
11598                 fprintf(stderr, "checking quota groups\n");
11599                 err = qgroup_verify_all(info);
11600                 if (err)
11601                         goto out;
11602                 report_qgroups(0);
11603                 err = repair_qgroups(info, &qgroups_repaired);
11604                 if (err)
11605                         goto out;
11606         }
11607
11608         if (!list_empty(&root->fs_info->recow_ebs)) {
11609                 error("transid errors in file system");
11610                 ret = 1;
11611         }
11612 out:
11613         /* Don't override original ret */
11614         if (!ret && qgroups_repaired)
11615                 ret = qgroups_repaired;
11616
11617         if (found_old_backref) { /*
11618                  * there was a disk format change when mixed
11619                  * backref was in testing tree. The old format
11620                  * existed about one week.
11621                  */
11622                 printf("\n * Found old mixed backref format. "
11623                        "The old format is not supported! *"
11624                        "\n * Please mount the FS in readonly mode, "
11625                        "backup data and re-format the FS. *\n\n");
11626                 ret = 1;
11627         }
11628         printf("found %llu bytes used err is %d\n",
11629                (unsigned long long)bytes_used, ret);
11630         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
11631         printf("total tree bytes: %llu\n",
11632                (unsigned long long)total_btree_bytes);
11633         printf("total fs tree bytes: %llu\n",
11634                (unsigned long long)total_fs_tree_bytes);
11635         printf("total extent tree bytes: %llu\n",
11636                (unsigned long long)total_extent_tree_bytes);
11637         printf("btree space waste bytes: %llu\n",
11638                (unsigned long long)btree_space_waste);
11639         printf("file data blocks allocated: %llu\n referenced %llu\n",
11640                 (unsigned long long)data_bytes_allocated,
11641                 (unsigned long long)data_bytes_referenced);
11642
11643         free_qgroup_counts();
11644         free_root_recs_tree(&root_cache);
11645 close_out:
11646         close_ctree(root);
11647 err_out:
11648         if (ctx.progress_enabled)
11649                 task_deinit(ctx.info);
11650
11651         return ret;
11652 }