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