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