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