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