Btrfs-progs: print out human readable errors for inodes and backrefs
[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                 return ret;
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                                 return ret;
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         btrfs_free_path(path);
3344
3345         if (!ret &&
3346             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
3347                 fprintf(stderr, "There are still entries left in the space "
3348                         "cache\n");
3349                 ret = -EINVAL;
3350         }
3351
3352         return ret;
3353 }
3354
3355 static int check_space_cache(struct btrfs_root *root)
3356 {
3357         struct btrfs_block_group_cache *cache;
3358         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
3359         int ret;
3360         int error = 0;
3361
3362         if (btrfs_super_generation(root->fs_info->super_copy) !=
3363             btrfs_super_cache_generation(root->fs_info->super_copy)) {
3364                 printf("cache and super generation don't match, space cache "
3365                        "will be invalidated\n");
3366                 return 0;
3367         }
3368
3369         while (1) {
3370                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
3371                 if (!cache)
3372                         break;
3373
3374                 start = cache->key.objectid + cache->key.offset;
3375                 if (!cache->free_space_ctl) {
3376                         if (btrfs_init_free_space_ctl(cache,
3377                                                       root->sectorsize)) {
3378                                 ret = -ENOMEM;
3379                                 break;
3380                         }
3381                 } else {
3382                         btrfs_remove_free_space_cache(cache);
3383                 }
3384
3385                 ret = load_free_space_cache(root->fs_info, cache);
3386                 if (!ret)
3387                         continue;
3388
3389                 ret = verify_space_cache(root, cache);
3390                 if (ret) {
3391                         fprintf(stderr, "cache appears valid but isnt %Lu\n",
3392                                 cache->key.objectid);
3393                         error++;
3394                 }
3395         }
3396
3397         return error ? -EINVAL : 0;
3398 }
3399
3400 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
3401                                u64 num_bytes)
3402 {
3403         struct btrfs_path *path;
3404         struct extent_buffer *leaf;
3405         struct btrfs_key key;
3406         int ret;
3407
3408         path = btrfs_alloc_path();
3409         if (!path) {
3410                 fprintf(stderr, "Error allocing path\n");
3411                 return -ENOMEM;
3412         }
3413
3414         key.objectid = bytenr;
3415         key.type = BTRFS_EXTENT_ITEM_KEY;
3416         key.offset = 0;
3417
3418
3419 again:
3420         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
3421                                 0, 0);
3422         if (ret < 0) {
3423                 fprintf(stderr, "Error looking up extent record %d\n", ret);
3424                 btrfs_free_path(path);
3425                 return ret;
3426         } else if (ret) {
3427                 if (path->slots[0])
3428                         path->slots[0]--;
3429                 else
3430                         btrfs_prev_leaf(root, path);
3431         }
3432
3433         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3434
3435         /*
3436          * Block group items come before extent items if they have the same
3437          * bytenr, so walk back one more just in case.  Dear future traveler,
3438          * first congrats on mastering time travel.  Now if it's not too much
3439          * trouble could you go back to 2006 and tell Chris to make the
3440          * BLOCK_GROUP_ITEM_KEY lower than the EXTENT_ITEM_KEY please?
3441          */
3442         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
3443                 if (path->slots[0])
3444                         path->slots[0]--;
3445                 else
3446                         btrfs_prev_leaf(root, path);
3447         }
3448
3449         while (num_bytes) {
3450                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3451                         ret = btrfs_next_leaf(root, path);
3452                         if (ret < 0) {
3453                                 fprintf(stderr, "Error going to next leaf "
3454                                         "%d\n", ret);
3455                                 btrfs_free_path(path);
3456                                 return ret;
3457                         } else if (ret) {
3458                                 break;
3459                         }
3460                 }
3461                 leaf = path->nodes[0];
3462                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3463                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
3464                         path->slots[0]++;
3465                         continue;
3466                 }
3467                 if (key.objectid + key.offset < bytenr) {
3468                         path->slots[0]++;
3469                         continue;
3470                 }
3471                 if (key.objectid > bytenr + num_bytes)
3472                         break;
3473
3474                 if (key.objectid == bytenr) {
3475                         if (key.offset >= num_bytes) {
3476                                 num_bytes = 0;
3477                                 break;
3478                         }
3479                         num_bytes -= key.offset;
3480                         bytenr += key.offset;
3481                 } else if (key.objectid < bytenr) {
3482                         if (key.objectid + key.offset >= bytenr + num_bytes) {
3483                                 num_bytes = 0;
3484                                 break;
3485                         }
3486                         num_bytes = (bytenr + num_bytes) -
3487                                 (key.objectid + key.offset);
3488                         bytenr = key.objectid + key.offset;
3489                 } else {
3490                         if (key.objectid + key.offset < bytenr + num_bytes) {
3491                                 u64 new_start = key.objectid + key.offset;
3492                                 u64 new_bytes = bytenr + num_bytes - new_start;
3493
3494                                 /*
3495                                  * Weird case, the extent is in the middle of
3496                                  * our range, we'll have to search one side
3497                                  * and then the other.  Not sure if this happens
3498                                  * in real life, but no harm in coding it up
3499                                  * anyway just in case.
3500                                  */
3501                                 btrfs_release_path(path);
3502                                 ret = check_extent_exists(root, new_start,
3503                                                           new_bytes);
3504                                 if (ret) {
3505                                         fprintf(stderr, "Right section didn't "
3506                                                 "have a record\n");
3507                                         break;
3508                                 }
3509                                 num_bytes = key.objectid - bytenr;
3510                                 goto again;
3511                         }
3512                         num_bytes = key.objectid - bytenr;
3513                 }
3514                 path->slots[0]++;
3515         }
3516         ret = 0;
3517
3518         if (num_bytes) {
3519                 fprintf(stderr, "There are no extents for csum range "
3520                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
3521                 ret = 1;
3522         }
3523
3524         btrfs_free_path(path);
3525         return ret;
3526 }
3527
3528 static int check_csums(struct btrfs_root *root)
3529 {
3530         struct btrfs_path *path;
3531         struct extent_buffer *leaf;
3532         struct btrfs_key key;
3533         u64 offset = 0, num_bytes = 0;
3534         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
3535         int errors = 0;
3536         int ret;
3537
3538         root = root->fs_info->csum_root;
3539
3540         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
3541         key.type = BTRFS_EXTENT_CSUM_KEY;
3542         key.offset = 0;
3543
3544         path = btrfs_alloc_path();
3545         if (!path)
3546                 return -ENOMEM;
3547
3548         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3549         if (ret < 0) {
3550                 fprintf(stderr, "Error searching csum tree %d\n", ret);
3551                 btrfs_free_path(path);
3552                 return ret;
3553         }
3554
3555         if (ret > 0 && path->slots[0])
3556                 path->slots[0]--;
3557         ret = 0;
3558
3559         while (1) {
3560                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3561                         ret = btrfs_next_leaf(root, path);
3562                         if (ret < 0) {
3563                                 fprintf(stderr, "Error going to next leaf "
3564                                         "%d\n", ret);
3565                                 break;
3566                         }
3567                         if (ret)
3568                                 break;
3569                 }
3570                 leaf = path->nodes[0];
3571
3572                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3573                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
3574                         path->slots[0]++;
3575                         continue;
3576                 }
3577
3578                 if (!num_bytes) {
3579                         offset = key.offset;
3580                 } else if (key.offset != offset + num_bytes) {
3581                         ret = check_extent_exists(root, offset, num_bytes);
3582                         if (ret) {
3583                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
3584                                         "there is no extent record\n",
3585                                         offset, offset+num_bytes);
3586                                 errors++;
3587                         }
3588                         offset = key.offset;
3589                         num_bytes = 0;
3590                 }
3591
3592                 num_bytes += (btrfs_item_size_nr(leaf, path->slots[0]) /
3593                               csum_size) * root->sectorsize;
3594                 path->slots[0]++;
3595         }
3596
3597         btrfs_free_path(path);
3598         return errors;
3599 }
3600
3601 static int run_next_block(struct btrfs_root *root,
3602                           struct block_info *bits,
3603                           int bits_nr,
3604                           u64 *last,
3605                           struct cache_tree *pending,
3606                           struct cache_tree *seen,
3607                           struct cache_tree *reada,
3608                           struct cache_tree *nodes,
3609                           struct cache_tree *extent_cache,
3610                           struct cache_tree *chunk_cache,
3611                           struct rb_root *dev_cache,
3612                           struct block_group_tree *block_group_cache,
3613                           struct device_extent_tree *dev_extent_cache)
3614 {
3615         struct extent_buffer *buf;
3616         u64 bytenr;
3617         u32 size;
3618         u64 parent;
3619         u64 owner;
3620         u64 flags;
3621         u64 ptr;
3622         int ret;
3623         int i;
3624         int nritems;
3625         struct btrfs_key key;
3626         struct cache_extent *cache;
3627         int reada_bits;
3628
3629         nritems = pick_next_pending(pending, reada, nodes, *last, bits,
3630                                     bits_nr, &reada_bits);
3631         if (nritems == 0)
3632                 return 1;
3633
3634         if (!reada_bits) {
3635                 for(i = 0; i < nritems; i++) {
3636                         ret = add_cache_extent(reada, bits[i].start,
3637                                                bits[i].size);
3638                         if (ret == -EEXIST)
3639                                 continue;
3640
3641                         /* fixme, get the parent transid */
3642                         readahead_tree_block(root, bits[i].start,
3643                                              bits[i].size, 0);
3644                 }
3645         }
3646         *last = bits[0].start;
3647         bytenr = bits[0].start;
3648         size = bits[0].size;
3649
3650         cache = lookup_cache_extent(pending, bytenr, size);
3651         if (cache) {
3652                 remove_cache_extent(pending, cache);
3653                 free(cache);
3654         }
3655         cache = lookup_cache_extent(reada, bytenr, size);
3656         if (cache) {
3657                 remove_cache_extent(reada, cache);
3658                 free(cache);
3659         }
3660         cache = lookup_cache_extent(nodes, bytenr, size);
3661         if (cache) {
3662                 remove_cache_extent(nodes, cache);
3663                 free(cache);
3664         }
3665         cache = lookup_cache_extent(seen, bytenr, size);
3666         if (cache) {
3667                 remove_cache_extent(seen, cache);
3668                 free(cache);
3669         }
3670
3671         /* fixme, get the real parent transid */
3672         buf = read_tree_block(root, bytenr, size, 0);
3673         if (!extent_buffer_uptodate(buf)) {
3674                 record_bad_block_io(root->fs_info,
3675                                     extent_cache, bytenr, size);
3676                 goto out;
3677         }
3678
3679         nritems = btrfs_header_nritems(buf);
3680
3681         ret = btrfs_lookup_extent_info(NULL, root, bytenr,
3682                                        btrfs_header_level(buf), 1, NULL,
3683                                        &flags);
3684         if (ret < 0)
3685                 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
3686
3687         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
3688                 parent = bytenr;
3689                 owner = 0;
3690         } else {
3691                 parent = 0;
3692                 owner = btrfs_header_owner(buf);
3693         }
3694
3695         ret = check_block(root, extent_cache, buf, flags);
3696         if (ret)
3697                 goto out;
3698
3699         if (btrfs_is_leaf(buf)) {
3700                 btree_space_waste += btrfs_leaf_free_space(root, buf);
3701                 for (i = 0; i < nritems; i++) {
3702                         struct btrfs_file_extent_item *fi;
3703                         btrfs_item_key_to_cpu(buf, &key, i);
3704                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
3705                                 process_extent_item(root, extent_cache, buf,
3706                                                     i);
3707                                 continue;
3708                         }
3709                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
3710                                 process_extent_item(root, extent_cache, buf,
3711                                                     i);
3712                                 continue;
3713                         }
3714                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
3715                                 total_csum_bytes +=
3716                                         btrfs_item_size_nr(buf, i);
3717                                 continue;
3718                         }
3719                         if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3720                                 process_chunk_item(chunk_cache, &key, buf, i);
3721                                 continue;
3722                         }
3723                         if (key.type == BTRFS_DEV_ITEM_KEY) {
3724                                 process_device_item(dev_cache, &key, buf, i);
3725                                 continue;
3726                         }
3727                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
3728                                 process_block_group_item(block_group_cache,
3729                                         &key, buf, i);
3730                                 continue;
3731                         }
3732                         if (key.type == BTRFS_DEV_EXTENT_KEY) {
3733                                 process_device_extent_item(dev_extent_cache,
3734                                         &key, buf, i);
3735                                 continue;
3736
3737                         }
3738                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
3739 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3740                                 process_extent_ref_v0(extent_cache, buf, i);
3741 #else
3742                                 BUG();
3743 #endif
3744                                 continue;
3745                         }
3746
3747                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
3748                                 add_tree_backref(extent_cache, key.objectid, 0,
3749                                                  key.offset, 0);
3750                                 continue;
3751                         }
3752                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
3753                                 add_tree_backref(extent_cache, key.objectid,
3754                                                  key.offset, 0, 0);
3755                                 continue;
3756                         }
3757                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
3758                                 struct btrfs_extent_data_ref *ref;
3759                                 ref = btrfs_item_ptr(buf, i,
3760                                                 struct btrfs_extent_data_ref);
3761                                 add_data_backref(extent_cache,
3762                                         key.objectid, 0,
3763                                         btrfs_extent_data_ref_root(buf, ref),
3764                                         btrfs_extent_data_ref_objectid(buf,
3765                                                                        ref),
3766                                         btrfs_extent_data_ref_offset(buf, ref),
3767                                         btrfs_extent_data_ref_count(buf, ref),
3768                                         0, root->sectorsize);
3769                                 continue;
3770                         }
3771                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
3772                                 struct btrfs_shared_data_ref *ref;
3773                                 ref = btrfs_item_ptr(buf, i,
3774                                                 struct btrfs_shared_data_ref);
3775                                 add_data_backref(extent_cache,
3776                                         key.objectid, key.offset, 0, 0, 0,
3777                                         btrfs_shared_data_ref_count(buf, ref),
3778                                         0, root->sectorsize);
3779                                 continue;
3780                         }
3781                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3782                                 continue;
3783                         fi = btrfs_item_ptr(buf, i,
3784                                             struct btrfs_file_extent_item);
3785                         if (btrfs_file_extent_type(buf, fi) ==
3786                             BTRFS_FILE_EXTENT_INLINE)
3787                                 continue;
3788                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
3789                                 continue;
3790
3791                         data_bytes_allocated +=
3792                                 btrfs_file_extent_disk_num_bytes(buf, fi);
3793                         if (data_bytes_allocated < root->sectorsize) {
3794                                 abort();
3795                         }
3796                         data_bytes_referenced +=
3797                                 btrfs_file_extent_num_bytes(buf, fi);
3798                         add_data_backref(extent_cache,
3799                                 btrfs_file_extent_disk_bytenr(buf, fi),
3800                                 parent, owner, key.objectid, key.offset -
3801                                 btrfs_file_extent_offset(buf, fi), 1, 1,
3802                                 btrfs_file_extent_disk_num_bytes(buf, fi));
3803                         BUG_ON(ret);
3804                 }
3805         } else {
3806                 int level;
3807                 struct btrfs_key first_key;
3808
3809                 first_key.objectid = 0;
3810
3811                 if (nritems > 0)
3812                         btrfs_item_key_to_cpu(buf, &first_key, 0);
3813                 level = btrfs_header_level(buf);
3814                 for (i = 0; i < nritems; i++) {
3815                         ptr = btrfs_node_blockptr(buf, i);
3816                         size = btrfs_level_size(root, level - 1);
3817                         btrfs_node_key_to_cpu(buf, &key, i);
3818                         ret = add_extent_rec(extent_cache, &key,
3819                                              ptr, size, 0, 0, 1, 0, 1, 0,
3820                                              size);
3821                         BUG_ON(ret);
3822
3823                         add_tree_backref(extent_cache, ptr, parent, owner, 1);
3824
3825                         if (level > 1) {
3826                                 add_pending(nodes, seen, ptr, size);
3827                         } else {
3828                                 add_pending(pending, seen, ptr, size);
3829                         }
3830                 }
3831                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
3832                                       nritems) * sizeof(struct btrfs_key_ptr);
3833         }
3834         total_btree_bytes += buf->len;
3835         if (fs_root_objectid(btrfs_header_owner(buf)))
3836                 total_fs_tree_bytes += buf->len;
3837         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
3838                 total_extent_tree_bytes += buf->len;
3839         if (!found_old_backref &&
3840             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
3841             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
3842             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
3843                 found_old_backref = 1;
3844 out:
3845         free_extent_buffer(buf);
3846         return 0;
3847 }
3848
3849 static int add_root_to_pending(struct extent_buffer *buf,
3850                                struct cache_tree *extent_cache,
3851                                struct cache_tree *pending,
3852                                struct cache_tree *seen,
3853                                struct cache_tree *nodes,
3854                                struct btrfs_key *root_key)
3855 {
3856         if (btrfs_header_level(buf) > 0)
3857                 add_pending(nodes, seen, buf->start, buf->len);
3858         else
3859                 add_pending(pending, seen, buf->start, buf->len);
3860         add_extent_rec(extent_cache, NULL, buf->start, buf->len,
3861                        0, 1, 1, 0, 1, 0, buf->len);
3862
3863         if (root_key->objectid == BTRFS_TREE_RELOC_OBJECTID ||
3864             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
3865                 add_tree_backref(extent_cache, buf->start, buf->start,
3866                                  0, 1);
3867         else
3868                 add_tree_backref(extent_cache, buf->start, 0,
3869                                  root_key->objectid, 1);
3870         return 0;
3871 }
3872
3873 /* as we fix the tree, we might be deleting blocks that
3874  * we're tracking for repair.  This hook makes sure we
3875  * remove any backrefs for blocks as we are fixing them.
3876  */
3877 static int free_extent_hook(struct btrfs_trans_handle *trans,
3878                             struct btrfs_root *root,
3879                             u64 bytenr, u64 num_bytes, u64 parent,
3880                             u64 root_objectid, u64 owner, u64 offset,
3881                             int refs_to_drop)
3882 {
3883         struct extent_record *rec;
3884         struct cache_extent *cache;
3885         int is_data;
3886         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
3887
3888         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
3889         cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
3890         if (!cache)
3891                 return 0;
3892
3893         rec = container_of(cache, struct extent_record, cache);
3894         if (is_data) {
3895                 struct data_backref *back;
3896                 back = find_data_backref(rec, parent, root_objectid, owner,
3897                                          offset, 1, bytenr, num_bytes);
3898                 if (!back)
3899                         goto out;
3900                 if (back->node.found_ref) {
3901                         back->found_ref -= refs_to_drop;
3902                         if (rec->refs)
3903                                 rec->refs -= refs_to_drop;
3904                 }
3905                 if (back->node.found_extent_tree) {
3906                         back->num_refs -= refs_to_drop;
3907                         if (rec->extent_item_refs)
3908                                 rec->extent_item_refs -= refs_to_drop;
3909                 }
3910                 if (back->found_ref == 0)
3911                         back->node.found_ref = 0;
3912                 if (back->num_refs == 0)
3913                         back->node.found_extent_tree = 0;
3914
3915                 if (!back->node.found_extent_tree && back->node.found_ref) {
3916                         list_del(&back->node.list);
3917                         free(back);
3918                 }
3919         } else {
3920                 struct tree_backref *back;
3921                 back = find_tree_backref(rec, parent, root_objectid);
3922                 if (!back)
3923                         goto out;
3924                 if (back->node.found_ref) {
3925                         if (rec->refs)
3926                                 rec->refs--;
3927                         back->node.found_ref = 0;
3928                 }
3929                 if (back->node.found_extent_tree) {
3930                         if (rec->extent_item_refs)
3931                                 rec->extent_item_refs--;
3932                         back->node.found_extent_tree = 0;
3933                 }
3934                 if (!back->node.found_extent_tree && back->node.found_ref) {
3935                         list_del(&back->node.list);
3936                         free(back);
3937                 }
3938         }
3939         maybe_free_extent_rec(extent_cache, rec);
3940 out:
3941         return 0;
3942 }
3943
3944 static int delete_extent_records(struct btrfs_trans_handle *trans,
3945                                  struct btrfs_root *root,
3946                                  struct btrfs_path *path,
3947                                  u64 bytenr, u64 new_len)
3948 {
3949         struct btrfs_key key;
3950         struct btrfs_key found_key;
3951         struct extent_buffer *leaf;
3952         int ret;
3953         int slot;
3954
3955
3956         key.objectid = bytenr;
3957         key.type = (u8)-1;
3958         key.offset = (u64)-1;
3959
3960         while(1) {
3961                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
3962                                         &key, path, 0, 1);
3963                 if (ret < 0)
3964                         break;
3965
3966                 if (ret > 0) {
3967                         ret = 0;
3968                         if (path->slots[0] == 0)
3969                                 break;
3970                         path->slots[0]--;
3971                 }
3972                 ret = 0;
3973
3974                 leaf = path->nodes[0];
3975                 slot = path->slots[0];
3976
3977                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3978                 if (found_key.objectid != bytenr)
3979                         break;
3980
3981                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
3982                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
3983                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3984                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
3985                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
3986                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
3987                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
3988                         btrfs_release_path(path);
3989                         if (found_key.type == 0) {
3990                                 if (found_key.offset == 0)
3991                                         break;
3992                                 key.offset = found_key.offset - 1;
3993                                 key.type = found_key.type;
3994                         }
3995                         key.type = found_key.type - 1;
3996                         key.offset = (u64)-1;
3997                         continue;
3998                 }
3999
4000                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
4001                         found_key.objectid, found_key.type, found_key.offset);
4002
4003                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
4004                 if (ret)
4005                         break;
4006                 btrfs_release_path(path);
4007
4008                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4009                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
4010                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
4011                                 found_key.offset : root->leafsize;
4012
4013                         ret = btrfs_update_block_group(trans, root, bytenr,
4014                                                        bytes, 0, 0);
4015                         if (ret)
4016                                 break;
4017                 }
4018         }
4019
4020         btrfs_release_path(path);
4021         return ret;
4022 }
4023
4024 /*
4025  * for a single backref, this will allocate a new extent
4026  * and add the backref to it.
4027  */
4028 static int record_extent(struct btrfs_trans_handle *trans,
4029                          struct btrfs_fs_info *info,
4030                          struct btrfs_path *path,
4031                          struct extent_record *rec,
4032                          struct extent_backref *back,
4033                          int allocated, u64 flags)
4034 {
4035         int ret;
4036         struct btrfs_root *extent_root = info->extent_root;
4037         struct extent_buffer *leaf;
4038         struct btrfs_key ins_key;
4039         struct btrfs_extent_item *ei;
4040         struct tree_backref *tback;
4041         struct data_backref *dback;
4042         struct btrfs_tree_block_info *bi;
4043
4044         if (!back->is_data)
4045                 rec->max_size = max_t(u64, rec->max_size,
4046                                     info->extent_root->leafsize);
4047
4048         if (!allocated) {
4049                 u32 item_size = sizeof(*ei);
4050
4051                 if (!back->is_data)
4052                         item_size += sizeof(*bi);
4053
4054                 ins_key.objectid = rec->start;
4055                 ins_key.offset = rec->max_size;
4056                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
4057
4058                 ret = btrfs_insert_empty_item(trans, extent_root, path,
4059                                         &ins_key, item_size);
4060                 if (ret)
4061                         goto fail;
4062
4063                 leaf = path->nodes[0];
4064                 ei = btrfs_item_ptr(leaf, path->slots[0],
4065                                     struct btrfs_extent_item);
4066
4067                 btrfs_set_extent_refs(leaf, ei, 0);
4068                 btrfs_set_extent_generation(leaf, ei, rec->generation);
4069
4070                 if (back->is_data) {
4071                         btrfs_set_extent_flags(leaf, ei,
4072                                                BTRFS_EXTENT_FLAG_DATA);
4073                 } else {
4074                         struct btrfs_disk_key copy_key;;
4075
4076                         tback = (struct tree_backref *)back;
4077                         bi = (struct btrfs_tree_block_info *)(ei + 1);
4078                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
4079                                              sizeof(*bi));
4080
4081                         btrfs_set_disk_key_objectid(&copy_key,
4082                                                     rec->info_objectid);
4083                         btrfs_set_disk_key_type(&copy_key, 0);
4084                         btrfs_set_disk_key_offset(&copy_key, 0);
4085
4086                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
4087                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
4088
4089                         btrfs_set_extent_flags(leaf, ei,
4090                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
4091                 }
4092
4093                 btrfs_mark_buffer_dirty(leaf);
4094                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
4095                                                rec->max_size, 1, 0);
4096                 if (ret)
4097                         goto fail;
4098                 btrfs_release_path(path);
4099         }
4100
4101         if (back->is_data) {
4102                 u64 parent;
4103                 int i;
4104
4105                 dback = (struct data_backref *)back;
4106                 if (back->full_backref)
4107                         parent = dback->parent;
4108                 else
4109                         parent = 0;
4110
4111                 for (i = 0; i < dback->found_ref; i++) {
4112                         /* if parent != 0, we're doing a full backref
4113                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
4114                          * just makes the backref allocator create a data
4115                          * backref
4116                          */
4117                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
4118                                                    rec->start, rec->max_size,
4119                                                    parent,
4120                                                    dback->root,
4121                                                    parent ?
4122                                                    BTRFS_FIRST_FREE_OBJECTID :
4123                                                    dback->owner,
4124                                                    dback->offset);
4125                         if (ret)
4126                                 break;
4127                 }
4128                 fprintf(stderr, "adding new data backref"
4129                                 " on %llu %s %llu owner %llu"
4130                                 " offset %llu found %d\n",
4131                                 (unsigned long long)rec->start,
4132                                 back->full_backref ?
4133                                 "parent" : "root",
4134                                 back->full_backref ?
4135                                 (unsigned long long)parent :
4136                                 (unsigned long long)dback->root,
4137                                 (unsigned long long)dback->owner,
4138                                 (unsigned long long)dback->offset,
4139                                 dback->found_ref);
4140         } else {
4141                 u64 parent;
4142
4143                 tback = (struct tree_backref *)back;
4144                 if (back->full_backref)
4145                         parent = tback->parent;
4146                 else
4147                         parent = 0;
4148
4149                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
4150                                            rec->start, rec->max_size,
4151                                            parent, tback->root, 0, 0);
4152                 fprintf(stderr, "adding new tree backref on "
4153                         "start %llu len %llu parent %llu root %llu\n",
4154                         rec->start, rec->max_size, tback->parent, tback->root);
4155         }
4156         if (ret)
4157                 goto fail;
4158 fail:
4159         btrfs_release_path(path);
4160         return ret;
4161 }
4162
4163 struct extent_entry {
4164         u64 bytenr;
4165         u64 bytes;
4166         int count;
4167         int broken;
4168         struct list_head list;
4169 };
4170
4171 static struct extent_entry *find_entry(struct list_head *entries,
4172                                        u64 bytenr, u64 bytes)
4173 {
4174         struct extent_entry *entry = NULL;
4175
4176         list_for_each_entry(entry, entries, list) {
4177                 if (entry->bytenr == bytenr && entry->bytes == bytes)
4178                         return entry;
4179         }
4180
4181         return NULL;
4182 }
4183
4184 static struct extent_entry *find_most_right_entry(struct list_head *entries)
4185 {
4186         struct extent_entry *entry, *best = NULL, *prev = NULL;
4187
4188         list_for_each_entry(entry, entries, list) {
4189                 if (!prev) {
4190                         prev = entry;
4191                         continue;
4192                 }
4193
4194                 /*
4195                  * If there are as many broken entries as entries then we know
4196                  * not to trust this particular entry.
4197                  */
4198                 if (entry->broken == entry->count)
4199                         continue;
4200
4201                 /*
4202                  * If our current entry == best then we can't be sure our best
4203                  * is really the best, so we need to keep searching.
4204                  */
4205                 if (best && best->count == entry->count) {
4206                         prev = entry;
4207                         best = NULL;
4208                         continue;
4209                 }
4210
4211                 /* Prev == entry, not good enough, have to keep searching */
4212                 if (!prev->broken && prev->count == entry->count)
4213                         continue;
4214
4215                 if (!best)
4216                         best = (prev->count > entry->count) ? prev : entry;
4217                 else if (best->count < entry->count)
4218                         best = entry;
4219                 prev = entry;
4220         }
4221
4222         return best;
4223 }
4224
4225 static int repair_ref(struct btrfs_trans_handle *trans,
4226                       struct btrfs_fs_info *info, struct btrfs_path *path,
4227                       struct data_backref *dback, struct extent_entry *entry)
4228 {
4229         struct btrfs_root *root;
4230         struct btrfs_file_extent_item *fi;
4231         struct extent_buffer *leaf;
4232         struct btrfs_key key;
4233         u64 bytenr, bytes;
4234         int ret;
4235
4236         key.objectid = dback->root;
4237         key.type = BTRFS_ROOT_ITEM_KEY;
4238         key.offset = (u64)-1;
4239         root = btrfs_read_fs_root(info, &key);
4240         if (IS_ERR(root)) {
4241                 fprintf(stderr, "Couldn't find root for our ref\n");
4242                 return -EINVAL;
4243         }
4244
4245         /*
4246          * The backref points to the original offset of the extent if it was
4247          * split, so we need to search down to the offset we have and then walk
4248          * forward until we find the backref we're looking for.
4249          */
4250         key.objectid = dback->owner;
4251         key.type = BTRFS_EXTENT_DATA_KEY;
4252         key.offset = dback->offset;
4253         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4254         if (ret < 0) {
4255                 fprintf(stderr, "Error looking up ref %d\n", ret);
4256                 return ret;
4257         }
4258
4259         while (1) {
4260                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4261                         ret = btrfs_next_leaf(root, path);
4262                         if (ret) {
4263                                 fprintf(stderr, "Couldn't find our ref, next\n");
4264                                 return -EINVAL;
4265                         }
4266                 }
4267                 leaf = path->nodes[0];
4268                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4269                 if (key.objectid != dback->owner ||
4270                     key.type != BTRFS_EXTENT_DATA_KEY) {
4271                         fprintf(stderr, "Couldn't find our ref, search\n");
4272                         return -EINVAL;
4273                 }
4274                 fi = btrfs_item_ptr(leaf, path->slots[0],
4275                                     struct btrfs_file_extent_item);
4276                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
4277                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
4278
4279                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
4280                         break;
4281                 path->slots[0]++;
4282         }
4283
4284         btrfs_release_path(path);
4285
4286         /*
4287          * Have to make sure that this root gets updated when we commit the
4288          * transaction
4289          */
4290         root->track_dirty = 1;
4291         if (root->last_trans != trans->transid) {
4292                 root->last_trans = trans->transid;
4293                 root->commit_root = root->node;
4294                 extent_buffer_get(root->node);
4295         }
4296
4297         /*
4298          * Ok we have the key of the file extent we want to fix, now we can cow
4299          * down to the thing and fix it.
4300          */
4301         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4302         if (ret < 0) {
4303                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
4304                         key.objectid, key.type, key.offset, ret);
4305                 return ret;
4306         }
4307         if (ret > 0) {
4308                 fprintf(stderr, "Well that's odd, we just found this key "
4309                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
4310                         key.offset);
4311                 return -EINVAL;
4312         }
4313         leaf = path->nodes[0];
4314         fi = btrfs_item_ptr(leaf, path->slots[0],
4315                             struct btrfs_file_extent_item);
4316
4317         if (btrfs_file_extent_compression(leaf, fi) &&
4318             dback->disk_bytenr != entry->bytenr) {
4319                 fprintf(stderr, "Ref doesn't match the record start and is "
4320                         "compressed, please take a btrfs-image of this file "
4321                         "system and send it to a btrfs developer so they can "
4322                         "complete this functionality for bytenr %Lu\n",
4323                         dback->disk_bytenr);
4324                 return -EINVAL;
4325         }
4326
4327         if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
4328                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4329         } else if (dback->disk_bytenr > entry->bytenr) {
4330                 u64 off_diff, offset;
4331
4332                 off_diff = dback->disk_bytenr - entry->bytenr;
4333                 offset = btrfs_file_extent_offset(leaf, fi);
4334                 if (dback->disk_bytenr + offset +
4335                     btrfs_file_extent_num_bytes(leaf, fi) >
4336                     entry->bytenr + entry->bytes) {
4337                         fprintf(stderr, "Ref is past the entry end, please "
4338                                 "take a btrfs-image of this file system and "
4339                                 "send it to a btrfs developer, ref %Lu\n",
4340                                 dback->disk_bytenr);
4341                         return -EINVAL;
4342                 }
4343                 offset += off_diff;
4344                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4345                 btrfs_set_file_extent_offset(leaf, fi, offset);
4346         } else if (dback->disk_bytenr < entry->bytenr) {
4347                 u64 offset;
4348
4349                 offset = btrfs_file_extent_offset(leaf, fi);
4350                 if (dback->disk_bytenr + offset < entry->bytenr) {
4351                         fprintf(stderr, "Ref is before the entry start, please"
4352                                 " take a btrfs-image of this file system and "
4353                                 "send it to a btrfs developer, ref %Lu\n",
4354                                 dback->disk_bytenr);
4355                         return -EINVAL;
4356                 }
4357
4358                 offset += dback->disk_bytenr;
4359                 offset -= entry->bytenr;
4360                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4361                 btrfs_set_file_extent_offset(leaf, fi, offset);
4362         }
4363
4364         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
4365
4366         /*
4367          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
4368          * only do this if we aren't using compression, otherwise it's a
4369          * trickier case.
4370          */
4371         if (!btrfs_file_extent_compression(leaf, fi))
4372                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
4373         else
4374                 printf("ram bytes may be wrong?\n");
4375         btrfs_mark_buffer_dirty(leaf);
4376         btrfs_release_path(path);
4377         return 0;
4378 }
4379
4380 static int verify_backrefs(struct btrfs_trans_handle *trans,
4381                            struct btrfs_fs_info *info, struct btrfs_path *path,
4382                            struct extent_record *rec)
4383 {
4384         struct extent_backref *back;
4385         struct data_backref *dback;
4386         struct extent_entry *entry, *best = NULL;
4387         LIST_HEAD(entries);
4388         int nr_entries = 0;
4389         int broken_entries = 0;
4390         int ret = 0;
4391         short mismatch = 0;
4392
4393         /*
4394          * Metadata is easy and the backrefs should always agree on bytenr and
4395          * size, if not we've got bigger issues.
4396          */
4397         if (rec->metadata)
4398                 return 0;
4399
4400         list_for_each_entry(back, &rec->backrefs, list) {
4401                 dback = (struct data_backref *)back;
4402                 /*
4403                  * We only pay attention to backrefs that we found a real
4404                  * backref for.
4405                  */
4406                 if (dback->found_ref == 0)
4407                         continue;
4408                 if (back->full_backref)
4409                         continue;
4410
4411                 /*
4412                  * For now we only catch when the bytes don't match, not the
4413                  * bytenr.  We can easily do this at the same time, but I want
4414                  * to have a fs image to test on before we just add repair
4415                  * functionality willy-nilly so we know we won't screw up the
4416                  * repair.
4417                  */
4418
4419                 entry = find_entry(&entries, dback->disk_bytenr,
4420                                    dback->bytes);
4421                 if (!entry) {
4422                         entry = malloc(sizeof(struct extent_entry));
4423                         if (!entry) {
4424                                 ret = -ENOMEM;
4425                                 goto out;
4426                         }
4427                         memset(entry, 0, sizeof(*entry));
4428                         entry->bytenr = dback->disk_bytenr;
4429                         entry->bytes = dback->bytes;
4430                         list_add_tail(&entry->list, &entries);
4431                         nr_entries++;
4432                 }
4433
4434                 /*
4435                  * If we only have on entry we may think the entries agree when
4436                  * in reality they don't so we have to do some extra checking.
4437                  */
4438                 if (dback->disk_bytenr != rec->start ||
4439                     dback->bytes != rec->nr || back->broken)
4440                         mismatch = 1;
4441
4442                 if (back->broken) {
4443                         entry->broken++;
4444                         broken_entries++;
4445                 }
4446
4447                 entry->count++;
4448         }
4449
4450         /* Yay all the backrefs agree, carry on good sir */
4451         if (nr_entries <= 1 && !mismatch)
4452                 goto out;
4453
4454         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
4455                 "%Lu\n", rec->start);
4456
4457         /*
4458          * First we want to see if the backrefs can agree amongst themselves who
4459          * is right, so figure out which one of the entries has the highest
4460          * count.
4461          */
4462         best = find_most_right_entry(&entries);
4463
4464         /*
4465          * Ok so we may have an even split between what the backrefs think, so
4466          * this is where we use the extent ref to see what it thinks.
4467          */
4468         if (!best) {
4469                 entry = find_entry(&entries, rec->start, rec->nr);
4470                 if (!entry && (!broken_entries || !rec->found_rec)) {
4471                         fprintf(stderr, "Backrefs don't agree with eachother "
4472                                 "and extent record doesn't agree with anybody,"
4473                                 " so we can't fix bytenr %Lu bytes %Lu\n",
4474                                 rec->start, rec->nr);
4475                         ret = -EINVAL;
4476                         goto out;
4477                 } else if (!entry) {
4478                         /*
4479                          * Ok our backrefs were broken, we'll assume this is the
4480                          * correct value and add an entry for this range.
4481                          */
4482                         entry = malloc(sizeof(struct extent_entry));
4483                         if (!entry) {
4484                                 ret = -ENOMEM;
4485                                 goto out;
4486                         }
4487                         memset(entry, 0, sizeof(*entry));
4488                         entry->bytenr = rec->start;
4489                         entry->bytes = rec->nr;
4490                         list_add_tail(&entry->list, &entries);
4491                         nr_entries++;
4492                 }
4493                 entry->count++;
4494                 best = find_most_right_entry(&entries);
4495                 if (!best) {
4496                         fprintf(stderr, "Backrefs and extent record evenly "
4497                                 "split on who is right, this is going to "
4498                                 "require user input to fix bytenr %Lu bytes "
4499                                 "%Lu\n", rec->start, rec->nr);
4500                         ret = -EINVAL;
4501                         goto out;
4502                 }
4503         }
4504
4505         /*
4506          * I don't think this can happen currently as we'll abort() if we catch
4507          * this case higher up, but in case somebody removes that we still can't
4508          * deal with it properly here yet, so just bail out of that's the case.
4509          */
4510         if (best->bytenr != rec->start) {
4511                 fprintf(stderr, "Extent start and backref starts don't match, "
4512                         "please use btrfs-image on this file system and send "
4513                         "it to a btrfs developer so they can make fsck fix "
4514                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
4515                         rec->start, rec->nr);
4516                 ret = -EINVAL;
4517                 goto out;
4518         }
4519
4520         /*
4521          * Ok great we all agreed on an extent record, let's go find the real
4522          * references and fix up the ones that don't match.
4523          */
4524         list_for_each_entry(back, &rec->backrefs, list) {
4525                 dback = (struct data_backref *)back;
4526
4527                 /*
4528                  * Still ignoring backrefs that don't have a real ref attached
4529                  * to them.
4530                  */
4531                 if (dback->found_ref == 0)
4532                         continue;
4533                 if (back->full_backref)
4534                         continue;
4535
4536                 if (dback->bytes == best->bytes &&
4537                     dback->disk_bytenr == best->bytenr)
4538                         continue;
4539
4540                 ret = repair_ref(trans, info, path, dback, best);
4541                 if (ret)
4542                         goto out;
4543         }
4544
4545         /*
4546          * Ok we messed with the actual refs, which means we need to drop our
4547          * entire cache and go back and rescan.  I know this is a huge pain and
4548          * adds a lot of extra work, but it's the only way to be safe.  Once all
4549          * the backrefs agree we may not need to do anything to the extent
4550          * record itself.
4551          */
4552         ret = -EAGAIN;
4553 out:
4554         while (!list_empty(&entries)) {
4555                 entry = list_entry(entries.next, struct extent_entry, list);
4556                 list_del_init(&entry->list);
4557                 free(entry);
4558         }
4559         return ret;
4560 }
4561
4562 static int process_duplicates(struct btrfs_root *root,
4563                               struct cache_tree *extent_cache,
4564                               struct extent_record *rec)
4565 {
4566         struct extent_record *good, *tmp;
4567         struct cache_extent *cache;
4568         int ret;
4569
4570         /*
4571          * If we found a extent record for this extent then return, or if we
4572          * have more than one duplicate we are likely going to need to delete
4573          * something.
4574          */
4575         if (rec->found_rec || rec->num_duplicates > 1)
4576                 return 0;
4577
4578         /* Shouldn't happen but just in case */
4579         BUG_ON(!rec->num_duplicates);
4580
4581         /*
4582          * So this happens if we end up with a backref that doesn't match the
4583          * actual extent entry.  So either the backref is bad or the extent
4584          * entry is bad.  Either way we want to have the extent_record actually
4585          * reflect what we found in the extent_tree, so we need to take the
4586          * duplicate out and use that as the extent_record since the only way we
4587          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
4588          */
4589         remove_cache_extent(extent_cache, &rec->cache);
4590
4591         good = list_entry(rec->dups.next, struct extent_record, list);
4592         list_del_init(&good->list);
4593         INIT_LIST_HEAD(&good->backrefs);
4594         INIT_LIST_HEAD(&good->dups);
4595         good->cache.start = good->start;
4596         good->cache.size = good->nr;
4597         good->content_checked = 0;
4598         good->owner_ref_checked = 0;
4599         good->num_duplicates = 0;
4600         good->refs = rec->refs;
4601         list_splice_init(&rec->backrefs, &good->backrefs);
4602         while (1) {
4603                 cache = lookup_cache_extent(extent_cache, good->start,
4604                                             good->nr);
4605                 if (!cache)
4606                         break;
4607                 tmp = container_of(cache, struct extent_record, cache);
4608
4609                 /*
4610                  * If we find another overlapping extent and it's found_rec is
4611                  * set then it's a duplicate and we need to try and delete
4612                  * something.
4613                  */
4614                 if (tmp->found_rec || tmp->num_duplicates > 0) {
4615                         if (list_empty(&good->list))
4616                                 list_add_tail(&good->list,
4617                                               &duplicate_extents);
4618                         good->num_duplicates += tmp->num_duplicates + 1;
4619                         list_splice_init(&tmp->dups, &good->dups);
4620                         list_del_init(&tmp->list);
4621                         list_add_tail(&tmp->list, &good->dups);
4622                         remove_cache_extent(extent_cache, &tmp->cache);
4623                         continue;
4624                 }
4625
4626                 /*
4627                  * Ok we have another non extent item backed extent rec, so lets
4628                  * just add it to this extent and carry on like we did above.
4629                  */
4630                 good->refs += tmp->refs;
4631                 list_splice_init(&tmp->backrefs, &good->backrefs);
4632                 remove_cache_extent(extent_cache, &tmp->cache);
4633                 free(tmp);
4634         }
4635         ret = insert_cache_extent(extent_cache, &good->cache);
4636         BUG_ON(ret);
4637         free(rec);
4638         return good->num_duplicates ? 0 : 1;
4639 }
4640
4641 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
4642                                     struct btrfs_root *root,
4643                                     struct extent_record *rec)
4644 {
4645         LIST_HEAD(delete_list);
4646         struct btrfs_path *path;
4647         struct extent_record *tmp, *good, *n;
4648         int nr_del = 0;
4649         int ret = 0;
4650         struct btrfs_key key;
4651
4652         path = btrfs_alloc_path();
4653         if (!path) {
4654                 ret = -ENOMEM;
4655                 goto out;
4656         }
4657
4658         good = rec;
4659         /* Find the record that covers all of the duplicates. */
4660         list_for_each_entry(tmp, &rec->dups, list) {
4661                 if (good->start < tmp->start)
4662                         continue;
4663                 if (good->nr > tmp->nr)
4664                         continue;
4665
4666                 if (tmp->start + tmp->nr < good->start + good->nr) {
4667                         fprintf(stderr, "Ok we have overlapping extents that "
4668                                 "aren't completely covered by eachother, this "
4669                                 "is going to require more careful thought.  "
4670                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
4671                                 tmp->start, tmp->nr, good->start, good->nr);
4672                         abort();
4673                 }
4674                 good = tmp;
4675         }
4676
4677         if (good != rec)
4678                 list_add_tail(&rec->list, &delete_list);
4679
4680         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
4681                 if (tmp == good)
4682                         continue;
4683                 list_move_tail(&tmp->list, &delete_list);
4684         }
4685
4686         root = root->fs_info->extent_root;
4687         list_for_each_entry(tmp, &delete_list, list) {
4688                 if (tmp->found_rec == 0)
4689                         continue;
4690                 key.objectid = tmp->start;
4691                 key.type = BTRFS_EXTENT_ITEM_KEY;
4692                 key.offset = tmp->nr;
4693
4694                 /* Shouldn't happen but just in case */
4695                 if (tmp->metadata) {
4696                         fprintf(stderr, "Well this shouldn't happen, extent "
4697                                 "record overlaps but is metadata? "
4698                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
4699                         abort();
4700                 }
4701
4702                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4703                 if (ret) {
4704                         if (ret > 0)
4705                                 ret = -EINVAL;
4706                         goto out;
4707                 }
4708                 ret = btrfs_del_item(trans, root, path);
4709                 if (ret)
4710                         goto out;
4711                 btrfs_release_path(path);
4712                 nr_del++;
4713         }
4714
4715 out:
4716         while (!list_empty(&delete_list)) {
4717                 tmp = list_entry(delete_list.next, struct extent_record, list);
4718                 list_del_init(&tmp->list);
4719                 if (tmp == rec)
4720                         continue;
4721                 free(tmp);
4722         }
4723
4724         while (!list_empty(&rec->dups)) {
4725                 tmp = list_entry(rec->dups.next, struct extent_record, list);
4726                 list_del_init(&tmp->list);
4727                 free(tmp);
4728         }
4729
4730         btrfs_free_path(path);
4731
4732         if (!ret && !nr_del)
4733                 rec->num_duplicates = 0;
4734
4735         return ret ? ret : nr_del;
4736 }
4737
4738 static int find_possible_backrefs(struct btrfs_trans_handle *trans,
4739                                   struct btrfs_fs_info *info,
4740                                   struct btrfs_path *path,
4741                                   struct cache_tree *extent_cache,
4742                                   struct extent_record *rec)
4743 {
4744         struct btrfs_root *root;
4745         struct extent_backref *back;
4746         struct data_backref *dback;
4747         struct cache_extent *cache;
4748         struct btrfs_file_extent_item *fi;
4749         struct btrfs_key key;
4750         u64 bytenr, bytes;
4751         int ret;
4752
4753         list_for_each_entry(back, &rec->backrefs, list) {
4754                 dback = (struct data_backref *)back;
4755
4756                 /* We found this one, we don't need to do a lookup */
4757                 if (dback->found_ref)
4758                         continue;
4759                 /* Don't care about full backrefs (poor unloved backrefs) */
4760                 if (back->full_backref)
4761                         continue;
4762                 key.objectid = dback->root;
4763                 key.type = BTRFS_ROOT_ITEM_KEY;
4764                 key.offset = (u64)-1;
4765
4766                 root = btrfs_read_fs_root(info, &key);
4767
4768                 /* No root, definitely a bad ref, skip */
4769                 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
4770                         continue;
4771                 /* Other err, exit */
4772                 if (IS_ERR(root))
4773                         return PTR_ERR(root);
4774
4775                 key.objectid = dback->owner;
4776                 key.type = BTRFS_EXTENT_DATA_KEY;
4777                 key.offset = dback->offset;
4778                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4779                 if (ret) {
4780                         btrfs_release_path(path);
4781                         if (ret < 0)
4782                                 return ret;
4783                         /* Didn't find it, we can carry on */
4784                         ret = 0;
4785                         continue;
4786                 }
4787
4788                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
4789                                     struct btrfs_file_extent_item);
4790                 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
4791                 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
4792                 btrfs_release_path(path);
4793                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4794                 if (cache) {
4795                         struct extent_record *tmp;
4796                         tmp = container_of(cache, struct extent_record, cache);
4797
4798                         /*
4799                          * If we found an extent record for the bytenr for this
4800                          * particular backref then we can't add it to our
4801                          * current extent record.  We only want to add backrefs
4802                          * that don't have a corresponding extent item in the
4803                          * extent tree since they likely belong to this record
4804                          * and we need to fix it if it doesn't match bytenrs.
4805                          */
4806                         if  (tmp->found_rec)
4807                                 continue;
4808                 }
4809
4810                 dback->found_ref += 1;
4811                 dback->disk_bytenr = bytenr;
4812                 dback->bytes = bytes;
4813
4814                 /*
4815                  * Set this so the verify backref code knows not to trust the
4816                  * values in this backref.
4817                  */
4818                 back->broken = 1;
4819         }
4820
4821         return 0;
4822 }
4823
4824 /*
4825  * when an incorrect extent item is found, this will delete
4826  * all of the existing entries for it and recreate them
4827  * based on what the tree scan found.
4828  */
4829 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
4830                              struct btrfs_fs_info *info,
4831                              struct cache_tree *extent_cache,
4832                              struct extent_record *rec)
4833 {
4834         int ret;
4835         struct btrfs_path *path;
4836         struct list_head *cur = rec->backrefs.next;
4837         struct cache_extent *cache;
4838         struct extent_backref *back;
4839         int allocated = 0;
4840         u64 flags = 0;
4841
4842         /* remember our flags for recreating the extent */
4843         ret = btrfs_lookup_extent_info(NULL, info->extent_root, rec->start,
4844                                        rec->max_size, rec->metadata, NULL,
4845                                        &flags);
4846         if (ret < 0)
4847                 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4848
4849         path = btrfs_alloc_path();
4850         if (!path)
4851                 return -ENOMEM;
4852
4853         if (rec->refs != rec->extent_item_refs && !rec->metadata) {
4854                 /*
4855                  * Sometimes the backrefs themselves are so broken they don't
4856                  * get attached to any meaningful rec, so first go back and
4857                  * check any of our backrefs that we couldn't find and throw
4858                  * them into the list if we find the backref so that
4859                  * verify_backrefs can figure out what to do.
4860                  */
4861                 ret = find_possible_backrefs(trans, info, path, extent_cache,
4862                                              rec);
4863                 if (ret < 0)
4864                         goto out;
4865         }
4866
4867         /* step one, make sure all of the backrefs agree */
4868         ret = verify_backrefs(trans, info, path, rec);
4869         if (ret < 0)
4870                 goto out;
4871
4872         /* step two, delete all the existing records */
4873         ret = delete_extent_records(trans, info->extent_root, path,
4874                                     rec->start, rec->max_size);
4875
4876         if (ret < 0)
4877                 goto out;
4878
4879         /* was this block corrupt?  If so, don't add references to it */
4880         cache = lookup_cache_extent(info->corrupt_blocks,
4881                                     rec->start, rec->max_size);
4882         if (cache) {
4883                 ret = 0;
4884                 goto out;
4885         }
4886
4887         /* step three, recreate all the refs we did find */
4888         while(cur != &rec->backrefs) {
4889                 back = list_entry(cur, struct extent_backref, list);
4890                 cur = cur->next;
4891
4892                 /*
4893                  * if we didn't find any references, don't create a
4894                  * new extent record
4895                  */
4896                 if (!back->found_ref)
4897                         continue;
4898
4899                 ret = record_extent(trans, info, path, rec, back, allocated, flags);
4900                 allocated = 1;
4901
4902                 if (ret)
4903                         goto out;
4904         }
4905 out:
4906         btrfs_free_path(path);
4907         return ret;
4908 }
4909
4910 /* right now we only prune from the extent allocation tree */
4911 static int prune_one_block(struct btrfs_trans_handle *trans,
4912                            struct btrfs_fs_info *info,
4913                            struct btrfs_corrupt_block *corrupt)
4914 {
4915         int ret;
4916         struct btrfs_path path;
4917         struct extent_buffer *eb;
4918         u64 found;
4919         int slot;
4920         int nritems;
4921         int level = corrupt->level + 1;
4922
4923         btrfs_init_path(&path);
4924 again:
4925         /* we want to stop at the parent to our busted block */
4926         path.lowest_level = level;
4927
4928         ret = btrfs_search_slot(trans, info->extent_root,
4929                                 &corrupt->key, &path, -1, 1);
4930
4931         if (ret < 0)
4932                 goto out;
4933
4934         eb = path.nodes[level];
4935         if (!eb) {
4936                 ret = -ENOENT;
4937                 goto out;
4938         }
4939
4940         /*
4941          * hopefully the search gave us the block we want to prune,
4942          * lets try that first
4943          */
4944         slot = path.slots[level];
4945         found =  btrfs_node_blockptr(eb, slot);
4946         if (found == corrupt->cache.start)
4947                 goto del_ptr;
4948
4949         nritems = btrfs_header_nritems(eb);
4950
4951         /* the search failed, lets scan this node and hope we find it */
4952         for (slot = 0; slot < nritems; slot++) {
4953                 found =  btrfs_node_blockptr(eb, slot);
4954                 if (found == corrupt->cache.start)
4955                         goto del_ptr;
4956         }
4957         /*
4958          * we couldn't find the bad block.  TODO, search all the nodes for pointers
4959          * to this block
4960          */
4961         if (eb == info->extent_root->node) {
4962                 ret = -ENOENT;
4963                 goto out;
4964         } else {
4965                 level++;
4966                 btrfs_release_path(&path);
4967                 goto again;
4968         }
4969
4970 del_ptr:
4971         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
4972         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
4973
4974 out:
4975         btrfs_release_path(&path);
4976         return ret;
4977 }
4978
4979 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
4980                                 struct btrfs_fs_info *info)
4981 {
4982         struct cache_extent *cache;
4983         struct btrfs_corrupt_block *corrupt;
4984
4985         cache = search_cache_extent(info->corrupt_blocks, 0);
4986         while (1) {
4987                 if (!cache)
4988                         break;
4989                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
4990                 prune_one_block(trans, info, corrupt);
4991                 cache = next_cache_extent(cache);
4992         }
4993         return 0;
4994 }
4995
4996 static void free_corrupt_block(struct cache_extent *cache)
4997 {
4998         struct btrfs_corrupt_block *corrupt;
4999
5000         corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
5001         free(corrupt);
5002 }
5003
5004 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
5005
5006 static int check_block_group(struct btrfs_trans_handle *trans,
5007                               struct btrfs_fs_info *info,
5008                               struct map_lookup *map,
5009                               int *reinit)
5010 {
5011         struct btrfs_key key;
5012         struct btrfs_path path;
5013         int ret;
5014
5015         key.objectid = map->ce.start;
5016         key.offset = map->ce.size;
5017         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
5018
5019         btrfs_init_path(&path);
5020         ret = btrfs_search_slot(NULL, info->extent_root,
5021                                 &key, &path, 0, 0);
5022         btrfs_release_path(&path);
5023         if (ret <= 0)
5024                 goto out;
5025
5026         ret = btrfs_make_block_group(trans, info->extent_root, 0, map->type,
5027                                BTRFS_FIRST_CHUNK_TREE_OBJECTID,
5028                                key.objectid, key.offset);
5029         *reinit = 1;
5030 out:
5031         return ret;
5032 }
5033
5034 static int check_block_groups(struct btrfs_trans_handle *trans,
5035                               struct btrfs_fs_info *info, int *reinit)
5036 {
5037         struct cache_extent *ce;
5038         struct map_lookup *map;
5039         struct btrfs_mapping_tree *map_tree = &info->mapping_tree;
5040
5041         /* this isn't quite working */
5042         return 0;
5043
5044         ce = search_cache_extent(&map_tree->cache_tree, 0);
5045         while (1) {
5046                 if (!ce)
5047                         break;
5048                 map = container_of(ce, struct map_lookup, ce);
5049                 check_block_group(trans, info, map, reinit);
5050                 ce = next_cache_extent(ce);
5051         }
5052         return 0;
5053 }
5054
5055 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
5056 {
5057         struct btrfs_block_group_cache *cache;
5058         u64 start, end;
5059         int ret;
5060
5061         while (1) {
5062                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
5063                                             &start, &end, EXTENT_DIRTY);
5064                 if (ret)
5065                         break;
5066                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
5067                                    GFP_NOFS);
5068         }
5069
5070         start = 0;
5071         while (1) {
5072                 cache = btrfs_lookup_first_block_group(fs_info, start);
5073                 if (!cache)
5074                         break;
5075                 if (cache->cached)
5076                         cache->cached = 0;
5077                 start = cache->key.objectid + cache->key.offset;
5078         }
5079 }
5080
5081 static int check_extent_refs(struct btrfs_trans_handle *trans,
5082                              struct btrfs_root *root,
5083                              struct cache_tree *extent_cache)
5084 {
5085         struct extent_record *rec;
5086         struct cache_extent *cache;
5087         int err = 0;
5088         int ret = 0;
5089         int fixed = 0;
5090         int reinit = 0;
5091         int had_dups = 0;
5092
5093         if (repair) {
5094                 /*
5095                  * if we're doing a repair, we have to make sure
5096                  * we don't allocate from the problem extents.
5097                  * In the worst case, this will be all the
5098                  * extents in the FS
5099                  */
5100                 cache = search_cache_extent(extent_cache, 0);
5101                 while(cache) {
5102                         rec = container_of(cache, struct extent_record, cache);
5103                         btrfs_pin_extent(root->fs_info,
5104                                          rec->start, rec->max_size);
5105                         cache = next_cache_extent(cache);
5106                 }
5107
5108                 /* pin down all the corrupted blocks too */
5109                 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
5110                 while(cache) {
5111                         btrfs_pin_extent(root->fs_info,
5112                                          cache->start, cache->size);
5113                         cache = next_cache_extent(cache);
5114                 }
5115                 prune_corrupt_blocks(trans, root->fs_info);
5116                 check_block_groups(trans, root->fs_info, &reinit);
5117                 if (reinit)
5118                         btrfs_read_block_groups(root->fs_info->extent_root);
5119                 reset_cached_block_groups(root->fs_info);
5120         }
5121
5122         /*
5123          * We need to delete any duplicate entries we find first otherwise we
5124          * could mess up the extent tree when we have backrefs that actually
5125          * belong to a different extent item and not the weird duplicate one.
5126          */
5127         while (repair && !list_empty(&duplicate_extents)) {
5128                 rec = list_entry(duplicate_extents.next, struct extent_record,
5129                                  list);
5130                 list_del_init(&rec->list);
5131
5132                 /* Sometimes we can find a backref before we find an actual
5133                  * extent, so we need to process it a little bit to see if there
5134                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
5135                  * if this is a backref screwup.  If we need to delete stuff
5136                  * process_duplicates() will return 0, otherwise it will return
5137                  * 1 and we
5138                  */
5139                 if (process_duplicates(root, extent_cache, rec))
5140                         continue;
5141                 ret = delete_duplicate_records(trans, root, rec);
5142                 if (ret < 0)
5143                         return ret;
5144                 /*
5145                  * delete_duplicate_records will return the number of entries
5146                  * deleted, so if it's greater than 0 then we know we actually
5147                  * did something and we need to remove.
5148                  */
5149                 if (ret)
5150                         had_dups = 1;
5151         }
5152
5153         if (had_dups)
5154                 return -EAGAIN;
5155
5156         while(1) {
5157                 fixed = 0;
5158                 cache = search_cache_extent(extent_cache, 0);
5159                 if (!cache)
5160                         break;
5161                 rec = container_of(cache, struct extent_record, cache);
5162                 if (rec->num_duplicates) {
5163                         fprintf(stderr, "extent item %llu has multiple extent "
5164                                 "items\n", (unsigned long long)rec->start);
5165                         err = 1;
5166                 }
5167
5168                 if (rec->refs != rec->extent_item_refs) {
5169                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
5170                                 (unsigned long long)rec->start,
5171                                 (unsigned long long)rec->nr);
5172                         fprintf(stderr, "extent item %llu, found %llu\n",
5173                                 (unsigned long long)rec->extent_item_refs,
5174                                 (unsigned long long)rec->refs);
5175                         if (!fixed && repair) {
5176                                 ret = fixup_extent_refs(trans, root->fs_info,
5177                                                         extent_cache, rec);
5178                                 if (ret)
5179                                         goto repair_abort;
5180                                 fixed = 1;
5181                         }
5182                         err = 1;
5183
5184                 }
5185                 if (all_backpointers_checked(rec, 1)) {
5186                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
5187                                 (unsigned long long)rec->start,
5188                                 (unsigned long long)rec->nr);
5189
5190                         if (!fixed && repair) {
5191                                 ret = fixup_extent_refs(trans, root->fs_info,
5192                                                         extent_cache, rec);
5193                                 if (ret)
5194                                         goto repair_abort;
5195                                 fixed = 1;
5196                         }
5197
5198                         err = 1;
5199                 }
5200                 if (!rec->owner_ref_checked) {
5201                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
5202                                 (unsigned long long)rec->start,
5203                                 (unsigned long long)rec->nr);
5204                         if (!fixed && repair) {
5205                                 ret = fixup_extent_refs(trans, root->fs_info,
5206                                                         extent_cache, rec);
5207                                 if (ret)
5208                                         goto repair_abort;
5209                                 fixed = 1;
5210                         }
5211                         err = 1;
5212                 }
5213
5214                 remove_cache_extent(extent_cache, cache);
5215                 free_all_extent_backrefs(rec);
5216                 free(rec);
5217         }
5218 repair_abort:
5219         if (repair) {
5220                 if (ret && ret != -EAGAIN) {
5221                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
5222                         exit(1);
5223                 } else if (!ret) {
5224                         btrfs_fix_block_accounting(trans, root);
5225                 }
5226                 if (err)
5227                         fprintf(stderr, "repaired damaged extent references\n");
5228                 return ret;
5229         }
5230         return err;
5231 }
5232
5233 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
5234 {
5235         u64 stripe_size;
5236
5237         if (type & BTRFS_BLOCK_GROUP_RAID0) {
5238                 stripe_size = length;
5239                 stripe_size /= num_stripes;
5240         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
5241                 stripe_size = length * 2;
5242                 stripe_size /= num_stripes;
5243         } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
5244                 stripe_size = length;
5245                 stripe_size /= (num_stripes - 1);
5246         } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
5247                 stripe_size = length;
5248                 stripe_size /= (num_stripes - 2);
5249         } else {
5250                 stripe_size = length;
5251         }
5252         return stripe_size;
5253 }
5254
5255 static int check_chunk_refs(struct chunk_record *chunk_rec,
5256                             struct block_group_tree *block_group_cache,
5257                             struct device_extent_tree *dev_extent_cache,
5258                             int silent)
5259 {
5260         struct cache_extent *block_group_item;
5261         struct block_group_record *block_group_rec;
5262         struct cache_extent *dev_extent_item;
5263         struct device_extent_record *dev_extent_rec;
5264         u64 devid;
5265         u64 offset;
5266         u64 length;
5267         int i;
5268         int ret = 0;
5269
5270         block_group_item = lookup_cache_extent(&block_group_cache->tree,
5271                                                chunk_rec->offset,
5272                                                chunk_rec->length);
5273         if (block_group_item) {
5274                 block_group_rec = container_of(block_group_item,
5275                                                struct block_group_record,
5276                                                cache);
5277                 if (chunk_rec->length != block_group_rec->offset ||
5278                     chunk_rec->offset != block_group_rec->objectid ||
5279                     chunk_rec->type_flags != block_group_rec->flags) {
5280                         if (!silent)
5281                                 fprintf(stderr,
5282                                         "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
5283                                         chunk_rec->objectid,
5284                                         chunk_rec->type,
5285                                         chunk_rec->offset,
5286                                         chunk_rec->length,
5287                                         chunk_rec->offset,
5288                                         chunk_rec->type_flags,
5289                                         block_group_rec->objectid,
5290                                         block_group_rec->type,
5291                                         block_group_rec->offset,
5292                                         block_group_rec->offset,
5293                                         block_group_rec->objectid,
5294                                         block_group_rec->flags);
5295                         ret = -1;
5296                 } else {
5297                         list_del_init(&block_group_rec->list);
5298                         chunk_rec->bg_rec = block_group_rec;
5299                 }
5300         } else {
5301                 if (!silent)
5302                         fprintf(stderr,
5303                                 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
5304                                 chunk_rec->objectid,
5305                                 chunk_rec->type,
5306                                 chunk_rec->offset,
5307                                 chunk_rec->length,
5308                                 chunk_rec->offset,
5309                                 chunk_rec->type_flags);
5310                 ret = -1;
5311         }
5312
5313         length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
5314                                     chunk_rec->num_stripes);
5315         for (i = 0; i < chunk_rec->num_stripes; ++i) {
5316                 devid = chunk_rec->stripes[i].devid;
5317                 offset = chunk_rec->stripes[i].offset;
5318                 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
5319                                                        devid, offset, length);
5320                 if (dev_extent_item) {
5321                         dev_extent_rec = container_of(dev_extent_item,
5322                                                 struct device_extent_record,
5323                                                 cache);
5324                         if (dev_extent_rec->objectid != devid ||
5325                             dev_extent_rec->offset != offset ||
5326                             dev_extent_rec->chunk_offset != chunk_rec->offset ||
5327                             dev_extent_rec->length != length) {
5328                                 if (!silent)
5329                                         fprintf(stderr,
5330                                                 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
5331                                                 chunk_rec->objectid,
5332                                                 chunk_rec->type,
5333                                                 chunk_rec->offset,
5334                                                 chunk_rec->stripes[i].devid,
5335                                                 chunk_rec->stripes[i].offset,
5336                                                 dev_extent_rec->objectid,
5337                                                 dev_extent_rec->offset,
5338                                                 dev_extent_rec->length);
5339                                 ret = -1;
5340                         } else {
5341                                 list_move(&dev_extent_rec->chunk_list,
5342                                           &chunk_rec->dextents);
5343                         }
5344                 } else {
5345                         if (!silent)
5346                                 fprintf(stderr,
5347                                         "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
5348                                         chunk_rec->objectid,
5349                                         chunk_rec->type,
5350                                         chunk_rec->offset,
5351                                         chunk_rec->stripes[i].devid,
5352                                         chunk_rec->stripes[i].offset);
5353                         ret = -1;
5354                 }
5355         }
5356         return ret;
5357 }
5358
5359 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
5360 int check_chunks(struct cache_tree *chunk_cache,
5361                  struct block_group_tree *block_group_cache,
5362                  struct device_extent_tree *dev_extent_cache,
5363                  struct list_head *good, struct list_head *bad, int silent)
5364 {
5365         struct cache_extent *chunk_item;
5366         struct chunk_record *chunk_rec;
5367         struct block_group_record *bg_rec;
5368         struct device_extent_record *dext_rec;
5369         int err;
5370         int ret = 0;
5371
5372         chunk_item = first_cache_extent(chunk_cache);
5373         while (chunk_item) {
5374                 chunk_rec = container_of(chunk_item, struct chunk_record,
5375                                          cache);
5376                 err = check_chunk_refs(chunk_rec, block_group_cache,
5377                                        dev_extent_cache, silent);
5378                 if (err) {
5379                         ret = err;
5380                         if (bad)
5381                                 list_add_tail(&chunk_rec->list, bad);
5382                 } else {
5383                         if (good)
5384                                 list_add_tail(&chunk_rec->list, good);
5385                 }
5386
5387                 chunk_item = next_cache_extent(chunk_item);
5388         }
5389
5390         list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
5391                 if (!silent)
5392                         fprintf(stderr,
5393                                 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
5394                                 bg_rec->objectid,
5395                                 bg_rec->offset,
5396                                 bg_rec->flags);
5397                 if (!ret)
5398                         ret = 1;
5399         }
5400
5401         list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
5402                             chunk_list) {
5403                 if (!silent)
5404                         fprintf(stderr,
5405                                 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
5406                                 dext_rec->objectid,
5407                                 dext_rec->offset,
5408                                 dext_rec->length);
5409                 if (!ret)
5410                         ret = 1;
5411         }
5412         return ret;
5413 }
5414
5415
5416 static int check_device_used(struct device_record *dev_rec,
5417                              struct device_extent_tree *dext_cache)
5418 {
5419         struct cache_extent *cache;
5420         struct device_extent_record *dev_extent_rec;
5421         u64 total_byte = 0;
5422
5423         cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
5424         while (cache) {
5425                 dev_extent_rec = container_of(cache,
5426                                               struct device_extent_record,
5427                                               cache);
5428                 if (dev_extent_rec->objectid != dev_rec->devid)
5429                         break;
5430
5431                 list_del(&dev_extent_rec->device_list);
5432                 total_byte += dev_extent_rec->length;
5433                 cache = next_cache_extent(cache);
5434         }
5435
5436         if (total_byte != dev_rec->byte_used) {
5437                 fprintf(stderr,
5438                         "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
5439                         total_byte, dev_rec->byte_used, dev_rec->objectid,
5440                         dev_rec->type, dev_rec->offset);
5441                 return -1;
5442         } else {
5443                 return 0;
5444         }
5445 }
5446
5447 /* check btrfs_dev_item -> btrfs_dev_extent */
5448 static int check_devices(struct rb_root *dev_cache,
5449                          struct device_extent_tree *dev_extent_cache)
5450 {
5451         struct rb_node *dev_node;
5452         struct device_record *dev_rec;
5453         struct device_extent_record *dext_rec;
5454         int err;
5455         int ret = 0;
5456
5457         dev_node = rb_first(dev_cache);
5458         while (dev_node) {
5459                 dev_rec = container_of(dev_node, struct device_record, node);
5460                 err = check_device_used(dev_rec, dev_extent_cache);
5461                 if (err)
5462                         ret = err;
5463
5464                 dev_node = rb_next(dev_node);
5465         }
5466         list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
5467                             device_list) {
5468                 fprintf(stderr,
5469                         "Device extent[%llu, %llu, %llu] didn't find its device.\n",
5470                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
5471                 if (!ret)
5472                         ret = 1;
5473         }
5474         return ret;
5475 }
5476
5477 static int check_chunks_and_extents(struct btrfs_root *root)
5478 {
5479         struct rb_root dev_cache;
5480         struct cache_tree chunk_cache;
5481         struct block_group_tree block_group_cache;
5482         struct device_extent_tree dev_extent_cache;
5483         struct cache_tree extent_cache;
5484         struct cache_tree seen;
5485         struct cache_tree pending;
5486         struct cache_tree reada;
5487         struct cache_tree nodes;
5488         struct cache_tree corrupt_blocks;
5489         struct btrfs_path path;
5490         struct btrfs_key key;
5491         struct btrfs_key found_key;
5492         int ret, err = 0;
5493         u64 last = 0;
5494         struct block_info *bits;
5495         int bits_nr;
5496         struct extent_buffer *leaf;
5497         struct btrfs_trans_handle *trans = NULL;
5498         int slot;
5499         struct btrfs_root_item ri;
5500
5501         dev_cache = RB_ROOT;
5502         cache_tree_init(&chunk_cache);
5503         block_group_tree_init(&block_group_cache);
5504         device_extent_tree_init(&dev_extent_cache);
5505
5506         cache_tree_init(&extent_cache);
5507         cache_tree_init(&seen);
5508         cache_tree_init(&pending);
5509         cache_tree_init(&nodes);
5510         cache_tree_init(&reada);
5511         cache_tree_init(&corrupt_blocks);
5512
5513         if (repair) {
5514                 trans = btrfs_start_transaction(root, 1);
5515                 if (IS_ERR(trans)) {
5516                         fprintf(stderr, "Error starting transaction\n");
5517                         return PTR_ERR(trans);
5518                 }
5519                 root->fs_info->fsck_extent_cache = &extent_cache;
5520                 root->fs_info->free_extent_hook = free_extent_hook;
5521                 root->fs_info->corrupt_blocks = &corrupt_blocks;
5522         }
5523
5524         bits_nr = 1024;
5525         bits = malloc(bits_nr * sizeof(struct block_info));
5526         if (!bits) {
5527                 perror("malloc");
5528                 exit(1);
5529         }
5530
5531 again:
5532         add_root_to_pending(root->fs_info->tree_root->node,
5533                             &extent_cache, &pending, &seen, &nodes,
5534                             &root->fs_info->tree_root->root_key);
5535
5536         add_root_to_pending(root->fs_info->chunk_root->node,
5537                             &extent_cache, &pending, &seen, &nodes,
5538                             &root->fs_info->chunk_root->root_key);
5539
5540         btrfs_init_path(&path);
5541         key.offset = 0;
5542         key.objectid = 0;
5543         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
5544         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
5545                                         &key, &path, 0, 0);
5546         BUG_ON(ret < 0);
5547         while(1) {
5548                 leaf = path.nodes[0];
5549                 slot = path.slots[0];
5550                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
5551                         ret = btrfs_next_leaf(root, &path);
5552                         if (ret != 0)
5553                                 break;
5554                         leaf = path.nodes[0];
5555                         slot = path.slots[0];
5556                 }
5557                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
5558                 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
5559                         unsigned long offset;
5560                         struct extent_buffer *buf;
5561
5562                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
5563                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
5564                         buf = read_tree_block(root->fs_info->tree_root,
5565                                               btrfs_root_bytenr(&ri),
5566                                               btrfs_level_size(root,
5567                                                btrfs_root_level(&ri)), 0);
5568                         add_root_to_pending(buf, &extent_cache, &pending,
5569                                             &seen, &nodes, &found_key);
5570                         free_extent_buffer(buf);
5571                 }
5572                 path.slots[0]++;
5573         }
5574         btrfs_release_path(&path);
5575         while(1) {
5576                 ret = run_next_block(root, bits, bits_nr, &last, &pending,
5577                                      &seen, &reada, &nodes, &extent_cache,
5578                                      &chunk_cache, &dev_cache,
5579                                      &block_group_cache, &dev_extent_cache);
5580                 if (ret != 0)
5581                         break;
5582         }
5583
5584         ret = check_extent_refs(trans, root, &extent_cache);
5585         if (ret == -EAGAIN) {
5586                 ret = btrfs_commit_transaction(trans, root);
5587                 if (ret)
5588                         goto out;
5589
5590                 trans = btrfs_start_transaction(root, 1);
5591                 if (IS_ERR(trans)) {
5592                         ret = PTR_ERR(trans);
5593                         goto out;
5594                 }
5595
5596                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
5597                 free_extent_cache_tree(&seen);
5598                 free_extent_cache_tree(&pending);
5599                 free_extent_cache_tree(&reada);
5600                 free_extent_cache_tree(&nodes);
5601                 free_extent_record_cache(root->fs_info, &extent_cache);
5602                 goto again;
5603         }
5604
5605         err = check_chunks(&chunk_cache, &block_group_cache,
5606                            &dev_extent_cache, NULL, NULL, 0);
5607         if (err && !ret)
5608                 ret = err;
5609
5610         err = check_devices(&dev_cache, &dev_extent_cache);
5611         if (err && !ret)
5612                 ret = err;
5613
5614         if (trans) {
5615                 err = btrfs_commit_transaction(trans, root);
5616                 if (!ret)
5617                         ret = err;
5618         }
5619 out:
5620         if (repair) {
5621                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
5622                 root->fs_info->fsck_extent_cache = NULL;
5623                 root->fs_info->free_extent_hook = NULL;
5624                 root->fs_info->corrupt_blocks = NULL;
5625         }
5626         free(bits);
5627         free_chunk_cache_tree(&chunk_cache);
5628         free_device_cache_tree(&dev_cache);
5629         free_block_group_tree(&block_group_cache);
5630         free_device_extent_tree(&dev_extent_cache);
5631         return ret;
5632 }
5633
5634 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
5635                            struct btrfs_root *root, int overwrite)
5636 {
5637         struct extent_buffer *c;
5638         struct extent_buffer *old = root->node;
5639         int level;
5640         struct btrfs_disk_key disk_key = {0,0,0};
5641
5642         level = 0;
5643
5644         if (overwrite) {
5645                 c = old;
5646                 extent_buffer_get(c);
5647                 goto init;
5648         }
5649         c = btrfs_alloc_free_block(trans, root,
5650                                    btrfs_level_size(root, 0),
5651                                    root->root_key.objectid,
5652                                    &disk_key, level, 0, 0);
5653         if (IS_ERR(c)) {
5654                 c = old;
5655                 extent_buffer_get(c);
5656         }
5657 init:
5658         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
5659         btrfs_set_header_level(c, level);
5660         btrfs_set_header_bytenr(c, c->start);
5661         btrfs_set_header_generation(c, trans->transid);
5662         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
5663         btrfs_set_header_owner(c, root->root_key.objectid);
5664
5665         write_extent_buffer(c, root->fs_info->fsid,
5666                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
5667
5668         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
5669                             (unsigned long)btrfs_header_chunk_tree_uuid(c),
5670                             BTRFS_UUID_SIZE);
5671
5672         btrfs_mark_buffer_dirty(c);
5673
5674         free_extent_buffer(old);
5675         root->node = c;
5676         add_root_to_dirty_list(root);
5677         return 0;
5678 }
5679
5680 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
5681                                 struct extent_buffer *eb, int tree_root)
5682 {
5683         struct extent_buffer *tmp;
5684         struct btrfs_root_item *ri;
5685         struct btrfs_key key;
5686         u64 bytenr;
5687         u32 leafsize;
5688         int level = btrfs_header_level(eb);
5689         int nritems;
5690         int ret;
5691         int i;
5692
5693         btrfs_pin_extent(fs_info, eb->start, eb->len);
5694
5695         leafsize = btrfs_super_leafsize(fs_info->super_copy);
5696         nritems = btrfs_header_nritems(eb);
5697         for (i = 0; i < nritems; i++) {
5698                 if (level == 0) {
5699                         btrfs_item_key_to_cpu(eb, &key, i);
5700                         if (key.type != BTRFS_ROOT_ITEM_KEY)
5701                                 continue;
5702                         /* Skip the extent root and reloc roots */
5703                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
5704                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5705                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
5706                                 continue;
5707                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
5708                         bytenr = btrfs_disk_root_bytenr(eb, ri);
5709
5710                         /*
5711                          * If at any point we start needing the real root we
5712                          * will have to build a stump root for the root we are
5713                          * in, but for now this doesn't actually use the root so
5714                          * just pass in extent_root.
5715                          */
5716                         tmp = read_tree_block(fs_info->extent_root, bytenr,
5717                                               leafsize, 0);
5718                         if (!tmp) {
5719                                 fprintf(stderr, "Error reading root block\n");
5720                                 return -EIO;
5721                         }
5722                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
5723                         free_extent_buffer(tmp);
5724                         if (ret)
5725                                 return ret;
5726                 } else {
5727                         bytenr = btrfs_node_blockptr(eb, i);
5728
5729                         /* If we aren't the tree root don't read the block */
5730                         if (level == 1 && !tree_root) {
5731                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
5732                                 continue;
5733                         }
5734
5735                         tmp = read_tree_block(fs_info->extent_root, bytenr,
5736                                               leafsize, 0);
5737                         if (!tmp) {
5738                                 fprintf(stderr, "Error reading tree block\n");
5739                                 return -EIO;
5740                         }
5741                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
5742                         free_extent_buffer(tmp);
5743                         if (ret)
5744                                 return ret;
5745                 }
5746         }
5747
5748         return 0;
5749 }
5750
5751 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
5752 {
5753         int ret;
5754
5755         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
5756         if (ret)
5757                 return ret;
5758
5759         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
5760 }
5761
5762 static int reset_block_groups(struct btrfs_fs_info *fs_info)
5763 {
5764         struct btrfs_path *path;
5765         struct extent_buffer *leaf;
5766         struct btrfs_chunk *chunk;
5767         struct btrfs_key key;
5768         int ret;
5769
5770         path = btrfs_alloc_path();
5771         if (!path)
5772                 return -ENOMEM;
5773
5774         key.objectid = 0;
5775         key.type = BTRFS_CHUNK_ITEM_KEY;
5776         key.offset = 0;
5777
5778         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
5779         if (ret < 0) {
5780                 btrfs_free_path(path);
5781                 return ret;
5782         }
5783
5784         /*
5785          * We do this in case the block groups were screwed up and had alloc
5786          * bits that aren't actually set on the chunks.  This happens with
5787          * restored images every time and could happen in real life I guess.
5788          */
5789         fs_info->avail_data_alloc_bits = 0;
5790         fs_info->avail_metadata_alloc_bits = 0;
5791         fs_info->avail_system_alloc_bits = 0;
5792
5793         /* First we need to create the in-memory block groups */
5794         while (1) {
5795                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5796                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
5797                         if (ret < 0) {
5798                                 btrfs_free_path(path);
5799                                 return ret;
5800                         }
5801                         if (ret) {
5802                                 ret = 0;
5803                                 break;
5804                         }
5805                 }
5806                 leaf = path->nodes[0];
5807                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5808                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
5809                         path->slots[0]++;
5810                         continue;
5811                 }
5812
5813                 chunk = btrfs_item_ptr(leaf, path->slots[0],
5814                                        struct btrfs_chunk);
5815                 btrfs_add_block_group(fs_info, 0,
5816                                       btrfs_chunk_type(leaf, chunk),
5817                                       key.objectid, key.offset,
5818                                       btrfs_chunk_length(leaf, chunk));
5819                 path->slots[0]++;
5820         }
5821
5822         btrfs_free_path(path);
5823         return 0;
5824 }
5825
5826 static int reset_balance(struct btrfs_trans_handle *trans,
5827                          struct btrfs_fs_info *fs_info)
5828 {
5829         struct btrfs_root *root = fs_info->tree_root;
5830         struct btrfs_path *path;
5831         struct extent_buffer *leaf;
5832         struct btrfs_key key;
5833         int del_slot, del_nr = 0;
5834         int ret;
5835         int found = 0;
5836
5837         path = btrfs_alloc_path();
5838         if (!path)
5839                 return -ENOMEM;
5840
5841         key.objectid = BTRFS_BALANCE_OBJECTID;
5842         key.type = BTRFS_BALANCE_ITEM_KEY;
5843         key.offset = 0;
5844
5845         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5846         if (ret) {
5847                 if (ret > 0)
5848                         ret = 0;
5849                 goto out;
5850         }
5851
5852         ret = btrfs_del_item(trans, root, path);
5853         if (ret)
5854                 goto out;
5855         btrfs_release_path(path);
5856
5857         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
5858         key.type = BTRFS_ROOT_ITEM_KEY;
5859         key.offset = 0;
5860
5861         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5862         if (ret < 0)
5863                 goto out;
5864         while (1) {
5865                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5866                         if (!found)
5867                                 break;
5868
5869                         if (del_nr) {
5870                                 ret = btrfs_del_items(trans, root, path,
5871                                                       del_slot, del_nr);
5872                                 del_nr = 0;
5873                                 if (ret)
5874                                         goto out;
5875                         }
5876                         key.offset++;
5877                         btrfs_release_path(path);
5878
5879                         found = 0;
5880                         ret = btrfs_search_slot(trans, root, &key, path,
5881                                                 -1, 1);
5882                         if (ret < 0)
5883                                 goto out;
5884                         continue;
5885                 }
5886                 found = 1;
5887                 leaf = path->nodes[0];
5888                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5889                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
5890                         break;
5891                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5892                         path->slots[0]++;
5893                         continue;
5894                 }
5895                 if (!del_nr) {
5896                         del_slot = path->slots[0];
5897                         del_nr = 1;
5898                 } else {
5899                         del_nr++;
5900                 }
5901                 path->slots[0]++;
5902         }
5903
5904         if (del_nr) {
5905                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
5906                 if (ret)
5907                         goto out;
5908         }
5909         btrfs_release_path(path);
5910
5911         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
5912         key.type = BTRFS_ROOT_ITEM_KEY;
5913         key.offset = (u64)-1;
5914         root = btrfs_read_fs_root(fs_info, &key);
5915         if (IS_ERR(root)) {
5916                 fprintf(stderr, "Error reading data reloc tree\n");
5917                 return PTR_ERR(root);
5918         }
5919         root->track_dirty = 1;
5920         if (root->last_trans != trans->transid) {
5921                 root->last_trans = trans->transid;
5922                 root->commit_root = root->node;
5923                 extent_buffer_get(root->node);
5924         }
5925         ret = btrfs_fsck_reinit_root(trans, root, 0);
5926 out:
5927         btrfs_free_path(path);
5928         return ret;
5929 }
5930
5931 static int reinit_extent_tree(struct btrfs_fs_info *fs_info)
5932 {
5933         struct btrfs_trans_handle *trans;
5934         u64 start = 0;
5935         int ret;
5936
5937         /*
5938          * The only reason we don't do this is because right now we're just
5939          * walking the trees we find and pinning down their bytes, we don't look
5940          * at any of the leaves.  In order to do mixed groups we'd have to check
5941          * the leaves of any fs roots and pin down the bytes for any file
5942          * extents we find.  Not hard but why do it if we don't have to?
5943          */
5944         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
5945                 fprintf(stderr, "We don't support re-initing the extent tree "
5946                         "for mixed block groups yet, please notify a btrfs "
5947                         "developer you want to do this so they can add this "
5948                         "functionality.\n");
5949                 return -EINVAL;
5950         }
5951
5952         trans = btrfs_start_transaction(fs_info->extent_root, 1);
5953         if (IS_ERR(trans)) {
5954                 fprintf(stderr, "Error starting transaction\n");
5955                 return PTR_ERR(trans);
5956         }
5957
5958         /*
5959          * first we need to walk all of the trees except the extent tree and pin
5960          * down the bytes that are in use so we don't overwrite any existing
5961          * metadata.
5962          */
5963         ret = pin_metadata_blocks(fs_info);
5964         if (ret) {
5965                 fprintf(stderr, "error pinning down used bytes\n");
5966                 return ret;
5967         }
5968
5969         /*
5970          * Need to drop all the block groups since we're going to recreate all
5971          * of them again.
5972          */
5973         btrfs_free_block_groups(fs_info);
5974         ret = reset_block_groups(fs_info);
5975         if (ret) {
5976                 fprintf(stderr, "error resetting the block groups\n");
5977                 return ret;
5978         }
5979
5980         /* Ok we can allocate now, reinit the extent root */
5981         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 1);
5982         if (ret) {
5983                 fprintf(stderr, "extent root initialization failed\n");
5984                 /*
5985                  * When the transaction code is updated we should end the
5986                  * transaction, but for now progs only knows about commit so
5987                  * just return an error.
5988                  */
5989                 return ret;
5990         }
5991
5992         ret = reset_balance(trans, fs_info);
5993         if (ret) {
5994                 fprintf(stderr, "error reseting the pending balance\n");
5995                 return ret;
5996         }
5997
5998         /*
5999          * Now we have all the in-memory block groups setup so we can make
6000          * allocations properly, and the metadata we care about is safe since we
6001          * pinned all of it above.
6002          */
6003         while (1) {
6004                 struct btrfs_block_group_cache *cache;
6005
6006                 cache = btrfs_lookup_first_block_group(fs_info, start);
6007                 if (!cache)
6008                         break;
6009                 start = cache->key.objectid + cache->key.offset;
6010                 ret = btrfs_insert_item(trans, fs_info->extent_root,
6011                                         &cache->key, &cache->item,
6012                                         sizeof(cache->item));
6013                 if (ret) {
6014                         fprintf(stderr, "Error adding block group\n");
6015                         return ret;
6016                 }
6017                 btrfs_extent_post_op(trans, fs_info->extent_root);
6018         }
6019
6020         /*
6021          * Ok now we commit and run the normal fsck, which will add extent
6022          * entries for all of the items it finds.
6023          */
6024         return btrfs_commit_transaction(trans, fs_info->extent_root);
6025 }
6026
6027 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
6028 {
6029         struct btrfs_path *path;
6030         struct btrfs_trans_handle *trans;
6031         struct btrfs_key key;
6032         int ret;
6033
6034         printf("Recowing metadata block %llu\n", eb->start);
6035         key.objectid = btrfs_header_owner(eb);
6036         key.type = BTRFS_ROOT_ITEM_KEY;
6037         key.offset = (u64)-1;
6038
6039         root = btrfs_read_fs_root(root->fs_info, &key);
6040         if (IS_ERR(root)) {
6041                 fprintf(stderr, "Couldn't find owner root %llu\n",
6042                         key.objectid);
6043                 return PTR_ERR(root);
6044         }
6045
6046         path = btrfs_alloc_path();
6047         if (!path)
6048                 return -ENOMEM;
6049
6050         trans = btrfs_start_transaction(root, 1);
6051         if (IS_ERR(trans)) {
6052                 btrfs_free_path(path);
6053                 return PTR_ERR(trans);
6054         }
6055
6056         path->lowest_level = btrfs_header_level(eb);
6057         if (path->lowest_level)
6058                 btrfs_node_key_to_cpu(eb, &key, 0);
6059         else
6060                 btrfs_item_key_to_cpu(eb, &key, 0);
6061
6062         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6063         btrfs_commit_transaction(trans, root);
6064         btrfs_free_path(path);
6065         return ret;
6066 }
6067
6068 static struct option long_options[] = {
6069         { "super", 1, NULL, 's' },
6070         { "repair", 0, NULL, 0 },
6071         { "init-csum-tree", 0, NULL, 0 },
6072         { "init-extent-tree", 0, NULL, 0 },
6073         { NULL, 0, NULL, 0}
6074 };
6075
6076 const char * const cmd_check_usage[] = {
6077         "btrfs check [options] <device>",
6078         "Check an unmounted btrfs filesystem.",
6079         "",
6080         "-s|--super <superblock>     use this superblock copy",
6081         "--repair                    try to repair the filesystem",
6082         "--init-csum-tree            create a new CRC tree",
6083         "--init-extent-tree          create a new extent tree",
6084         NULL
6085 };
6086
6087 int cmd_check(int argc, char **argv)
6088 {
6089         struct cache_tree root_cache;
6090         struct btrfs_root *root;
6091         struct btrfs_fs_info *info;
6092         u64 bytenr = 0;
6093         char uuidbuf[37];
6094         int ret;
6095         int num;
6096         int option_index = 0;
6097         int init_csum_tree = 0;
6098         int init_extent_tree = 0;
6099         int rw = 0;
6100
6101         while(1) {
6102                 int c;
6103                 c = getopt_long(argc, argv, "as:", long_options,
6104                                 &option_index);
6105                 if (c < 0)
6106                         break;
6107                 switch(c) {
6108                         case 'a': /* ignored */ break;
6109                         case 's':
6110                                 num = atol(optarg);
6111                                 bytenr = btrfs_sb_offset(num);
6112                                 printf("using SB copy %d, bytenr %llu\n", num,
6113                                        (unsigned long long)bytenr);
6114                                 break;
6115                         case '?':
6116                         case 'h':
6117                                 usage(cmd_check_usage);
6118                 }
6119                 if (option_index == 1) {
6120                         printf("enabling repair mode\n");
6121                         repair = 1;
6122                         rw = 1;
6123                 } else if (option_index == 2) {
6124                         printf("Creating a new CRC tree\n");
6125                         init_csum_tree = 1;
6126                         rw = 1;
6127                 } else if (option_index == 3) {
6128                         init_extent_tree = 1;
6129                         rw = 1;
6130                         repair = 1;
6131                 }
6132
6133         }
6134         argc = argc - optind;
6135
6136         if (argc != 1)
6137                 usage(cmd_check_usage);
6138
6139         radix_tree_init();
6140         cache_tree_init(&root_cache);
6141
6142         if((ret = check_mounted(argv[optind])) < 0) {
6143                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
6144                 return ret;
6145         } else if(ret) {
6146                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
6147                 return -EBUSY;
6148         }
6149
6150         info = open_ctree_fs_info(argv[optind], bytenr, 0, rw, 1);
6151         if (!info) {
6152                 fprintf(stderr, "Couldn't open file system\n");
6153                 return -EIO;
6154         }
6155
6156         uuid_unparse(info->super_copy->fsid, uuidbuf);
6157         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
6158
6159         if (!extent_buffer_uptodate(info->tree_root->node) ||
6160             !extent_buffer_uptodate(info->dev_root->node) ||
6161             !extent_buffer_uptodate(info->extent_root->node) ||
6162             !extent_buffer_uptodate(info->chunk_root->node)) {
6163                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
6164                 return -EIO;
6165         }
6166
6167         root = info->fs_root;
6168
6169         if (init_extent_tree) {
6170                 printf("Creating a new extent tree\n");
6171                 ret = reinit_extent_tree(info);
6172                 if (ret)
6173                         return ret;
6174         }
6175         fprintf(stderr, "checking extents\n");
6176         if (init_csum_tree) {
6177                 struct btrfs_trans_handle *trans;
6178
6179                 fprintf(stderr, "Reinit crc root\n");
6180                 trans = btrfs_start_transaction(info->csum_root, 1);
6181                 if (IS_ERR(trans)) {
6182                         fprintf(stderr, "Error starting transaction\n");
6183                         return PTR_ERR(trans);
6184                 }
6185
6186                 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
6187                 if (ret) {
6188                         fprintf(stderr, "crc root initialization failed\n");
6189                         return -EIO;
6190                 }
6191
6192                 ret = btrfs_commit_transaction(trans, info->csum_root);
6193                 if (ret)
6194                         exit(1);
6195                 goto out;
6196         }
6197         ret = check_chunks_and_extents(root);
6198         if (ret)
6199                 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
6200
6201         fprintf(stderr, "checking free space cache\n");
6202         ret = check_space_cache(root);
6203         if (ret)
6204                 goto out;
6205
6206         fprintf(stderr, "checking fs roots\n");
6207         ret = check_fs_roots(root, &root_cache);
6208         if (ret)
6209                 goto out;
6210
6211         fprintf(stderr, "checking csums\n");
6212         ret = check_csums(root);
6213         if (ret)
6214                 goto out;
6215
6216         fprintf(stderr, "checking root refs\n");
6217         ret = check_root_refs(root, &root_cache);
6218         if (ret)
6219                 goto out;
6220
6221         while (repair && !list_empty(&root->fs_info->recow_ebs)) {
6222                 struct extent_buffer *eb;
6223
6224                 eb = list_first_entry(&root->fs_info->recow_ebs,
6225                                       struct extent_buffer, recow);
6226                 ret = recow_extent_buffer(root, eb);
6227                 if (ret)
6228                         break;
6229         }
6230
6231         if (!list_empty(&root->fs_info->recow_ebs)) {
6232                 fprintf(stderr, "Transid errors in file system\n");
6233                 ret = 1;
6234         }
6235 out:
6236         free_root_recs_tree(&root_cache);
6237         close_ctree(root);
6238
6239         if (found_old_backref) { /*
6240                  * there was a disk format change when mixed
6241                  * backref was in testing tree. The old format
6242                  * existed about one week.
6243                  */
6244                 printf("\n * Found old mixed backref format. "
6245                        "The old format is not supported! *"
6246                        "\n * Please mount the FS in readonly mode, "
6247                        "backup data and re-format the FS. *\n\n");
6248                 ret = 1;
6249         }
6250         printf("found %llu bytes used err is %d\n",
6251                (unsigned long long)bytes_used, ret);
6252         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
6253         printf("total tree bytes: %llu\n",
6254                (unsigned long long)total_btree_bytes);
6255         printf("total fs tree bytes: %llu\n",
6256                (unsigned long long)total_fs_tree_bytes);
6257         printf("total extent tree bytes: %llu\n",
6258                (unsigned long long)total_extent_tree_bytes);
6259         printf("btree space waste bytes: %llu\n",
6260                (unsigned long long)btree_space_waste);
6261         printf("file data blocks allocated: %llu\n referenced %llu\n",
6262                 (unsigned long long)data_bytes_allocated,
6263                 (unsigned long long)data_bytes_referenced);
6264         printf("%s\n", BTRFS_BUILD_VERSION);
6265         return ret;
6266 }