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