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