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