Btrfs-progs: fsck: switch to is_fstree()
[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 #define _XOPEN_SOURCE 500
20 #define _GNU_SOURCE 1
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <getopt.h>
29 #include <uuid/uuid.h>
30 #include "ctree.h"
31 #include "volumes.h"
32 #include "repair.h"
33 #include "disk-io.h"
34 #include "print-tree.h"
35 #include "transaction.h"
36 #include "version.h"
37 #include "utils.h"
38 #include "commands.h"
39 #include "free-space-cache.h"
40 #include "btrfsck.h"
41 #include "qgroup-verify.h"
42
43 static u64 bytes_used = 0;
44 static u64 total_csum_bytes = 0;
45 static u64 total_btree_bytes = 0;
46 static u64 total_fs_tree_bytes = 0;
47 static u64 total_extent_tree_bytes = 0;
48 static u64 btree_space_waste = 0;
49 static u64 data_bytes_allocated = 0;
50 static u64 data_bytes_referenced = 0;
51 static int found_old_backref = 0;
52 static LIST_HEAD(duplicate_extents);
53 static LIST_HEAD(delete_items);
54 static int repair = 0;
55 static int no_holes = 0;
56 static int init_extent_tree = 0;
57 static int check_data_csum = 0;
58
59 struct extent_backref {
60         struct list_head list;
61         unsigned int is_data:1;
62         unsigned int found_extent_tree:1;
63         unsigned int full_backref:1;
64         unsigned int found_ref:1;
65         unsigned int broken:1;
66 };
67
68 struct data_backref {
69         struct extent_backref node;
70         union {
71                 u64 parent;
72                 u64 root;
73         };
74         u64 owner;
75         u64 offset;
76         u64 disk_bytenr;
77         u64 bytes;
78         u64 ram_bytes;
79         u32 num_refs;
80         u32 found_ref;
81 };
82
83 struct tree_backref {
84         struct extent_backref node;
85         union {
86                 u64 parent;
87                 u64 root;
88         };
89 };
90
91 struct extent_record {
92         struct list_head backrefs;
93         struct list_head dups;
94         struct list_head list;
95         struct cache_extent cache;
96         struct btrfs_disk_key parent_key;
97         u64 start;
98         u64 max_size;
99         u64 nr;
100         u64 refs;
101         u64 extent_item_refs;
102         u64 generation;
103         u64 parent_generation;
104         u64 info_objectid;
105         u32 num_duplicates;
106         u8 info_level;
107         unsigned int found_rec:1;
108         unsigned int content_checked:1;
109         unsigned int owner_ref_checked:1;
110         unsigned int is_root:1;
111         unsigned int metadata:1;
112 };
113
114 struct inode_backref {
115         struct list_head list;
116         unsigned int found_dir_item:1;
117         unsigned int found_dir_index:1;
118         unsigned int found_inode_ref:1;
119         unsigned int filetype:8;
120         int errors;
121         unsigned int ref_type;
122         u64 dir;
123         u64 index;
124         u16 namelen;
125         char name[0];
126 };
127
128 struct dropping_root_item_record {
129         struct list_head list;
130         struct btrfs_root_item ri;
131         struct btrfs_key found_key;
132 };
133
134 #define REF_ERR_NO_DIR_ITEM             (1 << 0)
135 #define REF_ERR_NO_DIR_INDEX            (1 << 1)
136 #define REF_ERR_NO_INODE_REF            (1 << 2)
137 #define REF_ERR_DUP_DIR_ITEM            (1 << 3)
138 #define REF_ERR_DUP_DIR_INDEX           (1 << 4)
139 #define REF_ERR_DUP_INODE_REF           (1 << 5)
140 #define REF_ERR_INDEX_UNMATCH           (1 << 6)
141 #define REF_ERR_FILETYPE_UNMATCH        (1 << 7)
142 #define REF_ERR_NAME_TOO_LONG           (1 << 8) // 100
143 #define REF_ERR_NO_ROOT_REF             (1 << 9)
144 #define REF_ERR_NO_ROOT_BACKREF         (1 << 10)
145 #define REF_ERR_DUP_ROOT_REF            (1 << 11)
146 #define REF_ERR_DUP_ROOT_BACKREF        (1 << 12)
147
148 struct inode_record {
149         struct list_head backrefs;
150         unsigned int checked:1;
151         unsigned int merging:1;
152         unsigned int found_inode_item:1;
153         unsigned int found_dir_item:1;
154         unsigned int found_file_extent:1;
155         unsigned int found_csum_item:1;
156         unsigned int some_csum_missing:1;
157         unsigned int nodatasum:1;
158         int errors;
159
160         u64 ino;
161         u32 nlink;
162         u32 imode;
163         u64 isize;
164         u64 nbytes;
165
166         u32 found_link;
167         u64 found_size;
168         u64 extent_start;
169         u64 extent_end;
170         u64 first_extent_gap;
171
172         u32 refs;
173 };
174
175 #define I_ERR_NO_INODE_ITEM             (1 << 0)
176 #define I_ERR_NO_ORPHAN_ITEM            (1 << 1)
177 #define I_ERR_DUP_INODE_ITEM            (1 << 2)
178 #define I_ERR_DUP_DIR_INDEX             (1 << 3)
179 #define I_ERR_ODD_DIR_ITEM              (1 << 4)
180 #define I_ERR_ODD_FILE_EXTENT           (1 << 5)
181 #define I_ERR_BAD_FILE_EXTENT           (1 << 6)
182 #define I_ERR_FILE_EXTENT_OVERLAP       (1 << 7)
183 #define I_ERR_FILE_EXTENT_DISCOUNT      (1 << 8) // 100
184 #define I_ERR_DIR_ISIZE_WRONG           (1 << 9)
185 #define I_ERR_FILE_NBYTES_WRONG         (1 << 10) // 400
186 #define I_ERR_ODD_CSUM_ITEM             (1 << 11)
187 #define I_ERR_SOME_CSUM_MISSING         (1 << 12)
188 #define I_ERR_LINK_COUNT_WRONG          (1 << 13)
189
190 struct root_backref {
191         struct list_head list;
192         unsigned int found_dir_item:1;
193         unsigned int found_dir_index:1;
194         unsigned int found_back_ref:1;
195         unsigned int found_forward_ref:1;
196         unsigned int reachable:1;
197         int errors;
198         u64 ref_root;
199         u64 dir;
200         u64 index;
201         u16 namelen;
202         char name[0];
203 };
204
205 struct root_record {
206         struct list_head backrefs;
207         struct cache_extent cache;
208         unsigned int found_root_item:1;
209         u64 objectid;
210         u32 found_ref;
211 };
212
213 struct ptr_node {
214         struct cache_extent cache;
215         void *data;
216 };
217
218 struct shared_node {
219         struct cache_extent cache;
220         struct cache_tree root_cache;
221         struct cache_tree inode_cache;
222         struct inode_record *current;
223         u32 refs;
224 };
225
226 struct block_info {
227         u64 start;
228         u32 size;
229 };
230
231 struct walk_control {
232         struct cache_tree shared;
233         struct shared_node *nodes[BTRFS_MAX_LEVEL];
234         int active_node;
235         int root_level;
236 };
237
238 struct bad_item {
239         struct btrfs_key key;
240         u64 root_id;
241         struct list_head list;
242 };
243
244 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
245
246 static u8 imode_to_type(u32 imode)
247 {
248 #define S_SHIFT 12
249         static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
250                 [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
251                 [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
252                 [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
253                 [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
254                 [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
255                 [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
256                 [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
257         };
258
259         return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
260 #undef S_SHIFT
261 }
262
263 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
264 {
265         struct device_record *rec1;
266         struct device_record *rec2;
267
268         rec1 = rb_entry(node1, struct device_record, node);
269         rec2 = rb_entry(node2, struct device_record, node);
270         if (rec1->devid > rec2->devid)
271                 return -1;
272         else if (rec1->devid < rec2->devid)
273                 return 1;
274         else
275                 return 0;
276 }
277
278 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
279 {
280         struct inode_record *rec;
281         struct inode_backref *backref;
282         struct inode_backref *orig;
283         size_t size;
284
285         rec = malloc(sizeof(*rec));
286         memcpy(rec, orig_rec, sizeof(*rec));
287         rec->refs = 1;
288         INIT_LIST_HEAD(&rec->backrefs);
289
290         list_for_each_entry(orig, &orig_rec->backrefs, list) {
291                 size = sizeof(*orig) + orig->namelen + 1;
292                 backref = malloc(size);
293                 memcpy(backref, orig, size);
294                 list_add_tail(&backref->list, &rec->backrefs);
295         }
296         return rec;
297 }
298
299 static void print_inode_error(int errors)
300 {
301         if (errors & I_ERR_NO_INODE_ITEM)
302                 fprintf(stderr, ", no inode item");
303         if (errors & I_ERR_NO_ORPHAN_ITEM)
304                 fprintf(stderr, ", no orphan item");
305         if (errors & I_ERR_DUP_INODE_ITEM)
306                 fprintf(stderr, ", dup inode item");
307         if (errors & I_ERR_DUP_DIR_INDEX)
308                 fprintf(stderr, ", dup dir index");
309         if (errors & I_ERR_ODD_DIR_ITEM)
310                 fprintf(stderr, ", odd dir item");
311         if (errors & I_ERR_ODD_FILE_EXTENT)
312                 fprintf(stderr, ", odd file extent");
313         if (errors & I_ERR_BAD_FILE_EXTENT)
314                 fprintf(stderr, ", bad file extent");
315         if (errors & I_ERR_FILE_EXTENT_OVERLAP)
316                 fprintf(stderr, ", file extent overlap");
317         if (errors & I_ERR_FILE_EXTENT_DISCOUNT)
318                 fprintf(stderr, ", file extent discount");
319         if (errors & I_ERR_DIR_ISIZE_WRONG)
320                 fprintf(stderr, ", dir isize wrong");
321         if (errors & I_ERR_FILE_NBYTES_WRONG)
322                 fprintf(stderr, ", nbytes wrong");
323         if (errors & I_ERR_ODD_CSUM_ITEM)
324                 fprintf(stderr, ", odd csum item");
325         if (errors & I_ERR_SOME_CSUM_MISSING)
326                 fprintf(stderr, ", some csum missing");
327         if (errors & I_ERR_LINK_COUNT_WRONG)
328                 fprintf(stderr, ", link count wrong");
329         fprintf(stderr, "\n");
330 }
331
332 static void print_ref_error(int errors)
333 {
334         if (errors & REF_ERR_NO_DIR_ITEM)
335                 fprintf(stderr, ", no dir item");
336         if (errors & REF_ERR_NO_DIR_INDEX)
337                 fprintf(stderr, ", no dir index");
338         if (errors & REF_ERR_NO_INODE_REF)
339                 fprintf(stderr, ", no inode ref");
340         if (errors & REF_ERR_DUP_DIR_ITEM)
341                 fprintf(stderr, ", dup dir item");
342         if (errors & REF_ERR_DUP_DIR_INDEX)
343                 fprintf(stderr, ", dup dir index");
344         if (errors & REF_ERR_DUP_INODE_REF)
345                 fprintf(stderr, ", dup inode ref");
346         if (errors & REF_ERR_INDEX_UNMATCH)
347                 fprintf(stderr, ", index unmatch");
348         if (errors & REF_ERR_FILETYPE_UNMATCH)
349                 fprintf(stderr, ", filetype unmatch");
350         if (errors & REF_ERR_NAME_TOO_LONG)
351                 fprintf(stderr, ", name too long");
352         if (errors & REF_ERR_NO_ROOT_REF)
353                 fprintf(stderr, ", no root ref");
354         if (errors & REF_ERR_NO_ROOT_BACKREF)
355                 fprintf(stderr, ", no root backref");
356         if (errors & REF_ERR_DUP_ROOT_REF)
357                 fprintf(stderr, ", dup root ref");
358         if (errors & REF_ERR_DUP_ROOT_BACKREF)
359                 fprintf(stderr, ", dup root backref");
360         fprintf(stderr, "\n");
361 }
362
363 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
364                                           u64 ino, int mod)
365 {
366         struct ptr_node *node;
367         struct cache_extent *cache;
368         struct inode_record *rec = NULL;
369         int ret;
370
371         cache = lookup_cache_extent(inode_cache, ino, 1);
372         if (cache) {
373                 node = container_of(cache, struct ptr_node, cache);
374                 rec = node->data;
375                 if (mod && rec->refs > 1) {
376                         node->data = clone_inode_rec(rec);
377                         rec->refs--;
378                         rec = node->data;
379                 }
380         } else if (mod) {
381                 rec = calloc(1, sizeof(*rec));
382                 rec->ino = ino;
383                 rec->extent_start = (u64)-1;
384                 rec->first_extent_gap = (u64)-1;
385                 rec->refs = 1;
386                 INIT_LIST_HEAD(&rec->backrefs);
387
388                 node = malloc(sizeof(*node));
389                 node->cache.start = ino;
390                 node->cache.size = 1;
391                 node->data = rec;
392
393                 if (ino == BTRFS_FREE_INO_OBJECTID)
394                         rec->found_link = 1;
395
396                 ret = insert_cache_extent(inode_cache, &node->cache);
397                 BUG_ON(ret);
398         }
399         return rec;
400 }
401
402 static void free_inode_rec(struct inode_record *rec)
403 {
404         struct inode_backref *backref;
405
406         if (--rec->refs > 0)
407                 return;
408
409         while (!list_empty(&rec->backrefs)) {
410                 backref = list_entry(rec->backrefs.next,
411                                      struct inode_backref, list);
412                 list_del(&backref->list);
413                 free(backref);
414         }
415         free(rec);
416 }
417
418 static int can_free_inode_rec(struct inode_record *rec)
419 {
420         if (!rec->errors && rec->checked && rec->found_inode_item &&
421             rec->nlink == rec->found_link && list_empty(&rec->backrefs))
422                 return 1;
423         return 0;
424 }
425
426 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
427                                  struct inode_record *rec)
428 {
429         struct cache_extent *cache;
430         struct inode_backref *tmp, *backref;
431         struct ptr_node *node;
432         unsigned char filetype;
433
434         if (!rec->found_inode_item)
435                 return;
436
437         filetype = imode_to_type(rec->imode);
438         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
439                 if (backref->found_dir_item && backref->found_dir_index) {
440                         if (backref->filetype != filetype)
441                                 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
442                         if (!backref->errors && backref->found_inode_ref) {
443                                 list_del(&backref->list);
444                                 free(backref);
445                         }
446                 }
447         }
448
449         if (!rec->checked || rec->merging)
450                 return;
451
452         if (S_ISDIR(rec->imode)) {
453                 if (rec->found_size != rec->isize)
454                         rec->errors |= I_ERR_DIR_ISIZE_WRONG;
455                 if (rec->found_file_extent)
456                         rec->errors |= I_ERR_ODD_FILE_EXTENT;
457         } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
458                 if (rec->found_dir_item)
459                         rec->errors |= I_ERR_ODD_DIR_ITEM;
460                 if (rec->found_size != rec->nbytes)
461                         rec->errors |= I_ERR_FILE_NBYTES_WRONG;
462                 if (rec->extent_start == (u64)-1 || rec->extent_start > 0)
463                         rec->first_extent_gap = 0;
464                 if (rec->nlink > 0 && !no_holes &&
465                     (rec->extent_end < rec->isize ||
466                      rec->first_extent_gap < rec->isize))
467                         rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
468         }
469
470         if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
471                 if (rec->found_csum_item && rec->nodatasum)
472                         rec->errors |= I_ERR_ODD_CSUM_ITEM;
473                 if (rec->some_csum_missing && !rec->nodatasum)
474                         rec->errors |= I_ERR_SOME_CSUM_MISSING;
475         }
476
477         BUG_ON(rec->refs != 1);
478         if (can_free_inode_rec(rec)) {
479                 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
480                 node = container_of(cache, struct ptr_node, cache);
481                 BUG_ON(node->data != rec);
482                 remove_cache_extent(inode_cache, &node->cache);
483                 free(node);
484                 free_inode_rec(rec);
485         }
486 }
487
488 static int check_orphan_item(struct btrfs_root *root, u64 ino)
489 {
490         struct btrfs_path path;
491         struct btrfs_key key;
492         int ret;
493
494         key.objectid = BTRFS_ORPHAN_OBJECTID;
495         key.type = BTRFS_ORPHAN_ITEM_KEY;
496         key.offset = ino;
497
498         btrfs_init_path(&path);
499         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
500         btrfs_release_path(&path);
501         if (ret > 0)
502                 ret = -ENOENT;
503         return ret;
504 }
505
506 static int process_inode_item(struct extent_buffer *eb,
507                               int slot, struct btrfs_key *key,
508                               struct shared_node *active_node)
509 {
510         struct inode_record *rec;
511         struct btrfs_inode_item *item;
512
513         rec = active_node->current;
514         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
515         if (rec->found_inode_item) {
516                 rec->errors |= I_ERR_DUP_INODE_ITEM;
517                 return 1;
518         }
519         item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
520         rec->nlink = btrfs_inode_nlink(eb, item);
521         rec->isize = btrfs_inode_size(eb, item);
522         rec->nbytes = btrfs_inode_nbytes(eb, item);
523         rec->imode = btrfs_inode_mode(eb, item);
524         if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
525                 rec->nodatasum = 1;
526         rec->found_inode_item = 1;
527         if (rec->nlink == 0)
528                 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
529         maybe_free_inode_rec(&active_node->inode_cache, rec);
530         return 0;
531 }
532
533 static struct inode_backref *get_inode_backref(struct inode_record *rec,
534                                                 const char *name,
535                                                 int namelen, u64 dir)
536 {
537         struct inode_backref *backref;
538
539         list_for_each_entry(backref, &rec->backrefs, list) {
540                 if (backref->dir != dir || backref->namelen != namelen)
541                         continue;
542                 if (memcmp(name, backref->name, namelen))
543                         continue;
544                 return backref;
545         }
546
547         backref = malloc(sizeof(*backref) + namelen + 1);
548         memset(backref, 0, sizeof(*backref));
549         backref->dir = dir;
550         backref->namelen = namelen;
551         memcpy(backref->name, name, namelen);
552         backref->name[namelen] = '\0';
553         list_add_tail(&backref->list, &rec->backrefs);
554         return backref;
555 }
556
557 static int add_inode_backref(struct cache_tree *inode_cache,
558                              u64 ino, u64 dir, u64 index,
559                              const char *name, int namelen,
560                              int filetype, int itemtype, int errors)
561 {
562         struct inode_record *rec;
563         struct inode_backref *backref;
564
565         rec = get_inode_rec(inode_cache, ino, 1);
566         backref = get_inode_backref(rec, name, namelen, dir);
567         if (errors)
568                 backref->errors |= errors;
569         if (itemtype == BTRFS_DIR_INDEX_KEY) {
570                 if (backref->found_dir_index)
571                         backref->errors |= REF_ERR_DUP_DIR_INDEX;
572                 if (backref->found_inode_ref && backref->index != index)
573                         backref->errors |= REF_ERR_INDEX_UNMATCH;
574                 if (backref->found_dir_item && backref->filetype != filetype)
575                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
576
577                 backref->index = index;
578                 backref->filetype = filetype;
579                 backref->found_dir_index = 1;
580         } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
581                 rec->found_link++;
582                 if (backref->found_dir_item)
583                         backref->errors |= REF_ERR_DUP_DIR_ITEM;
584                 if (backref->found_dir_index && backref->filetype != filetype)
585                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
586
587                 backref->filetype = filetype;
588                 backref->found_dir_item = 1;
589         } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
590                    (itemtype == BTRFS_INODE_EXTREF_KEY)) {
591                 if (backref->found_inode_ref)
592                         backref->errors |= REF_ERR_DUP_INODE_REF;
593                 if (backref->found_dir_index && backref->index != index)
594                         backref->errors |= REF_ERR_INDEX_UNMATCH;
595
596                 backref->ref_type = itemtype;
597                 backref->index = index;
598                 backref->found_inode_ref = 1;
599         } else {
600                 BUG_ON(1);
601         }
602
603         maybe_free_inode_rec(inode_cache, rec);
604         return 0;
605 }
606
607 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
608                             struct cache_tree *dst_cache)
609 {
610         struct inode_backref *backref;
611         u32 dir_count = 0;
612
613         dst->merging = 1;
614         list_for_each_entry(backref, &src->backrefs, list) {
615                 if (backref->found_dir_index) {
616                         add_inode_backref(dst_cache, dst->ino, backref->dir,
617                                         backref->index, backref->name,
618                                         backref->namelen, backref->filetype,
619                                         BTRFS_DIR_INDEX_KEY, backref->errors);
620                 }
621                 if (backref->found_dir_item) {
622                         dir_count++;
623                         add_inode_backref(dst_cache, dst->ino,
624                                         backref->dir, 0, backref->name,
625                                         backref->namelen, backref->filetype,
626                                         BTRFS_DIR_ITEM_KEY, backref->errors);
627                 }
628                 if (backref->found_inode_ref) {
629                         add_inode_backref(dst_cache, dst->ino,
630                                         backref->dir, backref->index,
631                                         backref->name, backref->namelen, 0,
632                                         backref->ref_type, backref->errors);
633                 }
634         }
635
636         if (src->found_dir_item)
637                 dst->found_dir_item = 1;
638         if (src->found_file_extent)
639                 dst->found_file_extent = 1;
640         if (src->found_csum_item)
641                 dst->found_csum_item = 1;
642         if (src->some_csum_missing)
643                 dst->some_csum_missing = 1;
644         if (dst->first_extent_gap > src->first_extent_gap)
645                 dst->first_extent_gap = src->first_extent_gap;
646
647         BUG_ON(src->found_link < dir_count);
648         dst->found_link += src->found_link - dir_count;
649         dst->found_size += src->found_size;
650         if (src->extent_start != (u64)-1) {
651                 if (dst->extent_start == (u64)-1) {
652                         dst->extent_start = src->extent_start;
653                         dst->extent_end = src->extent_end;
654                 } else {
655                         if (dst->extent_end > src->extent_start)
656                                 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
657                         else if (dst->extent_end < src->extent_start &&
658                                  dst->extent_end < dst->first_extent_gap)
659                                 dst->first_extent_gap = dst->extent_end;
660                         if (dst->extent_end < src->extent_end)
661                                 dst->extent_end = src->extent_end;
662                 }
663         }
664
665         dst->errors |= src->errors;
666         if (src->found_inode_item) {
667                 if (!dst->found_inode_item) {
668                         dst->nlink = src->nlink;
669                         dst->isize = src->isize;
670                         dst->nbytes = src->nbytes;
671                         dst->imode = src->imode;
672                         dst->nodatasum = src->nodatasum;
673                         dst->found_inode_item = 1;
674                 } else {
675                         dst->errors |= I_ERR_DUP_INODE_ITEM;
676                 }
677         }
678         dst->merging = 0;
679
680         return 0;
681 }
682
683 static int splice_shared_node(struct shared_node *src_node,
684                               struct shared_node *dst_node)
685 {
686         struct cache_extent *cache;
687         struct ptr_node *node, *ins;
688         struct cache_tree *src, *dst;
689         struct inode_record *rec, *conflict;
690         u64 current_ino = 0;
691         int splice = 0;
692         int ret;
693
694         if (--src_node->refs == 0)
695                 splice = 1;
696         if (src_node->current)
697                 current_ino = src_node->current->ino;
698
699         src = &src_node->root_cache;
700         dst = &dst_node->root_cache;
701 again:
702         cache = search_cache_extent(src, 0);
703         while (cache) {
704                 node = container_of(cache, struct ptr_node, cache);
705                 rec = node->data;
706                 cache = next_cache_extent(cache);
707
708                 if (splice) {
709                         remove_cache_extent(src, &node->cache);
710                         ins = node;
711                 } else {
712                         ins = malloc(sizeof(*ins));
713                         ins->cache.start = node->cache.start;
714                         ins->cache.size = node->cache.size;
715                         ins->data = rec;
716                         rec->refs++;
717                 }
718                 ret = insert_cache_extent(dst, &ins->cache);
719                 if (ret == -EEXIST) {
720                         conflict = get_inode_rec(dst, rec->ino, 1);
721                         merge_inode_recs(rec, conflict, dst);
722                         if (rec->checked) {
723                                 conflict->checked = 1;
724                                 if (dst_node->current == conflict)
725                                         dst_node->current = NULL;
726                         }
727                         maybe_free_inode_rec(dst, conflict);
728                         free_inode_rec(rec);
729                         free(ins);
730                 } else {
731                         BUG_ON(ret);
732                 }
733         }
734
735         if (src == &src_node->root_cache) {
736                 src = &src_node->inode_cache;
737                 dst = &dst_node->inode_cache;
738                 goto again;
739         }
740
741         if (current_ino > 0 && (!dst_node->current ||
742             current_ino > dst_node->current->ino)) {
743                 if (dst_node->current) {
744                         dst_node->current->checked = 1;
745                         maybe_free_inode_rec(dst, dst_node->current);
746                 }
747                 dst_node->current = get_inode_rec(dst, current_ino, 1);
748         }
749         return 0;
750 }
751
752 static void free_inode_ptr(struct cache_extent *cache)
753 {
754         struct ptr_node *node;
755         struct inode_record *rec;
756
757         node = container_of(cache, struct ptr_node, cache);
758         rec = node->data;
759         free_inode_rec(rec);
760         free(node);
761 }
762
763 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
764
765 static struct shared_node *find_shared_node(struct cache_tree *shared,
766                                             u64 bytenr)
767 {
768         struct cache_extent *cache;
769         struct shared_node *node;
770
771         cache = lookup_cache_extent(shared, bytenr, 1);
772         if (cache) {
773                 node = container_of(cache, struct shared_node, cache);
774                 return node;
775         }
776         return NULL;
777 }
778
779 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
780 {
781         int ret;
782         struct shared_node *node;
783
784         node = calloc(1, sizeof(*node));
785         node->cache.start = bytenr;
786         node->cache.size = 1;
787         cache_tree_init(&node->root_cache);
788         cache_tree_init(&node->inode_cache);
789         node->refs = refs;
790
791         ret = insert_cache_extent(shared, &node->cache);
792         BUG_ON(ret);
793         return 0;
794 }
795
796 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
797                              struct walk_control *wc, int level)
798 {
799         struct shared_node *node;
800         struct shared_node *dest;
801
802         if (level == wc->active_node)
803                 return 0;
804
805         BUG_ON(wc->active_node <= level);
806         node = find_shared_node(&wc->shared, bytenr);
807         if (!node) {
808                 add_shared_node(&wc->shared, bytenr, refs);
809                 node = find_shared_node(&wc->shared, bytenr);
810                 wc->nodes[level] = node;
811                 wc->active_node = level;
812                 return 0;
813         }
814
815         if (wc->root_level == wc->active_node &&
816             btrfs_root_refs(&root->root_item) == 0) {
817                 if (--node->refs == 0) {
818                         free_inode_recs_tree(&node->root_cache);
819                         free_inode_recs_tree(&node->inode_cache);
820                         remove_cache_extent(&wc->shared, &node->cache);
821                         free(node);
822                 }
823                 return 1;
824         }
825
826         dest = wc->nodes[wc->active_node];
827         splice_shared_node(node, dest);
828         if (node->refs == 0) {
829                 remove_cache_extent(&wc->shared, &node->cache);
830                 free(node);
831         }
832         return 1;
833 }
834
835 static int leave_shared_node(struct btrfs_root *root,
836                              struct walk_control *wc, int level)
837 {
838         struct shared_node *node;
839         struct shared_node *dest;
840         int i;
841
842         if (level == wc->root_level)
843                 return 0;
844
845         for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
846                 if (wc->nodes[i])
847                         break;
848         }
849         BUG_ON(i >= BTRFS_MAX_LEVEL);
850
851         node = wc->nodes[wc->active_node];
852         wc->nodes[wc->active_node] = NULL;
853         wc->active_node = i;
854
855         dest = wc->nodes[wc->active_node];
856         if (wc->active_node < wc->root_level ||
857             btrfs_root_refs(&root->root_item) > 0) {
858                 BUG_ON(node->refs <= 1);
859                 splice_shared_node(node, dest);
860         } else {
861                 BUG_ON(node->refs < 2);
862                 node->refs--;
863         }
864         return 0;
865 }
866
867 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
868                          u64 child_root_id)
869 {
870         struct btrfs_path path;
871         struct btrfs_key key;
872         struct extent_buffer *leaf;
873         int has_parent = 0;
874         int ret;
875
876         btrfs_init_path(&path);
877
878         key.objectid = parent_root_id;
879         key.type = BTRFS_ROOT_REF_KEY;
880         key.offset = child_root_id;
881         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
882                                 0, 0);
883         BUG_ON(ret < 0);
884         btrfs_release_path(&path);
885         if (!ret)
886                 return 1;
887
888         key.objectid = child_root_id;
889         key.type = BTRFS_ROOT_BACKREF_KEY;
890         key.offset = 0;
891         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
892                                 0, 0);
893         BUG_ON(ret <= 0);
894
895         while (1) {
896                 leaf = path.nodes[0];
897                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
898                         ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
899                         BUG_ON(ret < 0);
900
901                         if (ret > 0)
902                                 break;
903                         leaf = path.nodes[0];
904                 }
905
906                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
907                 if (key.objectid != child_root_id ||
908                     key.type != BTRFS_ROOT_BACKREF_KEY)
909                         break;
910
911                 has_parent = 1;
912
913                 if (key.offset == parent_root_id) {
914                         btrfs_release_path(&path);
915                         return 1;
916                 }
917
918                 path.slots[0]++;
919         }
920
921         btrfs_release_path(&path);
922         return has_parent? 0 : -1;
923 }
924
925 static int process_dir_item(struct btrfs_root *root,
926                             struct extent_buffer *eb,
927                             int slot, struct btrfs_key *key,
928                             struct shared_node *active_node)
929 {
930         u32 total;
931         u32 cur = 0;
932         u32 len;
933         u32 name_len;
934         u32 data_len;
935         int error;
936         int nritems = 0;
937         int filetype;
938         struct btrfs_dir_item *di;
939         struct inode_record *rec;
940         struct cache_tree *root_cache;
941         struct cache_tree *inode_cache;
942         struct btrfs_key location;
943         char namebuf[BTRFS_NAME_LEN];
944
945         root_cache = &active_node->root_cache;
946         inode_cache = &active_node->inode_cache;
947         rec = active_node->current;
948         rec->found_dir_item = 1;
949
950         di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
951         total = btrfs_item_size_nr(eb, slot);
952         while (cur < total) {
953                 nritems++;
954                 btrfs_dir_item_key_to_cpu(eb, di, &location);
955                 name_len = btrfs_dir_name_len(eb, di);
956                 data_len = btrfs_dir_data_len(eb, di);
957                 filetype = btrfs_dir_type(eb, di);
958
959                 rec->found_size += name_len;
960                 if (name_len <= BTRFS_NAME_LEN) {
961                         len = name_len;
962                         error = 0;
963                 } else {
964                         len = BTRFS_NAME_LEN;
965                         error = REF_ERR_NAME_TOO_LONG;
966                 }
967                 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
968
969                 if (location.type == BTRFS_INODE_ITEM_KEY) {
970                         add_inode_backref(inode_cache, location.objectid,
971                                           key->objectid, key->offset, namebuf,
972                                           len, filetype, key->type, error);
973                 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
974                         add_inode_backref(root_cache, location.objectid,
975                                           key->objectid, key->offset,
976                                           namebuf, len, filetype,
977                                           key->type, error);
978                 } else {
979                         fprintf(stderr, "warning line %d\n", __LINE__);
980                 }
981
982                 len = sizeof(*di) + name_len + data_len;
983                 di = (struct btrfs_dir_item *)((char *)di + len);
984                 cur += len;
985         }
986         if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
987                 rec->errors |= I_ERR_DUP_DIR_INDEX;
988
989         return 0;
990 }
991
992 static int process_inode_ref(struct extent_buffer *eb,
993                              int slot, struct btrfs_key *key,
994                              struct shared_node *active_node)
995 {
996         u32 total;
997         u32 cur = 0;
998         u32 len;
999         u32 name_len;
1000         u64 index;
1001         int error;
1002         struct cache_tree *inode_cache;
1003         struct btrfs_inode_ref *ref;
1004         char namebuf[BTRFS_NAME_LEN];
1005
1006         inode_cache = &active_node->inode_cache;
1007
1008         ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
1009         total = btrfs_item_size_nr(eb, slot);
1010         while (cur < total) {
1011                 name_len = btrfs_inode_ref_name_len(eb, ref);
1012                 index = btrfs_inode_ref_index(eb, ref);
1013                 if (name_len <= BTRFS_NAME_LEN) {
1014                         len = name_len;
1015                         error = 0;
1016                 } else {
1017                         len = BTRFS_NAME_LEN;
1018                         error = REF_ERR_NAME_TOO_LONG;
1019                 }
1020                 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1021                 add_inode_backref(inode_cache, key->objectid, key->offset,
1022                                   index, namebuf, len, 0, key->type, error);
1023
1024                 len = sizeof(*ref) + name_len;
1025                 ref = (struct btrfs_inode_ref *)((char *)ref + len);
1026                 cur += len;
1027         }
1028         return 0;
1029 }
1030
1031 static int process_inode_extref(struct extent_buffer *eb,
1032                                 int slot, struct btrfs_key *key,
1033                                 struct shared_node *active_node)
1034 {
1035         u32 total;
1036         u32 cur = 0;
1037         u32 len;
1038         u32 name_len;
1039         u64 index;
1040         u64 parent;
1041         int error;
1042         struct cache_tree *inode_cache;
1043         struct btrfs_inode_extref *extref;
1044         char namebuf[BTRFS_NAME_LEN];
1045
1046         inode_cache = &active_node->inode_cache;
1047
1048         extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
1049         total = btrfs_item_size_nr(eb, slot);
1050         while (cur < total) {
1051                 name_len = btrfs_inode_extref_name_len(eb, extref);
1052                 index = btrfs_inode_extref_index(eb, extref);
1053                 parent = btrfs_inode_extref_parent(eb, extref);
1054                 if (name_len <= BTRFS_NAME_LEN) {
1055                         len = name_len;
1056                         error = 0;
1057                 } else {
1058                         len = BTRFS_NAME_LEN;
1059                         error = REF_ERR_NAME_TOO_LONG;
1060                 }
1061                 read_extent_buffer(eb, namebuf,
1062                                    (unsigned long)(extref + 1), len);
1063                 add_inode_backref(inode_cache, key->objectid, parent,
1064                                   index, namebuf, len, 0, key->type, error);
1065
1066                 len = sizeof(*extref) + name_len;
1067                 extref = (struct btrfs_inode_extref *)((char *)extref + len);
1068                 cur += len;
1069         }
1070         return 0;
1071
1072 }
1073
1074 static u64 count_csum_range(struct btrfs_root *root, u64 start, u64 len)
1075 {
1076         struct btrfs_key key;
1077         struct btrfs_path path;
1078         struct extent_buffer *leaf;
1079         int ret ;
1080         size_t size;
1081         u64 found = 0;
1082         u64 csum_end;
1083         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1084
1085         btrfs_init_path(&path);
1086
1087         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1088         key.offset = start;
1089         key.type = BTRFS_EXTENT_CSUM_KEY;
1090
1091         ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1092                                 &key, &path, 0, 0);
1093         BUG_ON(ret < 0);
1094         if (ret > 0 && path.slots[0] > 0) {
1095                 leaf = path.nodes[0];
1096                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1097                 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1098                     key.type == BTRFS_EXTENT_CSUM_KEY)
1099                         path.slots[0]--;
1100         }
1101
1102         while (len > 0) {
1103                 leaf = path.nodes[0];
1104                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1105                         ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1106                         BUG_ON(ret < 0);
1107                         if (ret > 0)
1108                                 break;
1109                         leaf = path.nodes[0];
1110                 }
1111
1112                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1113                 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1114                     key.type != BTRFS_EXTENT_CSUM_KEY)
1115                         break;
1116
1117                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1118                 if (key.offset >= start + len)
1119                         break;
1120
1121                 if (key.offset > start)
1122                         start = key.offset;
1123
1124                 size = btrfs_item_size_nr(leaf, path.slots[0]);
1125                 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1126                 if (csum_end > start) {
1127                         size = min(csum_end - start, len);
1128                         len -= size;
1129                         start += size;
1130                         found += size;
1131                 }
1132
1133                 path.slots[0]++;
1134         }
1135         btrfs_release_path(&path);
1136         return found;
1137 }
1138
1139 static int process_file_extent(struct btrfs_root *root,
1140                                 struct extent_buffer *eb,
1141                                 int slot, struct btrfs_key *key,
1142                                 struct shared_node *active_node)
1143 {
1144         struct inode_record *rec;
1145         struct btrfs_file_extent_item *fi;
1146         u64 num_bytes = 0;
1147         u64 disk_bytenr = 0;
1148         u64 extent_offset = 0;
1149         u64 mask = root->sectorsize - 1;
1150         int extent_type;
1151
1152         rec = active_node->current;
1153         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1154         rec->found_file_extent = 1;
1155
1156         if (rec->extent_start == (u64)-1) {
1157                 rec->extent_start = key->offset;
1158                 rec->extent_end = key->offset;
1159         }
1160
1161         if (rec->extent_end > key->offset)
1162                 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1163         else if (rec->extent_end < key->offset &&
1164                  rec->extent_end < rec->first_extent_gap)
1165                 rec->first_extent_gap = rec->extent_end;
1166
1167         fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1168         extent_type = btrfs_file_extent_type(eb, fi);
1169
1170         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1171                 num_bytes = btrfs_file_extent_inline_len(eb, slot, fi);
1172                 if (num_bytes == 0)
1173                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1174                 rec->found_size += num_bytes;
1175                 num_bytes = (num_bytes + mask) & ~mask;
1176         } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1177                    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1178                 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1179                 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1180                 extent_offset = btrfs_file_extent_offset(eb, fi);
1181                 if (num_bytes == 0 || (num_bytes & mask))
1182                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1183                 if (num_bytes + extent_offset >
1184                     btrfs_file_extent_ram_bytes(eb, fi))
1185                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1186                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1187                     (btrfs_file_extent_compression(eb, fi) ||
1188                      btrfs_file_extent_encryption(eb, fi) ||
1189                      btrfs_file_extent_other_encoding(eb, fi)))
1190                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1191                 if (disk_bytenr > 0)
1192                         rec->found_size += num_bytes;
1193         } else {
1194                 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1195         }
1196         rec->extent_end = key->offset + num_bytes;
1197
1198         if (disk_bytenr > 0) {
1199                 u64 found;
1200                 if (btrfs_file_extent_compression(eb, fi))
1201                         num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1202                 else
1203                         disk_bytenr += extent_offset;
1204
1205                 found = count_csum_range(root, disk_bytenr, num_bytes);
1206                 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1207                         if (found > 0)
1208                                 rec->found_csum_item = 1;
1209                         if (found < num_bytes)
1210                                 rec->some_csum_missing = 1;
1211                 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1212                         if (found > 0)
1213                                 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1214                 }
1215         }
1216         return 0;
1217 }
1218
1219 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1220                             struct walk_control *wc)
1221 {
1222         struct btrfs_key key;
1223         u32 nritems;
1224         int i;
1225         int ret = 0;
1226         int error = 0;
1227         struct cache_tree *inode_cache;
1228         struct shared_node *active_node;
1229
1230         if (wc->root_level == wc->active_node &&
1231             btrfs_root_refs(&root->root_item) == 0)
1232                 return 0;
1233
1234         active_node = wc->nodes[wc->active_node];
1235         inode_cache = &active_node->inode_cache;
1236         nritems = btrfs_header_nritems(eb);
1237         for (i = 0; i < nritems; i++) {
1238                 btrfs_item_key_to_cpu(eb, &key, i);
1239
1240                 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1241                         continue;
1242                 if (key.type == BTRFS_ORPHAN_ITEM_KEY)
1243                         continue;
1244
1245                 if (active_node->current == NULL ||
1246                     active_node->current->ino < key.objectid) {
1247                         if (active_node->current) {
1248                                 active_node->current->checked = 1;
1249                                 maybe_free_inode_rec(inode_cache,
1250                                                      active_node->current);
1251                         }
1252                         active_node->current = get_inode_rec(inode_cache,
1253                                                              key.objectid, 1);
1254                 }
1255                 switch (key.type) {
1256                 case BTRFS_DIR_ITEM_KEY:
1257                 case BTRFS_DIR_INDEX_KEY:
1258                         ret = process_dir_item(root, eb, i, &key, active_node);
1259                         break;
1260                 case BTRFS_INODE_REF_KEY:
1261                         ret = process_inode_ref(eb, i, &key, active_node);
1262                         break;
1263                 case BTRFS_INODE_EXTREF_KEY:
1264                         ret = process_inode_extref(eb, i, &key, active_node);
1265                         break;
1266                 case BTRFS_INODE_ITEM_KEY:
1267                         ret = process_inode_item(eb, i, &key, active_node);
1268                         break;
1269                 case BTRFS_EXTENT_DATA_KEY:
1270                         ret = process_file_extent(root, eb, i, &key,
1271                                                   active_node);
1272                         break;
1273                 default:
1274                         break;
1275                 };
1276                 if (ret != 0)
1277                         error = 1;
1278         }
1279         return error;
1280 }
1281
1282 static void reada_walk_down(struct btrfs_root *root,
1283                             struct extent_buffer *node, int slot)
1284 {
1285         u64 bytenr;
1286         u64 ptr_gen;
1287         u32 nritems;
1288         u32 blocksize;
1289         int i;
1290         int ret;
1291         int level;
1292
1293         level = btrfs_header_level(node);
1294         if (level != 1)
1295                 return;
1296
1297         nritems = btrfs_header_nritems(node);
1298         blocksize = btrfs_level_size(root, level - 1);
1299         for (i = slot; i < nritems; i++) {
1300                 bytenr = btrfs_node_blockptr(node, i);
1301                 ptr_gen = btrfs_node_ptr_generation(node, i);
1302                 ret = readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1303                 if (ret)
1304                         break;
1305         }
1306 }
1307
1308 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1309                           struct walk_control *wc, int *level)
1310 {
1311         u64 bytenr;
1312         u64 ptr_gen;
1313         struct extent_buffer *next;
1314         struct extent_buffer *cur;
1315         u32 blocksize;
1316         int ret, err = 0;
1317         u64 refs;
1318
1319         WARN_ON(*level < 0);
1320         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1321         ret = btrfs_lookup_extent_info(NULL, root,
1322                                        path->nodes[*level]->start,
1323                                        *level, 1, &refs, NULL);
1324         if (ret < 0) {
1325                 err = ret;
1326                 goto out;
1327         }
1328
1329         if (refs > 1) {
1330                 ret = enter_shared_node(root, path->nodes[*level]->start,
1331                                         refs, wc, *level);
1332                 if (ret > 0) {
1333                         err = ret;
1334                         goto out;
1335                 }
1336         }
1337
1338         while (*level >= 0) {
1339                 WARN_ON(*level < 0);
1340                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1341                 cur = path->nodes[*level];
1342
1343                 if (btrfs_header_level(cur) != *level)
1344                         WARN_ON(1);
1345
1346                 if (path->slots[*level] >= btrfs_header_nritems(cur))
1347                         break;
1348                 if (*level == 0) {
1349                         ret = process_one_leaf(root, cur, wc);
1350                         break;
1351                 }
1352                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1353                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1354                 blocksize = btrfs_level_size(root, *level - 1);
1355                 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1356                                                1, &refs, NULL);
1357                 if (ret < 0)
1358                         refs = 0;
1359
1360                 if (refs > 1) {
1361                         ret = enter_shared_node(root, bytenr, refs,
1362                                                 wc, *level - 1);
1363                         if (ret > 0) {
1364                                 path->slots[*level]++;
1365                                 continue;
1366                         }
1367                 }
1368
1369                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1370                 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1371                         free_extent_buffer(next);
1372                         reada_walk_down(root, cur, path->slots[*level]);
1373                         next = read_tree_block(root, bytenr, blocksize,
1374                                                ptr_gen);
1375                         if (!next) {
1376                                 err = -EIO;
1377                                 goto out;
1378                         }
1379                 }
1380
1381                 *level = *level - 1;
1382                 free_extent_buffer(path->nodes[*level]);
1383                 path->nodes[*level] = next;
1384                 path->slots[*level] = 0;
1385         }
1386 out:
1387         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1388         return err;
1389 }
1390
1391 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1392                         struct walk_control *wc, int *level)
1393 {
1394         int i;
1395         struct extent_buffer *leaf;
1396
1397         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1398                 leaf = path->nodes[i];
1399                 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1400                         path->slots[i]++;
1401                         *level = i;
1402                         return 0;
1403                 } else {
1404                         free_extent_buffer(path->nodes[*level]);
1405                         path->nodes[*level] = NULL;
1406                         BUG_ON(*level > wc->active_node);
1407                         if (*level == wc->active_node)
1408                                 leave_shared_node(root, wc, *level);
1409                         *level = i + 1;
1410                 }
1411         }
1412         return 1;
1413 }
1414
1415 static int check_root_dir(struct inode_record *rec)
1416 {
1417         struct inode_backref *backref;
1418         int ret = -1;
1419
1420         if (!rec->found_inode_item || rec->errors)
1421                 goto out;
1422         if (rec->nlink != 1 || rec->found_link != 0)
1423                 goto out;
1424         if (list_empty(&rec->backrefs))
1425                 goto out;
1426         backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1427         if (!backref->found_inode_ref)
1428                 goto out;
1429         if (backref->index != 0 || backref->namelen != 2 ||
1430             memcmp(backref->name, "..", 2))
1431                 goto out;
1432         if (backref->found_dir_index || backref->found_dir_item)
1433                 goto out;
1434         ret = 0;
1435 out:
1436         return ret;
1437 }
1438
1439 static int repair_inode_isize(struct btrfs_trans_handle *trans,
1440                               struct btrfs_root *root, struct btrfs_path *path,
1441                               struct inode_record *rec)
1442 {
1443         struct btrfs_inode_item *ei;
1444         struct btrfs_key key;
1445         int ret;
1446
1447         key.objectid = rec->ino;
1448         key.type = BTRFS_INODE_ITEM_KEY;
1449         key.offset = (u64)-1;
1450
1451         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1452         if (ret < 0)
1453                 goto out;
1454         if (ret) {
1455                 if (!path->slots[0]) {
1456                         ret = -ENOENT;
1457                         goto out;
1458                 }
1459                 path->slots[0]--;
1460                 ret = 0;
1461         }
1462         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1463         if (key.objectid != rec->ino) {
1464                 ret = -ENOENT;
1465                 goto out;
1466         }
1467
1468         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1469                             struct btrfs_inode_item);
1470         btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1471         btrfs_mark_buffer_dirty(path->nodes[0]);
1472         rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1473         printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1474                root->root_key.objectid);
1475 out:
1476         btrfs_release_path(path);
1477         return ret;
1478 }
1479
1480 static int repair_inode_orphan_item(struct btrfs_trans_handle *trans,
1481                                     struct btrfs_root *root,
1482                                     struct btrfs_path *path,
1483                                     struct inode_record *rec)
1484 {
1485         struct btrfs_key key;
1486         int ret;
1487
1488         key.objectid = BTRFS_ORPHAN_OBJECTID;
1489         key.type = BTRFS_ORPHAN_ITEM_KEY;
1490         key.offset = rec->ino;
1491
1492         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1493         btrfs_release_path(path);
1494         if (!ret)
1495                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1496         return ret;
1497 }
1498
1499 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
1500 {
1501         struct btrfs_trans_handle *trans;
1502         struct btrfs_path *path;
1503         int ret = 0;
1504
1505         /* So far we just fix dir isize wrong */
1506         if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG | I_ERR_NO_ORPHAN_ITEM)))
1507                 return 1;
1508
1509         path = btrfs_alloc_path();
1510         if (!path)
1511                 return -ENOMEM;
1512
1513         trans = btrfs_start_transaction(root, 1);
1514         if (IS_ERR(trans)) {
1515                 btrfs_free_path(path);
1516                 return PTR_ERR(trans);
1517         }
1518
1519         if (rec->errors & I_ERR_DIR_ISIZE_WRONG)
1520                 ret = repair_inode_isize(trans, root, path, rec);
1521         if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
1522                 ret = repair_inode_orphan_item(trans, root, path, rec);
1523         btrfs_commit_transaction(trans, root);
1524         btrfs_free_path(path);
1525         return ret;
1526 }
1527
1528 static int check_inode_recs(struct btrfs_root *root,
1529                             struct cache_tree *inode_cache)
1530 {
1531         struct cache_extent *cache;
1532         struct ptr_node *node;
1533         struct inode_record *rec;
1534         struct inode_backref *backref;
1535         int ret;
1536         u64 error = 0;
1537         u64 root_dirid = btrfs_root_dirid(&root->root_item);
1538
1539         if (btrfs_root_refs(&root->root_item) == 0) {
1540                 if (!cache_tree_empty(inode_cache))
1541                         fprintf(stderr, "warning line %d\n", __LINE__);
1542                 return 0;
1543         }
1544
1545         rec = get_inode_rec(inode_cache, root_dirid, 0);
1546         if (rec) {
1547                 ret = check_root_dir(rec);
1548                 if (ret) {
1549                         fprintf(stderr, "root %llu root dir %llu error\n",
1550                                 (unsigned long long)root->root_key.objectid,
1551                                 (unsigned long long)root_dirid);
1552                         error++;
1553                 }
1554         } else {
1555                 fprintf(stderr, "root %llu root dir %llu not found\n",
1556                         (unsigned long long)root->root_key.objectid,
1557                         (unsigned long long)root_dirid);
1558         }
1559
1560         while (1) {
1561                 cache = search_cache_extent(inode_cache, 0);
1562                 if (!cache)
1563                         break;
1564                 node = container_of(cache, struct ptr_node, cache);
1565                 rec = node->data;
1566                 remove_cache_extent(inode_cache, &node->cache);
1567                 free(node);
1568                 if (rec->ino == root_dirid ||
1569                     rec->ino == BTRFS_ORPHAN_OBJECTID) {
1570                         free_inode_rec(rec);
1571                         continue;
1572                 }
1573
1574                 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
1575                         ret = check_orphan_item(root, rec->ino);
1576                         if (ret == 0)
1577                                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1578                         if (can_free_inode_rec(rec)) {
1579                                 free_inode_rec(rec);
1580                                 continue;
1581                         }
1582                 }
1583
1584                 if (repair) {
1585                         ret = try_repair_inode(root, rec);
1586                         if (ret == 0 && can_free_inode_rec(rec)) {
1587                                 free_inode_rec(rec);
1588                                 continue;
1589                         }
1590                         ret = 0;
1591                 }
1592
1593                 error++;
1594                 if (!rec->found_inode_item)
1595                         rec->errors |= I_ERR_NO_INODE_ITEM;
1596                 if (rec->found_link != rec->nlink)
1597                         rec->errors |= I_ERR_LINK_COUNT_WRONG;
1598                 fprintf(stderr, "root %llu inode %llu errors %x",
1599                         (unsigned long long) root->root_key.objectid,
1600                         (unsigned long long) rec->ino, rec->errors);
1601                 print_inode_error(rec->errors);
1602                 list_for_each_entry(backref, &rec->backrefs, list) {
1603                         if (!backref->found_dir_item)
1604                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1605                         if (!backref->found_dir_index)
1606                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1607                         if (!backref->found_inode_ref)
1608                                 backref->errors |= REF_ERR_NO_INODE_REF;
1609                         fprintf(stderr, "\tunresolved ref dir %llu index %llu"
1610                                 " namelen %u name %s filetype %d errors %x",
1611                                 (unsigned long long)backref->dir,
1612                                 (unsigned long long)backref->index,
1613                                 backref->namelen, backref->name,
1614                                 backref->filetype, backref->errors);
1615                         print_ref_error(backref->errors);
1616                 }
1617                 free_inode_rec(rec);
1618         }
1619         return (error > 0) ? -1 : 0;
1620 }
1621
1622 static struct root_record *get_root_rec(struct cache_tree *root_cache,
1623                                         u64 objectid)
1624 {
1625         struct cache_extent *cache;
1626         struct root_record *rec = NULL;
1627         int ret;
1628
1629         cache = lookup_cache_extent(root_cache, objectid, 1);
1630         if (cache) {
1631                 rec = container_of(cache, struct root_record, cache);
1632         } else {
1633                 rec = calloc(1, sizeof(*rec));
1634                 rec->objectid = objectid;
1635                 INIT_LIST_HEAD(&rec->backrefs);
1636                 rec->cache.start = objectid;
1637                 rec->cache.size = 1;
1638
1639                 ret = insert_cache_extent(root_cache, &rec->cache);
1640                 BUG_ON(ret);
1641         }
1642         return rec;
1643 }
1644
1645 static struct root_backref *get_root_backref(struct root_record *rec,
1646                                              u64 ref_root, u64 dir, u64 index,
1647                                              const char *name, int namelen)
1648 {
1649         struct root_backref *backref;
1650
1651         list_for_each_entry(backref, &rec->backrefs, list) {
1652                 if (backref->ref_root != ref_root || backref->dir != dir ||
1653                     backref->namelen != namelen)
1654                         continue;
1655                 if (memcmp(name, backref->name, namelen))
1656                         continue;
1657                 return backref;
1658         }
1659
1660         backref = malloc(sizeof(*backref) + namelen + 1);
1661         memset(backref, 0, sizeof(*backref));
1662         backref->ref_root = ref_root;
1663         backref->dir = dir;
1664         backref->index = index;
1665         backref->namelen = namelen;
1666         memcpy(backref->name, name, namelen);
1667         backref->name[namelen] = '\0';
1668         list_add_tail(&backref->list, &rec->backrefs);
1669         return backref;
1670 }
1671
1672 static void free_root_record(struct cache_extent *cache)
1673 {
1674         struct root_record *rec;
1675         struct root_backref *backref;
1676
1677         rec = container_of(cache, struct root_record, cache);
1678         while (!list_empty(&rec->backrefs)) {
1679                 backref = list_entry(rec->backrefs.next,
1680                                      struct root_backref, list);
1681                 list_del(&backref->list);
1682                 free(backref);
1683         }
1684
1685         kfree(rec);
1686 }
1687
1688 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
1689
1690 static int add_root_backref(struct cache_tree *root_cache,
1691                             u64 root_id, u64 ref_root, u64 dir, u64 index,
1692                             const char *name, int namelen,
1693                             int item_type, int errors)
1694 {
1695         struct root_record *rec;
1696         struct root_backref *backref;
1697
1698         rec = get_root_rec(root_cache, root_id);
1699         backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
1700
1701         backref->errors |= errors;
1702
1703         if (item_type != BTRFS_DIR_ITEM_KEY) {
1704                 if (backref->found_dir_index || backref->found_back_ref ||
1705                     backref->found_forward_ref) {
1706                         if (backref->index != index)
1707                                 backref->errors |= REF_ERR_INDEX_UNMATCH;
1708                 } else {
1709                         backref->index = index;
1710                 }
1711         }
1712
1713         if (item_type == BTRFS_DIR_ITEM_KEY) {
1714                 if (backref->found_forward_ref)
1715                         rec->found_ref++;
1716                 backref->found_dir_item = 1;
1717         } else if (item_type == BTRFS_DIR_INDEX_KEY) {
1718                 backref->found_dir_index = 1;
1719         } else if (item_type == BTRFS_ROOT_REF_KEY) {
1720                 if (backref->found_forward_ref)
1721                         backref->errors |= REF_ERR_DUP_ROOT_REF;
1722                 else if (backref->found_dir_item)
1723                         rec->found_ref++;
1724                 backref->found_forward_ref = 1;
1725         } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
1726                 if (backref->found_back_ref)
1727                         backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
1728                 backref->found_back_ref = 1;
1729         } else {
1730                 BUG_ON(1);
1731         }
1732
1733         if (backref->found_forward_ref && backref->found_dir_item)
1734                 backref->reachable = 1;
1735         return 0;
1736 }
1737
1738 static int merge_root_recs(struct btrfs_root *root,
1739                            struct cache_tree *src_cache,
1740                            struct cache_tree *dst_cache)
1741 {
1742         struct cache_extent *cache;
1743         struct ptr_node *node;
1744         struct inode_record *rec;
1745         struct inode_backref *backref;
1746
1747         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
1748                 free_inode_recs_tree(src_cache);
1749                 return 0;
1750         }
1751
1752         while (1) {
1753                 cache = search_cache_extent(src_cache, 0);
1754                 if (!cache)
1755                         break;
1756                 node = container_of(cache, struct ptr_node, cache);
1757                 rec = node->data;
1758                 remove_cache_extent(src_cache, &node->cache);
1759                 free(node);
1760
1761                 if (!is_child_root(root, root->objectid, rec->ino))
1762                         goto skip;
1763
1764                 list_for_each_entry(backref, &rec->backrefs, list) {
1765                         BUG_ON(backref->found_inode_ref);
1766                         if (backref->found_dir_item)
1767                                 add_root_backref(dst_cache, rec->ino,
1768                                         root->root_key.objectid, backref->dir,
1769                                         backref->index, backref->name,
1770                                         backref->namelen, BTRFS_DIR_ITEM_KEY,
1771                                         backref->errors);
1772                         if (backref->found_dir_index)
1773                                 add_root_backref(dst_cache, rec->ino,
1774                                         root->root_key.objectid, backref->dir,
1775                                         backref->index, backref->name,
1776                                         backref->namelen, BTRFS_DIR_INDEX_KEY,
1777                                         backref->errors);
1778                 }
1779 skip:
1780                 free_inode_rec(rec);
1781         }
1782         return 0;
1783 }
1784
1785 static int check_root_refs(struct btrfs_root *root,
1786                            struct cache_tree *root_cache)
1787 {
1788         struct root_record *rec;
1789         struct root_record *ref_root;
1790         struct root_backref *backref;
1791         struct cache_extent *cache;
1792         int loop = 1;
1793         int ret;
1794         int error;
1795         int errors = 0;
1796
1797         rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
1798         rec->found_ref = 1;
1799
1800         /* fixme: this can not detect circular references */
1801         while (loop) {
1802                 loop = 0;
1803                 cache = search_cache_extent(root_cache, 0);
1804                 while (1) {
1805                         if (!cache)
1806                                 break;
1807                         rec = container_of(cache, struct root_record, cache);
1808                         cache = next_cache_extent(cache);
1809
1810                         if (rec->found_ref == 0)
1811                                 continue;
1812
1813                         list_for_each_entry(backref, &rec->backrefs, list) {
1814                                 if (!backref->reachable)
1815                                         continue;
1816
1817                                 ref_root = get_root_rec(root_cache,
1818                                                         backref->ref_root);
1819                                 if (ref_root->found_ref > 0)
1820                                         continue;
1821
1822                                 backref->reachable = 0;
1823                                 rec->found_ref--;
1824                                 if (rec->found_ref == 0)
1825                                         loop = 1;
1826                         }
1827                 }
1828         }
1829
1830         cache = search_cache_extent(root_cache, 0);
1831         while (1) {
1832                 if (!cache)
1833                         break;
1834                 rec = container_of(cache, struct root_record, cache);
1835                 cache = next_cache_extent(cache);
1836
1837                 if (rec->found_ref == 0 &&
1838                     rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1839                     rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
1840                         ret = check_orphan_item(root->fs_info->tree_root,
1841                                                 rec->objectid);
1842                         if (ret == 0)
1843                                 continue;
1844
1845                         /*
1846                          * If we don't have a root item then we likely just have
1847                          * a dir item in a snapshot for this root but no actual
1848                          * ref key or anything so it's meaningless.
1849                          */
1850                         if (!rec->found_root_item)
1851                                 continue;
1852                         errors++;
1853                         fprintf(stderr, "fs tree %llu not referenced\n",
1854                                 (unsigned long long)rec->objectid);
1855                 }
1856
1857                 error = 0;
1858                 if (rec->found_ref > 0 && !rec->found_root_item)
1859                         error = 1;
1860                 list_for_each_entry(backref, &rec->backrefs, list) {
1861                         if (!backref->found_dir_item)
1862                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1863                         if (!backref->found_dir_index)
1864                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1865                         if (!backref->found_back_ref)
1866                                 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
1867                         if (!backref->found_forward_ref)
1868                                 backref->errors |= REF_ERR_NO_ROOT_REF;
1869                         if (backref->reachable && backref->errors)
1870                                 error = 1;
1871                 }
1872                 if (!error)
1873                         continue;
1874
1875                 errors++;
1876                 fprintf(stderr, "fs tree %llu refs %u %s\n",
1877                         (unsigned long long)rec->objectid, rec->found_ref,
1878                          rec->found_root_item ? "" : "not found");
1879
1880                 list_for_each_entry(backref, &rec->backrefs, list) {
1881                         if (!backref->reachable)
1882                                 continue;
1883                         if (!backref->errors && rec->found_root_item)
1884                                 continue;
1885                         fprintf(stderr, "\tunresolved ref root %llu dir %llu"
1886                                 " index %llu namelen %u name %s errors %x\n",
1887                                 (unsigned long long)backref->ref_root,
1888                                 (unsigned long long)backref->dir,
1889                                 (unsigned long long)backref->index,
1890                                 backref->namelen, backref->name,
1891                                 backref->errors);
1892                         print_ref_error(backref->errors);
1893                 }
1894         }
1895         return errors > 0 ? 1 : 0;
1896 }
1897
1898 static int process_root_ref(struct extent_buffer *eb, int slot,
1899                             struct btrfs_key *key,
1900                             struct cache_tree *root_cache)
1901 {
1902         u64 dirid;
1903         u64 index;
1904         u32 len;
1905         u32 name_len;
1906         struct btrfs_root_ref *ref;
1907         char namebuf[BTRFS_NAME_LEN];
1908         int error;
1909
1910         ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
1911
1912         dirid = btrfs_root_ref_dirid(eb, ref);
1913         index = btrfs_root_ref_sequence(eb, ref);
1914         name_len = btrfs_root_ref_name_len(eb, ref);
1915
1916         if (name_len <= BTRFS_NAME_LEN) {
1917                 len = name_len;
1918                 error = 0;
1919         } else {
1920                 len = BTRFS_NAME_LEN;
1921                 error = REF_ERR_NAME_TOO_LONG;
1922         }
1923         read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1924
1925         if (key->type == BTRFS_ROOT_REF_KEY) {
1926                 add_root_backref(root_cache, key->offset, key->objectid, dirid,
1927                                  index, namebuf, len, key->type, error);
1928         } else {
1929                 add_root_backref(root_cache, key->objectid, key->offset, dirid,
1930                                  index, namebuf, len, key->type, error);
1931         }
1932         return 0;
1933 }
1934
1935 static int check_fs_root(struct btrfs_root *root,
1936                          struct cache_tree *root_cache,
1937                          struct walk_control *wc)
1938 {
1939         int ret = 0;
1940         int wret;
1941         int level;
1942         struct btrfs_path path;
1943         struct shared_node root_node;
1944         struct root_record *rec;
1945         struct btrfs_root_item *root_item = &root->root_item;
1946
1947         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1948                 rec = get_root_rec(root_cache, root->root_key.objectid);
1949                 if (btrfs_root_refs(root_item) > 0)
1950                         rec->found_root_item = 1;
1951         }
1952
1953         btrfs_init_path(&path);
1954         memset(&root_node, 0, sizeof(root_node));
1955         cache_tree_init(&root_node.root_cache);
1956         cache_tree_init(&root_node.inode_cache);
1957
1958         level = btrfs_header_level(root->node);
1959         memset(wc->nodes, 0, sizeof(wc->nodes));
1960         wc->nodes[level] = &root_node;
1961         wc->active_node = level;
1962         wc->root_level = level;
1963
1964         if (btrfs_root_refs(root_item) > 0 ||
1965             btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1966                 path.nodes[level] = root->node;
1967                 extent_buffer_get(root->node);
1968                 path.slots[level] = 0;
1969         } else {
1970                 struct btrfs_key key;
1971                 struct btrfs_disk_key found_key;
1972
1973                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1974                 level = root_item->drop_level;
1975                 path.lowest_level = level;
1976                 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1977                 BUG_ON(wret < 0);
1978                 btrfs_node_key(path.nodes[level], &found_key,
1979                                 path.slots[level]);
1980                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
1981                                         sizeof(found_key)));
1982         }
1983
1984         while (1) {
1985                 wret = walk_down_tree(root, &path, wc, &level);
1986                 if (wret < 0)
1987                         ret = wret;
1988                 if (wret != 0)
1989                         break;
1990
1991                 wret = walk_up_tree(root, &path, wc, &level);
1992                 if (wret < 0)
1993                         ret = wret;
1994                 if (wret != 0)
1995                         break;
1996         }
1997         btrfs_release_path(&path);
1998
1999         merge_root_recs(root, &root_node.root_cache, root_cache);
2000
2001         if (root_node.current) {
2002                 root_node.current->checked = 1;
2003                 maybe_free_inode_rec(&root_node.inode_cache,
2004                                 root_node.current);
2005         }
2006
2007         ret = check_inode_recs(root, &root_node.inode_cache);
2008         return ret;
2009 }
2010
2011 static int fs_root_objectid(u64 objectid)
2012 {
2013         if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
2014             objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2015                 return 1;
2016         return is_fstree(objectid);
2017 }
2018
2019 static int check_fs_roots(struct btrfs_root *root,
2020                           struct cache_tree *root_cache)
2021 {
2022         struct btrfs_path path;
2023         struct btrfs_key key;
2024         struct walk_control wc;
2025         struct extent_buffer *leaf;
2026         struct btrfs_root *tmp_root;
2027         struct btrfs_root *tree_root = root->fs_info->tree_root;
2028         int ret;
2029         int err = 0;
2030
2031         /*
2032          * Just in case we made any changes to the extent tree that weren't
2033          * reflected into the free space cache yet.
2034          */
2035         if (repair)
2036                 reset_cached_block_groups(root->fs_info);
2037         memset(&wc, 0, sizeof(wc));
2038         cache_tree_init(&wc.shared);
2039         btrfs_init_path(&path);
2040
2041         key.offset = 0;
2042         key.objectid = 0;
2043         key.type = BTRFS_ROOT_ITEM_KEY;
2044         ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
2045         BUG_ON(ret < 0);
2046         while (1) {
2047                 leaf = path.nodes[0];
2048                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2049                         ret = btrfs_next_leaf(tree_root, &path);
2050                         if (ret != 0)
2051                                 break;
2052                         leaf = path.nodes[0];
2053                 }
2054                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2055                 if (key.type == BTRFS_ROOT_ITEM_KEY &&
2056                     fs_root_objectid(key.objectid)) {
2057                         key.offset = (u64)-1;
2058                         tmp_root = btrfs_read_fs_root(root->fs_info, &key);
2059                         if (IS_ERR(tmp_root)) {
2060                                 err = 1;
2061                                 goto next;
2062                         }
2063                         ret = check_fs_root(tmp_root, root_cache, &wc);
2064                         if (ret)
2065                                 err = 1;
2066                 } else if (key.type == BTRFS_ROOT_REF_KEY ||
2067                            key.type == BTRFS_ROOT_BACKREF_KEY) {
2068                         process_root_ref(leaf, path.slots[0], &key,
2069                                          root_cache);
2070                 }
2071 next:
2072                 path.slots[0]++;
2073         }
2074         btrfs_release_path(&path);
2075
2076         if (!cache_tree_empty(&wc.shared))
2077                 fprintf(stderr, "warning line %d\n", __LINE__);
2078
2079         return err;
2080 }
2081
2082 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
2083 {
2084         struct list_head *cur = rec->backrefs.next;
2085         struct extent_backref *back;
2086         struct tree_backref *tback;
2087         struct data_backref *dback;
2088         u64 found = 0;
2089         int err = 0;
2090
2091         while(cur != &rec->backrefs) {
2092                 back = list_entry(cur, struct extent_backref, list);
2093                 cur = cur->next;
2094                 if (!back->found_extent_tree) {
2095                         err = 1;
2096                         if (!print_errs)
2097                                 goto out;
2098                         if (back->is_data) {
2099                                 dback = (struct data_backref *)back;
2100                                 fprintf(stderr, "Backref %llu %s %llu"
2101                                         " owner %llu offset %llu num_refs %lu"
2102                                         " not found in extent tree\n",
2103                                         (unsigned long long)rec->start,
2104                                         back->full_backref ?
2105                                         "parent" : "root",
2106                                         back->full_backref ?
2107                                         (unsigned long long)dback->parent:
2108                                         (unsigned long long)dback->root,
2109                                         (unsigned long long)dback->owner,
2110                                         (unsigned long long)dback->offset,
2111                                         (unsigned long)dback->num_refs);
2112                         } else {
2113                                 tback = (struct tree_backref *)back;
2114                                 fprintf(stderr, "Backref %llu parent %llu"
2115                                         " root %llu not found in extent tree\n",
2116                                         (unsigned long long)rec->start,
2117                                         (unsigned long long)tback->parent,
2118                                         (unsigned long long)tback->root);
2119                         }
2120                 }
2121                 if (!back->is_data && !back->found_ref) {
2122                         err = 1;
2123                         if (!print_errs)
2124                                 goto out;
2125                         tback = (struct tree_backref *)back;
2126                         fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
2127                                 (unsigned long long)rec->start,
2128                                 back->full_backref ? "parent" : "root",
2129                                 back->full_backref ?
2130                                 (unsigned long long)tback->parent :
2131                                 (unsigned long long)tback->root, back);
2132                 }
2133                 if (back->is_data) {
2134                         dback = (struct data_backref *)back;
2135                         if (dback->found_ref != dback->num_refs) {
2136                                 err = 1;
2137                                 if (!print_errs)
2138                                         goto out;
2139                                 fprintf(stderr, "Incorrect local backref count"
2140                                         " on %llu %s %llu owner %llu"
2141                                         " offset %llu found %u wanted %u back %p\n",
2142                                         (unsigned long long)rec->start,
2143                                         back->full_backref ?
2144                                         "parent" : "root",
2145                                         back->full_backref ?
2146                                         (unsigned long long)dback->parent:
2147                                         (unsigned long long)dback->root,
2148                                         (unsigned long long)dback->owner,
2149                                         (unsigned long long)dback->offset,
2150                                         dback->found_ref, dback->num_refs, back);
2151                         }
2152                         if (dback->disk_bytenr != rec->start) {
2153                                 err = 1;
2154                                 if (!print_errs)
2155                                         goto out;
2156                                 fprintf(stderr, "Backref disk bytenr does not"
2157                                         " match extent record, bytenr=%llu, "
2158                                         "ref bytenr=%llu\n",
2159                                         (unsigned long long)rec->start,
2160                                         (unsigned long long)dback->disk_bytenr);
2161                         }
2162
2163                         if (dback->bytes != rec->nr) {
2164                                 err = 1;
2165                                 if (!print_errs)
2166                                         goto out;
2167                                 fprintf(stderr, "Backref bytes do not match "
2168                                         "extent backref, bytenr=%llu, ref "
2169                                         "bytes=%llu, backref bytes=%llu\n",
2170                                         (unsigned long long)rec->start,
2171                                         (unsigned long long)rec->nr,
2172                                         (unsigned long long)dback->bytes);
2173                         }
2174                 }
2175                 if (!back->is_data) {
2176                         found += 1;
2177                 } else {
2178                         dback = (struct data_backref *)back;
2179                         found += dback->found_ref;
2180                 }
2181         }
2182         if (found != rec->refs) {
2183                 err = 1;
2184                 if (!print_errs)
2185                         goto out;
2186                 fprintf(stderr, "Incorrect global backref count "
2187                         "on %llu found %llu wanted %llu\n",
2188                         (unsigned long long)rec->start,
2189                         (unsigned long long)found,
2190                         (unsigned long long)rec->refs);
2191         }
2192 out:
2193         return err;
2194 }
2195
2196 static int free_all_extent_backrefs(struct extent_record *rec)
2197 {
2198         struct extent_backref *back;
2199         struct list_head *cur;
2200         while (!list_empty(&rec->backrefs)) {
2201                 cur = rec->backrefs.next;
2202                 back = list_entry(cur, struct extent_backref, list);
2203                 list_del(cur);
2204                 free(back);
2205         }
2206         return 0;
2207 }
2208
2209 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
2210                                      struct cache_tree *extent_cache)
2211 {
2212         struct cache_extent *cache;
2213         struct extent_record *rec;
2214
2215         while (1) {
2216                 cache = first_cache_extent(extent_cache);
2217                 if (!cache)
2218                         break;
2219                 rec = container_of(cache, struct extent_record, cache);
2220                 btrfs_unpin_extent(fs_info, rec->start, rec->max_size);
2221                 remove_cache_extent(extent_cache, cache);
2222                 free_all_extent_backrefs(rec);
2223                 free(rec);
2224         }
2225 }
2226
2227 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
2228                                  struct extent_record *rec)
2229 {
2230         if (rec->content_checked && rec->owner_ref_checked &&
2231             rec->extent_item_refs == rec->refs && rec->refs > 0 &&
2232             rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
2233                 remove_cache_extent(extent_cache, &rec->cache);
2234                 free_all_extent_backrefs(rec);
2235                 list_del_init(&rec->list);
2236                 free(rec);
2237         }
2238         return 0;
2239 }
2240
2241 static int check_owner_ref(struct btrfs_root *root,
2242                             struct extent_record *rec,
2243                             struct extent_buffer *buf)
2244 {
2245         struct extent_backref *node;
2246         struct tree_backref *back;
2247         struct btrfs_root *ref_root;
2248         struct btrfs_key key;
2249         struct btrfs_path path;
2250         struct extent_buffer *parent;
2251         int level;
2252         int found = 0;
2253         int ret;
2254
2255         list_for_each_entry(node, &rec->backrefs, list) {
2256                 if (node->is_data)
2257                         continue;
2258                 if (!node->found_ref)
2259                         continue;
2260                 if (node->full_backref)
2261                         continue;
2262                 back = (struct tree_backref *)node;
2263                 if (btrfs_header_owner(buf) == back->root)
2264                         return 0;
2265         }
2266         BUG_ON(rec->is_root);
2267
2268         /* try to find the block by search corresponding fs tree */
2269         key.objectid = btrfs_header_owner(buf);
2270         key.type = BTRFS_ROOT_ITEM_KEY;
2271         key.offset = (u64)-1;
2272
2273         ref_root = btrfs_read_fs_root(root->fs_info, &key);
2274         if (IS_ERR(ref_root))
2275                 return 1;
2276
2277         level = btrfs_header_level(buf);
2278         if (level == 0)
2279                 btrfs_item_key_to_cpu(buf, &key, 0);
2280         else
2281                 btrfs_node_key_to_cpu(buf, &key, 0);
2282
2283         btrfs_init_path(&path);
2284         path.lowest_level = level + 1;
2285         ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
2286         if (ret < 0)
2287                 return 0;
2288
2289         parent = path.nodes[level + 1];
2290         if (parent && buf->start == btrfs_node_blockptr(parent,
2291                                                         path.slots[level + 1]))
2292                 found = 1;
2293
2294         btrfs_release_path(&path);
2295         return found ? 0 : 1;
2296 }
2297
2298 static int is_extent_tree_record(struct extent_record *rec)
2299 {
2300         struct list_head *cur = rec->backrefs.next;
2301         struct extent_backref *node;
2302         struct tree_backref *back;
2303         int is_extent = 0;
2304
2305         while(cur != &rec->backrefs) {
2306                 node = list_entry(cur, struct extent_backref, list);
2307                 cur = cur->next;
2308                 if (node->is_data)
2309                         return 0;
2310                 back = (struct tree_backref *)node;
2311                 if (node->full_backref)
2312                         return 0;
2313                 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
2314                         is_extent = 1;
2315         }
2316         return is_extent;
2317 }
2318
2319
2320 static int record_bad_block_io(struct btrfs_fs_info *info,
2321                                struct cache_tree *extent_cache,
2322                                u64 start, u64 len)
2323 {
2324         struct extent_record *rec;
2325         struct cache_extent *cache;
2326         struct btrfs_key key;
2327
2328         cache = lookup_cache_extent(extent_cache, start, len);
2329         if (!cache)
2330                 return 0;
2331
2332         rec = container_of(cache, struct extent_record, cache);
2333         if (!is_extent_tree_record(rec))
2334                 return 0;
2335
2336         btrfs_disk_key_to_cpu(&key, &rec->parent_key);
2337         return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
2338 }
2339
2340 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
2341                        struct extent_buffer *buf, int slot)
2342 {
2343         if (btrfs_header_level(buf)) {
2344                 struct btrfs_key_ptr ptr1, ptr2;
2345
2346                 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
2347                                    sizeof(struct btrfs_key_ptr));
2348                 read_extent_buffer(buf, &ptr2,
2349                                    btrfs_node_key_ptr_offset(slot + 1),
2350                                    sizeof(struct btrfs_key_ptr));
2351                 write_extent_buffer(buf, &ptr1,
2352                                     btrfs_node_key_ptr_offset(slot + 1),
2353                                     sizeof(struct btrfs_key_ptr));
2354                 write_extent_buffer(buf, &ptr2,
2355                                     btrfs_node_key_ptr_offset(slot),
2356                                     sizeof(struct btrfs_key_ptr));
2357                 if (slot == 0) {
2358                         struct btrfs_disk_key key;
2359                         btrfs_node_key(buf, &key, 0);
2360                         btrfs_fixup_low_keys(root, path, &key,
2361                                              btrfs_header_level(buf) + 1);
2362                 }
2363         } else {
2364                 struct btrfs_item *item1, *item2;
2365                 struct btrfs_key k1, k2;
2366                 char *item1_data, *item2_data;
2367                 u32 item1_offset, item2_offset, item1_size, item2_size;
2368
2369                 item1 = btrfs_item_nr(slot);
2370                 item2 = btrfs_item_nr(slot + 1);
2371                 btrfs_item_key_to_cpu(buf, &k1, slot);
2372                 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
2373                 item1_offset = btrfs_item_offset(buf, item1);
2374                 item2_offset = btrfs_item_offset(buf, item2);
2375                 item1_size = btrfs_item_size(buf, item1);
2376                 item2_size = btrfs_item_size(buf, item2);
2377
2378                 item1_data = malloc(item1_size);
2379                 if (!item1_data)
2380                         return -ENOMEM;
2381                 item2_data = malloc(item2_size);
2382                 if (!item2_data) {
2383                         free(item1_data);
2384                         return -ENOMEM;
2385                 }
2386
2387                 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
2388                 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
2389
2390                 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
2391                 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
2392                 free(item1_data);
2393                 free(item2_data);
2394
2395                 btrfs_set_item_offset(buf, item1, item2_offset);
2396                 btrfs_set_item_offset(buf, item2, item1_offset);
2397                 btrfs_set_item_size(buf, item1, item2_size);
2398                 btrfs_set_item_size(buf, item2, item1_size);
2399
2400                 path->slots[0] = slot;
2401                 btrfs_set_item_key_unsafe(root, path, &k2);
2402                 path->slots[0] = slot + 1;
2403                 btrfs_set_item_key_unsafe(root, path, &k1);
2404         }
2405         return 0;
2406 }
2407
2408 /*
2409  * Attempt to fix basic block failures.  Currently we only handle bad key
2410  * orders, we will cycle through the keys and swap them if necessary.
2411  */
2412 static int try_to_fix_bad_block(struct btrfs_trans_handle *trans,
2413                                 struct btrfs_root *root,
2414                                 struct extent_buffer *buf,
2415                                 struct btrfs_disk_key *parent_key,
2416                                 enum btrfs_tree_block_status status)
2417 {
2418         struct btrfs_path *path;
2419         struct btrfs_key k1, k2;
2420         int i;
2421         int ret;
2422
2423         if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
2424                 return -EIO;
2425
2426         k1.objectid = btrfs_header_owner(buf);
2427         k1.type = BTRFS_ROOT_ITEM_KEY;
2428         k1.offset = (u64)-1;
2429
2430         root = btrfs_read_fs_root(root->fs_info, &k1);
2431         if (IS_ERR(root))
2432                 return -EIO;
2433
2434         path = btrfs_alloc_path();
2435         if (!path)
2436                 return -EIO;
2437
2438         path->lowest_level = btrfs_header_level(buf);
2439         path->skip_check_block = 1;
2440         if (btrfs_header_level(buf))
2441                 btrfs_node_key_to_cpu(buf, &k1, 0);
2442         else
2443                 btrfs_item_key_to_cpu(buf, &k1, 0);
2444
2445         ret = btrfs_search_slot(trans, root, &k1, path, 0, 1);
2446         if (ret) {
2447                 btrfs_free_path(path);
2448                 return -EIO;
2449         }
2450
2451         buf = path->nodes[0];
2452         for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
2453                 if (btrfs_header_level(buf)) {
2454                         btrfs_node_key_to_cpu(buf, &k1, i);
2455                         btrfs_node_key_to_cpu(buf, &k2, i + 1);
2456                 } else {
2457                         btrfs_item_key_to_cpu(buf, &k1, i);
2458                         btrfs_item_key_to_cpu(buf, &k2, i + 1);
2459                 }
2460                 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
2461                         continue;
2462                 ret = swap_values(root, path, buf, i);
2463                 if (ret)
2464                         break;
2465                 btrfs_mark_buffer_dirty(buf);
2466                 i = 0;
2467         }
2468
2469         btrfs_free_path(path);
2470         return ret;
2471 }
2472
2473 static int check_block(struct btrfs_trans_handle *trans,
2474                        struct btrfs_root *root,
2475                        struct cache_tree *extent_cache,
2476                        struct extent_buffer *buf, u64 flags)
2477 {
2478         struct extent_record *rec;
2479         struct cache_extent *cache;
2480         struct btrfs_key key;
2481         enum btrfs_tree_block_status status;
2482         int ret = 0;
2483         int level;
2484
2485         cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
2486         if (!cache)
2487                 return 1;
2488         rec = container_of(cache, struct extent_record, cache);
2489         rec->generation = btrfs_header_generation(buf);
2490
2491         level = btrfs_header_level(buf);
2492         if (btrfs_header_nritems(buf) > 0) {
2493
2494                 if (level == 0)
2495                         btrfs_item_key_to_cpu(buf, &key, 0);
2496                 else
2497                         btrfs_node_key_to_cpu(buf, &key, 0);
2498
2499                 rec->info_objectid = key.objectid;
2500         }
2501         rec->info_level = level;
2502
2503         if (btrfs_is_leaf(buf))
2504                 status = btrfs_check_leaf(root, &rec->parent_key, buf);
2505         else
2506                 status = btrfs_check_node(root, &rec->parent_key, buf);
2507
2508         if (status != BTRFS_TREE_BLOCK_CLEAN) {
2509                 if (repair)
2510                         status = try_to_fix_bad_block(trans, root, buf,
2511                                                       &rec->parent_key,
2512                                                       status);
2513                 if (status != BTRFS_TREE_BLOCK_CLEAN) {
2514                         ret = -EIO;
2515                         fprintf(stderr, "bad block %llu\n",
2516                                 (unsigned long long)buf->start);
2517                 } else {
2518                         /*
2519                          * Signal to callers we need to start the scan over
2520                          * again since we'll have cow'ed blocks.
2521                          */
2522                         ret = -EAGAIN;
2523                 }
2524         } else {
2525                 rec->content_checked = 1;
2526                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
2527                         rec->owner_ref_checked = 1;
2528                 else {
2529                         ret = check_owner_ref(root, rec, buf);
2530                         if (!ret)
2531                                 rec->owner_ref_checked = 1;
2532                 }
2533         }
2534         if (!ret)
2535                 maybe_free_extent_rec(extent_cache, rec);
2536         return ret;
2537 }
2538
2539 static struct tree_backref *find_tree_backref(struct extent_record *rec,
2540                                                 u64 parent, u64 root)
2541 {
2542         struct list_head *cur = rec->backrefs.next;
2543         struct extent_backref *node;
2544         struct tree_backref *back;
2545
2546         while(cur != &rec->backrefs) {
2547                 node = list_entry(cur, struct extent_backref, list);
2548                 cur = cur->next;
2549                 if (node->is_data)
2550                         continue;
2551                 back = (struct tree_backref *)node;
2552                 if (parent > 0) {
2553                         if (!node->full_backref)
2554                                 continue;
2555                         if (parent == back->parent)
2556                                 return back;
2557                 } else {
2558                         if (node->full_backref)
2559                                 continue;
2560                         if (back->root == root)
2561                                 return back;
2562                 }
2563         }
2564         return NULL;
2565 }
2566
2567 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
2568                                                 u64 parent, u64 root)
2569 {
2570         struct tree_backref *ref = malloc(sizeof(*ref));
2571         memset(&ref->node, 0, sizeof(ref->node));
2572         if (parent > 0) {
2573                 ref->parent = parent;
2574                 ref->node.full_backref = 1;
2575         } else {
2576                 ref->root = root;
2577                 ref->node.full_backref = 0;
2578         }
2579         list_add_tail(&ref->node.list, &rec->backrefs);
2580
2581         return ref;
2582 }
2583
2584 static struct data_backref *find_data_backref(struct extent_record *rec,
2585                                                 u64 parent, u64 root,
2586                                                 u64 owner, u64 offset,
2587                                                 int found_ref,
2588                                                 u64 disk_bytenr, u64 bytes)
2589 {
2590         struct list_head *cur = rec->backrefs.next;
2591         struct extent_backref *node;
2592         struct data_backref *back;
2593
2594         while(cur != &rec->backrefs) {
2595                 node = list_entry(cur, struct extent_backref, list);
2596                 cur = cur->next;
2597                 if (!node->is_data)
2598                         continue;
2599                 back = (struct data_backref *)node;
2600                 if (parent > 0) {
2601                         if (!node->full_backref)
2602                                 continue;
2603                         if (parent == back->parent)
2604                                 return back;
2605                 } else {
2606                         if (node->full_backref)
2607                                 continue;
2608                         if (back->root == root && back->owner == owner &&
2609                             back->offset == offset) {
2610                                 if (found_ref && node->found_ref &&
2611                                     (back->bytes != bytes ||
2612                                     back->disk_bytenr != disk_bytenr))
2613                                         continue;
2614                                 return back;
2615                         }
2616                 }
2617         }
2618         return NULL;
2619 }
2620
2621 static struct data_backref *alloc_data_backref(struct extent_record *rec,
2622                                                 u64 parent, u64 root,
2623                                                 u64 owner, u64 offset,
2624                                                 u64 max_size)
2625 {
2626         struct data_backref *ref = malloc(sizeof(*ref));
2627         memset(&ref->node, 0, sizeof(ref->node));
2628         ref->node.is_data = 1;
2629
2630         if (parent > 0) {
2631                 ref->parent = parent;
2632                 ref->owner = 0;
2633                 ref->offset = 0;
2634                 ref->node.full_backref = 1;
2635         } else {
2636                 ref->root = root;
2637                 ref->owner = owner;
2638                 ref->offset = offset;
2639                 ref->node.full_backref = 0;
2640         }
2641         ref->bytes = max_size;
2642         ref->found_ref = 0;
2643         ref->num_refs = 0;
2644         list_add_tail(&ref->node.list, &rec->backrefs);
2645         if (max_size > rec->max_size)
2646                 rec->max_size = max_size;
2647         return ref;
2648 }
2649
2650 static int add_extent_rec(struct cache_tree *extent_cache,
2651                           struct btrfs_key *parent_key, u64 parent_gen,
2652                           u64 start, u64 nr, u64 extent_item_refs,
2653                           int is_root, int inc_ref, int set_checked,
2654                           int metadata, int extent_rec, u64 max_size)
2655 {
2656         struct extent_record *rec;
2657         struct cache_extent *cache;
2658         int ret = 0;
2659         int dup = 0;
2660
2661         cache = lookup_cache_extent(extent_cache, start, nr);
2662         if (cache) {
2663                 rec = container_of(cache, struct extent_record, cache);
2664                 if (inc_ref)
2665                         rec->refs++;
2666                 if (rec->nr == 1)
2667                         rec->nr = max(nr, max_size);
2668
2669                 /*
2670                  * We need to make sure to reset nr to whatever the extent
2671                  * record says was the real size, this way we can compare it to
2672                  * the backrefs.
2673                  */
2674                 if (extent_rec) {
2675                         if (start != rec->start || rec->found_rec) {
2676                                 struct extent_record *tmp;
2677
2678                                 dup = 1;
2679                                 if (list_empty(&rec->list))
2680                                         list_add_tail(&rec->list,
2681                                                       &duplicate_extents);
2682
2683                                 /*
2684                                  * We have to do this song and dance in case we
2685                                  * find an extent record that falls inside of
2686                                  * our current extent record but does not have
2687                                  * the same objectid.
2688                                  */
2689                                 tmp = malloc(sizeof(*tmp));
2690                                 if (!tmp)
2691                                         return -ENOMEM;
2692                                 tmp->start = start;
2693                                 tmp->max_size = max_size;
2694                                 tmp->nr = nr;
2695                                 tmp->found_rec = 1;
2696                                 tmp->metadata = metadata;
2697                                 tmp->extent_item_refs = extent_item_refs;
2698                                 INIT_LIST_HEAD(&tmp->list);
2699                                 list_add_tail(&tmp->list, &rec->dups);
2700                                 rec->num_duplicates++;
2701                         } else {
2702                                 rec->nr = nr;
2703                                 rec->found_rec = 1;
2704                         }
2705                 }
2706
2707                 if (extent_item_refs && !dup) {
2708                         if (rec->extent_item_refs) {
2709                                 fprintf(stderr, "block %llu rec "
2710                                         "extent_item_refs %llu, passed %llu\n",
2711                                         (unsigned long long)start,
2712                                         (unsigned long long)
2713                                                         rec->extent_item_refs,
2714                                         (unsigned long long)extent_item_refs);
2715                         }
2716                         rec->extent_item_refs = extent_item_refs;
2717                 }
2718                 if (is_root)
2719                         rec->is_root = 1;
2720                 if (set_checked) {
2721                         rec->content_checked = 1;
2722                         rec->owner_ref_checked = 1;
2723                 }
2724
2725                 if (parent_key)
2726                         btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2727                 if (parent_gen)
2728                         rec->parent_generation = parent_gen;
2729
2730                 if (rec->max_size < max_size)
2731                         rec->max_size = max_size;
2732
2733                 maybe_free_extent_rec(extent_cache, rec);
2734                 return ret;
2735         }
2736         rec = malloc(sizeof(*rec));
2737         rec->start = start;
2738         rec->max_size = max_size;
2739         rec->nr = max(nr, max_size);
2740         rec->found_rec = !!extent_rec;
2741         rec->content_checked = 0;
2742         rec->owner_ref_checked = 0;
2743         rec->num_duplicates = 0;
2744         rec->metadata = metadata;
2745         INIT_LIST_HEAD(&rec->backrefs);
2746         INIT_LIST_HEAD(&rec->dups);
2747         INIT_LIST_HEAD(&rec->list);
2748
2749         if (is_root)
2750                 rec->is_root = 1;
2751         else
2752                 rec->is_root = 0;
2753
2754         if (inc_ref)
2755                 rec->refs = 1;
2756         else
2757                 rec->refs = 0;
2758
2759         if (extent_item_refs)
2760                 rec->extent_item_refs = extent_item_refs;
2761         else
2762                 rec->extent_item_refs = 0;
2763
2764         if (parent_key)
2765                 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2766         else
2767                 memset(&rec->parent_key, 0, sizeof(*parent_key));
2768
2769         if (parent_gen)
2770                 rec->parent_generation = parent_gen;
2771         else
2772                 rec->parent_generation = 0;
2773
2774         rec->cache.start = start;
2775         rec->cache.size = nr;
2776         ret = insert_cache_extent(extent_cache, &rec->cache);
2777         BUG_ON(ret);
2778         bytes_used += nr;
2779         if (set_checked) {
2780                 rec->content_checked = 1;
2781                 rec->owner_ref_checked = 1;
2782         }
2783         return ret;
2784 }
2785
2786 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
2787                             u64 parent, u64 root, int found_ref)
2788 {
2789         struct extent_record *rec;
2790         struct tree_backref *back;
2791         struct cache_extent *cache;
2792
2793         cache = lookup_cache_extent(extent_cache, bytenr, 1);
2794         if (!cache) {
2795                 add_extent_rec(extent_cache, NULL, 0, bytenr,
2796                                1, 0, 0, 0, 0, 1, 0, 0);
2797                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
2798                 if (!cache)
2799                         abort();
2800         }
2801
2802         rec = container_of(cache, struct extent_record, cache);
2803         if (rec->start != bytenr) {
2804                 abort();
2805         }
2806
2807         back = find_tree_backref(rec, parent, root);
2808         if (!back)
2809                 back = alloc_tree_backref(rec, parent, root);
2810
2811         if (found_ref) {
2812                 if (back->node.found_ref) {
2813                         fprintf(stderr, "Extent back ref already exists "
2814                                 "for %llu parent %llu root %llu \n",
2815                                 (unsigned long long)bytenr,
2816                                 (unsigned long long)parent,
2817                                 (unsigned long long)root);
2818                 }
2819                 back->node.found_ref = 1;
2820         } else {
2821                 if (back->node.found_extent_tree) {
2822                         fprintf(stderr, "Extent back ref already exists "
2823                                 "for %llu parent %llu root %llu \n",
2824                                 (unsigned long long)bytenr,
2825                                 (unsigned long long)parent,
2826                                 (unsigned long long)root);
2827                 }
2828                 back->node.found_extent_tree = 1;
2829         }
2830         return 0;
2831 }
2832
2833 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
2834                             u64 parent, u64 root, u64 owner, u64 offset,
2835                             u32 num_refs, int found_ref, u64 max_size)
2836 {
2837         struct extent_record *rec;
2838         struct data_backref *back;
2839         struct cache_extent *cache;
2840
2841         cache = lookup_cache_extent(extent_cache, bytenr, 1);
2842         if (!cache) {
2843                 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
2844                                0, 0, max_size);
2845                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
2846                 if (!cache)
2847                         abort();
2848         }
2849
2850         rec = container_of(cache, struct extent_record, cache);
2851         if (rec->max_size < max_size)
2852                 rec->max_size = max_size;
2853
2854         /*
2855          * If found_ref is set then max_size is the real size and must match the
2856          * existing refs.  So if we have already found a ref then we need to
2857          * make sure that this ref matches the existing one, otherwise we need
2858          * to add a new backref so we can notice that the backrefs don't match
2859          * and we need to figure out who is telling the truth.  This is to
2860          * account for that awful fsync bug I introduced where we'd end up with
2861          * a btrfs_file_extent_item that would have its length include multiple
2862          * prealloc extents or point inside of a prealloc extent.
2863          */
2864         back = find_data_backref(rec, parent, root, owner, offset, found_ref,
2865                                  bytenr, max_size);
2866         if (!back)
2867                 back = alloc_data_backref(rec, parent, root, owner, offset,
2868                                           max_size);
2869
2870         if (found_ref) {
2871                 BUG_ON(num_refs != 1);
2872                 if (back->node.found_ref)
2873                         BUG_ON(back->bytes != max_size);
2874                 back->node.found_ref = 1;
2875                 back->found_ref += 1;
2876                 back->bytes = max_size;
2877                 back->disk_bytenr = bytenr;
2878                 rec->refs += 1;
2879                 rec->content_checked = 1;
2880                 rec->owner_ref_checked = 1;
2881         } else {
2882                 if (back->node.found_extent_tree) {
2883                         fprintf(stderr, "Extent back ref already exists "
2884                                 "for %llu parent %llu root %llu "
2885                                 "owner %llu offset %llu num_refs %lu\n",
2886                                 (unsigned long long)bytenr,
2887                                 (unsigned long long)parent,
2888                                 (unsigned long long)root,
2889                                 (unsigned long long)owner,
2890                                 (unsigned long long)offset,
2891                                 (unsigned long)num_refs);
2892                 }
2893                 back->num_refs = num_refs;
2894                 back->node.found_extent_tree = 1;
2895         }
2896         return 0;
2897 }
2898
2899 static int add_pending(struct cache_tree *pending,
2900                        struct cache_tree *seen, u64 bytenr, u32 size)
2901 {
2902         int ret;
2903         ret = add_cache_extent(seen, bytenr, size);
2904         if (ret)
2905                 return ret;
2906         add_cache_extent(pending, bytenr, size);
2907         return 0;
2908 }
2909
2910 static int pick_next_pending(struct cache_tree *pending,
2911                         struct cache_tree *reada,
2912                         struct cache_tree *nodes,
2913                         u64 last, struct block_info *bits, int bits_nr,
2914                         int *reada_bits)
2915 {
2916         unsigned long node_start = last;
2917         struct cache_extent *cache;
2918         int ret;
2919
2920         cache = search_cache_extent(reada, 0);
2921         if (cache) {
2922                 bits[0].start = cache->start;
2923                 bits[0].size = cache->size;
2924                 *reada_bits = 1;
2925                 return 1;
2926         }
2927         *reada_bits = 0;
2928         if (node_start > 32768)
2929                 node_start -= 32768;
2930
2931         cache = search_cache_extent(nodes, node_start);
2932         if (!cache)
2933                 cache = search_cache_extent(nodes, 0);
2934
2935         if (!cache) {
2936                  cache = search_cache_extent(pending, 0);
2937                  if (!cache)
2938                          return 0;
2939                  ret = 0;
2940                  do {
2941                          bits[ret].start = cache->start;
2942                          bits[ret].size = cache->size;
2943                          cache = next_cache_extent(cache);
2944                          ret++;
2945                  } while (cache && ret < bits_nr);
2946                  return ret;
2947         }
2948
2949         ret = 0;
2950         do {
2951                 bits[ret].start = cache->start;
2952                 bits[ret].size = cache->size;
2953                 cache = next_cache_extent(cache);
2954                 ret++;
2955         } while (cache && ret < bits_nr);
2956
2957         if (bits_nr - ret > 8) {
2958                 u64 lookup = bits[0].start + bits[0].size;
2959                 struct cache_extent *next;
2960                 next = search_cache_extent(pending, lookup);
2961                 while(next) {
2962                         if (next->start - lookup > 32768)
2963                                 break;
2964                         bits[ret].start = next->start;
2965                         bits[ret].size = next->size;
2966                         lookup = next->start + next->size;
2967                         ret++;
2968                         if (ret == bits_nr)
2969                                 break;
2970                         next = next_cache_extent(next);
2971                         if (!next)
2972                                 break;
2973                 }
2974         }
2975         return ret;
2976 }
2977
2978 static void free_chunk_record(struct cache_extent *cache)
2979 {
2980         struct chunk_record *rec;
2981
2982         rec = container_of(cache, struct chunk_record, cache);
2983         free(rec);
2984 }
2985
2986 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
2987 {
2988         cache_tree_free_extents(chunk_cache, free_chunk_record);
2989 }
2990
2991 static void free_device_record(struct rb_node *node)
2992 {
2993         struct device_record *rec;
2994
2995         rec = container_of(node, struct device_record, node);
2996         free(rec);
2997 }
2998
2999 FREE_RB_BASED_TREE(device_cache, free_device_record);
3000
3001 int insert_block_group_record(struct block_group_tree *tree,
3002                               struct block_group_record *bg_rec)
3003 {
3004         int ret;
3005
3006         ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
3007         if (ret)
3008                 return ret;
3009
3010         list_add_tail(&bg_rec->list, &tree->block_groups);
3011         return 0;
3012 }
3013
3014 static void free_block_group_record(struct cache_extent *cache)
3015 {
3016         struct block_group_record *rec;
3017
3018         rec = container_of(cache, struct block_group_record, cache);
3019         free(rec);
3020 }
3021
3022 void free_block_group_tree(struct block_group_tree *tree)
3023 {
3024         cache_tree_free_extents(&tree->tree, free_block_group_record);
3025 }
3026
3027 int insert_device_extent_record(struct device_extent_tree *tree,
3028                                 struct device_extent_record *de_rec)
3029 {
3030         int ret;
3031
3032         /*
3033          * Device extent is a bit different from the other extents, because
3034          * the extents which belong to the different devices may have the
3035          * same start and size, so we need use the special extent cache
3036          * search/insert functions.
3037          */
3038         ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
3039         if (ret)
3040                 return ret;
3041
3042         list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
3043         list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
3044         return 0;
3045 }
3046
3047 static void free_device_extent_record(struct cache_extent *cache)
3048 {
3049         struct device_extent_record *rec;
3050
3051         rec = container_of(cache, struct device_extent_record, cache);
3052         free(rec);
3053 }
3054
3055 void free_device_extent_tree(struct device_extent_tree *tree)
3056 {
3057         cache_tree_free_extents(&tree->tree, free_device_extent_record);
3058 }
3059
3060 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3061 static int process_extent_ref_v0(struct cache_tree *extent_cache,
3062                                  struct extent_buffer *leaf, int slot)
3063 {
3064         struct btrfs_extent_ref_v0 *ref0;
3065         struct btrfs_key key;
3066
3067         btrfs_item_key_to_cpu(leaf, &key, slot);
3068         ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
3069         if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
3070                 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
3071         } else {
3072                 add_data_backref(extent_cache, key.objectid, key.offset, 0,
3073                                  0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
3074         }
3075         return 0;
3076 }
3077 #endif
3078
3079 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
3080                                             struct btrfs_key *key,
3081                                             int slot)
3082 {
3083         struct btrfs_chunk *ptr;
3084         struct chunk_record *rec;
3085         int num_stripes, i;
3086
3087         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3088         num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
3089
3090         rec = malloc(btrfs_chunk_record_size(num_stripes));
3091         if (!rec) {
3092                 fprintf(stderr, "memory allocation failed\n");
3093                 exit(-1);
3094         }
3095
3096         memset(rec, 0, btrfs_chunk_record_size(num_stripes));
3097
3098         INIT_LIST_HEAD(&rec->list);
3099         INIT_LIST_HEAD(&rec->dextents);
3100         rec->bg_rec = NULL;
3101
3102         rec->cache.start = key->offset;
3103         rec->cache.size = btrfs_chunk_length(leaf, ptr);
3104
3105         rec->generation = btrfs_header_generation(leaf);
3106
3107         rec->objectid = key->objectid;
3108         rec->type = key->type;
3109         rec->offset = key->offset;
3110
3111         rec->length = rec->cache.size;
3112         rec->owner = btrfs_chunk_owner(leaf, ptr);
3113         rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
3114         rec->type_flags = btrfs_chunk_type(leaf, ptr);
3115         rec->io_width = btrfs_chunk_io_width(leaf, ptr);
3116         rec->io_align = btrfs_chunk_io_align(leaf, ptr);
3117         rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
3118         rec->num_stripes = num_stripes;
3119         rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
3120
3121         for (i = 0; i < rec->num_stripes; ++i) {
3122                 rec->stripes[i].devid =
3123                         btrfs_stripe_devid_nr(leaf, ptr, i);
3124                 rec->stripes[i].offset =
3125                         btrfs_stripe_offset_nr(leaf, ptr, i);
3126                 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
3127                                 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
3128                                 BTRFS_UUID_SIZE);
3129         }
3130
3131         return rec;
3132 }
3133
3134 static int process_chunk_item(struct cache_tree *chunk_cache,
3135                               struct btrfs_key *key, struct extent_buffer *eb,
3136                               int slot)
3137 {
3138         struct chunk_record *rec;
3139         int ret = 0;
3140
3141         rec = btrfs_new_chunk_record(eb, key, slot);
3142         ret = insert_cache_extent(chunk_cache, &rec->cache);
3143         if (ret) {
3144                 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
3145                         rec->offset, rec->length);
3146                 free(rec);
3147         }
3148
3149         return ret;
3150 }
3151
3152 static int process_device_item(struct rb_root *dev_cache,
3153                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
3154 {
3155         struct btrfs_dev_item *ptr;
3156         struct device_record *rec;
3157         int ret = 0;
3158
3159         ptr = btrfs_item_ptr(eb,
3160                 slot, struct btrfs_dev_item);
3161
3162         rec = malloc(sizeof(*rec));
3163         if (!rec) {
3164                 fprintf(stderr, "memory allocation failed\n");
3165                 return -ENOMEM;
3166         }
3167
3168         rec->devid = key->offset;
3169         rec->generation = btrfs_header_generation(eb);
3170
3171         rec->objectid = key->objectid;
3172         rec->type = key->type;
3173         rec->offset = key->offset;
3174
3175         rec->devid = btrfs_device_id(eb, ptr);
3176         rec->total_byte = btrfs_device_total_bytes(eb, ptr);
3177         rec->byte_used = btrfs_device_bytes_used(eb, ptr);
3178
3179         ret = rb_insert(dev_cache, &rec->node, device_record_compare);
3180         if (ret) {
3181                 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
3182                 free(rec);
3183         }
3184
3185         return ret;
3186 }
3187
3188 struct block_group_record *
3189 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
3190                              int slot)
3191 {
3192         struct btrfs_block_group_item *ptr;
3193         struct block_group_record *rec;
3194
3195         rec = malloc(sizeof(*rec));
3196         if (!rec) {
3197                 fprintf(stderr, "memory allocation failed\n");
3198                 exit(-1);
3199         }
3200         memset(rec, 0, sizeof(*rec));
3201
3202         rec->cache.start = key->objectid;
3203         rec->cache.size = key->offset;
3204
3205         rec->generation = btrfs_header_generation(leaf);
3206
3207         rec->objectid = key->objectid;
3208         rec->type = key->type;
3209         rec->offset = key->offset;
3210
3211         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
3212         rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
3213
3214         INIT_LIST_HEAD(&rec->list);
3215
3216         return rec;
3217 }
3218
3219 static int process_block_group_item(struct block_group_tree *block_group_cache,
3220                                     struct btrfs_key *key,
3221                                     struct extent_buffer *eb, int slot)
3222 {
3223         struct block_group_record *rec;
3224         int ret = 0;
3225
3226         rec = btrfs_new_block_group_record(eb, key, slot);
3227         ret = insert_block_group_record(block_group_cache, rec);
3228         if (ret) {
3229                 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
3230                         rec->objectid, rec->offset);
3231                 free(rec);
3232         }
3233
3234         return ret;
3235 }
3236
3237 struct device_extent_record *
3238 btrfs_new_device_extent_record(struct extent_buffer *leaf,
3239                                struct btrfs_key *key, int slot)
3240 {
3241         struct device_extent_record *rec;
3242         struct btrfs_dev_extent *ptr;
3243
3244         rec = malloc(sizeof(*rec));
3245         if (!rec) {
3246                 fprintf(stderr, "memory allocation failed\n");
3247                 exit(-1);
3248         }
3249         memset(rec, 0, sizeof(*rec));
3250
3251         rec->cache.objectid = key->objectid;
3252         rec->cache.start = key->offset;
3253
3254         rec->generation = btrfs_header_generation(leaf);
3255
3256         rec->objectid = key->objectid;
3257         rec->type = key->type;
3258         rec->offset = key->offset;
3259
3260         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
3261         rec->chunk_objecteid =
3262                 btrfs_dev_extent_chunk_objectid(leaf, ptr);
3263         rec->chunk_offset =
3264                 btrfs_dev_extent_chunk_offset(leaf, ptr);
3265         rec->length = btrfs_dev_extent_length(leaf, ptr);
3266         rec->cache.size = rec->length;
3267
3268         INIT_LIST_HEAD(&rec->chunk_list);
3269         INIT_LIST_HEAD(&rec->device_list);
3270
3271         return rec;
3272 }
3273
3274 static int
3275 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
3276                            struct btrfs_key *key, struct extent_buffer *eb,
3277                            int slot)
3278 {
3279         struct device_extent_record *rec;
3280         int ret;
3281
3282         rec = btrfs_new_device_extent_record(eb, key, slot);
3283         ret = insert_device_extent_record(dev_extent_cache, rec);
3284         if (ret) {
3285                 fprintf(stderr,
3286                         "Device extent[%llu, %llu, %llu] existed.\n",
3287                         rec->objectid, rec->offset, rec->length);
3288                 free(rec);
3289         }
3290
3291         return ret;
3292 }
3293
3294 static int process_extent_item(struct btrfs_root *root,
3295                                struct cache_tree *extent_cache,
3296                                struct extent_buffer *eb, int slot)
3297 {
3298         struct btrfs_extent_item *ei;
3299         struct btrfs_extent_inline_ref *iref;
3300         struct btrfs_extent_data_ref *dref;
3301         struct btrfs_shared_data_ref *sref;
3302         struct btrfs_key key;
3303         unsigned long end;
3304         unsigned long ptr;
3305         int type;
3306         u32 item_size = btrfs_item_size_nr(eb, slot);
3307         u64 refs = 0;
3308         u64 offset;
3309         u64 num_bytes;
3310         int metadata = 0;
3311
3312         btrfs_item_key_to_cpu(eb, &key, slot);
3313
3314         if (key.type == BTRFS_METADATA_ITEM_KEY) {
3315                 metadata = 1;
3316                 num_bytes = root->leafsize;
3317         } else {
3318                 num_bytes = key.offset;
3319         }
3320
3321         if (item_size < sizeof(*ei)) {
3322 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3323                 struct btrfs_extent_item_v0 *ei0;
3324                 BUG_ON(item_size != sizeof(*ei0));
3325                 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
3326                 refs = btrfs_extent_refs_v0(eb, ei0);
3327 #else
3328                 BUG();
3329 #endif
3330                 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
3331                                       num_bytes, refs, 0, 0, 0, metadata, 1,
3332                                       num_bytes);
3333         }
3334
3335         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
3336         refs = btrfs_extent_refs(eb, ei);
3337
3338         add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
3339                        refs, 0, 0, 0, metadata, 1, num_bytes);
3340
3341         ptr = (unsigned long)(ei + 1);
3342         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
3343             key.type == BTRFS_EXTENT_ITEM_KEY)
3344                 ptr += sizeof(struct btrfs_tree_block_info);
3345
3346         end = (unsigned long)ei + item_size;
3347         while (ptr < end) {
3348                 iref = (struct btrfs_extent_inline_ref *)ptr;
3349                 type = btrfs_extent_inline_ref_type(eb, iref);
3350                 offset = btrfs_extent_inline_ref_offset(eb, iref);
3351                 switch (type) {
3352                 case BTRFS_TREE_BLOCK_REF_KEY:
3353                         add_tree_backref(extent_cache, key.objectid,
3354                                          0, offset, 0);
3355                         break;
3356                 case BTRFS_SHARED_BLOCK_REF_KEY:
3357                         add_tree_backref(extent_cache, key.objectid,
3358                                          offset, 0, 0);
3359                         break;
3360                 case BTRFS_EXTENT_DATA_REF_KEY:
3361                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
3362                         add_data_backref(extent_cache, key.objectid, 0,
3363                                         btrfs_extent_data_ref_root(eb, dref),
3364                                         btrfs_extent_data_ref_objectid(eb,
3365                                                                        dref),
3366                                         btrfs_extent_data_ref_offset(eb, dref),
3367                                         btrfs_extent_data_ref_count(eb, dref),
3368                                         0, num_bytes);
3369                         break;
3370                 case BTRFS_SHARED_DATA_REF_KEY:
3371                         sref = (struct btrfs_shared_data_ref *)(iref + 1);
3372                         add_data_backref(extent_cache, key.objectid, offset,
3373                                         0, 0, 0,
3374                                         btrfs_shared_data_ref_count(eb, sref),
3375                                         0, num_bytes);
3376                         break;
3377                 default:
3378                         fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
3379                                 key.objectid, key.type, num_bytes);
3380                         goto out;
3381                 }
3382                 ptr += btrfs_extent_inline_ref_size(type);
3383         }
3384         WARN_ON(ptr > end);
3385 out:
3386         return 0;
3387 }
3388
3389 static int check_cache_range(struct btrfs_root *root,
3390                              struct btrfs_block_group_cache *cache,
3391                              u64 offset, u64 bytes)
3392 {
3393         struct btrfs_free_space *entry;
3394         u64 *logical;
3395         u64 bytenr;
3396         int stripe_len;
3397         int i, nr, ret;
3398
3399         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
3400                 bytenr = btrfs_sb_offset(i);
3401                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
3402                                        cache->key.objectid, bytenr, 0,
3403                                        &logical, &nr, &stripe_len);
3404                 if (ret)
3405                         return ret;
3406
3407                 while (nr--) {
3408                         if (logical[nr] + stripe_len <= offset)
3409                                 continue;
3410                         if (offset + bytes <= logical[nr])
3411                                 continue;
3412                         if (logical[nr] == offset) {
3413                                 if (stripe_len >= bytes) {
3414                                         kfree(logical);
3415                                         return 0;
3416                                 }
3417                                 bytes -= stripe_len;
3418                                 offset += stripe_len;
3419                         } else if (logical[nr] < offset) {
3420                                 if (logical[nr] + stripe_len >=
3421                                     offset + bytes) {
3422                                         kfree(logical);
3423                                         return 0;
3424                                 }
3425                                 bytes = (offset + bytes) -
3426                                         (logical[nr] + stripe_len);
3427                                 offset = logical[nr] + stripe_len;
3428                         } else {
3429                                 /*
3430                                  * Could be tricky, the super may land in the
3431                                  * middle of the area we're checking.  First
3432                                  * check the easiest case, it's at the end.
3433                                  */
3434                                 if (logical[nr] + stripe_len >=
3435                                     bytes + offset) {
3436                                         bytes = logical[nr] - offset;
3437                                         continue;
3438                                 }
3439
3440                                 /* Check the left side */
3441                                 ret = check_cache_range(root, cache,
3442                                                         offset,
3443                                                         logical[nr] - offset);
3444                                 if (ret) {
3445                                         kfree(logical);
3446                                         return ret;
3447                                 }
3448
3449                                 /* Now we continue with the right side */
3450                                 bytes = (offset + bytes) -
3451                                         (logical[nr] + stripe_len);
3452                                 offset = logical[nr] + stripe_len;
3453                         }
3454                 }
3455
3456                 kfree(logical);
3457         }
3458
3459         entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
3460         if (!entry) {
3461                 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
3462                         offset, offset+bytes);
3463                 return -EINVAL;
3464         }
3465
3466         if (entry->offset != offset) {
3467                 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
3468                         entry->offset);
3469                 return -EINVAL;
3470         }
3471
3472         if (entry->bytes != bytes) {
3473                 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
3474                         bytes, entry->bytes, offset);
3475                 return -EINVAL;
3476         }
3477
3478         unlink_free_space(cache->free_space_ctl, entry);
3479         free(entry);
3480         return 0;
3481 }
3482
3483 static int verify_space_cache(struct btrfs_root *root,
3484                               struct btrfs_block_group_cache *cache)
3485 {
3486         struct btrfs_path *path;
3487         struct extent_buffer *leaf;
3488         struct btrfs_key key;
3489         u64 last;
3490         int ret = 0;
3491
3492         path = btrfs_alloc_path();
3493         if (!path)
3494                 return -ENOMEM;
3495
3496         root = root->fs_info->extent_root;
3497
3498         last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
3499
3500         key.objectid = last;
3501         key.offset = 0;
3502         key.type = BTRFS_EXTENT_ITEM_KEY;
3503
3504         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3505         if (ret < 0)
3506                 goto out;
3507         ret = 0;
3508         while (1) {
3509                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3510                         ret = btrfs_next_leaf(root, path);
3511                         if (ret < 0)
3512                                 goto out;
3513                         if (ret > 0) {
3514                                 ret = 0;
3515                                 break;
3516                         }
3517                 }
3518                 leaf = path->nodes[0];
3519                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3520                 if (key.objectid >= cache->key.offset + cache->key.objectid)
3521                         break;
3522                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3523                     key.type != BTRFS_METADATA_ITEM_KEY) {
3524                         path->slots[0]++;
3525                         continue;
3526                 }
3527
3528                 if (last == key.objectid) {
3529                         if (key.type == BTRFS_EXTENT_ITEM_KEY)
3530                                 last = key.objectid + key.offset;
3531                         else
3532                                 last = key.objectid + root->leafsize;
3533                         path->slots[0]++;
3534                         continue;
3535                 }
3536
3537                 ret = check_cache_range(root, cache, last,
3538                                         key.objectid - last);
3539                 if (ret)
3540                         break;
3541                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
3542                         last = key.objectid + key.offset;
3543                 else
3544                         last = key.objectid + root->leafsize;
3545                 path->slots[0]++;
3546         }
3547
3548         if (last < cache->key.objectid + cache->key.offset)
3549                 ret = check_cache_range(root, cache, last,
3550                                         cache->key.objectid +
3551                                         cache->key.offset - last);
3552
3553 out:
3554         btrfs_free_path(path);
3555
3556         if (!ret &&
3557             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
3558                 fprintf(stderr, "There are still entries left in the space "
3559                         "cache\n");
3560                 ret = -EINVAL;
3561         }
3562
3563         return ret;
3564 }
3565
3566 static int check_space_cache(struct btrfs_root *root)
3567 {
3568         struct btrfs_block_group_cache *cache;
3569         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
3570         int ret;
3571         int error = 0;
3572
3573         if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
3574             btrfs_super_generation(root->fs_info->super_copy) !=
3575             btrfs_super_cache_generation(root->fs_info->super_copy)) {
3576                 printf("cache and super generation don't match, space cache "
3577                        "will be invalidated\n");
3578                 return 0;
3579         }
3580
3581         while (1) {
3582                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
3583                 if (!cache)
3584                         break;
3585
3586                 start = cache->key.objectid + cache->key.offset;
3587                 if (!cache->free_space_ctl) {
3588                         if (btrfs_init_free_space_ctl(cache,
3589                                                       root->sectorsize)) {
3590                                 ret = -ENOMEM;
3591                                 break;
3592                         }
3593                 } else {
3594                         btrfs_remove_free_space_cache(cache);
3595                 }
3596
3597                 ret = load_free_space_cache(root->fs_info, cache);
3598                 if (!ret)
3599                         continue;
3600
3601                 ret = verify_space_cache(root, cache);
3602                 if (ret) {
3603                         fprintf(stderr, "cache appears valid but isnt %Lu\n",
3604                                 cache->key.objectid);
3605                         error++;
3606                 }
3607         }
3608
3609         return error ? -EINVAL : 0;
3610 }
3611
3612 static int read_extent_data(struct btrfs_root *root, char *data,
3613                         u64 logical, u64 *len, int mirror)
3614 {
3615         u64 offset = 0;
3616         struct btrfs_multi_bio *multi = NULL;
3617         struct btrfs_fs_info *info = root->fs_info;
3618         struct btrfs_device *device;
3619         int ret = 0;
3620         u64 max_len = *len;
3621
3622         ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
3623                               &multi, mirror, NULL);
3624         if (ret) {
3625                 fprintf(stderr, "Couldn't map the block %llu\n",
3626                                 logical + offset);
3627                 goto err;
3628         }
3629         device = multi->stripes[0].dev;
3630
3631         if (device->fd == 0)
3632                 goto err;
3633         if (*len > max_len)
3634                 *len = max_len;
3635
3636         ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
3637         if (ret != *len)
3638                 ret = -EIO;
3639         else
3640                 ret = 0;
3641 err:
3642         kfree(multi);
3643         return ret;
3644 }
3645
3646 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
3647                         u64 num_bytes, unsigned long leaf_offset,
3648                         struct extent_buffer *eb) {
3649
3650         u64 offset = 0;
3651         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
3652         char *data;
3653         unsigned long csum_offset;
3654         u32 csum;
3655         u32 csum_expected;
3656         u64 read_len;
3657         u64 data_checked = 0;
3658         u64 tmp;
3659         int ret = 0;
3660         int mirror;
3661         int num_copies;
3662
3663         if (num_bytes % root->sectorsize)
3664                 return -EINVAL;
3665
3666         data = malloc(num_bytes);
3667         if (!data)
3668                 return -ENOMEM;
3669
3670         while (offset < num_bytes) {
3671                 mirror = 0;
3672 again:
3673                 read_len = num_bytes - offset;
3674                 /* read as much space once a time */
3675                 ret = read_extent_data(root, data + offset,
3676                                 bytenr + offset, &read_len, mirror);
3677                 if (ret)
3678                         goto out;
3679                 data_checked = 0;
3680                 /* verify every 4k data's checksum */
3681                 while (data_checked < read_len) {
3682                         csum = ~(u32)0;
3683                         tmp = offset + data_checked;
3684
3685                         csum = btrfs_csum_data(NULL, (char *)data + tmp,
3686                                                csum, root->sectorsize);
3687                         btrfs_csum_final(csum, (char *)&csum);
3688
3689                         csum_offset = leaf_offset +
3690                                  tmp / root->sectorsize * csum_size;
3691                         read_extent_buffer(eb, (char *)&csum_expected,
3692                                            csum_offset, csum_size);
3693                         /* try another mirror */
3694                         if (csum != csum_expected) {
3695                                 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
3696                                                 mirror, bytenr + tmp,
3697                                                 csum, csum_expected);
3698                                 num_copies = btrfs_num_copies(
3699                                                 &root->fs_info->mapping_tree,
3700                                                 bytenr, num_bytes);
3701                                 if (mirror < num_copies - 1) {
3702                                         mirror += 1;
3703                                         goto again;
3704                                 }
3705                         }
3706                         data_checked += root->sectorsize;
3707                 }
3708                 offset += read_len;
3709         }
3710 out:
3711         free(data);
3712         return ret;
3713 }
3714
3715 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
3716                                u64 num_bytes)
3717 {
3718         struct btrfs_path *path;
3719         struct extent_buffer *leaf;
3720         struct btrfs_key key;
3721         int ret;
3722
3723         path = btrfs_alloc_path();
3724         if (!path) {
3725                 fprintf(stderr, "Error allocing path\n");
3726                 return -ENOMEM;
3727         }
3728
3729         key.objectid = bytenr;
3730         key.type = BTRFS_EXTENT_ITEM_KEY;
3731         key.offset = 0;
3732
3733
3734 again:
3735         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
3736                                 0, 0);
3737         if (ret < 0) {
3738                 fprintf(stderr, "Error looking up extent record %d\n", ret);
3739                 btrfs_free_path(path);
3740                 return ret;
3741         } else if (ret) {
3742                 if (path->slots[0])
3743                         path->slots[0]--;
3744                 else
3745                         btrfs_prev_leaf(root, path);
3746         }
3747
3748         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3749
3750         /*
3751          * Block group items come before extent items if they have the same
3752          * bytenr, so walk back one more just in case.  Dear future traveler,
3753          * first congrats on mastering time travel.  Now if it's not too much
3754          * trouble could you go back to 2006 and tell Chris to make the
3755          * BLOCK_GROUP_ITEM_KEY lower than the EXTENT_ITEM_KEY please?
3756          */
3757         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
3758                 if (path->slots[0])
3759                         path->slots[0]--;
3760                 else
3761                         btrfs_prev_leaf(root, path);
3762         }
3763
3764         while (num_bytes) {
3765                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3766                         ret = btrfs_next_leaf(root, path);
3767                         if (ret < 0) {
3768                                 fprintf(stderr, "Error going to next leaf "
3769                                         "%d\n", ret);
3770                                 btrfs_free_path(path);
3771                                 return ret;
3772                         } else if (ret) {
3773                                 break;
3774                         }
3775                 }
3776                 leaf = path->nodes[0];
3777                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3778                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
3779                         path->slots[0]++;
3780                         continue;
3781                 }
3782                 if (key.objectid + key.offset < bytenr) {
3783                         path->slots[0]++;
3784                         continue;
3785                 }
3786                 if (key.objectid > bytenr + num_bytes)
3787                         break;
3788
3789                 if (key.objectid == bytenr) {
3790                         if (key.offset >= num_bytes) {
3791                                 num_bytes = 0;
3792                                 break;
3793                         }
3794                         num_bytes -= key.offset;
3795                         bytenr += key.offset;
3796                 } else if (key.objectid < bytenr) {
3797                         if (key.objectid + key.offset >= bytenr + num_bytes) {
3798                                 num_bytes = 0;
3799                                 break;
3800                         }
3801                         num_bytes = (bytenr + num_bytes) -
3802                                 (key.objectid + key.offset);
3803                         bytenr = key.objectid + key.offset;
3804                 } else {
3805                         if (key.objectid + key.offset < bytenr + num_bytes) {
3806                                 u64 new_start = key.objectid + key.offset;
3807                                 u64 new_bytes = bytenr + num_bytes - new_start;
3808
3809                                 /*
3810                                  * Weird case, the extent is in the middle of
3811                                  * our range, we'll have to search one side
3812                                  * and then the other.  Not sure if this happens
3813                                  * in real life, but no harm in coding it up
3814                                  * anyway just in case.
3815                                  */
3816                                 btrfs_release_path(path);
3817                                 ret = check_extent_exists(root, new_start,
3818                                                           new_bytes);
3819                                 if (ret) {
3820                                         fprintf(stderr, "Right section didn't "
3821                                                 "have a record\n");
3822                                         break;
3823                                 }
3824                                 num_bytes = key.objectid - bytenr;
3825                                 goto again;
3826                         }
3827                         num_bytes = key.objectid - bytenr;
3828                 }
3829                 path->slots[0]++;
3830         }
3831         ret = 0;
3832
3833         if (num_bytes) {
3834                 fprintf(stderr, "There are no extents for csum range "
3835                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
3836                 ret = 1;
3837         }
3838
3839         btrfs_free_path(path);
3840         return ret;
3841 }
3842
3843 static int check_csums(struct btrfs_root *root)
3844 {
3845         struct btrfs_path *path;
3846         struct extent_buffer *leaf;
3847         struct btrfs_key key;
3848         u64 offset = 0, num_bytes = 0;
3849         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
3850         int errors = 0;
3851         int ret;
3852         u64 data_len;
3853         unsigned long leaf_offset;
3854
3855         root = root->fs_info->csum_root;
3856
3857         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
3858         key.type = BTRFS_EXTENT_CSUM_KEY;
3859         key.offset = 0;
3860
3861         path = btrfs_alloc_path();
3862         if (!path)
3863                 return -ENOMEM;
3864
3865         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3866         if (ret < 0) {
3867                 fprintf(stderr, "Error searching csum tree %d\n", ret);
3868                 btrfs_free_path(path);
3869                 return ret;
3870         }
3871
3872         if (ret > 0 && path->slots[0])
3873                 path->slots[0]--;
3874         ret = 0;
3875
3876         while (1) {
3877                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3878                         ret = btrfs_next_leaf(root, path);
3879                         if (ret < 0) {
3880                                 fprintf(stderr, "Error going to next leaf "
3881                                         "%d\n", ret);
3882                                 break;
3883                         }
3884                         if (ret)
3885                                 break;
3886                 }
3887                 leaf = path->nodes[0];
3888
3889                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3890                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
3891                         path->slots[0]++;
3892                         continue;
3893                 }
3894
3895                 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
3896                               csum_size) * root->sectorsize;
3897                 if (!check_data_csum)
3898                         goto skip_csum_check;
3899                 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
3900                 ret = check_extent_csums(root, key.offset, data_len,
3901                                          leaf_offset, leaf);
3902                 if (ret)
3903                         break;
3904 skip_csum_check:
3905                 if (!num_bytes) {
3906                         offset = key.offset;
3907                 } else if (key.offset != offset + num_bytes) {
3908                         ret = check_extent_exists(root, offset, num_bytes);
3909                         if (ret) {
3910                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
3911                                         "there is no extent record\n",
3912                                         offset, offset+num_bytes);
3913                                 errors++;
3914                         }
3915                         offset = key.offset;
3916                         num_bytes = 0;
3917                 }
3918                 num_bytes += data_len;
3919                 path->slots[0]++;
3920         }
3921
3922         btrfs_free_path(path);
3923         return errors;
3924 }
3925
3926 static int is_dropped_key(struct btrfs_key *key,
3927                           struct btrfs_key *drop_key) {
3928         if (key->objectid < drop_key->objectid)
3929                 return 1;
3930         else if (key->objectid == drop_key->objectid) {
3931                 if (key->type < drop_key->type)
3932                         return 1;
3933                 else if (key->type == drop_key->type) {
3934                         if (key->offset < drop_key->offset)
3935                                 return 1;
3936                 }
3937         }
3938         return 0;
3939 }
3940
3941 static int run_next_block(struct btrfs_trans_handle *trans,
3942                           struct btrfs_root *root,
3943                           struct block_info *bits,
3944                           int bits_nr,
3945                           u64 *last,
3946                           struct cache_tree *pending,
3947                           struct cache_tree *seen,
3948                           struct cache_tree *reada,
3949                           struct cache_tree *nodes,
3950                           struct cache_tree *extent_cache,
3951                           struct cache_tree *chunk_cache,
3952                           struct rb_root *dev_cache,
3953                           struct block_group_tree *block_group_cache,
3954                           struct device_extent_tree *dev_extent_cache,
3955                           struct btrfs_root_item *ri)
3956 {
3957         struct extent_buffer *buf;
3958         u64 bytenr;
3959         u32 size;
3960         u64 parent;
3961         u64 owner;
3962         u64 flags;
3963         u64 ptr;
3964         u64 gen = 0;
3965         int ret = 0;
3966         int i;
3967         int nritems;
3968         struct btrfs_key key;
3969         struct cache_extent *cache;
3970         int reada_bits;
3971
3972         nritems = pick_next_pending(pending, reada, nodes, *last, bits,
3973                                     bits_nr, &reada_bits);
3974         if (nritems == 0)
3975                 return 1;
3976
3977         if (!reada_bits) {
3978                 for(i = 0; i < nritems; i++) {
3979                         ret = add_cache_extent(reada, bits[i].start,
3980                                                bits[i].size);
3981                         if (ret == -EEXIST)
3982                                 continue;
3983
3984                         /* fixme, get the parent transid */
3985                         readahead_tree_block(root, bits[i].start,
3986                                              bits[i].size, 0);
3987                 }
3988         }
3989         *last = bits[0].start;
3990         bytenr = bits[0].start;
3991         size = bits[0].size;
3992
3993         cache = lookup_cache_extent(pending, bytenr, size);
3994         if (cache) {
3995                 remove_cache_extent(pending, cache);
3996                 free(cache);
3997         }
3998         cache = lookup_cache_extent(reada, bytenr, size);
3999         if (cache) {
4000                 remove_cache_extent(reada, cache);
4001                 free(cache);
4002         }
4003         cache = lookup_cache_extent(nodes, bytenr, size);
4004         if (cache) {
4005                 remove_cache_extent(nodes, cache);
4006                 free(cache);
4007         }
4008         cache = lookup_cache_extent(extent_cache, bytenr, size);
4009         if (cache) {
4010                 struct extent_record *rec;
4011
4012                 rec = container_of(cache, struct extent_record, cache);
4013                 gen = rec->parent_generation;
4014         }
4015
4016         /* fixme, get the real parent transid */
4017         buf = read_tree_block(root, bytenr, size, gen);
4018         if (!extent_buffer_uptodate(buf)) {
4019                 record_bad_block_io(root->fs_info,
4020                                     extent_cache, bytenr, size);
4021                 goto out;
4022         }
4023
4024         nritems = btrfs_header_nritems(buf);
4025
4026         /*
4027          * FIXME, this only works only if we don't have any full
4028          * backref mode.
4029          */
4030         if (!init_extent_tree) {
4031                 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
4032                                        btrfs_header_level(buf), 1, NULL,
4033                                        &flags);
4034                 if (ret < 0)
4035                         flags = 0;
4036         } else {
4037                 flags = 0;
4038         }
4039
4040         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4041                 parent = bytenr;
4042                 owner = 0;
4043         } else {
4044                 parent = 0;
4045                 owner = btrfs_header_owner(buf);
4046         }
4047
4048         ret = check_block(trans, root, extent_cache, buf, flags);
4049         if (ret)
4050                 goto out;
4051
4052         if (btrfs_is_leaf(buf)) {
4053                 btree_space_waste += btrfs_leaf_free_space(root, buf);
4054                 for (i = 0; i < nritems; i++) {
4055                         struct btrfs_file_extent_item *fi;
4056                         btrfs_item_key_to_cpu(buf, &key, i);
4057                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
4058                                 process_extent_item(root, extent_cache, buf,
4059                                                     i);
4060                                 continue;
4061                         }
4062                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
4063                                 process_extent_item(root, extent_cache, buf,
4064                                                     i);
4065                                 continue;
4066                         }
4067                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
4068                                 total_csum_bytes +=
4069                                         btrfs_item_size_nr(buf, i);
4070                                 continue;
4071                         }
4072                         if (key.type == BTRFS_CHUNK_ITEM_KEY) {
4073                                 process_chunk_item(chunk_cache, &key, buf, i);
4074                                 continue;
4075                         }
4076                         if (key.type == BTRFS_DEV_ITEM_KEY) {
4077                                 process_device_item(dev_cache, &key, buf, i);
4078                                 continue;
4079                         }
4080                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
4081                                 process_block_group_item(block_group_cache,
4082                                         &key, buf, i);
4083                                 continue;
4084                         }
4085                         if (key.type == BTRFS_DEV_EXTENT_KEY) {
4086                                 process_device_extent_item(dev_extent_cache,
4087                                         &key, buf, i);
4088                                 continue;
4089
4090                         }
4091                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
4092 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4093                                 process_extent_ref_v0(extent_cache, buf, i);
4094 #else
4095                                 BUG();
4096 #endif
4097                                 continue;
4098                         }
4099
4100                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
4101                                 add_tree_backref(extent_cache, key.objectid, 0,
4102                                                  key.offset, 0);
4103                                 continue;
4104                         }
4105                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
4106                                 add_tree_backref(extent_cache, key.objectid,
4107                                                  key.offset, 0, 0);
4108                                 continue;
4109                         }
4110                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
4111                                 struct btrfs_extent_data_ref *ref;
4112                                 ref = btrfs_item_ptr(buf, i,
4113                                                 struct btrfs_extent_data_ref);
4114                                 add_data_backref(extent_cache,
4115                                         key.objectid, 0,
4116                                         btrfs_extent_data_ref_root(buf, ref),
4117                                         btrfs_extent_data_ref_objectid(buf,
4118                                                                        ref),
4119                                         btrfs_extent_data_ref_offset(buf, ref),
4120                                         btrfs_extent_data_ref_count(buf, ref),
4121                                         0, root->sectorsize);
4122                                 continue;
4123                         }
4124                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
4125                                 struct btrfs_shared_data_ref *ref;
4126                                 ref = btrfs_item_ptr(buf, i,
4127                                                 struct btrfs_shared_data_ref);
4128                                 add_data_backref(extent_cache,
4129                                         key.objectid, key.offset, 0, 0, 0,
4130                                         btrfs_shared_data_ref_count(buf, ref),
4131                                         0, root->sectorsize);
4132                                 continue;
4133                         }
4134                         if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
4135                                 struct bad_item *bad;
4136
4137                                 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
4138                                         continue;
4139                                 if (!owner)
4140                                         continue;
4141                                 bad = malloc(sizeof(struct bad_item));
4142                                 if (!bad)
4143                                         continue;
4144                                 INIT_LIST_HEAD(&bad->list);
4145                                 memcpy(&bad->key, &key,
4146                                        sizeof(struct btrfs_key));
4147                                 bad->root_id = owner;
4148                                 list_add_tail(&bad->list, &delete_items);
4149                                 continue;
4150                         }
4151                         if (key.type != BTRFS_EXTENT_DATA_KEY)
4152                                 continue;
4153                         fi = btrfs_item_ptr(buf, i,
4154                                             struct btrfs_file_extent_item);
4155                         if (btrfs_file_extent_type(buf, fi) ==
4156                             BTRFS_FILE_EXTENT_INLINE)
4157                                 continue;
4158                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
4159                                 continue;
4160
4161                         data_bytes_allocated +=
4162                                 btrfs_file_extent_disk_num_bytes(buf, fi);
4163                         if (data_bytes_allocated < root->sectorsize) {
4164                                 abort();
4165                         }
4166                         data_bytes_referenced +=
4167                                 btrfs_file_extent_num_bytes(buf, fi);
4168                         add_data_backref(extent_cache,
4169                                 btrfs_file_extent_disk_bytenr(buf, fi),
4170                                 parent, owner, key.objectid, key.offset -
4171                                 btrfs_file_extent_offset(buf, fi), 1, 1,
4172                                 btrfs_file_extent_disk_num_bytes(buf, fi));
4173                 }
4174         } else {
4175                 int level;
4176                 struct btrfs_key first_key;
4177
4178                 first_key.objectid = 0;
4179
4180                 if (nritems > 0)
4181                         btrfs_item_key_to_cpu(buf, &first_key, 0);
4182                 level = btrfs_header_level(buf);
4183                 for (i = 0; i < nritems; i++) {
4184                         ptr = btrfs_node_blockptr(buf, i);
4185                         size = btrfs_level_size(root, level - 1);
4186                         btrfs_node_key_to_cpu(buf, &key, i);
4187                         if (ri != NULL) {
4188                                 struct btrfs_key drop_key;
4189                                 btrfs_disk_key_to_cpu(&drop_key,
4190                                                       &ri->drop_progress);
4191                                 if ((level == ri->drop_level)
4192                                     && is_dropped_key(&key, &drop_key)) {
4193                                         continue;
4194                                 }
4195                         }
4196                         ret = add_extent_rec(extent_cache, &key,
4197                                              btrfs_node_ptr_generation(buf, i),
4198                                              ptr, size, 0, 0, 1, 0, 1, 0,
4199                                              size);
4200                         BUG_ON(ret);
4201
4202                         add_tree_backref(extent_cache, ptr, parent, owner, 1);
4203
4204                         if (level > 1) {
4205                                 add_pending(nodes, seen, ptr, size);
4206                         } else {
4207                                 add_pending(pending, seen, ptr, size);
4208                         }
4209                 }
4210                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
4211                                       nritems) * sizeof(struct btrfs_key_ptr);
4212         }
4213         total_btree_bytes += buf->len;
4214         if (fs_root_objectid(btrfs_header_owner(buf)))
4215                 total_fs_tree_bytes += buf->len;
4216         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
4217                 total_extent_tree_bytes += buf->len;
4218         if (!found_old_backref &&
4219             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
4220             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
4221             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
4222                 found_old_backref = 1;
4223 out:
4224         free_extent_buffer(buf);
4225         return ret;
4226 }
4227
4228 static int add_root_to_pending(struct extent_buffer *buf,
4229                                struct cache_tree *extent_cache,
4230                                struct cache_tree *pending,
4231                                struct cache_tree *seen,
4232                                struct cache_tree *nodes,
4233                                struct btrfs_key *root_key)
4234 {
4235         if (btrfs_header_level(buf) > 0)
4236                 add_pending(nodes, seen, buf->start, buf->len);
4237         else
4238                 add_pending(pending, seen, buf->start, buf->len);
4239         add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
4240                        0, 1, 1, 0, 1, 0, buf->len);
4241
4242         if (root_key->objectid == BTRFS_TREE_RELOC_OBJECTID ||
4243             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4244                 add_tree_backref(extent_cache, buf->start, buf->start,
4245                                  0, 1);
4246         else
4247                 add_tree_backref(extent_cache, buf->start, 0,
4248                                  root_key->objectid, 1);
4249         return 0;
4250 }
4251
4252 /* as we fix the tree, we might be deleting blocks that
4253  * we're tracking for repair.  This hook makes sure we
4254  * remove any backrefs for blocks as we are fixing them.
4255  */
4256 static int free_extent_hook(struct btrfs_trans_handle *trans,
4257                             struct btrfs_root *root,
4258                             u64 bytenr, u64 num_bytes, u64 parent,
4259                             u64 root_objectid, u64 owner, u64 offset,
4260                             int refs_to_drop)
4261 {
4262         struct extent_record *rec;
4263         struct cache_extent *cache;
4264         int is_data;
4265         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
4266
4267         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
4268         cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
4269         if (!cache)
4270                 return 0;
4271
4272         rec = container_of(cache, struct extent_record, cache);
4273         if (is_data) {
4274                 struct data_backref *back;
4275                 back = find_data_backref(rec, parent, root_objectid, owner,
4276                                          offset, 1, bytenr, num_bytes);
4277                 if (!back)
4278                         goto out;
4279                 if (back->node.found_ref) {
4280                         back->found_ref -= refs_to_drop;
4281                         if (rec->refs)
4282                                 rec->refs -= refs_to_drop;
4283                 }
4284                 if (back->node.found_extent_tree) {
4285                         back->num_refs -= refs_to_drop;
4286                         if (rec->extent_item_refs)
4287                                 rec->extent_item_refs -= refs_to_drop;
4288                 }
4289                 if (back->found_ref == 0)
4290                         back->node.found_ref = 0;
4291                 if (back->num_refs == 0)
4292                         back->node.found_extent_tree = 0;
4293
4294                 if (!back->node.found_extent_tree && back->node.found_ref) {
4295                         list_del(&back->node.list);
4296                         free(back);
4297                 }
4298         } else {
4299                 struct tree_backref *back;
4300                 back = find_tree_backref(rec, parent, root_objectid);
4301                 if (!back)
4302                         goto out;
4303                 if (back->node.found_ref) {
4304                         if (rec->refs)
4305                                 rec->refs--;
4306                         back->node.found_ref = 0;
4307                 }
4308                 if (back->node.found_extent_tree) {
4309                         if (rec->extent_item_refs)
4310                                 rec->extent_item_refs--;
4311                         back->node.found_extent_tree = 0;
4312                 }
4313                 if (!back->node.found_extent_tree && back->node.found_ref) {
4314                         list_del(&back->node.list);
4315                         free(back);
4316                 }
4317         }
4318         maybe_free_extent_rec(extent_cache, rec);
4319 out:
4320         return 0;
4321 }
4322
4323 static int delete_extent_records(struct btrfs_trans_handle *trans,
4324                                  struct btrfs_root *root,
4325                                  struct btrfs_path *path,
4326                                  u64 bytenr, u64 new_len)
4327 {
4328         struct btrfs_key key;
4329         struct btrfs_key found_key;
4330         struct extent_buffer *leaf;
4331         int ret;
4332         int slot;
4333
4334
4335         key.objectid = bytenr;
4336         key.type = (u8)-1;
4337         key.offset = (u64)-1;
4338
4339         while(1) {
4340                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
4341                                         &key, path, 0, 1);
4342                 if (ret < 0)
4343                         break;
4344
4345                 if (ret > 0) {
4346                         ret = 0;
4347                         if (path->slots[0] == 0)
4348                                 break;
4349                         path->slots[0]--;
4350                 }
4351                 ret = 0;
4352
4353                 leaf = path->nodes[0];
4354                 slot = path->slots[0];
4355
4356                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4357                 if (found_key.objectid != bytenr)
4358                         break;
4359
4360                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
4361                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
4362                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
4363                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
4364                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
4365                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
4366                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
4367                         btrfs_release_path(path);
4368                         if (found_key.type == 0) {
4369                                 if (found_key.offset == 0)
4370                                         break;
4371                                 key.offset = found_key.offset - 1;
4372                                 key.type = found_key.type;
4373                         }
4374                         key.type = found_key.type - 1;
4375                         key.offset = (u64)-1;
4376                         continue;
4377                 }
4378
4379                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
4380                         found_key.objectid, found_key.type, found_key.offset);
4381
4382                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
4383                 if (ret)
4384                         break;
4385                 btrfs_release_path(path);
4386
4387                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4388                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
4389                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
4390                                 found_key.offset : root->leafsize;
4391
4392                         ret = btrfs_update_block_group(trans, root, bytenr,
4393                                                        bytes, 0, 0);
4394                         if (ret)
4395                                 break;
4396                 }
4397         }
4398
4399         btrfs_release_path(path);
4400         return ret;
4401 }
4402
4403 /*
4404  * for a single backref, this will allocate a new extent
4405  * and add the backref to it.
4406  */
4407 static int record_extent(struct btrfs_trans_handle *trans,
4408                          struct btrfs_fs_info *info,
4409                          struct btrfs_path *path,
4410                          struct extent_record *rec,
4411                          struct extent_backref *back,
4412                          int allocated, u64 flags)
4413 {
4414         int ret;
4415         struct btrfs_root *extent_root = info->extent_root;
4416         struct extent_buffer *leaf;
4417         struct btrfs_key ins_key;
4418         struct btrfs_extent_item *ei;
4419         struct tree_backref *tback;
4420         struct data_backref *dback;
4421         struct btrfs_tree_block_info *bi;
4422
4423         if (!back->is_data)
4424                 rec->max_size = max_t(u64, rec->max_size,
4425                                     info->extent_root->leafsize);
4426
4427         if (!allocated) {
4428                 u32 item_size = sizeof(*ei);
4429
4430                 if (!back->is_data)
4431                         item_size += sizeof(*bi);
4432
4433                 ins_key.objectid = rec->start;
4434                 ins_key.offset = rec->max_size;
4435                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
4436
4437                 ret = btrfs_insert_empty_item(trans, extent_root, path,
4438                                         &ins_key, item_size);
4439                 if (ret)
4440                         goto fail;
4441
4442                 leaf = path->nodes[0];
4443                 ei = btrfs_item_ptr(leaf, path->slots[0],
4444                                     struct btrfs_extent_item);
4445
4446                 btrfs_set_extent_refs(leaf, ei, 0);
4447                 btrfs_set_extent_generation(leaf, ei, rec->generation);
4448
4449                 if (back->is_data) {
4450                         btrfs_set_extent_flags(leaf, ei,
4451                                                BTRFS_EXTENT_FLAG_DATA);
4452                 } else {
4453                         struct btrfs_disk_key copy_key;;
4454
4455                         tback = (struct tree_backref *)back;
4456                         bi = (struct btrfs_tree_block_info *)(ei + 1);
4457                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
4458                                              sizeof(*bi));
4459
4460                         btrfs_set_disk_key_objectid(&copy_key,
4461                                                     rec->info_objectid);
4462                         btrfs_set_disk_key_type(&copy_key, 0);
4463                         btrfs_set_disk_key_offset(&copy_key, 0);
4464
4465                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
4466                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
4467
4468                         btrfs_set_extent_flags(leaf, ei,
4469                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
4470                 }
4471
4472                 btrfs_mark_buffer_dirty(leaf);
4473                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
4474                                                rec->max_size, 1, 0);
4475                 if (ret)
4476                         goto fail;
4477                 btrfs_release_path(path);
4478         }
4479
4480         if (back->is_data) {
4481                 u64 parent;
4482                 int i;
4483
4484                 dback = (struct data_backref *)back;
4485                 if (back->full_backref)
4486                         parent = dback->parent;
4487                 else
4488                         parent = 0;
4489
4490                 for (i = 0; i < dback->found_ref; i++) {
4491                         /* if parent != 0, we're doing a full backref
4492                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
4493                          * just makes the backref allocator create a data
4494                          * backref
4495                          */
4496                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
4497                                                    rec->start, rec->max_size,
4498                                                    parent,
4499                                                    dback->root,
4500                                                    parent ?
4501                                                    BTRFS_FIRST_FREE_OBJECTID :
4502                                                    dback->owner,
4503                                                    dback->offset);
4504                         if (ret)
4505                                 break;
4506                 }
4507                 fprintf(stderr, "adding new data backref"
4508                                 " on %llu %s %llu owner %llu"
4509                                 " offset %llu found %d\n",
4510                                 (unsigned long long)rec->start,
4511                                 back->full_backref ?
4512                                 "parent" : "root",
4513                                 back->full_backref ?
4514                                 (unsigned long long)parent :
4515                                 (unsigned long long)dback->root,
4516                                 (unsigned long long)dback->owner,
4517                                 (unsigned long long)dback->offset,
4518                                 dback->found_ref);
4519         } else {
4520                 u64 parent;
4521
4522                 tback = (struct tree_backref *)back;
4523                 if (back->full_backref)
4524                         parent = tback->parent;
4525                 else
4526                         parent = 0;
4527
4528                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
4529                                            rec->start, rec->max_size,
4530                                            parent, tback->root, 0, 0);
4531                 fprintf(stderr, "adding new tree backref on "
4532                         "start %llu len %llu parent %llu root %llu\n",
4533                         rec->start, rec->max_size, tback->parent, tback->root);
4534         }
4535         if (ret)
4536                 goto fail;
4537 fail:
4538         btrfs_release_path(path);
4539         return ret;
4540 }
4541
4542 struct extent_entry {
4543         u64 bytenr;
4544         u64 bytes;
4545         int count;
4546         int broken;
4547         struct list_head list;
4548 };
4549
4550 static struct extent_entry *find_entry(struct list_head *entries,
4551                                        u64 bytenr, u64 bytes)
4552 {
4553         struct extent_entry *entry = NULL;
4554
4555         list_for_each_entry(entry, entries, list) {
4556                 if (entry->bytenr == bytenr && entry->bytes == bytes)
4557                         return entry;
4558         }
4559
4560         return NULL;
4561 }
4562
4563 static struct extent_entry *find_most_right_entry(struct list_head *entries)
4564 {
4565         struct extent_entry *entry, *best = NULL, *prev = NULL;
4566
4567         list_for_each_entry(entry, entries, list) {
4568                 if (!prev) {
4569                         prev = entry;
4570                         continue;
4571                 }
4572
4573                 /*
4574                  * If there are as many broken entries as entries then we know
4575                  * not to trust this particular entry.
4576                  */
4577                 if (entry->broken == entry->count)
4578                         continue;
4579
4580                 /*
4581                  * If our current entry == best then we can't be sure our best
4582                  * is really the best, so we need to keep searching.
4583                  */
4584                 if (best && best->count == entry->count) {
4585                         prev = entry;
4586                         best = NULL;
4587                         continue;
4588                 }
4589
4590                 /* Prev == entry, not good enough, have to keep searching */
4591                 if (!prev->broken && prev->count == entry->count)
4592                         continue;
4593
4594                 if (!best)
4595                         best = (prev->count > entry->count) ? prev : entry;
4596                 else if (best->count < entry->count)
4597                         best = entry;
4598                 prev = entry;
4599         }
4600
4601         return best;
4602 }
4603
4604 static int repair_ref(struct btrfs_trans_handle *trans,
4605                       struct btrfs_fs_info *info, struct btrfs_path *path,
4606                       struct data_backref *dback, struct extent_entry *entry)
4607 {
4608         struct btrfs_root *root;
4609         struct btrfs_file_extent_item *fi;
4610         struct extent_buffer *leaf;
4611         struct btrfs_key key;
4612         u64 bytenr, bytes;
4613         int ret;
4614
4615         key.objectid = dback->root;
4616         key.type = BTRFS_ROOT_ITEM_KEY;
4617         key.offset = (u64)-1;
4618         root = btrfs_read_fs_root(info, &key);
4619         if (IS_ERR(root)) {
4620                 fprintf(stderr, "Couldn't find root for our ref\n");
4621                 return -EINVAL;
4622         }
4623
4624         /*
4625          * The backref points to the original offset of the extent if it was
4626          * split, so we need to search down to the offset we have and then walk
4627          * forward until we find the backref we're looking for.
4628          */
4629         key.objectid = dback->owner;
4630         key.type = BTRFS_EXTENT_DATA_KEY;
4631         key.offset = dback->offset;
4632         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4633         if (ret < 0) {
4634                 fprintf(stderr, "Error looking up ref %d\n", ret);
4635                 return ret;
4636         }
4637
4638         while (1) {
4639                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4640                         ret = btrfs_next_leaf(root, path);
4641                         if (ret) {
4642                                 fprintf(stderr, "Couldn't find our ref, next\n");
4643                                 return -EINVAL;
4644                         }
4645                 }
4646                 leaf = path->nodes[0];
4647                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4648                 if (key.objectid != dback->owner ||
4649                     key.type != BTRFS_EXTENT_DATA_KEY) {
4650                         fprintf(stderr, "Couldn't find our ref, search\n");
4651                         return -EINVAL;
4652                 }
4653                 fi = btrfs_item_ptr(leaf, path->slots[0],
4654                                     struct btrfs_file_extent_item);
4655                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
4656                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
4657
4658                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
4659                         break;
4660                 path->slots[0]++;
4661         }
4662
4663         btrfs_release_path(path);
4664
4665         /*
4666          * Have to make sure that this root gets updated when we commit the
4667          * transaction
4668          */
4669         root->track_dirty = 1;
4670         if (root->last_trans != trans->transid) {
4671                 root->last_trans = trans->transid;
4672                 root->commit_root = root->node;
4673                 extent_buffer_get(root->node);
4674         }
4675
4676         /*
4677          * Ok we have the key of the file extent we want to fix, now we can cow
4678          * down to the thing and fix it.
4679          */
4680         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4681         if (ret < 0) {
4682                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
4683                         key.objectid, key.type, key.offset, ret);
4684                 return ret;
4685         }
4686         if (ret > 0) {
4687                 fprintf(stderr, "Well that's odd, we just found this key "
4688                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
4689                         key.offset);
4690                 return -EINVAL;
4691         }
4692         leaf = path->nodes[0];
4693         fi = btrfs_item_ptr(leaf, path->slots[0],
4694                             struct btrfs_file_extent_item);
4695
4696         if (btrfs_file_extent_compression(leaf, fi) &&
4697             dback->disk_bytenr != entry->bytenr) {
4698                 fprintf(stderr, "Ref doesn't match the record start and is "
4699                         "compressed, please take a btrfs-image of this file "
4700                         "system and send it to a btrfs developer so they can "
4701                         "complete this functionality for bytenr %Lu\n",
4702                         dback->disk_bytenr);
4703                 return -EINVAL;
4704         }
4705
4706         if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
4707                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4708         } else if (dback->disk_bytenr > entry->bytenr) {
4709                 u64 off_diff, offset;
4710
4711                 off_diff = dback->disk_bytenr - entry->bytenr;
4712                 offset = btrfs_file_extent_offset(leaf, fi);
4713                 if (dback->disk_bytenr + offset +
4714                     btrfs_file_extent_num_bytes(leaf, fi) >
4715                     entry->bytenr + entry->bytes) {
4716                         fprintf(stderr, "Ref is past the entry end, please "
4717                                 "take a btrfs-image of this file system and "
4718                                 "send it to a btrfs developer, ref %Lu\n",
4719                                 dback->disk_bytenr);
4720                         return -EINVAL;
4721                 }
4722                 offset += off_diff;
4723                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4724                 btrfs_set_file_extent_offset(leaf, fi, offset);
4725         } else if (dback->disk_bytenr < entry->bytenr) {
4726                 u64 offset;
4727
4728                 offset = btrfs_file_extent_offset(leaf, fi);
4729                 if (dback->disk_bytenr + offset < entry->bytenr) {
4730                         fprintf(stderr, "Ref is before the entry start, please"
4731                                 " take a btrfs-image of this file system and "
4732                                 "send it to a btrfs developer, ref %Lu\n",
4733                                 dback->disk_bytenr);
4734                         return -EINVAL;
4735                 }
4736
4737                 offset += dback->disk_bytenr;
4738                 offset -= entry->bytenr;
4739                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4740                 btrfs_set_file_extent_offset(leaf, fi, offset);
4741         }
4742
4743         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
4744
4745         /*
4746          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
4747          * only do this if we aren't using compression, otherwise it's a
4748          * trickier case.
4749          */
4750         if (!btrfs_file_extent_compression(leaf, fi))
4751                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
4752         else
4753                 printf("ram bytes may be wrong?\n");
4754         btrfs_mark_buffer_dirty(leaf);
4755         btrfs_release_path(path);
4756         return 0;
4757 }
4758
4759 static int verify_backrefs(struct btrfs_trans_handle *trans,
4760                            struct btrfs_fs_info *info, struct btrfs_path *path,
4761                            struct extent_record *rec)
4762 {
4763         struct extent_backref *back;
4764         struct data_backref *dback;
4765         struct extent_entry *entry, *best = NULL;
4766         LIST_HEAD(entries);
4767         int nr_entries = 0;
4768         int broken_entries = 0;
4769         int ret = 0;
4770         short mismatch = 0;
4771
4772         /*
4773          * Metadata is easy and the backrefs should always agree on bytenr and
4774          * size, if not we've got bigger issues.
4775          */
4776         if (rec->metadata)
4777                 return 0;
4778
4779         list_for_each_entry(back, &rec->backrefs, list) {
4780                 dback = (struct data_backref *)back;
4781                 /*
4782                  * We only pay attention to backrefs that we found a real
4783                  * backref for.
4784                  */
4785                 if (dback->found_ref == 0)
4786                         continue;
4787                 if (back->full_backref)
4788                         continue;
4789
4790                 /*
4791                  * For now we only catch when the bytes don't match, not the
4792                  * bytenr.  We can easily do this at the same time, but I want
4793                  * to have a fs image to test on before we just add repair
4794                  * functionality willy-nilly so we know we won't screw up the
4795                  * repair.
4796                  */
4797
4798                 entry = find_entry(&entries, dback->disk_bytenr,
4799                                    dback->bytes);
4800                 if (!entry) {
4801                         entry = malloc(sizeof(struct extent_entry));
4802                         if (!entry) {
4803                                 ret = -ENOMEM;
4804                                 goto out;
4805                         }
4806                         memset(entry, 0, sizeof(*entry));
4807                         entry->bytenr = dback->disk_bytenr;
4808                         entry->bytes = dback->bytes;
4809                         list_add_tail(&entry->list, &entries);
4810                         nr_entries++;
4811                 }
4812
4813                 /*
4814                  * If we only have on entry we may think the entries agree when
4815                  * in reality they don't so we have to do some extra checking.
4816                  */
4817                 if (dback->disk_bytenr != rec->start ||
4818                     dback->bytes != rec->nr || back->broken)
4819                         mismatch = 1;
4820
4821                 if (back->broken) {
4822                         entry->broken++;
4823                         broken_entries++;
4824                 }
4825
4826                 entry->count++;
4827         }
4828
4829         /* Yay all the backrefs agree, carry on good sir */
4830         if (nr_entries <= 1 && !mismatch)
4831                 goto out;
4832
4833         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
4834                 "%Lu\n", rec->start);
4835
4836         /*
4837          * First we want to see if the backrefs can agree amongst themselves who
4838          * is right, so figure out which one of the entries has the highest
4839          * count.
4840          */
4841         best = find_most_right_entry(&entries);
4842
4843         /*
4844          * Ok so we may have an even split between what the backrefs think, so
4845          * this is where we use the extent ref to see what it thinks.
4846          */
4847         if (!best) {
4848                 entry = find_entry(&entries, rec->start, rec->nr);
4849                 if (!entry && (!broken_entries || !rec->found_rec)) {
4850                         fprintf(stderr, "Backrefs don't agree with each other "
4851                                 "and extent record doesn't agree with anybody,"
4852                                 " so we can't fix bytenr %Lu bytes %Lu\n",
4853                                 rec->start, rec->nr);
4854                         ret = -EINVAL;
4855                         goto out;
4856                 } else if (!entry) {
4857                         /*
4858                          * Ok our backrefs were broken, we'll assume this is the
4859                          * correct value and add an entry for this range.
4860                          */
4861                         entry = malloc(sizeof(struct extent_entry));
4862                         if (!entry) {
4863                                 ret = -ENOMEM;
4864                                 goto out;
4865                         }
4866                         memset(entry, 0, sizeof(*entry));
4867                         entry->bytenr = rec->start;
4868                         entry->bytes = rec->nr;
4869                         list_add_tail(&entry->list, &entries);
4870                         nr_entries++;
4871                 }
4872                 entry->count++;
4873                 best = find_most_right_entry(&entries);
4874                 if (!best) {
4875                         fprintf(stderr, "Backrefs and extent record evenly "
4876                                 "split on who is right, this is going to "
4877                                 "require user input to fix bytenr %Lu bytes "
4878                                 "%Lu\n", rec->start, rec->nr);
4879                         ret = -EINVAL;
4880                         goto out;
4881                 }
4882         }
4883
4884         /*
4885          * I don't think this can happen currently as we'll abort() if we catch
4886          * this case higher up, but in case somebody removes that we still can't
4887          * deal with it properly here yet, so just bail out of that's the case.
4888          */
4889         if (best->bytenr != rec->start) {
4890                 fprintf(stderr, "Extent start and backref starts don't match, "
4891                         "please use btrfs-image on this file system and send "
4892                         "it to a btrfs developer so they can make fsck fix "
4893                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
4894                         rec->start, rec->nr);
4895                 ret = -EINVAL;
4896                 goto out;
4897         }
4898
4899         /*
4900          * Ok great we all agreed on an extent record, let's go find the real
4901          * references and fix up the ones that don't match.
4902          */
4903         list_for_each_entry(back, &rec->backrefs, list) {
4904                 dback = (struct data_backref *)back;
4905
4906                 /*
4907                  * Still ignoring backrefs that don't have a real ref attached
4908                  * to them.
4909                  */
4910                 if (dback->found_ref == 0)
4911                         continue;
4912                 if (back->full_backref)
4913                         continue;
4914
4915                 if (dback->bytes == best->bytes &&
4916                     dback->disk_bytenr == best->bytenr)
4917                         continue;
4918
4919                 ret = repair_ref(trans, info, path, dback, best);
4920                 if (ret)
4921                         goto out;
4922         }
4923
4924         /*
4925          * Ok we messed with the actual refs, which means we need to drop our
4926          * entire cache and go back and rescan.  I know this is a huge pain and
4927          * adds a lot of extra work, but it's the only way to be safe.  Once all
4928          * the backrefs agree we may not need to do anything to the extent
4929          * record itself.
4930          */
4931         ret = -EAGAIN;
4932 out:
4933         while (!list_empty(&entries)) {
4934                 entry = list_entry(entries.next, struct extent_entry, list);
4935                 list_del_init(&entry->list);
4936                 free(entry);
4937         }
4938         return ret;
4939 }
4940
4941 static int process_duplicates(struct btrfs_root *root,
4942                               struct cache_tree *extent_cache,
4943                               struct extent_record *rec)
4944 {
4945         struct extent_record *good, *tmp;
4946         struct cache_extent *cache;
4947         int ret;
4948
4949         /*
4950          * If we found a extent record for this extent then return, or if we
4951          * have more than one duplicate we are likely going to need to delete
4952          * something.
4953          */
4954         if (rec->found_rec || rec->num_duplicates > 1)
4955                 return 0;
4956
4957         /* Shouldn't happen but just in case */
4958         BUG_ON(!rec->num_duplicates);
4959
4960         /*
4961          * So this happens if we end up with a backref that doesn't match the
4962          * actual extent entry.  So either the backref is bad or the extent
4963          * entry is bad.  Either way we want to have the extent_record actually
4964          * reflect what we found in the extent_tree, so we need to take the
4965          * duplicate out and use that as the extent_record since the only way we
4966          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
4967          */
4968         remove_cache_extent(extent_cache, &rec->cache);
4969
4970         good = list_entry(rec->dups.next, struct extent_record, list);
4971         list_del_init(&good->list);
4972         INIT_LIST_HEAD(&good->backrefs);
4973         INIT_LIST_HEAD(&good->dups);
4974         good->cache.start = good->start;
4975         good->cache.size = good->nr;
4976         good->content_checked = 0;
4977         good->owner_ref_checked = 0;
4978         good->num_duplicates = 0;
4979         good->refs = rec->refs;
4980         list_splice_init(&rec->backrefs, &good->backrefs);
4981         while (1) {
4982                 cache = lookup_cache_extent(extent_cache, good->start,
4983                                             good->nr);
4984                 if (!cache)
4985                         break;
4986                 tmp = container_of(cache, struct extent_record, cache);
4987
4988                 /*
4989                  * If we find another overlapping extent and it's found_rec is
4990                  * set then it's a duplicate and we need to try and delete
4991                  * something.
4992                  */
4993                 if (tmp->found_rec || tmp->num_duplicates > 0) {
4994                         if (list_empty(&good->list))
4995                                 list_add_tail(&good->list,
4996                                               &duplicate_extents);
4997                         good->num_duplicates += tmp->num_duplicates + 1;
4998                         list_splice_init(&tmp->dups, &good->dups);
4999                         list_del_init(&tmp->list);
5000                         list_add_tail(&tmp->list, &good->dups);
5001                         remove_cache_extent(extent_cache, &tmp->cache);
5002                         continue;
5003                 }
5004
5005                 /*
5006                  * Ok we have another non extent item backed extent rec, so lets
5007                  * just add it to this extent and carry on like we did above.
5008                  */
5009                 good->refs += tmp->refs;
5010                 list_splice_init(&tmp->backrefs, &good->backrefs);
5011                 remove_cache_extent(extent_cache, &tmp->cache);
5012                 free(tmp);
5013         }
5014         ret = insert_cache_extent(extent_cache, &good->cache);
5015         BUG_ON(ret);
5016         free(rec);
5017         return good->num_duplicates ? 0 : 1;
5018 }
5019
5020 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
5021                                     struct btrfs_root *root,
5022                                     struct extent_record *rec)
5023 {
5024         LIST_HEAD(delete_list);
5025         struct btrfs_path *path;
5026         struct extent_record *tmp, *good, *n;
5027         int nr_del = 0;
5028         int ret = 0;
5029         struct btrfs_key key;
5030
5031         path = btrfs_alloc_path();
5032         if (!path) {
5033                 ret = -ENOMEM;
5034                 goto out;
5035         }
5036
5037         good = rec;
5038         /* Find the record that covers all of the duplicates. */
5039         list_for_each_entry(tmp, &rec->dups, list) {
5040                 if (good->start < tmp->start)
5041                         continue;
5042                 if (good->nr > tmp->nr)
5043                         continue;
5044
5045                 if (tmp->start + tmp->nr < good->start + good->nr) {
5046                         fprintf(stderr, "Ok we have overlapping extents that "
5047                                 "aren't completely covered by eachother, this "
5048                                 "is going to require more careful thought.  "
5049                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
5050                                 tmp->start, tmp->nr, good->start, good->nr);
5051                         abort();
5052                 }
5053                 good = tmp;
5054         }
5055
5056         if (good != rec)
5057                 list_add_tail(&rec->list, &delete_list);
5058
5059         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
5060                 if (tmp == good)
5061                         continue;
5062                 list_move_tail(&tmp->list, &delete_list);
5063         }
5064
5065         root = root->fs_info->extent_root;
5066         list_for_each_entry(tmp, &delete_list, list) {
5067                 if (tmp->found_rec == 0)
5068                         continue;
5069                 key.objectid = tmp->start;
5070                 key.type = BTRFS_EXTENT_ITEM_KEY;
5071                 key.offset = tmp->nr;
5072
5073                 /* Shouldn't happen but just in case */
5074                 if (tmp->metadata) {
5075                         fprintf(stderr, "Well this shouldn't happen, extent "
5076                                 "record overlaps but is metadata? "
5077                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
5078                         abort();
5079                 }
5080
5081                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5082                 if (ret) {
5083                         if (ret > 0)
5084                                 ret = -EINVAL;
5085                         goto out;
5086                 }
5087                 ret = btrfs_del_item(trans, root, path);
5088                 if (ret)
5089                         goto out;
5090                 btrfs_release_path(path);
5091                 nr_del++;
5092         }
5093
5094 out:
5095         while (!list_empty(&delete_list)) {
5096                 tmp = list_entry(delete_list.next, struct extent_record, list);
5097                 list_del_init(&tmp->list);
5098                 if (tmp == rec)
5099                         continue;
5100                 free(tmp);
5101         }
5102
5103         while (!list_empty(&rec->dups)) {
5104                 tmp = list_entry(rec->dups.next, struct extent_record, list);
5105                 list_del_init(&tmp->list);
5106                 free(tmp);
5107         }
5108
5109         btrfs_free_path(path);
5110
5111         if (!ret && !nr_del)
5112                 rec->num_duplicates = 0;
5113
5114         return ret ? ret : nr_del;
5115 }
5116
5117 static int find_possible_backrefs(struct btrfs_trans_handle *trans,
5118                                   struct btrfs_fs_info *info,
5119                                   struct btrfs_path *path,
5120                                   struct cache_tree *extent_cache,
5121                                   struct extent_record *rec)
5122 {
5123         struct btrfs_root *root;
5124         struct extent_backref *back;
5125         struct data_backref *dback;
5126         struct cache_extent *cache;
5127         struct btrfs_file_extent_item *fi;
5128         struct btrfs_key key;
5129         u64 bytenr, bytes;
5130         int ret;
5131
5132         list_for_each_entry(back, &rec->backrefs, list) {
5133                 dback = (struct data_backref *)back;
5134
5135                 /* We found this one, we don't need to do a lookup */
5136                 if (dback->found_ref)
5137                         continue;
5138                 /* Don't care about full backrefs (poor unloved backrefs) */
5139                 if (back->full_backref)
5140                         continue;
5141                 key.objectid = dback->root;
5142                 key.type = BTRFS_ROOT_ITEM_KEY;
5143                 key.offset = (u64)-1;
5144
5145                 root = btrfs_read_fs_root(info, &key);
5146
5147                 /* No root, definitely a bad ref, skip */
5148                 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
5149                         continue;
5150                 /* Other err, exit */
5151                 if (IS_ERR(root))
5152                         return PTR_ERR(root);
5153
5154                 key.objectid = dback->owner;
5155                 key.type = BTRFS_EXTENT_DATA_KEY;
5156                 key.offset = dback->offset;
5157                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5158                 if (ret) {
5159                         btrfs_release_path(path);
5160                         if (ret < 0)
5161                                 return ret;
5162                         /* Didn't find it, we can carry on */
5163                         ret = 0;
5164                         continue;
5165                 }
5166
5167                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5168                                     struct btrfs_file_extent_item);
5169                 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
5170                 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
5171                 btrfs_release_path(path);
5172                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
5173                 if (cache) {
5174                         struct extent_record *tmp;
5175                         tmp = container_of(cache, struct extent_record, cache);
5176
5177                         /*
5178                          * If we found an extent record for the bytenr for this
5179                          * particular backref then we can't add it to our
5180                          * current extent record.  We only want to add backrefs
5181                          * that don't have a corresponding extent item in the
5182                          * extent tree since they likely belong to this record
5183                          * and we need to fix it if it doesn't match bytenrs.
5184                          */
5185                         if  (tmp->found_rec)
5186                                 continue;
5187                 }
5188
5189                 dback->found_ref += 1;
5190                 dback->disk_bytenr = bytenr;
5191                 dback->bytes = bytes;
5192
5193                 /*
5194                  * Set this so the verify backref code knows not to trust the
5195                  * values in this backref.
5196                  */
5197                 back->broken = 1;
5198         }
5199
5200         return 0;
5201 }
5202
5203 /*
5204  * when an incorrect extent item is found, this will delete
5205  * all of the existing entries for it and recreate them
5206  * based on what the tree scan found.
5207  */
5208 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
5209                              struct btrfs_fs_info *info,
5210                              struct cache_tree *extent_cache,
5211                              struct extent_record *rec)
5212 {
5213         int ret;
5214         struct btrfs_path *path;
5215         struct list_head *cur = rec->backrefs.next;
5216         struct cache_extent *cache;
5217         struct extent_backref *back;
5218         int allocated = 0;
5219         u64 flags = 0;
5220
5221         /*
5222          * remember our flags for recreating the extent.
5223          * FIXME, if we have cleared extent tree, we can not
5224          * lookup extent info in extent tree.
5225          */
5226         if (!init_extent_tree) {
5227                 ret = btrfs_lookup_extent_info(NULL, info->extent_root,
5228                                         rec->start, rec->max_size,
5229                                         rec->metadata, NULL, &flags);
5230                 if (ret < 0)
5231                         flags = 0;
5232         } else {
5233                 flags = 0;
5234         }
5235
5236         path = btrfs_alloc_path();
5237         if (!path)
5238                 return -ENOMEM;
5239
5240         if (rec->refs != rec->extent_item_refs && !rec->metadata) {
5241                 /*
5242                  * Sometimes the backrefs themselves are so broken they don't
5243                  * get attached to any meaningful rec, so first go back and
5244                  * check any of our backrefs that we couldn't find and throw
5245                  * them into the list if we find the backref so that
5246                  * verify_backrefs can figure out what to do.
5247                  */
5248                 ret = find_possible_backrefs(trans, info, path, extent_cache,
5249                                              rec);
5250                 if (ret < 0)
5251                         goto out;
5252         }
5253
5254         /* step one, make sure all of the backrefs agree */
5255         ret = verify_backrefs(trans, info, path, rec);
5256         if (ret < 0)
5257                 goto out;
5258
5259         /* step two, delete all the existing records */
5260         ret = delete_extent_records(trans, info->extent_root, path,
5261                                     rec->start, rec->max_size);
5262
5263         if (ret < 0)
5264                 goto out;
5265
5266         /* was this block corrupt?  If so, don't add references to it */
5267         cache = lookup_cache_extent(info->corrupt_blocks,
5268                                     rec->start, rec->max_size);
5269         if (cache) {
5270                 ret = 0;
5271                 goto out;
5272         }
5273
5274         /* step three, recreate all the refs we did find */
5275         while(cur != &rec->backrefs) {
5276                 back = list_entry(cur, struct extent_backref, list);
5277                 cur = cur->next;
5278
5279                 /*
5280                  * if we didn't find any references, don't create a
5281                  * new extent record
5282                  */
5283                 if (!back->found_ref)
5284                         continue;
5285
5286                 ret = record_extent(trans, info, path, rec, back, allocated, flags);
5287                 allocated = 1;
5288
5289                 if (ret)
5290                         goto out;
5291         }
5292 out:
5293         btrfs_free_path(path);
5294         return ret;
5295 }
5296
5297 /* right now we only prune from the extent allocation tree */
5298 static int prune_one_block(struct btrfs_trans_handle *trans,
5299                            struct btrfs_fs_info *info,
5300                            struct btrfs_corrupt_block *corrupt)
5301 {
5302         int ret;
5303         struct btrfs_path path;
5304         struct extent_buffer *eb;
5305         u64 found;
5306         int slot;
5307         int nritems;
5308         int level = corrupt->level + 1;
5309
5310         btrfs_init_path(&path);
5311 again:
5312         /* we want to stop at the parent to our busted block */
5313         path.lowest_level = level;
5314
5315         ret = btrfs_search_slot(trans, info->extent_root,
5316                                 &corrupt->key, &path, -1, 1);
5317
5318         if (ret < 0)
5319                 goto out;
5320
5321         eb = path.nodes[level];
5322         if (!eb) {
5323                 ret = -ENOENT;
5324                 goto out;
5325         }
5326
5327         /*
5328          * hopefully the search gave us the block we want to prune,
5329          * lets try that first
5330          */
5331         slot = path.slots[level];
5332         found =  btrfs_node_blockptr(eb, slot);
5333         if (found == corrupt->cache.start)
5334                 goto del_ptr;
5335
5336         nritems = btrfs_header_nritems(eb);
5337
5338         /* the search failed, lets scan this node and hope we find it */
5339         for (slot = 0; slot < nritems; slot++) {
5340                 found =  btrfs_node_blockptr(eb, slot);
5341                 if (found == corrupt->cache.start)
5342                         goto del_ptr;
5343         }
5344         /*
5345          * we couldn't find the bad block.  TODO, search all the nodes for pointers
5346          * to this block
5347          */
5348         if (eb == info->extent_root->node) {
5349                 ret = -ENOENT;
5350                 goto out;
5351         } else {
5352                 level++;
5353                 btrfs_release_path(&path);
5354                 goto again;
5355         }
5356
5357 del_ptr:
5358         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
5359         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
5360
5361 out:
5362         btrfs_release_path(&path);
5363         return ret;
5364 }
5365
5366 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
5367                                 struct btrfs_fs_info *info)
5368 {
5369         struct cache_extent *cache;
5370         struct btrfs_corrupt_block *corrupt;
5371
5372         cache = search_cache_extent(info->corrupt_blocks, 0);
5373         while (1) {
5374                 if (!cache)
5375                         break;
5376                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
5377                 prune_one_block(trans, info, corrupt);
5378                 cache = next_cache_extent(cache);
5379         }
5380         return 0;
5381 }
5382
5383 static void free_corrupt_block(struct cache_extent *cache)
5384 {
5385         struct btrfs_corrupt_block *corrupt;
5386
5387         corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
5388         free(corrupt);
5389 }
5390
5391 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
5392
5393 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
5394 {
5395         struct btrfs_block_group_cache *cache;
5396         u64 start, end;
5397         int ret;
5398
5399         while (1) {
5400                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
5401                                             &start, &end, EXTENT_DIRTY);
5402                 if (ret)
5403                         break;
5404                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
5405                                    GFP_NOFS);
5406         }
5407
5408         start = 0;
5409         while (1) {
5410                 cache = btrfs_lookup_first_block_group(fs_info, start);
5411                 if (!cache)
5412                         break;
5413                 if (cache->cached)
5414                         cache->cached = 0;
5415                 start = cache->key.objectid + cache->key.offset;
5416         }
5417 }
5418
5419 static int check_extent_refs(struct btrfs_trans_handle *trans,
5420                              struct btrfs_root *root,
5421                              struct cache_tree *extent_cache)
5422 {
5423         struct extent_record *rec;
5424         struct cache_extent *cache;
5425         int err = 0;
5426         int ret = 0;
5427         int fixed = 0;
5428         int had_dups = 0;
5429
5430         if (repair) {
5431                 /*
5432                  * if we're doing a repair, we have to make sure
5433                  * we don't allocate from the problem extents.
5434                  * In the worst case, this will be all the
5435                  * extents in the FS
5436                  */
5437                 cache = search_cache_extent(extent_cache, 0);
5438                 while(cache) {
5439                         rec = container_of(cache, struct extent_record, cache);
5440                         btrfs_pin_extent(root->fs_info,
5441                                          rec->start, rec->max_size);
5442                         cache = next_cache_extent(cache);
5443                 }
5444
5445                 /* pin down all the corrupted blocks too */
5446                 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
5447                 while(cache) {
5448                         btrfs_pin_extent(root->fs_info,
5449                                          cache->start, cache->size);
5450                         cache = next_cache_extent(cache);
5451                 }
5452                 prune_corrupt_blocks(trans, root->fs_info);
5453                 reset_cached_block_groups(root->fs_info);
5454         }
5455
5456         /*
5457          * We need to delete any duplicate entries we find first otherwise we
5458          * could mess up the extent tree when we have backrefs that actually
5459          * belong to a different extent item and not the weird duplicate one.
5460          */
5461         while (repair && !list_empty(&duplicate_extents)) {
5462                 rec = list_entry(duplicate_extents.next, struct extent_record,
5463                                  list);
5464                 list_del_init(&rec->list);
5465
5466                 /* Sometimes we can find a backref before we find an actual
5467                  * extent, so we need to process it a little bit to see if there
5468                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
5469                  * if this is a backref screwup.  If we need to delete stuff
5470                  * process_duplicates() will return 0, otherwise it will return
5471                  * 1 and we
5472                  */
5473                 if (process_duplicates(root, extent_cache, rec))
5474                         continue;
5475                 ret = delete_duplicate_records(trans, root, rec);
5476                 if (ret < 0)
5477                         return ret;
5478                 /*
5479                  * delete_duplicate_records will return the number of entries
5480                  * deleted, so if it's greater than 0 then we know we actually
5481                  * did something and we need to remove.
5482                  */
5483                 if (ret)
5484                         had_dups = 1;
5485         }
5486
5487         if (had_dups)
5488                 return -EAGAIN;
5489
5490         while(1) {
5491                 fixed = 0;
5492                 cache = search_cache_extent(extent_cache, 0);
5493                 if (!cache)
5494                         break;
5495                 rec = container_of(cache, struct extent_record, cache);
5496                 if (rec->num_duplicates) {
5497                         fprintf(stderr, "extent item %llu has multiple extent "
5498                                 "items\n", (unsigned long long)rec->start);
5499                         err = 1;
5500                 }
5501
5502                 if (rec->refs != rec->extent_item_refs) {
5503                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
5504                                 (unsigned long long)rec->start,
5505                                 (unsigned long long)rec->nr);
5506                         fprintf(stderr, "extent item %llu, found %llu\n",
5507                                 (unsigned long long)rec->extent_item_refs,
5508                                 (unsigned long long)rec->refs);
5509                         if (!fixed && repair) {
5510                                 ret = fixup_extent_refs(trans, root->fs_info,
5511                                                         extent_cache, rec);
5512                                 if (ret)
5513                                         goto repair_abort;
5514                                 fixed = 1;
5515                         }
5516                         err = 1;
5517
5518                 }
5519                 if (all_backpointers_checked(rec, 1)) {
5520                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
5521                                 (unsigned long long)rec->start,
5522                                 (unsigned long long)rec->nr);
5523
5524                         if (!fixed && repair) {
5525                                 ret = fixup_extent_refs(trans, root->fs_info,
5526                                                         extent_cache, rec);
5527                                 if (ret)
5528                                         goto repair_abort;
5529                                 fixed = 1;
5530                         }
5531
5532                         err = 1;
5533                 }
5534                 if (!rec->owner_ref_checked) {
5535                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
5536                                 (unsigned long long)rec->start,
5537                                 (unsigned long long)rec->nr);
5538                         if (!fixed && repair) {
5539                                 ret = fixup_extent_refs(trans, root->fs_info,
5540                                                         extent_cache, rec);
5541                                 if (ret)
5542                                         goto repair_abort;
5543                                 fixed = 1;
5544                         }
5545                         err = 1;
5546                 }
5547
5548                 remove_cache_extent(extent_cache, cache);
5549                 free_all_extent_backrefs(rec);
5550                 free(rec);
5551         }
5552 repair_abort:
5553         if (repair) {
5554                 if (ret && ret != -EAGAIN) {
5555                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
5556                         exit(1);
5557                 } else if (!ret) {
5558                         btrfs_fix_block_accounting(trans, root);
5559                 }
5560                 if (err)
5561                         fprintf(stderr, "repaired damaged extent references\n");
5562                 return ret;
5563         }
5564         return err;
5565 }
5566
5567 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
5568 {
5569         u64 stripe_size;
5570
5571         if (type & BTRFS_BLOCK_GROUP_RAID0) {
5572                 stripe_size = length;
5573                 stripe_size /= num_stripes;
5574         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
5575                 stripe_size = length * 2;
5576                 stripe_size /= num_stripes;
5577         } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
5578                 stripe_size = length;
5579                 stripe_size /= (num_stripes - 1);
5580         } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
5581                 stripe_size = length;
5582                 stripe_size /= (num_stripes - 2);
5583         } else {
5584                 stripe_size = length;
5585         }
5586         return stripe_size;
5587 }
5588
5589 static int check_chunk_refs(struct chunk_record *chunk_rec,
5590                             struct block_group_tree *block_group_cache,
5591                             struct device_extent_tree *dev_extent_cache,
5592                             int silent)
5593 {
5594         struct cache_extent *block_group_item;
5595         struct block_group_record *block_group_rec;
5596         struct cache_extent *dev_extent_item;
5597         struct device_extent_record *dev_extent_rec;
5598         u64 devid;
5599         u64 offset;
5600         u64 length;
5601         int i;
5602         int ret = 0;
5603
5604         block_group_item = lookup_cache_extent(&block_group_cache->tree,
5605                                                chunk_rec->offset,
5606                                                chunk_rec->length);
5607         if (block_group_item) {
5608                 block_group_rec = container_of(block_group_item,
5609                                                struct block_group_record,
5610                                                cache);
5611                 if (chunk_rec->length != block_group_rec->offset ||
5612                     chunk_rec->offset != block_group_rec->objectid ||
5613                     chunk_rec->type_flags != block_group_rec->flags) {
5614                         if (!silent)
5615                                 fprintf(stderr,
5616                                         "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
5617                                         chunk_rec->objectid,
5618                                         chunk_rec->type,
5619                                         chunk_rec->offset,
5620                                         chunk_rec->length,
5621                                         chunk_rec->offset,
5622                                         chunk_rec->type_flags,
5623                                         block_group_rec->objectid,
5624                                         block_group_rec->type,
5625                                         block_group_rec->offset,
5626                                         block_group_rec->offset,
5627                                         block_group_rec->objectid,
5628                                         block_group_rec->flags);
5629                         ret = -1;
5630                 } else {
5631                         list_del_init(&block_group_rec->list);
5632                         chunk_rec->bg_rec = block_group_rec;
5633                 }
5634         } else {
5635                 if (!silent)
5636                         fprintf(stderr,
5637                                 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
5638                                 chunk_rec->objectid,
5639                                 chunk_rec->type,
5640                                 chunk_rec->offset,
5641                                 chunk_rec->length,
5642                                 chunk_rec->offset,
5643                                 chunk_rec->type_flags);
5644                 ret = -1;
5645         }
5646
5647         length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
5648                                     chunk_rec->num_stripes);
5649         for (i = 0; i < chunk_rec->num_stripes; ++i) {
5650                 devid = chunk_rec->stripes[i].devid;
5651                 offset = chunk_rec->stripes[i].offset;
5652                 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
5653                                                        devid, offset, length);
5654                 if (dev_extent_item) {
5655                         dev_extent_rec = container_of(dev_extent_item,
5656                                                 struct device_extent_record,
5657                                                 cache);
5658                         if (dev_extent_rec->objectid != devid ||
5659                             dev_extent_rec->offset != offset ||
5660                             dev_extent_rec->chunk_offset != chunk_rec->offset ||
5661                             dev_extent_rec->length != length) {
5662                                 if (!silent)
5663                                         fprintf(stderr,
5664                                                 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
5665                                                 chunk_rec->objectid,
5666                                                 chunk_rec->type,
5667                                                 chunk_rec->offset,
5668                                                 chunk_rec->stripes[i].devid,
5669                                                 chunk_rec->stripes[i].offset,
5670                                                 dev_extent_rec->objectid,
5671                                                 dev_extent_rec->offset,
5672                                                 dev_extent_rec->length);
5673                                 ret = -1;
5674                         } else {
5675                                 list_move(&dev_extent_rec->chunk_list,
5676                                           &chunk_rec->dextents);
5677                         }
5678                 } else {
5679                         if (!silent)
5680                                 fprintf(stderr,
5681                                         "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
5682                                         chunk_rec->objectid,
5683                                         chunk_rec->type,
5684                                         chunk_rec->offset,
5685                                         chunk_rec->stripes[i].devid,
5686                                         chunk_rec->stripes[i].offset);
5687                         ret = -1;
5688                 }
5689         }
5690         return ret;
5691 }
5692
5693 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
5694 int check_chunks(struct cache_tree *chunk_cache,
5695                  struct block_group_tree *block_group_cache,
5696                  struct device_extent_tree *dev_extent_cache,
5697                  struct list_head *good, struct list_head *bad, int silent)
5698 {
5699         struct cache_extent *chunk_item;
5700         struct chunk_record *chunk_rec;
5701         struct block_group_record *bg_rec;
5702         struct device_extent_record *dext_rec;
5703         int err;
5704         int ret = 0;
5705
5706         chunk_item = first_cache_extent(chunk_cache);
5707         while (chunk_item) {
5708                 chunk_rec = container_of(chunk_item, struct chunk_record,
5709                                          cache);
5710                 err = check_chunk_refs(chunk_rec, block_group_cache,
5711                                        dev_extent_cache, silent);
5712                 if (err) {
5713                         ret = err;
5714                         if (bad)
5715                                 list_add_tail(&chunk_rec->list, bad);
5716                 } else {
5717                         if (good)
5718                                 list_add_tail(&chunk_rec->list, good);
5719                 }
5720
5721                 chunk_item = next_cache_extent(chunk_item);
5722         }
5723
5724         list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
5725                 if (!silent)
5726                         fprintf(stderr,
5727                                 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
5728                                 bg_rec->objectid,
5729                                 bg_rec->offset,
5730                                 bg_rec->flags);
5731                 if (!ret)
5732                         ret = 1;
5733         }
5734
5735         list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
5736                             chunk_list) {
5737                 if (!silent)
5738                         fprintf(stderr,
5739                                 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
5740                                 dext_rec->objectid,
5741                                 dext_rec->offset,
5742                                 dext_rec->length);
5743                 if (!ret)
5744                         ret = 1;
5745         }
5746         return ret;
5747 }
5748
5749
5750 static int check_device_used(struct device_record *dev_rec,
5751                              struct device_extent_tree *dext_cache)
5752 {
5753         struct cache_extent *cache;
5754         struct device_extent_record *dev_extent_rec;
5755         u64 total_byte = 0;
5756
5757         cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
5758         while (cache) {
5759                 dev_extent_rec = container_of(cache,
5760                                               struct device_extent_record,
5761                                               cache);
5762                 if (dev_extent_rec->objectid != dev_rec->devid)
5763                         break;
5764
5765                 list_del(&dev_extent_rec->device_list);
5766                 total_byte += dev_extent_rec->length;
5767                 cache = next_cache_extent(cache);
5768         }
5769
5770         if (total_byte != dev_rec->byte_used) {
5771                 fprintf(stderr,
5772                         "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
5773                         total_byte, dev_rec->byte_used, dev_rec->objectid,
5774                         dev_rec->type, dev_rec->offset);
5775                 return -1;
5776         } else {
5777                 return 0;
5778         }
5779 }
5780
5781 /* check btrfs_dev_item -> btrfs_dev_extent */
5782 static int check_devices(struct rb_root *dev_cache,
5783                          struct device_extent_tree *dev_extent_cache)
5784 {
5785         struct rb_node *dev_node;
5786         struct device_record *dev_rec;
5787         struct device_extent_record *dext_rec;
5788         int err;
5789         int ret = 0;
5790
5791         dev_node = rb_first(dev_cache);
5792         while (dev_node) {
5793                 dev_rec = container_of(dev_node, struct device_record, node);
5794                 err = check_device_used(dev_rec, dev_extent_cache);
5795                 if (err)
5796                         ret = err;
5797
5798                 dev_node = rb_next(dev_node);
5799         }
5800         list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
5801                             device_list) {
5802                 fprintf(stderr,
5803                         "Device extent[%llu, %llu, %llu] didn't find its device.\n",
5804                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
5805                 if (!ret)
5806                         ret = 1;
5807         }
5808         return ret;
5809 }
5810
5811 static int check_chunks_and_extents(struct btrfs_root *root)
5812 {
5813         struct rb_root dev_cache;
5814         struct cache_tree chunk_cache;
5815         struct block_group_tree block_group_cache;
5816         struct device_extent_tree dev_extent_cache;
5817         struct cache_tree extent_cache;
5818         struct cache_tree seen;
5819         struct cache_tree pending;
5820         struct cache_tree reada;
5821         struct cache_tree nodes;
5822         struct cache_tree corrupt_blocks;
5823         struct btrfs_path path;
5824         struct btrfs_key key;
5825         struct btrfs_key found_key;
5826         int ret, err = 0;
5827         u64 last = 0;
5828         struct block_info *bits;
5829         int bits_nr;
5830         struct extent_buffer *leaf;
5831         struct btrfs_trans_handle *trans = NULL;
5832         int slot;
5833         struct btrfs_root_item ri;
5834         struct list_head dropping_trees;
5835
5836         dev_cache = RB_ROOT;
5837         cache_tree_init(&chunk_cache);
5838         block_group_tree_init(&block_group_cache);
5839         device_extent_tree_init(&dev_extent_cache);
5840
5841         cache_tree_init(&extent_cache);
5842         cache_tree_init(&seen);
5843         cache_tree_init(&pending);
5844         cache_tree_init(&nodes);
5845         cache_tree_init(&reada);
5846         cache_tree_init(&corrupt_blocks);
5847         INIT_LIST_HEAD(&dropping_trees);
5848
5849         if (repair) {
5850                 trans = btrfs_start_transaction(root, 1);
5851                 if (IS_ERR(trans)) {
5852                         fprintf(stderr, "Error starting transaction\n");
5853                         return PTR_ERR(trans);
5854                 }
5855                 root->fs_info->fsck_extent_cache = &extent_cache;
5856                 root->fs_info->free_extent_hook = free_extent_hook;
5857                 root->fs_info->corrupt_blocks = &corrupt_blocks;
5858         }
5859
5860         bits_nr = 1024;
5861         bits = malloc(bits_nr * sizeof(struct block_info));
5862         if (!bits) {
5863                 perror("malloc");
5864                 exit(1);
5865         }
5866
5867 again:
5868         add_root_to_pending(root->fs_info->tree_root->node,
5869                             &extent_cache, &pending, &seen, &nodes,
5870                             &root->fs_info->tree_root->root_key);
5871
5872         add_root_to_pending(root->fs_info->chunk_root->node,
5873                             &extent_cache, &pending, &seen, &nodes,
5874                             &root->fs_info->chunk_root->root_key);
5875
5876         btrfs_init_path(&path);
5877         key.offset = 0;
5878         key.objectid = 0;
5879         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
5880         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
5881                                         &key, &path, 0, 0);
5882         BUG_ON(ret < 0);
5883         while(1) {
5884                 leaf = path.nodes[0];
5885                 slot = path.slots[0];
5886                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
5887                         ret = btrfs_next_leaf(root, &path);
5888                         if (ret != 0)
5889                                 break;
5890                         leaf = path.nodes[0];
5891                         slot = path.slots[0];
5892                 }
5893                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
5894                 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
5895                         unsigned long offset;
5896                         struct extent_buffer *buf;
5897
5898                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
5899                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
5900                         if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
5901                                 buf = read_tree_block(root->fs_info->tree_root,
5902                                                       btrfs_root_bytenr(&ri),
5903                                                       btrfs_level_size(root,
5904                                                       btrfs_root_level(&ri)),
5905                                                       0);
5906                                 if (!buf) {
5907                                         ret = -EIO;
5908                                         goto out;
5909                                 }
5910                                 add_root_to_pending(buf, &extent_cache,
5911                                                     &pending, &seen, &nodes,
5912                                                     &found_key);
5913                                 free_extent_buffer(buf);
5914                         } else {
5915                                 struct dropping_root_item_record *dri_rec;
5916                                 dri_rec = malloc(sizeof(*dri_rec));
5917                                 if (!dri_rec) {
5918                                         perror("malloc");
5919                                         exit(1);
5920                                 }
5921                                 memcpy(&dri_rec->ri, &ri, sizeof(ri));
5922                                 memcpy(&dri_rec->found_key, &found_key,
5923                                        sizeof(found_key));
5924                                 list_add_tail(&dri_rec->list, &dropping_trees);
5925                         }
5926                 }
5927                 path.slots[0]++;
5928         }
5929         btrfs_release_path(&path);
5930         while (1) {
5931                 ret = run_next_block(trans, root, bits, bits_nr, &last,
5932                                      &pending, &seen, &reada, &nodes,
5933                                      &extent_cache, &chunk_cache, &dev_cache,
5934                                      &block_group_cache, &dev_extent_cache,
5935                                      NULL);
5936                 if (ret != 0)
5937                         break;
5938         }
5939
5940         while (!list_empty(&dropping_trees)) {
5941                 struct dropping_root_item_record *rec;
5942                 struct extent_buffer *buf;
5943                 rec = list_entry(dropping_trees.next,
5944                                  struct dropping_root_item_record, list);
5945                 last = 0;
5946                 if (!bits) {
5947                         perror("realloc");
5948                         exit(1);
5949                 }
5950                 buf = read_tree_block(root->fs_info->tree_root,
5951                                       btrfs_root_bytenr(&rec->ri),
5952                                       btrfs_level_size(root,
5953                                       btrfs_root_level(&rec->ri)), 0);
5954                 if (!buf) {
5955                         ret = -EIO;
5956                         goto out;
5957                 }
5958                 add_root_to_pending(buf, &extent_cache, &pending,
5959                                     &seen, &nodes, &rec->found_key);
5960                 while (1) {
5961                         ret = run_next_block(trans, root, bits, bits_nr, &last,
5962                                              &pending, &seen, &reada,
5963                                              &nodes, &extent_cache,
5964                                              &chunk_cache, &dev_cache,
5965                                              &block_group_cache,
5966                                              &dev_extent_cache,
5967                                              &rec->ri);
5968                         if (ret != 0)
5969                                 break;
5970                 }
5971                 free_extent_buffer(buf);
5972                 list_del(&rec->list);
5973                 free(rec);
5974         }
5975
5976         if (ret >= 0)
5977                 ret = check_extent_refs(trans, root, &extent_cache);
5978         if (ret == -EAGAIN) {
5979                 ret = btrfs_commit_transaction(trans, root);
5980                 if (ret)
5981                         goto out;
5982
5983                 trans = btrfs_start_transaction(root, 1);
5984                 if (IS_ERR(trans)) {
5985                         ret = PTR_ERR(trans);
5986                         goto out;
5987                 }
5988
5989                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
5990                 free_extent_cache_tree(&seen);
5991                 free_extent_cache_tree(&pending);
5992                 free_extent_cache_tree(&reada);
5993                 free_extent_cache_tree(&nodes);
5994                 free_extent_record_cache(root->fs_info, &extent_cache);
5995                 goto again;
5996         }
5997
5998         err = check_chunks(&chunk_cache, &block_group_cache,
5999                            &dev_extent_cache, NULL, NULL, 0);
6000         if (err && !ret)
6001                 ret = err;
6002
6003         err = check_devices(&dev_cache, &dev_extent_cache);
6004         if (err && !ret)
6005                 ret = err;
6006
6007         if (trans) {
6008                 err = btrfs_commit_transaction(trans, root);
6009                 if (!ret)
6010                         ret = err;
6011         }
6012 out:
6013         if (repair) {
6014                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
6015                 root->fs_info->fsck_extent_cache = NULL;
6016                 root->fs_info->free_extent_hook = NULL;
6017                 root->fs_info->corrupt_blocks = NULL;
6018         }
6019         free(bits);
6020         free_chunk_cache_tree(&chunk_cache);
6021         free_device_cache_tree(&dev_cache);
6022         free_block_group_tree(&block_group_cache);
6023         free_device_extent_tree(&dev_extent_cache);
6024         free_extent_cache_tree(&seen);
6025         free_extent_cache_tree(&pending);
6026         free_extent_cache_tree(&reada);
6027         free_extent_cache_tree(&nodes);
6028         return ret;
6029 }
6030
6031 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
6032                            struct btrfs_root *root, int overwrite)
6033 {
6034         struct extent_buffer *c;
6035         struct extent_buffer *old = root->node;
6036         int level;
6037         int ret;
6038         struct btrfs_disk_key disk_key = {0,0,0};
6039
6040         level = 0;
6041
6042         if (overwrite) {
6043                 c = old;
6044                 extent_buffer_get(c);
6045                 goto init;
6046         }
6047         c = btrfs_alloc_free_block(trans, root,
6048                                    btrfs_level_size(root, 0),
6049                                    root->root_key.objectid,
6050                                    &disk_key, level, 0, 0);
6051         if (IS_ERR(c)) {
6052                 c = old;
6053                 extent_buffer_get(c);
6054                 overwrite = 1;
6055         }
6056 init:
6057         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
6058         btrfs_set_header_level(c, level);
6059         btrfs_set_header_bytenr(c, c->start);
6060         btrfs_set_header_generation(c, trans->transid);
6061         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
6062         btrfs_set_header_owner(c, root->root_key.objectid);
6063
6064         write_extent_buffer(c, root->fs_info->fsid,
6065                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
6066
6067         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
6068                             btrfs_header_chunk_tree_uuid(c),
6069                             BTRFS_UUID_SIZE);
6070
6071         btrfs_mark_buffer_dirty(c);
6072         /*
6073          * this case can happen in the following case:
6074          *
6075          * 1.overwrite previous root.
6076          *
6077          * 2.reinit reloc data root, this is because we skip pin
6078          * down reloc data tree before which means we can allocate
6079          * same block bytenr here.
6080          */
6081         if (old->start == c->start) {
6082                 btrfs_set_root_generation(&root->root_item,
6083                                           trans->transid);
6084                 root->root_item.level = btrfs_header_level(root->node);
6085                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
6086                                         &root->root_key, &root->root_item);
6087                 if (ret) {
6088                         free_extent_buffer(c);
6089                         return ret;
6090                 }
6091         }
6092         free_extent_buffer(old);
6093         root->node = c;
6094         add_root_to_dirty_list(root);
6095         return 0;
6096 }
6097
6098 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
6099                                 struct extent_buffer *eb, int tree_root)
6100 {
6101         struct extent_buffer *tmp;
6102         struct btrfs_root_item *ri;
6103         struct btrfs_key key;
6104         u64 bytenr;
6105         u32 leafsize;
6106         int level = btrfs_header_level(eb);
6107         int nritems;
6108         int ret;
6109         int i;
6110
6111         btrfs_pin_extent(fs_info, eb->start, eb->len);
6112
6113         leafsize = btrfs_super_leafsize(fs_info->super_copy);
6114         nritems = btrfs_header_nritems(eb);
6115         for (i = 0; i < nritems; i++) {
6116                 if (level == 0) {
6117                         btrfs_item_key_to_cpu(eb, &key, i);
6118                         if (key.type != BTRFS_ROOT_ITEM_KEY)
6119                                 continue;
6120                         /* Skip the extent root and reloc roots */
6121                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
6122                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
6123                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
6124                                 continue;
6125                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
6126                         bytenr = btrfs_disk_root_bytenr(eb, ri);
6127
6128                         /*
6129                          * If at any point we start needing the real root we
6130                          * will have to build a stump root for the root we are
6131                          * in, but for now this doesn't actually use the root so
6132                          * just pass in extent_root.
6133                          */
6134                         tmp = read_tree_block(fs_info->extent_root, bytenr,
6135                                               leafsize, 0);
6136                         if (!tmp) {
6137                                 fprintf(stderr, "Error reading root block\n");
6138                                 return -EIO;
6139                         }
6140                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
6141                         free_extent_buffer(tmp);
6142                         if (ret)
6143                                 return ret;
6144                 } else {
6145                         bytenr = btrfs_node_blockptr(eb, i);
6146
6147                         /* If we aren't the tree root don't read the block */
6148                         if (level == 1 && !tree_root) {
6149                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
6150                                 continue;
6151                         }
6152
6153                         tmp = read_tree_block(fs_info->extent_root, bytenr,
6154                                               leafsize, 0);
6155                         if (!tmp) {
6156                                 fprintf(stderr, "Error reading tree block\n");
6157                                 return -EIO;
6158                         }
6159                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
6160                         free_extent_buffer(tmp);
6161                         if (ret)
6162                                 return ret;
6163                 }
6164         }
6165
6166         return 0;
6167 }
6168
6169 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
6170 {
6171         int ret;
6172
6173         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
6174         if (ret)
6175                 return ret;
6176
6177         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
6178 }
6179
6180 static int reset_block_groups(struct btrfs_fs_info *fs_info)
6181 {
6182         struct btrfs_block_group_cache *cache;
6183         struct btrfs_path *path;
6184         struct extent_buffer *leaf;
6185         struct btrfs_chunk *chunk;
6186         struct btrfs_key key;
6187         int ret;
6188         u64 start;
6189
6190         path = btrfs_alloc_path();
6191         if (!path)
6192                 return -ENOMEM;
6193
6194         key.objectid = 0;
6195         key.type = BTRFS_CHUNK_ITEM_KEY;
6196         key.offset = 0;
6197
6198         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
6199         if (ret < 0) {
6200                 btrfs_free_path(path);
6201                 return ret;
6202         }
6203
6204         /*
6205          * We do this in case the block groups were screwed up and had alloc
6206          * bits that aren't actually set on the chunks.  This happens with
6207          * restored images every time and could happen in real life I guess.
6208          */
6209         fs_info->avail_data_alloc_bits = 0;
6210         fs_info->avail_metadata_alloc_bits = 0;
6211         fs_info->avail_system_alloc_bits = 0;
6212
6213         /* First we need to create the in-memory block groups */
6214         while (1) {
6215                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6216                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
6217                         if (ret < 0) {
6218                                 btrfs_free_path(path);
6219                                 return ret;
6220                         }
6221                         if (ret) {
6222                                 ret = 0;
6223                                 break;
6224                         }
6225                 }
6226                 leaf = path->nodes[0];
6227                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6228                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6229                         path->slots[0]++;
6230                         continue;
6231                 }
6232
6233                 chunk = btrfs_item_ptr(leaf, path->slots[0],
6234                                        struct btrfs_chunk);
6235                 btrfs_add_block_group(fs_info, 0,
6236                                       btrfs_chunk_type(leaf, chunk),
6237                                       key.objectid, key.offset,
6238                                       btrfs_chunk_length(leaf, chunk));
6239                 set_extent_dirty(&fs_info->free_space_cache, key.offset,
6240                                  key.offset + btrfs_chunk_length(leaf, chunk),
6241                                  GFP_NOFS);
6242                 path->slots[0]++;
6243         }
6244         start = 0;
6245         while (1) {
6246                 cache = btrfs_lookup_first_block_group(fs_info, start);
6247                 if (!cache)
6248                         break;
6249                 cache->cached = 1;
6250                 start = cache->key.objectid + cache->key.offset;
6251         }
6252
6253         btrfs_free_path(path);
6254         return 0;
6255 }
6256
6257 static int reset_balance(struct btrfs_trans_handle *trans,
6258                          struct btrfs_fs_info *fs_info)
6259 {
6260         struct btrfs_root *root = fs_info->tree_root;
6261         struct btrfs_path *path;
6262         struct extent_buffer *leaf;
6263         struct btrfs_key key;
6264         int del_slot, del_nr = 0;
6265         int ret;
6266         int found = 0;
6267
6268         path = btrfs_alloc_path();
6269         if (!path)
6270                 return -ENOMEM;
6271
6272         key.objectid = BTRFS_BALANCE_OBJECTID;
6273         key.type = BTRFS_BALANCE_ITEM_KEY;
6274         key.offset = 0;
6275
6276         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6277         if (ret) {
6278                 if (ret > 0)
6279                         ret = 0;
6280                 if (!ret)
6281                         goto reinit_data_reloc;
6282                 else
6283                         goto out;
6284         }
6285
6286         ret = btrfs_del_item(trans, root, path);
6287         if (ret)
6288                 goto out;
6289         btrfs_release_path(path);
6290
6291         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
6292         key.type = BTRFS_ROOT_ITEM_KEY;
6293         key.offset = 0;
6294
6295         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6296         if (ret < 0)
6297                 goto out;
6298         while (1) {
6299                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6300                         if (!found)
6301                                 break;
6302
6303                         if (del_nr) {
6304                                 ret = btrfs_del_items(trans, root, path,
6305                                                       del_slot, del_nr);
6306                                 del_nr = 0;
6307                                 if (ret)
6308                                         goto out;
6309                         }
6310                         key.offset++;
6311                         btrfs_release_path(path);
6312
6313                         found = 0;
6314                         ret = btrfs_search_slot(trans, root, &key, path,
6315                                                 -1, 1);
6316                         if (ret < 0)
6317                                 goto out;
6318                         continue;
6319                 }
6320                 found = 1;
6321                 leaf = path->nodes[0];
6322                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6323                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
6324                         break;
6325                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
6326                         path->slots[0]++;
6327                         continue;
6328                 }
6329                 if (!del_nr) {
6330                         del_slot = path->slots[0];
6331                         del_nr = 1;
6332                 } else {
6333                         del_nr++;
6334                 }
6335                 path->slots[0]++;
6336         }
6337
6338         if (del_nr) {
6339                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
6340                 if (ret)
6341                         goto out;
6342         }
6343         btrfs_release_path(path);
6344
6345 reinit_data_reloc:
6346         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
6347         key.type = BTRFS_ROOT_ITEM_KEY;
6348         key.offset = (u64)-1;
6349         root = btrfs_read_fs_root(fs_info, &key);
6350         if (IS_ERR(root)) {
6351                 fprintf(stderr, "Error reading data reloc tree\n");
6352                 return PTR_ERR(root);
6353         }
6354         root->track_dirty = 1;
6355         if (root->last_trans != trans->transid) {
6356                 root->last_trans = trans->transid;
6357                 root->commit_root = root->node;
6358                 extent_buffer_get(root->node);
6359         }
6360         ret = btrfs_fsck_reinit_root(trans, root, 0);
6361         if (ret)
6362                 goto out;
6363         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
6364 out:
6365         btrfs_free_path(path);
6366         return ret;
6367 }
6368
6369 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
6370                               struct btrfs_fs_info *fs_info)
6371 {
6372         u64 start = 0;
6373         int ret;
6374
6375         /*
6376          * The only reason we don't do this is because right now we're just
6377          * walking the trees we find and pinning down their bytes, we don't look
6378          * at any of the leaves.  In order to do mixed groups we'd have to check
6379          * the leaves of any fs roots and pin down the bytes for any file
6380          * extents we find.  Not hard but why do it if we don't have to?
6381          */
6382         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
6383                 fprintf(stderr, "We don't support re-initing the extent tree "
6384                         "for mixed block groups yet, please notify a btrfs "
6385                         "developer you want to do this so they can add this "
6386                         "functionality.\n");
6387                 return -EINVAL;
6388         }
6389
6390         /*
6391          * first we need to walk all of the trees except the extent tree and pin
6392          * down the bytes that are in use so we don't overwrite any existing
6393          * metadata.
6394          */
6395         ret = pin_metadata_blocks(fs_info);
6396         if (ret) {
6397                 fprintf(stderr, "error pinning down used bytes\n");
6398                 return ret;
6399         }
6400
6401         /*
6402          * Need to drop all the block groups since we're going to recreate all
6403          * of them again.
6404          */
6405         btrfs_free_block_groups(fs_info);
6406         ret = reset_block_groups(fs_info);
6407         if (ret) {
6408                 fprintf(stderr, "error resetting the block groups\n");
6409                 return ret;
6410         }
6411
6412         /* Ok we can allocate now, reinit the extent root */
6413         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
6414         if (ret) {
6415                 fprintf(stderr, "extent root initialization failed\n");
6416                 /*
6417                  * When the transaction code is updated we should end the
6418                  * transaction, but for now progs only knows about commit so
6419                  * just return an error.
6420                  */
6421                 return ret;
6422         }
6423
6424         /*
6425          * Now we have all the in-memory block groups setup so we can make
6426          * allocations properly, and the metadata we care about is safe since we
6427          * pinned all of it above.
6428          */
6429         while (1) {
6430                 struct btrfs_block_group_cache *cache;
6431
6432                 cache = btrfs_lookup_first_block_group(fs_info, start);
6433                 if (!cache)
6434                         break;
6435                 start = cache->key.objectid + cache->key.offset;
6436                 ret = btrfs_insert_item(trans, fs_info->extent_root,
6437                                         &cache->key, &cache->item,
6438                                         sizeof(cache->item));
6439                 if (ret) {
6440                         fprintf(stderr, "Error adding block group\n");
6441                         return ret;
6442                 }
6443                 btrfs_extent_post_op(trans, fs_info->extent_root);
6444         }
6445
6446         ret = reset_balance(trans, fs_info);
6447         if (ret)
6448                 fprintf(stderr, "error reseting the pending balance\n");
6449
6450         return ret;
6451 }
6452
6453 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
6454 {
6455         struct btrfs_path *path;
6456         struct btrfs_trans_handle *trans;
6457         struct btrfs_key key;
6458         int ret;
6459
6460         printf("Recowing metadata block %llu\n", eb->start);
6461         key.objectid = btrfs_header_owner(eb);
6462         key.type = BTRFS_ROOT_ITEM_KEY;
6463         key.offset = (u64)-1;
6464
6465         root = btrfs_read_fs_root(root->fs_info, &key);
6466         if (IS_ERR(root)) {
6467                 fprintf(stderr, "Couldn't find owner root %llu\n",
6468                         key.objectid);
6469                 return PTR_ERR(root);
6470         }
6471
6472         path = btrfs_alloc_path();
6473         if (!path)
6474                 return -ENOMEM;
6475
6476         trans = btrfs_start_transaction(root, 1);
6477         if (IS_ERR(trans)) {
6478                 btrfs_free_path(path);
6479                 return PTR_ERR(trans);
6480         }
6481
6482         path->lowest_level = btrfs_header_level(eb);
6483         if (path->lowest_level)
6484                 btrfs_node_key_to_cpu(eb, &key, 0);
6485         else
6486                 btrfs_item_key_to_cpu(eb, &key, 0);
6487
6488         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6489         btrfs_commit_transaction(trans, root);
6490         btrfs_free_path(path);
6491         return ret;
6492 }
6493
6494 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
6495 {
6496         struct btrfs_path *path;
6497         struct btrfs_trans_handle *trans;
6498         struct btrfs_key key;
6499         int ret;
6500
6501         printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
6502                bad->key.type, bad->key.offset);
6503         key.objectid = bad->root_id;
6504         key.type = BTRFS_ROOT_ITEM_KEY;
6505         key.offset = (u64)-1;
6506
6507         root = btrfs_read_fs_root(root->fs_info, &key);
6508         if (IS_ERR(root)) {
6509                 fprintf(stderr, "Couldn't find owner root %llu\n",
6510                         key.objectid);
6511                 return PTR_ERR(root);
6512         }
6513
6514         path = btrfs_alloc_path();
6515         if (!path)
6516                 return -ENOMEM;
6517
6518         trans = btrfs_start_transaction(root, 1);
6519         if (IS_ERR(trans)) {
6520                 btrfs_free_path(path);
6521                 return PTR_ERR(trans);
6522         }
6523
6524         ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
6525         if (ret) {
6526                 if (ret > 0)
6527                         ret = 0;
6528                 goto out;
6529         }
6530         ret = btrfs_del_item(trans, root, path);
6531 out:
6532         btrfs_commit_transaction(trans, root);
6533         btrfs_free_path(path);
6534         return ret;
6535 }
6536
6537 static struct option long_options[] = {
6538         { "super", 1, NULL, 's' },
6539         { "repair", 0, NULL, 0 },
6540         { "init-csum-tree", 0, NULL, 0 },
6541         { "init-extent-tree", 0, NULL, 0 },
6542         { "check-data-csum", 0, NULL, 0 },
6543         { "backup", 0, NULL, 0 },
6544         { "qgroup-report", 0, NULL, 'Q' },
6545         { NULL, 0, NULL, 0}
6546 };
6547
6548 const char * const cmd_check_usage[] = {
6549         "btrfs check [options] <device>",
6550         "Check an unmounted btrfs filesystem.",
6551         "",
6552         "-s|--super <superblock>     use this superblock copy",
6553         "-b|--backup                 use the backup root copy",
6554         "--repair                    try to repair the filesystem",
6555         "--init-csum-tree            create a new CRC tree",
6556         "--init-extent-tree          create a new extent tree",
6557         "--check-data-csum           verify checkums of data blocks",
6558         "--qgroup-report             print a report on qgroup consistency",
6559         NULL
6560 };
6561
6562 int cmd_check(int argc, char **argv)
6563 {
6564         struct cache_tree root_cache;
6565         struct btrfs_root *root;
6566         struct btrfs_fs_info *info;
6567         u64 bytenr = 0;
6568         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
6569         int ret;
6570         u64 num;
6571         int option_index = 0;
6572         int init_csum_tree = 0;
6573         int qgroup_report = 0;
6574         enum btrfs_open_ctree_flags ctree_flags =
6575                 OPEN_CTREE_PARTIAL | OPEN_CTREE_EXCLUSIVE;
6576
6577         while(1) {
6578                 int c;
6579                 c = getopt_long(argc, argv, "as:b", long_options,
6580                                 &option_index);
6581                 if (c < 0)
6582                         break;
6583                 switch(c) {
6584                         case 'a': /* ignored */ break;
6585                         case 'b':
6586                                 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
6587                                 break;
6588                         case 's':
6589                                 num = arg_strtou64(optarg);
6590                                 if (num >= BTRFS_SUPER_MIRROR_MAX) {
6591                                         fprintf(stderr,
6592                                                 "ERROR: super mirror should be less than: %d\n",
6593                                                 BTRFS_SUPER_MIRROR_MAX);
6594                                         exit(1);
6595                                 }
6596                                 bytenr = btrfs_sb_offset(((int)num));
6597                                 printf("using SB copy %llu, bytenr %llu\n", num,
6598                                        (unsigned long long)bytenr);
6599                                 break;
6600                         case 'Q':
6601                                 qgroup_report = 1;
6602                                 break;
6603                         case '?':
6604                         case 'h':
6605                                 usage(cmd_check_usage);
6606                 }
6607                 if (option_index == 1) {
6608                         printf("enabling repair mode\n");
6609                         repair = 1;
6610                         ctree_flags |= OPEN_CTREE_WRITES;
6611                 } else if (option_index == 2) {
6612                         printf("Creating a new CRC tree\n");
6613                         init_csum_tree = 1;
6614                         repair = 1;
6615                         ctree_flags |= OPEN_CTREE_WRITES;
6616                 } else if (option_index == 3) {
6617                         init_extent_tree = 1;
6618                         ctree_flags |= (OPEN_CTREE_WRITES |
6619                                         OPEN_CTREE_NO_BLOCK_GROUPS);
6620                         repair = 1;
6621                 } else if (option_index == 4) {
6622                         check_data_csum = 1;
6623                 }
6624         }
6625         argc = argc - optind;
6626
6627         if (argc != 1)
6628                 usage(cmd_check_usage);
6629
6630         radix_tree_init();
6631         cache_tree_init(&root_cache);
6632
6633         if((ret = check_mounted(argv[optind])) < 0) {
6634                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
6635                 goto err_out;
6636         } else if(ret) {
6637                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
6638                 ret = -EBUSY;
6639                 goto err_out;
6640         }
6641
6642         info = open_ctree_fs_info(argv[optind], bytenr, 0, ctree_flags);
6643         if (!info) {
6644                 fprintf(stderr, "Couldn't open file system\n");
6645                 ret = -EIO;
6646                 goto err_out;
6647         }
6648
6649         root = info->fs_root;
6650         uuid_unparse(info->super_copy->fsid, uuidbuf);
6651         if (qgroup_report) {
6652                 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
6653                        uuidbuf);
6654                 ret = qgroup_verify_all(info);
6655                 if (ret == 0)
6656                         print_qgroup_report(1);
6657                 goto close_out;
6658         }
6659         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
6660
6661         if (!extent_buffer_uptodate(info->tree_root->node) ||
6662             !extent_buffer_uptodate(info->dev_root->node) ||
6663             !extent_buffer_uptodate(info->chunk_root->node)) {
6664                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
6665                 ret = -EIO;
6666                 goto close_out;
6667         }
6668
6669         if (init_extent_tree || init_csum_tree) {
6670                 struct btrfs_trans_handle *trans;
6671
6672                 trans = btrfs_start_transaction(info->extent_root, 0);
6673                 if (IS_ERR(trans)) {
6674                         fprintf(stderr, "Error starting transaction\n");
6675                         ret = PTR_ERR(trans);
6676                         goto close_out;
6677                 }
6678
6679                 if (init_extent_tree) {
6680                         printf("Creating a new extent tree\n");
6681                         ret = reinit_extent_tree(trans, info);
6682                         if (ret)
6683                                 goto close_out;
6684                 }
6685
6686                 if (init_csum_tree) {
6687                         fprintf(stderr, "Reinit crc root\n");
6688                         ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
6689                         if (ret) {
6690                                 fprintf(stderr, "crc root initialization failed\n");
6691                                 ret = -EIO;
6692                                 goto close_out;
6693                         }
6694                 }
6695                 /*
6696                  * Ok now we commit and run the normal fsck, which will add
6697                  * extent entries for all of the items it finds.
6698                  */
6699                 ret = btrfs_commit_transaction(trans, info->extent_root);
6700                 if (ret)
6701                         goto close_out;
6702         }
6703         if (!extent_buffer_uptodate(info->extent_root->node)) {
6704                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
6705                 ret = -EIO;
6706                 goto close_out;
6707         }
6708
6709         fprintf(stderr, "checking extents\n");
6710         ret = check_chunks_and_extents(root);
6711         if (ret)
6712                 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
6713
6714         fprintf(stderr, "checking free space cache\n");
6715         ret = check_space_cache(root);
6716         if (ret)
6717                 goto out;
6718
6719         /*
6720          * We used to have to have these hole extents in between our real
6721          * extents so if we don't have this flag set we need to make sure there
6722          * are no gaps in the file extents for inodes, otherwise we can just
6723          * ignore it when this happens.
6724          */
6725         no_holes = btrfs_fs_incompat(root->fs_info,
6726                                      BTRFS_FEATURE_INCOMPAT_NO_HOLES);
6727         fprintf(stderr, "checking fs roots\n");
6728         ret = check_fs_roots(root, &root_cache);
6729         if (ret)
6730                 goto out;
6731
6732         fprintf(stderr, "checking csums\n");
6733         ret = check_csums(root);
6734         if (ret)
6735                 goto out;
6736
6737         fprintf(stderr, "checking root refs\n");
6738         ret = check_root_refs(root, &root_cache);
6739         if (ret)
6740                 goto out;
6741
6742         while (repair && !list_empty(&root->fs_info->recow_ebs)) {
6743                 struct extent_buffer *eb;
6744
6745                 eb = list_first_entry(&root->fs_info->recow_ebs,
6746                                       struct extent_buffer, recow);
6747                 ret = recow_extent_buffer(root, eb);
6748                 if (ret)
6749                         break;
6750         }
6751
6752         while (!list_empty(&delete_items)) {
6753                 struct bad_item *bad;
6754
6755                 bad = list_first_entry(&delete_items, struct bad_item, list);
6756                 list_del_init(&bad->list);
6757                 if (repair)
6758                         ret = delete_bad_item(root, bad);
6759                 free(bad);
6760         }
6761
6762         if (info->quota_enabled) {
6763                 int err;
6764                 fprintf(stderr, "checking quota groups\n");
6765                 err = qgroup_verify_all(info);
6766                 if (err)
6767                         goto out;
6768         }
6769
6770         if (!list_empty(&root->fs_info->recow_ebs)) {
6771                 fprintf(stderr, "Transid errors in file system\n");
6772                 ret = 1;
6773         }
6774 out:
6775         print_qgroup_report(0);
6776         if (found_old_backref) { /*
6777                  * there was a disk format change when mixed
6778                  * backref was in testing tree. The old format
6779                  * existed about one week.
6780                  */
6781                 printf("\n * Found old mixed backref format. "
6782                        "The old format is not supported! *"
6783                        "\n * Please mount the FS in readonly mode, "
6784                        "backup data and re-format the FS. *\n\n");
6785                 ret = 1;
6786         }
6787         printf("found %llu bytes used err is %d\n",
6788                (unsigned long long)bytes_used, ret);
6789         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
6790         printf("total tree bytes: %llu\n",
6791                (unsigned long long)total_btree_bytes);
6792         printf("total fs tree bytes: %llu\n",
6793                (unsigned long long)total_fs_tree_bytes);
6794         printf("total extent tree bytes: %llu\n",
6795                (unsigned long long)total_extent_tree_bytes);
6796         printf("btree space waste bytes: %llu\n",
6797                (unsigned long long)btree_space_waste);
6798         printf("file data blocks allocated: %llu\n referenced %llu\n",
6799                 (unsigned long long)data_bytes_allocated,
6800                 (unsigned long long)data_bytes_referenced);
6801         printf("%s\n", BTRFS_BUILD_VERSION);
6802
6803         free_root_recs_tree(&root_cache);
6804 close_out:
6805         close_ctree(root);
6806 err_out:
6807         return ret;
6808 }