Btrfs-progs: break out rbtree util functions
[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;
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         key.offset = 0;
2257         key.objectid = 0;
2258         key.type = BTRFS_ROOT_ITEM_KEY;
2259         ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
2260         if (ret < 0) {
2261                 err = 1;
2262                 goto out;
2263         }
2264         while (1) {
2265                 leaf = path.nodes[0];
2266                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
2267                         ret = btrfs_next_leaf(tree_root, &path);
2268                         if (ret) {
2269                                 if (ret < 0)
2270                                         err = 1;
2271                                 break;
2272                         }
2273                         leaf = path.nodes[0];
2274                 }
2275                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
2276                 if (key.type == BTRFS_ROOT_ITEM_KEY &&
2277                     fs_root_objectid(key.objectid)) {
2278                         if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
2279                                 tmp_root = btrfs_read_fs_root_no_cache(
2280                                                 root->fs_info, &key);
2281                         } else {
2282                                 key.offset = (u64)-1;
2283                                 tmp_root = btrfs_read_fs_root(
2284                                                 root->fs_info, &key);
2285                         }
2286                         if (IS_ERR(tmp_root)) {
2287                                 err = 1;
2288                                 goto next;
2289                         }
2290                         ret = check_fs_root(tmp_root, root_cache, &wc);
2291                         if (ret)
2292                                 err = 1;
2293                         if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
2294                                 btrfs_free_fs_root(tmp_root);
2295                 } else if (key.type == BTRFS_ROOT_REF_KEY ||
2296                            key.type == BTRFS_ROOT_BACKREF_KEY) {
2297                         process_root_ref(leaf, path.slots[0], &key,
2298                                          root_cache);
2299                 }
2300 next:
2301                 path.slots[0]++;
2302         }
2303 out:
2304         btrfs_release_path(&path);
2305         if (err)
2306                 free_extent_cache_tree(&wc.shared);
2307         if (!cache_tree_empty(&wc.shared))
2308                 fprintf(stderr, "warning line %d\n", __LINE__);
2309
2310         return err;
2311 }
2312
2313 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
2314 {
2315         struct list_head *cur = rec->backrefs.next;
2316         struct extent_backref *back;
2317         struct tree_backref *tback;
2318         struct data_backref *dback;
2319         u64 found = 0;
2320         int err = 0;
2321
2322         while(cur != &rec->backrefs) {
2323                 back = list_entry(cur, struct extent_backref, list);
2324                 cur = cur->next;
2325                 if (!back->found_extent_tree) {
2326                         err = 1;
2327                         if (!print_errs)
2328                                 goto out;
2329                         if (back->is_data) {
2330                                 dback = (struct data_backref *)back;
2331                                 fprintf(stderr, "Backref %llu %s %llu"
2332                                         " owner %llu offset %llu num_refs %lu"
2333                                         " not found in extent tree\n",
2334                                         (unsigned long long)rec->start,
2335                                         back->full_backref ?
2336                                         "parent" : "root",
2337                                         back->full_backref ?
2338                                         (unsigned long long)dback->parent:
2339                                         (unsigned long long)dback->root,
2340                                         (unsigned long long)dback->owner,
2341                                         (unsigned long long)dback->offset,
2342                                         (unsigned long)dback->num_refs);
2343                         } else {
2344                                 tback = (struct tree_backref *)back;
2345                                 fprintf(stderr, "Backref %llu parent %llu"
2346                                         " root %llu not found in extent tree\n",
2347                                         (unsigned long long)rec->start,
2348                                         (unsigned long long)tback->parent,
2349                                         (unsigned long long)tback->root);
2350                         }
2351                 }
2352                 if (!back->is_data && !back->found_ref) {
2353                         err = 1;
2354                         if (!print_errs)
2355                                 goto out;
2356                         tback = (struct tree_backref *)back;
2357                         fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
2358                                 (unsigned long long)rec->start,
2359                                 back->full_backref ? "parent" : "root",
2360                                 back->full_backref ?
2361                                 (unsigned long long)tback->parent :
2362                                 (unsigned long long)tback->root, back);
2363                 }
2364                 if (back->is_data) {
2365                         dback = (struct data_backref *)back;
2366                         if (dback->found_ref != dback->num_refs) {
2367                                 err = 1;
2368                                 if (!print_errs)
2369                                         goto out;
2370                                 fprintf(stderr, "Incorrect local backref count"
2371                                         " on %llu %s %llu owner %llu"
2372                                         " offset %llu found %u wanted %u back %p\n",
2373                                         (unsigned long long)rec->start,
2374                                         back->full_backref ?
2375                                         "parent" : "root",
2376                                         back->full_backref ?
2377                                         (unsigned long long)dback->parent:
2378                                         (unsigned long long)dback->root,
2379                                         (unsigned long long)dback->owner,
2380                                         (unsigned long long)dback->offset,
2381                                         dback->found_ref, dback->num_refs, back);
2382                         }
2383                         if (dback->disk_bytenr != rec->start) {
2384                                 err = 1;
2385                                 if (!print_errs)
2386                                         goto out;
2387                                 fprintf(stderr, "Backref disk bytenr does not"
2388                                         " match extent record, bytenr=%llu, "
2389                                         "ref bytenr=%llu\n",
2390                                         (unsigned long long)rec->start,
2391                                         (unsigned long long)dback->disk_bytenr);
2392                         }
2393
2394                         if (dback->bytes != rec->nr) {
2395                                 err = 1;
2396                                 if (!print_errs)
2397                                         goto out;
2398                                 fprintf(stderr, "Backref bytes do not match "
2399                                         "extent backref, bytenr=%llu, ref "
2400                                         "bytes=%llu, backref bytes=%llu\n",
2401                                         (unsigned long long)rec->start,
2402                                         (unsigned long long)rec->nr,
2403                                         (unsigned long long)dback->bytes);
2404                         }
2405                 }
2406                 if (!back->is_data) {
2407                         found += 1;
2408                 } else {
2409                         dback = (struct data_backref *)back;
2410                         found += dback->found_ref;
2411                 }
2412         }
2413         if (found != rec->refs) {
2414                 err = 1;
2415                 if (!print_errs)
2416                         goto out;
2417                 fprintf(stderr, "Incorrect global backref count "
2418                         "on %llu found %llu wanted %llu\n",
2419                         (unsigned long long)rec->start,
2420                         (unsigned long long)found,
2421                         (unsigned long long)rec->refs);
2422         }
2423 out:
2424         return err;
2425 }
2426
2427 static int free_all_extent_backrefs(struct extent_record *rec)
2428 {
2429         struct extent_backref *back;
2430         struct list_head *cur;
2431         while (!list_empty(&rec->backrefs)) {
2432                 cur = rec->backrefs.next;
2433                 back = list_entry(cur, struct extent_backref, list);
2434                 list_del(cur);
2435                 free(back);
2436         }
2437         return 0;
2438 }
2439
2440 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
2441                                      struct cache_tree *extent_cache)
2442 {
2443         struct cache_extent *cache;
2444         struct extent_record *rec;
2445
2446         while (1) {
2447                 cache = first_cache_extent(extent_cache);
2448                 if (!cache)
2449                         break;
2450                 rec = container_of(cache, struct extent_record, cache);
2451                 btrfs_unpin_extent(fs_info, rec->start, rec->max_size);
2452                 remove_cache_extent(extent_cache, cache);
2453                 free_all_extent_backrefs(rec);
2454                 free(rec);
2455         }
2456 }
2457
2458 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
2459                                  struct extent_record *rec)
2460 {
2461         if (rec->content_checked && rec->owner_ref_checked &&
2462             rec->extent_item_refs == rec->refs && rec->refs > 0 &&
2463             rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
2464                 remove_cache_extent(extent_cache, &rec->cache);
2465                 free_all_extent_backrefs(rec);
2466                 list_del_init(&rec->list);
2467                 free(rec);
2468         }
2469         return 0;
2470 }
2471
2472 static int check_owner_ref(struct btrfs_root *root,
2473                             struct extent_record *rec,
2474                             struct extent_buffer *buf)
2475 {
2476         struct extent_backref *node;
2477         struct tree_backref *back;
2478         struct btrfs_root *ref_root;
2479         struct btrfs_key key;
2480         struct btrfs_path path;
2481         struct extent_buffer *parent;
2482         int level;
2483         int found = 0;
2484         int ret;
2485
2486         list_for_each_entry(node, &rec->backrefs, list) {
2487                 if (node->is_data)
2488                         continue;
2489                 if (!node->found_ref)
2490                         continue;
2491                 if (node->full_backref)
2492                         continue;
2493                 back = (struct tree_backref *)node;
2494                 if (btrfs_header_owner(buf) == back->root)
2495                         return 0;
2496         }
2497         BUG_ON(rec->is_root);
2498
2499         /* try to find the block by search corresponding fs tree */
2500         key.objectid = btrfs_header_owner(buf);
2501         key.type = BTRFS_ROOT_ITEM_KEY;
2502         key.offset = (u64)-1;
2503
2504         ref_root = btrfs_read_fs_root(root->fs_info, &key);
2505         if (IS_ERR(ref_root))
2506                 return 1;
2507
2508         level = btrfs_header_level(buf);
2509         if (level == 0)
2510                 btrfs_item_key_to_cpu(buf, &key, 0);
2511         else
2512                 btrfs_node_key_to_cpu(buf, &key, 0);
2513
2514         btrfs_init_path(&path);
2515         path.lowest_level = level + 1;
2516         ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
2517         if (ret < 0)
2518                 return 0;
2519
2520         parent = path.nodes[level + 1];
2521         if (parent && buf->start == btrfs_node_blockptr(parent,
2522                                                         path.slots[level + 1]))
2523                 found = 1;
2524
2525         btrfs_release_path(&path);
2526         return found ? 0 : 1;
2527 }
2528
2529 static int is_extent_tree_record(struct extent_record *rec)
2530 {
2531         struct list_head *cur = rec->backrefs.next;
2532         struct extent_backref *node;
2533         struct tree_backref *back;
2534         int is_extent = 0;
2535
2536         while(cur != &rec->backrefs) {
2537                 node = list_entry(cur, struct extent_backref, list);
2538                 cur = cur->next;
2539                 if (node->is_data)
2540                         return 0;
2541                 back = (struct tree_backref *)node;
2542                 if (node->full_backref)
2543                         return 0;
2544                 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
2545                         is_extent = 1;
2546         }
2547         return is_extent;
2548 }
2549
2550
2551 static int record_bad_block_io(struct btrfs_fs_info *info,
2552                                struct cache_tree *extent_cache,
2553                                u64 start, u64 len)
2554 {
2555         struct extent_record *rec;
2556         struct cache_extent *cache;
2557         struct btrfs_key key;
2558
2559         cache = lookup_cache_extent(extent_cache, start, len);
2560         if (!cache)
2561                 return 0;
2562
2563         rec = container_of(cache, struct extent_record, cache);
2564         if (!is_extent_tree_record(rec))
2565                 return 0;
2566
2567         btrfs_disk_key_to_cpu(&key, &rec->parent_key);
2568         return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
2569 }
2570
2571 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
2572                        struct extent_buffer *buf, int slot)
2573 {
2574         if (btrfs_header_level(buf)) {
2575                 struct btrfs_key_ptr ptr1, ptr2;
2576
2577                 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
2578                                    sizeof(struct btrfs_key_ptr));
2579                 read_extent_buffer(buf, &ptr2,
2580                                    btrfs_node_key_ptr_offset(slot + 1),
2581                                    sizeof(struct btrfs_key_ptr));
2582                 write_extent_buffer(buf, &ptr1,
2583                                     btrfs_node_key_ptr_offset(slot + 1),
2584                                     sizeof(struct btrfs_key_ptr));
2585                 write_extent_buffer(buf, &ptr2,
2586                                     btrfs_node_key_ptr_offset(slot),
2587                                     sizeof(struct btrfs_key_ptr));
2588                 if (slot == 0) {
2589                         struct btrfs_disk_key key;
2590                         btrfs_node_key(buf, &key, 0);
2591                         btrfs_fixup_low_keys(root, path, &key,
2592                                              btrfs_header_level(buf) + 1);
2593                 }
2594         } else {
2595                 struct btrfs_item *item1, *item2;
2596                 struct btrfs_key k1, k2;
2597                 char *item1_data, *item2_data;
2598                 u32 item1_offset, item2_offset, item1_size, item2_size;
2599
2600                 item1 = btrfs_item_nr(slot);
2601                 item2 = btrfs_item_nr(slot + 1);
2602                 btrfs_item_key_to_cpu(buf, &k1, slot);
2603                 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
2604                 item1_offset = btrfs_item_offset(buf, item1);
2605                 item2_offset = btrfs_item_offset(buf, item2);
2606                 item1_size = btrfs_item_size(buf, item1);
2607                 item2_size = btrfs_item_size(buf, item2);
2608
2609                 item1_data = malloc(item1_size);
2610                 if (!item1_data)
2611                         return -ENOMEM;
2612                 item2_data = malloc(item2_size);
2613                 if (!item2_data) {
2614                         free(item1_data);
2615                         return -ENOMEM;
2616                 }
2617
2618                 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
2619                 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
2620
2621                 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
2622                 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
2623                 free(item1_data);
2624                 free(item2_data);
2625
2626                 btrfs_set_item_offset(buf, item1, item2_offset);
2627                 btrfs_set_item_offset(buf, item2, item1_offset);
2628                 btrfs_set_item_size(buf, item1, item2_size);
2629                 btrfs_set_item_size(buf, item2, item1_size);
2630
2631                 path->slots[0] = slot;
2632                 btrfs_set_item_key_unsafe(root, path, &k2);
2633                 path->slots[0] = slot + 1;
2634                 btrfs_set_item_key_unsafe(root, path, &k1);
2635         }
2636         return 0;
2637 }
2638
2639 /*
2640  * Attempt to fix basic block failures.  Currently we only handle bad key
2641  * orders, we will cycle through the keys and swap them if necessary.
2642  */
2643 static int try_to_fix_bad_block(struct btrfs_trans_handle *trans,
2644                                 struct btrfs_root *root,
2645                                 struct extent_buffer *buf,
2646                                 struct btrfs_disk_key *parent_key,
2647                                 enum btrfs_tree_block_status status)
2648 {
2649         struct btrfs_path *path;
2650         struct btrfs_key k1, k2;
2651         int i;
2652         int level;
2653         int ret;
2654
2655         if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
2656                 return -EIO;
2657
2658         k1.objectid = btrfs_header_owner(buf);
2659         k1.type = BTRFS_ROOT_ITEM_KEY;
2660         k1.offset = (u64)-1;
2661
2662         root = btrfs_read_fs_root(root->fs_info, &k1);
2663         if (IS_ERR(root))
2664                 return -EIO;
2665
2666         record_root_in_trans(trans, root);
2667
2668         path = btrfs_alloc_path();
2669         if (!path)
2670                 return -EIO;
2671
2672         level = btrfs_header_level(buf);
2673         path->lowest_level = level;
2674         path->skip_check_block = 1;
2675         if (level)
2676                 btrfs_node_key_to_cpu(buf, &k1, 0);
2677         else
2678                 btrfs_item_key_to_cpu(buf, &k1, 0);
2679
2680         ret = btrfs_search_slot(trans, root, &k1, path, 0, 1);
2681         if (ret) {
2682                 btrfs_free_path(path);
2683                 return -EIO;
2684         }
2685
2686         buf = path->nodes[level];
2687         for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
2688                 if (level) {
2689                         btrfs_node_key_to_cpu(buf, &k1, i);
2690                         btrfs_node_key_to_cpu(buf, &k2, i + 1);
2691                 } else {
2692                         btrfs_item_key_to_cpu(buf, &k1, i);
2693                         btrfs_item_key_to_cpu(buf, &k2, i + 1);
2694                 }
2695                 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
2696                         continue;
2697                 ret = swap_values(root, path, buf, i);
2698                 if (ret)
2699                         break;
2700                 btrfs_mark_buffer_dirty(buf);
2701                 i = 0;
2702         }
2703
2704         btrfs_free_path(path);
2705         return ret;
2706 }
2707
2708 static int check_block(struct btrfs_trans_handle *trans,
2709                        struct btrfs_root *root,
2710                        struct cache_tree *extent_cache,
2711                        struct extent_buffer *buf, u64 flags)
2712 {
2713         struct extent_record *rec;
2714         struct cache_extent *cache;
2715         struct btrfs_key key;
2716         enum btrfs_tree_block_status status;
2717         int ret = 0;
2718         int level;
2719
2720         cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
2721         if (!cache)
2722                 return 1;
2723         rec = container_of(cache, struct extent_record, cache);
2724         rec->generation = btrfs_header_generation(buf);
2725
2726         level = btrfs_header_level(buf);
2727         if (btrfs_header_nritems(buf) > 0) {
2728
2729                 if (level == 0)
2730                         btrfs_item_key_to_cpu(buf, &key, 0);
2731                 else
2732                         btrfs_node_key_to_cpu(buf, &key, 0);
2733
2734                 rec->info_objectid = key.objectid;
2735         }
2736         rec->info_level = level;
2737
2738         if (btrfs_is_leaf(buf))
2739                 status = btrfs_check_leaf(root, &rec->parent_key, buf);
2740         else
2741                 status = btrfs_check_node(root, &rec->parent_key, buf);
2742
2743         if (status != BTRFS_TREE_BLOCK_CLEAN) {
2744                 if (repair)
2745                         status = try_to_fix_bad_block(trans, root, buf,
2746                                                       &rec->parent_key,
2747                                                       status);
2748                 if (status != BTRFS_TREE_BLOCK_CLEAN) {
2749                         ret = -EIO;
2750                         fprintf(stderr, "bad block %llu\n",
2751                                 (unsigned long long)buf->start);
2752                 } else {
2753                         /*
2754                          * Signal to callers we need to start the scan over
2755                          * again since we'll have cow'ed blocks.
2756                          */
2757                         ret = -EAGAIN;
2758                 }
2759         } else {
2760                 rec->content_checked = 1;
2761                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
2762                         rec->owner_ref_checked = 1;
2763                 else {
2764                         ret = check_owner_ref(root, rec, buf);
2765                         if (!ret)
2766                                 rec->owner_ref_checked = 1;
2767                 }
2768         }
2769         if (!ret)
2770                 maybe_free_extent_rec(extent_cache, rec);
2771         return ret;
2772 }
2773
2774 static struct tree_backref *find_tree_backref(struct extent_record *rec,
2775                                                 u64 parent, u64 root)
2776 {
2777         struct list_head *cur = rec->backrefs.next;
2778         struct extent_backref *node;
2779         struct tree_backref *back;
2780
2781         while(cur != &rec->backrefs) {
2782                 node = list_entry(cur, struct extent_backref, list);
2783                 cur = cur->next;
2784                 if (node->is_data)
2785                         continue;
2786                 back = (struct tree_backref *)node;
2787                 if (parent > 0) {
2788                         if (!node->full_backref)
2789                                 continue;
2790                         if (parent == back->parent)
2791                                 return back;
2792                 } else {
2793                         if (node->full_backref)
2794                                 continue;
2795                         if (back->root == root)
2796                                 return back;
2797                 }
2798         }
2799         return NULL;
2800 }
2801
2802 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
2803                                                 u64 parent, u64 root)
2804 {
2805         struct tree_backref *ref = malloc(sizeof(*ref));
2806         memset(&ref->node, 0, sizeof(ref->node));
2807         if (parent > 0) {
2808                 ref->parent = parent;
2809                 ref->node.full_backref = 1;
2810         } else {
2811                 ref->root = root;
2812                 ref->node.full_backref = 0;
2813         }
2814         list_add_tail(&ref->node.list, &rec->backrefs);
2815
2816         return ref;
2817 }
2818
2819 static struct data_backref *find_data_backref(struct extent_record *rec,
2820                                                 u64 parent, u64 root,
2821                                                 u64 owner, u64 offset,
2822                                                 int found_ref,
2823                                                 u64 disk_bytenr, u64 bytes)
2824 {
2825         struct list_head *cur = rec->backrefs.next;
2826         struct extent_backref *node;
2827         struct data_backref *back;
2828
2829         while(cur != &rec->backrefs) {
2830                 node = list_entry(cur, struct extent_backref, list);
2831                 cur = cur->next;
2832                 if (!node->is_data)
2833                         continue;
2834                 back = (struct data_backref *)node;
2835                 if (parent > 0) {
2836                         if (!node->full_backref)
2837                                 continue;
2838                         if (parent == back->parent)
2839                                 return back;
2840                 } else {
2841                         if (node->full_backref)
2842                                 continue;
2843                         if (back->root == root && back->owner == owner &&
2844                             back->offset == offset) {
2845                                 if (found_ref && node->found_ref &&
2846                                     (back->bytes != bytes ||
2847                                     back->disk_bytenr != disk_bytenr))
2848                                         continue;
2849                                 return back;
2850                         }
2851                 }
2852         }
2853         return NULL;
2854 }
2855
2856 static struct data_backref *alloc_data_backref(struct extent_record *rec,
2857                                                 u64 parent, u64 root,
2858                                                 u64 owner, u64 offset,
2859                                                 u64 max_size)
2860 {
2861         struct data_backref *ref = malloc(sizeof(*ref));
2862         memset(&ref->node, 0, sizeof(ref->node));
2863         ref->node.is_data = 1;
2864
2865         if (parent > 0) {
2866                 ref->parent = parent;
2867                 ref->owner = 0;
2868                 ref->offset = 0;
2869                 ref->node.full_backref = 1;
2870         } else {
2871                 ref->root = root;
2872                 ref->owner = owner;
2873                 ref->offset = offset;
2874                 ref->node.full_backref = 0;
2875         }
2876         ref->bytes = max_size;
2877         ref->found_ref = 0;
2878         ref->num_refs = 0;
2879         list_add_tail(&ref->node.list, &rec->backrefs);
2880         if (max_size > rec->max_size)
2881                 rec->max_size = max_size;
2882         return ref;
2883 }
2884
2885 static int add_extent_rec(struct cache_tree *extent_cache,
2886                           struct btrfs_key *parent_key, u64 parent_gen,
2887                           u64 start, u64 nr, u64 extent_item_refs,
2888                           int is_root, int inc_ref, int set_checked,
2889                           int metadata, int extent_rec, u64 max_size)
2890 {
2891         struct extent_record *rec;
2892         struct cache_extent *cache;
2893         int ret = 0;
2894         int dup = 0;
2895
2896         cache = lookup_cache_extent(extent_cache, start, nr);
2897         if (cache) {
2898                 rec = container_of(cache, struct extent_record, cache);
2899                 if (inc_ref)
2900                         rec->refs++;
2901                 if (rec->nr == 1)
2902                         rec->nr = max(nr, max_size);
2903
2904                 /*
2905                  * We need to make sure to reset nr to whatever the extent
2906                  * record says was the real size, this way we can compare it to
2907                  * the backrefs.
2908                  */
2909                 if (extent_rec) {
2910                         if (start != rec->start || rec->found_rec) {
2911                                 struct extent_record *tmp;
2912
2913                                 dup = 1;
2914                                 if (list_empty(&rec->list))
2915                                         list_add_tail(&rec->list,
2916                                                       &duplicate_extents);
2917
2918                                 /*
2919                                  * We have to do this song and dance in case we
2920                                  * find an extent record that falls inside of
2921                                  * our current extent record but does not have
2922                                  * the same objectid.
2923                                  */
2924                                 tmp = malloc(sizeof(*tmp));
2925                                 if (!tmp)
2926                                         return -ENOMEM;
2927                                 tmp->start = start;
2928                                 tmp->max_size = max_size;
2929                                 tmp->nr = nr;
2930                                 tmp->found_rec = 1;
2931                                 tmp->metadata = metadata;
2932                                 tmp->extent_item_refs = extent_item_refs;
2933                                 INIT_LIST_HEAD(&tmp->list);
2934                                 list_add_tail(&tmp->list, &rec->dups);
2935                                 rec->num_duplicates++;
2936                         } else {
2937                                 rec->nr = nr;
2938                                 rec->found_rec = 1;
2939                         }
2940                 }
2941
2942                 if (extent_item_refs && !dup) {
2943                         if (rec->extent_item_refs) {
2944                                 fprintf(stderr, "block %llu rec "
2945                                         "extent_item_refs %llu, passed %llu\n",
2946                                         (unsigned long long)start,
2947                                         (unsigned long long)
2948                                                         rec->extent_item_refs,
2949                                         (unsigned long long)extent_item_refs);
2950                         }
2951                         rec->extent_item_refs = extent_item_refs;
2952                 }
2953                 if (is_root)
2954                         rec->is_root = 1;
2955                 if (set_checked) {
2956                         rec->content_checked = 1;
2957                         rec->owner_ref_checked = 1;
2958                 }
2959
2960                 if (parent_key)
2961                         btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
2962                 if (parent_gen)
2963                         rec->parent_generation = parent_gen;
2964
2965                 if (rec->max_size < max_size)
2966                         rec->max_size = max_size;
2967
2968                 maybe_free_extent_rec(extent_cache, rec);
2969                 return ret;
2970         }
2971         rec = malloc(sizeof(*rec));
2972         rec->start = start;
2973         rec->max_size = max_size;
2974         rec->nr = max(nr, max_size);
2975         rec->found_rec = !!extent_rec;
2976         rec->content_checked = 0;
2977         rec->owner_ref_checked = 0;
2978         rec->num_duplicates = 0;
2979         rec->metadata = metadata;
2980         INIT_LIST_HEAD(&rec->backrefs);
2981         INIT_LIST_HEAD(&rec->dups);
2982         INIT_LIST_HEAD(&rec->list);
2983
2984         if (is_root)
2985                 rec->is_root = 1;
2986         else
2987                 rec->is_root = 0;
2988
2989         if (inc_ref)
2990                 rec->refs = 1;
2991         else
2992                 rec->refs = 0;
2993
2994         if (extent_item_refs)
2995                 rec->extent_item_refs = extent_item_refs;
2996         else
2997                 rec->extent_item_refs = 0;
2998
2999         if (parent_key)
3000                 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
3001         else
3002                 memset(&rec->parent_key, 0, sizeof(*parent_key));
3003
3004         if (parent_gen)
3005                 rec->parent_generation = parent_gen;
3006         else
3007                 rec->parent_generation = 0;
3008
3009         rec->cache.start = start;
3010         rec->cache.size = nr;
3011         ret = insert_cache_extent(extent_cache, &rec->cache);
3012         BUG_ON(ret);
3013         bytes_used += nr;
3014         if (set_checked) {
3015                 rec->content_checked = 1;
3016                 rec->owner_ref_checked = 1;
3017         }
3018         return ret;
3019 }
3020
3021 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
3022                             u64 parent, u64 root, int found_ref)
3023 {
3024         struct extent_record *rec;
3025         struct tree_backref *back;
3026         struct cache_extent *cache;
3027
3028         cache = lookup_cache_extent(extent_cache, bytenr, 1);
3029         if (!cache) {
3030                 add_extent_rec(extent_cache, NULL, 0, bytenr,
3031                                1, 0, 0, 0, 0, 1, 0, 0);
3032                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
3033                 if (!cache)
3034                         abort();
3035         }
3036
3037         rec = container_of(cache, struct extent_record, cache);
3038         if (rec->start != bytenr) {
3039                 abort();
3040         }
3041
3042         back = find_tree_backref(rec, parent, root);
3043         if (!back)
3044                 back = alloc_tree_backref(rec, parent, root);
3045
3046         if (found_ref) {
3047                 if (back->node.found_ref) {
3048                         fprintf(stderr, "Extent back ref already exists "
3049                                 "for %llu parent %llu root %llu \n",
3050                                 (unsigned long long)bytenr,
3051                                 (unsigned long long)parent,
3052                                 (unsigned long long)root);
3053                 }
3054                 back->node.found_ref = 1;
3055         } else {
3056                 if (back->node.found_extent_tree) {
3057                         fprintf(stderr, "Extent back ref already exists "
3058                                 "for %llu parent %llu root %llu \n",
3059                                 (unsigned long long)bytenr,
3060                                 (unsigned long long)parent,
3061                                 (unsigned long long)root);
3062                 }
3063                 back->node.found_extent_tree = 1;
3064         }
3065         maybe_free_extent_rec(extent_cache, rec);
3066         return 0;
3067 }
3068
3069 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
3070                             u64 parent, u64 root, u64 owner, u64 offset,
3071                             u32 num_refs, int found_ref, u64 max_size)
3072 {
3073         struct extent_record *rec;
3074         struct data_backref *back;
3075         struct cache_extent *cache;
3076
3077         cache = lookup_cache_extent(extent_cache, bytenr, 1);
3078         if (!cache) {
3079                 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
3080                                0, 0, max_size);
3081                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
3082                 if (!cache)
3083                         abort();
3084         }
3085
3086         rec = container_of(cache, struct extent_record, cache);
3087         if (rec->max_size < max_size)
3088                 rec->max_size = max_size;
3089
3090         /*
3091          * If found_ref is set then max_size is the real size and must match the
3092          * existing refs.  So if we have already found a ref then we need to
3093          * make sure that this ref matches the existing one, otherwise we need
3094          * to add a new backref so we can notice that the backrefs don't match
3095          * and we need to figure out who is telling the truth.  This is to
3096          * account for that awful fsync bug I introduced where we'd end up with
3097          * a btrfs_file_extent_item that would have its length include multiple
3098          * prealloc extents or point inside of a prealloc extent.
3099          */
3100         back = find_data_backref(rec, parent, root, owner, offset, found_ref,
3101                                  bytenr, max_size);
3102         if (!back)
3103                 back = alloc_data_backref(rec, parent, root, owner, offset,
3104                                           max_size);
3105
3106         if (found_ref) {
3107                 BUG_ON(num_refs != 1);
3108                 if (back->node.found_ref)
3109                         BUG_ON(back->bytes != max_size);
3110                 back->node.found_ref = 1;
3111                 back->found_ref += 1;
3112                 back->bytes = max_size;
3113                 back->disk_bytenr = bytenr;
3114                 rec->refs += 1;
3115                 rec->content_checked = 1;
3116                 rec->owner_ref_checked = 1;
3117         } else {
3118                 if (back->node.found_extent_tree) {
3119                         fprintf(stderr, "Extent back ref already exists "
3120                                 "for %llu parent %llu root %llu "
3121                                 "owner %llu offset %llu num_refs %lu\n",
3122                                 (unsigned long long)bytenr,
3123                                 (unsigned long long)parent,
3124                                 (unsigned long long)root,
3125                                 (unsigned long long)owner,
3126                                 (unsigned long long)offset,
3127                                 (unsigned long)num_refs);
3128                 }
3129                 back->num_refs = num_refs;
3130                 back->node.found_extent_tree = 1;
3131         }
3132         maybe_free_extent_rec(extent_cache, rec);
3133         return 0;
3134 }
3135
3136 static int add_pending(struct cache_tree *pending,
3137                        struct cache_tree *seen, u64 bytenr, u32 size)
3138 {
3139         int ret;
3140         ret = add_cache_extent(seen, bytenr, size);
3141         if (ret)
3142                 return ret;
3143         add_cache_extent(pending, bytenr, size);
3144         return 0;
3145 }
3146
3147 static int pick_next_pending(struct cache_tree *pending,
3148                         struct cache_tree *reada,
3149                         struct cache_tree *nodes,
3150                         u64 last, struct block_info *bits, int bits_nr,
3151                         int *reada_bits)
3152 {
3153         unsigned long node_start = last;
3154         struct cache_extent *cache;
3155         int ret;
3156
3157         cache = search_cache_extent(reada, 0);
3158         if (cache) {
3159                 bits[0].start = cache->start;
3160                 bits[0].size = cache->size;
3161                 *reada_bits = 1;
3162                 return 1;
3163         }
3164         *reada_bits = 0;
3165         if (node_start > 32768)
3166                 node_start -= 32768;
3167
3168         cache = search_cache_extent(nodes, node_start);
3169         if (!cache)
3170                 cache = search_cache_extent(nodes, 0);
3171
3172         if (!cache) {
3173                  cache = search_cache_extent(pending, 0);
3174                  if (!cache)
3175                          return 0;
3176                  ret = 0;
3177                  do {
3178                          bits[ret].start = cache->start;
3179                          bits[ret].size = cache->size;
3180                          cache = next_cache_extent(cache);
3181                          ret++;
3182                  } while (cache && ret < bits_nr);
3183                  return ret;
3184         }
3185
3186         ret = 0;
3187         do {
3188                 bits[ret].start = cache->start;
3189                 bits[ret].size = cache->size;
3190                 cache = next_cache_extent(cache);
3191                 ret++;
3192         } while (cache && ret < bits_nr);
3193
3194         if (bits_nr - ret > 8) {
3195                 u64 lookup = bits[0].start + bits[0].size;
3196                 struct cache_extent *next;
3197                 next = search_cache_extent(pending, lookup);
3198                 while(next) {
3199                         if (next->start - lookup > 32768)
3200                                 break;
3201                         bits[ret].start = next->start;
3202                         bits[ret].size = next->size;
3203                         lookup = next->start + next->size;
3204                         ret++;
3205                         if (ret == bits_nr)
3206                                 break;
3207                         next = next_cache_extent(next);
3208                         if (!next)
3209                                 break;
3210                 }
3211         }
3212         return ret;
3213 }
3214
3215 static void free_chunk_record(struct cache_extent *cache)
3216 {
3217         struct chunk_record *rec;
3218
3219         rec = container_of(cache, struct chunk_record, cache);
3220         free(rec);
3221 }
3222
3223 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
3224 {
3225         cache_tree_free_extents(chunk_cache, free_chunk_record);
3226 }
3227
3228 static void free_device_record(struct rb_node *node)
3229 {
3230         struct device_record *rec;
3231
3232         rec = container_of(node, struct device_record, node);
3233         free(rec);
3234 }
3235
3236 FREE_RB_BASED_TREE(device_cache, free_device_record);
3237
3238 int insert_block_group_record(struct block_group_tree *tree,
3239                               struct block_group_record *bg_rec)
3240 {
3241         int ret;
3242
3243         ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
3244         if (ret)
3245                 return ret;
3246
3247         list_add_tail(&bg_rec->list, &tree->block_groups);
3248         return 0;
3249 }
3250
3251 static void free_block_group_record(struct cache_extent *cache)
3252 {
3253         struct block_group_record *rec;
3254
3255         rec = container_of(cache, struct block_group_record, cache);
3256         free(rec);
3257 }
3258
3259 void free_block_group_tree(struct block_group_tree *tree)
3260 {
3261         cache_tree_free_extents(&tree->tree, free_block_group_record);
3262 }
3263
3264 int insert_device_extent_record(struct device_extent_tree *tree,
3265                                 struct device_extent_record *de_rec)
3266 {
3267         int ret;
3268
3269         /*
3270          * Device extent is a bit different from the other extents, because
3271          * the extents which belong to the different devices may have the
3272          * same start and size, so we need use the special extent cache
3273          * search/insert functions.
3274          */
3275         ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
3276         if (ret)
3277                 return ret;
3278
3279         list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
3280         list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
3281         return 0;
3282 }
3283
3284 static void free_device_extent_record(struct cache_extent *cache)
3285 {
3286         struct device_extent_record *rec;
3287
3288         rec = container_of(cache, struct device_extent_record, cache);
3289         free(rec);
3290 }
3291
3292 void free_device_extent_tree(struct device_extent_tree *tree)
3293 {
3294         cache_tree_free_extents(&tree->tree, free_device_extent_record);
3295 }
3296
3297 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3298 static int process_extent_ref_v0(struct cache_tree *extent_cache,
3299                                  struct extent_buffer *leaf, int slot)
3300 {
3301         struct btrfs_extent_ref_v0 *ref0;
3302         struct btrfs_key key;
3303
3304         btrfs_item_key_to_cpu(leaf, &key, slot);
3305         ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
3306         if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
3307                 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
3308         } else {
3309                 add_data_backref(extent_cache, key.objectid, key.offset, 0,
3310                                  0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
3311         }
3312         return 0;
3313 }
3314 #endif
3315
3316 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
3317                                             struct btrfs_key *key,
3318                                             int slot)
3319 {
3320         struct btrfs_chunk *ptr;
3321         struct chunk_record *rec;
3322         int num_stripes, i;
3323
3324         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3325         num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
3326
3327         rec = malloc(btrfs_chunk_record_size(num_stripes));
3328         if (!rec) {
3329                 fprintf(stderr, "memory allocation failed\n");
3330                 exit(-1);
3331         }
3332
3333         memset(rec, 0, btrfs_chunk_record_size(num_stripes));
3334
3335         INIT_LIST_HEAD(&rec->list);
3336         INIT_LIST_HEAD(&rec->dextents);
3337         rec->bg_rec = NULL;
3338
3339         rec->cache.start = key->offset;
3340         rec->cache.size = btrfs_chunk_length(leaf, ptr);
3341
3342         rec->generation = btrfs_header_generation(leaf);
3343
3344         rec->objectid = key->objectid;
3345         rec->type = key->type;
3346         rec->offset = key->offset;
3347
3348         rec->length = rec->cache.size;
3349         rec->owner = btrfs_chunk_owner(leaf, ptr);
3350         rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
3351         rec->type_flags = btrfs_chunk_type(leaf, ptr);
3352         rec->io_width = btrfs_chunk_io_width(leaf, ptr);
3353         rec->io_align = btrfs_chunk_io_align(leaf, ptr);
3354         rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
3355         rec->num_stripes = num_stripes;
3356         rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
3357
3358         for (i = 0; i < rec->num_stripes; ++i) {
3359                 rec->stripes[i].devid =
3360                         btrfs_stripe_devid_nr(leaf, ptr, i);
3361                 rec->stripes[i].offset =
3362                         btrfs_stripe_offset_nr(leaf, ptr, i);
3363                 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
3364                                 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
3365                                 BTRFS_UUID_SIZE);
3366         }
3367
3368         return rec;
3369 }
3370
3371 static int process_chunk_item(struct cache_tree *chunk_cache,
3372                               struct btrfs_key *key, struct extent_buffer *eb,
3373                               int slot)
3374 {
3375         struct chunk_record *rec;
3376         int ret = 0;
3377
3378         rec = btrfs_new_chunk_record(eb, key, slot);
3379         ret = insert_cache_extent(chunk_cache, &rec->cache);
3380         if (ret) {
3381                 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
3382                         rec->offset, rec->length);
3383                 free(rec);
3384         }
3385
3386         return ret;
3387 }
3388
3389 static int process_device_item(struct rb_root *dev_cache,
3390                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
3391 {
3392         struct btrfs_dev_item *ptr;
3393         struct device_record *rec;
3394         int ret = 0;
3395
3396         ptr = btrfs_item_ptr(eb,
3397                 slot, struct btrfs_dev_item);
3398
3399         rec = malloc(sizeof(*rec));
3400         if (!rec) {
3401                 fprintf(stderr, "memory allocation failed\n");
3402                 return -ENOMEM;
3403         }
3404
3405         rec->devid = key->offset;
3406         rec->generation = btrfs_header_generation(eb);
3407
3408         rec->objectid = key->objectid;
3409         rec->type = key->type;
3410         rec->offset = key->offset;
3411
3412         rec->devid = btrfs_device_id(eb, ptr);
3413         rec->total_byte = btrfs_device_total_bytes(eb, ptr);
3414         rec->byte_used = btrfs_device_bytes_used(eb, ptr);
3415
3416         ret = rb_insert(dev_cache, &rec->node, device_record_compare);
3417         if (ret) {
3418                 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
3419                 free(rec);
3420         }
3421
3422         return ret;
3423 }
3424
3425 struct block_group_record *
3426 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
3427                              int slot)
3428 {
3429         struct btrfs_block_group_item *ptr;
3430         struct block_group_record *rec;
3431
3432         rec = malloc(sizeof(*rec));
3433         if (!rec) {
3434                 fprintf(stderr, "memory allocation failed\n");
3435                 exit(-1);
3436         }
3437         memset(rec, 0, sizeof(*rec));
3438
3439         rec->cache.start = key->objectid;
3440         rec->cache.size = key->offset;
3441
3442         rec->generation = btrfs_header_generation(leaf);
3443
3444         rec->objectid = key->objectid;
3445         rec->type = key->type;
3446         rec->offset = key->offset;
3447
3448         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
3449         rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
3450
3451         INIT_LIST_HEAD(&rec->list);
3452
3453         return rec;
3454 }
3455
3456 static int process_block_group_item(struct block_group_tree *block_group_cache,
3457                                     struct btrfs_key *key,
3458                                     struct extent_buffer *eb, int slot)
3459 {
3460         struct block_group_record *rec;
3461         int ret = 0;
3462
3463         rec = btrfs_new_block_group_record(eb, key, slot);
3464         ret = insert_block_group_record(block_group_cache, rec);
3465         if (ret) {
3466                 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
3467                         rec->objectid, rec->offset);
3468                 free(rec);
3469         }
3470
3471         return ret;
3472 }
3473
3474 struct device_extent_record *
3475 btrfs_new_device_extent_record(struct extent_buffer *leaf,
3476                                struct btrfs_key *key, int slot)
3477 {
3478         struct device_extent_record *rec;
3479         struct btrfs_dev_extent *ptr;
3480
3481         rec = malloc(sizeof(*rec));
3482         if (!rec) {
3483                 fprintf(stderr, "memory allocation failed\n");
3484                 exit(-1);
3485         }
3486         memset(rec, 0, sizeof(*rec));
3487
3488         rec->cache.objectid = key->objectid;
3489         rec->cache.start = key->offset;
3490
3491         rec->generation = btrfs_header_generation(leaf);
3492
3493         rec->objectid = key->objectid;
3494         rec->type = key->type;
3495         rec->offset = key->offset;
3496
3497         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
3498         rec->chunk_objecteid =
3499                 btrfs_dev_extent_chunk_objectid(leaf, ptr);
3500         rec->chunk_offset =
3501                 btrfs_dev_extent_chunk_offset(leaf, ptr);
3502         rec->length = btrfs_dev_extent_length(leaf, ptr);
3503         rec->cache.size = rec->length;
3504
3505         INIT_LIST_HEAD(&rec->chunk_list);
3506         INIT_LIST_HEAD(&rec->device_list);
3507
3508         return rec;
3509 }
3510
3511 static int
3512 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
3513                            struct btrfs_key *key, struct extent_buffer *eb,
3514                            int slot)
3515 {
3516         struct device_extent_record *rec;
3517         int ret;
3518
3519         rec = btrfs_new_device_extent_record(eb, key, slot);
3520         ret = insert_device_extent_record(dev_extent_cache, rec);
3521         if (ret) {
3522                 fprintf(stderr,
3523                         "Device extent[%llu, %llu, %llu] existed.\n",
3524                         rec->objectid, rec->offset, rec->length);
3525                 free(rec);
3526         }
3527
3528         return ret;
3529 }
3530
3531 static int process_extent_item(struct btrfs_root *root,
3532                                struct cache_tree *extent_cache,
3533                                struct extent_buffer *eb, int slot)
3534 {
3535         struct btrfs_extent_item *ei;
3536         struct btrfs_extent_inline_ref *iref;
3537         struct btrfs_extent_data_ref *dref;
3538         struct btrfs_shared_data_ref *sref;
3539         struct btrfs_key key;
3540         unsigned long end;
3541         unsigned long ptr;
3542         int type;
3543         u32 item_size = btrfs_item_size_nr(eb, slot);
3544         u64 refs = 0;
3545         u64 offset;
3546         u64 num_bytes;
3547         int metadata = 0;
3548
3549         btrfs_item_key_to_cpu(eb, &key, slot);
3550
3551         if (key.type == BTRFS_METADATA_ITEM_KEY) {
3552                 metadata = 1;
3553                 num_bytes = root->leafsize;
3554         } else {
3555                 num_bytes = key.offset;
3556         }
3557
3558         if (item_size < sizeof(*ei)) {
3559 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3560                 struct btrfs_extent_item_v0 *ei0;
3561                 BUG_ON(item_size != sizeof(*ei0));
3562                 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
3563                 refs = btrfs_extent_refs_v0(eb, ei0);
3564 #else
3565                 BUG();
3566 #endif
3567                 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
3568                                       num_bytes, refs, 0, 0, 0, metadata, 1,
3569                                       num_bytes);
3570         }
3571
3572         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
3573         refs = btrfs_extent_refs(eb, ei);
3574
3575         add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
3576                        refs, 0, 0, 0, metadata, 1, num_bytes);
3577
3578         ptr = (unsigned long)(ei + 1);
3579         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
3580             key.type == BTRFS_EXTENT_ITEM_KEY)
3581                 ptr += sizeof(struct btrfs_tree_block_info);
3582
3583         end = (unsigned long)ei + item_size;
3584         while (ptr < end) {
3585                 iref = (struct btrfs_extent_inline_ref *)ptr;
3586                 type = btrfs_extent_inline_ref_type(eb, iref);
3587                 offset = btrfs_extent_inline_ref_offset(eb, iref);
3588                 switch (type) {
3589                 case BTRFS_TREE_BLOCK_REF_KEY:
3590                         add_tree_backref(extent_cache, key.objectid,
3591                                          0, offset, 0);
3592                         break;
3593                 case BTRFS_SHARED_BLOCK_REF_KEY:
3594                         add_tree_backref(extent_cache, key.objectid,
3595                                          offset, 0, 0);
3596                         break;
3597                 case BTRFS_EXTENT_DATA_REF_KEY:
3598                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
3599                         add_data_backref(extent_cache, key.objectid, 0,
3600                                         btrfs_extent_data_ref_root(eb, dref),
3601                                         btrfs_extent_data_ref_objectid(eb,
3602                                                                        dref),
3603                                         btrfs_extent_data_ref_offset(eb, dref),
3604                                         btrfs_extent_data_ref_count(eb, dref),
3605                                         0, num_bytes);
3606                         break;
3607                 case BTRFS_SHARED_DATA_REF_KEY:
3608                         sref = (struct btrfs_shared_data_ref *)(iref + 1);
3609                         add_data_backref(extent_cache, key.objectid, offset,
3610                                         0, 0, 0,
3611                                         btrfs_shared_data_ref_count(eb, sref),
3612                                         0, num_bytes);
3613                         break;
3614                 default:
3615                         fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
3616                                 key.objectid, key.type, num_bytes);
3617                         goto out;
3618                 }
3619                 ptr += btrfs_extent_inline_ref_size(type);
3620         }
3621         WARN_ON(ptr > end);
3622 out:
3623         return 0;
3624 }
3625
3626 static int check_cache_range(struct btrfs_root *root,
3627                              struct btrfs_block_group_cache *cache,
3628                              u64 offset, u64 bytes)
3629 {
3630         struct btrfs_free_space *entry;
3631         u64 *logical;
3632         u64 bytenr;
3633         int stripe_len;
3634         int i, nr, ret;
3635
3636         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
3637                 bytenr = btrfs_sb_offset(i);
3638                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
3639                                        cache->key.objectid, bytenr, 0,
3640                                        &logical, &nr, &stripe_len);
3641                 if (ret)
3642                         return ret;
3643
3644                 while (nr--) {
3645                         if (logical[nr] + stripe_len <= offset)
3646                                 continue;
3647                         if (offset + bytes <= logical[nr])
3648                                 continue;
3649                         if (logical[nr] == offset) {
3650                                 if (stripe_len >= bytes) {
3651                                         kfree(logical);
3652                                         return 0;
3653                                 }
3654                                 bytes -= stripe_len;
3655                                 offset += stripe_len;
3656                         } else if (logical[nr] < offset) {
3657                                 if (logical[nr] + stripe_len >=
3658                                     offset + bytes) {
3659                                         kfree(logical);
3660                                         return 0;
3661                                 }
3662                                 bytes = (offset + bytes) -
3663                                         (logical[nr] + stripe_len);
3664                                 offset = logical[nr] + stripe_len;
3665                         } else {
3666                                 /*
3667                                  * Could be tricky, the super may land in the
3668                                  * middle of the area we're checking.  First
3669                                  * check the easiest case, it's at the end.
3670                                  */
3671                                 if (logical[nr] + stripe_len >=
3672                                     bytes + offset) {
3673                                         bytes = logical[nr] - offset;
3674                                         continue;
3675                                 }
3676
3677                                 /* Check the left side */
3678                                 ret = check_cache_range(root, cache,
3679                                                         offset,
3680                                                         logical[nr] - offset);
3681                                 if (ret) {
3682                                         kfree(logical);
3683                                         return ret;
3684                                 }
3685
3686                                 /* Now we continue with the right side */
3687                                 bytes = (offset + bytes) -
3688                                         (logical[nr] + stripe_len);
3689                                 offset = logical[nr] + stripe_len;
3690                         }
3691                 }
3692
3693                 kfree(logical);
3694         }
3695
3696         entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
3697         if (!entry) {
3698                 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
3699                         offset, offset+bytes);
3700                 return -EINVAL;
3701         }
3702
3703         if (entry->offset != offset) {
3704                 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
3705                         entry->offset);
3706                 return -EINVAL;
3707         }
3708
3709         if (entry->bytes != bytes) {
3710                 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
3711                         bytes, entry->bytes, offset);
3712                 return -EINVAL;
3713         }
3714
3715         unlink_free_space(cache->free_space_ctl, entry);
3716         free(entry);
3717         return 0;
3718 }
3719
3720 static int verify_space_cache(struct btrfs_root *root,
3721                               struct btrfs_block_group_cache *cache)
3722 {
3723         struct btrfs_path *path;
3724         struct extent_buffer *leaf;
3725         struct btrfs_key key;
3726         u64 last;
3727         int ret = 0;
3728
3729         path = btrfs_alloc_path();
3730         if (!path)
3731                 return -ENOMEM;
3732
3733         root = root->fs_info->extent_root;
3734
3735         last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
3736
3737         key.objectid = last;
3738         key.offset = 0;
3739         key.type = BTRFS_EXTENT_ITEM_KEY;
3740
3741         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3742         if (ret < 0)
3743                 goto out;
3744         ret = 0;
3745         while (1) {
3746                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3747                         ret = btrfs_next_leaf(root, path);
3748                         if (ret < 0)
3749                                 goto out;
3750                         if (ret > 0) {
3751                                 ret = 0;
3752                                 break;
3753                         }
3754                 }
3755                 leaf = path->nodes[0];
3756                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3757                 if (key.objectid >= cache->key.offset + cache->key.objectid)
3758                         break;
3759                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
3760                     key.type != BTRFS_METADATA_ITEM_KEY) {
3761                         path->slots[0]++;
3762                         continue;
3763                 }
3764
3765                 if (last == key.objectid) {
3766                         if (key.type == BTRFS_EXTENT_ITEM_KEY)
3767                                 last = key.objectid + key.offset;
3768                         else
3769                                 last = key.objectid + root->leafsize;
3770                         path->slots[0]++;
3771                         continue;
3772                 }
3773
3774                 ret = check_cache_range(root, cache, last,
3775                                         key.objectid - last);
3776                 if (ret)
3777                         break;
3778                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
3779                         last = key.objectid + key.offset;
3780                 else
3781                         last = key.objectid + root->leafsize;
3782                 path->slots[0]++;
3783         }
3784
3785         if (last < cache->key.objectid + cache->key.offset)
3786                 ret = check_cache_range(root, cache, last,
3787                                         cache->key.objectid +
3788                                         cache->key.offset - last);
3789
3790 out:
3791         btrfs_free_path(path);
3792
3793         if (!ret &&
3794             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
3795                 fprintf(stderr, "There are still entries left in the space "
3796                         "cache\n");
3797                 ret = -EINVAL;
3798         }
3799
3800         return ret;
3801 }
3802
3803 static int check_space_cache(struct btrfs_root *root)
3804 {
3805         struct btrfs_block_group_cache *cache;
3806         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
3807         int ret;
3808         int error = 0;
3809
3810         if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
3811             btrfs_super_generation(root->fs_info->super_copy) !=
3812             btrfs_super_cache_generation(root->fs_info->super_copy)) {
3813                 printf("cache and super generation don't match, space cache "
3814                        "will be invalidated\n");
3815                 return 0;
3816         }
3817
3818         while (1) {
3819                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
3820                 if (!cache)
3821                         break;
3822
3823                 start = cache->key.objectid + cache->key.offset;
3824                 if (!cache->free_space_ctl) {
3825                         if (btrfs_init_free_space_ctl(cache,
3826                                                       root->sectorsize)) {
3827                                 ret = -ENOMEM;
3828                                 break;
3829                         }
3830                 } else {
3831                         btrfs_remove_free_space_cache(cache);
3832                 }
3833
3834                 ret = load_free_space_cache(root->fs_info, cache);
3835                 if (!ret)
3836                         continue;
3837
3838                 ret = verify_space_cache(root, cache);
3839                 if (ret) {
3840                         fprintf(stderr, "cache appears valid but isnt %Lu\n",
3841                                 cache->key.objectid);
3842                         error++;
3843                 }
3844         }
3845
3846         return error ? -EINVAL : 0;
3847 }
3848
3849 static int read_extent_data(struct btrfs_root *root, char *data,
3850                         u64 logical, u64 *len, int mirror)
3851 {
3852         u64 offset = 0;
3853         struct btrfs_multi_bio *multi = NULL;
3854         struct btrfs_fs_info *info = root->fs_info;
3855         struct btrfs_device *device;
3856         int ret = 0;
3857         u64 max_len = *len;
3858
3859         ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
3860                               &multi, mirror, NULL);
3861         if (ret) {
3862                 fprintf(stderr, "Couldn't map the block %llu\n",
3863                                 logical + offset);
3864                 goto err;
3865         }
3866         device = multi->stripes[0].dev;
3867
3868         if (device->fd == 0)
3869                 goto err;
3870         if (*len > max_len)
3871                 *len = max_len;
3872
3873         ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
3874         if (ret != *len)
3875                 ret = -EIO;
3876         else
3877                 ret = 0;
3878 err:
3879         kfree(multi);
3880         return ret;
3881 }
3882
3883 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
3884                         u64 num_bytes, unsigned long leaf_offset,
3885                         struct extent_buffer *eb) {
3886
3887         u64 offset = 0;
3888         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
3889         char *data;
3890         unsigned long csum_offset;
3891         u32 csum;
3892         u32 csum_expected;
3893         u64 read_len;
3894         u64 data_checked = 0;
3895         u64 tmp;
3896         int ret = 0;
3897         int mirror;
3898         int num_copies;
3899
3900         if (num_bytes % root->sectorsize)
3901                 return -EINVAL;
3902
3903         data = malloc(num_bytes);
3904         if (!data)
3905                 return -ENOMEM;
3906
3907         while (offset < num_bytes) {
3908                 mirror = 0;
3909 again:
3910                 read_len = num_bytes - offset;
3911                 /* read as much space once a time */
3912                 ret = read_extent_data(root, data + offset,
3913                                 bytenr + offset, &read_len, mirror);
3914                 if (ret)
3915                         goto out;
3916                 data_checked = 0;
3917                 /* verify every 4k data's checksum */
3918                 while (data_checked < read_len) {
3919                         csum = ~(u32)0;
3920                         tmp = offset + data_checked;
3921
3922                         csum = btrfs_csum_data(NULL, (char *)data + tmp,
3923                                                csum, root->sectorsize);
3924                         btrfs_csum_final(csum, (char *)&csum);
3925
3926                         csum_offset = leaf_offset +
3927                                  tmp / root->sectorsize * csum_size;
3928                         read_extent_buffer(eb, (char *)&csum_expected,
3929                                            csum_offset, csum_size);
3930                         /* try another mirror */
3931                         if (csum != csum_expected) {
3932                                 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
3933                                                 mirror, bytenr + tmp,
3934                                                 csum, csum_expected);
3935                                 num_copies = btrfs_num_copies(
3936                                                 &root->fs_info->mapping_tree,
3937                                                 bytenr, num_bytes);
3938                                 if (mirror < num_copies - 1) {
3939                                         mirror += 1;
3940                                         goto again;
3941                                 }
3942                         }
3943                         data_checked += root->sectorsize;
3944                 }
3945                 offset += read_len;
3946         }
3947 out:
3948         free(data);
3949         return ret;
3950 }
3951
3952 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
3953                                u64 num_bytes)
3954 {
3955         struct btrfs_path *path;
3956         struct extent_buffer *leaf;
3957         struct btrfs_key key;
3958         int ret;
3959
3960         path = btrfs_alloc_path();
3961         if (!path) {
3962                 fprintf(stderr, "Error allocing path\n");
3963                 return -ENOMEM;
3964         }
3965
3966         key.objectid = bytenr;
3967         key.type = BTRFS_EXTENT_ITEM_KEY;
3968         key.offset = (u64)-1;
3969
3970 again:
3971         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
3972                                 0, 0);
3973         if (ret < 0) {
3974                 fprintf(stderr, "Error looking up extent record %d\n", ret);
3975                 btrfs_free_path(path);
3976                 return ret;
3977         } else if (ret) {
3978                 if (path->slots[0] > 0) {
3979                         path->slots[0]--;
3980                 } else {
3981                         ret = btrfs_prev_leaf(root, path);
3982                         if (ret < 0) {
3983                                 goto out;
3984                         } else if (ret > 0) {
3985                                 ret = 0;
3986                                 goto out;
3987                         }
3988                 }
3989         }
3990
3991         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3992
3993         /*
3994          * Block group items come before extent items if they have the same
3995          * bytenr, so walk back one more just in case.  Dear future traveler,
3996          * first congrats on mastering time travel.  Now if it's not too much
3997          * trouble could you go back to 2006 and tell Chris to make the
3998          * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
3999          * EXTENT_ITEM_KEY please?
4000          */
4001         while (key.type > BTRFS_EXTENT_ITEM_KEY) {
4002                 if (path->slots[0] > 0) {
4003                         path->slots[0]--;
4004                 } else {
4005                         ret = btrfs_prev_leaf(root, path);
4006                         if (ret < 0) {
4007                                 goto out;
4008                         } else if (ret > 0) {
4009                                 ret = 0;
4010                                 goto out;
4011                         }
4012                 }
4013                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4014         }
4015
4016         while (num_bytes) {
4017                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4018                         ret = btrfs_next_leaf(root, path);
4019                         if (ret < 0) {
4020                                 fprintf(stderr, "Error going to next leaf "
4021                                         "%d\n", ret);
4022                                 btrfs_free_path(path);
4023                                 return ret;
4024                         } else if (ret) {
4025                                 break;
4026                         }
4027                 }
4028                 leaf = path->nodes[0];
4029                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4030                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
4031                         path->slots[0]++;
4032                         continue;
4033                 }
4034                 if (key.objectid + key.offset < bytenr) {
4035                         path->slots[0]++;
4036                         continue;
4037                 }
4038                 if (key.objectid > bytenr + num_bytes)
4039                         break;
4040
4041                 if (key.objectid == bytenr) {
4042                         if (key.offset >= num_bytes) {
4043                                 num_bytes = 0;
4044                                 break;
4045                         }
4046                         num_bytes -= key.offset;
4047                         bytenr += key.offset;
4048                 } else if (key.objectid < bytenr) {
4049                         if (key.objectid + key.offset >= bytenr + num_bytes) {
4050                                 num_bytes = 0;
4051                                 break;
4052                         }
4053                         num_bytes = (bytenr + num_bytes) -
4054                                 (key.objectid + key.offset);
4055                         bytenr = key.objectid + key.offset;
4056                 } else {
4057                         if (key.objectid + key.offset < bytenr + num_bytes) {
4058                                 u64 new_start = key.objectid + key.offset;
4059                                 u64 new_bytes = bytenr + num_bytes - new_start;
4060
4061                                 /*
4062                                  * Weird case, the extent is in the middle of
4063                                  * our range, we'll have to search one side
4064                                  * and then the other.  Not sure if this happens
4065                                  * in real life, but no harm in coding it up
4066                                  * anyway just in case.
4067                                  */
4068                                 btrfs_release_path(path);
4069                                 ret = check_extent_exists(root, new_start,
4070                                                           new_bytes);
4071                                 if (ret) {
4072                                         fprintf(stderr, "Right section didn't "
4073                                                 "have a record\n");
4074                                         break;
4075                                 }
4076                                 num_bytes = key.objectid - bytenr;
4077                                 goto again;
4078                         }
4079                         num_bytes = key.objectid - bytenr;
4080                 }
4081                 path->slots[0]++;
4082         }
4083         ret = 0;
4084
4085 out:
4086         if (num_bytes && !ret) {
4087                 fprintf(stderr, "There are no extents for csum range "
4088                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
4089                 ret = 1;
4090         }
4091
4092         btrfs_free_path(path);
4093         return ret;
4094 }
4095
4096 static int check_csums(struct btrfs_root *root)
4097 {
4098         struct btrfs_path *path;
4099         struct extent_buffer *leaf;
4100         struct btrfs_key key;
4101         u64 offset = 0, num_bytes = 0;
4102         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
4103         int errors = 0;
4104         int ret;
4105         u64 data_len;
4106         unsigned long leaf_offset;
4107
4108         root = root->fs_info->csum_root;
4109         if (!extent_buffer_uptodate(root->node)) {
4110                 fprintf(stderr, "No valid csum tree found\n");
4111                 return -ENOENT;
4112         }
4113
4114         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
4115         key.type = BTRFS_EXTENT_CSUM_KEY;
4116         key.offset = 0;
4117
4118         path = btrfs_alloc_path();
4119         if (!path)
4120                 return -ENOMEM;
4121
4122         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4123         if (ret < 0) {
4124                 fprintf(stderr, "Error searching csum tree %d\n", ret);
4125                 btrfs_free_path(path);
4126                 return ret;
4127         }
4128
4129         if (ret > 0 && path->slots[0])
4130                 path->slots[0]--;
4131         ret = 0;
4132
4133         while (1) {
4134                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4135                         ret = btrfs_next_leaf(root, path);
4136                         if (ret < 0) {
4137                                 fprintf(stderr, "Error going to next leaf "
4138                                         "%d\n", ret);
4139                                 break;
4140                         }
4141                         if (ret)
4142                                 break;
4143                 }
4144                 leaf = path->nodes[0];
4145
4146                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4147                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
4148                         path->slots[0]++;
4149                         continue;
4150                 }
4151
4152                 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
4153                               csum_size) * root->sectorsize;
4154                 if (!check_data_csum)
4155                         goto skip_csum_check;
4156                 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
4157                 ret = check_extent_csums(root, key.offset, data_len,
4158                                          leaf_offset, leaf);
4159                 if (ret)
4160                         break;
4161 skip_csum_check:
4162                 if (!num_bytes) {
4163                         offset = key.offset;
4164                 } else if (key.offset != offset + num_bytes) {
4165                         ret = check_extent_exists(root, offset, num_bytes);
4166                         if (ret) {
4167                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
4168                                         "there is no extent record\n",
4169                                         offset, offset+num_bytes);
4170                                 errors++;
4171                         }
4172                         offset = key.offset;
4173                         num_bytes = 0;
4174                 }
4175                 num_bytes += data_len;
4176                 path->slots[0]++;
4177         }
4178
4179         btrfs_free_path(path);
4180         return errors;
4181 }
4182
4183 static int is_dropped_key(struct btrfs_key *key,
4184                           struct btrfs_key *drop_key) {
4185         if (key->objectid < drop_key->objectid)
4186                 return 1;
4187         else if (key->objectid == drop_key->objectid) {
4188                 if (key->type < drop_key->type)
4189                         return 1;
4190                 else if (key->type == drop_key->type) {
4191                         if (key->offset < drop_key->offset)
4192                                 return 1;
4193                 }
4194         }
4195         return 0;
4196 }
4197
4198 static int run_next_block(struct btrfs_trans_handle *trans,
4199                           struct btrfs_root *root,
4200                           struct block_info *bits,
4201                           int bits_nr,
4202                           u64 *last,
4203                           struct cache_tree *pending,
4204                           struct cache_tree *seen,
4205                           struct cache_tree *reada,
4206                           struct cache_tree *nodes,
4207                           struct cache_tree *extent_cache,
4208                           struct cache_tree *chunk_cache,
4209                           struct rb_root *dev_cache,
4210                           struct block_group_tree *block_group_cache,
4211                           struct device_extent_tree *dev_extent_cache,
4212                           struct btrfs_root_item *ri)
4213 {
4214         struct extent_buffer *buf;
4215         u64 bytenr;
4216         u32 size;
4217         u64 parent;
4218         u64 owner;
4219         u64 flags;
4220         u64 ptr;
4221         u64 gen = 0;
4222         int ret = 0;
4223         int i;
4224         int nritems;
4225         struct btrfs_key key;
4226         struct cache_extent *cache;
4227         int reada_bits;
4228
4229         nritems = pick_next_pending(pending, reada, nodes, *last, bits,
4230                                     bits_nr, &reada_bits);
4231         if (nritems == 0)
4232                 return 1;
4233
4234         if (!reada_bits) {
4235                 for(i = 0; i < nritems; i++) {
4236                         ret = add_cache_extent(reada, bits[i].start,
4237                                                bits[i].size);
4238                         if (ret == -EEXIST)
4239                                 continue;
4240
4241                         /* fixme, get the parent transid */
4242                         readahead_tree_block(root, bits[i].start,
4243                                              bits[i].size, 0);
4244                 }
4245         }
4246         *last = bits[0].start;
4247         bytenr = bits[0].start;
4248         size = bits[0].size;
4249
4250         cache = lookup_cache_extent(pending, bytenr, size);
4251         if (cache) {
4252                 remove_cache_extent(pending, cache);
4253                 free(cache);
4254         }
4255         cache = lookup_cache_extent(reada, bytenr, size);
4256         if (cache) {
4257                 remove_cache_extent(reada, cache);
4258                 free(cache);
4259         }
4260         cache = lookup_cache_extent(nodes, bytenr, size);
4261         if (cache) {
4262                 remove_cache_extent(nodes, cache);
4263                 free(cache);
4264         }
4265         cache = lookup_cache_extent(extent_cache, bytenr, size);
4266         if (cache) {
4267                 struct extent_record *rec;
4268
4269                 rec = container_of(cache, struct extent_record, cache);
4270                 gen = rec->parent_generation;
4271         }
4272
4273         /* fixme, get the real parent transid */
4274         buf = read_tree_block(root, bytenr, size, gen);
4275         if (!extent_buffer_uptodate(buf)) {
4276                 record_bad_block_io(root->fs_info,
4277                                     extent_cache, bytenr, size);
4278                 goto out;
4279         }
4280
4281         nritems = btrfs_header_nritems(buf);
4282
4283         /*
4284          * FIXME, this only works only if we don't have any full
4285          * backref mode.
4286          */
4287         if (!init_extent_tree) {
4288                 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
4289                                        btrfs_header_level(buf), 1, NULL,
4290                                        &flags);
4291                 if (ret < 0)
4292                         flags = 0;
4293         } else {
4294                 flags = 0;
4295         }
4296
4297         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
4298                 parent = bytenr;
4299                 owner = 0;
4300         } else {
4301                 parent = 0;
4302                 owner = btrfs_header_owner(buf);
4303         }
4304
4305         ret = check_block(trans, root, extent_cache, buf, flags);
4306         if (ret)
4307                 goto out;
4308
4309         if (btrfs_is_leaf(buf)) {
4310                 btree_space_waste += btrfs_leaf_free_space(root, buf);
4311                 for (i = 0; i < nritems; i++) {
4312                         struct btrfs_file_extent_item *fi;
4313                         btrfs_item_key_to_cpu(buf, &key, i);
4314                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
4315                                 process_extent_item(root, extent_cache, buf,
4316                                                     i);
4317                                 continue;
4318                         }
4319                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
4320                                 process_extent_item(root, extent_cache, buf,
4321                                                     i);
4322                                 continue;
4323                         }
4324                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
4325                                 total_csum_bytes +=
4326                                         btrfs_item_size_nr(buf, i);
4327                                 continue;
4328                         }
4329                         if (key.type == BTRFS_CHUNK_ITEM_KEY) {
4330                                 process_chunk_item(chunk_cache, &key, buf, i);
4331                                 continue;
4332                         }
4333                         if (key.type == BTRFS_DEV_ITEM_KEY) {
4334                                 process_device_item(dev_cache, &key, buf, i);
4335                                 continue;
4336                         }
4337                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
4338                                 process_block_group_item(block_group_cache,
4339                                         &key, buf, i);
4340                                 continue;
4341                         }
4342                         if (key.type == BTRFS_DEV_EXTENT_KEY) {
4343                                 process_device_extent_item(dev_extent_cache,
4344                                         &key, buf, i);
4345                                 continue;
4346
4347                         }
4348                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
4349 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4350                                 process_extent_ref_v0(extent_cache, buf, i);
4351 #else
4352                                 BUG();
4353 #endif
4354                                 continue;
4355                         }
4356
4357                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
4358                                 add_tree_backref(extent_cache, key.objectid, 0,
4359                                                  key.offset, 0);
4360                                 continue;
4361                         }
4362                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
4363                                 add_tree_backref(extent_cache, key.objectid,
4364                                                  key.offset, 0, 0);
4365                                 continue;
4366                         }
4367                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
4368                                 struct btrfs_extent_data_ref *ref;
4369                                 ref = btrfs_item_ptr(buf, i,
4370                                                 struct btrfs_extent_data_ref);
4371                                 add_data_backref(extent_cache,
4372                                         key.objectid, 0,
4373                                         btrfs_extent_data_ref_root(buf, ref),
4374                                         btrfs_extent_data_ref_objectid(buf,
4375                                                                        ref),
4376                                         btrfs_extent_data_ref_offset(buf, ref),
4377                                         btrfs_extent_data_ref_count(buf, ref),
4378                                         0, root->sectorsize);
4379                                 continue;
4380                         }
4381                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
4382                                 struct btrfs_shared_data_ref *ref;
4383                                 ref = btrfs_item_ptr(buf, i,
4384                                                 struct btrfs_shared_data_ref);
4385                                 add_data_backref(extent_cache,
4386                                         key.objectid, key.offset, 0, 0, 0,
4387                                         btrfs_shared_data_ref_count(buf, ref),
4388                                         0, root->sectorsize);
4389                                 continue;
4390                         }
4391                         if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
4392                                 struct bad_item *bad;
4393
4394                                 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
4395                                         continue;
4396                                 if (!owner)
4397                                         continue;
4398                                 bad = malloc(sizeof(struct bad_item));
4399                                 if (!bad)
4400                                         continue;
4401                                 INIT_LIST_HEAD(&bad->list);
4402                                 memcpy(&bad->key, &key,
4403                                        sizeof(struct btrfs_key));
4404                                 bad->root_id = owner;
4405                                 list_add_tail(&bad->list, &delete_items);
4406                                 continue;
4407                         }
4408                         if (key.type != BTRFS_EXTENT_DATA_KEY)
4409                                 continue;
4410                         fi = btrfs_item_ptr(buf, i,
4411                                             struct btrfs_file_extent_item);
4412                         if (btrfs_file_extent_type(buf, fi) ==
4413                             BTRFS_FILE_EXTENT_INLINE)
4414                                 continue;
4415                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
4416                                 continue;
4417
4418                         data_bytes_allocated +=
4419                                 btrfs_file_extent_disk_num_bytes(buf, fi);
4420                         if (data_bytes_allocated < root->sectorsize) {
4421                                 abort();
4422                         }
4423                         data_bytes_referenced +=
4424                                 btrfs_file_extent_num_bytes(buf, fi);
4425                         add_data_backref(extent_cache,
4426                                 btrfs_file_extent_disk_bytenr(buf, fi),
4427                                 parent, owner, key.objectid, key.offset -
4428                                 btrfs_file_extent_offset(buf, fi), 1, 1,
4429                                 btrfs_file_extent_disk_num_bytes(buf, fi));
4430                 }
4431         } else {
4432                 int level;
4433                 struct btrfs_key first_key;
4434
4435                 first_key.objectid = 0;
4436
4437                 if (nritems > 0)
4438                         btrfs_item_key_to_cpu(buf, &first_key, 0);
4439                 level = btrfs_header_level(buf);
4440                 for (i = 0; i < nritems; i++) {
4441                         ptr = btrfs_node_blockptr(buf, i);
4442                         size = btrfs_level_size(root, level - 1);
4443                         btrfs_node_key_to_cpu(buf, &key, i);
4444                         if (ri != NULL) {
4445                                 struct btrfs_key drop_key;
4446                                 btrfs_disk_key_to_cpu(&drop_key,
4447                                                       &ri->drop_progress);
4448                                 if ((level == ri->drop_level)
4449                                     && is_dropped_key(&key, &drop_key)) {
4450                                         continue;
4451                                 }
4452                         }
4453                         ret = add_extent_rec(extent_cache, &key,
4454                                              btrfs_node_ptr_generation(buf, i),
4455                                              ptr, size, 0, 0, 1, 0, 1, 0,
4456                                              size);
4457                         BUG_ON(ret);
4458
4459                         add_tree_backref(extent_cache, ptr, parent, owner, 1);
4460
4461                         if (level > 1) {
4462                                 add_pending(nodes, seen, ptr, size);
4463                         } else {
4464                                 add_pending(pending, seen, ptr, size);
4465                         }
4466                 }
4467                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
4468                                       nritems) * sizeof(struct btrfs_key_ptr);
4469         }
4470         total_btree_bytes += buf->len;
4471         if (fs_root_objectid(btrfs_header_owner(buf)))
4472                 total_fs_tree_bytes += buf->len;
4473         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
4474                 total_extent_tree_bytes += buf->len;
4475         if (!found_old_backref &&
4476             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
4477             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
4478             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
4479                 found_old_backref = 1;
4480 out:
4481         free_extent_buffer(buf);
4482         return ret;
4483 }
4484
4485 static int add_root_to_pending(struct extent_buffer *buf,
4486                                struct cache_tree *extent_cache,
4487                                struct cache_tree *pending,
4488                                struct cache_tree *seen,
4489                                struct cache_tree *nodes,
4490                                struct btrfs_key *root_key)
4491 {
4492         if (btrfs_header_level(buf) > 0)
4493                 add_pending(nodes, seen, buf->start, buf->len);
4494         else
4495                 add_pending(pending, seen, buf->start, buf->len);
4496         add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
4497                        0, 1, 1, 0, 1, 0, buf->len);
4498
4499         if (root_key->objectid == BTRFS_TREE_RELOC_OBJECTID ||
4500             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
4501                 add_tree_backref(extent_cache, buf->start, buf->start,
4502                                  0, 1);
4503         else
4504                 add_tree_backref(extent_cache, buf->start, 0,
4505                                  root_key->objectid, 1);
4506         return 0;
4507 }
4508
4509 /* as we fix the tree, we might be deleting blocks that
4510  * we're tracking for repair.  This hook makes sure we
4511  * remove any backrefs for blocks as we are fixing them.
4512  */
4513 static int free_extent_hook(struct btrfs_trans_handle *trans,
4514                             struct btrfs_root *root,
4515                             u64 bytenr, u64 num_bytes, u64 parent,
4516                             u64 root_objectid, u64 owner, u64 offset,
4517                             int refs_to_drop)
4518 {
4519         struct extent_record *rec;
4520         struct cache_extent *cache;
4521         int is_data;
4522         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
4523
4524         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
4525         cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
4526         if (!cache)
4527                 return 0;
4528
4529         rec = container_of(cache, struct extent_record, cache);
4530         if (is_data) {
4531                 struct data_backref *back;
4532                 back = find_data_backref(rec, parent, root_objectid, owner,
4533                                          offset, 1, bytenr, num_bytes);
4534                 if (!back)
4535                         goto out;
4536                 if (back->node.found_ref) {
4537                         back->found_ref -= refs_to_drop;
4538                         if (rec->refs)
4539                                 rec->refs -= refs_to_drop;
4540                 }
4541                 if (back->node.found_extent_tree) {
4542                         back->num_refs -= refs_to_drop;
4543                         if (rec->extent_item_refs)
4544                                 rec->extent_item_refs -= refs_to_drop;
4545                 }
4546                 if (back->found_ref == 0)
4547                         back->node.found_ref = 0;
4548                 if (back->num_refs == 0)
4549                         back->node.found_extent_tree = 0;
4550
4551                 if (!back->node.found_extent_tree && back->node.found_ref) {
4552                         list_del(&back->node.list);
4553                         free(back);
4554                 }
4555         } else {
4556                 struct tree_backref *back;
4557                 back = find_tree_backref(rec, parent, root_objectid);
4558                 if (!back)
4559                         goto out;
4560                 if (back->node.found_ref) {
4561                         if (rec->refs)
4562                                 rec->refs--;
4563                         back->node.found_ref = 0;
4564                 }
4565                 if (back->node.found_extent_tree) {
4566                         if (rec->extent_item_refs)
4567                                 rec->extent_item_refs--;
4568                         back->node.found_extent_tree = 0;
4569                 }
4570                 if (!back->node.found_extent_tree && back->node.found_ref) {
4571                         list_del(&back->node.list);
4572                         free(back);
4573                 }
4574         }
4575         maybe_free_extent_rec(extent_cache, rec);
4576 out:
4577         return 0;
4578 }
4579
4580 static int delete_extent_records(struct btrfs_trans_handle *trans,
4581                                  struct btrfs_root *root,
4582                                  struct btrfs_path *path,
4583                                  u64 bytenr, u64 new_len)
4584 {
4585         struct btrfs_key key;
4586         struct btrfs_key found_key;
4587         struct extent_buffer *leaf;
4588         int ret;
4589         int slot;
4590
4591
4592         key.objectid = bytenr;
4593         key.type = (u8)-1;
4594         key.offset = (u64)-1;
4595
4596         while(1) {
4597                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
4598                                         &key, path, 0, 1);
4599                 if (ret < 0)
4600                         break;
4601
4602                 if (ret > 0) {
4603                         ret = 0;
4604                         if (path->slots[0] == 0)
4605                                 break;
4606                         path->slots[0]--;
4607                 }
4608                 ret = 0;
4609
4610                 leaf = path->nodes[0];
4611                 slot = path->slots[0];
4612
4613                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4614                 if (found_key.objectid != bytenr)
4615                         break;
4616
4617                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
4618                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
4619                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
4620                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
4621                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
4622                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
4623                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
4624                         btrfs_release_path(path);
4625                         if (found_key.type == 0) {
4626                                 if (found_key.offset == 0)
4627                                         break;
4628                                 key.offset = found_key.offset - 1;
4629                                 key.type = found_key.type;
4630                         }
4631                         key.type = found_key.type - 1;
4632                         key.offset = (u64)-1;
4633                         continue;
4634                 }
4635
4636                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
4637                         found_key.objectid, found_key.type, found_key.offset);
4638
4639                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
4640                 if (ret)
4641                         break;
4642                 btrfs_release_path(path);
4643
4644                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
4645                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
4646                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
4647                                 found_key.offset : root->leafsize;
4648
4649                         ret = btrfs_update_block_group(trans, root, bytenr,
4650                                                        bytes, 0, 0);
4651                         if (ret)
4652                                 break;
4653                 }
4654         }
4655
4656         btrfs_release_path(path);
4657         return ret;
4658 }
4659
4660 /*
4661  * for a single backref, this will allocate a new extent
4662  * and add the backref to it.
4663  */
4664 static int record_extent(struct btrfs_trans_handle *trans,
4665                          struct btrfs_fs_info *info,
4666                          struct btrfs_path *path,
4667                          struct extent_record *rec,
4668                          struct extent_backref *back,
4669                          int allocated, u64 flags)
4670 {
4671         int ret;
4672         struct btrfs_root *extent_root = info->extent_root;
4673         struct extent_buffer *leaf;
4674         struct btrfs_key ins_key;
4675         struct btrfs_extent_item *ei;
4676         struct tree_backref *tback;
4677         struct data_backref *dback;
4678         struct btrfs_tree_block_info *bi;
4679
4680         if (!back->is_data)
4681                 rec->max_size = max_t(u64, rec->max_size,
4682                                     info->extent_root->leafsize);
4683
4684         if (!allocated) {
4685                 u32 item_size = sizeof(*ei);
4686
4687                 if (!back->is_data)
4688                         item_size += sizeof(*bi);
4689
4690                 ins_key.objectid = rec->start;
4691                 ins_key.offset = rec->max_size;
4692                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
4693
4694                 ret = btrfs_insert_empty_item(trans, extent_root, path,
4695                                         &ins_key, item_size);
4696                 if (ret)
4697                         goto fail;
4698
4699                 leaf = path->nodes[0];
4700                 ei = btrfs_item_ptr(leaf, path->slots[0],
4701                                     struct btrfs_extent_item);
4702
4703                 btrfs_set_extent_refs(leaf, ei, 0);
4704                 btrfs_set_extent_generation(leaf, ei, rec->generation);
4705
4706                 if (back->is_data) {
4707                         btrfs_set_extent_flags(leaf, ei,
4708                                                BTRFS_EXTENT_FLAG_DATA);
4709                 } else {
4710                         struct btrfs_disk_key copy_key;;
4711
4712                         tback = (struct tree_backref *)back;
4713                         bi = (struct btrfs_tree_block_info *)(ei + 1);
4714                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
4715                                              sizeof(*bi));
4716
4717                         btrfs_set_disk_key_objectid(&copy_key,
4718                                                     rec->info_objectid);
4719                         btrfs_set_disk_key_type(&copy_key, 0);
4720                         btrfs_set_disk_key_offset(&copy_key, 0);
4721
4722                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
4723                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
4724
4725                         btrfs_set_extent_flags(leaf, ei,
4726                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
4727                 }
4728
4729                 btrfs_mark_buffer_dirty(leaf);
4730                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
4731                                                rec->max_size, 1, 0);
4732                 if (ret)
4733                         goto fail;
4734                 btrfs_release_path(path);
4735         }
4736
4737         if (back->is_data) {
4738                 u64 parent;
4739                 int i;
4740
4741                 dback = (struct data_backref *)back;
4742                 if (back->full_backref)
4743                         parent = dback->parent;
4744                 else
4745                         parent = 0;
4746
4747                 for (i = 0; i < dback->found_ref; i++) {
4748                         /* if parent != 0, we're doing a full backref
4749                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
4750                          * just makes the backref allocator create a data
4751                          * backref
4752                          */
4753                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
4754                                                    rec->start, rec->max_size,
4755                                                    parent,
4756                                                    dback->root,
4757                                                    parent ?
4758                                                    BTRFS_FIRST_FREE_OBJECTID :
4759                                                    dback->owner,
4760                                                    dback->offset);
4761                         if (ret)
4762                                 break;
4763                 }
4764                 fprintf(stderr, "adding new data backref"
4765                                 " on %llu %s %llu owner %llu"
4766                                 " offset %llu found %d\n",
4767                                 (unsigned long long)rec->start,
4768                                 back->full_backref ?
4769                                 "parent" : "root",
4770                                 back->full_backref ?
4771                                 (unsigned long long)parent :
4772                                 (unsigned long long)dback->root,
4773                                 (unsigned long long)dback->owner,
4774                                 (unsigned long long)dback->offset,
4775                                 dback->found_ref);
4776         } else {
4777                 u64 parent;
4778
4779                 tback = (struct tree_backref *)back;
4780                 if (back->full_backref)
4781                         parent = tback->parent;
4782                 else
4783                         parent = 0;
4784
4785                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
4786                                            rec->start, rec->max_size,
4787                                            parent, tback->root, 0, 0);
4788                 fprintf(stderr, "adding new tree backref on "
4789                         "start %llu len %llu parent %llu root %llu\n",
4790                         rec->start, rec->max_size, tback->parent, tback->root);
4791         }
4792         if (ret)
4793                 goto fail;
4794 fail:
4795         btrfs_release_path(path);
4796         return ret;
4797 }
4798
4799 struct extent_entry {
4800         u64 bytenr;
4801         u64 bytes;
4802         int count;
4803         int broken;
4804         struct list_head list;
4805 };
4806
4807 static struct extent_entry *find_entry(struct list_head *entries,
4808                                        u64 bytenr, u64 bytes)
4809 {
4810         struct extent_entry *entry = NULL;
4811
4812         list_for_each_entry(entry, entries, list) {
4813                 if (entry->bytenr == bytenr && entry->bytes == bytes)
4814                         return entry;
4815         }
4816
4817         return NULL;
4818 }
4819
4820 static struct extent_entry *find_most_right_entry(struct list_head *entries)
4821 {
4822         struct extent_entry *entry, *best = NULL, *prev = NULL;
4823
4824         list_for_each_entry(entry, entries, list) {
4825                 if (!prev) {
4826                         prev = entry;
4827                         continue;
4828                 }
4829
4830                 /*
4831                  * If there are as many broken entries as entries then we know
4832                  * not to trust this particular entry.
4833                  */
4834                 if (entry->broken == entry->count)
4835                         continue;
4836
4837                 /*
4838                  * If our current entry == best then we can't be sure our best
4839                  * is really the best, so we need to keep searching.
4840                  */
4841                 if (best && best->count == entry->count) {
4842                         prev = entry;
4843                         best = NULL;
4844                         continue;
4845                 }
4846
4847                 /* Prev == entry, not good enough, have to keep searching */
4848                 if (!prev->broken && prev->count == entry->count)
4849                         continue;
4850
4851                 if (!best)
4852                         best = (prev->count > entry->count) ? prev : entry;
4853                 else if (best->count < entry->count)
4854                         best = entry;
4855                 prev = entry;
4856         }
4857
4858         return best;
4859 }
4860
4861 static int repair_ref(struct btrfs_trans_handle *trans,
4862                       struct btrfs_fs_info *info, struct btrfs_path *path,
4863                       struct data_backref *dback, struct extent_entry *entry)
4864 {
4865         struct btrfs_root *root;
4866         struct btrfs_file_extent_item *fi;
4867         struct extent_buffer *leaf;
4868         struct btrfs_key key;
4869         u64 bytenr, bytes;
4870         int ret;
4871
4872         key.objectid = dback->root;
4873         key.type = BTRFS_ROOT_ITEM_KEY;
4874         key.offset = (u64)-1;
4875         root = btrfs_read_fs_root(info, &key);
4876         if (IS_ERR(root)) {
4877                 fprintf(stderr, "Couldn't find root for our ref\n");
4878                 return -EINVAL;
4879         }
4880
4881         /*
4882          * The backref points to the original offset of the extent if it was
4883          * split, so we need to search down to the offset we have and then walk
4884          * forward until we find the backref we're looking for.
4885          */
4886         key.objectid = dback->owner;
4887         key.type = BTRFS_EXTENT_DATA_KEY;
4888         key.offset = dback->offset;
4889         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4890         if (ret < 0) {
4891                 fprintf(stderr, "Error looking up ref %d\n", ret);
4892                 return ret;
4893         }
4894
4895         while (1) {
4896                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4897                         ret = btrfs_next_leaf(root, path);
4898                         if (ret) {
4899                                 fprintf(stderr, "Couldn't find our ref, next\n");
4900                                 return -EINVAL;
4901                         }
4902                 }
4903                 leaf = path->nodes[0];
4904                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4905                 if (key.objectid != dback->owner ||
4906                     key.type != BTRFS_EXTENT_DATA_KEY) {
4907                         fprintf(stderr, "Couldn't find our ref, search\n");
4908                         return -EINVAL;
4909                 }
4910                 fi = btrfs_item_ptr(leaf, path->slots[0],
4911                                     struct btrfs_file_extent_item);
4912                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
4913                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
4914
4915                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
4916                         break;
4917                 path->slots[0]++;
4918         }
4919
4920         btrfs_release_path(path);
4921
4922         /*
4923          * Have to make sure that this root gets updated when we commit the
4924          * transaction
4925          */
4926         record_root_in_trans(trans, root);
4927
4928         /*
4929          * Ok we have the key of the file extent we want to fix, now we can cow
4930          * down to the thing and fix it.
4931          */
4932         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4933         if (ret < 0) {
4934                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
4935                         key.objectid, key.type, key.offset, ret);
4936                 return ret;
4937         }
4938         if (ret > 0) {
4939                 fprintf(stderr, "Well that's odd, we just found this key "
4940                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
4941                         key.offset);
4942                 return -EINVAL;
4943         }
4944         leaf = path->nodes[0];
4945         fi = btrfs_item_ptr(leaf, path->slots[0],
4946                             struct btrfs_file_extent_item);
4947
4948         if (btrfs_file_extent_compression(leaf, fi) &&
4949             dback->disk_bytenr != entry->bytenr) {
4950                 fprintf(stderr, "Ref doesn't match the record start and is "
4951                         "compressed, please take a btrfs-image of this file "
4952                         "system and send it to a btrfs developer so they can "
4953                         "complete this functionality for bytenr %Lu\n",
4954                         dback->disk_bytenr);
4955                 return -EINVAL;
4956         }
4957
4958         if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
4959                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4960         } else if (dback->disk_bytenr > entry->bytenr) {
4961                 u64 off_diff, offset;
4962
4963                 off_diff = dback->disk_bytenr - entry->bytenr;
4964                 offset = btrfs_file_extent_offset(leaf, fi);
4965                 if (dback->disk_bytenr + offset +
4966                     btrfs_file_extent_num_bytes(leaf, fi) >
4967                     entry->bytenr + entry->bytes) {
4968                         fprintf(stderr, "Ref is past the entry end, please "
4969                                 "take a btrfs-image of this file system and "
4970                                 "send it to a btrfs developer, ref %Lu\n",
4971                                 dback->disk_bytenr);
4972                         return -EINVAL;
4973                 }
4974                 offset += off_diff;
4975                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4976                 btrfs_set_file_extent_offset(leaf, fi, offset);
4977         } else if (dback->disk_bytenr < entry->bytenr) {
4978                 u64 offset;
4979
4980                 offset = btrfs_file_extent_offset(leaf, fi);
4981                 if (dback->disk_bytenr + offset < entry->bytenr) {
4982                         fprintf(stderr, "Ref is before the entry start, 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
4989                 offset += dback->disk_bytenr;
4990                 offset -= entry->bytenr;
4991                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
4992                 btrfs_set_file_extent_offset(leaf, fi, offset);
4993         }
4994
4995         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
4996
4997         /*
4998          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
4999          * only do this if we aren't using compression, otherwise it's a
5000          * trickier case.
5001          */
5002         if (!btrfs_file_extent_compression(leaf, fi))
5003                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
5004         else
5005                 printf("ram bytes may be wrong?\n");
5006         btrfs_mark_buffer_dirty(leaf);
5007         btrfs_release_path(path);
5008         return 0;
5009 }
5010
5011 static int verify_backrefs(struct btrfs_trans_handle *trans,
5012                            struct btrfs_fs_info *info, struct btrfs_path *path,
5013                            struct extent_record *rec)
5014 {
5015         struct extent_backref *back;
5016         struct data_backref *dback;
5017         struct extent_entry *entry, *best = NULL;
5018         LIST_HEAD(entries);
5019         int nr_entries = 0;
5020         int broken_entries = 0;
5021         int ret = 0;
5022         short mismatch = 0;
5023
5024         /*
5025          * Metadata is easy and the backrefs should always agree on bytenr and
5026          * size, if not we've got bigger issues.
5027          */
5028         if (rec->metadata)
5029                 return 0;
5030
5031         list_for_each_entry(back, &rec->backrefs, list) {
5032                 if (back->full_backref || !back->is_data)
5033                         continue;
5034
5035                 dback = (struct data_backref *)back;
5036
5037                 /*
5038                  * We only pay attention to backrefs that we found a real
5039                  * backref for.
5040                  */
5041                 if (dback->found_ref == 0)
5042                         continue;
5043
5044                 /*
5045                  * For now we only catch when the bytes don't match, not the
5046                  * bytenr.  We can easily do this at the same time, but I want
5047                  * to have a fs image to test on before we just add repair
5048                  * functionality willy-nilly so we know we won't screw up the
5049                  * repair.
5050                  */
5051
5052                 entry = find_entry(&entries, dback->disk_bytenr,
5053                                    dback->bytes);
5054                 if (!entry) {
5055                         entry = malloc(sizeof(struct extent_entry));
5056                         if (!entry) {
5057                                 ret = -ENOMEM;
5058                                 goto out;
5059                         }
5060                         memset(entry, 0, sizeof(*entry));
5061                         entry->bytenr = dback->disk_bytenr;
5062                         entry->bytes = dback->bytes;
5063                         list_add_tail(&entry->list, &entries);
5064                         nr_entries++;
5065                 }
5066
5067                 /*
5068                  * If we only have on entry we may think the entries agree when
5069                  * in reality they don't so we have to do some extra checking.
5070                  */
5071                 if (dback->disk_bytenr != rec->start ||
5072                     dback->bytes != rec->nr || back->broken)
5073                         mismatch = 1;
5074
5075                 if (back->broken) {
5076                         entry->broken++;
5077                         broken_entries++;
5078                 }
5079
5080                 entry->count++;
5081         }
5082
5083         /* Yay all the backrefs agree, carry on good sir */
5084         if (nr_entries <= 1 && !mismatch)
5085                 goto out;
5086
5087         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
5088                 "%Lu\n", rec->start);
5089
5090         /*
5091          * First we want to see if the backrefs can agree amongst themselves who
5092          * is right, so figure out which one of the entries has the highest
5093          * count.
5094          */
5095         best = find_most_right_entry(&entries);
5096
5097         /*
5098          * Ok so we may have an even split between what the backrefs think, so
5099          * this is where we use the extent ref to see what it thinks.
5100          */
5101         if (!best) {
5102                 entry = find_entry(&entries, rec->start, rec->nr);
5103                 if (!entry && (!broken_entries || !rec->found_rec)) {
5104                         fprintf(stderr, "Backrefs don't agree with each other "
5105                                 "and extent record doesn't agree with anybody,"
5106                                 " so we can't fix bytenr %Lu bytes %Lu\n",
5107                                 rec->start, rec->nr);
5108                         ret = -EINVAL;
5109                         goto out;
5110                 } else if (!entry) {
5111                         /*
5112                          * Ok our backrefs were broken, we'll assume this is the
5113                          * correct value and add an entry for this range.
5114                          */
5115                         entry = malloc(sizeof(struct extent_entry));
5116                         if (!entry) {
5117                                 ret = -ENOMEM;
5118                                 goto out;
5119                         }
5120                         memset(entry, 0, sizeof(*entry));
5121                         entry->bytenr = rec->start;
5122                         entry->bytes = rec->nr;
5123                         list_add_tail(&entry->list, &entries);
5124                         nr_entries++;
5125                 }
5126                 entry->count++;
5127                 best = find_most_right_entry(&entries);
5128                 if (!best) {
5129                         fprintf(stderr, "Backrefs and extent record evenly "
5130                                 "split on who is right, this is going to "
5131                                 "require user input to fix bytenr %Lu bytes "
5132                                 "%Lu\n", rec->start, rec->nr);
5133                         ret = -EINVAL;
5134                         goto out;
5135                 }
5136         }
5137
5138         /*
5139          * I don't think this can happen currently as we'll abort() if we catch
5140          * this case higher up, but in case somebody removes that we still can't
5141          * deal with it properly here yet, so just bail out of that's the case.
5142          */
5143         if (best->bytenr != rec->start) {
5144                 fprintf(stderr, "Extent start and backref starts don't match, "
5145                         "please use btrfs-image on this file system and send "
5146                         "it to a btrfs developer so they can make fsck fix "
5147                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
5148                         rec->start, rec->nr);
5149                 ret = -EINVAL;
5150                 goto out;
5151         }
5152
5153         /*
5154          * Ok great we all agreed on an extent record, let's go find the real
5155          * references and fix up the ones that don't match.
5156          */
5157         list_for_each_entry(back, &rec->backrefs, list) {
5158                 if (back->full_backref || !back->is_data)
5159                         continue;
5160
5161                 dback = (struct data_backref *)back;
5162
5163                 /*
5164                  * Still ignoring backrefs that don't have a real ref attached
5165                  * to them.
5166                  */
5167                 if (dback->found_ref == 0)
5168                         continue;
5169
5170                 if (dback->bytes == best->bytes &&
5171                     dback->disk_bytenr == best->bytenr)
5172                         continue;
5173
5174                 ret = repair_ref(trans, info, path, dback, best);
5175                 if (ret)
5176                         goto out;
5177         }
5178
5179         /*
5180          * Ok we messed with the actual refs, which means we need to drop our
5181          * entire cache and go back and rescan.  I know this is a huge pain and
5182          * adds a lot of extra work, but it's the only way to be safe.  Once all
5183          * the backrefs agree we may not need to do anything to the extent
5184          * record itself.
5185          */
5186         ret = -EAGAIN;
5187 out:
5188         while (!list_empty(&entries)) {
5189                 entry = list_entry(entries.next, struct extent_entry, list);
5190                 list_del_init(&entry->list);
5191                 free(entry);
5192         }
5193         return ret;
5194 }
5195
5196 static int process_duplicates(struct btrfs_root *root,
5197                               struct cache_tree *extent_cache,
5198                               struct extent_record *rec)
5199 {
5200         struct extent_record *good, *tmp;
5201         struct cache_extent *cache;
5202         int ret;
5203
5204         /*
5205          * If we found a extent record for this extent then return, or if we
5206          * have more than one duplicate we are likely going to need to delete
5207          * something.
5208          */
5209         if (rec->found_rec || rec->num_duplicates > 1)
5210                 return 0;
5211
5212         /* Shouldn't happen but just in case */
5213         BUG_ON(!rec->num_duplicates);
5214
5215         /*
5216          * So this happens if we end up with a backref that doesn't match the
5217          * actual extent entry.  So either the backref is bad or the extent
5218          * entry is bad.  Either way we want to have the extent_record actually
5219          * reflect what we found in the extent_tree, so we need to take the
5220          * duplicate out and use that as the extent_record since the only way we
5221          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
5222          */
5223         remove_cache_extent(extent_cache, &rec->cache);
5224
5225         good = list_entry(rec->dups.next, struct extent_record, list);
5226         list_del_init(&good->list);
5227         INIT_LIST_HEAD(&good->backrefs);
5228         INIT_LIST_HEAD(&good->dups);
5229         good->cache.start = good->start;
5230         good->cache.size = good->nr;
5231         good->content_checked = 0;
5232         good->owner_ref_checked = 0;
5233         good->num_duplicates = 0;
5234         good->refs = rec->refs;
5235         list_splice_init(&rec->backrefs, &good->backrefs);
5236         while (1) {
5237                 cache = lookup_cache_extent(extent_cache, good->start,
5238                                             good->nr);
5239                 if (!cache)
5240                         break;
5241                 tmp = container_of(cache, struct extent_record, cache);
5242
5243                 /*
5244                  * If we find another overlapping extent and it's found_rec is
5245                  * set then it's a duplicate and we need to try and delete
5246                  * something.
5247                  */
5248                 if (tmp->found_rec || tmp->num_duplicates > 0) {
5249                         if (list_empty(&good->list))
5250                                 list_add_tail(&good->list,
5251                                               &duplicate_extents);
5252                         good->num_duplicates += tmp->num_duplicates + 1;
5253                         list_splice_init(&tmp->dups, &good->dups);
5254                         list_del_init(&tmp->list);
5255                         list_add_tail(&tmp->list, &good->dups);
5256                         remove_cache_extent(extent_cache, &tmp->cache);
5257                         continue;
5258                 }
5259
5260                 /*
5261                  * Ok we have another non extent item backed extent rec, so lets
5262                  * just add it to this extent and carry on like we did above.
5263                  */
5264                 good->refs += tmp->refs;
5265                 list_splice_init(&tmp->backrefs, &good->backrefs);
5266                 remove_cache_extent(extent_cache, &tmp->cache);
5267                 free(tmp);
5268         }
5269         ret = insert_cache_extent(extent_cache, &good->cache);
5270         BUG_ON(ret);
5271         free(rec);
5272         return good->num_duplicates ? 0 : 1;
5273 }
5274
5275 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
5276                                     struct btrfs_root *root,
5277                                     struct extent_record *rec)
5278 {
5279         LIST_HEAD(delete_list);
5280         struct btrfs_path *path;
5281         struct extent_record *tmp, *good, *n;
5282         int nr_del = 0;
5283         int ret = 0;
5284         struct btrfs_key key;
5285
5286         path = btrfs_alloc_path();
5287         if (!path) {
5288                 ret = -ENOMEM;
5289                 goto out;
5290         }
5291
5292         good = rec;
5293         /* Find the record that covers all of the duplicates. */
5294         list_for_each_entry(tmp, &rec->dups, list) {
5295                 if (good->start < tmp->start)
5296                         continue;
5297                 if (good->nr > tmp->nr)
5298                         continue;
5299
5300                 if (tmp->start + tmp->nr < good->start + good->nr) {
5301                         fprintf(stderr, "Ok we have overlapping extents that "
5302                                 "aren't completely covered by eachother, this "
5303                                 "is going to require more careful thought.  "
5304                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
5305                                 tmp->start, tmp->nr, good->start, good->nr);
5306                         abort();
5307                 }
5308                 good = tmp;
5309         }
5310
5311         if (good != rec)
5312                 list_add_tail(&rec->list, &delete_list);
5313
5314         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
5315                 if (tmp == good)
5316                         continue;
5317                 list_move_tail(&tmp->list, &delete_list);
5318         }
5319
5320         root = root->fs_info->extent_root;
5321         list_for_each_entry(tmp, &delete_list, list) {
5322                 if (tmp->found_rec == 0)
5323                         continue;
5324                 key.objectid = tmp->start;
5325                 key.type = BTRFS_EXTENT_ITEM_KEY;
5326                 key.offset = tmp->nr;
5327
5328                 /* Shouldn't happen but just in case */
5329                 if (tmp->metadata) {
5330                         fprintf(stderr, "Well this shouldn't happen, extent "
5331                                 "record overlaps but is metadata? "
5332                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
5333                         abort();
5334                 }
5335
5336                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5337                 if (ret) {
5338                         if (ret > 0)
5339                                 ret = -EINVAL;
5340                         goto out;
5341                 }
5342                 ret = btrfs_del_item(trans, root, path);
5343                 if (ret)
5344                         goto out;
5345                 btrfs_release_path(path);
5346                 nr_del++;
5347         }
5348
5349 out:
5350         while (!list_empty(&delete_list)) {
5351                 tmp = list_entry(delete_list.next, struct extent_record, list);
5352                 list_del_init(&tmp->list);
5353                 if (tmp == rec)
5354                         continue;
5355                 free(tmp);
5356         }
5357
5358         while (!list_empty(&rec->dups)) {
5359                 tmp = list_entry(rec->dups.next, struct extent_record, list);
5360                 list_del_init(&tmp->list);
5361                 free(tmp);
5362         }
5363
5364         btrfs_free_path(path);
5365
5366         if (!ret && !nr_del)
5367                 rec->num_duplicates = 0;
5368
5369         return ret ? ret : nr_del;
5370 }
5371
5372 static int find_possible_backrefs(struct btrfs_trans_handle *trans,
5373                                   struct btrfs_fs_info *info,
5374                                   struct btrfs_path *path,
5375                                   struct cache_tree *extent_cache,
5376                                   struct extent_record *rec)
5377 {
5378         struct btrfs_root *root;
5379         struct extent_backref *back;
5380         struct data_backref *dback;
5381         struct cache_extent *cache;
5382         struct btrfs_file_extent_item *fi;
5383         struct btrfs_key key;
5384         u64 bytenr, bytes;
5385         int ret;
5386
5387         list_for_each_entry(back, &rec->backrefs, list) {
5388                 /* Don't care about full backrefs (poor unloved backrefs) */
5389                 if (back->full_backref || !back->is_data)
5390                         continue;
5391
5392                 dback = (struct data_backref *)back;
5393
5394                 /* We found this one, we don't need to do a lookup */
5395                 if (dback->found_ref)
5396                         continue;
5397
5398                 key.objectid = dback->root;
5399                 key.type = BTRFS_ROOT_ITEM_KEY;
5400                 key.offset = (u64)-1;
5401
5402                 root = btrfs_read_fs_root(info, &key);
5403
5404                 /* No root, definitely a bad ref, skip */
5405                 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
5406                         continue;
5407                 /* Other err, exit */
5408                 if (IS_ERR(root))
5409                         return PTR_ERR(root);
5410
5411                 key.objectid = dback->owner;
5412                 key.type = BTRFS_EXTENT_DATA_KEY;
5413                 key.offset = dback->offset;
5414                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5415                 if (ret) {
5416                         btrfs_release_path(path);
5417                         if (ret < 0)
5418                                 return ret;
5419                         /* Didn't find it, we can carry on */
5420                         ret = 0;
5421                         continue;
5422                 }
5423
5424                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5425                                     struct btrfs_file_extent_item);
5426                 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
5427                 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
5428                 btrfs_release_path(path);
5429                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
5430                 if (cache) {
5431                         struct extent_record *tmp;
5432                         tmp = container_of(cache, struct extent_record, cache);
5433
5434                         /*
5435                          * If we found an extent record for the bytenr for this
5436                          * particular backref then we can't add it to our
5437                          * current extent record.  We only want to add backrefs
5438                          * that don't have a corresponding extent item in the
5439                          * extent tree since they likely belong to this record
5440                          * and we need to fix it if it doesn't match bytenrs.
5441                          */
5442                         if  (tmp->found_rec)
5443                                 continue;
5444                 }
5445
5446                 dback->found_ref += 1;
5447                 dback->disk_bytenr = bytenr;
5448                 dback->bytes = bytes;
5449
5450                 /*
5451                  * Set this so the verify backref code knows not to trust the
5452                  * values in this backref.
5453                  */
5454                 back->broken = 1;
5455         }
5456
5457         return 0;
5458 }
5459
5460 /*
5461  * when an incorrect extent item is found, this will delete
5462  * all of the existing entries for it and recreate them
5463  * based on what the tree scan found.
5464  */
5465 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
5466                              struct btrfs_fs_info *info,
5467                              struct cache_tree *extent_cache,
5468                              struct extent_record *rec)
5469 {
5470         int ret;
5471         struct btrfs_path *path;
5472         struct list_head *cur = rec->backrefs.next;
5473         struct cache_extent *cache;
5474         struct extent_backref *back;
5475         int allocated = 0;
5476         u64 flags = 0;
5477
5478         /*
5479          * remember our flags for recreating the extent.
5480          * FIXME, if we have cleared extent tree, we can not
5481          * lookup extent info in extent tree.
5482          */
5483         if (!init_extent_tree) {
5484                 ret = btrfs_lookup_extent_info(NULL, info->extent_root,
5485                                         rec->start, rec->max_size,
5486                                         rec->metadata, NULL, &flags);
5487                 if (ret < 0)
5488                         flags = 0;
5489         } else {
5490                 flags = 0;
5491         }
5492
5493         path = btrfs_alloc_path();
5494         if (!path)
5495                 return -ENOMEM;
5496
5497         if (rec->refs != rec->extent_item_refs && !rec->metadata) {
5498                 /*
5499                  * Sometimes the backrefs themselves are so broken they don't
5500                  * get attached to any meaningful rec, so first go back and
5501                  * check any of our backrefs that we couldn't find and throw
5502                  * them into the list if we find the backref so that
5503                  * verify_backrefs can figure out what to do.
5504                  */
5505                 ret = find_possible_backrefs(trans, info, path, extent_cache,
5506                                              rec);
5507                 if (ret < 0)
5508                         goto out;
5509         }
5510
5511         /* step one, make sure all of the backrefs agree */
5512         ret = verify_backrefs(trans, info, path, rec);
5513         if (ret < 0)
5514                 goto out;
5515
5516         /* step two, delete all the existing records */
5517         ret = delete_extent_records(trans, info->extent_root, path,
5518                                     rec->start, rec->max_size);
5519
5520         if (ret < 0)
5521                 goto out;
5522
5523         /* was this block corrupt?  If so, don't add references to it */
5524         cache = lookup_cache_extent(info->corrupt_blocks,
5525                                     rec->start, rec->max_size);
5526         if (cache) {
5527                 ret = 0;
5528                 goto out;
5529         }
5530
5531         /* step three, recreate all the refs we did find */
5532         while(cur != &rec->backrefs) {
5533                 back = list_entry(cur, struct extent_backref, list);
5534                 cur = cur->next;
5535
5536                 /*
5537                  * if we didn't find any references, don't create a
5538                  * new extent record
5539                  */
5540                 if (!back->found_ref)
5541                         continue;
5542
5543                 ret = record_extent(trans, info, path, rec, back, allocated, flags);
5544                 allocated = 1;
5545
5546                 if (ret)
5547                         goto out;
5548         }
5549 out:
5550         btrfs_free_path(path);
5551         return ret;
5552 }
5553
5554 /* right now we only prune from the extent allocation tree */
5555 static int prune_one_block(struct btrfs_trans_handle *trans,
5556                            struct btrfs_fs_info *info,
5557                            struct btrfs_corrupt_block *corrupt)
5558 {
5559         int ret;
5560         struct btrfs_path path;
5561         struct extent_buffer *eb;
5562         u64 found;
5563         int slot;
5564         int nritems;
5565         int level = corrupt->level + 1;
5566
5567         btrfs_init_path(&path);
5568 again:
5569         /* we want to stop at the parent to our busted block */
5570         path.lowest_level = level;
5571
5572         ret = btrfs_search_slot(trans, info->extent_root,
5573                                 &corrupt->key, &path, -1, 1);
5574
5575         if (ret < 0)
5576                 goto out;
5577
5578         eb = path.nodes[level];
5579         if (!eb) {
5580                 ret = -ENOENT;
5581                 goto out;
5582         }
5583
5584         /*
5585          * hopefully the search gave us the block we want to prune,
5586          * lets try that first
5587          */
5588         slot = path.slots[level];
5589         found =  btrfs_node_blockptr(eb, slot);
5590         if (found == corrupt->cache.start)
5591                 goto del_ptr;
5592
5593         nritems = btrfs_header_nritems(eb);
5594
5595         /* the search failed, lets scan this node and hope we find it */
5596         for (slot = 0; slot < nritems; slot++) {
5597                 found =  btrfs_node_blockptr(eb, slot);
5598                 if (found == corrupt->cache.start)
5599                         goto del_ptr;
5600         }
5601         /*
5602          * we couldn't find the bad block.  TODO, search all the nodes for pointers
5603          * to this block
5604          */
5605         if (eb == info->extent_root->node) {
5606                 ret = -ENOENT;
5607                 goto out;
5608         } else {
5609                 level++;
5610                 btrfs_release_path(&path);
5611                 goto again;
5612         }
5613
5614 del_ptr:
5615         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
5616         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
5617
5618 out:
5619         btrfs_release_path(&path);
5620         return ret;
5621 }
5622
5623 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
5624                                 struct btrfs_fs_info *info)
5625 {
5626         struct cache_extent *cache;
5627         struct btrfs_corrupt_block *corrupt;
5628
5629         cache = search_cache_extent(info->corrupt_blocks, 0);
5630         while (1) {
5631                 if (!cache)
5632                         break;
5633                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
5634                 prune_one_block(trans, info, corrupt);
5635                 cache = next_cache_extent(cache);
5636         }
5637         return 0;
5638 }
5639
5640 static void free_corrupt_block(struct cache_extent *cache)
5641 {
5642         struct btrfs_corrupt_block *corrupt;
5643
5644         corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
5645         free(corrupt);
5646 }
5647
5648 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
5649
5650 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
5651 {
5652         struct btrfs_block_group_cache *cache;
5653         u64 start, end;
5654         int ret;
5655
5656         while (1) {
5657                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
5658                                             &start, &end, EXTENT_DIRTY);
5659                 if (ret)
5660                         break;
5661                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
5662                                    GFP_NOFS);
5663         }
5664
5665         start = 0;
5666         while (1) {
5667                 cache = btrfs_lookup_first_block_group(fs_info, start);
5668                 if (!cache)
5669                         break;
5670                 if (cache->cached)
5671                         cache->cached = 0;
5672                 start = cache->key.objectid + cache->key.offset;
5673         }
5674 }
5675
5676 static int check_extent_refs(struct btrfs_trans_handle *trans,
5677                              struct btrfs_root *root,
5678                              struct cache_tree *extent_cache)
5679 {
5680         struct extent_record *rec;
5681         struct cache_extent *cache;
5682         int err = 0;
5683         int ret = 0;
5684         int fixed = 0;
5685         int had_dups = 0;
5686
5687         if (repair) {
5688                 /*
5689                  * if we're doing a repair, we have to make sure
5690                  * we don't allocate from the problem extents.
5691                  * In the worst case, this will be all the
5692                  * extents in the FS
5693                  */
5694                 cache = search_cache_extent(extent_cache, 0);
5695                 while(cache) {
5696                         rec = container_of(cache, struct extent_record, cache);
5697                         btrfs_pin_extent(root->fs_info,
5698                                          rec->start, rec->max_size);
5699                         cache = next_cache_extent(cache);
5700                 }
5701
5702                 /* pin down all the corrupted blocks too */
5703                 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
5704                 while(cache) {
5705                         btrfs_pin_extent(root->fs_info,
5706                                          cache->start, cache->size);
5707                         cache = next_cache_extent(cache);
5708                 }
5709                 prune_corrupt_blocks(trans, root->fs_info);
5710                 reset_cached_block_groups(root->fs_info);
5711         }
5712
5713         /*
5714          * We need to delete any duplicate entries we find first otherwise we
5715          * could mess up the extent tree when we have backrefs that actually
5716          * belong to a different extent item and not the weird duplicate one.
5717          */
5718         while (repair && !list_empty(&duplicate_extents)) {
5719                 rec = list_entry(duplicate_extents.next, struct extent_record,
5720                                  list);
5721                 list_del_init(&rec->list);
5722
5723                 /* Sometimes we can find a backref before we find an actual
5724                  * extent, so we need to process it a little bit to see if there
5725                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
5726                  * if this is a backref screwup.  If we need to delete stuff
5727                  * process_duplicates() will return 0, otherwise it will return
5728                  * 1 and we
5729                  */
5730                 if (process_duplicates(root, extent_cache, rec))
5731                         continue;
5732                 ret = delete_duplicate_records(trans, root, rec);
5733                 if (ret < 0)
5734                         return ret;
5735                 /*
5736                  * delete_duplicate_records will return the number of entries
5737                  * deleted, so if it's greater than 0 then we know we actually
5738                  * did something and we need to remove.
5739                  */
5740                 if (ret)
5741                         had_dups = 1;
5742         }
5743
5744         if (had_dups)
5745                 return -EAGAIN;
5746
5747         while(1) {
5748                 fixed = 0;
5749                 cache = search_cache_extent(extent_cache, 0);
5750                 if (!cache)
5751                         break;
5752                 rec = container_of(cache, struct extent_record, cache);
5753                 if (rec->num_duplicates) {
5754                         fprintf(stderr, "extent item %llu has multiple extent "
5755                                 "items\n", (unsigned long long)rec->start);
5756                         err = 1;
5757                 }
5758
5759                 if (rec->refs != rec->extent_item_refs) {
5760                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
5761                                 (unsigned long long)rec->start,
5762                                 (unsigned long long)rec->nr);
5763                         fprintf(stderr, "extent item %llu, found %llu\n",
5764                                 (unsigned long long)rec->extent_item_refs,
5765                                 (unsigned long long)rec->refs);
5766                         if (!fixed && repair) {
5767                                 ret = fixup_extent_refs(trans, root->fs_info,
5768                                                         extent_cache, rec);
5769                                 if (ret)
5770                                         goto repair_abort;
5771                                 fixed = 1;
5772                         }
5773                         err = 1;
5774
5775                 }
5776                 if (all_backpointers_checked(rec, 1)) {
5777                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
5778                                 (unsigned long long)rec->start,
5779                                 (unsigned long long)rec->nr);
5780
5781                         if (!fixed && repair) {
5782                                 ret = fixup_extent_refs(trans, root->fs_info,
5783                                                         extent_cache, rec);
5784                                 if (ret)
5785                                         goto repair_abort;
5786                                 fixed = 1;
5787                         }
5788
5789                         err = 1;
5790                 }
5791                 if (!rec->owner_ref_checked) {
5792                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
5793                                 (unsigned long long)rec->start,
5794                                 (unsigned long long)rec->nr);
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                         err = 1;
5803                 }
5804
5805                 remove_cache_extent(extent_cache, cache);
5806                 free_all_extent_backrefs(rec);
5807                 free(rec);
5808         }
5809 repair_abort:
5810         if (repair) {
5811                 if (ret && ret != -EAGAIN) {
5812                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
5813                         exit(1);
5814                 } else if (!ret) {
5815                         btrfs_fix_block_accounting(trans, root);
5816                 }
5817                 if (err)
5818                         fprintf(stderr, "repaired damaged extent references\n");
5819                 return ret;
5820         }
5821         return err;
5822 }
5823
5824 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
5825 {
5826         u64 stripe_size;
5827
5828         if (type & BTRFS_BLOCK_GROUP_RAID0) {
5829                 stripe_size = length;
5830                 stripe_size /= num_stripes;
5831         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
5832                 stripe_size = length * 2;
5833                 stripe_size /= num_stripes;
5834         } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
5835                 stripe_size = length;
5836                 stripe_size /= (num_stripes - 1);
5837         } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
5838                 stripe_size = length;
5839                 stripe_size /= (num_stripes - 2);
5840         } else {
5841                 stripe_size = length;
5842         }
5843         return stripe_size;
5844 }
5845
5846 static int check_chunk_refs(struct chunk_record *chunk_rec,
5847                             struct block_group_tree *block_group_cache,
5848                             struct device_extent_tree *dev_extent_cache,
5849                             int silent)
5850 {
5851         struct cache_extent *block_group_item;
5852         struct block_group_record *block_group_rec;
5853         struct cache_extent *dev_extent_item;
5854         struct device_extent_record *dev_extent_rec;
5855         u64 devid;
5856         u64 offset;
5857         u64 length;
5858         int i;
5859         int ret = 0;
5860
5861         block_group_item = lookup_cache_extent(&block_group_cache->tree,
5862                                                chunk_rec->offset,
5863                                                chunk_rec->length);
5864         if (block_group_item) {
5865                 block_group_rec = container_of(block_group_item,
5866                                                struct block_group_record,
5867                                                cache);
5868                 if (chunk_rec->length != block_group_rec->offset ||
5869                     chunk_rec->offset != block_group_rec->objectid ||
5870                     chunk_rec->type_flags != block_group_rec->flags) {
5871                         if (!silent)
5872                                 fprintf(stderr,
5873                                         "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
5874                                         chunk_rec->objectid,
5875                                         chunk_rec->type,
5876                                         chunk_rec->offset,
5877                                         chunk_rec->length,
5878                                         chunk_rec->offset,
5879                                         chunk_rec->type_flags,
5880                                         block_group_rec->objectid,
5881                                         block_group_rec->type,
5882                                         block_group_rec->offset,
5883                                         block_group_rec->offset,
5884                                         block_group_rec->objectid,
5885                                         block_group_rec->flags);
5886                         ret = -1;
5887                 } else {
5888                         list_del_init(&block_group_rec->list);
5889                         chunk_rec->bg_rec = block_group_rec;
5890                 }
5891         } else {
5892                 if (!silent)
5893                         fprintf(stderr,
5894                                 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
5895                                 chunk_rec->objectid,
5896                                 chunk_rec->type,
5897                                 chunk_rec->offset,
5898                                 chunk_rec->length,
5899                                 chunk_rec->offset,
5900                                 chunk_rec->type_flags);
5901                 ret = -1;
5902         }
5903
5904         length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
5905                                     chunk_rec->num_stripes);
5906         for (i = 0; i < chunk_rec->num_stripes; ++i) {
5907                 devid = chunk_rec->stripes[i].devid;
5908                 offset = chunk_rec->stripes[i].offset;
5909                 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
5910                                                        devid, offset, length);
5911                 if (dev_extent_item) {
5912                         dev_extent_rec = container_of(dev_extent_item,
5913                                                 struct device_extent_record,
5914                                                 cache);
5915                         if (dev_extent_rec->objectid != devid ||
5916                             dev_extent_rec->offset != offset ||
5917                             dev_extent_rec->chunk_offset != chunk_rec->offset ||
5918                             dev_extent_rec->length != length) {
5919                                 if (!silent)
5920                                         fprintf(stderr,
5921                                                 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
5922                                                 chunk_rec->objectid,
5923                                                 chunk_rec->type,
5924                                                 chunk_rec->offset,
5925                                                 chunk_rec->stripes[i].devid,
5926                                                 chunk_rec->stripes[i].offset,
5927                                                 dev_extent_rec->objectid,
5928                                                 dev_extent_rec->offset,
5929                                                 dev_extent_rec->length);
5930                                 ret = -1;
5931                         } else {
5932                                 list_move(&dev_extent_rec->chunk_list,
5933                                           &chunk_rec->dextents);
5934                         }
5935                 } else {
5936                         if (!silent)
5937                                 fprintf(stderr,
5938                                         "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
5939                                         chunk_rec->objectid,
5940                                         chunk_rec->type,
5941                                         chunk_rec->offset,
5942                                         chunk_rec->stripes[i].devid,
5943                                         chunk_rec->stripes[i].offset);
5944                         ret = -1;
5945                 }
5946         }
5947         return ret;
5948 }
5949
5950 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
5951 int check_chunks(struct cache_tree *chunk_cache,
5952                  struct block_group_tree *block_group_cache,
5953                  struct device_extent_tree *dev_extent_cache,
5954                  struct list_head *good, struct list_head *bad, int silent)
5955 {
5956         struct cache_extent *chunk_item;
5957         struct chunk_record *chunk_rec;
5958         struct block_group_record *bg_rec;
5959         struct device_extent_record *dext_rec;
5960         int err;
5961         int ret = 0;
5962
5963         chunk_item = first_cache_extent(chunk_cache);
5964         while (chunk_item) {
5965                 chunk_rec = container_of(chunk_item, struct chunk_record,
5966                                          cache);
5967                 err = check_chunk_refs(chunk_rec, block_group_cache,
5968                                        dev_extent_cache, silent);
5969                 if (err) {
5970                         ret = err;
5971                         if (bad)
5972                                 list_add_tail(&chunk_rec->list, bad);
5973                 } else {
5974                         if (good)
5975                                 list_add_tail(&chunk_rec->list, good);
5976                 }
5977
5978                 chunk_item = next_cache_extent(chunk_item);
5979         }
5980
5981         list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
5982                 if (!silent)
5983                         fprintf(stderr,
5984                                 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
5985                                 bg_rec->objectid,
5986                                 bg_rec->offset,
5987                                 bg_rec->flags);
5988                 if (!ret)
5989                         ret = 1;
5990         }
5991
5992         list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
5993                             chunk_list) {
5994                 if (!silent)
5995                         fprintf(stderr,
5996                                 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
5997                                 dext_rec->objectid,
5998                                 dext_rec->offset,
5999                                 dext_rec->length);
6000                 if (!ret)
6001                         ret = 1;
6002         }
6003         return ret;
6004 }
6005
6006
6007 static int check_device_used(struct device_record *dev_rec,
6008                              struct device_extent_tree *dext_cache)
6009 {
6010         struct cache_extent *cache;
6011         struct device_extent_record *dev_extent_rec;
6012         u64 total_byte = 0;
6013
6014         cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
6015         while (cache) {
6016                 dev_extent_rec = container_of(cache,
6017                                               struct device_extent_record,
6018                                               cache);
6019                 if (dev_extent_rec->objectid != dev_rec->devid)
6020                         break;
6021
6022                 list_del(&dev_extent_rec->device_list);
6023                 total_byte += dev_extent_rec->length;
6024                 cache = next_cache_extent(cache);
6025         }
6026
6027         if (total_byte != dev_rec->byte_used) {
6028                 fprintf(stderr,
6029                         "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
6030                         total_byte, dev_rec->byte_used, dev_rec->objectid,
6031                         dev_rec->type, dev_rec->offset);
6032                 return -1;
6033         } else {
6034                 return 0;
6035         }
6036 }
6037
6038 /* check btrfs_dev_item -> btrfs_dev_extent */
6039 static int check_devices(struct rb_root *dev_cache,
6040                          struct device_extent_tree *dev_extent_cache)
6041 {
6042         struct rb_node *dev_node;
6043         struct device_record *dev_rec;
6044         struct device_extent_record *dext_rec;
6045         int err;
6046         int ret = 0;
6047
6048         dev_node = rb_first(dev_cache);
6049         while (dev_node) {
6050                 dev_rec = container_of(dev_node, struct device_record, node);
6051                 err = check_device_used(dev_rec, dev_extent_cache);
6052                 if (err)
6053                         ret = err;
6054
6055                 dev_node = rb_next(dev_node);
6056         }
6057         list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
6058                             device_list) {
6059                 fprintf(stderr,
6060                         "Device extent[%llu, %llu, %llu] didn't find its device.\n",
6061                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
6062                 if (!ret)
6063                         ret = 1;
6064         }
6065         return ret;
6066 }
6067
6068 static int check_chunks_and_extents(struct btrfs_root *root)
6069 {
6070         struct rb_root dev_cache;
6071         struct cache_tree chunk_cache;
6072         struct block_group_tree block_group_cache;
6073         struct device_extent_tree dev_extent_cache;
6074         struct cache_tree extent_cache;
6075         struct cache_tree seen;
6076         struct cache_tree pending;
6077         struct cache_tree reada;
6078         struct cache_tree nodes;
6079         struct cache_tree corrupt_blocks;
6080         struct btrfs_path path;
6081         struct btrfs_key key;
6082         struct btrfs_key found_key;
6083         int ret, err = 0;
6084         u64 last = 0;
6085         struct block_info *bits;
6086         int bits_nr;
6087         struct extent_buffer *leaf;
6088         struct btrfs_trans_handle *trans = NULL;
6089         int slot;
6090         struct btrfs_root_item ri;
6091         struct list_head dropping_trees;
6092
6093         dev_cache = RB_ROOT;
6094         cache_tree_init(&chunk_cache);
6095         block_group_tree_init(&block_group_cache);
6096         device_extent_tree_init(&dev_extent_cache);
6097
6098         cache_tree_init(&extent_cache);
6099         cache_tree_init(&seen);
6100         cache_tree_init(&pending);
6101         cache_tree_init(&nodes);
6102         cache_tree_init(&reada);
6103         cache_tree_init(&corrupt_blocks);
6104         INIT_LIST_HEAD(&dropping_trees);
6105
6106         if (repair) {
6107                 trans = btrfs_start_transaction(root, 1);
6108                 if (IS_ERR(trans)) {
6109                         fprintf(stderr, "Error starting transaction\n");
6110                         return PTR_ERR(trans);
6111                 }
6112                 root->fs_info->fsck_extent_cache = &extent_cache;
6113                 root->fs_info->free_extent_hook = free_extent_hook;
6114                 root->fs_info->corrupt_blocks = &corrupt_blocks;
6115         }
6116
6117         bits_nr = 1024;
6118         bits = malloc(bits_nr * sizeof(struct block_info));
6119         if (!bits) {
6120                 perror("malloc");
6121                 exit(1);
6122         }
6123
6124 again:
6125         add_root_to_pending(root->fs_info->tree_root->node,
6126                             &extent_cache, &pending, &seen, &nodes,
6127                             &root->fs_info->tree_root->root_key);
6128
6129         add_root_to_pending(root->fs_info->chunk_root->node,
6130                             &extent_cache, &pending, &seen, &nodes,
6131                             &root->fs_info->chunk_root->root_key);
6132
6133         btrfs_init_path(&path);
6134         key.offset = 0;
6135         key.objectid = 0;
6136         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
6137         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
6138                                         &key, &path, 0, 0);
6139         if (ret < 0)
6140                 goto out;
6141         while(1) {
6142                 leaf = path.nodes[0];
6143                 slot = path.slots[0];
6144                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
6145                         ret = btrfs_next_leaf(root, &path);
6146                         if (ret != 0)
6147                                 break;
6148                         leaf = path.nodes[0];
6149                         slot = path.slots[0];
6150                 }
6151                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
6152                 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
6153                         unsigned long offset;
6154                         struct extent_buffer *buf;
6155
6156                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
6157                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
6158                         if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
6159                                 buf = read_tree_block(root->fs_info->tree_root,
6160                                                       btrfs_root_bytenr(&ri),
6161                                                       btrfs_level_size(root,
6162                                                       btrfs_root_level(&ri)),
6163                                                       0);
6164                                 if (!buf) {
6165                                         ret = -EIO;
6166                                         goto out;
6167                                 }
6168                                 add_root_to_pending(buf, &extent_cache,
6169                                                     &pending, &seen, &nodes,
6170                                                     &found_key);
6171                                 free_extent_buffer(buf);
6172                         } else {
6173                                 struct dropping_root_item_record *dri_rec;
6174                                 dri_rec = malloc(sizeof(*dri_rec));
6175                                 if (!dri_rec) {
6176                                         perror("malloc");
6177                                         exit(1);
6178                                 }
6179                                 memcpy(&dri_rec->ri, &ri, sizeof(ri));
6180                                 memcpy(&dri_rec->found_key, &found_key,
6181                                        sizeof(found_key));
6182                                 list_add_tail(&dri_rec->list, &dropping_trees);
6183                         }
6184                 }
6185                 path.slots[0]++;
6186         }
6187         btrfs_release_path(&path);
6188         while (1) {
6189                 ret = run_next_block(trans, root, bits, bits_nr, &last,
6190                                      &pending, &seen, &reada, &nodes,
6191                                      &extent_cache, &chunk_cache, &dev_cache,
6192                                      &block_group_cache, &dev_extent_cache,
6193                                      NULL);
6194                 if (ret != 0)
6195                         break;
6196         }
6197
6198         while (!list_empty(&dropping_trees)) {
6199                 struct dropping_root_item_record *rec;
6200                 struct extent_buffer *buf;
6201                 rec = list_entry(dropping_trees.next,
6202                                  struct dropping_root_item_record, list);
6203                 last = 0;
6204                 if (!bits) {
6205                         perror("realloc");
6206                         exit(1);
6207                 }
6208                 buf = read_tree_block(root->fs_info->tree_root,
6209                                       btrfs_root_bytenr(&rec->ri),
6210                                       btrfs_level_size(root,
6211                                       btrfs_root_level(&rec->ri)), 0);
6212                 if (!buf) {
6213                         ret = -EIO;
6214                         goto out;
6215                 }
6216                 add_root_to_pending(buf, &extent_cache, &pending,
6217                                     &seen, &nodes, &rec->found_key);
6218                 while (1) {
6219                         ret = run_next_block(trans, root, bits, bits_nr, &last,
6220                                              &pending, &seen, &reada,
6221                                              &nodes, &extent_cache,
6222                                              &chunk_cache, &dev_cache,
6223                                              &block_group_cache,
6224                                              &dev_extent_cache,
6225                                              &rec->ri);
6226                         if (ret != 0)
6227                                 break;
6228                 }
6229                 free_extent_buffer(buf);
6230                 list_del(&rec->list);
6231                 free(rec);
6232         }
6233
6234         if (ret >= 0)
6235                 ret = check_extent_refs(trans, root, &extent_cache);
6236         if (ret == -EAGAIN) {
6237                 ret = btrfs_commit_transaction(trans, root);
6238                 if (ret)
6239                         goto out;
6240
6241                 trans = btrfs_start_transaction(root, 1);
6242                 if (IS_ERR(trans)) {
6243                         ret = PTR_ERR(trans);
6244                         goto out;
6245                 }
6246
6247                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
6248                 free_extent_cache_tree(&seen);
6249                 free_extent_cache_tree(&pending);
6250                 free_extent_cache_tree(&reada);
6251                 free_extent_cache_tree(&nodes);
6252                 free_extent_record_cache(root->fs_info, &extent_cache);
6253                 goto again;
6254         }
6255
6256         err = check_chunks(&chunk_cache, &block_group_cache,
6257                            &dev_extent_cache, NULL, NULL, 0);
6258         if (err && !ret)
6259                 ret = err;
6260
6261         err = check_devices(&dev_cache, &dev_extent_cache);
6262         if (err && !ret)
6263                 ret = err;
6264
6265 out:
6266         if (trans) {
6267                 err = btrfs_commit_transaction(trans, root);
6268                 if (!ret)
6269                         ret = err;
6270         }
6271         if (repair) {
6272                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
6273                 root->fs_info->fsck_extent_cache = NULL;
6274                 root->fs_info->free_extent_hook = NULL;
6275                 root->fs_info->corrupt_blocks = NULL;
6276         }
6277         free(bits);
6278         free_chunk_cache_tree(&chunk_cache);
6279         free_device_cache_tree(&dev_cache);
6280         free_block_group_tree(&block_group_cache);
6281         free_device_extent_tree(&dev_extent_cache);
6282         free_extent_cache_tree(&seen);
6283         free_extent_cache_tree(&pending);
6284         free_extent_cache_tree(&reada);
6285         free_extent_cache_tree(&nodes);
6286         return ret;
6287 }
6288
6289 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
6290                            struct btrfs_root *root, int overwrite)
6291 {
6292         struct extent_buffer *c;
6293         struct extent_buffer *old = root->node;
6294         int level;
6295         int ret;
6296         struct btrfs_disk_key disk_key = {0,0,0};
6297
6298         level = 0;
6299
6300         if (overwrite) {
6301                 c = old;
6302                 extent_buffer_get(c);
6303                 goto init;
6304         }
6305         c = btrfs_alloc_free_block(trans, root,
6306                                    btrfs_level_size(root, 0),
6307                                    root->root_key.objectid,
6308                                    &disk_key, level, 0, 0);
6309         if (IS_ERR(c)) {
6310                 c = old;
6311                 extent_buffer_get(c);
6312                 overwrite = 1;
6313         }
6314 init:
6315         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
6316         btrfs_set_header_level(c, level);
6317         btrfs_set_header_bytenr(c, c->start);
6318         btrfs_set_header_generation(c, trans->transid);
6319         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
6320         btrfs_set_header_owner(c, root->root_key.objectid);
6321
6322         write_extent_buffer(c, root->fs_info->fsid,
6323                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
6324
6325         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
6326                             btrfs_header_chunk_tree_uuid(c),
6327                             BTRFS_UUID_SIZE);
6328
6329         btrfs_mark_buffer_dirty(c);
6330         /*
6331          * this case can happen in the following case:
6332          *
6333          * 1.overwrite previous root.
6334          *
6335          * 2.reinit reloc data root, this is because we skip pin
6336          * down reloc data tree before which means we can allocate
6337          * same block bytenr here.
6338          */
6339         if (old->start == c->start) {
6340                 btrfs_set_root_generation(&root->root_item,
6341                                           trans->transid);
6342                 root->root_item.level = btrfs_header_level(root->node);
6343                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
6344                                         &root->root_key, &root->root_item);
6345                 if (ret) {
6346                         free_extent_buffer(c);
6347                         return ret;
6348                 }
6349         }
6350         free_extent_buffer(old);
6351         root->node = c;
6352         add_root_to_dirty_list(root);
6353         return 0;
6354 }
6355
6356 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
6357                                 struct extent_buffer *eb, int tree_root)
6358 {
6359         struct extent_buffer *tmp;
6360         struct btrfs_root_item *ri;
6361         struct btrfs_key key;
6362         u64 bytenr;
6363         u32 leafsize;
6364         int level = btrfs_header_level(eb);
6365         int nritems;
6366         int ret;
6367         int i;
6368
6369         /*
6370          * If we have pinned this block before, don't pin it again.
6371          * This can not only avoid forever loop with broken filesystem
6372          * but also give us some speedups.
6373          */
6374         if (test_range_bit(&fs_info->pinned_extents, eb->start,
6375                            eb->start + eb->len - 1, EXTENT_DIRTY, 0))
6376                 return 0;
6377
6378         btrfs_pin_extent(fs_info, eb->start, eb->len);
6379
6380         leafsize = btrfs_super_leafsize(fs_info->super_copy);
6381         nritems = btrfs_header_nritems(eb);
6382         for (i = 0; i < nritems; i++) {
6383                 if (level == 0) {
6384                         btrfs_item_key_to_cpu(eb, &key, i);
6385                         if (key.type != BTRFS_ROOT_ITEM_KEY)
6386                                 continue;
6387                         /* Skip the extent root and reloc roots */
6388                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
6389                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
6390                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
6391                                 continue;
6392                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
6393                         bytenr = btrfs_disk_root_bytenr(eb, ri);
6394
6395                         /*
6396                          * If at any point we start needing the real root we
6397                          * will have to build a stump root for the root we are
6398                          * in, but for now this doesn't actually use the root so
6399                          * just pass in extent_root.
6400                          */
6401                         tmp = read_tree_block(fs_info->extent_root, bytenr,
6402                                               leafsize, 0);
6403                         if (!tmp) {
6404                                 fprintf(stderr, "Error reading root block\n");
6405                                 return -EIO;
6406                         }
6407                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
6408                         free_extent_buffer(tmp);
6409                         if (ret)
6410                                 return ret;
6411                 } else {
6412                         bytenr = btrfs_node_blockptr(eb, i);
6413
6414                         /* If we aren't the tree root don't read the block */
6415                         if (level == 1 && !tree_root) {
6416                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
6417                                 continue;
6418                         }
6419
6420                         tmp = read_tree_block(fs_info->extent_root, bytenr,
6421                                               leafsize, 0);
6422                         if (!tmp) {
6423                                 fprintf(stderr, "Error reading tree block\n");
6424                                 return -EIO;
6425                         }
6426                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
6427                         free_extent_buffer(tmp);
6428                         if (ret)
6429                                 return ret;
6430                 }
6431         }
6432
6433         return 0;
6434 }
6435
6436 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
6437 {
6438         int ret;
6439
6440         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
6441         if (ret)
6442                 return ret;
6443
6444         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
6445 }
6446
6447 static int reset_block_groups(struct btrfs_fs_info *fs_info)
6448 {
6449         struct btrfs_block_group_cache *cache;
6450         struct btrfs_path *path;
6451         struct extent_buffer *leaf;
6452         struct btrfs_chunk *chunk;
6453         struct btrfs_key key;
6454         int ret;
6455         u64 start;
6456
6457         path = btrfs_alloc_path();
6458         if (!path)
6459                 return -ENOMEM;
6460
6461         key.objectid = 0;
6462         key.type = BTRFS_CHUNK_ITEM_KEY;
6463         key.offset = 0;
6464
6465         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
6466         if (ret < 0) {
6467                 btrfs_free_path(path);
6468                 return ret;
6469         }
6470
6471         /*
6472          * We do this in case the block groups were screwed up and had alloc
6473          * bits that aren't actually set on the chunks.  This happens with
6474          * restored images every time and could happen in real life I guess.
6475          */
6476         fs_info->avail_data_alloc_bits = 0;
6477         fs_info->avail_metadata_alloc_bits = 0;
6478         fs_info->avail_system_alloc_bits = 0;
6479
6480         /* First we need to create the in-memory block groups */
6481         while (1) {
6482                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6483                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
6484                         if (ret < 0) {
6485                                 btrfs_free_path(path);
6486                                 return ret;
6487                         }
6488                         if (ret) {
6489                                 ret = 0;
6490                                 break;
6491                         }
6492                 }
6493                 leaf = path->nodes[0];
6494                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6495                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
6496                         path->slots[0]++;
6497                         continue;
6498                 }
6499
6500                 chunk = btrfs_item_ptr(leaf, path->slots[0],
6501                                        struct btrfs_chunk);
6502                 btrfs_add_block_group(fs_info, 0,
6503                                       btrfs_chunk_type(leaf, chunk),
6504                                       key.objectid, key.offset,
6505                                       btrfs_chunk_length(leaf, chunk));
6506                 set_extent_dirty(&fs_info->free_space_cache, key.offset,
6507                                  key.offset + btrfs_chunk_length(leaf, chunk),
6508                                  GFP_NOFS);
6509                 path->slots[0]++;
6510         }
6511         start = 0;
6512         while (1) {
6513                 cache = btrfs_lookup_first_block_group(fs_info, start);
6514                 if (!cache)
6515                         break;
6516                 cache->cached = 1;
6517                 start = cache->key.objectid + cache->key.offset;
6518         }
6519
6520         btrfs_free_path(path);
6521         return 0;
6522 }
6523
6524 static int reset_balance(struct btrfs_trans_handle *trans,
6525                          struct btrfs_fs_info *fs_info)
6526 {
6527         struct btrfs_root *root = fs_info->tree_root;
6528         struct btrfs_path *path;
6529         struct extent_buffer *leaf;
6530         struct btrfs_key key;
6531         int del_slot, del_nr = 0;
6532         int ret;
6533         int found = 0;
6534
6535         path = btrfs_alloc_path();
6536         if (!path)
6537                 return -ENOMEM;
6538
6539         key.objectid = BTRFS_BALANCE_OBJECTID;
6540         key.type = BTRFS_BALANCE_ITEM_KEY;
6541         key.offset = 0;
6542
6543         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6544         if (ret) {
6545                 if (ret > 0)
6546                         ret = 0;
6547                 if (!ret)
6548                         goto reinit_data_reloc;
6549                 else
6550                         goto out;
6551         }
6552
6553         ret = btrfs_del_item(trans, root, path);
6554         if (ret)
6555                 goto out;
6556         btrfs_release_path(path);
6557
6558         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
6559         key.type = BTRFS_ROOT_ITEM_KEY;
6560         key.offset = 0;
6561
6562         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6563         if (ret < 0)
6564                 goto out;
6565         while (1) {
6566                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6567                         if (!found)
6568                                 break;
6569
6570                         if (del_nr) {
6571                                 ret = btrfs_del_items(trans, root, path,
6572                                                       del_slot, del_nr);
6573                                 del_nr = 0;
6574                                 if (ret)
6575                                         goto out;
6576                         }
6577                         key.offset++;
6578                         btrfs_release_path(path);
6579
6580                         found = 0;
6581                         ret = btrfs_search_slot(trans, root, &key, path,
6582                                                 -1, 1);
6583                         if (ret < 0)
6584                                 goto out;
6585                         continue;
6586                 }
6587                 found = 1;
6588                 leaf = path->nodes[0];
6589                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6590                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
6591                         break;
6592                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
6593                         path->slots[0]++;
6594                         continue;
6595                 }
6596                 if (!del_nr) {
6597                         del_slot = path->slots[0];
6598                         del_nr = 1;
6599                 } else {
6600                         del_nr++;
6601                 }
6602                 path->slots[0]++;
6603         }
6604
6605         if (del_nr) {
6606                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
6607                 if (ret)
6608                         goto out;
6609         }
6610         btrfs_release_path(path);
6611
6612 reinit_data_reloc:
6613         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
6614         key.type = BTRFS_ROOT_ITEM_KEY;
6615         key.offset = (u64)-1;
6616         root = btrfs_read_fs_root(fs_info, &key);
6617         if (IS_ERR(root)) {
6618                 fprintf(stderr, "Error reading data reloc tree\n");
6619                 return PTR_ERR(root);
6620         }
6621         record_root_in_trans(trans, root);
6622         ret = btrfs_fsck_reinit_root(trans, root, 0);
6623         if (ret)
6624                 goto out;
6625         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
6626 out:
6627         btrfs_free_path(path);
6628         return ret;
6629 }
6630
6631 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
6632                               struct btrfs_fs_info *fs_info)
6633 {
6634         u64 start = 0;
6635         int ret;
6636
6637         /*
6638          * The only reason we don't do this is because right now we're just
6639          * walking the trees we find and pinning down their bytes, we don't look
6640          * at any of the leaves.  In order to do mixed groups we'd have to check
6641          * the leaves of any fs roots and pin down the bytes for any file
6642          * extents we find.  Not hard but why do it if we don't have to?
6643          */
6644         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
6645                 fprintf(stderr, "We don't support re-initing the extent tree "
6646                         "for mixed block groups yet, please notify a btrfs "
6647                         "developer you want to do this so they can add this "
6648                         "functionality.\n");
6649                 return -EINVAL;
6650         }
6651
6652         /*
6653          * first we need to walk all of the trees except the extent tree and pin
6654          * down the bytes that are in use so we don't overwrite any existing
6655          * metadata.
6656          */
6657         ret = pin_metadata_blocks(fs_info);
6658         if (ret) {
6659                 fprintf(stderr, "error pinning down used bytes\n");
6660                 return ret;
6661         }
6662
6663         /*
6664          * Need to drop all the block groups since we're going to recreate all
6665          * of them again.
6666          */
6667         btrfs_free_block_groups(fs_info);
6668         ret = reset_block_groups(fs_info);
6669         if (ret) {
6670                 fprintf(stderr, "error resetting the block groups\n");
6671                 return ret;
6672         }
6673
6674         /* Ok we can allocate now, reinit the extent root */
6675         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
6676         if (ret) {
6677                 fprintf(stderr, "extent root initialization failed\n");
6678                 /*
6679                  * When the transaction code is updated we should end the
6680                  * transaction, but for now progs only knows about commit so
6681                  * just return an error.
6682                  */
6683                 return ret;
6684         }
6685
6686         /*
6687          * Now we have all the in-memory block groups setup so we can make
6688          * allocations properly, and the metadata we care about is safe since we
6689          * pinned all of it above.
6690          */
6691         while (1) {
6692                 struct btrfs_block_group_cache *cache;
6693
6694                 cache = btrfs_lookup_first_block_group(fs_info, start);
6695                 if (!cache)
6696                         break;
6697                 start = cache->key.objectid + cache->key.offset;
6698                 ret = btrfs_insert_item(trans, fs_info->extent_root,
6699                                         &cache->key, &cache->item,
6700                                         sizeof(cache->item));
6701                 if (ret) {
6702                         fprintf(stderr, "Error adding block group\n");
6703                         return ret;
6704                 }
6705                 btrfs_extent_post_op(trans, fs_info->extent_root);
6706         }
6707
6708         ret = reset_balance(trans, fs_info);
6709         if (ret)
6710                 fprintf(stderr, "error reseting the pending balance\n");
6711
6712         return ret;
6713 }
6714
6715 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
6716 {
6717         struct btrfs_path *path;
6718         struct btrfs_trans_handle *trans;
6719         struct btrfs_key key;
6720         int ret;
6721
6722         printf("Recowing metadata block %llu\n", eb->start);
6723         key.objectid = btrfs_header_owner(eb);
6724         key.type = BTRFS_ROOT_ITEM_KEY;
6725         key.offset = (u64)-1;
6726
6727         root = btrfs_read_fs_root(root->fs_info, &key);
6728         if (IS_ERR(root)) {
6729                 fprintf(stderr, "Couldn't find owner root %llu\n",
6730                         key.objectid);
6731                 return PTR_ERR(root);
6732         }
6733
6734         path = btrfs_alloc_path();
6735         if (!path)
6736                 return -ENOMEM;
6737
6738         trans = btrfs_start_transaction(root, 1);
6739         if (IS_ERR(trans)) {
6740                 btrfs_free_path(path);
6741                 return PTR_ERR(trans);
6742         }
6743
6744         path->lowest_level = btrfs_header_level(eb);
6745         if (path->lowest_level)
6746                 btrfs_node_key_to_cpu(eb, &key, 0);
6747         else
6748                 btrfs_item_key_to_cpu(eb, &key, 0);
6749
6750         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6751         btrfs_commit_transaction(trans, root);
6752         btrfs_free_path(path);
6753         return ret;
6754 }
6755
6756 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
6757 {
6758         struct btrfs_path *path;
6759         struct btrfs_trans_handle *trans;
6760         struct btrfs_key key;
6761         int ret;
6762
6763         printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
6764                bad->key.type, bad->key.offset);
6765         key.objectid = bad->root_id;
6766         key.type = BTRFS_ROOT_ITEM_KEY;
6767         key.offset = (u64)-1;
6768
6769         root = btrfs_read_fs_root(root->fs_info, &key);
6770         if (IS_ERR(root)) {
6771                 fprintf(stderr, "Couldn't find owner root %llu\n",
6772                         key.objectid);
6773                 return PTR_ERR(root);
6774         }
6775
6776         path = btrfs_alloc_path();
6777         if (!path)
6778                 return -ENOMEM;
6779
6780         trans = btrfs_start_transaction(root, 1);
6781         if (IS_ERR(trans)) {
6782                 btrfs_free_path(path);
6783                 return PTR_ERR(trans);
6784         }
6785
6786         ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
6787         if (ret) {
6788                 if (ret > 0)
6789                         ret = 0;
6790                 goto out;
6791         }
6792         ret = btrfs_del_item(trans, root, path);
6793 out:
6794         btrfs_commit_transaction(trans, root);
6795         btrfs_free_path(path);
6796         return ret;
6797 }
6798
6799 static int zero_log_tree(struct btrfs_root *root)
6800 {
6801         struct btrfs_trans_handle *trans;
6802         int ret;
6803
6804         trans = btrfs_start_transaction(root, 1);
6805         if (IS_ERR(trans)) {
6806                 ret = PTR_ERR(trans);
6807                 return ret;
6808         }
6809         btrfs_set_super_log_root(root->fs_info->super_copy, 0);
6810         btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
6811         ret = btrfs_commit_transaction(trans, root);
6812         return ret;
6813 }
6814
6815 static int populate_csum(struct btrfs_trans_handle *trans,
6816                          struct btrfs_root *csum_root, char *buf, u64 start,
6817                          u64 len)
6818 {
6819         u64 offset = 0;
6820         u64 sectorsize;
6821         int ret = 0;
6822
6823         while (offset < len) {
6824                 sectorsize = csum_root->sectorsize;
6825                 ret = read_extent_data(csum_root, buf, start + offset,
6826                                        &sectorsize, 0);
6827                 if (ret)
6828                         break;
6829                 ret = btrfs_csum_file_block(trans, csum_root, start + len,
6830                                             start + offset, buf, sectorsize);
6831                 if (ret)
6832                         break;
6833                 offset += sectorsize;
6834         }
6835         return ret;
6836 }
6837
6838 static int fill_csum_tree(struct btrfs_trans_handle *trans,
6839                           struct btrfs_root *csum_root)
6840 {
6841         struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
6842         struct btrfs_path *path;
6843         struct btrfs_extent_item *ei;
6844         struct extent_buffer *leaf;
6845         char *buf;
6846         struct btrfs_key key;
6847         int ret;
6848
6849         path = btrfs_alloc_path();
6850         if (!path)
6851                 return -ENOMEM;
6852
6853         key.objectid = 0;
6854         key.type = BTRFS_EXTENT_ITEM_KEY;
6855         key.offset = 0;
6856
6857         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
6858         if (ret < 0) {
6859                 btrfs_free_path(path);
6860                 return ret;
6861         }
6862
6863         buf = malloc(csum_root->sectorsize);
6864         if (!buf) {
6865                 btrfs_free_path(path);
6866                 return -ENOMEM;
6867         }
6868
6869         while (1) {
6870                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
6871                         ret = btrfs_next_leaf(extent_root, path);
6872                         if (ret < 0)
6873                                 break;
6874                         if (ret) {
6875                                 ret = 0;
6876                                 break;
6877                         }
6878                 }
6879                 leaf = path->nodes[0];
6880
6881                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6882                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
6883                         path->slots[0]++;
6884                         continue;
6885                 }
6886
6887                 ei = btrfs_item_ptr(leaf, path->slots[0],
6888                                     struct btrfs_extent_item);
6889                 if (!(btrfs_extent_flags(leaf, ei) &
6890                       BTRFS_EXTENT_FLAG_DATA)) {
6891                         path->slots[0]++;
6892                         continue;
6893                 }
6894
6895                 ret = populate_csum(trans, csum_root, buf, key.objectid,
6896                                     key.offset);
6897                 if (ret)
6898                         break;
6899                 path->slots[0]++;
6900         }
6901
6902         btrfs_free_path(path);
6903         free(buf);
6904         return ret;
6905 }
6906
6907 static struct option long_options[] = {
6908         { "super", 1, NULL, 's' },
6909         { "repair", 0, NULL, 0 },
6910         { "init-csum-tree", 0, NULL, 0 },
6911         { "init-extent-tree", 0, NULL, 0 },
6912         { "check-data-csum", 0, NULL, 0 },
6913         { "backup", 0, NULL, 0 },
6914         { "subvol-extents", no_argument, NULL, 'E' },
6915         { "qgroup-report", 0, NULL, 'Q' },
6916         { NULL, 0, NULL, 0}
6917 };
6918
6919 const char * const cmd_check_usage[] = {
6920         "btrfs check [options] <device>",
6921         "Check an unmounted btrfs filesystem.",
6922         "",
6923         "-s|--super <superblock>     use this superblock copy",
6924         "-b|--backup                 use the backup root copy",
6925         "--repair                    try to repair the filesystem",
6926         "--init-csum-tree            create a new CRC tree",
6927         "--init-extent-tree          create a new extent tree",
6928         "--check-data-csum           verify checkums of data blocks",
6929         "--qgroup-report             print a report on qgroup consistency",
6930         "--subvol-extents            print subvolume extents and sharing state",
6931         NULL
6932 };
6933
6934 int cmd_check(int argc, char **argv)
6935 {
6936         struct cache_tree root_cache;
6937         struct btrfs_root *root;
6938         struct btrfs_fs_info *info;
6939         u64 bytenr = 0;
6940         u64 subvolid = 0;
6941         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
6942         int ret;
6943         u64 num;
6944         int option_index = 0;
6945         int init_csum_tree = 0;
6946         int qgroup_report = 0;
6947         enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
6948
6949         while(1) {
6950                 int c;
6951                 c = getopt_long(argc, argv, "as:b", long_options,
6952                                 &option_index);
6953                 if (c < 0)
6954                         break;
6955                 switch(c) {
6956                         case 'a': /* ignored */ break;
6957                         case 'b':
6958                                 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
6959                                 break;
6960                         case 's':
6961                                 num = arg_strtou64(optarg);
6962                                 if (num >= BTRFS_SUPER_MIRROR_MAX) {
6963                                         fprintf(stderr,
6964                                                 "ERROR: super mirror should be less than: %d\n",
6965                                                 BTRFS_SUPER_MIRROR_MAX);
6966                                         exit(1);
6967                                 }
6968                                 bytenr = btrfs_sb_offset(((int)num));
6969                                 printf("using SB copy %llu, bytenr %llu\n", num,
6970                                        (unsigned long long)bytenr);
6971                                 break;
6972                         case 'Q':
6973                                 qgroup_report = 1;
6974                                 break;
6975                         case 'E':
6976                                 subvolid = arg_strtou64(optarg);
6977                                 break;
6978                         case '?':
6979                         case 'h':
6980                                 usage(cmd_check_usage);
6981                 }
6982                 if (option_index == 1) {
6983                         printf("enabling repair mode\n");
6984                         repair = 1;
6985                         ctree_flags |= OPEN_CTREE_WRITES;
6986                 } else if (option_index == 2) {
6987                         printf("Creating a new CRC tree\n");
6988                         init_csum_tree = 1;
6989                         repair = 1;
6990                         ctree_flags |= OPEN_CTREE_WRITES;
6991                 } else if (option_index == 3) {
6992                         init_extent_tree = 1;
6993                         ctree_flags |= (OPEN_CTREE_WRITES |
6994                                         OPEN_CTREE_NO_BLOCK_GROUPS);
6995                         repair = 1;
6996                 } else if (option_index == 4) {
6997                         check_data_csum = 1;
6998                 }
6999         }
7000         argc = argc - optind;
7001
7002         if (check_argc_exact(argc, 1))
7003                 usage(cmd_check_usage);
7004
7005         radix_tree_init();
7006         cache_tree_init(&root_cache);
7007
7008         if((ret = check_mounted(argv[optind])) < 0) {
7009                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
7010                 goto err_out;
7011         } else if(ret) {
7012                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
7013                 ret = -EBUSY;
7014                 goto err_out;
7015         }
7016
7017         /* only allow partial opening under repair mode */
7018         if (repair)
7019                 ctree_flags |= OPEN_CTREE_PARTIAL;
7020
7021         info = open_ctree_fs_info(argv[optind], bytenr, 0, ctree_flags);
7022         if (!info) {
7023                 fprintf(stderr, "Couldn't open file system\n");
7024                 ret = -EIO;
7025                 goto err_out;
7026         }
7027
7028         root = info->fs_root;
7029         /*
7030          * repair mode will force us to commit transaction which
7031          * will make us fail to load log tree when mounting.
7032          */
7033         if (repair && btrfs_super_log_root(info->super_copy)) {
7034                 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
7035                 if (!ret) {
7036                         ret = 1;
7037                         goto close_out;
7038                 }
7039                 ret = zero_log_tree(root);
7040                 if (ret) {
7041                         fprintf(stderr, "fail to zero log tree\n");
7042                         goto close_out;
7043                 }
7044         }
7045
7046         uuid_unparse(info->super_copy->fsid, uuidbuf);
7047         if (qgroup_report) {
7048                 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
7049                        uuidbuf);
7050                 ret = qgroup_verify_all(info);
7051                 if (ret == 0)
7052                         print_qgroup_report(1);
7053                 goto close_out;
7054         }
7055         if (subvolid) {
7056                 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
7057                        subvolid, argv[optind], uuidbuf);
7058                 ret = print_extent_state(info, subvolid);
7059                 goto close_out;
7060         }
7061         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
7062
7063         if (!extent_buffer_uptodate(info->tree_root->node) ||
7064             !extent_buffer_uptodate(info->dev_root->node) ||
7065             !extent_buffer_uptodate(info->chunk_root->node)) {
7066                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
7067                 ret = -EIO;
7068                 goto close_out;
7069         }
7070
7071         if (init_extent_tree || init_csum_tree) {
7072                 struct btrfs_trans_handle *trans;
7073
7074                 trans = btrfs_start_transaction(info->extent_root, 0);
7075                 if (IS_ERR(trans)) {
7076                         fprintf(stderr, "Error starting transaction\n");
7077                         ret = PTR_ERR(trans);
7078                         goto close_out;
7079                 }
7080
7081                 if (init_extent_tree) {
7082                         printf("Creating a new extent tree\n");
7083                         ret = reinit_extent_tree(trans, info);
7084                         if (ret)
7085                                 goto close_out;
7086                 }
7087
7088                 if (init_csum_tree) {
7089                         fprintf(stderr, "Reinit crc root\n");
7090                         ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
7091                         if (ret) {
7092                                 fprintf(stderr, "crc root initialization failed\n");
7093                                 ret = -EIO;
7094                                 goto close_out;
7095                         }
7096
7097                         ret = fill_csum_tree(trans, info->csum_root);
7098                         if (ret) {
7099                                 fprintf(stderr, "crc refilling failed\n");
7100                                 return -EIO;
7101                         }
7102                 }
7103                 /*
7104                  * Ok now we commit and run the normal fsck, which will add
7105                  * extent entries for all of the items it finds.
7106                  */
7107                 ret = btrfs_commit_transaction(trans, info->extent_root);
7108                 if (ret)
7109                         goto close_out;
7110         }
7111         if (!extent_buffer_uptodate(info->extent_root->node)) {
7112                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
7113                 ret = -EIO;
7114                 goto close_out;
7115         }
7116         if (!extent_buffer_uptodate(info->csum_root->node)) {
7117                 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
7118                 ret = -EIO;
7119                 goto close_out;
7120         }
7121
7122         fprintf(stderr, "checking extents\n");
7123         ret = check_chunks_and_extents(root);
7124         if (ret)
7125                 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
7126
7127         fprintf(stderr, "checking free space cache\n");
7128         ret = check_space_cache(root);
7129         if (ret)
7130                 goto out;
7131
7132         /*
7133          * We used to have to have these hole extents in between our real
7134          * extents so if we don't have this flag set we need to make sure there
7135          * are no gaps in the file extents for inodes, otherwise we can just
7136          * ignore it when this happens.
7137          */
7138         no_holes = btrfs_fs_incompat(root->fs_info,
7139                                      BTRFS_FEATURE_INCOMPAT_NO_HOLES);
7140         fprintf(stderr, "checking fs roots\n");
7141         ret = check_fs_roots(root, &root_cache);
7142         if (ret)
7143                 goto out;
7144
7145         fprintf(stderr, "checking csums\n");
7146         ret = check_csums(root);
7147         if (ret)
7148                 goto out;
7149
7150         fprintf(stderr, "checking root refs\n");
7151         ret = check_root_refs(root, &root_cache);
7152         if (ret)
7153                 goto out;
7154
7155         while (repair && !list_empty(&root->fs_info->recow_ebs)) {
7156                 struct extent_buffer *eb;
7157
7158                 eb = list_first_entry(&root->fs_info->recow_ebs,
7159                                       struct extent_buffer, recow);
7160                 list_del_init(&eb->recow);
7161                 ret = recow_extent_buffer(root, eb);
7162                 if (ret)
7163                         break;
7164         }
7165
7166         while (!list_empty(&delete_items)) {
7167                 struct bad_item *bad;
7168
7169                 bad = list_first_entry(&delete_items, struct bad_item, list);
7170                 list_del_init(&bad->list);
7171                 if (repair)
7172                         ret = delete_bad_item(root, bad);
7173                 free(bad);
7174         }
7175
7176         if (info->quota_enabled) {
7177                 int err;
7178                 fprintf(stderr, "checking quota groups\n");
7179                 err = qgroup_verify_all(info);
7180                 if (err)
7181                         goto out;
7182         }
7183
7184         if (!list_empty(&root->fs_info->recow_ebs)) {
7185                 fprintf(stderr, "Transid errors in file system\n");
7186                 ret = 1;
7187         }
7188 out:
7189         print_qgroup_report(0);
7190         if (found_old_backref) { /*
7191                  * there was a disk format change when mixed
7192                  * backref was in testing tree. The old format
7193                  * existed about one week.
7194                  */
7195                 printf("\n * Found old mixed backref format. "
7196                        "The old format is not supported! *"
7197                        "\n * Please mount the FS in readonly mode, "
7198                        "backup data and re-format the FS. *\n\n");
7199                 ret = 1;
7200         }
7201         printf("found %llu bytes used err is %d\n",
7202                (unsigned long long)bytes_used, ret);
7203         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
7204         printf("total tree bytes: %llu\n",
7205                (unsigned long long)total_btree_bytes);
7206         printf("total fs tree bytes: %llu\n",
7207                (unsigned long long)total_fs_tree_bytes);
7208         printf("total extent tree bytes: %llu\n",
7209                (unsigned long long)total_extent_tree_bytes);
7210         printf("btree space waste bytes: %llu\n",
7211                (unsigned long long)btree_space_waste);
7212         printf("file data blocks allocated: %llu\n referenced %llu\n",
7213                 (unsigned long long)data_bytes_allocated,
7214                 (unsigned long long)data_bytes_referenced);
7215         printf("%s\n", BTRFS_BUILD_VERSION);
7216
7217         free_root_recs_tree(&root_cache);
7218 close_out:
7219         close_ctree(root);
7220 err_out:
7221         return ret;
7222 }