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