Btrfs-progs: fix reference check for roots in btrfsck
[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 "kerncompat.h"
31 #include "ctree.h"
32 #include "volumes.h"
33 #include "repair.h"
34 #include "disk-io.h"
35 #include "print-tree.h"
36 #include "transaction.h"
37 #include "list.h"
38 #include "version.h"
39 #include "utils.h"
40 #include "commands.h"
41 #include "free-space-cache.h"
42
43 static u64 bytes_used = 0;
44 static u64 total_csum_bytes = 0;
45 static u64 total_btree_bytes = 0;
46 static u64 total_fs_tree_bytes = 0;
47 static u64 total_extent_tree_bytes = 0;
48 static u64 btree_space_waste = 0;
49 static u64 data_bytes_allocated = 0;
50 static u64 data_bytes_referenced = 0;
51 static int found_old_backref = 0;
52 static LIST_HEAD(duplicate_extents);
53
54 struct extent_backref {
55         struct list_head list;
56         unsigned int is_data:1;
57         unsigned int found_extent_tree:1;
58         unsigned int full_backref:1;
59         unsigned int found_ref:1;
60 };
61
62 struct data_backref {
63         struct extent_backref node;
64         union {
65                 u64 parent;
66                 u64 root;
67         };
68         u64 owner;
69         u64 offset;
70         u64 disk_bytenr;
71         u64 bytes;
72         u64 ram_bytes;
73         u32 num_refs;
74         u32 found_ref;
75 };
76
77 struct tree_backref {
78         struct extent_backref node;
79         union {
80                 u64 parent;
81                 u64 root;
82         };
83 };
84
85 struct extent_record {
86         struct list_head backrefs;
87         struct list_head dups;
88         struct list_head list;
89         struct cache_extent cache;
90         struct btrfs_disk_key parent_key;
91         unsigned int found_rec;
92         u64 start;
93         u64 max_size;
94         u64 nr;
95         u64 refs;
96         u64 extent_item_refs;
97         u64 generation;
98         u64 info_objectid;
99         u64 num_duplicates;
100         u8 info_level;
101         unsigned int content_checked:1;
102         unsigned int owner_ref_checked:1;
103         unsigned int is_root:1;
104         unsigned int metadata:1;
105 };
106
107 struct inode_backref {
108         struct list_head list;
109         unsigned int found_dir_item:1;
110         unsigned int found_dir_index:1;
111         unsigned int found_inode_ref:1;
112         unsigned int filetype:8;
113         int errors;
114         unsigned int ref_type;
115         u64 dir;
116         u64 index;
117         u16 namelen;
118         char name[0];
119 };
120
121 #define REF_ERR_NO_DIR_ITEM             (1 << 0)
122 #define REF_ERR_NO_DIR_INDEX            (1 << 1)
123 #define REF_ERR_NO_INODE_REF            (1 << 2)
124 #define REF_ERR_DUP_DIR_ITEM            (1 << 3)
125 #define REF_ERR_DUP_DIR_INDEX           (1 << 4)
126 #define REF_ERR_DUP_INODE_REF           (1 << 5)
127 #define REF_ERR_INDEX_UNMATCH           (1 << 6)
128 #define REF_ERR_FILETYPE_UNMATCH        (1 << 7)
129 #define REF_ERR_NAME_TOO_LONG           (1 << 8) // 100
130 #define REF_ERR_NO_ROOT_REF             (1 << 9)
131 #define REF_ERR_NO_ROOT_BACKREF         (1 << 10)
132 #define REF_ERR_DUP_ROOT_REF            (1 << 11)
133 #define REF_ERR_DUP_ROOT_BACKREF        (1 << 12)
134
135 struct inode_record {
136         struct list_head backrefs;
137         unsigned int checked:1;
138         unsigned int merging:1;
139         unsigned int found_inode_item:1;
140         unsigned int found_dir_item:1;
141         unsigned int found_file_extent:1;
142         unsigned int found_csum_item:1;
143         unsigned int some_csum_missing:1;
144         unsigned int nodatasum:1;
145         int errors;
146
147         u64 ino;
148         u32 nlink;
149         u32 imode;
150         u64 isize;
151         u64 nbytes;
152
153         u32 found_link;
154         u64 found_size;
155         u64 extent_start;
156         u64 extent_end;
157         u64 first_extent_gap;
158
159         u32 refs;
160 };
161
162 #define I_ERR_NO_INODE_ITEM             (1 << 0)
163 #define I_ERR_NO_ORPHAN_ITEM            (1 << 1)
164 #define I_ERR_DUP_INODE_ITEM            (1 << 2)
165 #define I_ERR_DUP_DIR_INDEX             (1 << 3)
166 #define I_ERR_ODD_DIR_ITEM              (1 << 4)
167 #define I_ERR_ODD_FILE_EXTENT           (1 << 5)
168 #define I_ERR_BAD_FILE_EXTENT           (1 << 6)
169 #define I_ERR_FILE_EXTENT_OVERLAP       (1 << 7)
170 #define I_ERR_FILE_EXTENT_DISCOUNT      (1 << 8) // 100
171 #define I_ERR_DIR_ISIZE_WRONG           (1 << 9)
172 #define I_ERR_FILE_NBYTES_WRONG         (1 << 10) // 400
173 #define I_ERR_ODD_CSUM_ITEM             (1 << 11)
174 #define I_ERR_SOME_CSUM_MISSING         (1 << 12)
175 #define I_ERR_LINK_COUNT_WRONG          (1 << 13)
176
177 struct root_backref {
178         struct list_head list;
179         unsigned int found_dir_item:1;
180         unsigned int found_dir_index:1;
181         unsigned int found_back_ref:1;
182         unsigned int found_forward_ref:1;
183         unsigned int reachable:1;
184         int errors;
185         u64 ref_root;
186         u64 dir;
187         u64 index;
188         u16 namelen;
189         char name[0];
190 };
191
192 struct root_record {
193         struct list_head backrefs;
194         struct cache_extent cache;
195         unsigned int found_root_item:1;
196         u64 objectid;
197         u32 found_ref;
198 };
199
200 struct ptr_node {
201         struct cache_extent cache;
202         void *data;
203 };
204
205 struct shared_node {
206         struct cache_extent cache;
207         struct cache_tree root_cache;
208         struct cache_tree inode_cache;
209         struct inode_record *current;
210         u32 refs;
211 };
212
213 struct block_info {
214         u64 start;
215         u32 size;
216 };
217
218 struct walk_control {
219         struct cache_tree shared;
220         struct shared_node *nodes[BTRFS_MAX_LEVEL];
221         int active_node;
222         int root_level;
223 };
224
225 static u8 imode_to_type(u32 imode)
226 {
227 #define S_SHIFT 12
228         static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
229                 [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
230                 [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
231                 [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
232                 [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
233                 [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
234                 [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
235                 [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
236         };
237
238         return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
239 #undef S_SHIFT
240 }
241
242 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
243 {
244         struct inode_record *rec;
245         struct inode_backref *backref;
246         struct inode_backref *orig;
247         size_t size;
248
249         rec = malloc(sizeof(*rec));
250         memcpy(rec, orig_rec, sizeof(*rec));
251         rec->refs = 1;
252         INIT_LIST_HEAD(&rec->backrefs);
253
254         list_for_each_entry(orig, &orig_rec->backrefs, list) {
255                 size = sizeof(*orig) + orig->namelen + 1;
256                 backref = malloc(size);
257                 memcpy(backref, orig, size);
258                 list_add_tail(&backref->list, &rec->backrefs);
259         }
260         return rec;
261 }
262
263 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
264                                           u64 ino, int mod)
265 {
266         struct ptr_node *node;
267         struct cache_extent *cache;
268         struct inode_record *rec = NULL;
269         int ret;
270
271         cache = find_cache_extent(inode_cache, ino, 1);
272         if (cache) {
273                 node = container_of(cache, struct ptr_node, cache);
274                 rec = node->data;
275                 if (mod && rec->refs > 1) {
276                         node->data = clone_inode_rec(rec);
277                         rec->refs--;
278                         rec = node->data;
279                 }
280         } else if (mod) {
281                 rec = calloc(1, sizeof(*rec));
282                 rec->ino = ino;
283                 rec->extent_start = (u64)-1;
284                 rec->first_extent_gap = (u64)-1;
285                 rec->refs = 1;
286                 INIT_LIST_HEAD(&rec->backrefs);
287
288                 node = malloc(sizeof(*node));
289                 node->cache.start = ino;
290                 node->cache.size = 1;
291                 node->data = rec;
292
293                 if (ino == BTRFS_FREE_INO_OBJECTID)
294                         rec->found_link = 1;
295
296                 ret = insert_existing_cache_extent(inode_cache, &node->cache);
297                 BUG_ON(ret);
298         }
299         return rec;
300 }
301
302 static void free_inode_rec(struct inode_record *rec)
303 {
304         struct inode_backref *backref;
305
306         if (--rec->refs > 0)
307                 return;
308
309         while (!list_empty(&rec->backrefs)) {
310                 backref = list_entry(rec->backrefs.next,
311                                      struct inode_backref, list);
312                 list_del(&backref->list);
313                 free(backref);
314         }
315         free(rec);
316 }
317
318 static int can_free_inode_rec(struct inode_record *rec)
319 {
320         if (!rec->errors && rec->checked && rec->found_inode_item &&
321             rec->nlink == rec->found_link && list_empty(&rec->backrefs))
322                 return 1;
323         return 0;
324 }
325
326 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
327                                  struct inode_record *rec)
328 {
329         struct cache_extent *cache;
330         struct inode_backref *tmp, *backref;
331         struct ptr_node *node;
332         unsigned char filetype;
333
334         if (!rec->found_inode_item)
335                 return;
336
337         filetype = imode_to_type(rec->imode);
338         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
339                 if (backref->found_dir_item && backref->found_dir_index) {
340                         if (backref->filetype != filetype)
341                                 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
342                         if (!backref->errors && backref->found_inode_ref) {
343                                 list_del(&backref->list);
344                                 free(backref);
345                         }
346                 }
347         }
348
349         if (!rec->checked || rec->merging)
350                 return;
351
352         if (S_ISDIR(rec->imode)) {
353                 if (rec->found_size != rec->isize)
354                         rec->errors |= I_ERR_DIR_ISIZE_WRONG;
355                 if (rec->found_file_extent)
356                         rec->errors |= I_ERR_ODD_FILE_EXTENT;
357         } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
358                 if (rec->found_dir_item)
359                         rec->errors |= I_ERR_ODD_DIR_ITEM;
360                 if (rec->found_size != rec->nbytes)
361                         rec->errors |= I_ERR_FILE_NBYTES_WRONG;
362                 if (rec->extent_start == (u64)-1 || rec->extent_start > 0)
363                         rec->first_extent_gap = 0;
364                 if (rec->nlink > 0 && (rec->extent_end < rec->isize ||
365                     rec->first_extent_gap < rec->isize))
366                         rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
367         }
368
369         if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
370                 if (rec->found_csum_item && rec->nodatasum)
371                         rec->errors |= I_ERR_ODD_CSUM_ITEM;
372                 if (rec->some_csum_missing && !rec->nodatasum)
373                         rec->errors |= I_ERR_SOME_CSUM_MISSING;
374         }
375
376         BUG_ON(rec->refs != 1);
377         if (can_free_inode_rec(rec)) {
378                 cache = find_cache_extent(inode_cache, rec->ino, 1);
379                 node = container_of(cache, struct ptr_node, cache);
380                 BUG_ON(node->data != rec);
381                 remove_cache_extent(inode_cache, &node->cache);
382                 free(node);
383                 free_inode_rec(rec);
384         }
385 }
386
387 static int check_orphan_item(struct btrfs_root *root, u64 ino)
388 {
389         struct btrfs_path path;
390         struct btrfs_key key;
391         int ret;
392
393         key.objectid = BTRFS_ORPHAN_OBJECTID;
394         key.type = BTRFS_ORPHAN_ITEM_KEY;
395         key.offset = ino;
396
397         btrfs_init_path(&path);
398         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
399         btrfs_release_path(root, &path);
400         if (ret > 0)
401                 ret = -ENOENT;
402         return ret;
403 }
404
405 static int process_inode_item(struct extent_buffer *eb,
406                               int slot, struct btrfs_key *key,
407                               struct shared_node *active_node)
408 {
409         struct inode_record *rec;
410         struct btrfs_inode_item *item;
411
412         rec = active_node->current;
413         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
414         if (rec->found_inode_item) {
415                 rec->errors |= I_ERR_DUP_INODE_ITEM;
416                 return 1;
417         }
418         item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
419         rec->nlink = btrfs_inode_nlink(eb, item);
420         rec->isize = btrfs_inode_size(eb, item);
421         rec->nbytes = btrfs_inode_nbytes(eb, item);
422         rec->imode = btrfs_inode_mode(eb, item);
423         if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
424                 rec->nodatasum = 1;
425         rec->found_inode_item = 1;
426         if (rec->nlink == 0)
427                 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
428         maybe_free_inode_rec(&active_node->inode_cache, rec);
429         return 0;
430 }
431
432 static struct inode_backref *get_inode_backref(struct inode_record *rec,
433                                                 const char *name,
434                                                 int namelen, u64 dir)
435 {
436         struct inode_backref *backref;
437
438         list_for_each_entry(backref, &rec->backrefs, list) {
439                 if (backref->dir != dir || backref->namelen != namelen)
440                         continue;
441                 if (memcmp(name, backref->name, namelen))
442                         continue;
443                 return backref;
444         }
445
446         backref = malloc(sizeof(*backref) + namelen + 1);
447         memset(backref, 0, sizeof(*backref));
448         backref->dir = dir;
449         backref->namelen = namelen;
450         memcpy(backref->name, name, namelen);
451         backref->name[namelen] = '\0';
452         list_add_tail(&backref->list, &rec->backrefs);
453         return backref;
454 }
455
456 static int add_inode_backref(struct cache_tree *inode_cache,
457                              u64 ino, u64 dir, u64 index,
458                              const char *name, int namelen,
459                              int filetype, int itemtype, int errors)
460 {
461         struct inode_record *rec;
462         struct inode_backref *backref;
463
464         rec = get_inode_rec(inode_cache, ino, 1);
465         backref = get_inode_backref(rec, name, namelen, dir);
466         if (errors)
467                 backref->errors |= errors;
468         if (itemtype == BTRFS_DIR_INDEX_KEY) {
469                 if (backref->found_dir_index)
470                         backref->errors |= REF_ERR_DUP_DIR_INDEX;
471                 if (backref->found_inode_ref && backref->index != index)
472                         backref->errors |= REF_ERR_INDEX_UNMATCH;
473                 if (backref->found_dir_item && backref->filetype != filetype)
474                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
475
476                 backref->index = index;
477                 backref->filetype = filetype;
478                 backref->found_dir_index = 1;
479         } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
480                 rec->found_link++;
481                 if (backref->found_dir_item)
482                         backref->errors |= REF_ERR_DUP_DIR_ITEM;
483                 if (backref->found_dir_index && backref->filetype != filetype)
484                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
485
486                 backref->filetype = filetype;
487                 backref->found_dir_item = 1;
488         } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
489                    (itemtype == BTRFS_INODE_EXTREF_KEY)) {
490                 if (backref->found_inode_ref)
491                         backref->errors |= REF_ERR_DUP_INODE_REF;
492                 if (backref->found_dir_index && backref->index != index)
493                         backref->errors |= REF_ERR_INDEX_UNMATCH;
494
495                 backref->ref_type = itemtype;
496                 backref->index = index;
497                 backref->found_inode_ref = 1;
498         } else {
499                 BUG_ON(1);
500         }
501
502         maybe_free_inode_rec(inode_cache, rec);
503         return 0;
504 }
505
506 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
507                             struct cache_tree *dst_cache)
508 {
509         struct inode_backref *backref;
510         u32 dir_count = 0;
511
512         dst->merging = 1;
513         list_for_each_entry(backref, &src->backrefs, list) {
514                 if (backref->found_dir_index) {
515                         add_inode_backref(dst_cache, dst->ino, backref->dir,
516                                         backref->index, backref->name,
517                                         backref->namelen, backref->filetype,
518                                         BTRFS_DIR_INDEX_KEY, backref->errors);
519                 }
520                 if (backref->found_dir_item) {
521                         dir_count++;
522                         add_inode_backref(dst_cache, dst->ino,
523                                         backref->dir, 0, backref->name,
524                                         backref->namelen, backref->filetype,
525                                         BTRFS_DIR_ITEM_KEY, backref->errors);
526                 }
527                 if (backref->found_inode_ref) {
528                         add_inode_backref(dst_cache, dst->ino,
529                                         backref->dir, backref->index,
530                                         backref->name, backref->namelen, 0,
531                                         backref->ref_type, backref->errors);
532                 }
533         }
534
535         if (src->found_dir_item)
536                 dst->found_dir_item = 1;
537         if (src->found_file_extent)
538                 dst->found_file_extent = 1;
539         if (src->found_csum_item)
540                 dst->found_csum_item = 1;
541         if (src->some_csum_missing)
542                 dst->some_csum_missing = 1;
543         if (dst->first_extent_gap > src->first_extent_gap)
544                 dst->first_extent_gap = src->first_extent_gap;
545
546         BUG_ON(src->found_link < dir_count);
547         dst->found_link += src->found_link - dir_count;
548         dst->found_size += src->found_size;
549         if (src->extent_start != (u64)-1) {
550                 if (dst->extent_start == (u64)-1) {
551                         dst->extent_start = src->extent_start;
552                         dst->extent_end = src->extent_end;
553                 } else {
554                         if (dst->extent_end > src->extent_start)
555                                 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
556                         else if (dst->extent_end < src->extent_start &&
557                                  dst->extent_end < dst->first_extent_gap)
558                                 dst->first_extent_gap = dst->extent_end;
559                         if (dst->extent_end < src->extent_end)
560                                 dst->extent_end = src->extent_end;
561                 }
562         }
563
564         dst->errors |= src->errors;
565         if (src->found_inode_item) {
566                 if (!dst->found_inode_item) {
567                         dst->nlink = src->nlink;
568                         dst->isize = src->isize;
569                         dst->nbytes = src->nbytes;
570                         dst->imode = src->imode;
571                         dst->nodatasum = src->nodatasum;
572                         dst->found_inode_item = 1;
573                 } else {
574                         dst->errors |= I_ERR_DUP_INODE_ITEM;
575                 }
576         }
577         dst->merging = 0;
578
579         return 0;
580 }
581
582 static int splice_shared_node(struct shared_node *src_node,
583                               struct shared_node *dst_node)
584 {
585         struct cache_extent *cache;
586         struct ptr_node *node, *ins;
587         struct cache_tree *src, *dst;
588         struct inode_record *rec, *conflict;
589         u64 current_ino = 0;
590         int splice = 0;
591         int ret;
592
593         if (--src_node->refs == 0)
594                 splice = 1;
595         if (src_node->current)
596                 current_ino = src_node->current->ino;
597
598         src = &src_node->root_cache;
599         dst = &dst_node->root_cache;
600 again:
601         cache = find_first_cache_extent(src, 0);
602         while (cache) {
603                 node = container_of(cache, struct ptr_node, cache);
604                 rec = node->data;
605                 cache = next_cache_extent(cache);
606
607                 if (splice) {
608                         remove_cache_extent(src, &node->cache);
609                         ins = node;
610                 } else {
611                         ins = malloc(sizeof(*ins));
612                         ins->cache.start = node->cache.start;
613                         ins->cache.size = node->cache.size;
614                         ins->data = rec;
615                         rec->refs++;
616                 }
617                 ret = insert_existing_cache_extent(dst, &ins->cache);
618                 if (ret == -EEXIST) {
619                         conflict = get_inode_rec(dst, rec->ino, 1);
620                         merge_inode_recs(rec, conflict, dst);
621                         if (rec->checked) {
622                                 conflict->checked = 1;
623                                 if (dst_node->current == conflict)
624                                         dst_node->current = NULL;
625                         }
626                         maybe_free_inode_rec(dst, conflict);
627                         free_inode_rec(rec);
628                         free(ins);
629                 } else {
630                         BUG_ON(ret);
631                 }
632         }
633
634         if (src == &src_node->root_cache) {
635                 src = &src_node->inode_cache;
636                 dst = &dst_node->inode_cache;
637                 goto again;
638         }
639
640         if (current_ino > 0 && (!dst_node->current ||
641             current_ino > dst_node->current->ino)) {
642                 if (dst_node->current) {
643                         dst_node->current->checked = 1;
644                         maybe_free_inode_rec(dst, dst_node->current);
645                 }
646                 dst_node->current = get_inode_rec(dst, current_ino, 1);
647         }
648         return 0;
649 }
650
651 static void free_inode_recs(struct cache_tree *inode_cache)
652 {
653         struct cache_extent *cache;
654         struct ptr_node *node;
655         struct inode_record *rec;
656
657         while (1) {
658                 cache = find_first_cache_extent(inode_cache, 0);
659                 if (!cache)
660                         break;
661                 node = container_of(cache, struct ptr_node, cache);
662                 rec = node->data;
663                 remove_cache_extent(inode_cache, &node->cache);
664                 free(node);
665                 free_inode_rec(rec);
666         }
667 }
668
669 static struct shared_node *find_shared_node(struct cache_tree *shared,
670                                             u64 bytenr)
671 {
672         struct cache_extent *cache;
673         struct shared_node *node;
674
675         cache = find_cache_extent(shared, bytenr, 1);
676         if (cache) {
677                 node = container_of(cache, struct shared_node, cache);
678                 return node;
679         }
680         return NULL;
681 }
682
683 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
684 {
685         int ret;
686         struct shared_node *node;
687
688         node = calloc(1, sizeof(*node));
689         node->cache.start = bytenr;
690         node->cache.size = 1;
691         cache_tree_init(&node->root_cache);
692         cache_tree_init(&node->inode_cache);
693         node->refs = refs;
694
695         ret = insert_existing_cache_extent(shared, &node->cache);
696         BUG_ON(ret);
697         return 0;
698 }
699
700 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
701                              struct walk_control *wc, int level)
702 {
703         struct shared_node *node;
704         struct shared_node *dest;
705
706         if (level == wc->active_node)
707                 return 0;
708
709         BUG_ON(wc->active_node <= level);
710         node = find_shared_node(&wc->shared, bytenr);
711         if (!node) {
712                 add_shared_node(&wc->shared, bytenr, refs);
713                 node = find_shared_node(&wc->shared, bytenr);
714                 wc->nodes[level] = node;
715                 wc->active_node = level;
716                 return 0;
717         }
718
719         if (wc->root_level == wc->active_node &&
720             btrfs_root_refs(&root->root_item) == 0) {
721                 if (--node->refs == 0) {
722                         free_inode_recs(&node->root_cache);
723                         free_inode_recs(&node->inode_cache);
724                         remove_cache_extent(&wc->shared, &node->cache);
725                         free(node);
726                 }
727                 return 1;
728         }
729
730         dest = wc->nodes[wc->active_node];
731         splice_shared_node(node, dest);
732         if (node->refs == 0) {
733                 remove_cache_extent(&wc->shared, &node->cache);
734                 free(node);
735         }
736         return 1;
737 }
738
739 static int leave_shared_node(struct btrfs_root *root,
740                              struct walk_control *wc, int level)
741 {
742         struct shared_node *node;
743         struct shared_node *dest;
744         int i;
745
746         if (level == wc->root_level)
747                 return 0;
748
749         for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
750                 if (wc->nodes[i])
751                         break;
752         }
753         BUG_ON(i >= BTRFS_MAX_LEVEL);
754
755         node = wc->nodes[wc->active_node];
756         wc->nodes[wc->active_node] = NULL;
757         wc->active_node = i;
758
759         dest = wc->nodes[wc->active_node];
760         if (wc->active_node < wc->root_level ||
761             btrfs_root_refs(&root->root_item) > 0) {
762                 BUG_ON(node->refs <= 1);
763                 splice_shared_node(node, dest);
764         } else {
765                 BUG_ON(node->refs < 2);
766                 node->refs--;
767         }
768         return 0;
769 }
770
771 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
772                          u64 child_root_id)
773 {
774         struct btrfs_path path;
775         struct btrfs_key key;
776         struct extent_buffer *leaf;
777         int has_parent = 0;
778         int ret;
779
780         btrfs_init_path(&path);
781
782         key.objectid = parent_root_id;
783         key.type = BTRFS_ROOT_REF_KEY;
784         key.offset = child_root_id;
785         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
786                                 0, 0);
787         BUG_ON(ret < 0);
788         btrfs_release_path(root, &path);
789         if (!ret)
790                 return 1;
791
792         key.objectid = child_root_id;
793         key.type = BTRFS_ROOT_BACKREF_KEY;
794         key.offset = 0;
795         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
796                                 0, 0);
797         BUG_ON(ret <= 0);
798
799         while (1) {
800                 leaf = path.nodes[0];
801                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
802                         ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
803                         BUG_ON(ret < 0);
804
805                         if (ret > 0)
806                                 break;
807                         leaf = path.nodes[0];
808                 }
809
810                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
811                 if (key.objectid != child_root_id ||
812                     key.type != BTRFS_ROOT_BACKREF_KEY)
813                         break;
814
815                 has_parent = 1;
816
817                 if (key.offset == parent_root_id) {
818                         btrfs_release_path(root, &path);
819                         return 1;
820                 }
821
822                 path.slots[0]++;
823         }
824
825         btrfs_release_path(root, &path);
826         return has_parent? 0 : -1;
827 }
828
829 static int process_dir_item(struct btrfs_root *root,
830                             struct extent_buffer *eb,
831                             int slot, struct btrfs_key *key,
832                             struct shared_node *active_node)
833 {
834         u32 total;
835         u32 cur = 0;
836         u32 len;
837         u32 name_len;
838         u32 data_len;
839         int error;
840         int nritems = 0;
841         int filetype;
842         struct btrfs_dir_item *di;
843         struct inode_record *rec;
844         struct cache_tree *root_cache;
845         struct cache_tree *inode_cache;
846         struct btrfs_key location;
847         char namebuf[BTRFS_NAME_LEN];
848
849         root_cache = &active_node->root_cache;
850         inode_cache = &active_node->inode_cache;
851         rec = active_node->current;
852         rec->found_dir_item = 1;
853
854         di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
855         total = btrfs_item_size_nr(eb, slot);
856         while (cur < total) {
857                 nritems++;
858                 btrfs_dir_item_key_to_cpu(eb, di, &location);
859                 name_len = btrfs_dir_name_len(eb, di);
860                 data_len = btrfs_dir_data_len(eb, di);
861                 filetype = btrfs_dir_type(eb, di);
862
863                 rec->found_size += name_len;
864                 if (name_len <= BTRFS_NAME_LEN) {
865                         len = name_len;
866                         error = 0;
867                 } else {
868                         len = BTRFS_NAME_LEN;
869                         error = REF_ERR_NAME_TOO_LONG;
870                 }
871                 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
872
873                 if (location.type == BTRFS_INODE_ITEM_KEY) {
874                         add_inode_backref(inode_cache, location.objectid,
875                                           key->objectid, key->offset, namebuf,
876                                           len, filetype, key->type, error);
877                 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
878                         add_inode_backref(root_cache, location.objectid,
879                                           key->objectid, key->offset,
880                                           namebuf, len, filetype,
881                                           key->type, error);
882                 } else {
883                         fprintf(stderr, "warning line %d\n", __LINE__);
884                 }
885
886                 len = sizeof(*di) + name_len + data_len;
887                 di = (struct btrfs_dir_item *)((char *)di + len);
888                 cur += len;
889         }
890         if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
891                 rec->errors |= I_ERR_DUP_DIR_INDEX;
892
893         return 0;
894 }
895
896 static int process_inode_ref(struct extent_buffer *eb,
897                              int slot, struct btrfs_key *key,
898                              struct shared_node *active_node)
899 {
900         u32 total;
901         u32 cur = 0;
902         u32 len;
903         u32 name_len;
904         u64 index;
905         int error;
906         struct cache_tree *inode_cache;
907         struct btrfs_inode_ref *ref;
908         char namebuf[BTRFS_NAME_LEN];
909
910         inode_cache = &active_node->inode_cache;
911
912         ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
913         total = btrfs_item_size_nr(eb, slot);
914         while (cur < total) {
915                 name_len = btrfs_inode_ref_name_len(eb, ref);
916                 index = btrfs_inode_ref_index(eb, ref);
917                 if (name_len <= BTRFS_NAME_LEN) {
918                         len = name_len;
919                         error = 0;
920                 } else {
921                         len = BTRFS_NAME_LEN;
922                         error = REF_ERR_NAME_TOO_LONG;
923                 }
924                 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
925                 add_inode_backref(inode_cache, key->objectid, key->offset,
926                                   index, namebuf, len, 0, key->type, error);
927
928                 len = sizeof(*ref) + name_len;
929                 ref = (struct btrfs_inode_ref *)((char *)ref + len);
930                 cur += len;
931         }
932         return 0;
933 }
934
935 static int process_inode_extref(struct extent_buffer *eb,
936                                 int slot, struct btrfs_key *key,
937                                 struct shared_node *active_node)
938 {
939         u32 total;
940         u32 cur = 0;
941         u32 len;
942         u32 name_len;
943         u64 index;
944         u64 parent;
945         int error;
946         struct cache_tree *inode_cache;
947         struct btrfs_inode_extref *extref;
948         char namebuf[BTRFS_NAME_LEN];
949
950         inode_cache = &active_node->inode_cache;
951
952         extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
953         total = btrfs_item_size_nr(eb, slot);
954         while (cur < total) {
955                 name_len = btrfs_inode_extref_name_len(eb, extref);
956                 index = btrfs_inode_extref_index(eb, extref);
957                 parent = btrfs_inode_extref_parent(eb, extref);
958                 if (name_len <= BTRFS_NAME_LEN) {
959                         len = name_len;
960                         error = 0;
961                 } else {
962                         len = BTRFS_NAME_LEN;
963                         error = REF_ERR_NAME_TOO_LONG;
964                 }
965                 read_extent_buffer(eb, namebuf,
966                                    (unsigned long)(extref + 1), len);
967                 add_inode_backref(inode_cache, key->objectid, parent,
968                                   index, namebuf, len, 0, key->type, error);
969
970                 len = sizeof(*extref) + name_len;
971                 extref = (struct btrfs_inode_extref *)((char *)extref + len);
972                 cur += len;
973         }
974         return 0;
975
976 }
977
978 static u64 count_csum_range(struct btrfs_root *root, u64 start, u64 len)
979 {
980         struct btrfs_key key;
981         struct btrfs_path path;
982         struct extent_buffer *leaf;
983         int ret ;
984         size_t size;
985         u64 found = 0;
986         u64 csum_end;
987         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
988
989         btrfs_init_path(&path);
990
991         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
992         key.offset = start;
993         key.type = BTRFS_EXTENT_CSUM_KEY;
994
995         ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
996                                 &key, &path, 0, 0);
997         BUG_ON(ret < 0);
998         if (ret > 0 && path.slots[0] > 0) {
999                 leaf = path.nodes[0];
1000                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1001                 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1002                     key.type == BTRFS_EXTENT_CSUM_KEY)
1003                         path.slots[0]--;
1004         }
1005
1006         while (len > 0) {
1007                 leaf = path.nodes[0];
1008                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1009                         ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1010                         BUG_ON(ret < 0);
1011                         if (ret > 0)
1012                                 break;
1013                         leaf = path.nodes[0];
1014                 }
1015
1016                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1017                 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1018                     key.type != BTRFS_EXTENT_CSUM_KEY)
1019                         break;
1020
1021                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1022                 if (key.offset >= start + len)
1023                         break;
1024
1025                 if (key.offset > start)
1026                         start = key.offset;
1027
1028                 size = btrfs_item_size_nr(leaf, path.slots[0]);
1029                 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1030                 if (csum_end > start) {
1031                         size = min(csum_end - start, len);
1032                         len -= size;
1033                         start += size;
1034                         found += size;
1035                 }
1036
1037                 path.slots[0]++;
1038         }
1039         btrfs_release_path(root->fs_info->csum_root, &path);
1040         return found;
1041 }
1042
1043 static int process_file_extent(struct btrfs_root *root,
1044                                 struct extent_buffer *eb,
1045                                 int slot, struct btrfs_key *key,
1046                                 struct shared_node *active_node)
1047 {
1048         struct inode_record *rec;
1049         struct btrfs_file_extent_item *fi;
1050         u64 num_bytes = 0;
1051         u64 disk_bytenr = 0;
1052         u64 extent_offset = 0;
1053         u64 mask = root->sectorsize - 1;
1054         int extent_type;
1055
1056         rec = active_node->current;
1057         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1058         rec->found_file_extent = 1;
1059
1060         if (rec->extent_start == (u64)-1) {
1061                 rec->extent_start = key->offset;
1062                 rec->extent_end = key->offset;
1063         }
1064
1065         if (rec->extent_end > key->offset)
1066                 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1067         else if (rec->extent_end < key->offset &&
1068                  rec->extent_end < rec->first_extent_gap)
1069                 rec->first_extent_gap = rec->extent_end;
1070
1071         fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1072         extent_type = btrfs_file_extent_type(eb, fi);
1073
1074         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1075                 num_bytes = btrfs_file_extent_inline_len(eb, fi);
1076                 if (num_bytes == 0)
1077                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1078                 rec->found_size += num_bytes;
1079                 num_bytes = (num_bytes + mask) & ~mask;
1080         } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1081                    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1082                 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1083                 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1084                 extent_offset = btrfs_file_extent_offset(eb, fi);
1085                 if (num_bytes == 0 || (num_bytes & mask))
1086                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1087                 if (num_bytes + extent_offset >
1088                     btrfs_file_extent_ram_bytes(eb, fi))
1089                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1090                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1091                     (btrfs_file_extent_compression(eb, fi) ||
1092                      btrfs_file_extent_encryption(eb, fi) ||
1093                      btrfs_file_extent_other_encoding(eb, fi)))
1094                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1095                 if (disk_bytenr > 0)
1096                         rec->found_size += num_bytes;
1097         } else {
1098                 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1099         }
1100         rec->extent_end = key->offset + num_bytes;
1101
1102         if (disk_bytenr > 0) {
1103                 u64 found;
1104                 if (btrfs_file_extent_compression(eb, fi))
1105                         num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1106                 else
1107                         disk_bytenr += extent_offset;
1108
1109                 found = count_csum_range(root, disk_bytenr, num_bytes);
1110                 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1111                         if (found > 0)
1112                                 rec->found_csum_item = 1;
1113                         if (found < num_bytes)
1114                                 rec->some_csum_missing = 1;
1115                 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1116                         if (found > 0)
1117                                 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1118                 }
1119         }
1120         return 0;
1121 }
1122
1123 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1124                             struct walk_control *wc)
1125 {
1126         struct btrfs_key key;
1127         u32 nritems;
1128         int i;
1129         int ret = 0;
1130         struct cache_tree *inode_cache;
1131         struct shared_node *active_node;
1132
1133         if (wc->root_level == wc->active_node &&
1134             btrfs_root_refs(&root->root_item) == 0)
1135                 return 0;
1136
1137         active_node = wc->nodes[wc->active_node];
1138         inode_cache = &active_node->inode_cache;
1139         nritems = btrfs_header_nritems(eb);
1140         for (i = 0; i < nritems; i++) {
1141                 btrfs_item_key_to_cpu(eb, &key, i);
1142
1143                 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1144                         continue;
1145
1146                 if (active_node->current == NULL ||
1147                     active_node->current->ino < key.objectid) {
1148                         if (active_node->current) {
1149                                 active_node->current->checked = 1;
1150                                 maybe_free_inode_rec(inode_cache,
1151                                                      active_node->current);
1152                         }
1153                         active_node->current = get_inode_rec(inode_cache,
1154                                                              key.objectid, 1);
1155                 }
1156                 switch (key.type) {
1157                 case BTRFS_DIR_ITEM_KEY:
1158                 case BTRFS_DIR_INDEX_KEY:
1159                         ret = process_dir_item(root, eb, i, &key, active_node);
1160                         break;
1161                 case BTRFS_INODE_REF_KEY:
1162                         ret = process_inode_ref(eb, i, &key, active_node);
1163                         break;
1164                 case BTRFS_INODE_EXTREF_KEY:
1165                         ret = process_inode_extref(eb, i, &key, active_node);
1166                         break;
1167                 case BTRFS_INODE_ITEM_KEY:
1168                         ret = process_inode_item(eb, i, &key, active_node);
1169                         break;
1170                 case BTRFS_EXTENT_DATA_KEY:
1171                         ret = process_file_extent(root, eb, i, &key,
1172                                                   active_node);
1173                         break;
1174                 default:
1175                         break;
1176                 };
1177         }
1178         return ret;
1179 }
1180
1181 static void reada_walk_down(struct btrfs_root *root,
1182                             struct extent_buffer *node, int slot)
1183 {
1184         u64 bytenr;
1185         u64 ptr_gen;
1186         u32 nritems;
1187         u32 blocksize;
1188         int i;
1189         int ret;
1190         int level;
1191
1192         level = btrfs_header_level(node);
1193         if (level != 1)
1194                 return;
1195
1196         nritems = btrfs_header_nritems(node);
1197         blocksize = btrfs_level_size(root, level - 1);
1198         for (i = slot; i < nritems; i++) {
1199                 bytenr = btrfs_node_blockptr(node, i);
1200                 ptr_gen = btrfs_node_ptr_generation(node, i);
1201                 ret = readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1202                 if (ret)
1203                         break;
1204         }
1205 }
1206
1207 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1208                           struct walk_control *wc, int *level)
1209 {
1210         u64 bytenr;
1211         u64 ptr_gen;
1212         struct extent_buffer *next;
1213         struct extent_buffer *cur;
1214         u32 blocksize;
1215         int ret;
1216         u64 refs;
1217
1218         WARN_ON(*level < 0);
1219         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1220         ret = btrfs_lookup_extent_info(NULL, root,
1221                                        path->nodes[*level]->start,
1222                                        *level, 1, &refs, NULL);
1223         if (ret < 0)
1224                 goto out;
1225
1226         if (refs > 1) {
1227                 ret = enter_shared_node(root, path->nodes[*level]->start,
1228                                         refs, wc, *level);
1229                 if (ret > 0)
1230                         goto out;
1231         }
1232
1233         while (*level >= 0) {
1234                 WARN_ON(*level < 0);
1235                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1236                 cur = path->nodes[*level];
1237
1238                 if (btrfs_header_level(cur) != *level)
1239                         WARN_ON(1);
1240
1241                 if (path->slots[*level] >= btrfs_header_nritems(cur))
1242                         break;
1243                 if (*level == 0) {
1244                         ret = process_one_leaf(root, cur, wc);
1245                         break;
1246                 }
1247                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1248                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1249                 blocksize = btrfs_level_size(root, *level - 1);
1250                 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1251                                                1, &refs, NULL);
1252                 if (ret < 0)
1253                         refs = 0;
1254
1255                 if (refs > 1) {
1256                         ret = enter_shared_node(root, bytenr, refs,
1257                                                 wc, *level - 1);
1258                         if (ret > 0) {
1259                                 path->slots[*level]++;
1260                                 continue;
1261                         }
1262                 }
1263
1264                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1265                 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1266                         free_extent_buffer(next);
1267                         reada_walk_down(root, cur, path->slots[*level]);
1268                         next = read_tree_block(root, bytenr, blocksize,
1269                                                ptr_gen);
1270                 }
1271
1272                 *level = *level - 1;
1273                 free_extent_buffer(path->nodes[*level]);
1274                 path->nodes[*level] = next;
1275                 path->slots[*level] = 0;
1276         }
1277 out:
1278         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1279         return 0;
1280 }
1281
1282 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1283                         struct walk_control *wc, int *level)
1284 {
1285         int i;
1286         struct extent_buffer *leaf;
1287
1288         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1289                 leaf = path->nodes[i];
1290                 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1291                         path->slots[i]++;
1292                         *level = i;
1293                         return 0;
1294                 } else {
1295                         free_extent_buffer(path->nodes[*level]);
1296                         path->nodes[*level] = NULL;
1297                         BUG_ON(*level > wc->active_node);
1298                         if (*level == wc->active_node)
1299                                 leave_shared_node(root, wc, *level);
1300                         *level = i + 1;
1301                 }
1302         }
1303         return 1;
1304 }
1305
1306 static int check_root_dir(struct inode_record *rec)
1307 {
1308         struct inode_backref *backref;
1309         int ret = -1;
1310
1311         if (!rec->found_inode_item || rec->errors)
1312                 goto out;
1313         if (rec->nlink != 1 || rec->found_link != 0)
1314                 goto out;
1315         if (list_empty(&rec->backrefs))
1316                 goto out;
1317         backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1318         if (!backref->found_inode_ref)
1319                 goto out;
1320         if (backref->index != 0 || backref->namelen != 2 ||
1321             memcmp(backref->name, "..", 2))
1322                 goto out;
1323         if (backref->found_dir_index || backref->found_dir_item)
1324                 goto out;
1325         ret = 0;
1326 out:
1327         return ret;
1328 }
1329
1330 static int check_inode_recs(struct btrfs_root *root,
1331                             struct cache_tree *inode_cache)
1332 {
1333         struct cache_extent *cache;
1334         struct ptr_node *node;
1335         struct inode_record *rec;
1336         struct inode_backref *backref;
1337         int ret;
1338         u64 error = 0;
1339         u64 root_dirid = btrfs_root_dirid(&root->root_item);
1340
1341         if (btrfs_root_refs(&root->root_item) == 0) {
1342                 if (!cache_tree_empty(inode_cache))
1343                         fprintf(stderr, "warning line %d\n", __LINE__);
1344                 return 0;
1345         }
1346
1347         rec = get_inode_rec(inode_cache, root_dirid, 0);
1348         if (rec) {
1349                 ret = check_root_dir(rec);
1350                 if (ret) {
1351                         fprintf(stderr, "root %llu root dir %llu error\n",
1352                                 (unsigned long long)root->root_key.objectid,
1353                                 (unsigned long long)root_dirid);
1354                         error++;
1355                 }
1356         } else {
1357                 fprintf(stderr, "root %llu root dir %llu not found\n",
1358                         (unsigned long long)root->root_key.objectid,
1359                         (unsigned long long)root_dirid);
1360         }
1361
1362         while (1) {
1363                 cache = find_first_cache_extent(inode_cache, 0);
1364                 if (!cache)
1365                         break;
1366                 node = container_of(cache, struct ptr_node, cache);
1367                 rec = node->data;
1368                 remove_cache_extent(inode_cache, &node->cache);
1369                 free(node);
1370                 if (rec->ino == root_dirid ||
1371                     rec->ino == BTRFS_ORPHAN_OBJECTID) {
1372                         free_inode_rec(rec);
1373                         continue;
1374                 }
1375
1376                 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
1377                         ret = check_orphan_item(root, rec->ino);
1378                         if (ret == 0)
1379                                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1380                         if (can_free_inode_rec(rec)) {
1381                                 free_inode_rec(rec);
1382                                 continue;
1383                         }
1384                 }
1385
1386                 error++;
1387                 if (!rec->found_inode_item)
1388                         rec->errors |= I_ERR_NO_INODE_ITEM;
1389                 if (rec->found_link != rec->nlink)
1390                         rec->errors |= I_ERR_LINK_COUNT_WRONG;
1391                 fprintf(stderr, "root %llu inode %llu errors %x\n",
1392                         (unsigned long long) root->root_key.objectid,
1393                         (unsigned long long) rec->ino, rec->errors);
1394                 list_for_each_entry(backref, &rec->backrefs, list) {
1395                         if (!backref->found_dir_item)
1396                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1397                         if (!backref->found_dir_index)
1398                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1399                         if (!backref->found_inode_ref)
1400                                 backref->errors |= REF_ERR_NO_INODE_REF;
1401                         fprintf(stderr, "\tunresolved ref dir %llu index %llu"
1402                                 " namelen %u name %s filetype %d error %x\n",
1403                                 (unsigned long long)backref->dir,
1404                                 (unsigned long long)backref->index,
1405                                 backref->namelen, backref->name,
1406                                 backref->filetype, backref->errors);
1407                 }
1408                 free_inode_rec(rec);
1409         }
1410         return (error > 0) ? -1 : 0;
1411 }
1412
1413 static struct root_record *get_root_rec(struct cache_tree *root_cache,
1414                                         u64 objectid)
1415 {
1416         struct cache_extent *cache;
1417         struct root_record *rec = NULL;
1418         int ret;
1419
1420         cache = find_cache_extent(root_cache, objectid, 1);
1421         if (cache) {
1422                 rec = container_of(cache, struct root_record, cache);
1423         } else {
1424                 rec = calloc(1, sizeof(*rec));
1425                 rec->objectid = objectid;
1426                 INIT_LIST_HEAD(&rec->backrefs);
1427                 rec->cache.start = objectid;
1428                 rec->cache.size = 1;
1429
1430                 ret = insert_existing_cache_extent(root_cache, &rec->cache);
1431                 BUG_ON(ret);
1432         }
1433         return rec;
1434 }
1435
1436 static struct root_backref *get_root_backref(struct root_record *rec,
1437                                              u64 ref_root, u64 dir, u64 index,
1438                                              const char *name, int namelen)
1439 {
1440         struct root_backref *backref;
1441
1442         list_for_each_entry(backref, &rec->backrefs, list) {
1443                 if (backref->ref_root != ref_root || backref->dir != dir ||
1444                     backref->namelen != namelen)
1445                         continue;
1446                 if (memcmp(name, backref->name, namelen))
1447                         continue;
1448                 return backref;
1449         }
1450
1451         backref = malloc(sizeof(*backref) + namelen + 1);
1452         memset(backref, 0, sizeof(*backref));
1453         backref->ref_root = ref_root;
1454         backref->dir = dir;
1455         backref->index = index;
1456         backref->namelen = namelen;
1457         memcpy(backref->name, name, namelen);
1458         backref->name[namelen] = '\0';
1459         list_add_tail(&backref->list, &rec->backrefs);
1460         return backref;
1461 }
1462
1463 static void free_root_recs(struct cache_tree *root_cache)
1464 {
1465         struct cache_extent *cache;
1466         struct root_record *rec;
1467         struct root_backref *backref;
1468
1469         while (1) {
1470                 cache = find_first_cache_extent(root_cache, 0);
1471                 if (!cache)
1472                         break;
1473                 rec = container_of(cache, struct root_record, cache);
1474                 remove_cache_extent(root_cache, &rec->cache);
1475
1476                 while (!list_empty(&rec->backrefs)) {
1477                         backref = list_entry(rec->backrefs.next,
1478                                              struct root_backref, list);
1479                         list_del(&backref->list);
1480                         free(backref);
1481                 }
1482                 kfree(rec);
1483         }
1484 }
1485
1486 static int add_root_backref(struct cache_tree *root_cache,
1487                             u64 root_id, u64 ref_root, u64 dir, u64 index,
1488                             const char *name, int namelen,
1489                             int item_type, int errors)
1490 {
1491         struct root_record *rec;
1492         struct root_backref *backref;
1493
1494         rec = get_root_rec(root_cache, root_id);
1495         backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
1496
1497         backref->errors |= errors;
1498
1499         if (item_type != BTRFS_DIR_ITEM_KEY) {
1500                 if (backref->found_dir_index || backref->found_back_ref ||
1501                     backref->found_forward_ref) {
1502                         if (backref->index != index)
1503                                 backref->errors |= REF_ERR_INDEX_UNMATCH;
1504                 } else {
1505                         backref->index = index;
1506                 }
1507         }
1508
1509         if (item_type == BTRFS_DIR_ITEM_KEY) {
1510                 if (backref->found_forward_ref)
1511                         rec->found_ref++;
1512                 backref->found_dir_item = 1;
1513         } else if (item_type == BTRFS_DIR_INDEX_KEY) {
1514                 backref->found_dir_index = 1;
1515         } else if (item_type == BTRFS_ROOT_REF_KEY) {
1516                 if (backref->found_forward_ref)
1517                         backref->errors |= REF_ERR_DUP_ROOT_REF;
1518                 else if (backref->found_dir_item)
1519                         rec->found_ref++;
1520                 backref->found_forward_ref = 1;
1521         } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
1522                 if (backref->found_back_ref)
1523                         backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
1524                 backref->found_back_ref = 1;
1525         } else {
1526                 BUG_ON(1);
1527         }
1528
1529         if (backref->found_forward_ref && backref->found_dir_item)
1530                 backref->reachable = 1;
1531         return 0;
1532 }
1533
1534 static int merge_root_recs(struct btrfs_root *root,
1535                            struct cache_tree *src_cache,
1536                            struct cache_tree *dst_cache)
1537 {
1538         struct cache_extent *cache;
1539         struct ptr_node *node;
1540         struct inode_record *rec;
1541         struct inode_backref *backref;
1542
1543         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
1544                 free_inode_recs(src_cache);
1545                 return 0;
1546         }
1547
1548         while (1) {
1549                 cache = find_first_cache_extent(src_cache, 0);
1550                 if (!cache)
1551                         break;
1552                 node = container_of(cache, struct ptr_node, cache);
1553                 rec = node->data;
1554                 remove_cache_extent(src_cache, &node->cache);
1555                 free(node);
1556
1557                 if (!is_child_root(root, root->objectid, rec->ino))
1558                         goto skip;
1559
1560                 list_for_each_entry(backref, &rec->backrefs, list) {
1561                         BUG_ON(backref->found_inode_ref);
1562                         if (backref->found_dir_item)
1563                                 add_root_backref(dst_cache, rec->ino,
1564                                         root->root_key.objectid, backref->dir,
1565                                         backref->index, backref->name,
1566                                         backref->namelen, BTRFS_DIR_ITEM_KEY,
1567                                         backref->errors);
1568                         if (backref->found_dir_index)
1569                                 add_root_backref(dst_cache, rec->ino,
1570                                         root->root_key.objectid, backref->dir,
1571                                         backref->index, backref->name,
1572                                         backref->namelen, BTRFS_DIR_INDEX_KEY,
1573                                         backref->errors);
1574                 }
1575 skip:
1576                 free_inode_rec(rec);
1577         }
1578         return 0;
1579 }
1580
1581 static int check_root_refs(struct btrfs_root *root,
1582                            struct cache_tree *root_cache)
1583 {
1584         struct root_record *rec;
1585         struct root_record *ref_root;
1586         struct root_backref *backref;
1587         struct cache_extent *cache;
1588         int loop = 1;
1589         int ret;
1590         int error;
1591         int errors = 0;
1592
1593         rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
1594         rec->found_ref = 1;
1595
1596         /* fixme: this can not detect circular references */
1597         while (loop) {
1598                 loop = 0;
1599                 cache = find_first_cache_extent(root_cache, 0);
1600                 while (1) {
1601                         if (!cache)
1602                                 break;
1603                         rec = container_of(cache, struct root_record, cache);
1604                         cache = next_cache_extent(cache);
1605
1606                         if (rec->found_ref == 0)
1607                                 continue;
1608
1609                         list_for_each_entry(backref, &rec->backrefs, list) {
1610                                 if (!backref->reachable)
1611                                         continue;
1612
1613                                 ref_root = get_root_rec(root_cache,
1614                                                         backref->ref_root);
1615                                 if (ref_root->found_ref > 0)
1616                                         continue;
1617
1618                                 backref->reachable = 0;
1619                                 rec->found_ref--;
1620                                 if (rec->found_ref == 0)
1621                                         loop = 1;
1622                         }
1623                 }
1624         }
1625
1626         cache = find_first_cache_extent(root_cache, 0);
1627         while (1) {
1628                 if (!cache)
1629                         break;
1630                 rec = container_of(cache, struct root_record, cache);
1631                 cache = next_cache_extent(cache);
1632
1633                 if (rec->found_ref == 0 &&
1634                     rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1635                     rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
1636                         ret = check_orphan_item(root->fs_info->tree_root,
1637                                                 rec->objectid);
1638                         if (ret == 0)
1639                                 continue;
1640
1641                         /*
1642                          * If we don't have a root item then we likely just have
1643                          * a dir item in a snapshot for this root but no actual
1644                          * ref key or anything so it's meaningless.
1645                          */
1646                         if (!rec->found_root_item)
1647                                 continue;
1648                         errors++;
1649                         fprintf(stderr, "fs tree %llu not referenced\n",
1650                                 (unsigned long long)rec->objectid);
1651                 }
1652
1653                 error = 0;
1654                 if (rec->found_ref > 0 && !rec->found_root_item)
1655                         error = 1;
1656                 list_for_each_entry(backref, &rec->backrefs, list) {
1657                         if (!backref->found_dir_item)
1658                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1659                         if (!backref->found_dir_index)
1660                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1661                         if (!backref->found_back_ref)
1662                                 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
1663                         if (!backref->found_forward_ref)
1664                                 backref->errors |= REF_ERR_NO_ROOT_REF;
1665                         if (backref->reachable && backref->errors)
1666                                 error = 1;
1667                 }
1668                 if (!error)
1669                         continue;
1670
1671                 errors++;
1672                 fprintf(stderr, "fs tree %llu refs %u %s\n",
1673                         (unsigned long long)rec->objectid, rec->found_ref,
1674                          rec->found_root_item ? "" : "not found");
1675
1676                 list_for_each_entry(backref, &rec->backrefs, list) {
1677                         if (!backref->reachable)
1678                                 continue;
1679                         if (!backref->errors && rec->found_root_item)
1680                                 continue;
1681                         fprintf(stderr, "\tunresolved ref root %llu dir %llu"
1682                                 " index %llu namelen %u name %s error %x\n",
1683                                 (unsigned long long)backref->ref_root,
1684                                 (unsigned long long)backref->dir,
1685                                 (unsigned long long)backref->index,
1686                                 backref->namelen, backref->name,
1687                                 backref->errors);
1688                 }
1689         }
1690         return errors > 0 ? 1 : 0;
1691 }
1692
1693 static int process_root_ref(struct extent_buffer *eb, int slot,
1694                             struct btrfs_key *key,
1695                             struct cache_tree *root_cache)
1696 {
1697         u64 dirid;
1698         u64 index;
1699         u32 len;
1700         u32 name_len;
1701         struct btrfs_root_ref *ref;
1702         char namebuf[BTRFS_NAME_LEN];
1703         int error;
1704
1705         ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
1706
1707         dirid = btrfs_root_ref_dirid(eb, ref);
1708         index = btrfs_root_ref_sequence(eb, ref);
1709         name_len = btrfs_root_ref_name_len(eb, ref);
1710
1711         if (name_len <= BTRFS_NAME_LEN) {
1712                 len = name_len;
1713                 error = 0;
1714         } else {
1715                 len = BTRFS_NAME_LEN;
1716                 error = REF_ERR_NAME_TOO_LONG;
1717         }
1718         read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1719
1720         if (key->type == BTRFS_ROOT_REF_KEY) {
1721                 add_root_backref(root_cache, key->offset, key->objectid, dirid,
1722                                  index, namebuf, len, key->type, error);
1723         } else {
1724                 add_root_backref(root_cache, key->objectid, key->offset, dirid,
1725                                  index, namebuf, len, key->type, error);
1726         }
1727         return 0;
1728 }
1729
1730 static int check_fs_root(struct btrfs_root *root,
1731                          struct cache_tree *root_cache,
1732                          struct walk_control *wc)
1733 {
1734         int ret = 0;
1735         int wret;
1736         int level;
1737         struct btrfs_path path;
1738         struct shared_node root_node;
1739         struct root_record *rec;
1740         struct btrfs_root_item *root_item = &root->root_item;
1741
1742         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1743                 rec = get_root_rec(root_cache, root->root_key.objectid);
1744                 if (btrfs_root_refs(root_item) > 0)
1745                         rec->found_root_item = 1;
1746         }
1747
1748         btrfs_init_path(&path);
1749         memset(&root_node, 0, sizeof(root_node));
1750         cache_tree_init(&root_node.root_cache);
1751         cache_tree_init(&root_node.inode_cache);
1752
1753         level = btrfs_header_level(root->node);
1754         memset(wc->nodes, 0, sizeof(wc->nodes));
1755         wc->nodes[level] = &root_node;
1756         wc->active_node = level;
1757         wc->root_level = level;
1758
1759         if (btrfs_root_refs(root_item) > 0 ||
1760             btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1761                 path.nodes[level] = root->node;
1762                 extent_buffer_get(root->node);
1763                 path.slots[level] = 0;
1764         } else {
1765                 struct btrfs_key key;
1766                 struct btrfs_disk_key found_key;
1767
1768                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1769                 level = root_item->drop_level;
1770                 path.lowest_level = level;
1771                 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1772                 BUG_ON(wret < 0);
1773                 btrfs_node_key(path.nodes[level], &found_key,
1774                                 path.slots[level]);
1775                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
1776                                         sizeof(found_key)));
1777         }
1778
1779         while (1) {
1780                 wret = walk_down_tree(root, &path, wc, &level);
1781                 if (wret < 0)
1782                         ret = wret;
1783                 if (wret != 0)
1784                         break;
1785
1786                 wret = walk_up_tree(root, &path, wc, &level);
1787                 if (wret < 0)
1788                         ret = wret;
1789                 if (wret != 0)
1790                         break;
1791         }
1792         btrfs_release_path(root, &path);
1793
1794         merge_root_recs(root, &root_node.root_cache, root_cache);
1795
1796         if (root_node.current) {
1797                 root_node.current->checked = 1;
1798                 maybe_free_inode_rec(&root_node.inode_cache,
1799                                 root_node.current);
1800         }
1801
1802         ret = check_inode_recs(root, &root_node.inode_cache);
1803         return ret;
1804 }
1805
1806 static int fs_root_objectid(u64 objectid)
1807 {
1808         if (objectid == BTRFS_FS_TREE_OBJECTID ||
1809             objectid == BTRFS_TREE_RELOC_OBJECTID ||
1810             objectid == BTRFS_DATA_RELOC_TREE_OBJECTID ||
1811             (objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1812              objectid <= BTRFS_LAST_FREE_OBJECTID))
1813                 return 1;
1814         return 0;
1815 }
1816
1817 static int check_fs_roots(struct btrfs_root *root,
1818                           struct cache_tree *root_cache)
1819 {
1820         struct btrfs_path path;
1821         struct btrfs_key key;
1822         struct walk_control wc;
1823         struct extent_buffer *leaf;
1824         struct btrfs_root *tmp_root;
1825         struct btrfs_root *tree_root = root->fs_info->tree_root;
1826         int ret;
1827         int err = 0;
1828
1829         memset(&wc, 0, sizeof(wc));
1830         cache_tree_init(&wc.shared);
1831         btrfs_init_path(&path);
1832
1833         key.offset = 0;
1834         key.objectid = 0;
1835         key.type = BTRFS_ROOT_ITEM_KEY;
1836         ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
1837         BUG_ON(ret < 0);
1838         while (1) {
1839                 leaf = path.nodes[0];
1840                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1841                         ret = btrfs_next_leaf(tree_root, &path);
1842                         if (ret != 0)
1843                                 break;
1844                         leaf = path.nodes[0];
1845                 }
1846                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1847                 if (key.type == BTRFS_ROOT_ITEM_KEY &&
1848                     fs_root_objectid(key.objectid)) {
1849                         tmp_root = btrfs_read_fs_root_no_cache(root->fs_info,
1850                                                                &key);
1851                         if (IS_ERR(tmp_root)) {
1852                                 err = 1;
1853                                 goto next;
1854                         }
1855                         ret = check_fs_root(tmp_root, root_cache, &wc);
1856                         if (ret)
1857                                 err = 1;
1858                         btrfs_free_fs_root(root->fs_info, tmp_root);
1859                 } else if (key.type == BTRFS_ROOT_REF_KEY ||
1860                            key.type == BTRFS_ROOT_BACKREF_KEY) {
1861                         process_root_ref(leaf, path.slots[0], &key,
1862                                          root_cache);
1863                 }
1864 next:
1865                 path.slots[0]++;
1866         }
1867         btrfs_release_path(tree_root, &path);
1868
1869         if (!cache_tree_empty(&wc.shared))
1870                 fprintf(stderr, "warning line %d\n", __LINE__);
1871
1872         return err;
1873 }
1874
1875 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
1876 {
1877         struct list_head *cur = rec->backrefs.next;
1878         struct extent_backref *back;
1879         struct tree_backref *tback;
1880         struct data_backref *dback;
1881         u64 found = 0;
1882         int err = 0;
1883
1884         while(cur != &rec->backrefs) {
1885                 back = list_entry(cur, struct extent_backref, list);
1886                 cur = cur->next;
1887                 if (!back->found_extent_tree) {
1888                         err = 1;
1889                         if (!print_errs)
1890                                 goto out;
1891                         if (back->is_data) {
1892                                 dback = (struct data_backref *)back;
1893                                 fprintf(stderr, "Backref %llu %s %llu"
1894                                         " owner %llu offset %llu num_refs %lu"
1895                                         " not found in extent tree\n",
1896                                         (unsigned long long)rec->start,
1897                                         back->full_backref ?
1898                                         "parent" : "root",
1899                                         back->full_backref ?
1900                                         (unsigned long long)dback->parent:
1901                                         (unsigned long long)dback->root,
1902                                         (unsigned long long)dback->owner,
1903                                         (unsigned long long)dback->offset,
1904                                         (unsigned long)dback->num_refs);
1905                         } else {
1906                                 tback = (struct tree_backref *)back;
1907                                 fprintf(stderr, "Backref %llu parent %llu"
1908                                         " root %llu not found in extent tree\n",
1909                                         (unsigned long long)rec->start,
1910                                         (unsigned long long)tback->parent,
1911                                         (unsigned long long)tback->root);
1912                         }
1913                 }
1914                 if (!back->is_data && !back->found_ref) {
1915                         err = 1;
1916                         if (!print_errs)
1917                                 goto out;
1918                         tback = (struct tree_backref *)back;
1919                         fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
1920                                 (unsigned long long)rec->start,
1921                                 back->full_backref ? "parent" : "root",
1922                                 back->full_backref ?
1923                                 (unsigned long long)tback->parent :
1924                                 (unsigned long long)tback->root, back);
1925                 }
1926                 if (back->is_data) {
1927                         dback = (struct data_backref *)back;
1928                         if (dback->found_ref != dback->num_refs) {
1929                                 err = 1;
1930                                 if (!print_errs)
1931                                         goto out;
1932                                 fprintf(stderr, "Incorrect local backref count"
1933                                         " on %llu %s %llu owner %llu"
1934                                         " offset %llu found %u wanted %u back %p\n",
1935                                         (unsigned long long)rec->start,
1936                                         back->full_backref ?
1937                                         "parent" : "root",
1938                                         back->full_backref ? 
1939                                         (unsigned long long)dback->parent:
1940                                         (unsigned long long)dback->root,
1941                                         (unsigned long long)dback->owner,
1942                                         (unsigned long long)dback->offset,
1943                                         dback->found_ref, dback->num_refs, back);
1944                         }
1945                         if (dback->disk_bytenr != rec->start) {
1946                                 err = 1;
1947                                 if (!print_errs)
1948                                         goto out;
1949                                 fprintf(stderr, "Backref disk bytenr does not"
1950                                         " match extent record, bytenr=%llu, "
1951                                         "ref bytenr=%llu\n",
1952                                         (unsigned long long)rec->start,
1953                                         (unsigned long long)dback->disk_bytenr);
1954                         }
1955
1956                         if (dback->bytes != rec->nr) {
1957                                 err = 1;
1958                                 if (!print_errs)
1959                                         goto out;
1960                                 fprintf(stderr, "Backref bytes do not match "
1961                                         "extent backref, bytenr=%llu, ref "
1962                                         "bytes=%llu, backref bytes=%llu\n",
1963                                         (unsigned long long)rec->start,
1964                                         (unsigned long long)rec->nr,
1965                                         (unsigned long long)dback->bytes);
1966                         }
1967                 }
1968                 if (!back->is_data) {
1969                         found += 1;
1970                 } else {
1971                         dback = (struct data_backref *)back;
1972                         found += dback->found_ref;
1973                 }
1974         }
1975         if (found != rec->refs) {
1976                 err = 1;
1977                 if (!print_errs)
1978                         goto out;
1979                 fprintf(stderr, "Incorrect global backref count "
1980                         "on %llu found %llu wanted %llu\n",
1981                         (unsigned long long)rec->start,
1982                         (unsigned long long)found,
1983                         (unsigned long long)rec->refs);
1984         }
1985 out:
1986         return err;
1987 }
1988
1989 static int free_all_extent_backrefs(struct extent_record *rec)
1990 {
1991         struct extent_backref *back;
1992         struct list_head *cur;
1993         while (!list_empty(&rec->backrefs)) {
1994                 cur = rec->backrefs.next;
1995                 back = list_entry(cur, struct extent_backref, list);
1996                 list_del(cur);
1997                 free(back);
1998         }
1999         return 0;
2000 }
2001
2002 static void free_extent_cache(struct btrfs_fs_info *fs_info,
2003                               struct cache_tree *extent_cache)
2004 {
2005         struct cache_extent *cache;
2006         struct extent_record *rec;
2007
2008         while (1) {
2009                 cache = find_first_cache_extent(extent_cache, 0);
2010                 if (!cache)
2011                         break;
2012                 rec = container_of(cache, struct extent_record, cache);
2013                 btrfs_unpin_extent(fs_info, rec->start, rec->max_size);
2014                 remove_cache_extent(extent_cache, cache);
2015                 free_all_extent_backrefs(rec);
2016                 free(rec);
2017         }
2018 }
2019
2020 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
2021                                  struct extent_record *rec)
2022 {
2023         if (rec->content_checked && rec->owner_ref_checked &&
2024             rec->extent_item_refs == rec->refs && rec->refs > 0 &&
2025             rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
2026                 remove_cache_extent(extent_cache, &rec->cache);
2027                 free_all_extent_backrefs(rec);
2028                 list_del_init(&rec->list);
2029                 free(rec);
2030         }
2031         return 0;
2032 }
2033
2034 static int check_owner_ref(struct btrfs_root *root,
2035                             struct extent_record *rec,
2036                             struct extent_buffer *buf)
2037 {
2038         struct extent_backref *node;
2039         struct tree_backref *back;
2040         struct btrfs_root *ref_root;
2041         struct btrfs_key key;
2042         struct btrfs_path path;
2043         struct extent_buffer *parent;
2044         int level;
2045         int found = 0;
2046         int ret;
2047
2048         list_for_each_entry(node, &rec->backrefs, list) {
2049                 if (node->is_data)
2050                         continue;
2051                 if (!node->found_ref)
2052                         continue;
2053                 if (node->full_backref)
2054                         continue;
2055                 back = (struct tree_backref *)node;
2056                 if (btrfs_header_owner(buf) == back->root)
2057                         return 0;
2058         }
2059         BUG_ON(rec->is_root);
2060
2061         /* try to find the block by search corresponding fs tree */
2062         key.objectid = btrfs_header_owner(buf);
2063         key.type = BTRFS_ROOT_ITEM_KEY;
2064         key.offset = (u64)-1;
2065
2066         ref_root = btrfs_read_fs_root(root->fs_info, &key);
2067         if (IS_ERR(ref_root))
2068                 return 1;
2069
2070         level = btrfs_header_level(buf);
2071         if (level == 0)
2072                 btrfs_item_key_to_cpu(buf, &key, 0);
2073         else
2074                 btrfs_node_key_to_cpu(buf, &key, 0);
2075
2076         btrfs_init_path(&path);
2077         path.lowest_level = level + 1;
2078         ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
2079         if (ret < 0)
2080                 return 0;
2081
2082         parent = path.nodes[level + 1];
2083         if (parent && buf->start == btrfs_node_blockptr(parent,
2084                                                         path.slots[level + 1]))
2085                 found = 1;
2086
2087         btrfs_release_path(ref_root, &path);
2088         return found ? 0 : 1;
2089 }
2090
2091 static int is_extent_tree_record(struct extent_record *rec)
2092 {
2093         struct list_head *cur = rec->backrefs.next;
2094         struct extent_backref *node;
2095         struct tree_backref *back;
2096         int is_extent = 0;
2097
2098         while(cur != &rec->backrefs) {
2099                 node = list_entry(cur, struct extent_backref, list);
2100                 cur = cur->next;
2101                 if (node->is_data)
2102                         return 0;
2103                 back = (struct tree_backref *)node;
2104                 if (node->full_backref)
2105                         return 0;
2106                 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
2107                         is_extent = 1;
2108         }
2109         return is_extent;
2110 }
2111
2112
2113 static int record_bad_block_io(struct btrfs_fs_info *info,
2114                                struct cache_tree *extent_cache,
2115                                u64 start, u64 len)
2116 {
2117         struct extent_record *rec;
2118         struct cache_extent *cache;
2119         struct btrfs_key key;
2120
2121         cache = find_cache_extent(extent_cache, start, len);
2122         if (!cache)
2123                 return 0;
2124
2125         rec = container_of(cache, struct extent_record, cache);
2126         if (!is_extent_tree_record(rec))
2127                 return 0;
2128
2129         btrfs_disk_key_to_cpu(&key, &rec->parent_key);
2130         return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
2131 }
2132
2133 static int check_block(struct btrfs_root *root,
2134                        struct cache_tree *extent_cache,
2135                        struct extent_buffer *buf, u64 flags)
2136 {
2137         struct extent_record *rec;
2138         struct cache_extent *cache;
2139         struct btrfs_key key;
2140         int ret = 1;
2141         int level;
2142
2143         cache = find_cache_extent(extent_cache, buf->start, buf->len);
2144         if (!cache)
2145                 return 1;
2146         rec = container_of(cache, struct extent_record, cache);
2147         rec->generation = btrfs_header_generation(buf);
2148
2149         level = btrfs_header_level(buf);
2150         if (btrfs_header_nritems(buf) > 0) {
2151
2152                 if (level == 0)
2153                         btrfs_item_key_to_cpu(buf, &key, 0);
2154                 else
2155                         btrfs_node_key_to_cpu(buf, &key, 0);
2156
2157                 rec->info_objectid = key.objectid;
2158         }
2159         rec->info_level = level;
2160
2161         if (btrfs_is_leaf(buf))
2162                 ret = btrfs_check_leaf(root, &rec->parent_key, buf);
2163         else
2164                 ret = btrfs_check_node(root, &rec->parent_key, buf);
2165
2166         if (ret) {
2167                 fprintf(stderr, "bad block %llu\n",
2168                         (unsigned long long)buf->start);
2169         } else {
2170                 rec->content_checked = 1;
2171                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
2172                         rec->owner_ref_checked = 1;
2173                 else {
2174                         ret = check_owner_ref(root, rec, buf);
2175                         if (!ret)
2176                                 rec->owner_ref_checked = 1;
2177                 }
2178         }
2179         if (!ret)
2180                 maybe_free_extent_rec(extent_cache, rec);
2181         return ret;
2182 }
2183
2184 static struct tree_backref *find_tree_backref(struct extent_record *rec,
2185                                                 u64 parent, u64 root)
2186 {
2187         struct list_head *cur = rec->backrefs.next;
2188         struct extent_backref *node;
2189         struct tree_backref *back;
2190
2191         while(cur != &rec->backrefs) {
2192                 node = list_entry(cur, struct extent_backref, list);
2193                 cur = cur->next;
2194                 if (node->is_data)
2195                         continue;
2196                 back = (struct tree_backref *)node;
2197                 if (parent > 0) {
2198                         if (!node->full_backref)
2199                                 continue;
2200                         if (parent == back->parent)
2201                                 return back;
2202                 } else {
2203                         if (node->full_backref)
2204                                 continue;
2205                         if (back->root == root)
2206                                 return back;
2207                 }
2208         }
2209         return NULL;
2210 }
2211
2212 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
2213                                                 u64 parent, u64 root)
2214 {
2215         struct tree_backref *ref = malloc(sizeof(*ref));
2216         memset(&ref->node, 0, sizeof(ref->node));
2217         if (parent > 0) {
2218                 ref->parent = parent;
2219                 ref->node.full_backref = 1;
2220         } else {
2221                 ref->root = root;
2222                 ref->node.full_backref = 0;
2223         }
2224         list_add_tail(&ref->node.list, &rec->backrefs);
2225
2226         return ref;
2227 }
2228
2229 static struct data_backref *find_data_backref(struct extent_record *rec,
2230                                                 u64 parent, u64 root,
2231                                                 u64 owner, u64 offset,
2232                                                 int found_ref,
2233                                                 u64 disk_bytenr, u64 bytes)
2234 {
2235         struct list_head *cur = rec->backrefs.next;
2236         struct extent_backref *node;
2237         struct data_backref *back;
2238
2239         while(cur != &rec->backrefs) {
2240                 node = list_entry(cur, struct extent_backref, list);
2241                 cur = cur->next;
2242                 if (!node->is_data)
2243                         continue;
2244                 back = (struct data_backref *)node;
2245                 if (parent > 0) {
2246                         if (!node->full_backref)
2247                                 continue;
2248                         if (parent == back->parent)
2249                                 return back;
2250                 } else {
2251                         if (node->full_backref)
2252                                 continue;
2253                         if (back->root == root && back->owner == owner &&
2254                             back->offset == offset) {
2255                                 if (found_ref && node->found_ref &&
2256                                     (back->bytes != bytes ||
2257                                     back->disk_bytenr != disk_bytenr))
2258                                         continue;
2259                                 return back;
2260                         }
2261                 }
2262         }
2263         return NULL;
2264 }
2265
2266 static struct data_backref *alloc_data_backref(struct extent_record *rec,
2267                                                 u64 parent, u64 root,
2268                                                 u64 owner, u64 offset,
2269                                                 u64 max_size)
2270 {
2271         struct data_backref *ref = malloc(sizeof(*ref));
2272         memset(&ref->node, 0, sizeof(ref->node));
2273         ref->node.is_data = 1;
2274
2275         if (parent > 0) {
2276                 ref->parent = parent;
2277                 ref->owner = 0;
2278                 ref->offset = 0;
2279                 ref->node.full_backref = 1;
2280         } else {
2281                 ref->root = root;
2282                 ref->owner = owner;
2283                 ref->offset = offset;
2284                 ref->node.full_backref = 0;
2285         }
2286         ref->bytes = max_size;
2287         ref->found_ref = 0;
2288         ref->num_refs = 0;
2289         list_add_tail(&ref->node.list, &rec->backrefs);
2290         if (max_size > rec->max_size)
2291                 rec->max_size = max_size;
2292         return ref;
2293 }
2294
2295 static int add_extent_rec(struct cache_tree *extent_cache,
2296                           struct btrfs_key *parent_key,
2297                           u64 start, u64 nr, u64 extent_item_refs,
2298                           int is_root, int inc_ref, int set_checked,
2299                           int metadata, int extent_rec, u64 max_size)
2300 {
2301         struct extent_record *rec;
2302         struct cache_extent *cache;
2303         int ret = 0;
2304         int dup = 0;
2305
2306         cache = find_cache_extent(extent_cache, start, nr);
2307         if (cache) {
2308                 rec = container_of(cache, struct extent_record, cache);
2309                 if (inc_ref)
2310                         rec->refs++;
2311                 if (rec->nr == 1)
2312                         rec->nr = max(nr, max_size);
2313
2314                 /*
2315                  * We need to make sure to reset nr to whatever the extent
2316                  * record says was the real size, this way we can compare it to
2317                  * the backrefs.
2318                  */
2319                 if (extent_rec) {
2320                         if (start != rec->start || rec->found_rec) {
2321                                 struct extent_record *tmp;
2322
2323                                 dup = 1;
2324                                 if (list_empty(&rec->list))
2325                                         list_add_tail(&rec->list,
2326                                                       &duplicate_extents);
2327
2328                                 /*
2329                                  * We have to do this song and dance in case we
2330                                  * find an extent record that falls inside of
2331                                  * our current extent record but does not have
2332                                  * the same objectid.
2333                                  */
2334                                 tmp = malloc(sizeof(*tmp));
2335                                 if (!tmp)
2336                                         return -ENOMEM;
2337                                 tmp->start = start;
2338                                 tmp->max_size = max_size;
2339                                 tmp->nr = nr;
2340                                 tmp->found_rec = 1;
2341                                 tmp->metadata = metadata;
2342                                 tmp->extent_item_refs = extent_item_refs;
2343                                 INIT_LIST_HEAD(&tmp->list);
2344                                 list_add_tail(&tmp->list, &rec->dups);
2345                                 rec->num_duplicates++;
2346                         } else {
2347                                 rec->nr = nr;
2348                                 rec->found_rec = 1;
2349                         }
2350                 }
2351
2352                 if (extent_item_refs && !dup) {
2353                         if (rec->extent_item_refs) {
2354                                 fprintf(stderr, "block %llu rec "
2355                                         "extent_item_refs %llu, passed %llu\n",
2356                                         (unsigned long long)start,
2357                                         (unsigned long long)
2358                                                         rec->extent_item_refs,
2359                                         (unsigned long long)extent_item_refs);
2360                         }
2361                         rec->extent_item_refs = extent_item_refs;
2362                 }
2363                 if (is_root)
2364                         rec->is_root = 1;
2365                 if (set_checked) {
2366                         rec->content_checked = 1;
2367                         rec->owner_ref_checked = 1;
2368                 }
2369
2370                 if (parent_key)
2371                         btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2372
2373                 if (rec->max_size < max_size)
2374                         rec->max_size = max_size;
2375
2376                 maybe_free_extent_rec(extent_cache, rec);
2377                 return ret;
2378         }
2379         rec = malloc(sizeof(*rec));
2380         rec->start = start;
2381         rec->max_size = max_size;
2382         rec->nr = max(nr, max_size);
2383         rec->found_rec = extent_rec;
2384         rec->content_checked = 0;
2385         rec->owner_ref_checked = 0;
2386         rec->num_duplicates = 0;
2387         rec->metadata = metadata;
2388         INIT_LIST_HEAD(&rec->backrefs);
2389         INIT_LIST_HEAD(&rec->dups);
2390         INIT_LIST_HEAD(&rec->list);
2391
2392         if (is_root)
2393                 rec->is_root = 1;
2394         else
2395                 rec->is_root = 0;
2396
2397         if (inc_ref)
2398                 rec->refs = 1;
2399         else
2400                 rec->refs = 0;
2401
2402         if (extent_item_refs)
2403                 rec->extent_item_refs = extent_item_refs;
2404         else
2405                 rec->extent_item_refs = 0;
2406
2407         if (parent_key)
2408                 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2409         else
2410                 memset(&rec->parent_key, 0, sizeof(*parent_key));
2411
2412         rec->cache.start = start;
2413         rec->cache.size = nr;
2414         ret = insert_existing_cache_extent(extent_cache, &rec->cache);
2415         BUG_ON(ret);
2416         bytes_used += nr;
2417         if (set_checked) {
2418                 rec->content_checked = 1;
2419                 rec->owner_ref_checked = 1;
2420         }
2421         return ret;
2422 }
2423
2424 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
2425                             u64 parent, u64 root, int found_ref)
2426 {
2427         struct extent_record *rec;
2428         struct tree_backref *back;
2429         struct cache_extent *cache;
2430
2431         cache = find_cache_extent(extent_cache, bytenr, 1);
2432         if (!cache) {
2433                 add_extent_rec(extent_cache, NULL, bytenr,
2434                                1, 0, 0, 0, 0, 1, 0, 0);
2435                 cache = find_cache_extent(extent_cache, bytenr, 1);
2436                 if (!cache)
2437                         abort();
2438         }
2439
2440         rec = container_of(cache, struct extent_record, cache);
2441         if (rec->start != bytenr) {
2442                 abort();
2443         }
2444
2445         back = find_tree_backref(rec, parent, root);
2446         if (!back)
2447                 back = alloc_tree_backref(rec, parent, root);
2448
2449         if (found_ref) {
2450                 if (back->node.found_ref) {
2451                         fprintf(stderr, "Extent back ref already exists "
2452                                 "for %llu parent %llu root %llu \n",
2453                                 (unsigned long long)bytenr,
2454                                 (unsigned long long)parent,
2455                                 (unsigned long long)root);
2456                 }
2457                 back->node.found_ref = 1;
2458         } else {
2459                 if (back->node.found_extent_tree) {
2460                         fprintf(stderr, "Extent back ref already exists "
2461                                 "for %llu parent %llu root %llu \n",
2462                                 (unsigned long long)bytenr,
2463                                 (unsigned long long)parent,
2464                                 (unsigned long long)root);
2465                 }
2466                 back->node.found_extent_tree = 1;
2467         }
2468         return 0;
2469 }
2470
2471 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
2472                             u64 parent, u64 root, u64 owner, u64 offset,
2473                             u32 num_refs, int found_ref, u64 max_size)
2474 {
2475         struct extent_record *rec;
2476         struct data_backref *back;
2477         struct cache_extent *cache;
2478
2479         cache = find_cache_extent(extent_cache, bytenr, 1);
2480         if (!cache) {
2481                 add_extent_rec(extent_cache, NULL, bytenr, 1, 0, 0, 0, 0,
2482                                0, 0, max_size);
2483                 cache = find_cache_extent(extent_cache, bytenr, 1);
2484                 if (!cache)
2485                         abort();
2486         }
2487
2488         rec = container_of(cache, struct extent_record, cache);
2489         if (rec->max_size < max_size)
2490                 rec->max_size = max_size;
2491
2492         /*
2493          * If found_ref is set then max_size is the real size and must match the
2494          * existing refs.  So if we have already found a ref then we need to
2495          * make sure that this ref matches the existing one, otherwise we need
2496          * to add a new backref so we can notice that the backrefs don't match
2497          * and we need to figure out who is telling the truth.  This is to
2498          * account for that awful fsync bug I introduced where we'd end up with
2499          * a btrfs_file_extent_item that would have its length include multiple
2500          * prealloc extents or point inside of a prealloc extent.
2501          */
2502         back = find_data_backref(rec, parent, root, owner, offset, found_ref,
2503                                  bytenr, max_size);
2504         if (!back)
2505                 back = alloc_data_backref(rec, parent, root, owner, offset,
2506                                           max_size);
2507
2508         if (found_ref) {
2509                 BUG_ON(num_refs != 1);
2510                 if (back->node.found_ref)
2511                         BUG_ON(back->bytes != max_size);
2512                 back->node.found_ref = 1;
2513                 back->found_ref += 1;
2514                 back->bytes = max_size;
2515                 back->disk_bytenr = bytenr;
2516                 rec->refs += 1;
2517                 rec->content_checked = 1;
2518                 rec->owner_ref_checked = 1;
2519         } else {
2520                 if (back->node.found_extent_tree) {
2521                         fprintf(stderr, "Extent back ref already exists "
2522                                 "for %llu parent %llu root %llu"
2523                                 "owner %llu offset %llu num_refs %lu\n",
2524                                 (unsigned long long)bytenr,
2525                                 (unsigned long long)parent,
2526                                 (unsigned long long)root,
2527                                 (unsigned long long)owner,
2528                                 (unsigned long long)offset,
2529                                 (unsigned long)num_refs);
2530                 }
2531                 back->num_refs = num_refs;
2532                 back->node.found_extent_tree = 1;
2533         }
2534         return 0;
2535 }
2536
2537 static int add_pending(struct cache_tree *pending,
2538                        struct cache_tree *seen, u64 bytenr, u32 size)
2539 {
2540         int ret;
2541         ret = insert_cache_extent(seen, bytenr, size);
2542         if (ret)
2543                 return ret;
2544         insert_cache_extent(pending, bytenr, size);
2545         return 0;
2546 }
2547
2548 static int pick_next_pending(struct cache_tree *pending,
2549                         struct cache_tree *reada,
2550                         struct cache_tree *nodes,
2551                         u64 last, struct block_info *bits, int bits_nr,
2552                         int *reada_bits)
2553 {
2554         unsigned long node_start = last;
2555         struct cache_extent *cache;
2556         int ret;
2557
2558         cache = find_first_cache_extent(reada, 0);
2559         if (cache) {
2560                 bits[0].start = cache->start;
2561                 bits[1].size = cache->size;
2562                 *reada_bits = 1;
2563                 return 1;
2564         }
2565         *reada_bits = 0;
2566         if (node_start > 32768)
2567                 node_start -= 32768;
2568
2569         cache = find_first_cache_extent(nodes, node_start);
2570         if (!cache)
2571                 cache = find_first_cache_extent(nodes, 0);
2572
2573         if (!cache) {
2574                  cache = find_first_cache_extent(pending, 0);
2575                  if (!cache)
2576                          return 0;
2577                  ret = 0;
2578                  do {
2579                          bits[ret].start = cache->start;
2580                          bits[ret].size = cache->size;
2581                          cache = next_cache_extent(cache);
2582                          ret++;
2583                  } while (cache && ret < bits_nr);
2584                  return ret;
2585         }
2586
2587         ret = 0;
2588         do {
2589                 bits[ret].start = cache->start;
2590                 bits[ret].size = cache->size;
2591                 cache = next_cache_extent(cache);
2592                 ret++;
2593         } while (cache && ret < bits_nr);
2594
2595         if (bits_nr - ret > 8) {
2596                 u64 lookup = bits[0].start + bits[0].size;
2597                 struct cache_extent *next;
2598                 next = find_first_cache_extent(pending, lookup);
2599                 while(next) {
2600                         if (next->start - lookup > 32768)
2601                                 break;
2602                         bits[ret].start = next->start;
2603                         bits[ret].size = next->size;
2604                         lookup = next->start + next->size;
2605                         ret++;
2606                         if (ret == bits_nr)
2607                                 break;
2608                         next = next_cache_extent(next);
2609                         if (!next)
2610                                 break;
2611                 }
2612         }
2613         return ret;
2614 }
2615
2616 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2617 static int process_extent_ref_v0(struct cache_tree *extent_cache,
2618                                  struct extent_buffer *leaf, int slot)
2619 {
2620         struct btrfs_extent_ref_v0 *ref0;
2621         struct btrfs_key key;
2622
2623         btrfs_item_key_to_cpu(leaf, &key, slot);
2624         ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
2625         if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
2626                 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
2627         } else {
2628                 add_data_backref(extent_cache, key.objectid, key.offset, 0,
2629                                  0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
2630         }
2631         return 0;
2632 }
2633 #endif
2634
2635 static int process_extent_item(struct btrfs_root *root,
2636                                struct cache_tree *extent_cache,
2637                                struct extent_buffer *eb, int slot)
2638 {
2639         struct btrfs_extent_item *ei;
2640         struct btrfs_extent_inline_ref *iref;
2641         struct btrfs_extent_data_ref *dref;
2642         struct btrfs_shared_data_ref *sref;
2643         struct btrfs_key key;
2644         unsigned long end;
2645         unsigned long ptr;
2646         int type;
2647         u32 item_size = btrfs_item_size_nr(eb, slot);
2648         u64 refs = 0;
2649         u64 offset;
2650         u64 num_bytes;
2651         int metadata = 0;
2652
2653         btrfs_item_key_to_cpu(eb, &key, slot);
2654
2655         if (key.type == BTRFS_METADATA_ITEM_KEY) {
2656                 metadata = 1;
2657                 num_bytes = root->leafsize;
2658         } else {
2659                 num_bytes = key.offset;
2660         }
2661
2662         if (item_size < sizeof(*ei)) {
2663 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2664                 struct btrfs_extent_item_v0 *ei0;
2665                 BUG_ON(item_size != sizeof(*ei0));
2666                 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
2667                 refs = btrfs_extent_refs_v0(eb, ei0);
2668 #else
2669                 BUG();
2670 #endif
2671                 return add_extent_rec(extent_cache, NULL, key.objectid,
2672                                       num_bytes, refs, 0, 0, 0, metadata, 1,
2673                                       num_bytes);
2674         }
2675
2676         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
2677         refs = btrfs_extent_refs(eb, ei);
2678
2679         add_extent_rec(extent_cache, NULL, key.objectid, num_bytes,
2680                        refs, 0, 0, 0, metadata, 1, num_bytes);
2681
2682         ptr = (unsigned long)(ei + 1);
2683         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
2684             key.type == BTRFS_EXTENT_ITEM_KEY)
2685                 ptr += sizeof(struct btrfs_tree_block_info);
2686
2687         end = (unsigned long)ei + item_size;
2688         while (ptr < end) {
2689                 iref = (struct btrfs_extent_inline_ref *)ptr;
2690                 type = btrfs_extent_inline_ref_type(eb, iref);
2691                 offset = btrfs_extent_inline_ref_offset(eb, iref);
2692                 switch (type) {
2693                 case BTRFS_TREE_BLOCK_REF_KEY:
2694                         add_tree_backref(extent_cache, key.objectid,
2695                                          0, offset, 0);
2696                         break;
2697                 case BTRFS_SHARED_BLOCK_REF_KEY:
2698                         add_tree_backref(extent_cache, key.objectid,
2699                                          offset, 0, 0);
2700                         break;
2701                 case BTRFS_EXTENT_DATA_REF_KEY:
2702                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
2703                         add_data_backref(extent_cache, key.objectid, 0,
2704                                         btrfs_extent_data_ref_root(eb, dref),
2705                                         btrfs_extent_data_ref_objectid(eb,
2706                                                                        dref),
2707                                         btrfs_extent_data_ref_offset(eb, dref),
2708                                         btrfs_extent_data_ref_count(eb, dref),
2709                                         0, num_bytes);
2710                         break;
2711                 case BTRFS_SHARED_DATA_REF_KEY:
2712                         sref = (struct btrfs_shared_data_ref *)(iref + 1);
2713                         add_data_backref(extent_cache, key.objectid, offset,
2714                                         0, 0, 0,
2715                                         btrfs_shared_data_ref_count(eb, sref),
2716                                         0, num_bytes);
2717                         break;
2718                 default:
2719                         fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
2720                                 key.objectid, key.type, num_bytes);
2721                         goto out;
2722                 }
2723                 ptr += btrfs_extent_inline_ref_size(type);
2724         }
2725         WARN_ON(ptr > end);
2726 out:
2727         return 0;
2728 }
2729
2730 static int check_cache_range(struct btrfs_root *root,
2731                              struct btrfs_block_group_cache *cache,
2732                              u64 offset, u64 bytes)
2733 {
2734         struct btrfs_free_space *entry;
2735         u64 *logical;
2736         u64 bytenr;
2737         int stripe_len;
2738         int i, nr, ret;
2739
2740         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2741                 bytenr = btrfs_sb_offset(i);
2742                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
2743                                        cache->key.objectid, bytenr, 0,
2744                                        &logical, &nr, &stripe_len);
2745                 if (ret)
2746                         return ret;
2747
2748                 while (nr--) {
2749                         if (logical[nr] + stripe_len <= offset)
2750                                 continue;
2751                         if (offset + bytes <= logical[nr])
2752                                 continue;
2753                         if (logical[nr] == offset) {
2754                                 if (stripe_len >= bytes) {
2755                                         kfree(logical);
2756                                         return 0;
2757                                 }
2758                                 bytes -= stripe_len;
2759                                 offset += stripe_len;
2760                         } else if (logical[nr] < offset) {
2761                                 if (logical[nr] + stripe_len >=
2762                                     offset + bytes) {
2763                                         kfree(logical);
2764                                         return 0;
2765                                 }
2766                                 bytes = (offset + bytes) -
2767                                         (logical[nr] + stripe_len);
2768                                 offset = logical[nr] + stripe_len;
2769                         } else {
2770                                 /*
2771                                  * Could be tricky, the super may land in the
2772                                  * middle of the area we're checking.  First
2773                                  * check the easiest case, it's at the end.
2774                                  */
2775                                 if (logical[nr] + stripe_len >=
2776                                     bytes + offset) {
2777                                         bytes = logical[nr] - offset;
2778                                         continue;
2779                                 }
2780
2781                                 /* Check the left side */
2782                                 ret = check_cache_range(root, cache,
2783                                                         offset,
2784                                                         logical[nr] - offset);
2785                                 if (ret) {
2786                                         kfree(logical);
2787                                         return ret;
2788                                 }
2789
2790                                 /* Now we continue with the right side */
2791                                 bytes = (offset + bytes) -
2792                                         (logical[nr] + stripe_len);
2793                                 offset = logical[nr] + stripe_len;
2794                         }
2795                 }
2796
2797                 kfree(logical);
2798         }
2799
2800         entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
2801         if (!entry) {
2802                 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
2803                         offset, offset+bytes);
2804                 return -EINVAL;
2805         }
2806
2807         if (entry->offset != offset) {
2808                 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
2809                         entry->offset);
2810                 return -EINVAL;
2811         }
2812
2813         if (entry->bytes != bytes) {
2814                 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
2815                         bytes, entry->bytes, offset);
2816                 return -EINVAL;
2817         }
2818
2819         unlink_free_space(cache->free_space_ctl, entry);
2820         free(entry);
2821         return 0;
2822 }
2823
2824 static int verify_space_cache(struct btrfs_root *root,
2825                               struct btrfs_block_group_cache *cache)
2826 {
2827         struct btrfs_path *path;
2828         struct extent_buffer *leaf;
2829         struct btrfs_key key;
2830         u64 last;
2831         int ret = 0;
2832
2833         path = btrfs_alloc_path();
2834         if (!path)
2835                 return -ENOMEM;
2836
2837         root = root->fs_info->extent_root;
2838
2839         last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
2840
2841         key.objectid = last;
2842         key.offset = 0;
2843         key.type = BTRFS_EXTENT_ITEM_KEY;
2844
2845         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2846         if (ret < 0)
2847                 return ret;
2848         ret = 0;
2849         while (1) {
2850                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2851                         ret = btrfs_next_leaf(root, path);
2852                         if (ret < 0)
2853                                 return ret;
2854                         if (ret > 0) {
2855                                 ret = 0;
2856                                 break;
2857                         }
2858                 }
2859                 leaf = path->nodes[0];
2860                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2861                 if (key.objectid >= cache->key.offset + cache->key.objectid)
2862                         break;
2863                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
2864                     key.type != BTRFS_METADATA_ITEM_KEY) {
2865                         path->slots[0]++;
2866                         continue;
2867                 }
2868
2869                 if (last == key.objectid) {
2870                         if (key.type == BTRFS_EXTENT_ITEM_KEY)
2871                                 last = key.objectid + key.offset;
2872                         else
2873                                 last = key.objectid + root->leafsize;
2874                         path->slots[0]++;
2875                         continue;
2876                 }
2877
2878                 ret = check_cache_range(root, cache, last,
2879                                         key.objectid - last);
2880                 if (ret)
2881                         break;
2882                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
2883                         last = key.objectid + key.offset;
2884                 else
2885                         last = key.objectid + root->leafsize;
2886                 path->slots[0]++;
2887         }
2888
2889         if (last < cache->key.objectid + cache->key.offset)
2890                 ret = check_cache_range(root, cache, last,
2891                                         cache->key.objectid +
2892                                         cache->key.offset - last);
2893         btrfs_free_path(path);
2894
2895         if (!ret &&
2896             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
2897                 fprintf(stderr, "There are still entries left in the space "
2898                         "cache\n");
2899                 ret = -EINVAL;
2900         }
2901
2902         return ret;
2903 }
2904
2905 static int check_space_cache(struct btrfs_root *root)
2906 {
2907         struct btrfs_block_group_cache *cache;
2908         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
2909         int ret;
2910         int error = 0;
2911
2912         if (btrfs_super_generation(root->fs_info->super_copy) !=
2913             btrfs_super_cache_generation(root->fs_info->super_copy)) {
2914                 printf("cache and super generation don't match, space cache "
2915                        "will be invalidated\n");
2916                 return 0;
2917         }
2918
2919         while (1) {
2920                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
2921                 if (!cache)
2922                         break;
2923
2924                 start = cache->key.objectid + cache->key.offset;
2925                 if (!cache->free_space_ctl) {
2926                         if (btrfs_init_free_space_ctl(cache,
2927                                                       root->sectorsize)) {
2928                                 ret = -ENOMEM;
2929                                 break;
2930                         }
2931                 } else {
2932                         btrfs_remove_free_space_cache(cache);
2933                 }
2934
2935                 ret = load_free_space_cache(root->fs_info, cache);
2936                 if (!ret)
2937                         continue;
2938
2939                 ret = verify_space_cache(root, cache);
2940                 if (ret) {
2941                         fprintf(stderr, "cache appears valid but isnt %Lu\n",
2942                                 cache->key.objectid);
2943                         error++;
2944                 }
2945         }
2946
2947         return error ? -EINVAL : 0;
2948 }
2949
2950 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
2951                                u64 num_bytes)
2952 {
2953         struct btrfs_path *path;
2954         struct extent_buffer *leaf;
2955         struct btrfs_key key;
2956         int ret;
2957
2958         path = btrfs_alloc_path();
2959         if (!path) {
2960                 fprintf(stderr, "Error allocing path\n");
2961                 return -ENOMEM;
2962         }
2963
2964         key.objectid = bytenr;
2965         key.type = BTRFS_EXTENT_ITEM_KEY;
2966         key.offset = 0;
2967
2968
2969 again:
2970         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
2971                                 0, 0);
2972         if (ret < 0) {
2973                 fprintf(stderr, "Error looking up extent record %d\n", ret);
2974                 btrfs_free_path(path);
2975                 return ret;
2976         } else if (ret) {
2977                 if (path->slots[0])
2978                         path->slots[0]--;
2979                 else
2980                         btrfs_prev_leaf(root, path);
2981         }
2982
2983         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2984
2985         /*
2986          * Block group items come before extent items if they have the same
2987          * bytenr, so walk back one more just in case.  Dear future traveler,
2988          * first congrats on mastering time travel.  Now if it's not too much
2989          * trouble could you go back to 2006 and tell Chris to make the
2990          * BLOCK_GROUP_ITEM_KEY lower than the EXTENT_ITEM_KEY please?
2991          */
2992         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
2993                 if (path->slots[0])
2994                         path->slots[0]--;
2995                 else
2996                         btrfs_prev_leaf(root, path);
2997         }
2998
2999         while (num_bytes) {
3000                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3001                         ret = btrfs_next_leaf(root, path);
3002                         if (ret < 0) {
3003                                 fprintf(stderr, "Error going to next leaf "
3004                                         "%d\n", ret);
3005                                 btrfs_free_path(path);
3006                                 return ret;
3007                         } else if (ret) {
3008                                 break;
3009                         }
3010                 }
3011                 leaf = path->nodes[0];
3012                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3013                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
3014                         path->slots[0]++;
3015                         continue;
3016                 }
3017                 if (key.objectid + key.offset < bytenr) {
3018                         path->slots[0]++;
3019                         continue;
3020                 }
3021                 if (key.objectid > bytenr + num_bytes)
3022                         break;
3023
3024                 if (key.objectid == bytenr) {
3025                         if (key.offset >= num_bytes) {
3026                                 num_bytes = 0;
3027                                 break;
3028                         }
3029                         num_bytes -= key.offset;
3030                         bytenr += key.offset;
3031                 } else if (key.objectid < bytenr) {
3032                         if (key.objectid + key.offset >= bytenr + num_bytes) {
3033                                 num_bytes = 0;
3034                                 break;
3035                         }
3036                         num_bytes = (bytenr + num_bytes) -
3037                                 (key.objectid + key.offset);
3038                         bytenr = key.objectid + key.offset;
3039                 } else {
3040                         if (key.objectid + key.offset < bytenr + num_bytes) {
3041                                 u64 new_start = key.objectid + key.offset;
3042                                 u64 new_bytes = bytenr + num_bytes - new_start;
3043
3044                                 /*
3045                                  * Weird case, the extent is in the middle of
3046                                  * our range, we'll have to search one side
3047                                  * and then the other.  Not sure if this happens
3048                                  * in real life, but no harm in coding it up
3049                                  * anyway just in case.
3050                                  */
3051                                 btrfs_release_path(root, path);
3052                                 ret = check_extent_exists(root, new_start,
3053                                                           new_bytes);
3054                                 if (ret) {
3055                                         fprintf(stderr, "Right section didn't "
3056                                                 "have a record\n");
3057                                         break;
3058                                 }
3059                                 num_bytes = key.objectid - bytenr;
3060                                 goto again;
3061                         }
3062                         num_bytes = key.objectid - bytenr;
3063                 }
3064                 path->slots[0]++;
3065         }
3066         ret = 0;
3067
3068         if (num_bytes) {
3069                 fprintf(stderr, "There are no extents for csum range "
3070                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
3071                 ret = 1;
3072         }
3073
3074         btrfs_free_path(path);
3075         return ret;
3076 }
3077
3078 static int check_csums(struct btrfs_root *root)
3079 {
3080         struct btrfs_path *path;
3081         struct extent_buffer *leaf;
3082         struct btrfs_key key;
3083         u64 offset = 0, num_bytes = 0;
3084         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
3085         int errors = 0;
3086         int ret;
3087
3088         root = root->fs_info->csum_root;
3089
3090         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
3091         key.type = BTRFS_EXTENT_CSUM_KEY;
3092         key.offset = 0;
3093
3094         path = btrfs_alloc_path();
3095         if (!path)
3096                 return -ENOMEM;
3097
3098         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3099         if (ret < 0) {
3100                 fprintf(stderr, "Error searching csum tree %d\n", ret);
3101                 btrfs_free_path(path);
3102                 return ret;
3103         }
3104
3105         if (ret > 0 && path->slots[0])
3106                 path->slots[0]--;
3107         ret = 0;
3108
3109         while (1) {
3110                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3111                         ret = btrfs_next_leaf(root, path);
3112                         if (ret < 0) {
3113                                 fprintf(stderr, "Error going to next leaf "
3114                                         "%d\n", ret);
3115                                 break;
3116                         }
3117                         if (ret)
3118                                 break;
3119                 }
3120                 leaf = path->nodes[0];
3121
3122                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3123                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
3124                         path->slots[0]++;
3125                         continue;
3126                 }
3127
3128                 if (!num_bytes) {
3129                         offset = key.offset;
3130                 } else if (key.offset != offset + num_bytes) {
3131                         ret = check_extent_exists(root, offset, num_bytes);
3132                         if (ret) {
3133                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
3134                                         "there is no extent record\n",
3135                                         offset, offset+num_bytes);
3136                                 errors++;
3137                         }
3138                         offset = key.offset;
3139                         num_bytes = 0;
3140                 }
3141
3142                 num_bytes += (btrfs_item_size_nr(leaf, path->slots[0]) /
3143                               csum_size) * root->sectorsize;
3144                 path->slots[0]++;
3145         }
3146
3147         btrfs_free_path(path);
3148         return errors;
3149 }
3150
3151 static int run_next_block(struct btrfs_root *root,
3152                           struct block_info *bits,
3153                           int bits_nr,
3154                           u64 *last,
3155                           struct cache_tree *pending,
3156                           struct cache_tree *seen,
3157                           struct cache_tree *reada,
3158                           struct cache_tree *nodes,
3159                           struct cache_tree *extent_cache)
3160 {
3161         struct extent_buffer *buf;
3162         u64 bytenr;
3163         u32 size;
3164         u64 parent;
3165         u64 owner;
3166         u64 flags;
3167         int ret;
3168         int i;
3169         int nritems;
3170         struct btrfs_key key;
3171         struct cache_extent *cache;
3172         int reada_bits;
3173
3174         ret = pick_next_pending(pending, reada, nodes, *last, bits,
3175                                 bits_nr, &reada_bits);
3176         if (ret == 0) {
3177                 return 1;
3178         }
3179         if (!reada_bits) {
3180                 for(i = 0; i < ret; i++) {
3181                         insert_cache_extent(reada, bits[i].start,
3182                                             bits[i].size);
3183
3184                         /* fixme, get the parent transid */
3185                         readahead_tree_block(root, bits[i].start,
3186                                              bits[i].size, 0);
3187                 }
3188         }
3189         *last = bits[0].start;
3190         bytenr = bits[0].start;
3191         size = bits[0].size;
3192
3193         cache = find_cache_extent(pending, bytenr, size);
3194         if (cache) {
3195                 remove_cache_extent(pending, cache);
3196                 free(cache);
3197         }
3198         cache = find_cache_extent(reada, bytenr, size);
3199         if (cache) {
3200                 remove_cache_extent(reada, cache);
3201                 free(cache);
3202         }
3203         cache = find_cache_extent(nodes, bytenr, size);
3204         if (cache) {
3205                 remove_cache_extent(nodes, cache);
3206                 free(cache);
3207         }
3208
3209         /* fixme, get the real parent transid */
3210         buf = read_tree_block(root, bytenr, size, 0);
3211         if (!extent_buffer_uptodate(buf)) {
3212                 record_bad_block_io(root->fs_info,
3213                                     extent_cache, bytenr, size);
3214                 goto out;
3215         }
3216
3217         nritems = btrfs_header_nritems(buf);
3218
3219         ret = btrfs_lookup_extent_info(NULL, root, bytenr,
3220                                        btrfs_header_level(buf), 1, NULL,
3221                                        &flags);
3222         if (ret < 0)
3223                 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3224
3225         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3226                 parent = bytenr;
3227                 owner = 0;
3228         } else {
3229                 parent = 0;
3230                 owner = btrfs_header_owner(buf);
3231         }
3232
3233         ret = check_block(root, extent_cache, buf, flags);
3234         if (ret)
3235                 goto out;
3236
3237         if (btrfs_is_leaf(buf)) {
3238                 btree_space_waste += btrfs_leaf_free_space(root, buf);
3239                 for (i = 0; i < nritems; i++) {
3240                         struct btrfs_file_extent_item *fi;
3241                         btrfs_item_key_to_cpu(buf, &key, i);
3242                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
3243                                 process_extent_item(root, extent_cache, buf,
3244                                                     i);
3245                                 continue;
3246                         }
3247                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
3248                                 process_extent_item(root, extent_cache, buf,
3249                                                     i);
3250                                 continue;
3251                         }
3252                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
3253                                 total_csum_bytes +=
3254                                         btrfs_item_size_nr(buf, i);
3255                                 continue;
3256                         }
3257                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
3258                                 continue;
3259                         }
3260                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
3261 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3262                                 process_extent_ref_v0(extent_cache, buf, i);
3263 #else
3264                                 BUG();
3265 #endif
3266                                 continue;
3267                         }
3268
3269                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
3270                                 add_tree_backref(extent_cache, key.objectid, 0,
3271                                                  key.offset, 0);
3272                                 continue;
3273                         }
3274                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
3275                                 add_tree_backref(extent_cache, key.objectid,
3276                                                  key.offset, 0, 0);
3277                                 continue;
3278                         }
3279                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
3280                                 struct btrfs_extent_data_ref *ref;
3281                                 ref = btrfs_item_ptr(buf, i,
3282                                                 struct btrfs_extent_data_ref);
3283                                 add_data_backref(extent_cache,
3284                                         key.objectid, 0,
3285                                         btrfs_extent_data_ref_root(buf, ref),
3286                                         btrfs_extent_data_ref_objectid(buf,
3287                                                                        ref),
3288                                         btrfs_extent_data_ref_offset(buf, ref),
3289                                         btrfs_extent_data_ref_count(buf, ref),
3290                                         0, root->sectorsize);
3291                                 continue;
3292                         }
3293                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
3294                                 struct btrfs_shared_data_ref *ref;
3295                                 ref = btrfs_item_ptr(buf, i,
3296                                                 struct btrfs_shared_data_ref);
3297                                 add_data_backref(extent_cache,
3298                                         key.objectid, key.offset, 0, 0, 0, 
3299                                         btrfs_shared_data_ref_count(buf, ref),
3300                                         0, root->sectorsize);
3301                                 continue;
3302                         }
3303                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3304                                 continue;
3305                         fi = btrfs_item_ptr(buf, i,
3306                                             struct btrfs_file_extent_item);
3307                         if (btrfs_file_extent_type(buf, fi) ==
3308                             BTRFS_FILE_EXTENT_INLINE)
3309                                 continue;
3310                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
3311                                 continue;
3312
3313                         data_bytes_allocated +=
3314                                 btrfs_file_extent_disk_num_bytes(buf, fi);
3315                         if (data_bytes_allocated < root->sectorsize) {
3316                                 abort();
3317                         }
3318                         data_bytes_referenced +=
3319                                 btrfs_file_extent_num_bytes(buf, fi);
3320                         add_data_backref(extent_cache,
3321                                 btrfs_file_extent_disk_bytenr(buf, fi),
3322                                 parent, owner, key.objectid, key.offset -
3323                                 btrfs_file_extent_offset(buf, fi), 1, 1,
3324                                 btrfs_file_extent_disk_num_bytes(buf, fi));
3325                         BUG_ON(ret);
3326                 }
3327         } else {
3328                 int level;
3329                 struct btrfs_key first_key;
3330
3331                 first_key.objectid = 0;
3332
3333                 if (nritems > 0)
3334                         btrfs_item_key_to_cpu(buf, &first_key, 0);
3335                 level = btrfs_header_level(buf);
3336                 for (i = 0; i < nritems; i++) {
3337                         u64 ptr = btrfs_node_blockptr(buf, i);
3338                         u32 size = btrfs_level_size(root, level - 1);
3339                         btrfs_node_key_to_cpu(buf, &key, i);
3340                         ret = add_extent_rec(extent_cache, &key,
3341                                              ptr, size, 0, 0, 1, 0, 1, 0,
3342                                              size);
3343                         BUG_ON(ret);
3344
3345                         add_tree_backref(extent_cache, ptr, parent, owner, 1);
3346
3347                         if (level > 1) {
3348                                 add_pending(nodes, seen, ptr, size);
3349                         } else {
3350                                 add_pending(pending, seen, ptr, size);
3351                         }
3352                 }
3353                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
3354                                       nritems) * sizeof(struct btrfs_key_ptr);
3355         }
3356         total_btree_bytes += buf->len;
3357         if (fs_root_objectid(btrfs_header_owner(buf)))
3358                 total_fs_tree_bytes += buf->len;
3359         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
3360                 total_extent_tree_bytes += buf->len;
3361         if (!found_old_backref &&
3362             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
3363             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
3364             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
3365                 found_old_backref = 1;
3366 out:
3367         free_extent_buffer(buf);
3368         return 0;
3369 }
3370
3371 static int add_root_to_pending(struct extent_buffer *buf,
3372                                struct cache_tree *extent_cache,
3373                                struct cache_tree *pending,
3374                                struct cache_tree *seen,
3375                                struct cache_tree *nodes,
3376                                struct btrfs_key *root_key)
3377 {
3378         if (btrfs_header_level(buf) > 0)
3379                 add_pending(nodes, seen, buf->start, buf->len);
3380         else
3381                 add_pending(pending, seen, buf->start, buf->len);
3382         add_extent_rec(extent_cache, NULL, buf->start, buf->len,
3383                        0, 1, 1, 0, 1, 0, buf->len);
3384
3385         if (root_key->objectid == BTRFS_TREE_RELOC_OBJECTID ||
3386             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3387                 add_tree_backref(extent_cache, buf->start, buf->start,
3388                                  0, 1);
3389         else
3390                 add_tree_backref(extent_cache, buf->start, 0,
3391                                  root_key->objectid, 1);
3392         return 0;
3393 }
3394
3395 /* as we fix the tree, we might be deleting blocks that
3396  * we're tracking for repair.  This hook makes sure we
3397  * remove any backrefs for blocks as we are fixing them.
3398  */
3399 static int free_extent_hook(struct btrfs_trans_handle *trans,
3400                             struct btrfs_root *root,
3401                             u64 bytenr, u64 num_bytes, u64 parent,
3402                             u64 root_objectid, u64 owner, u64 offset,
3403                             int refs_to_drop)
3404 {
3405         struct extent_record *rec;
3406         struct cache_extent *cache;
3407         int is_data;
3408         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
3409
3410         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
3411         cache = find_cache_extent(extent_cache, bytenr, num_bytes);
3412         if (!cache)
3413                 return 0;
3414
3415         rec = container_of(cache, struct extent_record, cache);
3416         if (is_data) {
3417                 struct data_backref *back;
3418                 back = find_data_backref(rec, parent, root_objectid, owner,
3419                                          offset, 1, bytenr, num_bytes);
3420                 if (!back)
3421                         goto out;
3422                 if (back->node.found_ref) {
3423                         back->found_ref -= refs_to_drop;
3424                         if (rec->refs)
3425                                 rec->refs -= refs_to_drop;
3426                 }
3427                 if (back->node.found_extent_tree) {
3428                         back->num_refs -= refs_to_drop;
3429                         if (rec->extent_item_refs)
3430                                 rec->extent_item_refs -= refs_to_drop;
3431                 }
3432                 if (back->found_ref == 0)
3433                         back->node.found_ref = 0;
3434                 if (back->num_refs == 0)
3435                         back->node.found_extent_tree = 0;
3436
3437                 if (!back->node.found_extent_tree && back->node.found_ref) {
3438                         list_del(&back->node.list);
3439                         free(back);
3440                 }
3441         } else {
3442                 struct tree_backref *back;
3443                 back = find_tree_backref(rec, parent, root_objectid);
3444                 if (!back)
3445                         goto out;
3446                 if (back->node.found_ref) {
3447                         if (rec->refs)
3448                                 rec->refs--;
3449                         back->node.found_ref = 0;
3450                 }
3451                 if (back->node.found_extent_tree) {
3452                         if (rec->extent_item_refs)
3453                                 rec->extent_item_refs--;
3454                         back->node.found_extent_tree = 0;
3455                 }
3456                 if (!back->node.found_extent_tree && back->node.found_ref) {
3457                         list_del(&back->node.list);
3458                         free(back);
3459                 }
3460         }
3461         maybe_free_extent_rec(extent_cache, rec);
3462 out:
3463         return 0;
3464 }
3465
3466 static int delete_extent_records(struct btrfs_trans_handle *trans,
3467                                  struct btrfs_root *root,
3468                                  struct btrfs_path *path,
3469                                  u64 bytenr, u64 new_len)
3470 {
3471         struct btrfs_key key;
3472         struct btrfs_key found_key;
3473         struct extent_buffer *leaf;
3474         int ret;
3475         int slot;
3476
3477
3478         key.objectid = bytenr;
3479         key.type = (u8)-1;
3480         key.offset = (u64)-1;
3481
3482         while(1) {
3483                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
3484                                         &key, path, 0, 1);
3485                 if (ret < 0)
3486                         break;
3487
3488                 if (ret > 0) {
3489                         ret = 0;
3490                         if (path->slots[0] == 0)
3491                                 break;
3492                         path->slots[0]--;
3493                 }
3494                 ret = 0;
3495
3496                 leaf = path->nodes[0];
3497                 slot = path->slots[0];
3498
3499                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3500                 if (found_key.objectid != bytenr)
3501                         break;
3502
3503                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
3504                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
3505                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3506                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
3507                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
3508                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
3509                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
3510                         btrfs_release_path(NULL, path);
3511                         if (found_key.type == 0) {
3512                                 if (found_key.offset == 0)
3513                                         break;
3514                                 key.offset = found_key.offset - 1;
3515                                 key.type = found_key.type;
3516                         }
3517                         key.type = found_key.type - 1;
3518                         key.offset = (u64)-1;
3519                         continue;
3520                 }
3521
3522                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
3523                         found_key.objectid, found_key.type, found_key.offset);
3524
3525                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
3526                 if (ret)
3527                         break;
3528                 btrfs_release_path(NULL, path);
3529
3530                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
3531                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
3532                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
3533                                 found_key.offset : root->leafsize;
3534
3535                         ret = btrfs_update_block_group(trans, root, bytenr,
3536                                                        bytes, 0, 0);
3537                         if (ret)
3538                                 break;
3539                 }
3540         }
3541
3542         btrfs_release_path(NULL, path);
3543         return ret;
3544 }
3545
3546 /*
3547  * for a single backref, this will allocate a new extent
3548  * and add the backref to it.
3549  */
3550 static int record_extent(struct btrfs_trans_handle *trans,
3551                          struct btrfs_fs_info *info,
3552                          struct btrfs_path *path,
3553                          struct extent_record *rec,
3554                          struct extent_backref *back,
3555                          int allocated, u64 flags)
3556 {
3557         int ret;
3558         struct btrfs_root *extent_root = info->extent_root;
3559         struct extent_buffer *leaf;
3560         struct btrfs_key ins_key;
3561         struct btrfs_extent_item *ei;
3562         struct tree_backref *tback;
3563         struct data_backref *dback;
3564         struct btrfs_tree_block_info *bi;
3565
3566         if (!back->is_data)
3567                 rec->max_size = max_t(u64, rec->max_size,
3568                                     info->extent_root->leafsize);
3569
3570         if (!allocated) {
3571                 u32 item_size = sizeof(*ei);
3572
3573                 if (!back->is_data)
3574                         item_size += sizeof(*bi);
3575
3576                 ins_key.objectid = rec->start;
3577                 ins_key.offset = rec->max_size;
3578                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
3579
3580                 ret = btrfs_insert_empty_item(trans, extent_root, path,
3581                                         &ins_key, item_size);
3582                 if (ret)
3583                         goto fail;
3584
3585                 leaf = path->nodes[0];
3586                 ei = btrfs_item_ptr(leaf, path->slots[0],
3587                                     struct btrfs_extent_item);
3588
3589                 btrfs_set_extent_refs(leaf, ei, 0);
3590                 btrfs_set_extent_generation(leaf, ei, rec->generation);
3591
3592                 if (back->is_data) {
3593                         btrfs_set_extent_flags(leaf, ei,
3594                                                BTRFS_EXTENT_FLAG_DATA);
3595                 } else {
3596                         struct btrfs_disk_key copy_key;;
3597
3598                         tback = (struct tree_backref *)back;
3599                         bi = (struct btrfs_tree_block_info *)(ei + 1);
3600                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
3601                                              sizeof(*bi));
3602                         memset(&copy_key, 0, sizeof(copy_key));
3603
3604                         copy_key.objectid = le64_to_cpu(rec->info_objectid);
3605                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
3606                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
3607
3608                         btrfs_set_extent_flags(leaf, ei,
3609                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
3610                 }
3611
3612                 btrfs_mark_buffer_dirty(leaf);
3613                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
3614                                                rec->max_size, 1, 0);
3615                 if (ret)
3616                         goto fail;
3617                 btrfs_release_path(NULL, path);
3618         }
3619
3620         if (back->is_data) {
3621                 u64 parent;
3622                 int i;
3623
3624                 dback = (struct data_backref *)back;
3625                 if (back->full_backref)
3626                         parent = dback->parent;
3627                 else
3628                         parent = 0;
3629
3630                 for (i = 0; i < dback->found_ref; i++) {
3631                         /* if parent != 0, we're doing a full backref
3632                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
3633                          * just makes the backref allocator create a data
3634                          * backref
3635                          */
3636                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
3637                                                    rec->start, rec->max_size,
3638                                                    parent,
3639                                                    dback->root,
3640                                                    parent ?
3641                                                    BTRFS_FIRST_FREE_OBJECTID :
3642                                                    dback->owner,
3643                                                    dback->offset);
3644                         if (ret)
3645                                 break;
3646                 }
3647                 fprintf(stderr, "adding new data backref"
3648                                 " on %llu %s %llu owner %llu"
3649                                 " offset %llu found %d\n",
3650                                 (unsigned long long)rec->start,
3651                                 back->full_backref ?
3652                                 "parent" : "root",
3653                                 back->full_backref ?
3654                                 (unsigned long long)parent :
3655                                 (unsigned long long)dback->root,
3656                                 (unsigned long long)dback->owner,
3657                                 (unsigned long long)dback->offset,
3658                                 dback->found_ref);
3659         } else {
3660                 u64 parent;
3661
3662                 tback = (struct tree_backref *)back;
3663                 if (back->full_backref)
3664                         parent = tback->parent;
3665                 else
3666                         parent = 0;
3667
3668                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
3669                                            rec->start, rec->max_size,
3670                                            parent, tback->root, 0, 0);
3671                 fprintf(stderr, "adding new tree backref on "
3672                         "start %llu len %llu parent %llu root %llu\n",
3673                         rec->start, rec->max_size, tback->parent, tback->root);
3674         }
3675         if (ret)
3676                 goto fail;
3677 fail:
3678         btrfs_release_path(NULL, path);
3679         return ret;
3680 }
3681
3682 struct extent_entry {
3683         u64 bytenr;
3684         u64 bytes;
3685         int count;
3686         struct list_head list;
3687 };
3688
3689 static struct extent_entry *find_entry(struct list_head *entries,
3690                                        u64 bytenr, u64 bytes)
3691 {
3692         struct extent_entry *entry = NULL;
3693
3694         list_for_each_entry(entry, entries, list) {
3695                 if (entry->bytenr == bytenr && entry->bytes == bytes)
3696                         return entry;
3697         }
3698
3699         return NULL;
3700 }
3701
3702 static struct extent_entry *find_most_right_entry(struct list_head *entries)
3703 {
3704         struct extent_entry *entry, *best = NULL, *prev = NULL;
3705
3706         list_for_each_entry(entry, entries, list) {
3707                 if (!prev) {
3708                         prev = entry;
3709                         continue;
3710                 }
3711
3712                 /*
3713                  * If our current entry == best then we can't be sure our best
3714                  * is really the best, so we need to keep searching.
3715                  */
3716                 if (best && best->count == entry->count) {
3717                         prev = entry;
3718                         best = NULL;
3719                         continue;
3720                 }
3721
3722                 /* Prev == entry, not good enough, have to keep searching */
3723                 if (prev->count == entry->count)
3724                         continue;
3725
3726                 if (!best)
3727                         best = (prev->count > entry->count) ? prev : entry;
3728                 else if (best->count < entry->count)
3729                         best = entry;
3730                 prev = entry;
3731         }
3732
3733         return best;
3734 }
3735
3736 static int repair_ref(struct btrfs_trans_handle *trans,
3737                       struct btrfs_fs_info *info, struct btrfs_path *path,
3738                       struct data_backref *dback, struct extent_entry *entry)
3739 {
3740         struct btrfs_root *root;
3741         struct btrfs_file_extent_item *fi;
3742         struct extent_buffer *leaf;
3743         struct btrfs_key key;
3744         u64 bytenr, bytes;
3745         int ret;
3746
3747         key.objectid = dback->root;
3748         key.type = BTRFS_ROOT_ITEM_KEY;
3749         key.offset = (u64)-1;
3750         root = btrfs_read_fs_root(info, &key);
3751         if (IS_ERR(root)) {
3752                 fprintf(stderr, "Couldn't find root for our ref\n");
3753                 return -EINVAL;
3754         }
3755
3756         /*
3757          * The backref points to the original offset of the extent if it was
3758          * split, so we need to search down to the offset we have and then walk
3759          * forward until we find the backref we're looking for.
3760          */
3761         key.objectid = dback->owner;
3762         key.type = BTRFS_EXTENT_DATA_KEY;
3763         key.offset = dback->offset;
3764         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3765         if (ret < 0) {
3766                 fprintf(stderr, "Error looking up ref %d\n", ret);
3767                 return ret;
3768         }
3769
3770         while (1) {
3771                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3772                         ret = btrfs_next_leaf(root, path);
3773                         if (ret) {
3774                                 fprintf(stderr, "Couldn't find our ref, next\n");
3775                                 return -EINVAL;
3776                         }
3777                 }
3778                 leaf = path->nodes[0];
3779                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3780                 if (key.objectid != dback->owner ||
3781                     key.type != BTRFS_EXTENT_DATA_KEY) {
3782                         fprintf(stderr, "Couldn't find our ref, search\n");
3783                         return -EINVAL;
3784                 }
3785                 fi = btrfs_item_ptr(leaf, path->slots[0],
3786                                     struct btrfs_file_extent_item);
3787                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
3788                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
3789
3790                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
3791                         break;
3792                 path->slots[0]++;
3793         }
3794
3795         btrfs_release_path(root, path);
3796
3797         /*
3798          * Have to make sure that this root gets updated when we commit the
3799          * transaction
3800          */
3801         root->track_dirty = 1;
3802         if (root->last_trans != trans->transid) {
3803                 root->last_trans = trans->transid;
3804                 root->commit_root = root->node;
3805                 extent_buffer_get(root->node);
3806         }
3807
3808         /*
3809          * Ok we have the key of the file extent we want to fix, now we can cow
3810          * down to the thing and fix it.
3811          */
3812         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3813         if (ret < 0) {
3814                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
3815                         key.objectid, key.type, key.offset, ret);
3816                 return ret;
3817         }
3818         if (ret > 0) {
3819                 fprintf(stderr, "Well that's odd, we just found this key "
3820                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
3821                         key.offset);
3822                 return -EINVAL;
3823         }
3824         leaf = path->nodes[0];
3825         fi = btrfs_item_ptr(leaf, path->slots[0],
3826                             struct btrfs_file_extent_item);
3827
3828         if (btrfs_file_extent_compression(leaf, fi) &&
3829             dback->disk_bytenr != entry->bytenr) {
3830                 fprintf(stderr, "Ref doesn't match the record start and is "
3831                         "compressed, please take a btrfs-image of this file "
3832                         "system and send it to a btrfs developer so they can "
3833                         "complete this functionality for bytenr %Lu\n",
3834                         dback->disk_bytenr);
3835                 return -EINVAL;
3836         }
3837
3838         if (dback->disk_bytenr > entry->bytenr) {
3839                 u64 off_diff, offset;
3840
3841                 off_diff = dback->disk_bytenr - entry->bytenr;
3842                 offset = btrfs_file_extent_offset(leaf, fi);
3843                 if (dback->disk_bytenr + offset +
3844                     btrfs_file_extent_num_bytes(leaf, fi) >
3845                     entry->bytenr + entry->bytes) {
3846                         fprintf(stderr, "Ref is past the entry end, please "
3847                                 "take a btrfs-image of this file system and "
3848                                 "send it to a btrfs developer, ref %Lu\n",
3849                                 dback->disk_bytenr);
3850                         return -EINVAL;
3851                 }
3852                 offset += off_diff;
3853                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
3854                 btrfs_set_file_extent_offset(leaf, fi, offset);
3855         } else if (dback->disk_bytenr < entry->bytenr) {
3856                 u64 offset;
3857
3858                 offset = btrfs_file_extent_offset(leaf, fi);
3859                 if (dback->disk_bytenr + offset < entry->bytenr) {
3860                         fprintf(stderr, "Ref is before the entry start, please"
3861                                 " take a btrfs-image of this file system and "
3862                                 "send it to a btrfs developer, ref %Lu\n",
3863                                 dback->disk_bytenr);
3864                         return -EINVAL;
3865                 }
3866
3867                 offset += dback->disk_bytenr;
3868                 offset -= entry->bytenr;
3869                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
3870                 btrfs_set_file_extent_offset(leaf, fi, offset);
3871         }
3872
3873         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
3874
3875         /*
3876          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
3877          * only do this if we aren't using compression, otherwise it's a
3878          * trickier case.
3879          */
3880         if (!btrfs_file_extent_compression(leaf, fi))
3881                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
3882         else
3883                 printf("ram bytes may be wrong?\n");
3884         btrfs_mark_buffer_dirty(leaf);
3885         btrfs_release_path(root, path);
3886         return 0;
3887 }
3888
3889 static int verify_backrefs(struct btrfs_trans_handle *trans,
3890                            struct btrfs_fs_info *info, struct btrfs_path *path,
3891                            struct extent_record *rec)
3892 {
3893         struct extent_backref *back;
3894         struct data_backref *dback;
3895         struct extent_entry *entry, *best = NULL;
3896         LIST_HEAD(entries);
3897         int nr_entries = 0;
3898         int ret = 0;
3899
3900         /*
3901          * Metadata is easy and the backrefs should always agree on bytenr and
3902          * size, if not we've got bigger issues.
3903          */
3904         if (rec->metadata)
3905                 return 0;
3906
3907         list_for_each_entry(back, &rec->backrefs, list) {
3908                 dback = (struct data_backref *)back;
3909                 /*
3910                  * We only pay attention to backrefs that we found a real
3911                  * backref for.
3912                  */
3913                 if (dback->found_ref == 0)
3914                         continue;
3915                 if (back->full_backref)
3916                         continue;
3917
3918                 /*
3919                  * For now we only catch when the bytes don't match, not the
3920                  * bytenr.  We can easily do this at the same time, but I want
3921                  * to have a fs image to test on before we just add repair
3922                  * functionality willy-nilly so we know we won't screw up the
3923                  * repair.
3924                  */
3925
3926                 entry = find_entry(&entries, dback->disk_bytenr,
3927                                    dback->bytes);
3928                 if (!entry) {
3929                         entry = malloc(sizeof(struct extent_entry));
3930                         if (!entry) {
3931                                 ret = -ENOMEM;
3932                                 goto out;
3933                         }
3934                         memset(entry, 0, sizeof(*entry));
3935                         entry->bytenr = dback->disk_bytenr;
3936                         entry->bytes = dback->bytes;
3937                         list_add_tail(&entry->list, &entries);
3938                         nr_entries++;
3939                 }
3940                 entry->count++;
3941         }
3942
3943         /* Yay all the backrefs agree, carry on good sir */
3944         if (nr_entries <= 1)
3945                 goto out;
3946
3947         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
3948                 "%Lu\n", rec->start);
3949
3950         /*
3951          * First we want to see if the backrefs can agree amongst themselves who
3952          * is right, so figure out which one of the entries has the highest
3953          * count.
3954          */
3955         best = find_most_right_entry(&entries);
3956
3957         /*
3958          * Ok so we may have an even split between what the backrefs think, so
3959          * this is where we use the extent ref to see what it thinks.
3960          */
3961         if (!best) {
3962                 entry = find_entry(&entries, rec->start, rec->nr);
3963                 if (!entry) {
3964                         fprintf(stderr, "Backrefs don't agree with eachother "
3965                                 "and extent record doesn't agree with anybody,"
3966                                 " so we can't fix bytenr %Lu bytes %Lu\n",
3967                                 rec->start, rec->nr);
3968                         ret = -EINVAL;
3969                         goto out;
3970                 }
3971                 entry->count++;
3972                 best = find_most_right_entry(&entries);
3973                 if (!best) {
3974                         fprintf(stderr, "Backrefs and extent record evenly "
3975                                 "split on who is right, this is going to "
3976                                 "require user input to fix bytenr %Lu bytes "
3977                                 "%Lu\n", rec->start, rec->nr);
3978                         ret = -EINVAL;
3979                         goto out;
3980                 }
3981         }
3982
3983         /*
3984          * I don't think this can happen currently as we'll abort() if we catch
3985          * this case higher up, but in case somebody removes that we still can't
3986          * deal with it properly here yet, so just bail out of that's the case.
3987          */
3988         if (best->bytenr != rec->start) {
3989                 fprintf(stderr, "Extent start and backref starts don't match, "
3990                         "please use btrfs-image on this file system and send "
3991                         "it to a btrfs developer so they can make fsck fix "
3992                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
3993                         rec->start, rec->nr);
3994                 ret = -EINVAL;
3995                 goto out;
3996         }
3997
3998         /*
3999          * Ok great we all agreed on an extent record, let's go find the real
4000          * references and fix up the ones that don't match.
4001          */
4002         list_for_each_entry(back, &rec->backrefs, list) {
4003                 dback = (struct data_backref *)back;
4004
4005                 /*
4006                  * Still ignoring backrefs that don't have a real ref attached
4007                  * to them.
4008                  */
4009                 if (dback->found_ref == 0)
4010                         continue;
4011                 if (back->full_backref)
4012                         continue;
4013
4014                 if (dback->bytes == best->bytes &&
4015                     dback->disk_bytenr == best->bytenr)
4016                         continue;
4017
4018                 ret = repair_ref(trans, info, path, dback, best);
4019                 if (ret)
4020                         goto out;
4021         }
4022
4023         /*
4024          * Ok we messed with the actual refs, which means we need to drop our
4025          * entire cache and go back and rescan.  I know this is a huge pain and
4026          * adds a lot of extra work, but it's the only way to be safe.  Once all
4027          * the backrefs agree we may not need to do anything to the extent
4028          * record itself.
4029          */
4030         ret = -EAGAIN;
4031 out:
4032         while (!list_empty(&entries)) {
4033                 entry = list_entry(entries.next, struct extent_entry, list);
4034                 list_del_init(&entry->list);
4035                 free(entry);
4036         }
4037         return ret;
4038 }
4039
4040 static int process_duplicates(struct btrfs_root *root,
4041                               struct cache_tree *extent_cache,
4042                               struct extent_record *rec)
4043 {
4044         struct extent_record *good, *tmp;
4045         struct cache_extent *cache;
4046         int ret;
4047
4048         /*
4049          * If we found a extent record for this extent then return, or if we
4050          * have more than one duplicate we are likely going to need to delete
4051          * something.
4052          */
4053         if (rec->found_rec || rec->num_duplicates > 1)
4054                 return 0;
4055
4056         /* Shouldn't happen but just in case */
4057         BUG_ON(!rec->num_duplicates);
4058
4059         /*
4060          * So this happens if we end up with a backref that doesn't match the
4061          * actual extent entry.  So either the backref is bad or the extent
4062          * entry is bad.  Either way we want to have the extent_record actually
4063          * reflect what we found in the extent_tree, so we need to take the
4064          * duplicate out and use that as the extent_record since the only way we
4065          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
4066          */
4067         remove_cache_extent(extent_cache, &rec->cache);
4068
4069         good = list_entry(rec->dups.next, struct extent_record, list);
4070         list_del_init(&good->list);
4071         INIT_LIST_HEAD(&good->backrefs);
4072         INIT_LIST_HEAD(&good->dups);
4073         good->cache.start = good->start;
4074         good->cache.size = good->nr;
4075         good->content_checked = 0;
4076         good->owner_ref_checked = 0;
4077         good->num_duplicates = 0;
4078         good->refs = rec->refs;
4079         list_splice_init(&rec->backrefs, &good->backrefs);
4080         while (1) {
4081                 cache = find_cache_extent(extent_cache, good->start,
4082                                           good->nr);
4083                 if (!cache)
4084                         break;
4085                 tmp = container_of(cache, struct extent_record, cache);
4086
4087                 /*
4088                  * If we find another overlapping extent and it's found_rec is
4089                  * set then it's a duplicate and we need to try and delete
4090                  * something.
4091                  */
4092                 if (tmp->found_rec || tmp->num_duplicates > 0) {
4093                         if (list_empty(&good->list))
4094                                 list_add_tail(&good->list,
4095                                               &duplicate_extents);
4096                         good->num_duplicates += tmp->num_duplicates + 1;
4097                         list_splice_init(&tmp->dups, &good->dups);
4098                         list_del_init(&tmp->list);
4099                         list_add_tail(&tmp->list, &good->dups);
4100                         remove_cache_extent(extent_cache, &tmp->cache);
4101                         continue;
4102                 }
4103
4104                 /*
4105                  * Ok we have another non extent item backed extent rec, so lets
4106                  * just add it to this extent and carry on like we did above.
4107                  */
4108                 good->refs += tmp->refs;
4109                 list_splice_init(&tmp->backrefs, &good->backrefs);
4110                 remove_cache_extent(extent_cache, &tmp->cache);
4111                 free(tmp);
4112         }
4113         ret = insert_existing_cache_extent(extent_cache, &good->cache);
4114         BUG_ON(ret);
4115         free(rec);
4116         return good->num_duplicates ? 0 : 1;
4117 }
4118
4119 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
4120                                     struct btrfs_root *root,
4121                                     struct extent_record *rec)
4122 {
4123         LIST_HEAD(delete_list);
4124         struct btrfs_path *path;
4125         struct extent_record *tmp, *good, *n;
4126         int nr_del = 0;
4127         int ret = 0;
4128         struct btrfs_key key;
4129
4130         path = btrfs_alloc_path();
4131         if (!path) {
4132                 ret = -ENOMEM;
4133                 goto out;
4134         }
4135
4136         good = rec;
4137         /* Find the record that covers all of the duplicates. */
4138         list_for_each_entry(tmp, &rec->dups, list) {
4139                 if (good->start < tmp->start)
4140                         continue;
4141                 if (good->nr > tmp->nr)
4142                         continue;
4143
4144                 if (tmp->start + tmp->nr < good->start + good->nr) {
4145                         fprintf(stderr, "Ok we have overlapping extents that "
4146                                 "aren't completely covered by eachother, this "
4147                                 "is going to require more careful thought.  "
4148                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
4149                                 tmp->start, tmp->nr, good->start, good->nr);
4150                         abort();
4151                 }
4152                 good = tmp;
4153         }
4154
4155         if (good != rec)
4156                 list_add_tail(&rec->list, &delete_list);
4157
4158         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
4159                 if (tmp == good)
4160                         continue;
4161                 list_move_tail(&tmp->list, &delete_list);
4162         }
4163
4164         root = root->fs_info->extent_root;
4165         list_for_each_entry(tmp, &delete_list, list) {
4166                 if (tmp->found_rec == 0)
4167                         continue;
4168                 key.objectid = tmp->start;
4169                 key.type = BTRFS_EXTENT_ITEM_KEY;
4170                 key.offset = tmp->nr;
4171
4172                 /* Shouldn't happen but just in case */
4173                 if (tmp->metadata) {
4174                         fprintf(stderr, "Well this shouldn't happen, extent "
4175                                 "record overlaps but is metadata? "
4176                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
4177                         abort();
4178                 }
4179
4180                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4181                 if (ret) {
4182                         if (ret > 0)
4183                                 ret = -EINVAL;
4184                         goto out;
4185                 }
4186                 ret = btrfs_del_item(trans, root, path);
4187                 if (ret)
4188                         goto out;
4189                 btrfs_release_path(root, path);
4190                 nr_del++;
4191         }
4192
4193 out:
4194         while (!list_empty(&delete_list)) {
4195                 tmp = list_entry(delete_list.next, struct extent_record, list);
4196                 list_del_init(&tmp->list);
4197                 if (tmp == rec)
4198                         continue;
4199                 free(tmp);
4200         }
4201
4202         while (!list_empty(&rec->dups)) {
4203                 tmp = list_entry(rec->dups.next, struct extent_record, list);
4204                 list_del_init(&tmp->list);
4205                 free(tmp);
4206         }
4207
4208         btrfs_free_path(path);
4209
4210         if (!ret && !nr_del)
4211                 rec->num_duplicates = 0;
4212
4213         return ret ? ret : nr_del;
4214 }
4215
4216 /*
4217  * when an incorrect extent item is found, this will delete
4218  * all of the existing entries for it and recreate them
4219  * based on what the tree scan found.
4220  */
4221 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
4222                              struct btrfs_fs_info *info,
4223                              struct extent_record *rec)
4224 {
4225         int ret;
4226         struct btrfs_path *path;
4227         struct list_head *cur = rec->backrefs.next;
4228         struct cache_extent *cache;
4229         struct extent_backref *back;
4230         int allocated = 0;
4231         u64 flags = 0;
4232
4233         /* remember our flags for recreating the extent */
4234         ret = btrfs_lookup_extent_info(NULL, info->extent_root, rec->start,
4235                                        rec->max_size, rec->metadata, NULL,
4236                                        &flags);
4237         if (ret < 0)
4238                 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4239
4240         path = btrfs_alloc_path();
4241
4242         /* step one, make sure all of the backrefs agree */
4243         ret = verify_backrefs(trans, info, path, rec);
4244         if (ret < 0)
4245                 goto out;
4246
4247         /* step two, delete all the existing records */
4248         ret = delete_extent_records(trans, info->extent_root, path,
4249                                     rec->start, rec->max_size);
4250
4251         if (ret < 0)
4252                 goto out;
4253
4254         /* was this block corrupt?  If so, don't add references to it */
4255         cache = find_cache_extent(info->corrupt_blocks, rec->start, rec->max_size);
4256         if (cache) {
4257                 ret = 0;
4258                 goto out;
4259         }
4260
4261         /* step three, recreate all the refs we did find */
4262         while(cur != &rec->backrefs) {
4263                 back = list_entry(cur, struct extent_backref, list);
4264                 cur = cur->next;
4265
4266                 /*
4267                  * if we didn't find any references, don't create a
4268                  * new extent record
4269                  */
4270                 if (!back->found_ref)
4271                         continue;
4272
4273                 ret = record_extent(trans, info, path, rec, back, allocated, flags);
4274                 allocated = 1;
4275
4276                 if (ret)
4277                         goto out;
4278         }
4279 out:
4280         btrfs_free_path(path);
4281         return ret;
4282 }
4283
4284 /* right now we only prune from the extent allocation tree */
4285 static int prune_one_block(struct btrfs_trans_handle *trans,
4286                            struct btrfs_fs_info *info,
4287                            struct btrfs_corrupt_block *corrupt)
4288 {
4289         int ret;
4290         struct btrfs_path path;
4291         struct extent_buffer *eb;
4292         u64 found;
4293         int slot;
4294         int nritems;
4295         int level = corrupt->level + 1;
4296
4297         btrfs_init_path(&path);
4298 again:
4299         /* we want to stop at the parent to our busted block */
4300         path.lowest_level = level;
4301
4302         ret = btrfs_search_slot(trans, info->extent_root,
4303                                 &corrupt->key, &path, -1, 1);
4304
4305         if (ret < 0)
4306                 goto out;
4307
4308         eb = path.nodes[level];
4309         if (!eb) {
4310                 ret = -ENOENT;
4311                 goto out;
4312         }
4313
4314         /*
4315          * hopefully the search gave us the block we want to prune,
4316          * lets try that first
4317          */
4318         slot = path.slots[level];
4319         found =  btrfs_node_blockptr(eb, slot);
4320         if (found == corrupt->cache.start)
4321                 goto del_ptr;
4322
4323         nritems = btrfs_header_nritems(eb);
4324
4325         /* the search failed, lets scan this node and hope we find it */
4326         for (slot = 0; slot < nritems; slot++) {
4327                 found =  btrfs_node_blockptr(eb, slot);
4328                 if (found == corrupt->cache.start)
4329                         goto del_ptr;
4330         }
4331         /*
4332          * we couldn't find the bad block.  TODO, search all the nodes for pointers
4333          * to this block
4334          */
4335         if (eb == info->extent_root->node) {
4336                 ret = -ENOENT;
4337                 goto out;
4338         } else {
4339                 level++;
4340                 btrfs_release_path(NULL, &path);
4341                 goto again;
4342         }
4343
4344 del_ptr:
4345         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
4346         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
4347
4348 out:
4349         btrfs_release_path(NULL, &path);
4350         return ret;
4351 }
4352
4353 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
4354                                 struct btrfs_fs_info *info)
4355 {
4356         struct cache_extent *cache;
4357         struct btrfs_corrupt_block *corrupt;
4358
4359         cache = find_first_cache_extent(info->corrupt_blocks, 0);
4360         while (1) {
4361                 if (!cache)
4362                         break;
4363                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
4364                 prune_one_block(trans, info, corrupt);
4365                 cache = next_cache_extent(cache);
4366         }
4367         return 0;
4368 }
4369
4370 static void free_corrupt_blocks(struct btrfs_fs_info *info)
4371 {
4372         struct cache_extent *cache;
4373         struct btrfs_corrupt_block *corrupt;
4374
4375         while (1) {
4376                 cache = find_first_cache_extent(info->corrupt_blocks, 0);
4377                 if (!cache)
4378                         break;
4379                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
4380                 remove_cache_extent(info->corrupt_blocks, cache);
4381                 free(corrupt);
4382         }
4383 }
4384
4385 static int check_block_group(struct btrfs_trans_handle *trans,
4386                               struct btrfs_fs_info *info,
4387                               struct map_lookup *map,
4388                               int *reinit)
4389 {
4390         struct btrfs_key key;
4391         struct btrfs_path path;
4392         int ret;
4393
4394         key.objectid = map->ce.start;
4395         key.offset = map->ce.size;
4396         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
4397
4398         btrfs_init_path(&path);
4399         ret = btrfs_search_slot(NULL, info->extent_root,
4400                                 &key, &path, 0, 0);
4401         btrfs_release_path(NULL, &path);
4402         if (ret <= 0)
4403                 goto out;
4404
4405         ret = btrfs_make_block_group(trans, info->extent_root, 0, map->type,
4406                                BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4407                                key.objectid, key.offset);
4408         *reinit = 1;
4409 out:
4410         return ret;
4411 }
4412
4413 static int check_block_groups(struct btrfs_trans_handle *trans,
4414                               struct btrfs_fs_info *info, int *reinit)
4415 {
4416         struct cache_extent *ce;
4417         struct map_lookup *map;
4418         struct btrfs_mapping_tree *map_tree = &info->mapping_tree;
4419
4420         /* this isn't quite working */
4421         return 0;
4422
4423         ce = find_first_cache_extent(&map_tree->cache_tree, 0);
4424         while (1) {
4425                 if (!ce)
4426                         break;
4427                 map = container_of(ce, struct map_lookup, ce);
4428                 check_block_group(trans, info, map, reinit);
4429                 ce = next_cache_extent(ce);
4430         }
4431         return 0;
4432 }
4433
4434 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
4435 {
4436         struct btrfs_block_group_cache *cache;
4437         u64 start, end;
4438         int ret;
4439
4440         while (1) {
4441                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
4442                                             &start, &end, EXTENT_DIRTY);
4443                 if (ret)
4444                         break;
4445                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
4446                                    GFP_NOFS);
4447         }
4448
4449         start = 0;
4450         while (1) {
4451                 cache = btrfs_lookup_first_block_group(fs_info, start);
4452                 if (!cache)
4453                         break;
4454                 if (cache->cached)
4455                         cache->cached = 0;
4456                 start = cache->key.objectid + cache->key.offset;
4457         }
4458 }
4459
4460 static int check_extent_refs(struct btrfs_trans_handle *trans,
4461                              struct btrfs_root *root,
4462                              struct cache_tree *extent_cache, int repair)
4463 {
4464         struct extent_record *rec;
4465         struct cache_extent *cache;
4466         int err = 0;
4467         int ret = 0;
4468         int fixed = 0;
4469         int reinit = 0;
4470         int had_dups = 0;
4471
4472         if (repair) {
4473                 /*
4474                  * if we're doing a repair, we have to make sure
4475                  * we don't allocate from the problem extents.
4476                  * In the worst case, this will be all the
4477                  * extents in the FS
4478                  */
4479                 cache = find_first_cache_extent(extent_cache, 0);
4480                 while(cache) {
4481                         rec = container_of(cache, struct extent_record, cache);
4482                         btrfs_pin_extent(root->fs_info,
4483                                          rec->start, rec->max_size);
4484                         cache = next_cache_extent(cache);
4485                 }
4486
4487                 /* pin down all the corrupted blocks too */
4488                 cache = find_first_cache_extent(root->fs_info->corrupt_blocks, 0);
4489                 while(cache) {
4490                         rec = container_of(cache, struct extent_record, cache);
4491                         btrfs_pin_extent(root->fs_info,
4492                                          rec->start, rec->max_size);
4493                         cache = next_cache_extent(cache);
4494                 }
4495                 prune_corrupt_blocks(trans, root->fs_info);
4496                 check_block_groups(trans, root->fs_info, &reinit);
4497                 if (reinit)
4498                         btrfs_read_block_groups(root->fs_info->extent_root);
4499                 reset_cached_block_groups(root->fs_info);
4500         }
4501
4502         /*
4503          * We need to delete any duplicate entries we find first otherwise we
4504          * could mess up the extent tree when we have backrefs that actually
4505          * belong to a different extent item and not the weird duplicate one.
4506          */
4507         while (repair && !list_empty(&duplicate_extents)) {
4508                 rec = list_entry(duplicate_extents.next, struct extent_record,
4509                                  list);
4510                 list_del_init(&rec->list);
4511
4512                 /* Sometimes we can find a backref before we find an actual
4513                  * extent, so we need to process it a little bit to see if there
4514                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
4515                  * if this is a backref screwup.  If we need to delete stuff
4516                  * process_duplicates() will return 0, otherwise it will return
4517                  * 1 and we
4518                  */
4519                 if (process_duplicates(root, extent_cache, rec))
4520                         continue;
4521                 ret = delete_duplicate_records(trans, root, rec);
4522                 if (ret < 0)
4523                         return ret;
4524                 /*
4525                  * delete_duplicate_records will return the number of entries
4526                  * deleted, so if it's greater than 0 then we know we actually
4527                  * did something and we need to remove.
4528                  */
4529                 if (ret)
4530                         had_dups = 1;
4531         }
4532
4533         if (had_dups)
4534                 return -EAGAIN;
4535
4536         while(1) {
4537                 fixed = 0;
4538                 cache = find_first_cache_extent(extent_cache, 0);
4539                 if (!cache)
4540                         break;
4541                 rec = container_of(cache, struct extent_record, cache);
4542                 if (rec->num_duplicates) {
4543                         fprintf(stderr, "extent item %llu has multiple extent "
4544                                 "items\n", (unsigned long long)rec->start);
4545                         err = 1;
4546                 }
4547
4548                 if (rec->refs != rec->extent_item_refs) {
4549                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
4550                                 (unsigned long long)rec->start,
4551                                 (unsigned long long)rec->nr);
4552                         fprintf(stderr, "extent item %llu, found %llu\n",
4553                                 (unsigned long long)rec->extent_item_refs,
4554                                 (unsigned long long)rec->refs);
4555                         if (!fixed && repair) {
4556                                 ret = fixup_extent_refs(trans, root->fs_info, rec);
4557                                 if (ret)
4558                                         goto repair_abort;
4559                                 fixed = 1;
4560                         }
4561                         err = 1;
4562
4563                 }
4564                 if (all_backpointers_checked(rec, 1)) {
4565                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
4566                                 (unsigned long long)rec->start,
4567                                 (unsigned long long)rec->nr);
4568
4569                         if (!fixed && repair) {
4570                                 ret = fixup_extent_refs(trans, root->fs_info, rec);
4571                                 if (ret)
4572                                         goto repair_abort;
4573                                 fixed = 1;
4574                         }
4575
4576                         err = 1;
4577                 }
4578                 if (!rec->owner_ref_checked) {
4579                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
4580                                 (unsigned long long)rec->start,
4581                                 (unsigned long long)rec->nr);
4582                         if (!fixed && repair) {
4583                                 ret = fixup_extent_refs(trans, root->fs_info, rec);
4584                                 if (ret)
4585                                         goto repair_abort;
4586                                 fixed = 1;
4587                         }
4588                         err = 1;
4589                 }
4590
4591                 remove_cache_extent(extent_cache, cache);
4592                 free_all_extent_backrefs(rec);
4593                 free(rec);
4594         }
4595 repair_abort:
4596         if (repair) {
4597                 if (ret && ret != -EAGAIN) {
4598                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
4599                         exit(1);
4600                 } else if (!ret) {
4601                         btrfs_fix_block_accounting(trans, root);
4602                 }
4603                 if (err)
4604                         fprintf(stderr, "repaired damaged extent references\n");
4605                 return ret;
4606         }
4607         return err;
4608 }
4609
4610 static void free_cache_tree(struct cache_tree *tree)
4611 {
4612         struct cache_extent *cache;
4613
4614         while (1) {
4615                 cache = find_first_cache_extent(tree, 0);
4616                 if (!cache)
4617                         break;
4618                 remove_cache_extent(tree, cache);
4619                 free(cache);
4620         }
4621 }
4622
4623 static int check_extents(struct btrfs_root *root, int repair)
4624 {
4625         struct cache_tree extent_cache;
4626         struct cache_tree seen;
4627         struct cache_tree pending;
4628         struct cache_tree reada;
4629         struct cache_tree nodes;
4630         struct cache_tree corrupt_blocks;
4631         struct btrfs_path path;
4632         struct btrfs_key key;
4633         struct btrfs_key found_key;
4634         int ret;
4635         u64 last = 0;
4636         struct block_info *bits;
4637         int bits_nr;
4638         struct extent_buffer *leaf;
4639         struct btrfs_trans_handle *trans = NULL;
4640         int slot;
4641         struct btrfs_root_item ri;
4642
4643         cache_tree_init(&extent_cache);
4644         cache_tree_init(&seen);
4645         cache_tree_init(&pending);
4646         cache_tree_init(&nodes);
4647         cache_tree_init(&reada);
4648         cache_tree_init(&corrupt_blocks);
4649
4650         if (repair) {
4651                 trans = btrfs_start_transaction(root, 1);
4652                 if (IS_ERR(trans)) {
4653                         fprintf(stderr, "Error starting transaction\n");
4654                         return PTR_ERR(trans);
4655                 }
4656                 root->fs_info->fsck_extent_cache = &extent_cache;
4657                 root->fs_info->free_extent_hook = free_extent_hook;
4658                 root->fs_info->corrupt_blocks = &corrupt_blocks;
4659         }
4660
4661         bits_nr = 1024;
4662         bits = malloc(bits_nr * sizeof(struct block_info));
4663         if (!bits) {
4664                 perror("malloc");
4665                 exit(1);
4666         }
4667
4668 again:
4669         add_root_to_pending(root->fs_info->tree_root->node,
4670                             &extent_cache, &pending, &seen, &nodes,
4671                             &root->fs_info->tree_root->root_key);
4672
4673         add_root_to_pending(root->fs_info->chunk_root->node,
4674                             &extent_cache, &pending, &seen, &nodes,
4675                             &root->fs_info->chunk_root->root_key);
4676
4677         btrfs_init_path(&path);
4678         key.offset = 0;
4679         key.objectid = 0;
4680         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
4681         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
4682                                         &key, &path, 0, 0);
4683         BUG_ON(ret < 0);
4684         while(1) {
4685                 leaf = path.nodes[0];
4686                 slot = path.slots[0];
4687                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
4688                         ret = btrfs_next_leaf(root, &path);
4689                         if (ret != 0)
4690                                 break;
4691                         leaf = path.nodes[0];
4692                         slot = path.slots[0];
4693                 }
4694                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
4695                 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
4696                         unsigned long offset;
4697                         struct extent_buffer *buf;
4698
4699                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
4700                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
4701                         buf = read_tree_block(root->fs_info->tree_root,
4702                                               btrfs_root_bytenr(&ri),
4703                                               btrfs_level_size(root,
4704                                                btrfs_root_level(&ri)), 0);
4705                         add_root_to_pending(buf, &extent_cache, &pending,
4706                                             &seen, &nodes, &found_key);
4707                         free_extent_buffer(buf);
4708                 }
4709                 path.slots[0]++;
4710         }
4711         btrfs_release_path(root, &path);
4712         while(1) {
4713                 ret = run_next_block(root, bits, bits_nr, &last, &pending,
4714                                      &seen, &reada, &nodes, &extent_cache);
4715                 if (ret != 0)
4716                         break;
4717         }
4718         ret = check_extent_refs(trans, root, &extent_cache, repair);
4719
4720         if (ret == -EAGAIN) {
4721                 ret = btrfs_commit_transaction(trans, root);
4722                 if (ret)
4723                         goto out;
4724
4725                 trans = btrfs_start_transaction(root, 1);
4726                 if (IS_ERR(trans)) {
4727                         ret = PTR_ERR(trans);
4728                         goto out;
4729                 }
4730
4731                 free_corrupt_blocks(root->fs_info);
4732                 free_cache_tree(&seen);
4733                 free_cache_tree(&pending);
4734                 free_cache_tree(&reada);
4735                 free_cache_tree(&nodes);
4736                 free_extent_cache(root->fs_info, &extent_cache);
4737                 goto again;
4738         }
4739
4740         if (trans) {
4741                 int err;
4742
4743                 err = btrfs_commit_transaction(trans, root);
4744                 if (!ret)
4745                         ret = err;
4746         }
4747 out:
4748         if (repair) {
4749                 free_corrupt_blocks(root->fs_info);
4750                 root->fs_info->fsck_extent_cache = NULL;
4751                 root->fs_info->free_extent_hook = NULL;
4752                 root->fs_info->corrupt_blocks = NULL;
4753         }
4754         free(bits);
4755         return ret;
4756 }
4757
4758 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
4759                                 struct extent_buffer *eb, int tree_root)
4760 {
4761         struct extent_buffer *tmp;
4762         struct btrfs_root_item *ri;
4763         struct btrfs_key key;
4764         u64 bytenr;
4765         u32 leafsize;
4766         int level = btrfs_header_level(eb);
4767         int nritems;
4768         int ret;
4769         int i;
4770
4771         btrfs_pin_extent(fs_info, eb->start, eb->len);
4772
4773         leafsize = btrfs_super_leafsize(fs_info->super_copy);
4774         nritems = btrfs_header_nritems(eb);
4775         for (i = 0; i < nritems; i++) {
4776                 if (level == 0) {
4777                         btrfs_item_key_to_cpu(eb, &key, i);
4778                         if (key.type != BTRFS_ROOT_ITEM_KEY)
4779                                 continue;
4780                         /* Skip the extent root and reloc roots */
4781                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
4782                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
4783                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
4784                                 continue;
4785                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
4786                         bytenr = btrfs_disk_root_bytenr(eb, ri);
4787
4788                         /*
4789                          * If at any point we start needing the real root we
4790                          * will have to build a stump root for the root we are
4791                          * in, but for now this doesn't actually use the root so
4792                          * just pass in extent_root.
4793                          */
4794                         tmp = read_tree_block(fs_info->extent_root, bytenr,
4795                                               leafsize, 0);
4796                         if (!tmp) {
4797                                 fprintf(stderr, "Error reading root block\n");
4798                                 return -EIO;
4799                         }
4800                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
4801                         free_extent_buffer(tmp);
4802                         if (ret)
4803                                 return ret;
4804                 } else {
4805                         bytenr = btrfs_node_blockptr(eb, i);
4806
4807                         /* If we aren't the tree root don't read the block */
4808                         if (level == 1 && !tree_root) {
4809                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
4810                                 continue;
4811                         }
4812
4813                         tmp = read_tree_block(fs_info->extent_root, bytenr,
4814                                               leafsize, 0);
4815                         if (!tmp) {
4816                                 fprintf(stderr, "Error reading tree block\n");
4817                                 return -EIO;
4818                         }
4819                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
4820                         free_extent_buffer(tmp);
4821                         if (ret)
4822                                 return ret;
4823                 }
4824         }
4825
4826         return 0;
4827 }
4828
4829 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
4830 {
4831         int ret;
4832
4833         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
4834         if (ret)
4835                 return ret;
4836
4837         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
4838 }
4839
4840 static int reset_block_groups(struct btrfs_fs_info *fs_info)
4841 {
4842         struct btrfs_path *path;
4843         struct extent_buffer *leaf;
4844         struct btrfs_chunk *chunk;
4845         struct btrfs_key key;
4846         int ret;
4847
4848         path = btrfs_alloc_path();
4849         if (!path)
4850                 return -ENOMEM;
4851
4852         key.objectid = 0;
4853         key.type = BTRFS_CHUNK_ITEM_KEY;
4854         key.offset = 0;
4855
4856         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
4857         if (ret < 0) {
4858                 btrfs_free_path(path);
4859                 return ret;
4860         }
4861
4862         /*
4863          * We do this in case the block groups were screwed up and had alloc
4864          * bits that aren't actually set on the chunks.  This happens with
4865          * restored images every time and could happen in real life I guess.
4866          */
4867         fs_info->avail_data_alloc_bits = 0;
4868         fs_info->avail_metadata_alloc_bits = 0;
4869         fs_info->avail_system_alloc_bits = 0;
4870
4871         /* First we need to create the in-memory block groups */
4872         while (1) {
4873                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4874                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
4875                         if (ret < 0) {
4876                                 btrfs_free_path(path);
4877                                 return ret;
4878                         }
4879                         if (ret) {
4880                                 ret = 0;
4881                                 break;
4882                         }
4883                 }
4884                 leaf = path->nodes[0];
4885                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4886                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
4887                         path->slots[0]++;
4888                         continue;
4889                 }
4890
4891                 chunk = btrfs_item_ptr(leaf, path->slots[0],
4892                                        struct btrfs_chunk);
4893                 btrfs_add_block_group(fs_info, 0,
4894                                       btrfs_chunk_type(leaf, chunk),
4895                                       key.objectid, key.offset,
4896                                       btrfs_chunk_length(leaf, chunk));
4897                 path->slots[0]++;
4898         }
4899
4900         btrfs_free_path(path);
4901         return 0;
4902 }
4903
4904 static int reset_balance(struct btrfs_trans_handle *trans,
4905                          struct btrfs_fs_info *fs_info)
4906 {
4907         struct btrfs_root *root = fs_info->tree_root;
4908         struct btrfs_path *path;
4909         struct extent_buffer *leaf;
4910         struct btrfs_key key;
4911         int del_slot, del_nr = 0;
4912         int ret;
4913         int found = 0;
4914
4915         path = btrfs_alloc_path();
4916         if (!path)
4917                 return -ENOMEM;
4918
4919         key.objectid = BTRFS_BALANCE_OBJECTID;
4920         key.type = BTRFS_BALANCE_ITEM_KEY;
4921         key.offset = 0;
4922
4923         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4924         if (ret) {
4925                 if (ret > 0)
4926                         ret = 0;
4927                 goto out;
4928         }
4929
4930         ret = btrfs_del_item(trans, root, path);
4931         if (ret)
4932                 goto out;
4933         btrfs_release_path(root, path);
4934
4935         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
4936         key.type = BTRFS_ROOT_ITEM_KEY;
4937         key.offset = 0;
4938
4939         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4940         if (ret < 0)
4941                 goto out;
4942         while (1) {
4943                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4944                         if (!found)
4945                                 break;
4946
4947                         if (del_nr) {
4948                                 ret = btrfs_del_items(trans, root, path,
4949                                                       del_slot, del_nr);
4950                                 del_nr = 0;
4951                                 if (ret)
4952                                         goto out;
4953                         }
4954                         key.offset++;
4955                         btrfs_release_path(root, path);
4956
4957                         found = 0;
4958                         ret = btrfs_search_slot(trans, root, &key, path,
4959                                                 -1, 1);
4960                         if (ret < 0)
4961                                 goto out;
4962                         continue;
4963                 }
4964                 found = 1;
4965                 leaf = path->nodes[0];
4966                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4967                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
4968                         break;
4969                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
4970                         path->slots[0]++;
4971                         continue;
4972                 }
4973                 if (!del_nr) {
4974                         del_slot = path->slots[0];
4975                         del_nr = 1;
4976                 } else {
4977                         del_nr++;
4978                 }
4979                 path->slots[0]++;
4980         }
4981
4982         if (del_nr) {
4983                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
4984                 if (ret)
4985                         goto out;
4986         }
4987         btrfs_release_path(root, path);
4988
4989         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
4990         key.type = BTRFS_ROOT_ITEM_KEY;
4991         key.offset = (u64)-1;
4992         root = btrfs_read_fs_root(fs_info, &key);
4993         if (IS_ERR(root)) {
4994                 fprintf(stderr, "Error reading data reloc tree\n");
4995                 return PTR_ERR(root);
4996         }
4997         root->track_dirty = 1;
4998         if (root->last_trans != trans->transid) {
4999                 root->last_trans = trans->transid;
5000                 root->commit_root = root->node;
5001                 extent_buffer_get(root->node);
5002         }
5003         ret = btrfs_fsck_reinit_root(trans, root, 0);
5004 out:
5005         btrfs_free_path(path);
5006         return ret;
5007 }
5008
5009 static int reinit_extent_tree(struct btrfs_fs_info *fs_info)
5010 {
5011         struct btrfs_trans_handle *trans;
5012         u64 start = 0;
5013         int ret;
5014
5015         /*
5016          * The only reason we don't do this is because right now we're just
5017          * walking the trees we find and pinning down their bytes, we don't look
5018          * at any of the leaves.  In order to do mixed groups we'd have to check
5019          * the leaves of any fs roots and pin down the bytes for any file
5020          * extents we find.  Not hard but why do it if we don't have to?
5021          */
5022         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
5023                 fprintf(stderr, "We don't support re-initing the extent tree "
5024                         "for mixed block groups yet, please notify a btrfs "
5025                         "developer you want to do this so they can add this "
5026                         "functionality.\n");
5027                 return -EINVAL;
5028         }
5029
5030         trans = btrfs_start_transaction(fs_info->extent_root, 1);
5031         if (IS_ERR(trans)) {
5032                 fprintf(stderr, "Error starting transaction\n");
5033                 return PTR_ERR(trans);
5034         }
5035
5036         /*
5037          * first we need to walk all of the trees except the extent tree and pin
5038          * down the bytes that are in use so we don't overwrite any existing
5039          * metadata.
5040          */
5041         ret = pin_metadata_blocks(fs_info);
5042         if (ret) {
5043                 fprintf(stderr, "error pinning down used bytes\n");
5044                 return ret;
5045         }
5046
5047         /*
5048          * Need to drop all the block groups since we're going to recreate all
5049          * of them again.
5050          */
5051         btrfs_free_block_groups(fs_info);
5052         ret = reset_block_groups(fs_info);
5053         if (ret) {
5054                 fprintf(stderr, "error resetting the block groups\n");
5055                 return ret;
5056         }
5057
5058         /* Ok we can allocate now, reinit the extent root */
5059         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 1);
5060         if (ret) {
5061                 fprintf(stderr, "extent root initialization failed\n");
5062                 /*
5063                  * When the transaction code is updated we should end the
5064                  * transaction, but for now progs only knows about commit so
5065                  * just return an error.
5066                  */
5067                 return ret;
5068         }
5069
5070         ret = reset_balance(trans, fs_info);
5071         if (ret) {
5072                 fprintf(stderr, "error reseting the pending balance\n");
5073                 return ret;
5074         }
5075
5076         /*
5077          * Now we have all the in-memory block groups setup so we can make
5078          * allocations properly, and the metadata we care about is safe since we
5079          * pinned all of it above.
5080          */
5081         while (1) {
5082                 struct btrfs_block_group_cache *cache;
5083
5084                 cache = btrfs_lookup_first_block_group(fs_info, start);
5085                 if (!cache)
5086                         break;
5087                 start = cache->key.objectid + cache->key.offset;
5088                 ret = btrfs_insert_item(trans, fs_info->extent_root,
5089                                         &cache->key, &cache->item,
5090                                         sizeof(cache->item));
5091                 if (ret) {
5092                         fprintf(stderr, "Error adding block group\n");
5093                         return ret;
5094                 }
5095                 btrfs_extent_post_op(trans, fs_info->extent_root);
5096         }
5097
5098         /*
5099          * Ok now we commit and run the normal fsck, which will add extent
5100          * entries for all of the items it finds.
5101          */
5102         return btrfs_commit_transaction(trans, fs_info->extent_root);
5103 }
5104
5105 static struct option long_options[] = {
5106         { "super", 1, NULL, 's' },
5107         { "repair", 0, NULL, 0 },
5108         { "init-csum-tree", 0, NULL, 0 },
5109         { "init-extent-tree", 0, NULL, 0 },
5110         { 0, 0, 0, 0}
5111 };
5112
5113 const char * const cmd_check_usage[] = {
5114         "btrfs check [options] <device>",
5115         "Check an unmounted btrfs filesystem.",
5116         "",
5117         "-s|--super <superblock>     use this superblock copy",
5118         "--repair                    try to repair the filesystem",
5119         "--init-csum-tree            create a new CRC tree",
5120         "--init-extent-tree          create a new extent tree",
5121         NULL
5122 };
5123
5124 int cmd_check(int argc, char **argv)
5125 {
5126         struct cache_tree root_cache;
5127         struct btrfs_root *root;
5128         struct btrfs_fs_info *info;
5129         u64 bytenr = 0;
5130         char uuidbuf[37];
5131         int ret;
5132         int num;
5133         int repair = 0;
5134         int option_index = 0;
5135         int init_csum_tree = 0;
5136         int init_extent_tree = 0;
5137         int rw = 0;
5138
5139         while(1) {
5140                 int c;
5141                 c = getopt_long(argc, argv, "as:", long_options,
5142                                 &option_index);
5143                 if (c < 0)
5144                         break;
5145                 switch(c) {
5146                         case 'a': /* ignored */ break;
5147                         case 's':
5148                                 num = atol(optarg);
5149                                 bytenr = btrfs_sb_offset(num);
5150                                 printf("using SB copy %d, bytenr %llu\n", num,
5151                                        (unsigned long long)bytenr);
5152                                 break;
5153                         case '?':
5154                         case 'h':
5155                                 usage(cmd_check_usage);
5156                 }
5157                 if (option_index == 1) {
5158                         printf("enabling repair mode\n");
5159                         repair = 1;
5160                         rw = 1;
5161                 } else if (option_index == 2) {
5162                         printf("Creating a new CRC tree\n");
5163                         init_csum_tree = 1;
5164                         rw = 1;
5165                 } else if (option_index == 3) {
5166                         init_extent_tree = 1;
5167                         rw = 1;
5168                         repair = 1;
5169                 }
5170
5171         }
5172         argc = argc - optind;
5173
5174         if (argc != 1)
5175                 usage(cmd_check_usage);
5176
5177         radix_tree_init();
5178         cache_tree_init(&root_cache);
5179
5180         if((ret = check_mounted(argv[optind])) < 0) {
5181                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
5182                 return ret;
5183         } else if(ret) {
5184                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
5185                 return -EBUSY;
5186         }
5187
5188         info = open_ctree_fs_info(argv[optind], bytenr, 0, rw, 1);
5189         if (!info) {
5190                 fprintf(stderr, "Couldn't open file system\n");
5191                 return -EIO;
5192         }
5193
5194         uuid_unparse(info->super_copy->fsid, uuidbuf);
5195         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
5196
5197         if (!extent_buffer_uptodate(info->tree_root->node) ||
5198             !extent_buffer_uptodate(info->dev_root->node) ||
5199             !extent_buffer_uptodate(info->extent_root->node) ||
5200             !extent_buffer_uptodate(info->chunk_root->node)) {
5201                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
5202                 return -EIO;
5203         }
5204
5205         root = info->fs_root;
5206
5207         if (init_extent_tree) {
5208                 printf("Creating a new extent tree\n");
5209                 ret = reinit_extent_tree(info);
5210                 if (ret)
5211                         return ret;
5212         }
5213         fprintf(stderr, "checking extents\n");
5214         if (init_csum_tree) {
5215                 struct btrfs_trans_handle *trans;
5216
5217                 fprintf(stderr, "Reinit crc root\n");
5218                 trans = btrfs_start_transaction(info->csum_root, 1);
5219                 if (IS_ERR(trans)) {
5220                         fprintf(stderr, "Error starting transaction\n");
5221                         return PTR_ERR(trans);
5222                 }
5223
5224                 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
5225                 if (ret) {
5226                         fprintf(stderr, "crc root initialization failed\n");
5227                         return -EIO;
5228                 }
5229
5230                 ret = btrfs_commit_transaction(trans, root);
5231                 if (ret)
5232                         exit(1);
5233                 goto out;
5234         }
5235         ret = check_extents(root, repair);
5236         if (ret)
5237                 fprintf(stderr, "Errors found in extent allocation tree\n");
5238
5239         fprintf(stderr, "checking free space cache\n");
5240         ret = check_space_cache(root);
5241         if (ret)
5242                 goto out;
5243
5244         fprintf(stderr, "checking fs roots\n");
5245         ret = check_fs_roots(root, &root_cache);
5246         if (ret)
5247                 goto out;
5248
5249         fprintf(stderr, "checking csums\n");
5250         ret = check_csums(root);
5251         if (ret)
5252                 goto out;
5253
5254         fprintf(stderr, "checking root refs\n");
5255         ret = check_root_refs(root, &root_cache);
5256 out:
5257         free_root_recs(&root_cache);
5258         close_ctree(root);
5259
5260         if (found_old_backref) { /*
5261                  * there was a disk format change when mixed
5262                  * backref was in testing tree. The old format
5263                  * existed about one week.
5264                  */
5265                 printf("\n * Found old mixed backref format. "
5266                        "The old format is not supported! *"
5267                        "\n * Please mount the FS in readonly mode, "
5268                        "backup data and re-format the FS. *\n\n");
5269                 ret = 1;
5270         }
5271         printf("found %llu bytes used err is %d\n",
5272                (unsigned long long)bytes_used, ret);
5273         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
5274         printf("total tree bytes: %llu\n",
5275                (unsigned long long)total_btree_bytes);
5276         printf("total fs tree bytes: %llu\n",
5277                (unsigned long long)total_fs_tree_bytes);
5278         printf("total extent tree bytes: %llu\n",
5279                (unsigned long long)total_extent_tree_bytes);
5280         printf("btree space waste bytes: %llu\n",
5281                (unsigned long long)btree_space_waste);
5282         printf("file data blocks allocated: %llu\n referenced %llu\n",
5283                 (unsigned long long)data_bytes_allocated,
5284                 (unsigned long long)data_bytes_referenced);
5285         printf("%s\n", BTRFS_BUILD_VERSION);
5286         return ret;
5287 }