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