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