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