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