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