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