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