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