Btrfs-progs: Add block group check funtion
[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(root, &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(root, &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(root, &path);
828                         return 1;
829                 }
830
831                 path.slots[0]++;
832         }
833
834         btrfs_release_path(root, &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(root->fs_info->csum_root, &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;
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                 goto out;
1234
1235         if (refs > 1) {
1236                 ret = enter_shared_node(root, path->nodes[*level]->start,
1237                                         refs, wc, *level);
1238                 if (ret > 0)
1239                         goto out;
1240         }
1241
1242         while (*level >= 0) {
1243                 WARN_ON(*level < 0);
1244                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1245                 cur = path->nodes[*level];
1246
1247                 if (btrfs_header_level(cur) != *level)
1248                         WARN_ON(1);
1249
1250                 if (path->slots[*level] >= btrfs_header_nritems(cur))
1251                         break;
1252                 if (*level == 0) {
1253                         ret = process_one_leaf(root, cur, wc);
1254                         break;
1255                 }
1256                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1257                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1258                 blocksize = btrfs_level_size(root, *level - 1);
1259                 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1260                                                1, &refs, NULL);
1261                 if (ret < 0)
1262                         refs = 0;
1263
1264                 if (refs > 1) {
1265                         ret = enter_shared_node(root, bytenr, refs,
1266                                                 wc, *level - 1);
1267                         if (ret > 0) {
1268                                 path->slots[*level]++;
1269                                 continue;
1270                         }
1271                 }
1272
1273                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1274                 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1275                         free_extent_buffer(next);
1276                         reada_walk_down(root, cur, path->slots[*level]);
1277                         next = read_tree_block(root, bytenr, blocksize,
1278                                                ptr_gen);
1279                 }
1280
1281                 *level = *level - 1;
1282                 free_extent_buffer(path->nodes[*level]);
1283                 path->nodes[*level] = next;
1284                 path->slots[*level] = 0;
1285         }
1286 out:
1287         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1288         return 0;
1289 }
1290
1291 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1292                         struct walk_control *wc, int *level)
1293 {
1294         int i;
1295         struct extent_buffer *leaf;
1296
1297         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1298                 leaf = path->nodes[i];
1299                 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1300                         path->slots[i]++;
1301                         *level = i;
1302                         return 0;
1303                 } else {
1304                         free_extent_buffer(path->nodes[*level]);
1305                         path->nodes[*level] = NULL;
1306                         BUG_ON(*level > wc->active_node);
1307                         if (*level == wc->active_node)
1308                                 leave_shared_node(root, wc, *level);
1309                         *level = i + 1;
1310                 }
1311         }
1312         return 1;
1313 }
1314
1315 static int check_root_dir(struct inode_record *rec)
1316 {
1317         struct inode_backref *backref;
1318         int ret = -1;
1319
1320         if (!rec->found_inode_item || rec->errors)
1321                 goto out;
1322         if (rec->nlink != 1 || rec->found_link != 0)
1323                 goto out;
1324         if (list_empty(&rec->backrefs))
1325                 goto out;
1326         backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1327         if (!backref->found_inode_ref)
1328                 goto out;
1329         if (backref->index != 0 || backref->namelen != 2 ||
1330             memcmp(backref->name, "..", 2))
1331                 goto out;
1332         if (backref->found_dir_index || backref->found_dir_item)
1333                 goto out;
1334         ret = 0;
1335 out:
1336         return ret;
1337 }
1338
1339 static int check_inode_recs(struct btrfs_root *root,
1340                             struct cache_tree *inode_cache)
1341 {
1342         struct cache_extent *cache;
1343         struct ptr_node *node;
1344         struct inode_record *rec;
1345         struct inode_backref *backref;
1346         int ret;
1347         u64 error = 0;
1348         u64 root_dirid = btrfs_root_dirid(&root->root_item);
1349
1350         if (btrfs_root_refs(&root->root_item) == 0) {
1351                 if (!cache_tree_empty(inode_cache))
1352                         fprintf(stderr, "warning line %d\n", __LINE__);
1353                 return 0;
1354         }
1355
1356         rec = get_inode_rec(inode_cache, root_dirid, 0);
1357         if (rec) {
1358                 ret = check_root_dir(rec);
1359                 if (ret) {
1360                         fprintf(stderr, "root %llu root dir %llu error\n",
1361                                 (unsigned long long)root->root_key.objectid,
1362                                 (unsigned long long)root_dirid);
1363                         error++;
1364                 }
1365         } else {
1366                 fprintf(stderr, "root %llu root dir %llu not found\n",
1367                         (unsigned long long)root->root_key.objectid,
1368                         (unsigned long long)root_dirid);
1369         }
1370
1371         while (1) {
1372                 cache = search_cache_extent(inode_cache, 0);
1373                 if (!cache)
1374                         break;
1375                 node = container_of(cache, struct ptr_node, cache);
1376                 rec = node->data;
1377                 remove_cache_extent(inode_cache, &node->cache);
1378                 free(node);
1379                 if (rec->ino == root_dirid ||
1380                     rec->ino == BTRFS_ORPHAN_OBJECTID) {
1381                         free_inode_rec(rec);
1382                         continue;
1383                 }
1384
1385                 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
1386                         ret = check_orphan_item(root, rec->ino);
1387                         if (ret == 0)
1388                                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1389                         if (can_free_inode_rec(rec)) {
1390                                 free_inode_rec(rec);
1391                                 continue;
1392                         }
1393                 }
1394
1395                 error++;
1396                 if (!rec->found_inode_item)
1397                         rec->errors |= I_ERR_NO_INODE_ITEM;
1398                 if (rec->found_link != rec->nlink)
1399                         rec->errors |= I_ERR_LINK_COUNT_WRONG;
1400                 fprintf(stderr, "root %llu inode %llu errors %x\n",
1401                         (unsigned long long) root->root_key.objectid,
1402                         (unsigned long long) rec->ino, rec->errors);
1403                 list_for_each_entry(backref, &rec->backrefs, list) {
1404                         if (!backref->found_dir_item)
1405                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1406                         if (!backref->found_dir_index)
1407                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1408                         if (!backref->found_inode_ref)
1409                                 backref->errors |= REF_ERR_NO_INODE_REF;
1410                         fprintf(stderr, "\tunresolved ref dir %llu index %llu"
1411                                 " namelen %u name %s filetype %d error %x\n",
1412                                 (unsigned long long)backref->dir,
1413                                 (unsigned long long)backref->index,
1414                                 backref->namelen, backref->name,
1415                                 backref->filetype, backref->errors);
1416                 }
1417                 free_inode_rec(rec);
1418         }
1419         return (error > 0) ? -1 : 0;
1420 }
1421
1422 static struct root_record *get_root_rec(struct cache_tree *root_cache,
1423                                         u64 objectid)
1424 {
1425         struct cache_extent *cache;
1426         struct root_record *rec = NULL;
1427         int ret;
1428
1429         cache = lookup_cache_extent(root_cache, objectid, 1);
1430         if (cache) {
1431                 rec = container_of(cache, struct root_record, cache);
1432         } else {
1433                 rec = calloc(1, sizeof(*rec));
1434                 rec->objectid = objectid;
1435                 INIT_LIST_HEAD(&rec->backrefs);
1436                 rec->cache.start = objectid;
1437                 rec->cache.size = 1;
1438
1439                 ret = insert_cache_extent(root_cache, &rec->cache);
1440                 BUG_ON(ret);
1441         }
1442         return rec;
1443 }
1444
1445 static struct root_backref *get_root_backref(struct root_record *rec,
1446                                              u64 ref_root, u64 dir, u64 index,
1447                                              const char *name, int namelen)
1448 {
1449         struct root_backref *backref;
1450
1451         list_for_each_entry(backref, &rec->backrefs, list) {
1452                 if (backref->ref_root != ref_root || backref->dir != dir ||
1453                     backref->namelen != namelen)
1454                         continue;
1455                 if (memcmp(name, backref->name, namelen))
1456                         continue;
1457                 return backref;
1458         }
1459
1460         backref = malloc(sizeof(*backref) + namelen + 1);
1461         memset(backref, 0, sizeof(*backref));
1462         backref->ref_root = ref_root;
1463         backref->dir = dir;
1464         backref->index = index;
1465         backref->namelen = namelen;
1466         memcpy(backref->name, name, namelen);
1467         backref->name[namelen] = '\0';
1468         list_add_tail(&backref->list, &rec->backrefs);
1469         return backref;
1470 }
1471
1472 static void free_root_record(struct cache_extent *cache)
1473 {
1474         struct root_record *rec;
1475         struct root_backref *backref;
1476
1477         rec = container_of(cache, struct root_record, cache);
1478         while (!list_empty(&rec->backrefs)) {
1479                 backref = list_entry(rec->backrefs.next,
1480                                      struct root_backref, list);
1481                 list_del(&backref->list);
1482                 free(backref);
1483         }
1484
1485         kfree(rec);
1486 }
1487
1488 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
1489
1490 static int add_root_backref(struct cache_tree *root_cache,
1491                             u64 root_id, u64 ref_root, u64 dir, u64 index,
1492                             const char *name, int namelen,
1493                             int item_type, int errors)
1494 {
1495         struct root_record *rec;
1496         struct root_backref *backref;
1497
1498         rec = get_root_rec(root_cache, root_id);
1499         backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
1500
1501         backref->errors |= errors;
1502
1503         if (item_type != BTRFS_DIR_ITEM_KEY) {
1504                 if (backref->found_dir_index || backref->found_back_ref ||
1505                     backref->found_forward_ref) {
1506                         if (backref->index != index)
1507                                 backref->errors |= REF_ERR_INDEX_UNMATCH;
1508                 } else {
1509                         backref->index = index;
1510                 }
1511         }
1512
1513         if (item_type == BTRFS_DIR_ITEM_KEY) {
1514                 if (backref->found_forward_ref)
1515                         rec->found_ref++;
1516                 backref->found_dir_item = 1;
1517         } else if (item_type == BTRFS_DIR_INDEX_KEY) {
1518                 backref->found_dir_index = 1;
1519         } else if (item_type == BTRFS_ROOT_REF_KEY) {
1520                 if (backref->found_forward_ref)
1521                         backref->errors |= REF_ERR_DUP_ROOT_REF;
1522                 else if (backref->found_dir_item)
1523                         rec->found_ref++;
1524                 backref->found_forward_ref = 1;
1525         } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
1526                 if (backref->found_back_ref)
1527                         backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
1528                 backref->found_back_ref = 1;
1529         } else {
1530                 BUG_ON(1);
1531         }
1532
1533         if (backref->found_forward_ref && backref->found_dir_item)
1534                 backref->reachable = 1;
1535         return 0;
1536 }
1537
1538 static int merge_root_recs(struct btrfs_root *root,
1539                            struct cache_tree *src_cache,
1540                            struct cache_tree *dst_cache)
1541 {
1542         struct cache_extent *cache;
1543         struct ptr_node *node;
1544         struct inode_record *rec;
1545         struct inode_backref *backref;
1546
1547         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
1548                 free_inode_recs_tree(src_cache);
1549                 return 0;
1550         }
1551
1552         while (1) {
1553                 cache = search_cache_extent(src_cache, 0);
1554                 if (!cache)
1555                         break;
1556                 node = container_of(cache, struct ptr_node, cache);
1557                 rec = node->data;
1558                 remove_cache_extent(src_cache, &node->cache);
1559                 free(node);
1560
1561                 if (!is_child_root(root, root->objectid, rec->ino))
1562                         goto skip;
1563
1564                 list_for_each_entry(backref, &rec->backrefs, list) {
1565                         BUG_ON(backref->found_inode_ref);
1566                         if (backref->found_dir_item)
1567                                 add_root_backref(dst_cache, rec->ino,
1568                                         root->root_key.objectid, backref->dir,
1569                                         backref->index, backref->name,
1570                                         backref->namelen, BTRFS_DIR_ITEM_KEY,
1571                                         backref->errors);
1572                         if (backref->found_dir_index)
1573                                 add_root_backref(dst_cache, rec->ino,
1574                                         root->root_key.objectid, backref->dir,
1575                                         backref->index, backref->name,
1576                                         backref->namelen, BTRFS_DIR_INDEX_KEY,
1577                                         backref->errors);
1578                 }
1579 skip:
1580                 free_inode_rec(rec);
1581         }
1582         return 0;
1583 }
1584
1585 static int check_root_refs(struct btrfs_root *root,
1586                            struct cache_tree *root_cache)
1587 {
1588         struct root_record *rec;
1589         struct root_record *ref_root;
1590         struct root_backref *backref;
1591         struct cache_extent *cache;
1592         int loop = 1;
1593         int ret;
1594         int error;
1595         int errors = 0;
1596
1597         rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
1598         rec->found_ref = 1;
1599
1600         /* fixme: this can not detect circular references */
1601         while (loop) {
1602                 loop = 0;
1603                 cache = search_cache_extent(root_cache, 0);
1604                 while (1) {
1605                         if (!cache)
1606                                 break;
1607                         rec = container_of(cache, struct root_record, cache);
1608                         cache = next_cache_extent(cache);
1609
1610                         if (rec->found_ref == 0)
1611                                 continue;
1612
1613                         list_for_each_entry(backref, &rec->backrefs, list) {
1614                                 if (!backref->reachable)
1615                                         continue;
1616
1617                                 ref_root = get_root_rec(root_cache,
1618                                                         backref->ref_root);
1619                                 if (ref_root->found_ref > 0)
1620                                         continue;
1621
1622                                 backref->reachable = 0;
1623                                 rec->found_ref--;
1624                                 if (rec->found_ref == 0)
1625                                         loop = 1;
1626                         }
1627                 }
1628         }
1629
1630         cache = search_cache_extent(root_cache, 0);
1631         while (1) {
1632                 if (!cache)
1633                         break;
1634                 rec = container_of(cache, struct root_record, cache);
1635                 cache = next_cache_extent(cache);
1636
1637                 if (rec->found_ref == 0 &&
1638                     rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1639                     rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
1640                         ret = check_orphan_item(root->fs_info->tree_root,
1641                                                 rec->objectid);
1642                         if (ret == 0)
1643                                 continue;
1644
1645                         /*
1646                          * If we don't have a root item then we likely just have
1647                          * a dir item in a snapshot for this root but no actual
1648                          * ref key or anything so it's meaningless.
1649                          */
1650                         if (!rec->found_root_item)
1651                                 continue;
1652                         errors++;
1653                         fprintf(stderr, "fs tree %llu not referenced\n",
1654                                 (unsigned long long)rec->objectid);
1655                 }
1656
1657                 error = 0;
1658                 if (rec->found_ref > 0 && !rec->found_root_item)
1659                         error = 1;
1660                 list_for_each_entry(backref, &rec->backrefs, list) {
1661                         if (!backref->found_dir_item)
1662                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1663                         if (!backref->found_dir_index)
1664                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1665                         if (!backref->found_back_ref)
1666                                 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
1667                         if (!backref->found_forward_ref)
1668                                 backref->errors |= REF_ERR_NO_ROOT_REF;
1669                         if (backref->reachable && backref->errors)
1670                                 error = 1;
1671                 }
1672                 if (!error)
1673                         continue;
1674
1675                 errors++;
1676                 fprintf(stderr, "fs tree %llu refs %u %s\n",
1677                         (unsigned long long)rec->objectid, rec->found_ref,
1678                          rec->found_root_item ? "" : "not found");
1679
1680                 list_for_each_entry(backref, &rec->backrefs, list) {
1681                         if (!backref->reachable)
1682                                 continue;
1683                         if (!backref->errors && rec->found_root_item)
1684                                 continue;
1685                         fprintf(stderr, "\tunresolved ref root %llu dir %llu"
1686                                 " index %llu namelen %u name %s error %x\n",
1687                                 (unsigned long long)backref->ref_root,
1688                                 (unsigned long long)backref->dir,
1689                                 (unsigned long long)backref->index,
1690                                 backref->namelen, backref->name,
1691                                 backref->errors);
1692                 }
1693         }
1694         return errors > 0 ? 1 : 0;
1695 }
1696
1697 static int process_root_ref(struct extent_buffer *eb, int slot,
1698                             struct btrfs_key *key,
1699                             struct cache_tree *root_cache)
1700 {
1701         u64 dirid;
1702         u64 index;
1703         u32 len;
1704         u32 name_len;
1705         struct btrfs_root_ref *ref;
1706         char namebuf[BTRFS_NAME_LEN];
1707         int error;
1708
1709         ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
1710
1711         dirid = btrfs_root_ref_dirid(eb, ref);
1712         index = btrfs_root_ref_sequence(eb, ref);
1713         name_len = btrfs_root_ref_name_len(eb, ref);
1714
1715         if (name_len <= BTRFS_NAME_LEN) {
1716                 len = name_len;
1717                 error = 0;
1718         } else {
1719                 len = BTRFS_NAME_LEN;
1720                 error = REF_ERR_NAME_TOO_LONG;
1721         }
1722         read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1723
1724         if (key->type == BTRFS_ROOT_REF_KEY) {
1725                 add_root_backref(root_cache, key->offset, key->objectid, dirid,
1726                                  index, namebuf, len, key->type, error);
1727         } else {
1728                 add_root_backref(root_cache, key->objectid, key->offset, dirid,
1729                                  index, namebuf, len, key->type, error);
1730         }
1731         return 0;
1732 }
1733
1734 static int check_fs_root(struct btrfs_root *root,
1735                          struct cache_tree *root_cache,
1736                          struct walk_control *wc)
1737 {
1738         int ret = 0;
1739         int wret;
1740         int level;
1741         struct btrfs_path path;
1742         struct shared_node root_node;
1743         struct root_record *rec;
1744         struct btrfs_root_item *root_item = &root->root_item;
1745
1746         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1747                 rec = get_root_rec(root_cache, root->root_key.objectid);
1748                 if (btrfs_root_refs(root_item) > 0)
1749                         rec->found_root_item = 1;
1750         }
1751
1752         btrfs_init_path(&path);
1753         memset(&root_node, 0, sizeof(root_node));
1754         cache_tree_init(&root_node.root_cache);
1755         cache_tree_init(&root_node.inode_cache);
1756
1757         level = btrfs_header_level(root->node);
1758         memset(wc->nodes, 0, sizeof(wc->nodes));
1759         wc->nodes[level] = &root_node;
1760         wc->active_node = level;
1761         wc->root_level = level;
1762
1763         if (btrfs_root_refs(root_item) > 0 ||
1764             btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1765                 path.nodes[level] = root->node;
1766                 extent_buffer_get(root->node);
1767                 path.slots[level] = 0;
1768         } else {
1769                 struct btrfs_key key;
1770                 struct btrfs_disk_key found_key;
1771
1772                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1773                 level = root_item->drop_level;
1774                 path.lowest_level = level;
1775                 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1776                 BUG_ON(wret < 0);
1777                 btrfs_node_key(path.nodes[level], &found_key,
1778                                 path.slots[level]);
1779                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
1780                                         sizeof(found_key)));
1781         }
1782
1783         while (1) {
1784                 wret = walk_down_tree(root, &path, wc, &level);
1785                 if (wret < 0)
1786                         ret = wret;
1787                 if (wret != 0)
1788                         break;
1789
1790                 wret = walk_up_tree(root, &path, wc, &level);
1791                 if (wret < 0)
1792                         ret = wret;
1793                 if (wret != 0)
1794                         break;
1795         }
1796         btrfs_release_path(root, &path);
1797
1798         merge_root_recs(root, &root_node.root_cache, root_cache);
1799
1800         if (root_node.current) {
1801                 root_node.current->checked = 1;
1802                 maybe_free_inode_rec(&root_node.inode_cache,
1803                                 root_node.current);
1804         }
1805
1806         ret = check_inode_recs(root, &root_node.inode_cache);
1807         return ret;
1808 }
1809
1810 static int fs_root_objectid(u64 objectid)
1811 {
1812         if (objectid == BTRFS_FS_TREE_OBJECTID ||
1813             objectid == BTRFS_TREE_RELOC_OBJECTID ||
1814             objectid == BTRFS_DATA_RELOC_TREE_OBJECTID ||
1815             (objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1816              objectid <= BTRFS_LAST_FREE_OBJECTID))
1817                 return 1;
1818         return 0;
1819 }
1820
1821 static int check_fs_roots(struct btrfs_root *root,
1822                           struct cache_tree *root_cache)
1823 {
1824         struct btrfs_path path;
1825         struct btrfs_key key;
1826         struct walk_control wc;
1827         struct extent_buffer *leaf;
1828         struct btrfs_root *tmp_root;
1829         struct btrfs_root *tree_root = root->fs_info->tree_root;
1830         int ret;
1831         int err = 0;
1832
1833         memset(&wc, 0, sizeof(wc));
1834         cache_tree_init(&wc.shared);
1835         btrfs_init_path(&path);
1836
1837         key.offset = 0;
1838         key.objectid = 0;
1839         key.type = BTRFS_ROOT_ITEM_KEY;
1840         ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
1841         BUG_ON(ret < 0);
1842         while (1) {
1843                 leaf = path.nodes[0];
1844                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1845                         ret = btrfs_next_leaf(tree_root, &path);
1846                         if (ret != 0)
1847                                 break;
1848                         leaf = path.nodes[0];
1849                 }
1850                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1851                 if (key.type == BTRFS_ROOT_ITEM_KEY &&
1852                     fs_root_objectid(key.objectid)) {
1853                         tmp_root = btrfs_read_fs_root_no_cache(root->fs_info,
1854                                                                &key);
1855                         if (IS_ERR(tmp_root)) {
1856                                 err = 1;
1857                                 goto next;
1858                         }
1859                         ret = check_fs_root(tmp_root, root_cache, &wc);
1860                         if (ret)
1861                                 err = 1;
1862                         btrfs_free_fs_root(tmp_root);
1863                 } else if (key.type == BTRFS_ROOT_REF_KEY ||
1864                            key.type == BTRFS_ROOT_BACKREF_KEY) {
1865                         process_root_ref(leaf, path.slots[0], &key,
1866                                          root_cache);
1867                 }
1868 next:
1869                 path.slots[0]++;
1870         }
1871         btrfs_release_path(tree_root, &path);
1872
1873         if (!cache_tree_empty(&wc.shared))
1874                 fprintf(stderr, "warning line %d\n", __LINE__);
1875
1876         return err;
1877 }
1878
1879 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
1880 {
1881         struct list_head *cur = rec->backrefs.next;
1882         struct extent_backref *back;
1883         struct tree_backref *tback;
1884         struct data_backref *dback;
1885         u64 found = 0;
1886         int err = 0;
1887
1888         while(cur != &rec->backrefs) {
1889                 back = list_entry(cur, struct extent_backref, list);
1890                 cur = cur->next;
1891                 if (!back->found_extent_tree) {
1892                         err = 1;
1893                         if (!print_errs)
1894                                 goto out;
1895                         if (back->is_data) {
1896                                 dback = (struct data_backref *)back;
1897                                 fprintf(stderr, "Backref %llu %s %llu"
1898                                         " owner %llu offset %llu num_refs %lu"
1899                                         " not found in extent tree\n",
1900                                         (unsigned long long)rec->start,
1901                                         back->full_backref ?
1902                                         "parent" : "root",
1903                                         back->full_backref ?
1904                                         (unsigned long long)dback->parent:
1905                                         (unsigned long long)dback->root,
1906                                         (unsigned long long)dback->owner,
1907                                         (unsigned long long)dback->offset,
1908                                         (unsigned long)dback->num_refs);
1909                         } else {
1910                                 tback = (struct tree_backref *)back;
1911                                 fprintf(stderr, "Backref %llu parent %llu"
1912                                         " root %llu not found in extent tree\n",
1913                                         (unsigned long long)rec->start,
1914                                         (unsigned long long)tback->parent,
1915                                         (unsigned long long)tback->root);
1916                         }
1917                 }
1918                 if (!back->is_data && !back->found_ref) {
1919                         err = 1;
1920                         if (!print_errs)
1921                                 goto out;
1922                         tback = (struct tree_backref *)back;
1923                         fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
1924                                 (unsigned long long)rec->start,
1925                                 back->full_backref ? "parent" : "root",
1926                                 back->full_backref ?
1927                                 (unsigned long long)tback->parent :
1928                                 (unsigned long long)tback->root, back);
1929                 }
1930                 if (back->is_data) {
1931                         dback = (struct data_backref *)back;
1932                         if (dback->found_ref != dback->num_refs) {
1933                                 err = 1;
1934                                 if (!print_errs)
1935                                         goto out;
1936                                 fprintf(stderr, "Incorrect local backref count"
1937                                         " on %llu %s %llu owner %llu"
1938                                         " offset %llu found %u wanted %u back %p\n",
1939                                         (unsigned long long)rec->start,
1940                                         back->full_backref ?
1941                                         "parent" : "root",
1942                                         back->full_backref ?
1943                                         (unsigned long long)dback->parent:
1944                                         (unsigned long long)dback->root,
1945                                         (unsigned long long)dback->owner,
1946                                         (unsigned long long)dback->offset,
1947                                         dback->found_ref, dback->num_refs, back);
1948                         }
1949                         if (dback->disk_bytenr != rec->start) {
1950                                 err = 1;
1951                                 if (!print_errs)
1952                                         goto out;
1953                                 fprintf(stderr, "Backref disk bytenr does not"
1954                                         " match extent record, bytenr=%llu, "
1955                                         "ref bytenr=%llu\n",
1956                                         (unsigned long long)rec->start,
1957                                         (unsigned long long)dback->disk_bytenr);
1958                         }
1959
1960                         if (dback->bytes != rec->nr) {
1961                                 err = 1;
1962                                 if (!print_errs)
1963                                         goto out;
1964                                 fprintf(stderr, "Backref bytes do not match "
1965                                         "extent backref, bytenr=%llu, ref "
1966                                         "bytes=%llu, backref bytes=%llu\n",
1967                                         (unsigned long long)rec->start,
1968                                         (unsigned long long)rec->nr,
1969                                         (unsigned long long)dback->bytes);
1970                         }
1971                 }
1972                 if (!back->is_data) {
1973                         found += 1;
1974                 } else {
1975                         dback = (struct data_backref *)back;
1976                         found += dback->found_ref;
1977                 }
1978         }
1979         if (found != rec->refs) {
1980                 err = 1;
1981                 if (!print_errs)
1982                         goto out;
1983                 fprintf(stderr, "Incorrect global backref count "
1984                         "on %llu found %llu wanted %llu\n",
1985                         (unsigned long long)rec->start,
1986                         (unsigned long long)found,
1987                         (unsigned long long)rec->refs);
1988         }
1989 out:
1990         return err;
1991 }
1992
1993 static int free_all_extent_backrefs(struct extent_record *rec)
1994 {
1995         struct extent_backref *back;
1996         struct list_head *cur;
1997         while (!list_empty(&rec->backrefs)) {
1998                 cur = rec->backrefs.next;
1999                 back = list_entry(cur, struct extent_backref, list);
2000                 list_del(cur);
2001                 free(back);
2002         }
2003         return 0;
2004 }
2005
2006 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
2007                                      struct cache_tree *extent_cache)
2008 {
2009         struct cache_extent *cache;
2010         struct extent_record *rec;
2011
2012         while (1) {
2013                 cache = first_cache_extent(extent_cache);
2014                 if (!cache)
2015                         break;
2016                 rec = container_of(cache, struct extent_record, cache);
2017                 btrfs_unpin_extent(fs_info, rec->start, rec->max_size);
2018                 remove_cache_extent(extent_cache, cache);
2019                 free_all_extent_backrefs(rec);
2020                 free(rec);
2021         }
2022 }
2023
2024 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
2025                                  struct extent_record *rec)
2026 {
2027         if (rec->content_checked && rec->owner_ref_checked &&
2028             rec->extent_item_refs == rec->refs && rec->refs > 0 &&
2029             rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
2030                 remove_cache_extent(extent_cache, &rec->cache);
2031                 free_all_extent_backrefs(rec);
2032                 list_del_init(&rec->list);
2033                 free(rec);
2034         }
2035         return 0;
2036 }
2037
2038 static int check_owner_ref(struct btrfs_root *root,
2039                             struct extent_record *rec,
2040                             struct extent_buffer *buf)
2041 {
2042         struct extent_backref *node;
2043         struct tree_backref *back;
2044         struct btrfs_root *ref_root;
2045         struct btrfs_key key;
2046         struct btrfs_path path;
2047         struct extent_buffer *parent;
2048         int level;
2049         int found = 0;
2050         int ret;
2051
2052         list_for_each_entry(node, &rec->backrefs, list) {
2053                 if (node->is_data)
2054                         continue;
2055                 if (!node->found_ref)
2056                         continue;
2057                 if (node->full_backref)
2058                         continue;
2059                 back = (struct tree_backref *)node;
2060                 if (btrfs_header_owner(buf) == back->root)
2061                         return 0;
2062         }
2063         BUG_ON(rec->is_root);
2064
2065         /* try to find the block by search corresponding fs tree */
2066         key.objectid = btrfs_header_owner(buf);
2067         key.type = BTRFS_ROOT_ITEM_KEY;
2068         key.offset = (u64)-1;
2069
2070         ref_root = btrfs_read_fs_root(root->fs_info, &key);
2071         if (IS_ERR(ref_root))
2072                 return 1;
2073
2074         level = btrfs_header_level(buf);
2075         if (level == 0)
2076                 btrfs_item_key_to_cpu(buf, &key, 0);
2077         else
2078                 btrfs_node_key_to_cpu(buf, &key, 0);
2079
2080         btrfs_init_path(&path);
2081         path.lowest_level = level + 1;
2082         ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
2083         if (ret < 0)
2084                 return 0;
2085
2086         parent = path.nodes[level + 1];
2087         if (parent && buf->start == btrfs_node_blockptr(parent,
2088                                                         path.slots[level + 1]))
2089                 found = 1;
2090
2091         btrfs_release_path(ref_root, &path);
2092         return found ? 0 : 1;
2093 }
2094
2095 static int is_extent_tree_record(struct extent_record *rec)
2096 {
2097         struct list_head *cur = rec->backrefs.next;
2098         struct extent_backref *node;
2099         struct tree_backref *back;
2100         int is_extent = 0;
2101
2102         while(cur != &rec->backrefs) {
2103                 node = list_entry(cur, struct extent_backref, list);
2104                 cur = cur->next;
2105                 if (node->is_data)
2106                         return 0;
2107                 back = (struct tree_backref *)node;
2108                 if (node->full_backref)
2109                         return 0;
2110                 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
2111                         is_extent = 1;
2112         }
2113         return is_extent;
2114 }
2115
2116
2117 static int record_bad_block_io(struct btrfs_fs_info *info,
2118                                struct cache_tree *extent_cache,
2119                                u64 start, u64 len)
2120 {
2121         struct extent_record *rec;
2122         struct cache_extent *cache;
2123         struct btrfs_key key;
2124
2125         cache = lookup_cache_extent(extent_cache, start, len);
2126         if (!cache)
2127                 return 0;
2128
2129         rec = container_of(cache, struct extent_record, cache);
2130         if (!is_extent_tree_record(rec))
2131                 return 0;
2132
2133         btrfs_disk_key_to_cpu(&key, &rec->parent_key);
2134         return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
2135 }
2136
2137 static int check_block(struct btrfs_root *root,
2138                        struct cache_tree *extent_cache,
2139                        struct extent_buffer *buf, u64 flags)
2140 {
2141         struct extent_record *rec;
2142         struct cache_extent *cache;
2143         struct btrfs_key key;
2144         int ret = 1;
2145         int level;
2146
2147         cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
2148         if (!cache)
2149                 return 1;
2150         rec = container_of(cache, struct extent_record, cache);
2151         rec->generation = btrfs_header_generation(buf);
2152
2153         level = btrfs_header_level(buf);
2154         if (btrfs_header_nritems(buf) > 0) {
2155
2156                 if (level == 0)
2157                         btrfs_item_key_to_cpu(buf, &key, 0);
2158                 else
2159                         btrfs_node_key_to_cpu(buf, &key, 0);
2160
2161                 rec->info_objectid = key.objectid;
2162         }
2163         rec->info_level = level;
2164
2165         if (btrfs_is_leaf(buf))
2166                 ret = btrfs_check_leaf(root, &rec->parent_key, buf);
2167         else
2168                 ret = btrfs_check_node(root, &rec->parent_key, buf);
2169
2170         if (ret) {
2171                 fprintf(stderr, "bad block %llu\n",
2172                         (unsigned long long)buf->start);
2173         } else {
2174                 rec->content_checked = 1;
2175                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
2176                         rec->owner_ref_checked = 1;
2177                 else {
2178                         ret = check_owner_ref(root, rec, buf);
2179                         if (!ret)
2180                                 rec->owner_ref_checked = 1;
2181                 }
2182         }
2183         if (!ret)
2184                 maybe_free_extent_rec(extent_cache, rec);
2185         return ret;
2186 }
2187
2188 static struct tree_backref *find_tree_backref(struct extent_record *rec,
2189                                                 u64 parent, u64 root)
2190 {
2191         struct list_head *cur = rec->backrefs.next;
2192         struct extent_backref *node;
2193         struct tree_backref *back;
2194
2195         while(cur != &rec->backrefs) {
2196                 node = list_entry(cur, struct extent_backref, list);
2197                 cur = cur->next;
2198                 if (node->is_data)
2199                         continue;
2200                 back = (struct tree_backref *)node;
2201                 if (parent > 0) {
2202                         if (!node->full_backref)
2203                                 continue;
2204                         if (parent == back->parent)
2205                                 return back;
2206                 } else {
2207                         if (node->full_backref)
2208                                 continue;
2209                         if (back->root == root)
2210                                 return back;
2211                 }
2212         }
2213         return NULL;
2214 }
2215
2216 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
2217                                                 u64 parent, u64 root)
2218 {
2219         struct tree_backref *ref = malloc(sizeof(*ref));
2220         memset(&ref->node, 0, sizeof(ref->node));
2221         if (parent > 0) {
2222                 ref->parent = parent;
2223                 ref->node.full_backref = 1;
2224         } else {
2225                 ref->root = root;
2226                 ref->node.full_backref = 0;
2227         }
2228         list_add_tail(&ref->node.list, &rec->backrefs);
2229
2230         return ref;
2231 }
2232
2233 static struct data_backref *find_data_backref(struct extent_record *rec,
2234                                                 u64 parent, u64 root,
2235                                                 u64 owner, u64 offset,
2236                                                 int found_ref,
2237                                                 u64 disk_bytenr, u64 bytes)
2238 {
2239         struct list_head *cur = rec->backrefs.next;
2240         struct extent_backref *node;
2241         struct data_backref *back;
2242
2243         while(cur != &rec->backrefs) {
2244                 node = list_entry(cur, struct extent_backref, list);
2245                 cur = cur->next;
2246                 if (!node->is_data)
2247                         continue;
2248                 back = (struct data_backref *)node;
2249                 if (parent > 0) {
2250                         if (!node->full_backref)
2251                                 continue;
2252                         if (parent == back->parent)
2253                                 return back;
2254                 } else {
2255                         if (node->full_backref)
2256                                 continue;
2257                         if (back->root == root && back->owner == owner &&
2258                             back->offset == offset) {
2259                                 if (found_ref && node->found_ref &&
2260                                     (back->bytes != bytes ||
2261                                     back->disk_bytenr != disk_bytenr))
2262                                         continue;
2263                                 return back;
2264                         }
2265                 }
2266         }
2267         return NULL;
2268 }
2269
2270 static struct data_backref *alloc_data_backref(struct extent_record *rec,
2271                                                 u64 parent, u64 root,
2272                                                 u64 owner, u64 offset,
2273                                                 u64 max_size)
2274 {
2275         struct data_backref *ref = malloc(sizeof(*ref));
2276         memset(&ref->node, 0, sizeof(ref->node));
2277         ref->node.is_data = 1;
2278
2279         if (parent > 0) {
2280                 ref->parent = parent;
2281                 ref->owner = 0;
2282                 ref->offset = 0;
2283                 ref->node.full_backref = 1;
2284         } else {
2285                 ref->root = root;
2286                 ref->owner = owner;
2287                 ref->offset = offset;
2288                 ref->node.full_backref = 0;
2289         }
2290         ref->bytes = max_size;
2291         ref->found_ref = 0;
2292         ref->num_refs = 0;
2293         list_add_tail(&ref->node.list, &rec->backrefs);
2294         if (max_size > rec->max_size)
2295                 rec->max_size = max_size;
2296         return ref;
2297 }
2298
2299 static int add_extent_rec(struct cache_tree *extent_cache,
2300                           struct btrfs_key *parent_key,
2301                           u64 start, u64 nr, u64 extent_item_refs,
2302                           int is_root, int inc_ref, int set_checked,
2303                           int metadata, int extent_rec, u64 max_size)
2304 {
2305         struct extent_record *rec;
2306         struct cache_extent *cache;
2307         int ret = 0;
2308         int dup = 0;
2309
2310         cache = lookup_cache_extent(extent_cache, start, nr);
2311         if (cache) {
2312                 rec = container_of(cache, struct extent_record, cache);
2313                 if (inc_ref)
2314                         rec->refs++;
2315                 if (rec->nr == 1)
2316                         rec->nr = max(nr, max_size);
2317
2318                 /*
2319                  * We need to make sure to reset nr to whatever the extent
2320                  * record says was the real size, this way we can compare it to
2321                  * the backrefs.
2322                  */
2323                 if (extent_rec) {
2324                         if (start != rec->start || rec->found_rec) {
2325                                 struct extent_record *tmp;
2326
2327                                 dup = 1;
2328                                 if (list_empty(&rec->list))
2329                                         list_add_tail(&rec->list,
2330                                                       &duplicate_extents);
2331
2332                                 /*
2333                                  * We have to do this song and dance in case we
2334                                  * find an extent record that falls inside of
2335                                  * our current extent record but does not have
2336                                  * the same objectid.
2337                                  */
2338                                 tmp = malloc(sizeof(*tmp));
2339                                 if (!tmp)
2340                                         return -ENOMEM;
2341                                 tmp->start = start;
2342                                 tmp->max_size = max_size;
2343                                 tmp->nr = nr;
2344                                 tmp->found_rec = 1;
2345                                 tmp->metadata = metadata;
2346                                 tmp->extent_item_refs = extent_item_refs;
2347                                 INIT_LIST_HEAD(&tmp->list);
2348                                 list_add_tail(&tmp->list, &rec->dups);
2349                                 rec->num_duplicates++;
2350                         } else {
2351                                 rec->nr = nr;
2352                                 rec->found_rec = 1;
2353                         }
2354                 }
2355
2356                 if (extent_item_refs && !dup) {
2357                         if (rec->extent_item_refs) {
2358                                 fprintf(stderr, "block %llu rec "
2359                                         "extent_item_refs %llu, passed %llu\n",
2360                                         (unsigned long long)start,
2361                                         (unsigned long long)
2362                                                         rec->extent_item_refs,
2363                                         (unsigned long long)extent_item_refs);
2364                         }
2365                         rec->extent_item_refs = extent_item_refs;
2366                 }
2367                 if (is_root)
2368                         rec->is_root = 1;
2369                 if (set_checked) {
2370                         rec->content_checked = 1;
2371                         rec->owner_ref_checked = 1;
2372                 }
2373
2374                 if (parent_key)
2375                         btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2376
2377                 if (rec->max_size < max_size)
2378                         rec->max_size = max_size;
2379
2380                 maybe_free_extent_rec(extent_cache, rec);
2381                 return ret;
2382         }
2383         rec = malloc(sizeof(*rec));
2384         rec->start = start;
2385         rec->max_size = max_size;
2386         rec->nr = max(nr, max_size);
2387         rec->found_rec = extent_rec;
2388         rec->content_checked = 0;
2389         rec->owner_ref_checked = 0;
2390         rec->num_duplicates = 0;
2391         rec->metadata = metadata;
2392         INIT_LIST_HEAD(&rec->backrefs);
2393         INIT_LIST_HEAD(&rec->dups);
2394         INIT_LIST_HEAD(&rec->list);
2395
2396         if (is_root)
2397                 rec->is_root = 1;
2398         else
2399                 rec->is_root = 0;
2400
2401         if (inc_ref)
2402                 rec->refs = 1;
2403         else
2404                 rec->refs = 0;
2405
2406         if (extent_item_refs)
2407                 rec->extent_item_refs = extent_item_refs;
2408         else
2409                 rec->extent_item_refs = 0;
2410
2411         if (parent_key)
2412                 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2413         else
2414                 memset(&rec->parent_key, 0, sizeof(*parent_key));
2415
2416         rec->cache.start = start;
2417         rec->cache.size = nr;
2418         ret = insert_cache_extent(extent_cache, &rec->cache);
2419         BUG_ON(ret);
2420         bytes_used += nr;
2421         if (set_checked) {
2422                 rec->content_checked = 1;
2423                 rec->owner_ref_checked = 1;
2424         }
2425         return ret;
2426 }
2427
2428 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
2429                             u64 parent, u64 root, int found_ref)
2430 {
2431         struct extent_record *rec;
2432         struct tree_backref *back;
2433         struct cache_extent *cache;
2434
2435         cache = lookup_cache_extent(extent_cache, bytenr, 1);
2436         if (!cache) {
2437                 add_extent_rec(extent_cache, NULL, bytenr,
2438                                1, 0, 0, 0, 0, 1, 0, 0);
2439                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
2440                 if (!cache)
2441                         abort();
2442         }
2443
2444         rec = container_of(cache, struct extent_record, cache);
2445         if (rec->start != bytenr) {
2446                 abort();
2447         }
2448
2449         back = find_tree_backref(rec, parent, root);
2450         if (!back)
2451                 back = alloc_tree_backref(rec, parent, root);
2452
2453         if (found_ref) {
2454                 if (back->node.found_ref) {
2455                         fprintf(stderr, "Extent back ref already exists "
2456                                 "for %llu parent %llu root %llu \n",
2457                                 (unsigned long long)bytenr,
2458                                 (unsigned long long)parent,
2459                                 (unsigned long long)root);
2460                 }
2461                 back->node.found_ref = 1;
2462         } else {
2463                 if (back->node.found_extent_tree) {
2464                         fprintf(stderr, "Extent back ref already exists "
2465                                 "for %llu parent %llu root %llu \n",
2466                                 (unsigned long long)bytenr,
2467                                 (unsigned long long)parent,
2468                                 (unsigned long long)root);
2469                 }
2470                 back->node.found_extent_tree = 1;
2471         }
2472         return 0;
2473 }
2474
2475 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
2476                             u64 parent, u64 root, u64 owner, u64 offset,
2477                             u32 num_refs, int found_ref, u64 max_size)
2478 {
2479         struct extent_record *rec;
2480         struct data_backref *back;
2481         struct cache_extent *cache;
2482
2483         cache = lookup_cache_extent(extent_cache, bytenr, 1);
2484         if (!cache) {
2485                 add_extent_rec(extent_cache, NULL, bytenr, 1, 0, 0, 0, 0,
2486                                0, 0, max_size);
2487                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
2488                 if (!cache)
2489                         abort();
2490         }
2491
2492         rec = container_of(cache, struct extent_record, cache);
2493         if (rec->max_size < max_size)
2494                 rec->max_size = max_size;
2495
2496         /*
2497          * If found_ref is set then max_size is the real size and must match the
2498          * existing refs.  So if we have already found a ref then we need to
2499          * make sure that this ref matches the existing one, otherwise we need
2500          * to add a new backref so we can notice that the backrefs don't match
2501          * and we need to figure out who is telling the truth.  This is to
2502          * account for that awful fsync bug I introduced where we'd end up with
2503          * a btrfs_file_extent_item that would have its length include multiple
2504          * prealloc extents or point inside of a prealloc extent.
2505          */
2506         back = find_data_backref(rec, parent, root, owner, offset, found_ref,
2507                                  bytenr, max_size);
2508         if (!back)
2509                 back = alloc_data_backref(rec, parent, root, owner, offset,
2510                                           max_size);
2511
2512         if (found_ref) {
2513                 BUG_ON(num_refs != 1);
2514                 if (back->node.found_ref)
2515                         BUG_ON(back->bytes != max_size);
2516                 back->node.found_ref = 1;
2517                 back->found_ref += 1;
2518                 back->bytes = max_size;
2519                 back->disk_bytenr = bytenr;
2520                 rec->refs += 1;
2521                 rec->content_checked = 1;
2522                 rec->owner_ref_checked = 1;
2523         } else {
2524                 if (back->node.found_extent_tree) {
2525                         fprintf(stderr, "Extent back ref already exists "
2526                                 "for %llu parent %llu root %llu"
2527                                 "owner %llu offset %llu num_refs %lu\n",
2528                                 (unsigned long long)bytenr,
2529                                 (unsigned long long)parent,
2530                                 (unsigned long long)root,
2531                                 (unsigned long long)owner,
2532                                 (unsigned long long)offset,
2533                                 (unsigned long)num_refs);
2534                 }
2535                 back->num_refs = num_refs;
2536                 back->node.found_extent_tree = 1;
2537         }
2538         return 0;
2539 }
2540
2541 static int add_pending(struct cache_tree *pending,
2542                        struct cache_tree *seen, u64 bytenr, u32 size)
2543 {
2544         int ret;
2545         ret = add_cache_extent(seen, bytenr, size);
2546         if (ret)
2547                 return ret;
2548         add_cache_extent(pending, bytenr, size);
2549         return 0;
2550 }
2551
2552 static int pick_next_pending(struct cache_tree *pending,
2553                         struct cache_tree *reada,
2554                         struct cache_tree *nodes,
2555                         u64 last, struct block_info *bits, int bits_nr,
2556                         int *reada_bits)
2557 {
2558         unsigned long node_start = last;
2559         struct cache_extent *cache;
2560         int ret;
2561
2562         cache = search_cache_extent(reada, 0);
2563         if (cache) {
2564                 bits[0].start = cache->start;
2565                 bits[1].size = cache->size;
2566                 *reada_bits = 1;
2567                 return 1;
2568         }
2569         *reada_bits = 0;
2570         if (node_start > 32768)
2571                 node_start -= 32768;
2572
2573         cache = search_cache_extent(nodes, node_start);
2574         if (!cache)
2575                 cache = search_cache_extent(nodes, 0);
2576
2577         if (!cache) {
2578                  cache = search_cache_extent(pending, 0);
2579                  if (!cache)
2580                          return 0;
2581                  ret = 0;
2582                  do {
2583                          bits[ret].start = cache->start;
2584                          bits[ret].size = cache->size;
2585                          cache = next_cache_extent(cache);
2586                          ret++;
2587                  } while (cache && ret < bits_nr);
2588                  return ret;
2589         }
2590
2591         ret = 0;
2592         do {
2593                 bits[ret].start = cache->start;
2594                 bits[ret].size = cache->size;
2595                 cache = next_cache_extent(cache);
2596                 ret++;
2597         } while (cache && ret < bits_nr);
2598
2599         if (bits_nr - ret > 8) {
2600                 u64 lookup = bits[0].start + bits[0].size;
2601                 struct cache_extent *next;
2602                 next = search_cache_extent(pending, lookup);
2603                 while(next) {
2604                         if (next->start - lookup > 32768)
2605                                 break;
2606                         bits[ret].start = next->start;
2607                         bits[ret].size = next->size;
2608                         lookup = next->start + next->size;
2609                         ret++;
2610                         if (ret == bits_nr)
2611                                 break;
2612                         next = next_cache_extent(next);
2613                         if (!next)
2614                                 break;
2615                 }
2616         }
2617         return ret;
2618 }
2619
2620 static void free_chunk_record(struct cache_extent *cache)
2621 {
2622         struct chunk_record *rec;
2623
2624         rec = container_of(cache, struct chunk_record, cache);
2625         free(rec);
2626 }
2627
2628 FREE_EXTENT_CACHE_BASED_TREE(chunk_cache, free_chunk_record);
2629
2630 static void free_device_record(struct rb_node *node)
2631 {
2632         struct device_record *rec;
2633
2634         rec = container_of(node, struct device_record, node);
2635         free(rec);
2636 }
2637
2638 FREE_RB_BASED_TREE(device_cache, free_device_record);
2639
2640 static void block_group_tree_init(struct block_group_tree *tree)
2641 {
2642         cache_tree_init(&tree->tree);
2643         INIT_LIST_HEAD(&tree->block_groups);
2644 }
2645
2646 static int insert_block_group_record(struct block_group_tree *tree,
2647                                      struct block_group_record *bg_rec)
2648 {
2649         int ret;
2650
2651         ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
2652         if (ret)
2653                 return ret;
2654
2655         list_add_tail(&bg_rec->list, &tree->block_groups);
2656         return 0;
2657 }
2658
2659 static void free_block_group_record(struct cache_extent *cache)
2660 {
2661         struct block_group_record *rec;
2662
2663         rec = container_of(cache, struct block_group_record, cache);
2664         free(rec);
2665 }
2666
2667 static void free_block_group_tree(struct block_group_tree *tree)
2668 {
2669         cache_tree_free_extents(&tree->tree, free_block_group_record);
2670 }
2671
2672 static void device_extent_tree_init(struct device_extent_tree *tree)
2673 {
2674         cache_tree_init(&tree->tree);
2675         INIT_LIST_HEAD(&tree->no_chunk_orphans);
2676         INIT_LIST_HEAD(&tree->no_device_orphans);
2677 }
2678
2679 static int insert_device_extent_record(struct device_extent_tree *tree,
2680                                        struct device_extent_record *de_rec)
2681 {
2682         int ret;
2683
2684         /*
2685          * Device extent is a bit different from the other extents, because
2686          * the extents which belong to the different devices may have the
2687          * same start and size, so we need use the special extent cache
2688          * search/insert functions.
2689          */
2690         ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
2691         if (ret)
2692                 return ret;
2693
2694         list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
2695         list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
2696         return 0;
2697 }
2698
2699 static void free_device_extent_record(struct cache_extent *cache)
2700 {
2701         struct device_extent_record *rec;
2702
2703         rec = container_of(cache, struct device_extent_record, cache);
2704         free(rec);
2705 }
2706
2707 static void free_device_extent_tree(struct device_extent_tree *tree)
2708 {
2709         cache_tree_free_extents(&tree->tree, free_device_extent_record);
2710 }
2711
2712 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2713 static int process_extent_ref_v0(struct cache_tree *extent_cache,
2714                                  struct extent_buffer *leaf, int slot)
2715 {
2716         struct btrfs_extent_ref_v0 *ref0;
2717         struct btrfs_key key;
2718
2719         btrfs_item_key_to_cpu(leaf, &key, slot);
2720         ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
2721         if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
2722                 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
2723         } else {
2724                 add_data_backref(extent_cache, key.objectid, key.offset, 0,
2725                                  0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
2726         }
2727         return 0;
2728 }
2729 #endif
2730
2731 static inline unsigned long chunk_record_size(int num_stripes)
2732 {
2733         return sizeof(struct chunk_record) +
2734                sizeof(struct stripe) * num_stripes;
2735 }
2736
2737 static int process_chunk_item(struct cache_tree *chunk_cache,
2738                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
2739 {
2740         struct btrfs_chunk *ptr;
2741         struct chunk_record *rec;
2742         int num_stripes, i;
2743         int ret = 0;
2744
2745         ptr = btrfs_item_ptr(eb,
2746                 slot, struct btrfs_chunk);
2747
2748         num_stripes = btrfs_chunk_num_stripes(eb, ptr);
2749
2750         rec = malloc(chunk_record_size(num_stripes));
2751         if (!rec) {
2752                 fprintf(stderr, "memory allocation failed\n");
2753                 return -ENOMEM;
2754         }
2755
2756         rec->cache.start = key->offset;
2757         rec->cache.size = btrfs_chunk_length(eb, ptr);
2758
2759         rec->objectid = key->objectid;
2760         rec->type = key->type;
2761         rec->offset = key->offset;
2762
2763         rec->length = rec->cache.size;
2764         rec->type_flags = btrfs_chunk_type(eb, ptr);
2765         rec->num_stripes = num_stripes;
2766         rec->sub_stripes = btrfs_chunk_sub_stripes(eb, ptr);
2767
2768         for (i = 0; i < rec->num_stripes; ++i) {
2769                 rec->stripes[i].devid =
2770                         btrfs_stripe_devid_nr(eb, ptr, i);
2771                 rec->stripes[i].offset =
2772                         btrfs_stripe_offset_nr(eb, ptr, i);
2773         }
2774
2775         ret = insert_cache_extent(chunk_cache, &rec->cache);
2776         if (ret) {
2777                 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
2778                         rec->offset, rec->length);
2779                 free(rec);
2780         }
2781
2782         return ret;
2783 }
2784
2785 static int process_device_item(struct rb_root *dev_cache,
2786                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
2787 {
2788         struct btrfs_dev_item *ptr;
2789         struct device_record *rec;
2790         int ret = 0;
2791
2792         ptr = btrfs_item_ptr(eb,
2793                 slot, struct btrfs_dev_item);
2794
2795         rec = malloc(sizeof(*rec));
2796         if (!rec) {
2797                 fprintf(stderr, "memory allocation failed\n");
2798                 return -ENOMEM;
2799         }
2800
2801         rec->devid = key->offset;
2802
2803         rec->objectid = key->objectid;
2804         rec->type = key->type;
2805         rec->offset = key->offset;
2806
2807         rec->devid = btrfs_device_id(eb, ptr);
2808         rec->total_byte = btrfs_device_total_bytes(eb, ptr);
2809         rec->byte_used = btrfs_device_bytes_used(eb, ptr);
2810
2811         ret = rb_insert(dev_cache, &rec->node, device_record_compare);
2812         if (ret) {
2813                 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
2814                 free(rec);
2815         }
2816
2817         return ret;
2818 }
2819
2820 static int process_block_group_item(struct block_group_tree *block_group_cache,
2821                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
2822 {
2823         struct btrfs_block_group_item *ptr;
2824         struct block_group_record *rec;
2825         int ret = 0;
2826
2827         ptr = btrfs_item_ptr(eb, slot,
2828                 struct btrfs_block_group_item);
2829
2830         rec = malloc(sizeof(*rec));
2831         if (!rec) {
2832                 fprintf(stderr, "memory allocation failed\n");
2833                 return -ENOMEM;
2834         }
2835
2836         rec->cache.start = key->objectid;
2837         rec->cache.size = key->offset;
2838
2839         rec->objectid = key->objectid;
2840         rec->type = key->type;
2841         rec->offset = key->offset;
2842         rec->flags = btrfs_disk_block_group_flags(eb, ptr);
2843
2844         ret = insert_block_group_record(block_group_cache, rec);
2845         if (ret) {
2846                 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
2847                         rec->objectid, rec->offset);
2848                 free(rec);
2849         }
2850
2851         return ret;
2852 }
2853
2854 static int
2855 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
2856                            struct btrfs_key *key, struct extent_buffer *eb,
2857                            int slot)
2858 {
2859         int ret = 0;
2860
2861         struct btrfs_dev_extent *ptr;
2862         struct device_extent_record *rec;
2863
2864         ptr = btrfs_item_ptr(eb,
2865                 slot, struct btrfs_dev_extent);
2866
2867         rec = malloc(sizeof(*rec));
2868         if (!rec) {
2869                 fprintf(stderr, "memory allocation failed\n");
2870                 return -ENOMEM;
2871         }
2872
2873         rec->cache.objectid = key->objectid;
2874         rec->cache.start = key->offset;
2875
2876         rec->objectid = key->objectid;
2877         rec->type = key->type;
2878         rec->offset = key->offset;
2879
2880         rec->chunk_objecteid =
2881                 btrfs_dev_extent_chunk_objectid(eb, ptr);
2882         rec->chunk_offset =
2883                 btrfs_dev_extent_chunk_offset(eb, ptr);
2884         rec->length = btrfs_dev_extent_length(eb, ptr);
2885         rec->cache.size = rec->length;
2886
2887         ret = insert_device_extent_record(dev_extent_cache, rec);
2888         if (ret) {
2889                 fprintf(stderr, "Device extent[%llu, %llu, %llu] existed.\n",
2890                         rec->objectid, rec->offset, rec->length);
2891                 free(rec);
2892         }
2893
2894         return ret;
2895 }
2896
2897 static int process_extent_item(struct btrfs_root *root,
2898                                struct cache_tree *extent_cache,
2899                                struct extent_buffer *eb, int slot)
2900 {
2901         struct btrfs_extent_item *ei;
2902         struct btrfs_extent_inline_ref *iref;
2903         struct btrfs_extent_data_ref *dref;
2904         struct btrfs_shared_data_ref *sref;
2905         struct btrfs_key key;
2906         unsigned long end;
2907         unsigned long ptr;
2908         int type;
2909         u32 item_size = btrfs_item_size_nr(eb, slot);
2910         u64 refs = 0;
2911         u64 offset;
2912         u64 num_bytes;
2913         int metadata = 0;
2914
2915         btrfs_item_key_to_cpu(eb, &key, slot);
2916
2917         if (key.type == BTRFS_METADATA_ITEM_KEY) {
2918                 metadata = 1;
2919                 num_bytes = root->leafsize;
2920         } else {
2921                 num_bytes = key.offset;
2922         }
2923
2924         if (item_size < sizeof(*ei)) {
2925 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2926                 struct btrfs_extent_item_v0 *ei0;
2927                 BUG_ON(item_size != sizeof(*ei0));
2928                 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
2929                 refs = btrfs_extent_refs_v0(eb, ei0);
2930 #else
2931                 BUG();
2932 #endif
2933                 return add_extent_rec(extent_cache, NULL, key.objectid,
2934                                       num_bytes, refs, 0, 0, 0, metadata, 1,
2935                                       num_bytes);
2936         }
2937
2938         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
2939         refs = btrfs_extent_refs(eb, ei);
2940
2941         add_extent_rec(extent_cache, NULL, key.objectid, num_bytes,
2942                        refs, 0, 0, 0, metadata, 1, num_bytes);
2943
2944         ptr = (unsigned long)(ei + 1);
2945         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
2946             key.type == BTRFS_EXTENT_ITEM_KEY)
2947                 ptr += sizeof(struct btrfs_tree_block_info);
2948
2949         end = (unsigned long)ei + item_size;
2950         while (ptr < end) {
2951                 iref = (struct btrfs_extent_inline_ref *)ptr;
2952                 type = btrfs_extent_inline_ref_type(eb, iref);
2953                 offset = btrfs_extent_inline_ref_offset(eb, iref);
2954                 switch (type) {
2955                 case BTRFS_TREE_BLOCK_REF_KEY:
2956                         add_tree_backref(extent_cache, key.objectid,
2957                                          0, offset, 0);
2958                         break;
2959                 case BTRFS_SHARED_BLOCK_REF_KEY:
2960                         add_tree_backref(extent_cache, key.objectid,
2961                                          offset, 0, 0);
2962                         break;
2963                 case BTRFS_EXTENT_DATA_REF_KEY:
2964                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
2965                         add_data_backref(extent_cache, key.objectid, 0,
2966                                         btrfs_extent_data_ref_root(eb, dref),
2967                                         btrfs_extent_data_ref_objectid(eb,
2968                                                                        dref),
2969                                         btrfs_extent_data_ref_offset(eb, dref),
2970                                         btrfs_extent_data_ref_count(eb, dref),
2971                                         0, num_bytes);
2972                         break;
2973                 case BTRFS_SHARED_DATA_REF_KEY:
2974                         sref = (struct btrfs_shared_data_ref *)(iref + 1);
2975                         add_data_backref(extent_cache, key.objectid, offset,
2976                                         0, 0, 0,
2977                                         btrfs_shared_data_ref_count(eb, sref),
2978                                         0, num_bytes);
2979                         break;
2980                 default:
2981                         fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
2982                                 key.objectid, key.type, num_bytes);
2983                         goto out;
2984                 }
2985                 ptr += btrfs_extent_inline_ref_size(type);
2986         }
2987         WARN_ON(ptr > end);
2988 out:
2989         return 0;
2990 }
2991
2992 static int check_cache_range(struct btrfs_root *root,
2993                              struct btrfs_block_group_cache *cache,
2994                              u64 offset, u64 bytes)
2995 {
2996         struct btrfs_free_space *entry;
2997         u64 *logical;
2998         u64 bytenr;
2999         int stripe_len;
3000         int i, nr, ret;
3001
3002         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
3003                 bytenr = btrfs_sb_offset(i);
3004                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
3005                                        cache->key.objectid, bytenr, 0,
3006                                        &logical, &nr, &stripe_len);
3007                 if (ret)
3008                         return ret;
3009
3010                 while (nr--) {
3011                         if (logical[nr] + stripe_len <= offset)
3012                                 continue;
3013                         if (offset + bytes <= logical[nr])
3014                                 continue;
3015                         if (logical[nr] == offset) {
3016                                 if (stripe_len >= bytes) {
3017                                         kfree(logical);
3018                                         return 0;
3019                                 }
3020                                 bytes -= stripe_len;
3021                                 offset += stripe_len;
3022                         } else if (logical[nr] < offset) {
3023                                 if (logical[nr] + stripe_len >=
3024                                     offset + bytes) {
3025                                         kfree(logical);
3026                                         return 0;
3027                                 }
3028                                 bytes = (offset + bytes) -
3029                                         (logical[nr] + stripe_len);
3030                                 offset = logical[nr] + stripe_len;
3031                         } else {
3032                                 /*
3033                                  * Could be tricky, the super may land in the
3034                                  * middle of the area we're checking.  First
3035                                  * check the easiest case, it's at the end.
3036                                  */
3037                                 if (logical[nr] + stripe_len >=
3038                                     bytes + offset) {
3039                                         bytes = logical[nr] - offset;
3040                                         continue;
3041                                 }
3042
3043                                 /* Check the left side */
3044                                 ret = check_cache_range(root, cache,
3045                                                         offset,
3046                                                         logical[nr] - offset);
3047                                 if (ret) {
3048                                         kfree(logical);
3049                                         return ret;
3050                                 }
3051
3052                                 /* Now we continue with the right side */
3053                                 bytes = (offset + bytes) -
3054                                         (logical[nr] + stripe_len);
3055                                 offset = logical[nr] + stripe_len;
3056                         }
3057                 }
3058
3059                 kfree(logical);
3060         }
3061
3062         entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
3063         if (!entry) {
3064                 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
3065                         offset, offset+bytes);
3066                 return -EINVAL;
3067         }
3068
3069         if (entry->offset != offset) {
3070                 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
3071                         entry->offset);
3072                 return -EINVAL;
3073         }
3074
3075         if (entry->bytes != bytes) {
3076                 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
3077                         bytes, entry->bytes, offset);
3078                 return -EINVAL;
3079         }
3080
3081         unlink_free_space(cache->free_space_ctl, entry);
3082         free(entry);
3083         return 0;
3084 }
3085
3086 static int verify_space_cache(struct btrfs_root *root,
3087                               struct btrfs_block_group_cache *cache)
3088 {
3089         struct btrfs_path *path;
3090         struct extent_buffer *leaf;
3091         struct btrfs_key key;
3092         u64 last;
3093         int ret = 0;
3094
3095         path = btrfs_alloc_path();
3096         if (!path)
3097                 return -ENOMEM;
3098
3099         root = root->fs_info->extent_root;
3100
3101         last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
3102
3103         key.objectid = last;
3104         key.offset = 0;
3105         key.type = BTRFS_EXTENT_ITEM_KEY;
3106
3107         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3108         if (ret < 0)
3109                 return ret;
3110         ret = 0;
3111         while (1) {
3112                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3113                         ret = btrfs_next_leaf(root, path);
3114                         if (ret < 0)
3115                                 return ret;
3116                         if (ret > 0) {
3117                                 ret = 0;
3118                                 break;
3119                         }
3120                 }
3121                 leaf = path->nodes[0];
3122                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3123                 if (key.objectid >= cache->key.offset + cache->key.objectid)
3124                         break;
3125                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3126                     key.type != BTRFS_METADATA_ITEM_KEY) {
3127                         path->slots[0]++;
3128                         continue;
3129                 }
3130
3131                 if (last == key.objectid) {
3132                         if (key.type == BTRFS_EXTENT_ITEM_KEY)
3133                                 last = key.objectid + key.offset;
3134                         else
3135                                 last = key.objectid + root->leafsize;
3136                         path->slots[0]++;
3137                         continue;
3138                 }
3139
3140                 ret = check_cache_range(root, cache, last,
3141                                         key.objectid - last);
3142                 if (ret)
3143                         break;
3144                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
3145                         last = key.objectid + key.offset;
3146                 else
3147                         last = key.objectid + root->leafsize;
3148                 path->slots[0]++;
3149         }
3150
3151         if (last < cache->key.objectid + cache->key.offset)
3152                 ret = check_cache_range(root, cache, last,
3153                                         cache->key.objectid +
3154                                         cache->key.offset - last);
3155         btrfs_free_path(path);
3156
3157         if (!ret &&
3158             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
3159                 fprintf(stderr, "There are still entries left in the space "
3160                         "cache\n");
3161                 ret = -EINVAL;
3162         }
3163
3164         return ret;
3165 }
3166
3167 static int check_space_cache(struct btrfs_root *root)
3168 {
3169         struct btrfs_block_group_cache *cache;
3170         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
3171         int ret;
3172         int error = 0;
3173
3174         if (btrfs_super_generation(root->fs_info->super_copy) !=
3175             btrfs_super_cache_generation(root->fs_info->super_copy)) {
3176                 printf("cache and super generation don't match, space cache "
3177                        "will be invalidated\n");
3178                 return 0;
3179         }
3180
3181         while (1) {
3182                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
3183                 if (!cache)
3184                         break;
3185
3186                 start = cache->key.objectid + cache->key.offset;
3187                 if (!cache->free_space_ctl) {
3188                         if (btrfs_init_free_space_ctl(cache,
3189                                                       root->sectorsize)) {
3190                                 ret = -ENOMEM;
3191                                 break;
3192                         }
3193                 } else {
3194                         btrfs_remove_free_space_cache(cache);
3195                 }
3196
3197                 ret = load_free_space_cache(root->fs_info, cache);
3198                 if (!ret)
3199                         continue;
3200
3201                 ret = verify_space_cache(root, cache);
3202                 if (ret) {
3203                         fprintf(stderr, "cache appears valid but isnt %Lu\n",
3204                                 cache->key.objectid);
3205                         error++;
3206                 }
3207         }
3208
3209         return error ? -EINVAL : 0;
3210 }
3211
3212 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
3213                                u64 num_bytes)
3214 {
3215         struct btrfs_path *path;
3216         struct extent_buffer *leaf;
3217         struct btrfs_key key;
3218         int ret;
3219
3220         path = btrfs_alloc_path();
3221         if (!path) {
3222                 fprintf(stderr, "Error allocing path\n");
3223                 return -ENOMEM;
3224         }
3225
3226         key.objectid = bytenr;
3227         key.type = BTRFS_EXTENT_ITEM_KEY;
3228         key.offset = 0;
3229
3230
3231 again:
3232         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
3233                                 0, 0);
3234         if (ret < 0) {
3235                 fprintf(stderr, "Error looking up extent record %d\n", ret);
3236                 btrfs_free_path(path);
3237                 return ret;
3238         } else if (ret) {
3239                 if (path->slots[0])
3240                         path->slots[0]--;
3241                 else
3242                         btrfs_prev_leaf(root, path);
3243         }
3244
3245         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3246
3247         /*
3248          * Block group items come before extent items if they have the same
3249          * bytenr, so walk back one more just in case.  Dear future traveler,
3250          * first congrats on mastering time travel.  Now if it's not too much
3251          * trouble could you go back to 2006 and tell Chris to make the
3252          * BLOCK_GROUP_ITEM_KEY lower than the EXTENT_ITEM_KEY please?
3253          */
3254         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
3255                 if (path->slots[0])
3256                         path->slots[0]--;
3257                 else
3258                         btrfs_prev_leaf(root, path);
3259         }
3260
3261         while (num_bytes) {
3262                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3263                         ret = btrfs_next_leaf(root, path);
3264                         if (ret < 0) {
3265                                 fprintf(stderr, "Error going to next leaf "
3266                                         "%d\n", ret);
3267                                 btrfs_free_path(path);
3268                                 return ret;
3269                         } else if (ret) {
3270                                 break;
3271                         }
3272                 }
3273                 leaf = path->nodes[0];
3274                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3275                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
3276                         path->slots[0]++;
3277                         continue;
3278                 }
3279                 if (key.objectid + key.offset < bytenr) {
3280                         path->slots[0]++;
3281                         continue;
3282                 }
3283                 if (key.objectid > bytenr + num_bytes)
3284                         break;
3285
3286                 if (key.objectid == bytenr) {
3287                         if (key.offset >= num_bytes) {
3288                                 num_bytes = 0;
3289                                 break;
3290                         }
3291                         num_bytes -= key.offset;
3292                         bytenr += key.offset;
3293                 } else if (key.objectid < bytenr) {
3294                         if (key.objectid + key.offset >= bytenr + num_bytes) {
3295                                 num_bytes = 0;
3296                                 break;
3297                         }
3298                         num_bytes = (bytenr + num_bytes) -
3299                                 (key.objectid + key.offset);
3300                         bytenr = key.objectid + key.offset;
3301                 } else {
3302                         if (key.objectid + key.offset < bytenr + num_bytes) {
3303                                 u64 new_start = key.objectid + key.offset;
3304                                 u64 new_bytes = bytenr + num_bytes - new_start;
3305
3306                                 /*
3307                                  * Weird case, the extent is in the middle of
3308                                  * our range, we'll have to search one side
3309                                  * and then the other.  Not sure if this happens
3310                                  * in real life, but no harm in coding it up
3311                                  * anyway just in case.
3312                                  */
3313                                 btrfs_release_path(root, path);
3314                                 ret = check_extent_exists(root, new_start,
3315                                                           new_bytes);
3316                                 if (ret) {
3317                                         fprintf(stderr, "Right section didn't "
3318                                                 "have a record\n");
3319                                         break;
3320                                 }
3321                                 num_bytes = key.objectid - bytenr;
3322                                 goto again;
3323                         }
3324                         num_bytes = key.objectid - bytenr;
3325                 }
3326                 path->slots[0]++;
3327         }
3328         ret = 0;
3329
3330         if (num_bytes) {
3331                 fprintf(stderr, "There are no extents for csum range "
3332                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
3333                 ret = 1;
3334         }
3335
3336         btrfs_free_path(path);
3337         return ret;
3338 }
3339
3340 static int check_csums(struct btrfs_root *root)
3341 {
3342         struct btrfs_path *path;
3343         struct extent_buffer *leaf;
3344         struct btrfs_key key;
3345         u64 offset = 0, num_bytes = 0;
3346         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
3347         int errors = 0;
3348         int ret;
3349
3350         root = root->fs_info->csum_root;
3351
3352         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
3353         key.type = BTRFS_EXTENT_CSUM_KEY;
3354         key.offset = 0;
3355
3356         path = btrfs_alloc_path();
3357         if (!path)
3358                 return -ENOMEM;
3359
3360         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3361         if (ret < 0) {
3362                 fprintf(stderr, "Error searching csum tree %d\n", ret);
3363                 btrfs_free_path(path);
3364                 return ret;
3365         }
3366
3367         if (ret > 0 && path->slots[0])
3368                 path->slots[0]--;
3369         ret = 0;
3370
3371         while (1) {
3372                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3373                         ret = btrfs_next_leaf(root, path);
3374                         if (ret < 0) {
3375                                 fprintf(stderr, "Error going to next leaf "
3376                                         "%d\n", ret);
3377                                 break;
3378                         }
3379                         if (ret)
3380                                 break;
3381                 }
3382                 leaf = path->nodes[0];
3383
3384                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3385                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
3386                         path->slots[0]++;
3387                         continue;
3388                 }
3389
3390                 if (!num_bytes) {
3391                         offset = key.offset;
3392                 } else if (key.offset != offset + num_bytes) {
3393                         ret = check_extent_exists(root, offset, num_bytes);
3394                         if (ret) {
3395                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
3396                                         "there is no extent record\n",
3397                                         offset, offset+num_bytes);
3398                                 errors++;
3399                         }
3400                         offset = key.offset;
3401                         num_bytes = 0;
3402                 }
3403
3404                 num_bytes += (btrfs_item_size_nr(leaf, path->slots[0]) /
3405                               csum_size) * root->sectorsize;
3406                 path->slots[0]++;
3407         }
3408
3409         btrfs_free_path(path);
3410         return errors;
3411 }
3412
3413 static int run_next_block(struct btrfs_root *root,
3414                           struct block_info *bits,
3415                           int bits_nr,
3416                           u64 *last,
3417                           struct cache_tree *pending,
3418                           struct cache_tree *seen,
3419                           struct cache_tree *reada,
3420                           struct cache_tree *nodes,
3421                           struct cache_tree *extent_cache,
3422                           struct cache_tree *chunk_cache,
3423                           struct rb_root *dev_cache,
3424                           struct block_group_tree *block_group_cache,
3425                           struct device_extent_tree *dev_extent_cache)
3426 {
3427         struct extent_buffer *buf;
3428         u64 bytenr;
3429         u32 size;
3430         u64 parent;
3431         u64 owner;
3432         u64 flags;
3433         int ret;
3434         int i;
3435         int nritems;
3436         struct btrfs_key key;
3437         struct cache_extent *cache;
3438         int reada_bits;
3439
3440         nritems = pick_next_pending(pending, reada, nodes, *last, bits,
3441                                     bits_nr, &reada_bits);
3442         if (nritems == 0)
3443                 return 1;
3444
3445         if (!reada_bits) {
3446                 for(i = 0; i < nritems; i++) {
3447                         ret = add_cache_extent(reada, bits[i].start,
3448                                                bits[i].size);
3449                         if (ret == -EEXIST)
3450                                 continue;
3451
3452                         /* fixme, get the parent transid */
3453                         readahead_tree_block(root, bits[i].start,
3454                                              bits[i].size, 0);
3455                 }
3456         }
3457         *last = bits[0].start;
3458         bytenr = bits[0].start;
3459         size = bits[0].size;
3460
3461         cache = lookup_cache_extent(pending, bytenr, size);
3462         if (cache) {
3463                 remove_cache_extent(pending, cache);
3464                 free(cache);
3465         }
3466         cache = lookup_cache_extent(reada, bytenr, size);
3467         if (cache) {
3468                 remove_cache_extent(reada, cache);
3469                 free(cache);
3470         }
3471         cache = lookup_cache_extent(nodes, bytenr, size);
3472         if (cache) {
3473                 remove_cache_extent(nodes, cache);
3474                 free(cache);
3475         }
3476
3477         /* fixme, get the real parent transid */
3478         buf = read_tree_block(root, bytenr, size, 0);
3479         if (!extent_buffer_uptodate(buf)) {
3480                 record_bad_block_io(root->fs_info,
3481                                     extent_cache, bytenr, size);
3482                 goto out;
3483         }
3484
3485         nritems = btrfs_header_nritems(buf);
3486
3487         ret = btrfs_lookup_extent_info(NULL, root, bytenr,
3488                                        btrfs_header_level(buf), 1, NULL,
3489                                        &flags);
3490         if (ret < 0)
3491                 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3492
3493         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3494                 parent = bytenr;
3495                 owner = 0;
3496         } else {
3497                 parent = 0;
3498                 owner = btrfs_header_owner(buf);
3499         }
3500
3501         ret = check_block(root, extent_cache, buf, flags);
3502         if (ret)
3503                 goto out;
3504
3505         if (btrfs_is_leaf(buf)) {
3506                 btree_space_waste += btrfs_leaf_free_space(root, buf);
3507                 for (i = 0; i < nritems; i++) {
3508                         struct btrfs_file_extent_item *fi;
3509                         btrfs_item_key_to_cpu(buf, &key, i);
3510                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
3511                                 process_extent_item(root, extent_cache, buf,
3512                                                     i);
3513                                 continue;
3514                         }
3515                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
3516                                 process_extent_item(root, extent_cache, buf,
3517                                                     i);
3518                                 continue;
3519                         }
3520                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
3521                                 total_csum_bytes +=
3522                                         btrfs_item_size_nr(buf, i);
3523                                 continue;
3524                         }
3525                         if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3526                                 process_chunk_item(chunk_cache, &key, buf, i);
3527                                 continue;
3528                         }
3529                         if (key.type == BTRFS_DEV_ITEM_KEY) {
3530                                 process_device_item(dev_cache, &key, buf, i);
3531                                 continue;
3532                         }
3533                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
3534                                 process_block_group_item(block_group_cache,
3535                                         &key, buf, i);
3536                                 continue;
3537                         }
3538                         if (key.type == BTRFS_DEV_EXTENT_KEY) {
3539                                 process_device_extent_item(dev_extent_cache,
3540                                         &key, buf, i);
3541                                 continue;
3542
3543                         }
3544                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
3545 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3546                                 process_extent_ref_v0(extent_cache, buf, i);
3547 #else
3548                                 BUG();
3549 #endif
3550                                 continue;
3551                         }
3552
3553                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
3554                                 add_tree_backref(extent_cache, key.objectid, 0,
3555                                                  key.offset, 0);
3556                                 continue;
3557                         }
3558                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
3559                                 add_tree_backref(extent_cache, key.objectid,
3560                                                  key.offset, 0, 0);
3561                                 continue;
3562                         }
3563                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
3564                                 struct btrfs_extent_data_ref *ref;
3565                                 ref = btrfs_item_ptr(buf, i,
3566                                                 struct btrfs_extent_data_ref);
3567                                 add_data_backref(extent_cache,
3568                                         key.objectid, 0,
3569                                         btrfs_extent_data_ref_root(buf, ref),
3570                                         btrfs_extent_data_ref_objectid(buf,
3571                                                                        ref),
3572                                         btrfs_extent_data_ref_offset(buf, ref),
3573                                         btrfs_extent_data_ref_count(buf, ref),
3574                                         0, root->sectorsize);
3575                                 continue;
3576                         }
3577                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
3578                                 struct btrfs_shared_data_ref *ref;
3579                                 ref = btrfs_item_ptr(buf, i,
3580                                                 struct btrfs_shared_data_ref);
3581                                 add_data_backref(extent_cache,
3582                                         key.objectid, key.offset, 0, 0, 0,
3583                                         btrfs_shared_data_ref_count(buf, ref),
3584                                         0, root->sectorsize);
3585                                 continue;
3586                         }
3587                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3588                                 continue;
3589                         fi = btrfs_item_ptr(buf, i,
3590                                             struct btrfs_file_extent_item);
3591                         if (btrfs_file_extent_type(buf, fi) ==
3592                             BTRFS_FILE_EXTENT_INLINE)
3593                                 continue;
3594                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
3595                                 continue;
3596
3597                         data_bytes_allocated +=
3598                                 btrfs_file_extent_disk_num_bytes(buf, fi);
3599                         if (data_bytes_allocated < root->sectorsize) {
3600                                 abort();
3601                         }
3602                         data_bytes_referenced +=
3603                                 btrfs_file_extent_num_bytes(buf, fi);
3604                         add_data_backref(extent_cache,
3605                                 btrfs_file_extent_disk_bytenr(buf, fi),
3606                                 parent, owner, key.objectid, key.offset -
3607                                 btrfs_file_extent_offset(buf, fi), 1, 1,
3608                                 btrfs_file_extent_disk_num_bytes(buf, fi));
3609                         BUG_ON(ret);
3610                 }
3611         } else {
3612                 int level;
3613                 struct btrfs_key first_key;
3614
3615                 first_key.objectid = 0;
3616
3617                 if (nritems > 0)
3618                         btrfs_item_key_to_cpu(buf, &first_key, 0);
3619                 level = btrfs_header_level(buf);
3620                 for (i = 0; i < nritems; i++) {
3621                         u64 ptr = btrfs_node_blockptr(buf, i);
3622                         u32 size = btrfs_level_size(root, level - 1);
3623                         btrfs_node_key_to_cpu(buf, &key, i);
3624                         ret = add_extent_rec(extent_cache, &key,
3625                                              ptr, size, 0, 0, 1, 0, 1, 0,
3626                                              size);
3627                         BUG_ON(ret);
3628
3629                         add_tree_backref(extent_cache, ptr, parent, owner, 1);
3630
3631                         if (level > 1) {
3632                                 add_pending(nodes, seen, ptr, size);
3633                         } else {
3634                                 add_pending(pending, seen, ptr, size);
3635                         }
3636                 }
3637                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
3638                                       nritems) * sizeof(struct btrfs_key_ptr);
3639         }
3640         total_btree_bytes += buf->len;
3641         if (fs_root_objectid(btrfs_header_owner(buf)))
3642                 total_fs_tree_bytes += buf->len;
3643         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
3644                 total_extent_tree_bytes += buf->len;
3645         if (!found_old_backref &&
3646             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
3647             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
3648             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
3649                 found_old_backref = 1;
3650 out:
3651         free_extent_buffer(buf);
3652         return 0;
3653 }
3654
3655 static int add_root_to_pending(struct extent_buffer *buf,
3656                                struct cache_tree *extent_cache,
3657                                struct cache_tree *pending,
3658                                struct cache_tree *seen,
3659                                struct cache_tree *nodes,
3660                                struct btrfs_key *root_key)
3661 {
3662         if (btrfs_header_level(buf) > 0)
3663                 add_pending(nodes, seen, buf->start, buf->len);
3664         else
3665                 add_pending(pending, seen, buf->start, buf->len);
3666         add_extent_rec(extent_cache, NULL, buf->start, buf->len,
3667                        0, 1, 1, 0, 1, 0, buf->len);
3668
3669         if (root_key->objectid == BTRFS_TREE_RELOC_OBJECTID ||
3670             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3671                 add_tree_backref(extent_cache, buf->start, buf->start,
3672                                  0, 1);
3673         else
3674                 add_tree_backref(extent_cache, buf->start, 0,
3675                                  root_key->objectid, 1);
3676         return 0;
3677 }
3678
3679 /* as we fix the tree, we might be deleting blocks that
3680  * we're tracking for repair.  This hook makes sure we
3681  * remove any backrefs for blocks as we are fixing them.
3682  */
3683 static int free_extent_hook(struct btrfs_trans_handle *trans,
3684                             struct btrfs_root *root,
3685                             u64 bytenr, u64 num_bytes, u64 parent,
3686                             u64 root_objectid, u64 owner, u64 offset,
3687                             int refs_to_drop)
3688 {
3689         struct extent_record *rec;
3690         struct cache_extent *cache;
3691         int is_data;
3692         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
3693
3694         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
3695         cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
3696         if (!cache)
3697                 return 0;
3698
3699         rec = container_of(cache, struct extent_record, cache);
3700         if (is_data) {
3701                 struct data_backref *back;
3702                 back = find_data_backref(rec, parent, root_objectid, owner,
3703                                          offset, 1, bytenr, num_bytes);
3704                 if (!back)
3705                         goto out;
3706                 if (back->node.found_ref) {
3707                         back->found_ref -= refs_to_drop;
3708                         if (rec->refs)
3709                                 rec->refs -= refs_to_drop;
3710                 }
3711                 if (back->node.found_extent_tree) {
3712                         back->num_refs -= refs_to_drop;
3713                         if (rec->extent_item_refs)
3714                                 rec->extent_item_refs -= refs_to_drop;
3715                 }
3716                 if (back->found_ref == 0)
3717                         back->node.found_ref = 0;
3718                 if (back->num_refs == 0)
3719                         back->node.found_extent_tree = 0;
3720
3721                 if (!back->node.found_extent_tree && back->node.found_ref) {
3722                         list_del(&back->node.list);
3723                         free(back);
3724                 }
3725         } else {
3726                 struct tree_backref *back;
3727                 back = find_tree_backref(rec, parent, root_objectid);
3728                 if (!back)
3729                         goto out;
3730                 if (back->node.found_ref) {
3731                         if (rec->refs)
3732                                 rec->refs--;
3733                         back->node.found_ref = 0;
3734                 }
3735                 if (back->node.found_extent_tree) {
3736                         if (rec->extent_item_refs)
3737                                 rec->extent_item_refs--;
3738                         back->node.found_extent_tree = 0;
3739                 }
3740                 if (!back->node.found_extent_tree && back->node.found_ref) {
3741                         list_del(&back->node.list);
3742                         free(back);
3743                 }
3744         }
3745         maybe_free_extent_rec(extent_cache, rec);
3746 out:
3747         return 0;
3748 }
3749
3750 static int delete_extent_records(struct btrfs_trans_handle *trans,
3751                                  struct btrfs_root *root,
3752                                  struct btrfs_path *path,
3753                                  u64 bytenr, u64 new_len)
3754 {
3755         struct btrfs_key key;
3756         struct btrfs_key found_key;
3757         struct extent_buffer *leaf;
3758         int ret;
3759         int slot;
3760
3761
3762         key.objectid = bytenr;
3763         key.type = (u8)-1;
3764         key.offset = (u64)-1;
3765
3766         while(1) {
3767                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
3768                                         &key, path, 0, 1);
3769                 if (ret < 0)
3770                         break;
3771
3772                 if (ret > 0) {
3773                         ret = 0;
3774                         if (path->slots[0] == 0)
3775                                 break;
3776                         path->slots[0]--;
3777                 }
3778                 ret = 0;
3779
3780                 leaf = path->nodes[0];
3781                 slot = path->slots[0];
3782
3783                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3784                 if (found_key.objectid != bytenr)
3785                         break;
3786
3787                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
3788                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
3789                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3790                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
3791                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
3792                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
3793                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
3794                         btrfs_release_path(NULL, path);
3795                         if (found_key.type == 0) {
3796                                 if (found_key.offset == 0)
3797                                         break;
3798                                 key.offset = found_key.offset - 1;
3799                                 key.type = found_key.type;
3800                         }
3801                         key.type = found_key.type - 1;
3802                         key.offset = (u64)-1;
3803                         continue;
3804                 }
3805
3806                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
3807                         found_key.objectid, found_key.type, found_key.offset);
3808
3809                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
3810                 if (ret)
3811                         break;
3812                 btrfs_release_path(NULL, path);
3813
3814                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
3815                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
3816                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
3817                                 found_key.offset : root->leafsize;
3818
3819                         ret = btrfs_update_block_group(trans, root, bytenr,
3820                                                        bytes, 0, 0);
3821                         if (ret)
3822                                 break;
3823                 }
3824         }
3825
3826         btrfs_release_path(NULL, path);
3827         return ret;
3828 }
3829
3830 /*
3831  * for a single backref, this will allocate a new extent
3832  * and add the backref to it.
3833  */
3834 static int record_extent(struct btrfs_trans_handle *trans,
3835                          struct btrfs_fs_info *info,
3836                          struct btrfs_path *path,
3837                          struct extent_record *rec,
3838                          struct extent_backref *back,
3839                          int allocated, u64 flags)
3840 {
3841         int ret;
3842         struct btrfs_root *extent_root = info->extent_root;
3843         struct extent_buffer *leaf;
3844         struct btrfs_key ins_key;
3845         struct btrfs_extent_item *ei;
3846         struct tree_backref *tback;
3847         struct data_backref *dback;
3848         struct btrfs_tree_block_info *bi;
3849
3850         if (!back->is_data)
3851                 rec->max_size = max_t(u64, rec->max_size,
3852                                     info->extent_root->leafsize);
3853
3854         if (!allocated) {
3855                 u32 item_size = sizeof(*ei);
3856
3857                 if (!back->is_data)
3858                         item_size += sizeof(*bi);
3859
3860                 ins_key.objectid = rec->start;
3861                 ins_key.offset = rec->max_size;
3862                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
3863
3864                 ret = btrfs_insert_empty_item(trans, extent_root, path,
3865                                         &ins_key, item_size);
3866                 if (ret)
3867                         goto fail;
3868
3869                 leaf = path->nodes[0];
3870                 ei = btrfs_item_ptr(leaf, path->slots[0],
3871                                     struct btrfs_extent_item);
3872
3873                 btrfs_set_extent_refs(leaf, ei, 0);
3874                 btrfs_set_extent_generation(leaf, ei, rec->generation);
3875
3876                 if (back->is_data) {
3877                         btrfs_set_extent_flags(leaf, ei,
3878                                                BTRFS_EXTENT_FLAG_DATA);
3879                 } else {
3880                         struct btrfs_disk_key copy_key;;
3881
3882                         tback = (struct tree_backref *)back;
3883                         bi = (struct btrfs_tree_block_info *)(ei + 1);
3884                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
3885                                              sizeof(*bi));
3886                         memset(&copy_key, 0, sizeof(copy_key));
3887
3888                         copy_key.objectid = le64_to_cpu(rec->info_objectid);
3889                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
3890                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
3891
3892                         btrfs_set_extent_flags(leaf, ei,
3893                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
3894                 }
3895
3896                 btrfs_mark_buffer_dirty(leaf);
3897                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
3898                                                rec->max_size, 1, 0);
3899                 if (ret)
3900                         goto fail;
3901                 btrfs_release_path(NULL, path);
3902         }
3903
3904         if (back->is_data) {
3905                 u64 parent;
3906                 int i;
3907
3908                 dback = (struct data_backref *)back;
3909                 if (back->full_backref)
3910                         parent = dback->parent;
3911                 else
3912                         parent = 0;
3913
3914                 for (i = 0; i < dback->found_ref; i++) {
3915                         /* if parent != 0, we're doing a full backref
3916                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
3917                          * just makes the backref allocator create a data
3918                          * backref
3919                          */
3920                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
3921                                                    rec->start, rec->max_size,
3922                                                    parent,
3923                                                    dback->root,
3924                                                    parent ?
3925                                                    BTRFS_FIRST_FREE_OBJECTID :
3926                                                    dback->owner,
3927                                                    dback->offset);
3928                         if (ret)
3929                                 break;
3930                 }
3931                 fprintf(stderr, "adding new data backref"
3932                                 " on %llu %s %llu owner %llu"
3933                                 " offset %llu found %d\n",
3934                                 (unsigned long long)rec->start,
3935                                 back->full_backref ?
3936                                 "parent" : "root",
3937                                 back->full_backref ?
3938                                 (unsigned long long)parent :
3939                                 (unsigned long long)dback->root,
3940                                 (unsigned long long)dback->owner,
3941                                 (unsigned long long)dback->offset,
3942                                 dback->found_ref);
3943         } else {
3944                 u64 parent;
3945
3946                 tback = (struct tree_backref *)back;
3947                 if (back->full_backref)
3948                         parent = tback->parent;
3949                 else
3950                         parent = 0;
3951
3952                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
3953                                            rec->start, rec->max_size,
3954                                            parent, tback->root, 0, 0);
3955                 fprintf(stderr, "adding new tree backref on "
3956                         "start %llu len %llu parent %llu root %llu\n",
3957                         rec->start, rec->max_size, tback->parent, tback->root);
3958         }
3959         if (ret)
3960                 goto fail;
3961 fail:
3962         btrfs_release_path(NULL, path);
3963         return ret;
3964 }
3965
3966 struct extent_entry {
3967         u64 bytenr;
3968         u64 bytes;
3969         int count;
3970         struct list_head list;
3971 };
3972
3973 static struct extent_entry *find_entry(struct list_head *entries,
3974                                        u64 bytenr, u64 bytes)
3975 {
3976         struct extent_entry *entry = NULL;
3977
3978         list_for_each_entry(entry, entries, list) {
3979                 if (entry->bytenr == bytenr && entry->bytes == bytes)
3980                         return entry;
3981         }
3982
3983         return NULL;
3984 }
3985
3986 static struct extent_entry *find_most_right_entry(struct list_head *entries)
3987 {
3988         struct extent_entry *entry, *best = NULL, *prev = NULL;
3989
3990         list_for_each_entry(entry, entries, list) {
3991                 if (!prev) {
3992                         prev = entry;
3993                         continue;
3994                 }
3995
3996                 /*
3997                  * If our current entry == best then we can't be sure our best
3998                  * is really the best, so we need to keep searching.
3999                  */
4000                 if (best && best->count == entry->count) {
4001                         prev = entry;
4002                         best = NULL;
4003                         continue;
4004                 }
4005
4006                 /* Prev == entry, not good enough, have to keep searching */
4007                 if (prev->count == entry->count)
4008                         continue;
4009
4010                 if (!best)
4011                         best = (prev->count > entry->count) ? prev : entry;
4012                 else if (best->count < entry->count)
4013                         best = entry;
4014                 prev = entry;
4015         }
4016
4017         return best;
4018 }
4019
4020 static int repair_ref(struct btrfs_trans_handle *trans,
4021                       struct btrfs_fs_info *info, struct btrfs_path *path,
4022                       struct data_backref *dback, struct extent_entry *entry)
4023 {
4024         struct btrfs_root *root;
4025         struct btrfs_file_extent_item *fi;
4026         struct extent_buffer *leaf;
4027         struct btrfs_key key;
4028         u64 bytenr, bytes;
4029         int ret;
4030
4031         key.objectid = dback->root;
4032         key.type = BTRFS_ROOT_ITEM_KEY;
4033         key.offset = (u64)-1;
4034         root = btrfs_read_fs_root(info, &key);
4035         if (IS_ERR(root)) {
4036                 fprintf(stderr, "Couldn't find root for our ref\n");
4037                 return -EINVAL;
4038         }
4039
4040         /*
4041          * The backref points to the original offset of the extent if it was
4042          * split, so we need to search down to the offset we have and then walk
4043          * forward until we find the backref we're looking for.
4044          */
4045         key.objectid = dback->owner;
4046         key.type = BTRFS_EXTENT_DATA_KEY;
4047         key.offset = dback->offset;
4048         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4049         if (ret < 0) {
4050                 fprintf(stderr, "Error looking up ref %d\n", ret);
4051                 return ret;
4052         }
4053
4054         while (1) {
4055                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4056                         ret = btrfs_next_leaf(root, path);
4057                         if (ret) {
4058                                 fprintf(stderr, "Couldn't find our ref, next\n");
4059                                 return -EINVAL;
4060                         }
4061                 }
4062                 leaf = path->nodes[0];
4063                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4064                 if (key.objectid != dback->owner ||
4065                     key.type != BTRFS_EXTENT_DATA_KEY) {
4066                         fprintf(stderr, "Couldn't find our ref, search\n");
4067                         return -EINVAL;
4068                 }
4069                 fi = btrfs_item_ptr(leaf, path->slots[0],
4070                                     struct btrfs_file_extent_item);
4071                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
4072                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
4073
4074                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
4075                         break;
4076                 path->slots[0]++;
4077         }
4078
4079         btrfs_release_path(root, path);
4080
4081         /*
4082          * Have to make sure that this root gets updated when we commit the
4083          * transaction
4084          */
4085         root->track_dirty = 1;
4086         if (root->last_trans != trans->transid) {
4087                 root->last_trans = trans->transid;
4088                 root->commit_root = root->node;
4089                 extent_buffer_get(root->node);
4090         }
4091
4092         /*
4093          * Ok we have the key of the file extent we want to fix, now we can cow
4094          * down to the thing and fix it.
4095          */
4096         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4097         if (ret < 0) {
4098                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
4099                         key.objectid, key.type, key.offset, ret);
4100                 return ret;
4101         }
4102         if (ret > 0) {
4103                 fprintf(stderr, "Well that's odd, we just found this key "
4104                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
4105                         key.offset);
4106                 return -EINVAL;
4107         }
4108         leaf = path->nodes[0];
4109         fi = btrfs_item_ptr(leaf, path->slots[0],
4110                             struct btrfs_file_extent_item);
4111
4112         if (btrfs_file_extent_compression(leaf, fi) &&
4113             dback->disk_bytenr != entry->bytenr) {
4114                 fprintf(stderr, "Ref doesn't match the record start and is "
4115                         "compressed, please take a btrfs-image of this file "
4116                         "system and send it to a btrfs developer so they can "
4117                         "complete this functionality for bytenr %Lu\n",
4118                         dback->disk_bytenr);
4119                 return -EINVAL;
4120         }
4121
4122         if (dback->disk_bytenr > entry->bytenr) {
4123                 u64 off_diff, offset;
4124
4125                 off_diff = dback->disk_bytenr - entry->bytenr;
4126                 offset = btrfs_file_extent_offset(leaf, fi);
4127                 if (dback->disk_bytenr + offset +
4128                     btrfs_file_extent_num_bytes(leaf, fi) >
4129                     entry->bytenr + entry->bytes) {
4130                         fprintf(stderr, "Ref is past the entry end, please "
4131                                 "take a btrfs-image of this file system and "
4132                                 "send it to a btrfs developer, ref %Lu\n",
4133                                 dback->disk_bytenr);
4134                         return -EINVAL;
4135                 }
4136                 offset += off_diff;
4137                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4138                 btrfs_set_file_extent_offset(leaf, fi, offset);
4139         } else if (dback->disk_bytenr < entry->bytenr) {
4140                 u64 offset;
4141
4142                 offset = btrfs_file_extent_offset(leaf, fi);
4143                 if (dback->disk_bytenr + offset < entry->bytenr) {
4144                         fprintf(stderr, "Ref is before the entry start, please"
4145                                 " take a btrfs-image of this file system and "
4146                                 "send it to a btrfs developer, ref %Lu\n",
4147                                 dback->disk_bytenr);
4148                         return -EINVAL;
4149                 }
4150
4151                 offset += dback->disk_bytenr;
4152                 offset -= entry->bytenr;
4153                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4154                 btrfs_set_file_extent_offset(leaf, fi, offset);
4155         }
4156
4157         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
4158
4159         /*
4160          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
4161          * only do this if we aren't using compression, otherwise it's a
4162          * trickier case.
4163          */
4164         if (!btrfs_file_extent_compression(leaf, fi))
4165                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
4166         else
4167                 printf("ram bytes may be wrong?\n");
4168         btrfs_mark_buffer_dirty(leaf);
4169         btrfs_release_path(root, path);
4170         return 0;
4171 }
4172
4173 static int verify_backrefs(struct btrfs_trans_handle *trans,
4174                            struct btrfs_fs_info *info, struct btrfs_path *path,
4175                            struct extent_record *rec)
4176 {
4177         struct extent_backref *back;
4178         struct data_backref *dback;
4179         struct extent_entry *entry, *best = NULL;
4180         LIST_HEAD(entries);
4181         int nr_entries = 0;
4182         int ret = 0;
4183
4184         /*
4185          * Metadata is easy and the backrefs should always agree on bytenr and
4186          * size, if not we've got bigger issues.
4187          */
4188         if (rec->metadata)
4189                 return 0;
4190
4191         list_for_each_entry(back, &rec->backrefs, list) {
4192                 dback = (struct data_backref *)back;
4193                 /*
4194                  * We only pay attention to backrefs that we found a real
4195                  * backref for.
4196                  */
4197                 if (dback->found_ref == 0)
4198                         continue;
4199                 if (back->full_backref)
4200                         continue;
4201
4202                 /*
4203                  * For now we only catch when the bytes don't match, not the
4204                  * bytenr.  We can easily do this at the same time, but I want
4205                  * to have a fs image to test on before we just add repair
4206                  * functionality willy-nilly so we know we won't screw up the
4207                  * repair.
4208                  */
4209
4210                 entry = find_entry(&entries, dback->disk_bytenr,
4211                                    dback->bytes);
4212                 if (!entry) {
4213                         entry = malloc(sizeof(struct extent_entry));
4214                         if (!entry) {
4215                                 ret = -ENOMEM;
4216                                 goto out;
4217                         }
4218                         memset(entry, 0, sizeof(*entry));
4219                         entry->bytenr = dback->disk_bytenr;
4220                         entry->bytes = dback->bytes;
4221                         list_add_tail(&entry->list, &entries);
4222                         nr_entries++;
4223                 }
4224                 entry->count++;
4225         }
4226
4227         /* Yay all the backrefs agree, carry on good sir */
4228         if (nr_entries <= 1)
4229                 goto out;
4230
4231         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
4232                 "%Lu\n", rec->start);
4233
4234         /*
4235          * First we want to see if the backrefs can agree amongst themselves who
4236          * is right, so figure out which one of the entries has the highest
4237          * count.
4238          */
4239         best = find_most_right_entry(&entries);
4240
4241         /*
4242          * Ok so we may have an even split between what the backrefs think, so
4243          * this is where we use the extent ref to see what it thinks.
4244          */
4245         if (!best) {
4246                 entry = find_entry(&entries, rec->start, rec->nr);
4247                 if (!entry) {
4248                         fprintf(stderr, "Backrefs don't agree with eachother "
4249                                 "and extent record doesn't agree with anybody,"
4250                                 " so we can't fix bytenr %Lu bytes %Lu\n",
4251                                 rec->start, rec->nr);
4252                         ret = -EINVAL;
4253                         goto out;
4254                 }
4255                 entry->count++;
4256                 best = find_most_right_entry(&entries);
4257                 if (!best) {
4258                         fprintf(stderr, "Backrefs and extent record evenly "
4259                                 "split on who is right, this is going to "
4260                                 "require user input to fix bytenr %Lu bytes "
4261                                 "%Lu\n", rec->start, rec->nr);
4262                         ret = -EINVAL;
4263                         goto out;
4264                 }
4265         }
4266
4267         /*
4268          * I don't think this can happen currently as we'll abort() if we catch
4269          * this case higher up, but in case somebody removes that we still can't
4270          * deal with it properly here yet, so just bail out of that's the case.
4271          */
4272         if (best->bytenr != rec->start) {
4273                 fprintf(stderr, "Extent start and backref starts don't match, "
4274                         "please use btrfs-image on this file system and send "
4275                         "it to a btrfs developer so they can make fsck fix "
4276                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
4277                         rec->start, rec->nr);
4278                 ret = -EINVAL;
4279                 goto out;
4280         }
4281
4282         /*
4283          * Ok great we all agreed on an extent record, let's go find the real
4284          * references and fix up the ones that don't match.
4285          */
4286         list_for_each_entry(back, &rec->backrefs, list) {
4287                 dback = (struct data_backref *)back;
4288
4289                 /*
4290                  * Still ignoring backrefs that don't have a real ref attached
4291                  * to them.
4292                  */
4293                 if (dback->found_ref == 0)
4294                         continue;
4295                 if (back->full_backref)
4296                         continue;
4297
4298                 if (dback->bytes == best->bytes &&
4299                     dback->disk_bytenr == best->bytenr)
4300                         continue;
4301
4302                 ret = repair_ref(trans, info, path, dback, best);
4303                 if (ret)
4304                         goto out;
4305         }
4306
4307         /*
4308          * Ok we messed with the actual refs, which means we need to drop our
4309          * entire cache and go back and rescan.  I know this is a huge pain and
4310          * adds a lot of extra work, but it's the only way to be safe.  Once all
4311          * the backrefs agree we may not need to do anything to the extent
4312          * record itself.
4313          */
4314         ret = -EAGAIN;
4315 out:
4316         while (!list_empty(&entries)) {
4317                 entry = list_entry(entries.next, struct extent_entry, list);
4318                 list_del_init(&entry->list);
4319                 free(entry);
4320         }
4321         return ret;
4322 }
4323
4324 static int process_duplicates(struct btrfs_root *root,
4325                               struct cache_tree *extent_cache,
4326                               struct extent_record *rec)
4327 {
4328         struct extent_record *good, *tmp;
4329         struct cache_extent *cache;
4330         int ret;
4331
4332         /*
4333          * If we found a extent record for this extent then return, or if we
4334          * have more than one duplicate we are likely going to need to delete
4335          * something.
4336          */
4337         if (rec->found_rec || rec->num_duplicates > 1)
4338                 return 0;
4339
4340         /* Shouldn't happen but just in case */
4341         BUG_ON(!rec->num_duplicates);
4342
4343         /*
4344          * So this happens if we end up with a backref that doesn't match the
4345          * actual extent entry.  So either the backref is bad or the extent
4346          * entry is bad.  Either way we want to have the extent_record actually
4347          * reflect what we found in the extent_tree, so we need to take the
4348          * duplicate out and use that as the extent_record since the only way we
4349          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
4350          */
4351         remove_cache_extent(extent_cache, &rec->cache);
4352
4353         good = list_entry(rec->dups.next, struct extent_record, list);
4354         list_del_init(&good->list);
4355         INIT_LIST_HEAD(&good->backrefs);
4356         INIT_LIST_HEAD(&good->dups);
4357         good->cache.start = good->start;
4358         good->cache.size = good->nr;
4359         good->content_checked = 0;
4360         good->owner_ref_checked = 0;
4361         good->num_duplicates = 0;
4362         good->refs = rec->refs;
4363         list_splice_init(&rec->backrefs, &good->backrefs);
4364         while (1) {
4365                 cache = lookup_cache_extent(extent_cache, good->start,
4366                                             good->nr);
4367                 if (!cache)
4368                         break;
4369                 tmp = container_of(cache, struct extent_record, cache);
4370
4371                 /*
4372                  * If we find another overlapping extent and it's found_rec is
4373                  * set then it's a duplicate and we need to try and delete
4374                  * something.
4375                  */
4376                 if (tmp->found_rec || tmp->num_duplicates > 0) {
4377                         if (list_empty(&good->list))
4378                                 list_add_tail(&good->list,
4379                                               &duplicate_extents);
4380                         good->num_duplicates += tmp->num_duplicates + 1;
4381                         list_splice_init(&tmp->dups, &good->dups);
4382                         list_del_init(&tmp->list);
4383                         list_add_tail(&tmp->list, &good->dups);
4384                         remove_cache_extent(extent_cache, &tmp->cache);
4385                         continue;
4386                 }
4387
4388                 /*
4389                  * Ok we have another non extent item backed extent rec, so lets
4390                  * just add it to this extent and carry on like we did above.
4391                  */
4392                 good->refs += tmp->refs;
4393                 list_splice_init(&tmp->backrefs, &good->backrefs);
4394                 remove_cache_extent(extent_cache, &tmp->cache);
4395                 free(tmp);
4396         }
4397         ret = insert_cache_extent(extent_cache, &good->cache);
4398         BUG_ON(ret);
4399         free(rec);
4400         return good->num_duplicates ? 0 : 1;
4401 }
4402
4403 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
4404                                     struct btrfs_root *root,
4405                                     struct extent_record *rec)
4406 {
4407         LIST_HEAD(delete_list);
4408         struct btrfs_path *path;
4409         struct extent_record *tmp, *good, *n;
4410         int nr_del = 0;
4411         int ret = 0;
4412         struct btrfs_key key;
4413
4414         path = btrfs_alloc_path();
4415         if (!path) {
4416                 ret = -ENOMEM;
4417                 goto out;
4418         }
4419
4420         good = rec;
4421         /* Find the record that covers all of the duplicates. */
4422         list_for_each_entry(tmp, &rec->dups, list) {
4423                 if (good->start < tmp->start)
4424                         continue;
4425                 if (good->nr > tmp->nr)
4426                         continue;
4427
4428                 if (tmp->start + tmp->nr < good->start + good->nr) {
4429                         fprintf(stderr, "Ok we have overlapping extents that "
4430                                 "aren't completely covered by eachother, this "
4431                                 "is going to require more careful thought.  "
4432                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
4433                                 tmp->start, tmp->nr, good->start, good->nr);
4434                         abort();
4435                 }
4436                 good = tmp;
4437         }
4438
4439         if (good != rec)
4440                 list_add_tail(&rec->list, &delete_list);
4441
4442         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
4443                 if (tmp == good)
4444                         continue;
4445                 list_move_tail(&tmp->list, &delete_list);
4446         }
4447
4448         root = root->fs_info->extent_root;
4449         list_for_each_entry(tmp, &delete_list, list) {
4450                 if (tmp->found_rec == 0)
4451                         continue;
4452                 key.objectid = tmp->start;
4453                 key.type = BTRFS_EXTENT_ITEM_KEY;
4454                 key.offset = tmp->nr;
4455
4456                 /* Shouldn't happen but just in case */
4457                 if (tmp->metadata) {
4458                         fprintf(stderr, "Well this shouldn't happen, extent "
4459                                 "record overlaps but is metadata? "
4460                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
4461                         abort();
4462                 }
4463
4464                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4465                 if (ret) {
4466                         if (ret > 0)
4467                                 ret = -EINVAL;
4468                         goto out;
4469                 }
4470                 ret = btrfs_del_item(trans, root, path);
4471                 if (ret)
4472                         goto out;
4473                 btrfs_release_path(root, path);
4474                 nr_del++;
4475         }
4476
4477 out:
4478         while (!list_empty(&delete_list)) {
4479                 tmp = list_entry(delete_list.next, struct extent_record, list);
4480                 list_del_init(&tmp->list);
4481                 if (tmp == rec)
4482                         continue;
4483                 free(tmp);
4484         }
4485
4486         while (!list_empty(&rec->dups)) {
4487                 tmp = list_entry(rec->dups.next, struct extent_record, list);
4488                 list_del_init(&tmp->list);
4489                 free(tmp);
4490         }
4491
4492         btrfs_free_path(path);
4493
4494         if (!ret && !nr_del)
4495                 rec->num_duplicates = 0;
4496
4497         return ret ? ret : nr_del;
4498 }
4499
4500 /*
4501  * when an incorrect extent item is found, this will delete
4502  * all of the existing entries for it and recreate them
4503  * based on what the tree scan found.
4504  */
4505 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
4506                              struct btrfs_fs_info *info,
4507                              struct extent_record *rec)
4508 {
4509         int ret;
4510         struct btrfs_path *path;
4511         struct list_head *cur = rec->backrefs.next;
4512         struct cache_extent *cache;
4513         struct extent_backref *back;
4514         int allocated = 0;
4515         u64 flags = 0;
4516
4517         /* remember our flags for recreating the extent */
4518         ret = btrfs_lookup_extent_info(NULL, info->extent_root, rec->start,
4519                                        rec->max_size, rec->metadata, NULL,
4520                                        &flags);
4521         if (ret < 0)
4522                 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4523
4524         path = btrfs_alloc_path();
4525
4526         /* step one, make sure all of the backrefs agree */
4527         ret = verify_backrefs(trans, info, path, rec);
4528         if (ret < 0)
4529                 goto out;
4530
4531         /* step two, delete all the existing records */
4532         ret = delete_extent_records(trans, info->extent_root, path,
4533                                     rec->start, rec->max_size);
4534
4535         if (ret < 0)
4536                 goto out;
4537
4538         /* was this block corrupt?  If so, don't add references to it */
4539         cache = lookup_cache_extent(info->corrupt_blocks,
4540                                     rec->start, rec->max_size);
4541         if (cache) {
4542                 ret = 0;
4543                 goto out;
4544         }
4545
4546         /* step three, recreate all the refs we did find */
4547         while(cur != &rec->backrefs) {
4548                 back = list_entry(cur, struct extent_backref, list);
4549                 cur = cur->next;
4550
4551                 /*
4552                  * if we didn't find any references, don't create a
4553                  * new extent record
4554                  */
4555                 if (!back->found_ref)
4556                         continue;
4557
4558                 ret = record_extent(trans, info, path, rec, back, allocated, flags);
4559                 allocated = 1;
4560
4561                 if (ret)
4562                         goto out;
4563         }
4564 out:
4565         btrfs_free_path(path);
4566         return ret;
4567 }
4568
4569 /* right now we only prune from the extent allocation tree */
4570 static int prune_one_block(struct btrfs_trans_handle *trans,
4571                            struct btrfs_fs_info *info,
4572                            struct btrfs_corrupt_block *corrupt)
4573 {
4574         int ret;
4575         struct btrfs_path path;
4576         struct extent_buffer *eb;
4577         u64 found;
4578         int slot;
4579         int nritems;
4580         int level = corrupt->level + 1;
4581
4582         btrfs_init_path(&path);
4583 again:
4584         /* we want to stop at the parent to our busted block */
4585         path.lowest_level = level;
4586
4587         ret = btrfs_search_slot(trans, info->extent_root,
4588                                 &corrupt->key, &path, -1, 1);
4589
4590         if (ret < 0)
4591                 goto out;
4592
4593         eb = path.nodes[level];
4594         if (!eb) {
4595                 ret = -ENOENT;
4596                 goto out;
4597         }
4598
4599         /*
4600          * hopefully the search gave us the block we want to prune,
4601          * lets try that first
4602          */
4603         slot = path.slots[level];
4604         found =  btrfs_node_blockptr(eb, slot);
4605         if (found == corrupt->cache.start)
4606                 goto del_ptr;
4607
4608         nritems = btrfs_header_nritems(eb);
4609
4610         /* the search failed, lets scan this node and hope we find it */
4611         for (slot = 0; slot < nritems; slot++) {
4612                 found =  btrfs_node_blockptr(eb, slot);
4613                 if (found == corrupt->cache.start)
4614                         goto del_ptr;
4615         }
4616         /*
4617          * we couldn't find the bad block.  TODO, search all the nodes for pointers
4618          * to this block
4619          */
4620         if (eb == info->extent_root->node) {
4621                 ret = -ENOENT;
4622                 goto out;
4623         } else {
4624                 level++;
4625                 btrfs_release_path(NULL, &path);
4626                 goto again;
4627         }
4628
4629 del_ptr:
4630         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
4631         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
4632
4633 out:
4634         btrfs_release_path(NULL, &path);
4635         return ret;
4636 }
4637
4638 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
4639                                 struct btrfs_fs_info *info)
4640 {
4641         struct cache_extent *cache;
4642         struct btrfs_corrupt_block *corrupt;
4643
4644         cache = search_cache_extent(info->corrupt_blocks, 0);
4645         while (1) {
4646                 if (!cache)
4647                         break;
4648                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
4649                 prune_one_block(trans, info, corrupt);
4650                 cache = next_cache_extent(cache);
4651         }
4652         return 0;
4653 }
4654
4655 static void free_corrupt_block(struct cache_extent *cache)
4656 {
4657         struct btrfs_corrupt_block *corrupt;
4658
4659         corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
4660         free(corrupt);
4661 }
4662
4663 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
4664
4665 static int check_block_group(struct btrfs_trans_handle *trans,
4666                               struct btrfs_fs_info *info,
4667                               struct map_lookup *map,
4668                               int *reinit)
4669 {
4670         struct btrfs_key key;
4671         struct btrfs_path path;
4672         int ret;
4673
4674         key.objectid = map->ce.start;
4675         key.offset = map->ce.size;
4676         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
4677
4678         btrfs_init_path(&path);
4679         ret = btrfs_search_slot(NULL, info->extent_root,
4680                                 &key, &path, 0, 0);
4681         btrfs_release_path(NULL, &path);
4682         if (ret <= 0)
4683                 goto out;
4684
4685         ret = btrfs_make_block_group(trans, info->extent_root, 0, map->type,
4686                                BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4687                                key.objectid, key.offset);
4688         *reinit = 1;
4689 out:
4690         return ret;
4691 }
4692
4693 static int check_block_groups(struct btrfs_trans_handle *trans,
4694                               struct btrfs_fs_info *info, int *reinit)
4695 {
4696         struct cache_extent *ce;
4697         struct map_lookup *map;
4698         struct btrfs_mapping_tree *map_tree = &info->mapping_tree;
4699
4700         /* this isn't quite working */
4701         return 0;
4702
4703         ce = search_cache_extent(&map_tree->cache_tree, 0);
4704         while (1) {
4705                 if (!ce)
4706                         break;
4707                 map = container_of(ce, struct map_lookup, ce);
4708                 check_block_group(trans, info, map, reinit);
4709                 ce = next_cache_extent(ce);
4710         }
4711         return 0;
4712 }
4713
4714 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
4715 {
4716         struct btrfs_block_group_cache *cache;
4717         u64 start, end;
4718         int ret;
4719
4720         while (1) {
4721                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
4722                                             &start, &end, EXTENT_DIRTY);
4723                 if (ret)
4724                         break;
4725                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
4726                                    GFP_NOFS);
4727         }
4728
4729         start = 0;
4730         while (1) {
4731                 cache = btrfs_lookup_first_block_group(fs_info, start);
4732                 if (!cache)
4733                         break;
4734                 if (cache->cached)
4735                         cache->cached = 0;
4736                 start = cache->key.objectid + cache->key.offset;
4737         }
4738 }
4739
4740 static int check_extent_refs(struct btrfs_trans_handle *trans,
4741                              struct btrfs_root *root,
4742                              struct cache_tree *extent_cache, int repair)
4743 {
4744         struct extent_record *rec;
4745         struct cache_extent *cache;
4746         int err = 0;
4747         int ret = 0;
4748         int fixed = 0;
4749         int reinit = 0;
4750         int had_dups = 0;
4751
4752         if (repair) {
4753                 /*
4754                  * if we're doing a repair, we have to make sure
4755                  * we don't allocate from the problem extents.
4756                  * In the worst case, this will be all the
4757                  * extents in the FS
4758                  */
4759                 cache = search_cache_extent(extent_cache, 0);
4760                 while(cache) {
4761                         rec = container_of(cache, struct extent_record, cache);
4762                         btrfs_pin_extent(root->fs_info,
4763                                          rec->start, rec->max_size);
4764                         cache = next_cache_extent(cache);
4765                 }
4766
4767                 /* pin down all the corrupted blocks too */
4768                 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
4769                 while(cache) {
4770                         rec = container_of(cache, struct extent_record, cache);
4771                         btrfs_pin_extent(root->fs_info,
4772                                          rec->start, rec->max_size);
4773                         cache = next_cache_extent(cache);
4774                 }
4775                 prune_corrupt_blocks(trans, root->fs_info);
4776                 check_block_groups(trans, root->fs_info, &reinit);
4777                 if (reinit)
4778                         btrfs_read_block_groups(root->fs_info->extent_root);
4779                 reset_cached_block_groups(root->fs_info);
4780         }
4781
4782         /*
4783          * We need to delete any duplicate entries we find first otherwise we
4784          * could mess up the extent tree when we have backrefs that actually
4785          * belong to a different extent item and not the weird duplicate one.
4786          */
4787         while (repair && !list_empty(&duplicate_extents)) {
4788                 rec = list_entry(duplicate_extents.next, struct extent_record,
4789                                  list);
4790                 list_del_init(&rec->list);
4791
4792                 /* Sometimes we can find a backref before we find an actual
4793                  * extent, so we need to process it a little bit to see if there
4794                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
4795                  * if this is a backref screwup.  If we need to delete stuff
4796                  * process_duplicates() will return 0, otherwise it will return
4797                  * 1 and we
4798                  */
4799                 if (process_duplicates(root, extent_cache, rec))
4800                         continue;
4801                 ret = delete_duplicate_records(trans, root, rec);
4802                 if (ret < 0)
4803                         return ret;
4804                 /*
4805                  * delete_duplicate_records will return the number of entries
4806                  * deleted, so if it's greater than 0 then we know we actually
4807                  * did something and we need to remove.
4808                  */
4809                 if (ret)
4810                         had_dups = 1;
4811         }
4812
4813         if (had_dups)
4814                 return -EAGAIN;
4815
4816         while(1) {
4817                 fixed = 0;
4818                 cache = search_cache_extent(extent_cache, 0);
4819                 if (!cache)
4820                         break;
4821                 rec = container_of(cache, struct extent_record, cache);
4822                 if (rec->num_duplicates) {
4823                         fprintf(stderr, "extent item %llu has multiple extent "
4824                                 "items\n", (unsigned long long)rec->start);
4825                         err = 1;
4826                 }
4827
4828                 if (rec->refs != rec->extent_item_refs) {
4829                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
4830                                 (unsigned long long)rec->start,
4831                                 (unsigned long long)rec->nr);
4832                         fprintf(stderr, "extent item %llu, found %llu\n",
4833                                 (unsigned long long)rec->extent_item_refs,
4834                                 (unsigned long long)rec->refs);
4835                         if (!fixed && repair) {
4836                                 ret = fixup_extent_refs(trans, root->fs_info, rec);
4837                                 if (ret)
4838                                         goto repair_abort;
4839                                 fixed = 1;
4840                         }
4841                         err = 1;
4842
4843                 }
4844                 if (all_backpointers_checked(rec, 1)) {
4845                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
4846                                 (unsigned long long)rec->start,
4847                                 (unsigned long long)rec->nr);
4848
4849                         if (!fixed && repair) {
4850                                 ret = fixup_extent_refs(trans, root->fs_info, rec);
4851                                 if (ret)
4852                                         goto repair_abort;
4853                                 fixed = 1;
4854                         }
4855
4856                         err = 1;
4857                 }
4858                 if (!rec->owner_ref_checked) {
4859                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
4860                                 (unsigned long long)rec->start,
4861                                 (unsigned long long)rec->nr);
4862                         if (!fixed && repair) {
4863                                 ret = fixup_extent_refs(trans, root->fs_info, rec);
4864                                 if (ret)
4865                                         goto repair_abort;
4866                                 fixed = 1;
4867                         }
4868                         err = 1;
4869                 }
4870
4871                 remove_cache_extent(extent_cache, cache);
4872                 free_all_extent_backrefs(rec);
4873                 free(rec);
4874         }
4875 repair_abort:
4876         if (repair) {
4877                 if (ret && ret != -EAGAIN) {
4878                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
4879                         exit(1);
4880                 } else if (!ret) {
4881                         btrfs_fix_block_accounting(trans, root);
4882                 }
4883                 if (err)
4884                         fprintf(stderr, "repaired damaged extent references\n");
4885                 return ret;
4886         }
4887         return err;
4888 }
4889
4890 static u64 calc_stripe_length(struct chunk_record *chunk_rec)
4891 {
4892         u64 stripe_size;
4893
4894         if (chunk_rec->type_flags & BTRFS_BLOCK_GROUP_RAID0) {
4895                 stripe_size = chunk_rec->length;
4896                 stripe_size /= chunk_rec->num_stripes;
4897         } else if (chunk_rec->type_flags & BTRFS_BLOCK_GROUP_RAID10) {
4898                 stripe_size = chunk_rec->length * 2;
4899                 stripe_size /= chunk_rec->num_stripes;
4900         } else if (chunk_rec->type_flags & BTRFS_BLOCK_GROUP_RAID5) {
4901                 stripe_size = chunk_rec->length;
4902                 stripe_size /= (chunk_rec->num_stripes - 1);
4903         } else if (chunk_rec->type_flags & BTRFS_BLOCK_GROUP_RAID6) {
4904                 stripe_size = chunk_rec->length;
4905                 stripe_size /= (chunk_rec->num_stripes - 2);
4906         } else {
4907                 stripe_size = chunk_rec->length;
4908         }
4909         return stripe_size;
4910 }
4911
4912 static int check_chunk_refs(struct chunk_record *chunk_rec,
4913                             struct block_group_tree *block_group_cache,
4914                             struct device_extent_tree *dev_extent_cache)
4915 {
4916         struct cache_extent *block_group_item;
4917         struct block_group_record *block_group_rec;
4918         struct cache_extent *dev_extent_item;
4919         struct device_extent_record *dev_extent_rec;
4920         u64 devid;
4921         u64 offset;
4922         u64 length;
4923         int i;
4924         int ret = 0;
4925
4926         block_group_item = lookup_cache_extent(&block_group_cache->tree,
4927                                                chunk_rec->offset,
4928                                                chunk_rec->length);
4929         if (block_group_item) {
4930                 block_group_rec = container_of(block_group_item,
4931                                                struct block_group_record,
4932                                                cache);
4933                 if (chunk_rec->length != block_group_rec->offset ||
4934                     chunk_rec->offset != block_group_rec->objectid ||
4935                     chunk_rec->type_flags != block_group_rec->flags) {
4936                         fprintf(stderr,
4937                                 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
4938                                 chunk_rec->objectid,
4939                                 chunk_rec->type,
4940                                 chunk_rec->offset,
4941                                 chunk_rec->length,
4942                                 chunk_rec->offset,
4943                                 chunk_rec->type_flags,
4944                                 block_group_rec->objectid,
4945                                 block_group_rec->type,
4946                                 block_group_rec->offset,
4947                                 block_group_rec->offset,
4948                                 block_group_rec->objectid,
4949                                 block_group_rec->flags);
4950                         ret = -1;
4951                 }
4952                 list_del(&block_group_rec->list);
4953         } else {
4954                 fprintf(stderr,
4955                         "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
4956                         chunk_rec->objectid,
4957                         chunk_rec->type,
4958                         chunk_rec->offset,
4959                         chunk_rec->length,
4960                         chunk_rec->offset,
4961                         chunk_rec->type_flags);
4962                 ret = -1;
4963         }
4964
4965         length = calc_stripe_length(chunk_rec);
4966         for (i = 0; i < chunk_rec->num_stripes; ++i) {
4967                 devid = chunk_rec->stripes[i].devid;
4968                 offset = chunk_rec->stripes[i].offset;
4969                 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
4970                                                        devid, offset, length);
4971                 if (dev_extent_item) {
4972                         dev_extent_rec = container_of(dev_extent_item,
4973                                                 struct device_extent_record,
4974                                                 cache);
4975                         if (dev_extent_rec->objectid != devid ||
4976                             dev_extent_rec->offset != offset ||
4977                             dev_extent_rec->chunk_offset != chunk_rec->offset ||
4978                             dev_extent_rec->length != length) {
4979                                 fprintf(stderr,
4980                                         "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
4981                                         chunk_rec->objectid,
4982                                         chunk_rec->type,
4983                                         chunk_rec->offset,
4984                                         chunk_rec->stripes[i].devid,
4985                                         chunk_rec->stripes[i].offset,
4986                                         dev_extent_rec->objectid,
4987                                         dev_extent_rec->offset,
4988                                         dev_extent_rec->length);
4989                                 ret = -1;
4990                         }
4991                         list_del(&dev_extent_rec->chunk_list);
4992                 } else {
4993                         fprintf(stderr,
4994                                 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
4995                                 chunk_rec->objectid,
4996                                 chunk_rec->type,
4997                                 chunk_rec->offset,
4998                                 chunk_rec->stripes[i].devid,
4999                                 chunk_rec->stripes[i].offset);
5000                         ret = -1;
5001                 }
5002         }
5003         return ret;
5004 }
5005
5006 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
5007 static int check_chunks(struct cache_tree *chunk_cache,
5008                         struct block_group_tree *block_group_cache,
5009                         struct device_extent_tree *dev_extent_cache)
5010 {
5011         struct cache_extent *chunk_item;
5012         struct chunk_record *chunk_rec;
5013         struct block_group_record *bg_rec;
5014         struct device_extent_record *dext_rec;
5015         int err;
5016         int ret = 0;
5017
5018         chunk_item = first_cache_extent(chunk_cache);
5019         while (chunk_item) {
5020                 chunk_rec = container_of(chunk_item, struct chunk_record,
5021                                          cache);
5022                 err = check_chunk_refs(chunk_rec, block_group_cache,
5023                                        dev_extent_cache);
5024                 if (err)
5025                         ret = err;
5026
5027                 chunk_item = next_cache_extent(chunk_item);
5028         }
5029
5030         list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
5031                 fprintf(stderr,
5032                         "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
5033                         bg_rec->objectid, bg_rec->offset, bg_rec->flags);
5034                 if (!ret)
5035                         ret = 1;
5036         }
5037
5038         list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
5039                             chunk_list) {
5040                 fprintf(stderr,
5041                         "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
5042                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
5043                 if (!ret)
5044                         ret = 1;
5045         }
5046         return ret;
5047 }
5048
5049
5050 static int check_device_used(struct device_record *dev_rec,
5051                              struct device_extent_tree *dext_cache)
5052 {
5053         struct cache_extent *cache;
5054         struct device_extent_record *dev_extent_rec;
5055         u64 total_byte = 0;
5056
5057         cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
5058         while (cache) {
5059                 dev_extent_rec = container_of(cache,
5060                                               struct device_extent_record,
5061                                               cache);
5062                 if (dev_extent_rec->objectid != dev_rec->devid)
5063                         break;
5064
5065                 list_del(&dev_extent_rec->device_list);
5066                 total_byte += dev_extent_rec->length;
5067                 cache = next_cache_extent(cache);
5068         }
5069
5070         if (total_byte != dev_rec->byte_used) {
5071                 fprintf(stderr,
5072                         "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
5073                         total_byte, dev_rec->byte_used, dev_rec->objectid,
5074                         dev_rec->type, dev_rec->offset);
5075                 return -1;
5076         } else {
5077                 return 0;
5078         }
5079 }
5080
5081 /* check btrfs_dev_item -> btrfs_dev_extent */
5082 static int check_devices(struct rb_root *dev_cache,
5083                          struct device_extent_tree *dev_extent_cache)
5084 {
5085         struct rb_node *dev_node;
5086         struct device_record *dev_rec;
5087         struct device_extent_record *dext_rec;
5088         int err;
5089         int ret = 0;
5090
5091         dev_node = rb_first(dev_cache);
5092         while (dev_node) {
5093                 dev_rec = container_of(dev_node, struct device_record, node);
5094                 err = check_device_used(dev_rec, dev_extent_cache);
5095                 if (err)
5096                         ret = err;
5097
5098                 dev_node = rb_next(dev_node);
5099         }
5100         list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
5101                             device_list) {
5102                 fprintf(stderr,
5103                         "Device extent[%llu, %llu, %llu] didn't find its device.\n",
5104                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
5105                 if (!ret)
5106                         ret = 1;
5107         }
5108         return ret;
5109 }
5110
5111 static int check_chunks_and_extents(struct btrfs_root *root, int repair)
5112 {
5113         struct rb_root dev_cache;
5114         struct cache_tree chunk_cache;
5115         struct block_group_tree block_group_cache;
5116         struct device_extent_tree dev_extent_cache;
5117         struct cache_tree extent_cache;
5118         struct cache_tree seen;
5119         struct cache_tree pending;
5120         struct cache_tree reada;
5121         struct cache_tree nodes;
5122         struct cache_tree corrupt_blocks;
5123         struct btrfs_path path;
5124         struct btrfs_key key;
5125         struct btrfs_key found_key;
5126         int ret, err = 0;
5127         u64 last = 0;
5128         struct block_info *bits;
5129         int bits_nr;
5130         struct extent_buffer *leaf;
5131         struct btrfs_trans_handle *trans = NULL;
5132         int slot;
5133         struct btrfs_root_item ri;
5134
5135         dev_cache = RB_ROOT;
5136         cache_tree_init(&chunk_cache);
5137         block_group_tree_init(&block_group_cache);
5138         device_extent_tree_init(&dev_extent_cache);
5139
5140         cache_tree_init(&extent_cache);
5141         cache_tree_init(&seen);
5142         cache_tree_init(&pending);
5143         cache_tree_init(&nodes);
5144         cache_tree_init(&reada);
5145         cache_tree_init(&corrupt_blocks);
5146
5147         if (repair) {
5148                 trans = btrfs_start_transaction(root, 1);
5149                 if (IS_ERR(trans)) {
5150                         fprintf(stderr, "Error starting transaction\n");
5151                         return PTR_ERR(trans);
5152                 }
5153                 root->fs_info->fsck_extent_cache = &extent_cache;
5154                 root->fs_info->free_extent_hook = free_extent_hook;
5155                 root->fs_info->corrupt_blocks = &corrupt_blocks;
5156         }
5157
5158         bits_nr = 1024;
5159         bits = malloc(bits_nr * sizeof(struct block_info));
5160         if (!bits) {
5161                 perror("malloc");
5162                 exit(1);
5163         }
5164
5165 again:
5166         add_root_to_pending(root->fs_info->tree_root->node,
5167                             &extent_cache, &pending, &seen, &nodes,
5168                             &root->fs_info->tree_root->root_key);
5169
5170         add_root_to_pending(root->fs_info->chunk_root->node,
5171                             &extent_cache, &pending, &seen, &nodes,
5172                             &root->fs_info->chunk_root->root_key);
5173
5174         btrfs_init_path(&path);
5175         key.offset = 0;
5176         key.objectid = 0;
5177         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
5178         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
5179                                         &key, &path, 0, 0);
5180         BUG_ON(ret < 0);
5181         while(1) {
5182                 leaf = path.nodes[0];
5183                 slot = path.slots[0];
5184                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
5185                         ret = btrfs_next_leaf(root, &path);
5186                         if (ret != 0)
5187                                 break;
5188                         leaf = path.nodes[0];
5189                         slot = path.slots[0];
5190                 }
5191                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
5192                 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
5193                         unsigned long offset;
5194                         struct extent_buffer *buf;
5195
5196                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
5197                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
5198                         buf = read_tree_block(root->fs_info->tree_root,
5199                                               btrfs_root_bytenr(&ri),
5200                                               btrfs_level_size(root,
5201                                                btrfs_root_level(&ri)), 0);
5202                         add_root_to_pending(buf, &extent_cache, &pending,
5203                                             &seen, &nodes, &found_key);
5204                         free_extent_buffer(buf);
5205                 }
5206                 path.slots[0]++;
5207         }
5208         btrfs_release_path(root, &path);
5209         while(1) {
5210                 ret = run_next_block(root, bits, bits_nr, &last, &pending,
5211                                      &seen, &reada, &nodes, &extent_cache,
5212                                      &chunk_cache, &dev_cache,
5213                                      &block_group_cache, &dev_extent_cache);
5214                 if (ret != 0)
5215                         break;
5216         }
5217
5218         ret = check_extent_refs(trans, root, &extent_cache, repair);
5219         if (ret == -EAGAIN) {
5220                 ret = btrfs_commit_transaction(trans, root);
5221                 if (ret)
5222                         goto out;
5223
5224                 trans = btrfs_start_transaction(root, 1);
5225                 if (IS_ERR(trans)) {
5226                         ret = PTR_ERR(trans);
5227                         goto out;
5228                 }
5229
5230                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
5231                 free_extent_cache_tree(&seen);
5232                 free_extent_cache_tree(&pending);
5233                 free_extent_cache_tree(&reada);
5234                 free_extent_cache_tree(&nodes);
5235                 free_extent_record_cache(root->fs_info, &extent_cache);
5236                 goto again;
5237         }
5238
5239         err = check_chunks(&chunk_cache, &block_group_cache,
5240                            &dev_extent_cache);
5241         if (err && !ret)
5242                 ret = err;
5243
5244         err = check_devices(&dev_cache, &dev_extent_cache);
5245         if (err && !ret)
5246                 ret = err;
5247
5248         if (trans) {
5249                 int err;
5250
5251                 err = btrfs_commit_transaction(trans, root);
5252                 if (!ret)
5253                         ret = err;
5254         }
5255 out:
5256         if (repair) {
5257                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
5258                 root->fs_info->fsck_extent_cache = NULL;
5259                 root->fs_info->free_extent_hook = NULL;
5260                 root->fs_info->corrupt_blocks = NULL;
5261         }
5262         free(bits);
5263         free_chunk_cache_tree(&chunk_cache);
5264         free_device_cache_tree(&dev_cache);
5265         free_block_group_tree(&block_group_cache);
5266         free_device_extent_tree(&dev_extent_cache);
5267         return ret;
5268 }
5269
5270 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
5271                                 struct extent_buffer *eb, int tree_root)
5272 {
5273         struct extent_buffer *tmp;
5274         struct btrfs_root_item *ri;
5275         struct btrfs_key key;
5276         u64 bytenr;
5277         u32 leafsize;
5278         int level = btrfs_header_level(eb);
5279         int nritems;
5280         int ret;
5281         int i;
5282
5283         btrfs_pin_extent(fs_info, eb->start, eb->len);
5284
5285         leafsize = btrfs_super_leafsize(fs_info->super_copy);
5286         nritems = btrfs_header_nritems(eb);
5287         for (i = 0; i < nritems; i++) {
5288                 if (level == 0) {
5289                         btrfs_item_key_to_cpu(eb, &key, i);
5290                         if (key.type != BTRFS_ROOT_ITEM_KEY)
5291                                 continue;
5292                         /* Skip the extent root and reloc roots */
5293                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
5294                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5295                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
5296                                 continue;
5297                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
5298                         bytenr = btrfs_disk_root_bytenr(eb, ri);
5299
5300                         /*
5301                          * If at any point we start needing the real root we
5302                          * will have to build a stump root for the root we are
5303                          * in, but for now this doesn't actually use the root so
5304                          * just pass in extent_root.
5305                          */
5306                         tmp = read_tree_block(fs_info->extent_root, bytenr,
5307                                               leafsize, 0);
5308                         if (!tmp) {
5309                                 fprintf(stderr, "Error reading root block\n");
5310                                 return -EIO;
5311                         }
5312                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
5313                         free_extent_buffer(tmp);
5314                         if (ret)
5315                                 return ret;
5316                 } else {
5317                         bytenr = btrfs_node_blockptr(eb, i);
5318
5319                         /* If we aren't the tree root don't read the block */
5320                         if (level == 1 && !tree_root) {
5321                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
5322                                 continue;
5323                         }
5324
5325                         tmp = read_tree_block(fs_info->extent_root, bytenr,
5326                                               leafsize, 0);
5327                         if (!tmp) {
5328                                 fprintf(stderr, "Error reading tree block\n");
5329                                 return -EIO;
5330                         }
5331                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
5332                         free_extent_buffer(tmp);
5333                         if (ret)
5334                                 return ret;
5335                 }
5336         }
5337
5338         return 0;
5339 }
5340
5341 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
5342 {
5343         int ret;
5344
5345         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
5346         if (ret)
5347                 return ret;
5348
5349         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
5350 }
5351
5352 static int reset_block_groups(struct btrfs_fs_info *fs_info)
5353 {
5354         struct btrfs_path *path;
5355         struct extent_buffer *leaf;
5356         struct btrfs_chunk *chunk;
5357         struct btrfs_key key;
5358         int ret;
5359
5360         path = btrfs_alloc_path();
5361         if (!path)
5362                 return -ENOMEM;
5363
5364         key.objectid = 0;
5365         key.type = BTRFS_CHUNK_ITEM_KEY;
5366         key.offset = 0;
5367
5368         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
5369         if (ret < 0) {
5370                 btrfs_free_path(path);
5371                 return ret;
5372         }
5373
5374         /*
5375          * We do this in case the block groups were screwed up and had alloc
5376          * bits that aren't actually set on the chunks.  This happens with
5377          * restored images every time and could happen in real life I guess.
5378          */
5379         fs_info->avail_data_alloc_bits = 0;
5380         fs_info->avail_metadata_alloc_bits = 0;
5381         fs_info->avail_system_alloc_bits = 0;
5382
5383         /* First we need to create the in-memory block groups */
5384         while (1) {
5385                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5386                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
5387                         if (ret < 0) {
5388                                 btrfs_free_path(path);
5389                                 return ret;
5390                         }
5391                         if (ret) {
5392                                 ret = 0;
5393                                 break;
5394                         }
5395                 }
5396                 leaf = path->nodes[0];
5397                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5398                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
5399                         path->slots[0]++;
5400                         continue;
5401                 }
5402
5403                 chunk = btrfs_item_ptr(leaf, path->slots[0],
5404                                        struct btrfs_chunk);
5405                 btrfs_add_block_group(fs_info, 0,
5406                                       btrfs_chunk_type(leaf, chunk),
5407                                       key.objectid, key.offset,
5408                                       btrfs_chunk_length(leaf, chunk));
5409                 path->slots[0]++;
5410         }
5411
5412         btrfs_free_path(path);
5413         return 0;
5414 }
5415
5416 static int reset_balance(struct btrfs_trans_handle *trans,
5417                          struct btrfs_fs_info *fs_info)
5418 {
5419         struct btrfs_root *root = fs_info->tree_root;
5420         struct btrfs_path *path;
5421         struct extent_buffer *leaf;
5422         struct btrfs_key key;
5423         int del_slot, del_nr = 0;
5424         int ret;
5425         int found = 0;
5426
5427         path = btrfs_alloc_path();
5428         if (!path)
5429                 return -ENOMEM;
5430
5431         key.objectid = BTRFS_BALANCE_OBJECTID;
5432         key.type = BTRFS_BALANCE_ITEM_KEY;
5433         key.offset = 0;
5434
5435         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5436         if (ret) {
5437                 if (ret > 0)
5438                         ret = 0;
5439                 goto out;
5440         }
5441
5442         ret = btrfs_del_item(trans, root, path);
5443         if (ret)
5444                 goto out;
5445         btrfs_release_path(root, path);
5446
5447         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
5448         key.type = BTRFS_ROOT_ITEM_KEY;
5449         key.offset = 0;
5450
5451         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5452         if (ret < 0)
5453                 goto out;
5454         while (1) {
5455                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5456                         if (!found)
5457                                 break;
5458
5459                         if (del_nr) {
5460                                 ret = btrfs_del_items(trans, root, path,
5461                                                       del_slot, del_nr);
5462                                 del_nr = 0;
5463                                 if (ret)
5464                                         goto out;
5465                         }
5466                         key.offset++;
5467                         btrfs_release_path(root, path);
5468
5469                         found = 0;
5470                         ret = btrfs_search_slot(trans, root, &key, path,
5471                                                 -1, 1);
5472                         if (ret < 0)
5473                                 goto out;
5474                         continue;
5475                 }
5476                 found = 1;
5477                 leaf = path->nodes[0];
5478                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5479                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
5480                         break;
5481                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5482                         path->slots[0]++;
5483                         continue;
5484                 }
5485                 if (!del_nr) {
5486                         del_slot = path->slots[0];
5487                         del_nr = 1;
5488                 } else {
5489                         del_nr++;
5490                 }
5491                 path->slots[0]++;
5492         }
5493
5494         if (del_nr) {
5495                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
5496                 if (ret)
5497                         goto out;
5498         }
5499         btrfs_release_path(root, path);
5500
5501         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
5502         key.type = BTRFS_ROOT_ITEM_KEY;
5503         key.offset = (u64)-1;
5504         root = btrfs_read_fs_root(fs_info, &key);
5505         if (IS_ERR(root)) {
5506                 fprintf(stderr, "Error reading data reloc tree\n");
5507                 return PTR_ERR(root);
5508         }
5509         root->track_dirty = 1;
5510         if (root->last_trans != trans->transid) {
5511                 root->last_trans = trans->transid;
5512                 root->commit_root = root->node;
5513                 extent_buffer_get(root->node);
5514         }
5515         ret = btrfs_fsck_reinit_root(trans, root, 0);
5516 out:
5517         btrfs_free_path(path);
5518         return ret;
5519 }
5520
5521 static int reinit_extent_tree(struct btrfs_fs_info *fs_info)
5522 {
5523         struct btrfs_trans_handle *trans;
5524         u64 start = 0;
5525         int ret;
5526
5527         /*
5528          * The only reason we don't do this is because right now we're just
5529          * walking the trees we find and pinning down their bytes, we don't look
5530          * at any of the leaves.  In order to do mixed groups we'd have to check
5531          * the leaves of any fs roots and pin down the bytes for any file
5532          * extents we find.  Not hard but why do it if we don't have to?
5533          */
5534         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
5535                 fprintf(stderr, "We don't support re-initing the extent tree "
5536                         "for mixed block groups yet, please notify a btrfs "
5537                         "developer you want to do this so they can add this "
5538                         "functionality.\n");
5539                 return -EINVAL;
5540         }
5541
5542         trans = btrfs_start_transaction(fs_info->extent_root, 1);
5543         if (IS_ERR(trans)) {
5544                 fprintf(stderr, "Error starting transaction\n");
5545                 return PTR_ERR(trans);
5546         }
5547
5548         /*
5549          * first we need to walk all of the trees except the extent tree and pin
5550          * down the bytes that are in use so we don't overwrite any existing
5551          * metadata.
5552          */
5553         ret = pin_metadata_blocks(fs_info);
5554         if (ret) {
5555                 fprintf(stderr, "error pinning down used bytes\n");
5556                 return ret;
5557         }
5558
5559         /*
5560          * Need to drop all the block groups since we're going to recreate all
5561          * of them again.
5562          */
5563         btrfs_free_block_groups(fs_info);
5564         ret = reset_block_groups(fs_info);
5565         if (ret) {
5566                 fprintf(stderr, "error resetting the block groups\n");
5567                 return ret;
5568         }
5569
5570         /* Ok we can allocate now, reinit the extent root */
5571         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 1);
5572         if (ret) {
5573                 fprintf(stderr, "extent root initialization failed\n");
5574                 /*
5575                  * When the transaction code is updated we should end the
5576                  * transaction, but for now progs only knows about commit so
5577                  * just return an error.
5578                  */
5579                 return ret;
5580         }
5581
5582         ret = reset_balance(trans, fs_info);
5583         if (ret) {
5584                 fprintf(stderr, "error reseting the pending balance\n");
5585                 return ret;
5586         }
5587
5588         /*
5589          * Now we have all the in-memory block groups setup so we can make
5590          * allocations properly, and the metadata we care about is safe since we
5591          * pinned all of it above.
5592          */
5593         while (1) {
5594                 struct btrfs_block_group_cache *cache;
5595
5596                 cache = btrfs_lookup_first_block_group(fs_info, start);
5597                 if (!cache)
5598                         break;
5599                 start = cache->key.objectid + cache->key.offset;
5600                 ret = btrfs_insert_item(trans, fs_info->extent_root,
5601                                         &cache->key, &cache->item,
5602                                         sizeof(cache->item));
5603                 if (ret) {
5604                         fprintf(stderr, "Error adding block group\n");
5605                         return ret;
5606                 }
5607                 btrfs_extent_post_op(trans, fs_info->extent_root);
5608         }
5609
5610         /*
5611          * Ok now we commit and run the normal fsck, which will add extent
5612          * entries for all of the items it finds.
5613          */
5614         return btrfs_commit_transaction(trans, fs_info->extent_root);
5615 }
5616
5617 static struct option long_options[] = {
5618         { "super", 1, NULL, 's' },
5619         { "repair", 0, NULL, 0 },
5620         { "init-csum-tree", 0, NULL, 0 },
5621         { "init-extent-tree", 0, NULL, 0 },
5622         { 0, 0, 0, 0}
5623 };
5624
5625 const char * const cmd_check_usage[] = {
5626         "btrfs check [options] <device>",
5627         "Check an unmounted btrfs filesystem.",
5628         "",
5629         "-s|--super <superblock>     use this superblock copy",
5630         "--repair                    try to repair the filesystem",
5631         "--init-csum-tree            create a new CRC tree",
5632         "--init-extent-tree          create a new extent tree",
5633         NULL
5634 };
5635
5636 int cmd_check(int argc, char **argv)
5637 {
5638         struct cache_tree root_cache;
5639         struct btrfs_root *root;
5640         struct btrfs_fs_info *info;
5641         u64 bytenr = 0;
5642         char uuidbuf[37];
5643         int ret;
5644         int num;
5645         int repair = 0;
5646         int option_index = 0;
5647         int init_csum_tree = 0;
5648         int init_extent_tree = 0;
5649         int rw = 0;
5650
5651         while(1) {
5652                 int c;
5653                 c = getopt_long(argc, argv, "as:", long_options,
5654                                 &option_index);
5655                 if (c < 0)
5656                         break;
5657                 switch(c) {
5658                         case 'a': /* ignored */ break;
5659                         case 's':
5660                                 num = atol(optarg);
5661                                 bytenr = btrfs_sb_offset(num);
5662                                 printf("using SB copy %d, bytenr %llu\n", num,
5663                                        (unsigned long long)bytenr);
5664                                 break;
5665                         case '?':
5666                         case 'h':
5667                                 usage(cmd_check_usage);
5668                 }
5669                 if (option_index == 1) {
5670                         printf("enabling repair mode\n");
5671                         repair = 1;
5672                         rw = 1;
5673                 } else if (option_index == 2) {
5674                         printf("Creating a new CRC tree\n");
5675                         init_csum_tree = 1;
5676                         rw = 1;
5677                 } else if (option_index == 3) {
5678                         init_extent_tree = 1;
5679                         rw = 1;
5680                         repair = 1;
5681                 }
5682
5683         }
5684         argc = argc - optind;
5685
5686         if (argc != 1)
5687                 usage(cmd_check_usage);
5688
5689         radix_tree_init();
5690         cache_tree_init(&root_cache);
5691
5692         if((ret = check_mounted(argv[optind])) < 0) {
5693                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
5694                 return ret;
5695         } else if(ret) {
5696                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
5697                 return -EBUSY;
5698         }
5699
5700         info = open_ctree_fs_info(argv[optind], bytenr, 0, rw, 1);
5701         if (!info) {
5702                 fprintf(stderr, "Couldn't open file system\n");
5703                 return -EIO;
5704         }
5705
5706         uuid_unparse(info->super_copy->fsid, uuidbuf);
5707         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
5708
5709         if (!extent_buffer_uptodate(info->tree_root->node) ||
5710             !extent_buffer_uptodate(info->dev_root->node) ||
5711             !extent_buffer_uptodate(info->extent_root->node) ||
5712             !extent_buffer_uptodate(info->chunk_root->node)) {
5713                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
5714                 return -EIO;
5715         }
5716
5717         root = info->fs_root;
5718
5719         if (init_extent_tree) {
5720                 printf("Creating a new extent tree\n");
5721                 ret = reinit_extent_tree(info);
5722                 if (ret)
5723                         return ret;
5724         }
5725         fprintf(stderr, "checking extents\n");
5726         if (init_csum_tree) {
5727                 struct btrfs_trans_handle *trans;
5728
5729                 fprintf(stderr, "Reinit crc root\n");
5730                 trans = btrfs_start_transaction(info->csum_root, 1);
5731                 if (IS_ERR(trans)) {
5732                         fprintf(stderr, "Error starting transaction\n");
5733                         return PTR_ERR(trans);
5734                 }
5735
5736                 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
5737                 if (ret) {
5738                         fprintf(stderr, "crc root initialization failed\n");
5739                         return -EIO;
5740                 }
5741
5742                 ret = btrfs_commit_transaction(trans, root);
5743                 if (ret)
5744                         exit(1);
5745                 goto out;
5746         }
5747         ret = check_chunks_and_extents(root, repair);
5748         if (ret)
5749                 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
5750
5751         fprintf(stderr, "checking free space cache\n");
5752         ret = check_space_cache(root);
5753         if (ret)
5754                 goto out;
5755
5756         fprintf(stderr, "checking fs roots\n");
5757         ret = check_fs_roots(root, &root_cache);
5758         if (ret)
5759                 goto out;
5760
5761         fprintf(stderr, "checking csums\n");
5762         ret = check_csums(root);
5763         if (ret)
5764                 goto out;
5765
5766         fprintf(stderr, "checking root refs\n");
5767         ret = check_root_refs(root, &root_cache);
5768 out:
5769         free_root_recs_tree(&root_cache);
5770         close_ctree(root);
5771
5772         if (found_old_backref) { /*
5773                  * there was a disk format change when mixed
5774                  * backref was in testing tree. The old format
5775                  * existed about one week.
5776                  */
5777                 printf("\n * Found old mixed backref format. "
5778                        "The old format is not supported! *"
5779                        "\n * Please mount the FS in readonly mode, "
5780                        "backup data and re-format the FS. *\n\n");
5781                 ret = 1;
5782         }
5783         printf("found %llu bytes used err is %d\n",
5784                (unsigned long long)bytes_used, ret);
5785         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
5786         printf("total tree bytes: %llu\n",
5787                (unsigned long long)total_btree_bytes);
5788         printf("total fs tree bytes: %llu\n",
5789                (unsigned long long)total_fs_tree_bytes);
5790         printf("total extent tree bytes: %llu\n",
5791                (unsigned long long)total_extent_tree_bytes);
5792         printf("btree space waste bytes: %llu\n",
5793                (unsigned long long)btree_space_waste);
5794         printf("file data blocks allocated: %llu\n referenced %llu\n",
5795                 (unsigned long long)data_bytes_allocated,
5796                 (unsigned long long)data_bytes_referenced);
5797         printf("%s\n", BTRFS_BUILD_VERSION);
5798         return ret;
5799 }