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