Btrfs-progs: keep track of transid failures and fix them if possible
[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 static int repair = 0;
53
54 struct extent_backref {
55         struct list_head list;
56         unsigned int is_data:1;
57         unsigned int found_extent_tree:1;
58         unsigned int full_backref:1;
59         unsigned int found_ref:1;
60         unsigned int broken:1;
61 };
62
63 struct data_backref {
64         struct extent_backref node;
65         union {
66                 u64 parent;
67                 u64 root;
68         };
69         u64 owner;
70         u64 offset;
71         u64 disk_bytenr;
72         u64 bytes;
73         u64 ram_bytes;
74         u32 num_refs;
75         u32 found_ref;
76 };
77
78 struct tree_backref {
79         struct extent_backref node;
80         union {
81                 u64 parent;
82                 u64 root;
83         };
84 };
85
86 struct extent_record {
87         struct list_head backrefs;
88         struct list_head dups;
89         struct list_head list;
90         struct cache_extent cache;
91         struct btrfs_disk_key parent_key;
92         unsigned int found_rec;
93         u64 start;
94         u64 max_size;
95         u64 nr;
96         u64 refs;
97         u64 extent_item_refs;
98         u64 generation;
99         u64 info_objectid;
100         u64 num_duplicates;
101         u8 info_level;
102         unsigned int content_checked:1;
103         unsigned int owner_ref_checked:1;
104         unsigned int is_root:1;
105         unsigned int metadata:1;
106 };
107
108 struct inode_backref {
109         struct list_head list;
110         unsigned int found_dir_item:1;
111         unsigned int found_dir_index:1;
112         unsigned int found_inode_ref:1;
113         unsigned int filetype:8;
114         int errors;
115         unsigned int ref_type;
116         u64 dir;
117         u64 index;
118         u16 namelen;
119         char name[0];
120 };
121
122 #define REF_ERR_NO_DIR_ITEM             (1 << 0)
123 #define REF_ERR_NO_DIR_INDEX            (1 << 1)
124 #define REF_ERR_NO_INODE_REF            (1 << 2)
125 #define REF_ERR_DUP_DIR_ITEM            (1 << 3)
126 #define REF_ERR_DUP_DIR_INDEX           (1 << 4)
127 #define REF_ERR_DUP_INODE_REF           (1 << 5)
128 #define REF_ERR_INDEX_UNMATCH           (1 << 6)
129 #define REF_ERR_FILETYPE_UNMATCH        (1 << 7)
130 #define REF_ERR_NAME_TOO_LONG           (1 << 8) // 100
131 #define REF_ERR_NO_ROOT_REF             (1 << 9)
132 #define REF_ERR_NO_ROOT_BACKREF         (1 << 10)
133 #define REF_ERR_DUP_ROOT_REF            (1 << 11)
134 #define REF_ERR_DUP_ROOT_BACKREF        (1 << 12)
135
136 struct inode_record {
137         struct list_head backrefs;
138         unsigned int checked:1;
139         unsigned int merging:1;
140         unsigned int found_inode_item:1;
141         unsigned int found_dir_item:1;
142         unsigned int found_file_extent:1;
143         unsigned int found_csum_item:1;
144         unsigned int some_csum_missing:1;
145         unsigned int nodatasum:1;
146         int errors;
147
148         u64 ino;
149         u32 nlink;
150         u32 imode;
151         u64 isize;
152         u64 nbytes;
153
154         u32 found_link;
155         u64 found_size;
156         u64 extent_start;
157         u64 extent_end;
158         u64 first_extent_gap;
159
160         u32 refs;
161 };
162
163 #define I_ERR_NO_INODE_ITEM             (1 << 0)
164 #define I_ERR_NO_ORPHAN_ITEM            (1 << 1)
165 #define I_ERR_DUP_INODE_ITEM            (1 << 2)
166 #define I_ERR_DUP_DIR_INDEX             (1 << 3)
167 #define I_ERR_ODD_DIR_ITEM              (1 << 4)
168 #define I_ERR_ODD_FILE_EXTENT           (1 << 5)
169 #define I_ERR_BAD_FILE_EXTENT           (1 << 6)
170 #define I_ERR_FILE_EXTENT_OVERLAP       (1 << 7)
171 #define I_ERR_FILE_EXTENT_DISCOUNT      (1 << 8) // 100
172 #define I_ERR_DIR_ISIZE_WRONG           (1 << 9)
173 #define I_ERR_FILE_NBYTES_WRONG         (1 << 10) // 400
174 #define I_ERR_ODD_CSUM_ITEM             (1 << 11)
175 #define I_ERR_SOME_CSUM_MISSING         (1 << 12)
176 #define I_ERR_LINK_COUNT_WRONG          (1 << 13)
177
178 struct root_backref {
179         struct list_head list;
180         unsigned int found_dir_item:1;
181         unsigned int found_dir_index:1;
182         unsigned int found_back_ref:1;
183         unsigned int found_forward_ref:1;
184         unsigned int reachable:1;
185         int errors;
186         u64 ref_root;
187         u64 dir;
188         u64 index;
189         u16 namelen;
190         char name[0];
191 };
192
193 struct root_record {
194         struct list_head backrefs;
195         struct cache_extent cache;
196         unsigned int found_root_item:1;
197         u64 objectid;
198         u32 found_ref;
199 };
200
201 struct ptr_node {
202         struct cache_extent cache;
203         void *data;
204 };
205
206 struct shared_node {
207         struct cache_extent cache;
208         struct cache_tree root_cache;
209         struct cache_tree inode_cache;
210         struct inode_record *current;
211         u32 refs;
212 };
213
214 struct block_info {
215         u64 start;
216         u32 size;
217 };
218
219 struct walk_control {
220         struct cache_tree shared;
221         struct shared_node *nodes[BTRFS_MAX_LEVEL];
222         int active_node;
223         int root_level;
224 };
225
226 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info);
227
228 static u8 imode_to_type(u32 imode)
229 {
230 #define S_SHIFT 12
231         static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
232                 [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
233                 [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
234                 [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
235                 [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
236                 [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
237                 [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
238                 [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
239         };
240
241         return btrfs_type_by_mode[(imode & S_IFMT) >> S_SHIFT];
242 #undef S_SHIFT
243 }
244
245 static int device_record_compare(struct rb_node *node1, struct rb_node *node2)
246 {
247         struct device_record *rec1;
248         struct device_record *rec2;
249
250         rec1 = rb_entry(node1, struct device_record, node);
251         rec2 = rb_entry(node2, struct device_record, node);
252         if (rec1->devid > rec2->devid)
253                 return -1;
254         else if (rec1->devid < rec2->devid)
255                 return 1;
256         else
257                 return 0;
258 }
259
260 static struct inode_record *clone_inode_rec(struct inode_record *orig_rec)
261 {
262         struct inode_record *rec;
263         struct inode_backref *backref;
264         struct inode_backref *orig;
265         size_t size;
266
267         rec = malloc(sizeof(*rec));
268         memcpy(rec, orig_rec, sizeof(*rec));
269         rec->refs = 1;
270         INIT_LIST_HEAD(&rec->backrefs);
271
272         list_for_each_entry(orig, &orig_rec->backrefs, list) {
273                 size = sizeof(*orig) + orig->namelen + 1;
274                 backref = malloc(size);
275                 memcpy(backref, orig, size);
276                 list_add_tail(&backref->list, &rec->backrefs);
277         }
278         return rec;
279 }
280
281 static struct inode_record *get_inode_rec(struct cache_tree *inode_cache,
282                                           u64 ino, int mod)
283 {
284         struct ptr_node *node;
285         struct cache_extent *cache;
286         struct inode_record *rec = NULL;
287         int ret;
288
289         cache = lookup_cache_extent(inode_cache, ino, 1);
290         if (cache) {
291                 node = container_of(cache, struct ptr_node, cache);
292                 rec = node->data;
293                 if (mod && rec->refs > 1) {
294                         node->data = clone_inode_rec(rec);
295                         rec->refs--;
296                         rec = node->data;
297                 }
298         } else if (mod) {
299                 rec = calloc(1, sizeof(*rec));
300                 rec->ino = ino;
301                 rec->extent_start = (u64)-1;
302                 rec->first_extent_gap = (u64)-1;
303                 rec->refs = 1;
304                 INIT_LIST_HEAD(&rec->backrefs);
305
306                 node = malloc(sizeof(*node));
307                 node->cache.start = ino;
308                 node->cache.size = 1;
309                 node->data = rec;
310
311                 if (ino == BTRFS_FREE_INO_OBJECTID)
312                         rec->found_link = 1;
313
314                 ret = insert_cache_extent(inode_cache, &node->cache);
315                 BUG_ON(ret);
316         }
317         return rec;
318 }
319
320 static void free_inode_rec(struct inode_record *rec)
321 {
322         struct inode_backref *backref;
323
324         if (--rec->refs > 0)
325                 return;
326
327         while (!list_empty(&rec->backrefs)) {
328                 backref = list_entry(rec->backrefs.next,
329                                      struct inode_backref, list);
330                 list_del(&backref->list);
331                 free(backref);
332         }
333         free(rec);
334 }
335
336 static int can_free_inode_rec(struct inode_record *rec)
337 {
338         if (!rec->errors && rec->checked && rec->found_inode_item &&
339             rec->nlink == rec->found_link && list_empty(&rec->backrefs))
340                 return 1;
341         return 0;
342 }
343
344 static void maybe_free_inode_rec(struct cache_tree *inode_cache,
345                                  struct inode_record *rec)
346 {
347         struct cache_extent *cache;
348         struct inode_backref *tmp, *backref;
349         struct ptr_node *node;
350         unsigned char filetype;
351
352         if (!rec->found_inode_item)
353                 return;
354
355         filetype = imode_to_type(rec->imode);
356         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
357                 if (backref->found_dir_item && backref->found_dir_index) {
358                         if (backref->filetype != filetype)
359                                 backref->errors |= REF_ERR_FILETYPE_UNMATCH;
360                         if (!backref->errors && backref->found_inode_ref) {
361                                 list_del(&backref->list);
362                                 free(backref);
363                         }
364                 }
365         }
366
367         if (!rec->checked || rec->merging)
368                 return;
369
370         if (S_ISDIR(rec->imode)) {
371                 if (rec->found_size != rec->isize)
372                         rec->errors |= I_ERR_DIR_ISIZE_WRONG;
373                 if (rec->found_file_extent)
374                         rec->errors |= I_ERR_ODD_FILE_EXTENT;
375         } else if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
376                 if (rec->found_dir_item)
377                         rec->errors |= I_ERR_ODD_DIR_ITEM;
378                 if (rec->found_size != rec->nbytes)
379                         rec->errors |= I_ERR_FILE_NBYTES_WRONG;
380                 if (rec->extent_start == (u64)-1 || rec->extent_start > 0)
381                         rec->first_extent_gap = 0;
382                 if (rec->nlink > 0 && (rec->extent_end < rec->isize ||
383                     rec->first_extent_gap < rec->isize))
384                         rec->errors |= I_ERR_FILE_EXTENT_DISCOUNT;
385         }
386
387         if (S_ISREG(rec->imode) || S_ISLNK(rec->imode)) {
388                 if (rec->found_csum_item && rec->nodatasum)
389                         rec->errors |= I_ERR_ODD_CSUM_ITEM;
390                 if (rec->some_csum_missing && !rec->nodatasum)
391                         rec->errors |= I_ERR_SOME_CSUM_MISSING;
392         }
393
394         BUG_ON(rec->refs != 1);
395         if (can_free_inode_rec(rec)) {
396                 cache = lookup_cache_extent(inode_cache, rec->ino, 1);
397                 node = container_of(cache, struct ptr_node, cache);
398                 BUG_ON(node->data != rec);
399                 remove_cache_extent(inode_cache, &node->cache);
400                 free(node);
401                 free_inode_rec(rec);
402         }
403 }
404
405 static int check_orphan_item(struct btrfs_root *root, u64 ino)
406 {
407         struct btrfs_path path;
408         struct btrfs_key key;
409         int ret;
410
411         key.objectid = BTRFS_ORPHAN_OBJECTID;
412         key.type = BTRFS_ORPHAN_ITEM_KEY;
413         key.offset = ino;
414
415         btrfs_init_path(&path);
416         ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
417         btrfs_release_path(&path);
418         if (ret > 0)
419                 ret = -ENOENT;
420         return ret;
421 }
422
423 static int process_inode_item(struct extent_buffer *eb,
424                               int slot, struct btrfs_key *key,
425                               struct shared_node *active_node)
426 {
427         struct inode_record *rec;
428         struct btrfs_inode_item *item;
429
430         rec = active_node->current;
431         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
432         if (rec->found_inode_item) {
433                 rec->errors |= I_ERR_DUP_INODE_ITEM;
434                 return 1;
435         }
436         item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
437         rec->nlink = btrfs_inode_nlink(eb, item);
438         rec->isize = btrfs_inode_size(eb, item);
439         rec->nbytes = btrfs_inode_nbytes(eb, item);
440         rec->imode = btrfs_inode_mode(eb, item);
441         if (btrfs_inode_flags(eb, item) & BTRFS_INODE_NODATASUM)
442                 rec->nodatasum = 1;
443         rec->found_inode_item = 1;
444         if (rec->nlink == 0)
445                 rec->errors |= I_ERR_NO_ORPHAN_ITEM;
446         maybe_free_inode_rec(&active_node->inode_cache, rec);
447         return 0;
448 }
449
450 static struct inode_backref *get_inode_backref(struct inode_record *rec,
451                                                 const char *name,
452                                                 int namelen, u64 dir)
453 {
454         struct inode_backref *backref;
455
456         list_for_each_entry(backref, &rec->backrefs, list) {
457                 if (backref->dir != dir || backref->namelen != namelen)
458                         continue;
459                 if (memcmp(name, backref->name, namelen))
460                         continue;
461                 return backref;
462         }
463
464         backref = malloc(sizeof(*backref) + namelen + 1);
465         memset(backref, 0, sizeof(*backref));
466         backref->dir = dir;
467         backref->namelen = namelen;
468         memcpy(backref->name, name, namelen);
469         backref->name[namelen] = '\0';
470         list_add_tail(&backref->list, &rec->backrefs);
471         return backref;
472 }
473
474 static int add_inode_backref(struct cache_tree *inode_cache,
475                              u64 ino, u64 dir, u64 index,
476                              const char *name, int namelen,
477                              int filetype, int itemtype, int errors)
478 {
479         struct inode_record *rec;
480         struct inode_backref *backref;
481
482         rec = get_inode_rec(inode_cache, ino, 1);
483         backref = get_inode_backref(rec, name, namelen, dir);
484         if (errors)
485                 backref->errors |= errors;
486         if (itemtype == BTRFS_DIR_INDEX_KEY) {
487                 if (backref->found_dir_index)
488                         backref->errors |= REF_ERR_DUP_DIR_INDEX;
489                 if (backref->found_inode_ref && backref->index != index)
490                         backref->errors |= REF_ERR_INDEX_UNMATCH;
491                 if (backref->found_dir_item && backref->filetype != filetype)
492                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
493
494                 backref->index = index;
495                 backref->filetype = filetype;
496                 backref->found_dir_index = 1;
497         } else if (itemtype == BTRFS_DIR_ITEM_KEY) {
498                 rec->found_link++;
499                 if (backref->found_dir_item)
500                         backref->errors |= REF_ERR_DUP_DIR_ITEM;
501                 if (backref->found_dir_index && backref->filetype != filetype)
502                         backref->errors |= REF_ERR_FILETYPE_UNMATCH;
503
504                 backref->filetype = filetype;
505                 backref->found_dir_item = 1;
506         } else if ((itemtype == BTRFS_INODE_REF_KEY) ||
507                    (itemtype == BTRFS_INODE_EXTREF_KEY)) {
508                 if (backref->found_inode_ref)
509                         backref->errors |= REF_ERR_DUP_INODE_REF;
510                 if (backref->found_dir_index && backref->index != index)
511                         backref->errors |= REF_ERR_INDEX_UNMATCH;
512
513                 backref->ref_type = itemtype;
514                 backref->index = index;
515                 backref->found_inode_ref = 1;
516         } else {
517                 BUG_ON(1);
518         }
519
520         maybe_free_inode_rec(inode_cache, rec);
521         return 0;
522 }
523
524 static int merge_inode_recs(struct inode_record *src, struct inode_record *dst,
525                             struct cache_tree *dst_cache)
526 {
527         struct inode_backref *backref;
528         u32 dir_count = 0;
529
530         dst->merging = 1;
531         list_for_each_entry(backref, &src->backrefs, list) {
532                 if (backref->found_dir_index) {
533                         add_inode_backref(dst_cache, dst->ino, backref->dir,
534                                         backref->index, backref->name,
535                                         backref->namelen, backref->filetype,
536                                         BTRFS_DIR_INDEX_KEY, backref->errors);
537                 }
538                 if (backref->found_dir_item) {
539                         dir_count++;
540                         add_inode_backref(dst_cache, dst->ino,
541                                         backref->dir, 0, backref->name,
542                                         backref->namelen, backref->filetype,
543                                         BTRFS_DIR_ITEM_KEY, backref->errors);
544                 }
545                 if (backref->found_inode_ref) {
546                         add_inode_backref(dst_cache, dst->ino,
547                                         backref->dir, backref->index,
548                                         backref->name, backref->namelen, 0,
549                                         backref->ref_type, backref->errors);
550                 }
551         }
552
553         if (src->found_dir_item)
554                 dst->found_dir_item = 1;
555         if (src->found_file_extent)
556                 dst->found_file_extent = 1;
557         if (src->found_csum_item)
558                 dst->found_csum_item = 1;
559         if (src->some_csum_missing)
560                 dst->some_csum_missing = 1;
561         if (dst->first_extent_gap > src->first_extent_gap)
562                 dst->first_extent_gap = src->first_extent_gap;
563
564         BUG_ON(src->found_link < dir_count);
565         dst->found_link += src->found_link - dir_count;
566         dst->found_size += src->found_size;
567         if (src->extent_start != (u64)-1) {
568                 if (dst->extent_start == (u64)-1) {
569                         dst->extent_start = src->extent_start;
570                         dst->extent_end = src->extent_end;
571                 } else {
572                         if (dst->extent_end > src->extent_start)
573                                 dst->errors |= I_ERR_FILE_EXTENT_OVERLAP;
574                         else if (dst->extent_end < src->extent_start &&
575                                  dst->extent_end < dst->first_extent_gap)
576                                 dst->first_extent_gap = dst->extent_end;
577                         if (dst->extent_end < src->extent_end)
578                                 dst->extent_end = src->extent_end;
579                 }
580         }
581
582         dst->errors |= src->errors;
583         if (src->found_inode_item) {
584                 if (!dst->found_inode_item) {
585                         dst->nlink = src->nlink;
586                         dst->isize = src->isize;
587                         dst->nbytes = src->nbytes;
588                         dst->imode = src->imode;
589                         dst->nodatasum = src->nodatasum;
590                         dst->found_inode_item = 1;
591                 } else {
592                         dst->errors |= I_ERR_DUP_INODE_ITEM;
593                 }
594         }
595         dst->merging = 0;
596
597         return 0;
598 }
599
600 static int splice_shared_node(struct shared_node *src_node,
601                               struct shared_node *dst_node)
602 {
603         struct cache_extent *cache;
604         struct ptr_node *node, *ins;
605         struct cache_tree *src, *dst;
606         struct inode_record *rec, *conflict;
607         u64 current_ino = 0;
608         int splice = 0;
609         int ret;
610
611         if (--src_node->refs == 0)
612                 splice = 1;
613         if (src_node->current)
614                 current_ino = src_node->current->ino;
615
616         src = &src_node->root_cache;
617         dst = &dst_node->root_cache;
618 again:
619         cache = search_cache_extent(src, 0);
620         while (cache) {
621                 node = container_of(cache, struct ptr_node, cache);
622                 rec = node->data;
623                 cache = next_cache_extent(cache);
624
625                 if (splice) {
626                         remove_cache_extent(src, &node->cache);
627                         ins = node;
628                 } else {
629                         ins = malloc(sizeof(*ins));
630                         ins->cache.start = node->cache.start;
631                         ins->cache.size = node->cache.size;
632                         ins->data = rec;
633                         rec->refs++;
634                 }
635                 ret = insert_cache_extent(dst, &ins->cache);
636                 if (ret == -EEXIST) {
637                         conflict = get_inode_rec(dst, rec->ino, 1);
638                         merge_inode_recs(rec, conflict, dst);
639                         if (rec->checked) {
640                                 conflict->checked = 1;
641                                 if (dst_node->current == conflict)
642                                         dst_node->current = NULL;
643                         }
644                         maybe_free_inode_rec(dst, conflict);
645                         free_inode_rec(rec);
646                         free(ins);
647                 } else {
648                         BUG_ON(ret);
649                 }
650         }
651
652         if (src == &src_node->root_cache) {
653                 src = &src_node->inode_cache;
654                 dst = &dst_node->inode_cache;
655                 goto again;
656         }
657
658         if (current_ino > 0 && (!dst_node->current ||
659             current_ino > dst_node->current->ino)) {
660                 if (dst_node->current) {
661                         dst_node->current->checked = 1;
662                         maybe_free_inode_rec(dst, dst_node->current);
663                 }
664                 dst_node->current = get_inode_rec(dst, current_ino, 1);
665         }
666         return 0;
667 }
668
669 static void free_inode_ptr(struct cache_extent *cache)
670 {
671         struct ptr_node *node;
672         struct inode_record *rec;
673
674         node = container_of(cache, struct ptr_node, cache);
675         rec = node->data;
676         free_inode_rec(rec);
677         free(node);
678 }
679
680 FREE_EXTENT_CACHE_BASED_TREE(inode_recs, free_inode_ptr);
681
682 static struct shared_node *find_shared_node(struct cache_tree *shared,
683                                             u64 bytenr)
684 {
685         struct cache_extent *cache;
686         struct shared_node *node;
687
688         cache = lookup_cache_extent(shared, bytenr, 1);
689         if (cache) {
690                 node = container_of(cache, struct shared_node, cache);
691                 return node;
692         }
693         return NULL;
694 }
695
696 static int add_shared_node(struct cache_tree *shared, u64 bytenr, u32 refs)
697 {
698         int ret;
699         struct shared_node *node;
700
701         node = calloc(1, sizeof(*node));
702         node->cache.start = bytenr;
703         node->cache.size = 1;
704         cache_tree_init(&node->root_cache);
705         cache_tree_init(&node->inode_cache);
706         node->refs = refs;
707
708         ret = insert_cache_extent(shared, &node->cache);
709         BUG_ON(ret);
710         return 0;
711 }
712
713 static int enter_shared_node(struct btrfs_root *root, u64 bytenr, u32 refs,
714                              struct walk_control *wc, int level)
715 {
716         struct shared_node *node;
717         struct shared_node *dest;
718
719         if (level == wc->active_node)
720                 return 0;
721
722         BUG_ON(wc->active_node <= level);
723         node = find_shared_node(&wc->shared, bytenr);
724         if (!node) {
725                 add_shared_node(&wc->shared, bytenr, refs);
726                 node = find_shared_node(&wc->shared, bytenr);
727                 wc->nodes[level] = node;
728                 wc->active_node = level;
729                 return 0;
730         }
731
732         if (wc->root_level == wc->active_node &&
733             btrfs_root_refs(&root->root_item) == 0) {
734                 if (--node->refs == 0) {
735                         free_inode_recs_tree(&node->root_cache);
736                         free_inode_recs_tree(&node->inode_cache);
737                         remove_cache_extent(&wc->shared, &node->cache);
738                         free(node);
739                 }
740                 return 1;
741         }
742
743         dest = wc->nodes[wc->active_node];
744         splice_shared_node(node, dest);
745         if (node->refs == 0) {
746                 remove_cache_extent(&wc->shared, &node->cache);
747                 free(node);
748         }
749         return 1;
750 }
751
752 static int leave_shared_node(struct btrfs_root *root,
753                              struct walk_control *wc, int level)
754 {
755         struct shared_node *node;
756         struct shared_node *dest;
757         int i;
758
759         if (level == wc->root_level)
760                 return 0;
761
762         for (i = level + 1; i < BTRFS_MAX_LEVEL; i++) {
763                 if (wc->nodes[i])
764                         break;
765         }
766         BUG_ON(i >= BTRFS_MAX_LEVEL);
767
768         node = wc->nodes[wc->active_node];
769         wc->nodes[wc->active_node] = NULL;
770         wc->active_node = i;
771
772         dest = wc->nodes[wc->active_node];
773         if (wc->active_node < wc->root_level ||
774             btrfs_root_refs(&root->root_item) > 0) {
775                 BUG_ON(node->refs <= 1);
776                 splice_shared_node(node, dest);
777         } else {
778                 BUG_ON(node->refs < 2);
779                 node->refs--;
780         }
781         return 0;
782 }
783
784 static int is_child_root(struct btrfs_root *root, u64 parent_root_id,
785                          u64 child_root_id)
786 {
787         struct btrfs_path path;
788         struct btrfs_key key;
789         struct extent_buffer *leaf;
790         int has_parent = 0;
791         int ret;
792
793         btrfs_init_path(&path);
794
795         key.objectid = parent_root_id;
796         key.type = BTRFS_ROOT_REF_KEY;
797         key.offset = child_root_id;
798         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
799                                 0, 0);
800         BUG_ON(ret < 0);
801         btrfs_release_path(&path);
802         if (!ret)
803                 return 1;
804
805         key.objectid = child_root_id;
806         key.type = BTRFS_ROOT_BACKREF_KEY;
807         key.offset = 0;
808         ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, &path,
809                                 0, 0);
810         BUG_ON(ret <= 0);
811
812         while (1) {
813                 leaf = path.nodes[0];
814                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
815                         ret = btrfs_next_leaf(root->fs_info->tree_root, &path);
816                         BUG_ON(ret < 0);
817
818                         if (ret > 0)
819                                 break;
820                         leaf = path.nodes[0];
821                 }
822
823                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
824                 if (key.objectid != child_root_id ||
825                     key.type != BTRFS_ROOT_BACKREF_KEY)
826                         break;
827
828                 has_parent = 1;
829
830                 if (key.offset == parent_root_id) {
831                         btrfs_release_path(&path);
832                         return 1;
833                 }
834
835                 path.slots[0]++;
836         }
837
838         btrfs_release_path(&path);
839         return has_parent? 0 : -1;
840 }
841
842 static int process_dir_item(struct btrfs_root *root,
843                             struct extent_buffer *eb,
844                             int slot, struct btrfs_key *key,
845                             struct shared_node *active_node)
846 {
847         u32 total;
848         u32 cur = 0;
849         u32 len;
850         u32 name_len;
851         u32 data_len;
852         int error;
853         int nritems = 0;
854         int filetype;
855         struct btrfs_dir_item *di;
856         struct inode_record *rec;
857         struct cache_tree *root_cache;
858         struct cache_tree *inode_cache;
859         struct btrfs_key location;
860         char namebuf[BTRFS_NAME_LEN];
861
862         root_cache = &active_node->root_cache;
863         inode_cache = &active_node->inode_cache;
864         rec = active_node->current;
865         rec->found_dir_item = 1;
866
867         di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
868         total = btrfs_item_size_nr(eb, slot);
869         while (cur < total) {
870                 nritems++;
871                 btrfs_dir_item_key_to_cpu(eb, di, &location);
872                 name_len = btrfs_dir_name_len(eb, di);
873                 data_len = btrfs_dir_data_len(eb, di);
874                 filetype = btrfs_dir_type(eb, di);
875
876                 rec->found_size += name_len;
877                 if (name_len <= BTRFS_NAME_LEN) {
878                         len = name_len;
879                         error = 0;
880                 } else {
881                         len = BTRFS_NAME_LEN;
882                         error = REF_ERR_NAME_TOO_LONG;
883                 }
884                 read_extent_buffer(eb, namebuf, (unsigned long)(di + 1), len);
885
886                 if (location.type == BTRFS_INODE_ITEM_KEY) {
887                         add_inode_backref(inode_cache, location.objectid,
888                                           key->objectid, key->offset, namebuf,
889                                           len, filetype, key->type, error);
890                 } else if (location.type == BTRFS_ROOT_ITEM_KEY) {
891                         add_inode_backref(root_cache, location.objectid,
892                                           key->objectid, key->offset,
893                                           namebuf, len, filetype,
894                                           key->type, error);
895                 } else {
896                         fprintf(stderr, "warning line %d\n", __LINE__);
897                 }
898
899                 len = sizeof(*di) + name_len + data_len;
900                 di = (struct btrfs_dir_item *)((char *)di + len);
901                 cur += len;
902         }
903         if (key->type == BTRFS_DIR_INDEX_KEY && nritems > 1)
904                 rec->errors |= I_ERR_DUP_DIR_INDEX;
905
906         return 0;
907 }
908
909 static int process_inode_ref(struct extent_buffer *eb,
910                              int slot, struct btrfs_key *key,
911                              struct shared_node *active_node)
912 {
913         u32 total;
914         u32 cur = 0;
915         u32 len;
916         u32 name_len;
917         u64 index;
918         int error;
919         struct cache_tree *inode_cache;
920         struct btrfs_inode_ref *ref;
921         char namebuf[BTRFS_NAME_LEN];
922
923         inode_cache = &active_node->inode_cache;
924
925         ref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
926         total = btrfs_item_size_nr(eb, slot);
927         while (cur < total) {
928                 name_len = btrfs_inode_ref_name_len(eb, ref);
929                 index = btrfs_inode_ref_index(eb, ref);
930                 if (name_len <= BTRFS_NAME_LEN) {
931                         len = name_len;
932                         error = 0;
933                 } else {
934                         len = BTRFS_NAME_LEN;
935                         error = REF_ERR_NAME_TOO_LONG;
936                 }
937                 read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
938                 add_inode_backref(inode_cache, key->objectid, key->offset,
939                                   index, namebuf, len, 0, key->type, error);
940
941                 len = sizeof(*ref) + name_len;
942                 ref = (struct btrfs_inode_ref *)((char *)ref + len);
943                 cur += len;
944         }
945         return 0;
946 }
947
948 static int process_inode_extref(struct extent_buffer *eb,
949                                 int slot, struct btrfs_key *key,
950                                 struct shared_node *active_node)
951 {
952         u32 total;
953         u32 cur = 0;
954         u32 len;
955         u32 name_len;
956         u64 index;
957         u64 parent;
958         int error;
959         struct cache_tree *inode_cache;
960         struct btrfs_inode_extref *extref;
961         char namebuf[BTRFS_NAME_LEN];
962
963         inode_cache = &active_node->inode_cache;
964
965         extref = btrfs_item_ptr(eb, slot, struct btrfs_inode_extref);
966         total = btrfs_item_size_nr(eb, slot);
967         while (cur < total) {
968                 name_len = btrfs_inode_extref_name_len(eb, extref);
969                 index = btrfs_inode_extref_index(eb, extref);
970                 parent = btrfs_inode_extref_parent(eb, extref);
971                 if (name_len <= BTRFS_NAME_LEN) {
972                         len = name_len;
973                         error = 0;
974                 } else {
975                         len = BTRFS_NAME_LEN;
976                         error = REF_ERR_NAME_TOO_LONG;
977                 }
978                 read_extent_buffer(eb, namebuf,
979                                    (unsigned long)(extref + 1), len);
980                 add_inode_backref(inode_cache, key->objectid, parent,
981                                   index, namebuf, len, 0, key->type, error);
982
983                 len = sizeof(*extref) + name_len;
984                 extref = (struct btrfs_inode_extref *)((char *)extref + len);
985                 cur += len;
986         }
987         return 0;
988
989 }
990
991 static u64 count_csum_range(struct btrfs_root *root, u64 start, u64 len)
992 {
993         struct btrfs_key key;
994         struct btrfs_path path;
995         struct extent_buffer *leaf;
996         int ret ;
997         size_t size;
998         u64 found = 0;
999         u64 csum_end;
1000         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
1001
1002         btrfs_init_path(&path);
1003
1004         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1005         key.offset = start;
1006         key.type = BTRFS_EXTENT_CSUM_KEY;
1007
1008         ret = btrfs_search_slot(NULL, root->fs_info->csum_root,
1009                                 &key, &path, 0, 0);
1010         BUG_ON(ret < 0);
1011         if (ret > 0 && path.slots[0] > 0) {
1012                 leaf = path.nodes[0];
1013                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0] - 1);
1014                 if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
1015                     key.type == BTRFS_EXTENT_CSUM_KEY)
1016                         path.slots[0]--;
1017         }
1018
1019         while (len > 0) {
1020                 leaf = path.nodes[0];
1021                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
1022                         ret = btrfs_next_leaf(root->fs_info->csum_root, &path);
1023                         BUG_ON(ret < 0);
1024                         if (ret > 0)
1025                                 break;
1026                         leaf = path.nodes[0];
1027                 }
1028
1029                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1030                 if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1031                     key.type != BTRFS_EXTENT_CSUM_KEY)
1032                         break;
1033
1034                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
1035                 if (key.offset >= start + len)
1036                         break;
1037
1038                 if (key.offset > start)
1039                         start = key.offset;
1040
1041                 size = btrfs_item_size_nr(leaf, path.slots[0]);
1042                 csum_end = key.offset + (size / csum_size) * root->sectorsize;
1043                 if (csum_end > start) {
1044                         size = min(csum_end - start, len);
1045                         len -= size;
1046                         start += size;
1047                         found += size;
1048                 }
1049
1050                 path.slots[0]++;
1051         }
1052         btrfs_release_path(&path);
1053         return found;
1054 }
1055
1056 static int process_file_extent(struct btrfs_root *root,
1057                                 struct extent_buffer *eb,
1058                                 int slot, struct btrfs_key *key,
1059                                 struct shared_node *active_node)
1060 {
1061         struct inode_record *rec;
1062         struct btrfs_file_extent_item *fi;
1063         u64 num_bytes = 0;
1064         u64 disk_bytenr = 0;
1065         u64 extent_offset = 0;
1066         u64 mask = root->sectorsize - 1;
1067         int extent_type;
1068
1069         rec = active_node->current;
1070         BUG_ON(rec->ino != key->objectid || rec->refs > 1);
1071         rec->found_file_extent = 1;
1072
1073         if (rec->extent_start == (u64)-1) {
1074                 rec->extent_start = key->offset;
1075                 rec->extent_end = key->offset;
1076         }
1077
1078         if (rec->extent_end > key->offset)
1079                 rec->errors |= I_ERR_FILE_EXTENT_OVERLAP;
1080         else if (rec->extent_end < key->offset &&
1081                  rec->extent_end < rec->first_extent_gap)
1082                 rec->first_extent_gap = rec->extent_end;
1083
1084         fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
1085         extent_type = btrfs_file_extent_type(eb, fi);
1086
1087         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1088                 num_bytes = btrfs_file_extent_inline_len(eb, fi);
1089                 if (num_bytes == 0)
1090                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1091                 rec->found_size += num_bytes;
1092                 num_bytes = (num_bytes + mask) & ~mask;
1093         } else if (extent_type == BTRFS_FILE_EXTENT_REG ||
1094                    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1095                 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1096                 disk_bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1097                 extent_offset = btrfs_file_extent_offset(eb, fi);
1098                 if (num_bytes == 0 || (num_bytes & mask))
1099                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1100                 if (num_bytes + extent_offset >
1101                     btrfs_file_extent_ram_bytes(eb, fi))
1102                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1103                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC &&
1104                     (btrfs_file_extent_compression(eb, fi) ||
1105                      btrfs_file_extent_encryption(eb, fi) ||
1106                      btrfs_file_extent_other_encoding(eb, fi)))
1107                         rec->errors |= I_ERR_BAD_FILE_EXTENT;
1108                 if (disk_bytenr > 0)
1109                         rec->found_size += num_bytes;
1110         } else {
1111                 rec->errors |= I_ERR_BAD_FILE_EXTENT;
1112         }
1113         rec->extent_end = key->offset + num_bytes;
1114
1115         if (disk_bytenr > 0) {
1116                 u64 found;
1117                 if (btrfs_file_extent_compression(eb, fi))
1118                         num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1119                 else
1120                         disk_bytenr += extent_offset;
1121
1122                 found = count_csum_range(root, disk_bytenr, num_bytes);
1123                 if (extent_type == BTRFS_FILE_EXTENT_REG) {
1124                         if (found > 0)
1125                                 rec->found_csum_item = 1;
1126                         if (found < num_bytes)
1127                                 rec->some_csum_missing = 1;
1128                 } else if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1129                         if (found > 0)
1130                                 rec->errors |= I_ERR_ODD_CSUM_ITEM;
1131                 }
1132         }
1133         return 0;
1134 }
1135
1136 static int process_one_leaf(struct btrfs_root *root, struct extent_buffer *eb,
1137                             struct walk_control *wc)
1138 {
1139         struct btrfs_key key;
1140         u32 nritems;
1141         int i;
1142         int ret = 0;
1143         struct cache_tree *inode_cache;
1144         struct shared_node *active_node;
1145
1146         if (wc->root_level == wc->active_node &&
1147             btrfs_root_refs(&root->root_item) == 0)
1148                 return 0;
1149
1150         active_node = wc->nodes[wc->active_node];
1151         inode_cache = &active_node->inode_cache;
1152         nritems = btrfs_header_nritems(eb);
1153         for (i = 0; i < nritems; i++) {
1154                 btrfs_item_key_to_cpu(eb, &key, i);
1155
1156                 if (key.objectid == BTRFS_FREE_SPACE_OBJECTID)
1157                         continue;
1158
1159                 if (active_node->current == NULL ||
1160                     active_node->current->ino < key.objectid) {
1161                         if (active_node->current) {
1162                                 active_node->current->checked = 1;
1163                                 maybe_free_inode_rec(inode_cache,
1164                                                      active_node->current);
1165                         }
1166                         active_node->current = get_inode_rec(inode_cache,
1167                                                              key.objectid, 1);
1168                 }
1169                 switch (key.type) {
1170                 case BTRFS_DIR_ITEM_KEY:
1171                 case BTRFS_DIR_INDEX_KEY:
1172                         ret = process_dir_item(root, eb, i, &key, active_node);
1173                         break;
1174                 case BTRFS_INODE_REF_KEY:
1175                         ret = process_inode_ref(eb, i, &key, active_node);
1176                         break;
1177                 case BTRFS_INODE_EXTREF_KEY:
1178                         ret = process_inode_extref(eb, i, &key, active_node);
1179                         break;
1180                 case BTRFS_INODE_ITEM_KEY:
1181                         ret = process_inode_item(eb, i, &key, active_node);
1182                         break;
1183                 case BTRFS_EXTENT_DATA_KEY:
1184                         ret = process_file_extent(root, eb, i, &key,
1185                                                   active_node);
1186                         break;
1187                 default:
1188                         break;
1189                 };
1190         }
1191         return ret;
1192 }
1193
1194 static void reada_walk_down(struct btrfs_root *root,
1195                             struct extent_buffer *node, int slot)
1196 {
1197         u64 bytenr;
1198         u64 ptr_gen;
1199         u32 nritems;
1200         u32 blocksize;
1201         int i;
1202         int ret;
1203         int level;
1204
1205         level = btrfs_header_level(node);
1206         if (level != 1)
1207                 return;
1208
1209         nritems = btrfs_header_nritems(node);
1210         blocksize = btrfs_level_size(root, level - 1);
1211         for (i = slot; i < nritems; i++) {
1212                 bytenr = btrfs_node_blockptr(node, i);
1213                 ptr_gen = btrfs_node_ptr_generation(node, i);
1214                 ret = readahead_tree_block(root, bytenr, blocksize, ptr_gen);
1215                 if (ret)
1216                         break;
1217         }
1218 }
1219
1220 static int walk_down_tree(struct btrfs_root *root, struct btrfs_path *path,
1221                           struct walk_control *wc, int *level)
1222 {
1223         u64 bytenr;
1224         u64 ptr_gen;
1225         struct extent_buffer *next;
1226         struct extent_buffer *cur;
1227         u32 blocksize;
1228         int ret, err = 0;
1229         u64 refs;
1230
1231         WARN_ON(*level < 0);
1232         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1233         ret = btrfs_lookup_extent_info(NULL, root,
1234                                        path->nodes[*level]->start,
1235                                        *level, 1, &refs, NULL);
1236         if (ret < 0) {
1237                 err = ret;
1238                 goto out;
1239         }
1240
1241         if (refs > 1) {
1242                 ret = enter_shared_node(root, path->nodes[*level]->start,
1243                                         refs, wc, *level);
1244                 if (ret > 0) {
1245                         err = ret;
1246                         goto out;
1247                 }
1248         }
1249
1250         while (*level >= 0) {
1251                 WARN_ON(*level < 0);
1252                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1253                 cur = path->nodes[*level];
1254
1255                 if (btrfs_header_level(cur) != *level)
1256                         WARN_ON(1);
1257
1258                 if (path->slots[*level] >= btrfs_header_nritems(cur))
1259                         break;
1260                 if (*level == 0) {
1261                         ret = process_one_leaf(root, cur, wc);
1262                         break;
1263                 }
1264                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1265                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1266                 blocksize = btrfs_level_size(root, *level - 1);
1267                 ret = btrfs_lookup_extent_info(NULL, root, bytenr, *level - 1,
1268                                                1, &refs, NULL);
1269                 if (ret < 0)
1270                         refs = 0;
1271
1272                 if (refs > 1) {
1273                         ret = enter_shared_node(root, bytenr, refs,
1274                                                 wc, *level - 1);
1275                         if (ret > 0) {
1276                                 path->slots[*level]++;
1277                                 continue;
1278                         }
1279                 }
1280
1281                 next = btrfs_find_tree_block(root, bytenr, blocksize);
1282                 if (!next || !btrfs_buffer_uptodate(next, ptr_gen)) {
1283                         free_extent_buffer(next);
1284                         reada_walk_down(root, cur, path->slots[*level]);
1285                         next = read_tree_block(root, bytenr, blocksize,
1286                                                ptr_gen);
1287                         if (!next) {
1288                                 err = -EIO;
1289                                 goto out;
1290                         }
1291                 }
1292
1293                 *level = *level - 1;
1294                 free_extent_buffer(path->nodes[*level]);
1295                 path->nodes[*level] = next;
1296                 path->slots[*level] = 0;
1297         }
1298 out:
1299         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
1300         return err;
1301 }
1302
1303 static int walk_up_tree(struct btrfs_root *root, struct btrfs_path *path,
1304                         struct walk_control *wc, int *level)
1305 {
1306         int i;
1307         struct extent_buffer *leaf;
1308
1309         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1310                 leaf = path->nodes[i];
1311                 if (path->slots[i] + 1 < btrfs_header_nritems(leaf)) {
1312                         path->slots[i]++;
1313                         *level = i;
1314                         return 0;
1315                 } else {
1316                         free_extent_buffer(path->nodes[*level]);
1317                         path->nodes[*level] = NULL;
1318                         BUG_ON(*level > wc->active_node);
1319                         if (*level == wc->active_node)
1320                                 leave_shared_node(root, wc, *level);
1321                         *level = i + 1;
1322                 }
1323         }
1324         return 1;
1325 }
1326
1327 static int check_root_dir(struct inode_record *rec)
1328 {
1329         struct inode_backref *backref;
1330         int ret = -1;
1331
1332         if (!rec->found_inode_item || rec->errors)
1333                 goto out;
1334         if (rec->nlink != 1 || rec->found_link != 0)
1335                 goto out;
1336         if (list_empty(&rec->backrefs))
1337                 goto out;
1338         backref = list_entry(rec->backrefs.next, struct inode_backref, list);
1339         if (!backref->found_inode_ref)
1340                 goto out;
1341         if (backref->index != 0 || backref->namelen != 2 ||
1342             memcmp(backref->name, "..", 2))
1343                 goto out;
1344         if (backref->found_dir_index || backref->found_dir_item)
1345                 goto out;
1346         ret = 0;
1347 out:
1348         return ret;
1349 }
1350
1351 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
1352 {
1353         struct btrfs_trans_handle *trans;
1354         struct btrfs_path *path;
1355         struct btrfs_inode_item *ei;
1356         struct btrfs_key key;
1357         int ret;
1358
1359         /* So far we just fix dir isize wrong */
1360         if (!(rec->errors & I_ERR_DIR_ISIZE_WRONG))
1361                 return 1;
1362
1363         path = btrfs_alloc_path();
1364         if (!path)
1365                 return -ENOMEM;
1366
1367         trans = btrfs_start_transaction(root, 1);
1368         if (IS_ERR(trans)) {
1369                 btrfs_free_path(path);
1370                 return PTR_ERR(trans);
1371         }
1372
1373         key.objectid = rec->ino;
1374         key.type = BTRFS_INODE_ITEM_KEY;
1375         key.offset = (u64)-1;
1376
1377         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1378         if (ret < 0)
1379                 goto out;
1380         if (ret) {
1381                 if (!path->slots[0]) {
1382                         ret = -ENOENT;
1383                         goto out;
1384                 }
1385                 path->slots[0]--;
1386                 ret = 0;
1387         }
1388         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1389         if (key.objectid != rec->ino) {
1390                 ret = -ENOENT;
1391                 goto out;
1392         }
1393
1394         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1395                             struct btrfs_inode_item);
1396         btrfs_set_inode_size(path->nodes[0], ei, rec->found_size);
1397         btrfs_mark_buffer_dirty(path->nodes[0]);
1398         rec->errors &= ~I_ERR_DIR_ISIZE_WRONG;
1399         printf("reset isize for dir %Lu root %Lu\n", rec->ino,
1400                root->root_key.objectid);
1401 out:
1402         btrfs_commit_transaction(trans, root);
1403         btrfs_free_path(path);
1404         return ret;
1405 }
1406
1407 static int check_inode_recs(struct btrfs_root *root,
1408                             struct cache_tree *inode_cache)
1409 {
1410         struct cache_extent *cache;
1411         struct ptr_node *node;
1412         struct inode_record *rec;
1413         struct inode_backref *backref;
1414         int ret;
1415         u64 error = 0;
1416         u64 root_dirid = btrfs_root_dirid(&root->root_item);
1417
1418         if (btrfs_root_refs(&root->root_item) == 0) {
1419                 if (!cache_tree_empty(inode_cache))
1420                         fprintf(stderr, "warning line %d\n", __LINE__);
1421                 return 0;
1422         }
1423
1424         rec = get_inode_rec(inode_cache, root_dirid, 0);
1425         if (rec) {
1426                 ret = check_root_dir(rec);
1427                 if (ret) {
1428                         fprintf(stderr, "root %llu root dir %llu error\n",
1429                                 (unsigned long long)root->root_key.objectid,
1430                                 (unsigned long long)root_dirid);
1431                         error++;
1432                 }
1433         } else {
1434                 fprintf(stderr, "root %llu root dir %llu not found\n",
1435                         (unsigned long long)root->root_key.objectid,
1436                         (unsigned long long)root_dirid);
1437         }
1438
1439         while (1) {
1440                 cache = search_cache_extent(inode_cache, 0);
1441                 if (!cache)
1442                         break;
1443                 node = container_of(cache, struct ptr_node, cache);
1444                 rec = node->data;
1445                 remove_cache_extent(inode_cache, &node->cache);
1446                 free(node);
1447                 if (rec->ino == root_dirid ||
1448                     rec->ino == BTRFS_ORPHAN_OBJECTID) {
1449                         free_inode_rec(rec);
1450                         continue;
1451                 }
1452
1453                 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
1454                         ret = check_orphan_item(root, rec->ino);
1455                         if (ret == 0)
1456                                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
1457                         if (can_free_inode_rec(rec)) {
1458                                 free_inode_rec(rec);
1459                                 continue;
1460                         }
1461                 }
1462
1463                 if (repair) {
1464                         ret = try_repair_inode(root, rec);
1465                         if (ret == 0 && can_free_inode_rec(rec)) {
1466                                 free_inode_rec(rec);
1467                                 continue;
1468                         }
1469                         ret = 0;
1470                 }
1471
1472                 error++;
1473                 if (!rec->found_inode_item)
1474                         rec->errors |= I_ERR_NO_INODE_ITEM;
1475                 if (rec->found_link != rec->nlink)
1476                         rec->errors |= I_ERR_LINK_COUNT_WRONG;
1477                 fprintf(stderr, "root %llu inode %llu errors %x\n",
1478                         (unsigned long long) root->root_key.objectid,
1479                         (unsigned long long) rec->ino, rec->errors);
1480                 list_for_each_entry(backref, &rec->backrefs, list) {
1481                         if (!backref->found_dir_item)
1482                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1483                         if (!backref->found_dir_index)
1484                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1485                         if (!backref->found_inode_ref)
1486                                 backref->errors |= REF_ERR_NO_INODE_REF;
1487                         fprintf(stderr, "\tunresolved ref dir %llu index %llu"
1488                                 " namelen %u name %s filetype %d error %x\n",
1489                                 (unsigned long long)backref->dir,
1490                                 (unsigned long long)backref->index,
1491                                 backref->namelen, backref->name,
1492                                 backref->filetype, backref->errors);
1493                 }
1494                 free_inode_rec(rec);
1495         }
1496         return (error > 0) ? -1 : 0;
1497 }
1498
1499 static struct root_record *get_root_rec(struct cache_tree *root_cache,
1500                                         u64 objectid)
1501 {
1502         struct cache_extent *cache;
1503         struct root_record *rec = NULL;
1504         int ret;
1505
1506         cache = lookup_cache_extent(root_cache, objectid, 1);
1507         if (cache) {
1508                 rec = container_of(cache, struct root_record, cache);
1509         } else {
1510                 rec = calloc(1, sizeof(*rec));
1511                 rec->objectid = objectid;
1512                 INIT_LIST_HEAD(&rec->backrefs);
1513                 rec->cache.start = objectid;
1514                 rec->cache.size = 1;
1515
1516                 ret = insert_cache_extent(root_cache, &rec->cache);
1517                 BUG_ON(ret);
1518         }
1519         return rec;
1520 }
1521
1522 static struct root_backref *get_root_backref(struct root_record *rec,
1523                                              u64 ref_root, u64 dir, u64 index,
1524                                              const char *name, int namelen)
1525 {
1526         struct root_backref *backref;
1527
1528         list_for_each_entry(backref, &rec->backrefs, list) {
1529                 if (backref->ref_root != ref_root || backref->dir != dir ||
1530                     backref->namelen != namelen)
1531                         continue;
1532                 if (memcmp(name, backref->name, namelen))
1533                         continue;
1534                 return backref;
1535         }
1536
1537         backref = malloc(sizeof(*backref) + namelen + 1);
1538         memset(backref, 0, sizeof(*backref));
1539         backref->ref_root = ref_root;
1540         backref->dir = dir;
1541         backref->index = index;
1542         backref->namelen = namelen;
1543         memcpy(backref->name, name, namelen);
1544         backref->name[namelen] = '\0';
1545         list_add_tail(&backref->list, &rec->backrefs);
1546         return backref;
1547 }
1548
1549 static void free_root_record(struct cache_extent *cache)
1550 {
1551         struct root_record *rec;
1552         struct root_backref *backref;
1553
1554         rec = container_of(cache, struct root_record, cache);
1555         while (!list_empty(&rec->backrefs)) {
1556                 backref = list_entry(rec->backrefs.next,
1557                                      struct root_backref, list);
1558                 list_del(&backref->list);
1559                 free(backref);
1560         }
1561
1562         kfree(rec);
1563 }
1564
1565 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
1566
1567 static int add_root_backref(struct cache_tree *root_cache,
1568                             u64 root_id, u64 ref_root, u64 dir, u64 index,
1569                             const char *name, int namelen,
1570                             int item_type, int errors)
1571 {
1572         struct root_record *rec;
1573         struct root_backref *backref;
1574
1575         rec = get_root_rec(root_cache, root_id);
1576         backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
1577
1578         backref->errors |= errors;
1579
1580         if (item_type != BTRFS_DIR_ITEM_KEY) {
1581                 if (backref->found_dir_index || backref->found_back_ref ||
1582                     backref->found_forward_ref) {
1583                         if (backref->index != index)
1584                                 backref->errors |= REF_ERR_INDEX_UNMATCH;
1585                 } else {
1586                         backref->index = index;
1587                 }
1588         }
1589
1590         if (item_type == BTRFS_DIR_ITEM_KEY) {
1591                 if (backref->found_forward_ref)
1592                         rec->found_ref++;
1593                 backref->found_dir_item = 1;
1594         } else if (item_type == BTRFS_DIR_INDEX_KEY) {
1595                 backref->found_dir_index = 1;
1596         } else if (item_type == BTRFS_ROOT_REF_KEY) {
1597                 if (backref->found_forward_ref)
1598                         backref->errors |= REF_ERR_DUP_ROOT_REF;
1599                 else if (backref->found_dir_item)
1600                         rec->found_ref++;
1601                 backref->found_forward_ref = 1;
1602         } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
1603                 if (backref->found_back_ref)
1604                         backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
1605                 backref->found_back_ref = 1;
1606         } else {
1607                 BUG_ON(1);
1608         }
1609
1610         if (backref->found_forward_ref && backref->found_dir_item)
1611                 backref->reachable = 1;
1612         return 0;
1613 }
1614
1615 static int merge_root_recs(struct btrfs_root *root,
1616                            struct cache_tree *src_cache,
1617                            struct cache_tree *dst_cache)
1618 {
1619         struct cache_extent *cache;
1620         struct ptr_node *node;
1621         struct inode_record *rec;
1622         struct inode_backref *backref;
1623
1624         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
1625                 free_inode_recs_tree(src_cache);
1626                 return 0;
1627         }
1628
1629         while (1) {
1630                 cache = search_cache_extent(src_cache, 0);
1631                 if (!cache)
1632                         break;
1633                 node = container_of(cache, struct ptr_node, cache);
1634                 rec = node->data;
1635                 remove_cache_extent(src_cache, &node->cache);
1636                 free(node);
1637
1638                 if (!is_child_root(root, root->objectid, rec->ino))
1639                         goto skip;
1640
1641                 list_for_each_entry(backref, &rec->backrefs, list) {
1642                         BUG_ON(backref->found_inode_ref);
1643                         if (backref->found_dir_item)
1644                                 add_root_backref(dst_cache, rec->ino,
1645                                         root->root_key.objectid, backref->dir,
1646                                         backref->index, backref->name,
1647                                         backref->namelen, BTRFS_DIR_ITEM_KEY,
1648                                         backref->errors);
1649                         if (backref->found_dir_index)
1650                                 add_root_backref(dst_cache, rec->ino,
1651                                         root->root_key.objectid, backref->dir,
1652                                         backref->index, backref->name,
1653                                         backref->namelen, BTRFS_DIR_INDEX_KEY,
1654                                         backref->errors);
1655                 }
1656 skip:
1657                 free_inode_rec(rec);
1658         }
1659         return 0;
1660 }
1661
1662 static int check_root_refs(struct btrfs_root *root,
1663                            struct cache_tree *root_cache)
1664 {
1665         struct root_record *rec;
1666         struct root_record *ref_root;
1667         struct root_backref *backref;
1668         struct cache_extent *cache;
1669         int loop = 1;
1670         int ret;
1671         int error;
1672         int errors = 0;
1673
1674         rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
1675         rec->found_ref = 1;
1676
1677         /* fixme: this can not detect circular references */
1678         while (loop) {
1679                 loop = 0;
1680                 cache = search_cache_extent(root_cache, 0);
1681                 while (1) {
1682                         if (!cache)
1683                                 break;
1684                         rec = container_of(cache, struct root_record, cache);
1685                         cache = next_cache_extent(cache);
1686
1687                         if (rec->found_ref == 0)
1688                                 continue;
1689
1690                         list_for_each_entry(backref, &rec->backrefs, list) {
1691                                 if (!backref->reachable)
1692                                         continue;
1693
1694                                 ref_root = get_root_rec(root_cache,
1695                                                         backref->ref_root);
1696                                 if (ref_root->found_ref > 0)
1697                                         continue;
1698
1699                                 backref->reachable = 0;
1700                                 rec->found_ref--;
1701                                 if (rec->found_ref == 0)
1702                                         loop = 1;
1703                         }
1704                 }
1705         }
1706
1707         cache = search_cache_extent(root_cache, 0);
1708         while (1) {
1709                 if (!cache)
1710                         break;
1711                 rec = container_of(cache, struct root_record, cache);
1712                 cache = next_cache_extent(cache);
1713
1714                 if (rec->found_ref == 0 &&
1715                     rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1716                     rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
1717                         ret = check_orphan_item(root->fs_info->tree_root,
1718                                                 rec->objectid);
1719                         if (ret == 0)
1720                                 continue;
1721
1722                         /*
1723                          * If we don't have a root item then we likely just have
1724                          * a dir item in a snapshot for this root but no actual
1725                          * ref key or anything so it's meaningless.
1726                          */
1727                         if (!rec->found_root_item)
1728                                 continue;
1729                         errors++;
1730                         fprintf(stderr, "fs tree %llu not referenced\n",
1731                                 (unsigned long long)rec->objectid);
1732                 }
1733
1734                 error = 0;
1735                 if (rec->found_ref > 0 && !rec->found_root_item)
1736                         error = 1;
1737                 list_for_each_entry(backref, &rec->backrefs, list) {
1738                         if (!backref->found_dir_item)
1739                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
1740                         if (!backref->found_dir_index)
1741                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
1742                         if (!backref->found_back_ref)
1743                                 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
1744                         if (!backref->found_forward_ref)
1745                                 backref->errors |= REF_ERR_NO_ROOT_REF;
1746                         if (backref->reachable && backref->errors)
1747                                 error = 1;
1748                 }
1749                 if (!error)
1750                         continue;
1751
1752                 errors++;
1753                 fprintf(stderr, "fs tree %llu refs %u %s\n",
1754                         (unsigned long long)rec->objectid, rec->found_ref,
1755                          rec->found_root_item ? "" : "not found");
1756
1757                 list_for_each_entry(backref, &rec->backrefs, list) {
1758                         if (!backref->reachable)
1759                                 continue;
1760                         if (!backref->errors && rec->found_root_item)
1761                                 continue;
1762                         fprintf(stderr, "\tunresolved ref root %llu dir %llu"
1763                                 " index %llu namelen %u name %s error %x\n",
1764                                 (unsigned long long)backref->ref_root,
1765                                 (unsigned long long)backref->dir,
1766                                 (unsigned long long)backref->index,
1767                                 backref->namelen, backref->name,
1768                                 backref->errors);
1769                 }
1770         }
1771         return errors > 0 ? 1 : 0;
1772 }
1773
1774 static int process_root_ref(struct extent_buffer *eb, int slot,
1775                             struct btrfs_key *key,
1776                             struct cache_tree *root_cache)
1777 {
1778         u64 dirid;
1779         u64 index;
1780         u32 len;
1781         u32 name_len;
1782         struct btrfs_root_ref *ref;
1783         char namebuf[BTRFS_NAME_LEN];
1784         int error;
1785
1786         ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
1787
1788         dirid = btrfs_root_ref_dirid(eb, ref);
1789         index = btrfs_root_ref_sequence(eb, ref);
1790         name_len = btrfs_root_ref_name_len(eb, ref);
1791
1792         if (name_len <= BTRFS_NAME_LEN) {
1793                 len = name_len;
1794                 error = 0;
1795         } else {
1796                 len = BTRFS_NAME_LEN;
1797                 error = REF_ERR_NAME_TOO_LONG;
1798         }
1799         read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
1800
1801         if (key->type == BTRFS_ROOT_REF_KEY) {
1802                 add_root_backref(root_cache, key->offset, key->objectid, dirid,
1803                                  index, namebuf, len, key->type, error);
1804         } else {
1805                 add_root_backref(root_cache, key->objectid, key->offset, dirid,
1806                                  index, namebuf, len, key->type, error);
1807         }
1808         return 0;
1809 }
1810
1811 static int check_fs_root(struct btrfs_root *root,
1812                          struct cache_tree *root_cache,
1813                          struct walk_control *wc)
1814 {
1815         int ret = 0;
1816         int wret;
1817         int level;
1818         struct btrfs_path path;
1819         struct shared_node root_node;
1820         struct root_record *rec;
1821         struct btrfs_root_item *root_item = &root->root_item;
1822
1823         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1824                 rec = get_root_rec(root_cache, root->root_key.objectid);
1825                 if (btrfs_root_refs(root_item) > 0)
1826                         rec->found_root_item = 1;
1827         }
1828
1829         btrfs_init_path(&path);
1830         memset(&root_node, 0, sizeof(root_node));
1831         cache_tree_init(&root_node.root_cache);
1832         cache_tree_init(&root_node.inode_cache);
1833
1834         level = btrfs_header_level(root->node);
1835         memset(wc->nodes, 0, sizeof(wc->nodes));
1836         wc->nodes[level] = &root_node;
1837         wc->active_node = level;
1838         wc->root_level = level;
1839
1840         if (btrfs_root_refs(root_item) > 0 ||
1841             btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
1842                 path.nodes[level] = root->node;
1843                 extent_buffer_get(root->node);
1844                 path.slots[level] = 0;
1845         } else {
1846                 struct btrfs_key key;
1847                 struct btrfs_disk_key found_key;
1848
1849                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
1850                 level = root_item->drop_level;
1851                 path.lowest_level = level;
1852                 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
1853                 BUG_ON(wret < 0);
1854                 btrfs_node_key(path.nodes[level], &found_key,
1855                                 path.slots[level]);
1856                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
1857                                         sizeof(found_key)));
1858         }
1859
1860         while (1) {
1861                 wret = walk_down_tree(root, &path, wc, &level);
1862                 if (wret < 0)
1863                         ret = wret;
1864                 if (wret != 0)
1865                         break;
1866
1867                 wret = walk_up_tree(root, &path, wc, &level);
1868                 if (wret < 0)
1869                         ret = wret;
1870                 if (wret != 0)
1871                         break;
1872         }
1873         btrfs_release_path(&path);
1874
1875         merge_root_recs(root, &root_node.root_cache, root_cache);
1876
1877         if (root_node.current) {
1878                 root_node.current->checked = 1;
1879                 maybe_free_inode_rec(&root_node.inode_cache,
1880                                 root_node.current);
1881         }
1882
1883         ret = check_inode_recs(root, &root_node.inode_cache);
1884         return ret;
1885 }
1886
1887 static int fs_root_objectid(u64 objectid)
1888 {
1889         if (objectid == BTRFS_FS_TREE_OBJECTID ||
1890             objectid == BTRFS_TREE_RELOC_OBJECTID ||
1891             objectid == BTRFS_DATA_RELOC_TREE_OBJECTID ||
1892             (objectid >= BTRFS_FIRST_FREE_OBJECTID &&
1893              objectid <= BTRFS_LAST_FREE_OBJECTID))
1894                 return 1;
1895         return 0;
1896 }
1897
1898 static int check_fs_roots(struct btrfs_root *root,
1899                           struct cache_tree *root_cache)
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);
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)
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)
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);
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                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
5601
5602         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
5603                             (unsigned long)btrfs_header_chunk_tree_uuid(c),
5604                             BTRFS_UUID_SIZE);
5605
5606         btrfs_mark_buffer_dirty(c);
5607
5608         free_extent_buffer(old);
5609         root->node = c;
5610         add_root_to_dirty_list(root);
5611         return 0;
5612 }
5613
5614 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
5615                                 struct extent_buffer *eb, int tree_root)
5616 {
5617         struct extent_buffer *tmp;
5618         struct btrfs_root_item *ri;
5619         struct btrfs_key key;
5620         u64 bytenr;
5621         u32 leafsize;
5622         int level = btrfs_header_level(eb);
5623         int nritems;
5624         int ret;
5625         int i;
5626
5627         btrfs_pin_extent(fs_info, eb->start, eb->len);
5628
5629         leafsize = btrfs_super_leafsize(fs_info->super_copy);
5630         nritems = btrfs_header_nritems(eb);
5631         for (i = 0; i < nritems; i++) {
5632                 if (level == 0) {
5633                         btrfs_item_key_to_cpu(eb, &key, i);
5634                         if (key.type != BTRFS_ROOT_ITEM_KEY)
5635                                 continue;
5636                         /* Skip the extent root and reloc roots */
5637                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
5638                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
5639                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
5640                                 continue;
5641                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
5642                         bytenr = btrfs_disk_root_bytenr(eb, ri);
5643
5644                         /*
5645                          * If at any point we start needing the real root we
5646                          * will have to build a stump root for the root we are
5647                          * in, but for now this doesn't actually use the root so
5648                          * just pass in extent_root.
5649                          */
5650                         tmp = read_tree_block(fs_info->extent_root, bytenr,
5651                                               leafsize, 0);
5652                         if (!tmp) {
5653                                 fprintf(stderr, "Error reading root block\n");
5654                                 return -EIO;
5655                         }
5656                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
5657                         free_extent_buffer(tmp);
5658                         if (ret)
5659                                 return ret;
5660                 } else {
5661                         bytenr = btrfs_node_blockptr(eb, i);
5662
5663                         /* If we aren't the tree root don't read the block */
5664                         if (level == 1 && !tree_root) {
5665                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
5666                                 continue;
5667                         }
5668
5669                         tmp = read_tree_block(fs_info->extent_root, bytenr,
5670                                               leafsize, 0);
5671                         if (!tmp) {
5672                                 fprintf(stderr, "Error reading tree block\n");
5673                                 return -EIO;
5674                         }
5675                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
5676                         free_extent_buffer(tmp);
5677                         if (ret)
5678                                 return ret;
5679                 }
5680         }
5681
5682         return 0;
5683 }
5684
5685 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
5686 {
5687         int ret;
5688
5689         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
5690         if (ret)
5691                 return ret;
5692
5693         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
5694 }
5695
5696 static int reset_block_groups(struct btrfs_fs_info *fs_info)
5697 {
5698         struct btrfs_path *path;
5699         struct extent_buffer *leaf;
5700         struct btrfs_chunk *chunk;
5701         struct btrfs_key key;
5702         int ret;
5703
5704         path = btrfs_alloc_path();
5705         if (!path)
5706                 return -ENOMEM;
5707
5708         key.objectid = 0;
5709         key.type = BTRFS_CHUNK_ITEM_KEY;
5710         key.offset = 0;
5711
5712         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
5713         if (ret < 0) {
5714                 btrfs_free_path(path);
5715                 return ret;
5716         }
5717
5718         /*
5719          * We do this in case the block groups were screwed up and had alloc
5720          * bits that aren't actually set on the chunks.  This happens with
5721          * restored images every time and could happen in real life I guess.
5722          */
5723         fs_info->avail_data_alloc_bits = 0;
5724         fs_info->avail_metadata_alloc_bits = 0;
5725         fs_info->avail_system_alloc_bits = 0;
5726
5727         /* First we need to create the in-memory block groups */
5728         while (1) {
5729                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5730                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
5731                         if (ret < 0) {
5732                                 btrfs_free_path(path);
5733                                 return ret;
5734                         }
5735                         if (ret) {
5736                                 ret = 0;
5737                                 break;
5738                         }
5739                 }
5740                 leaf = path->nodes[0];
5741                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5742                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
5743                         path->slots[0]++;
5744                         continue;
5745                 }
5746
5747                 chunk = btrfs_item_ptr(leaf, path->slots[0],
5748                                        struct btrfs_chunk);
5749                 btrfs_add_block_group(fs_info, 0,
5750                                       btrfs_chunk_type(leaf, chunk),
5751                                       key.objectid, key.offset,
5752                                       btrfs_chunk_length(leaf, chunk));
5753                 path->slots[0]++;
5754         }
5755
5756         btrfs_free_path(path);
5757         return 0;
5758 }
5759
5760 static int reset_balance(struct btrfs_trans_handle *trans,
5761                          struct btrfs_fs_info *fs_info)
5762 {
5763         struct btrfs_root *root = fs_info->tree_root;
5764         struct btrfs_path *path;
5765         struct extent_buffer *leaf;
5766         struct btrfs_key key;
5767         int del_slot, del_nr = 0;
5768         int ret;
5769         int found = 0;
5770
5771         path = btrfs_alloc_path();
5772         if (!path)
5773                 return -ENOMEM;
5774
5775         key.objectid = BTRFS_BALANCE_OBJECTID;
5776         key.type = BTRFS_BALANCE_ITEM_KEY;
5777         key.offset = 0;
5778
5779         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5780         if (ret) {
5781                 if (ret > 0)
5782                         ret = 0;
5783                 goto out;
5784         }
5785
5786         ret = btrfs_del_item(trans, root, path);
5787         if (ret)
5788                 goto out;
5789         btrfs_release_path(path);
5790
5791         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
5792         key.type = BTRFS_ROOT_ITEM_KEY;
5793         key.offset = 0;
5794
5795         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5796         if (ret < 0)
5797                 goto out;
5798         while (1) {
5799                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5800                         if (!found)
5801                                 break;
5802
5803                         if (del_nr) {
5804                                 ret = btrfs_del_items(trans, root, path,
5805                                                       del_slot, del_nr);
5806                                 del_nr = 0;
5807                                 if (ret)
5808                                         goto out;
5809                         }
5810                         key.offset++;
5811                         btrfs_release_path(path);
5812
5813                         found = 0;
5814                         ret = btrfs_search_slot(trans, root, &key, path,
5815                                                 -1, 1);
5816                         if (ret < 0)
5817                                 goto out;
5818                         continue;
5819                 }
5820                 found = 1;
5821                 leaf = path->nodes[0];
5822                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5823                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
5824                         break;
5825                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5826                         path->slots[0]++;
5827                         continue;
5828                 }
5829                 if (!del_nr) {
5830                         del_slot = path->slots[0];
5831                         del_nr = 1;
5832                 } else {
5833                         del_nr++;
5834                 }
5835                 path->slots[0]++;
5836         }
5837
5838         if (del_nr) {
5839                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
5840                 if (ret)
5841                         goto out;
5842         }
5843         btrfs_release_path(path);
5844
5845         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
5846         key.type = BTRFS_ROOT_ITEM_KEY;
5847         key.offset = (u64)-1;
5848         root = btrfs_read_fs_root(fs_info, &key);
5849         if (IS_ERR(root)) {
5850                 fprintf(stderr, "Error reading data reloc tree\n");
5851                 return PTR_ERR(root);
5852         }
5853         root->track_dirty = 1;
5854         if (root->last_trans != trans->transid) {
5855                 root->last_trans = trans->transid;
5856                 root->commit_root = root->node;
5857                 extent_buffer_get(root->node);
5858         }
5859         ret = btrfs_fsck_reinit_root(trans, root, 0);
5860 out:
5861         btrfs_free_path(path);
5862         return ret;
5863 }
5864
5865 static int reinit_extent_tree(struct btrfs_fs_info *fs_info)
5866 {
5867         struct btrfs_trans_handle *trans;
5868         u64 start = 0;
5869         int ret;
5870
5871         /*
5872          * The only reason we don't do this is because right now we're just
5873          * walking the trees we find and pinning down their bytes, we don't look
5874          * at any of the leaves.  In order to do mixed groups we'd have to check
5875          * the leaves of any fs roots and pin down the bytes for any file
5876          * extents we find.  Not hard but why do it if we don't have to?
5877          */
5878         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
5879                 fprintf(stderr, "We don't support re-initing the extent tree "
5880                         "for mixed block groups yet, please notify a btrfs "
5881                         "developer you want to do this so they can add this "
5882                         "functionality.\n");
5883                 return -EINVAL;
5884         }
5885
5886         trans = btrfs_start_transaction(fs_info->extent_root, 1);
5887         if (IS_ERR(trans)) {
5888                 fprintf(stderr, "Error starting transaction\n");
5889                 return PTR_ERR(trans);
5890         }
5891
5892         /*
5893          * first we need to walk all of the trees except the extent tree and pin
5894          * down the bytes that are in use so we don't overwrite any existing
5895          * metadata.
5896          */
5897         ret = pin_metadata_blocks(fs_info);
5898         if (ret) {
5899                 fprintf(stderr, "error pinning down used bytes\n");
5900                 return ret;
5901         }
5902
5903         /*
5904          * Need to drop all the block groups since we're going to recreate all
5905          * of them again.
5906          */
5907         btrfs_free_block_groups(fs_info);
5908         ret = reset_block_groups(fs_info);
5909         if (ret) {
5910                 fprintf(stderr, "error resetting the block groups\n");
5911                 return ret;
5912         }
5913
5914         /* Ok we can allocate now, reinit the extent root */
5915         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 1);
5916         if (ret) {
5917                 fprintf(stderr, "extent root initialization failed\n");
5918                 /*
5919                  * When the transaction code is updated we should end the
5920                  * transaction, but for now progs only knows about commit so
5921                  * just return an error.
5922                  */
5923                 return ret;
5924         }
5925
5926         ret = reset_balance(trans, fs_info);
5927         if (ret) {
5928                 fprintf(stderr, "error reseting the pending balance\n");
5929                 return ret;
5930         }
5931
5932         /*
5933          * Now we have all the in-memory block groups setup so we can make
5934          * allocations properly, and the metadata we care about is safe since we
5935          * pinned all of it above.
5936          */
5937         while (1) {
5938                 struct btrfs_block_group_cache *cache;
5939
5940                 cache = btrfs_lookup_first_block_group(fs_info, start);
5941                 if (!cache)
5942                         break;
5943                 start = cache->key.objectid + cache->key.offset;
5944                 ret = btrfs_insert_item(trans, fs_info->extent_root,
5945                                         &cache->key, &cache->item,
5946                                         sizeof(cache->item));
5947                 if (ret) {
5948                         fprintf(stderr, "Error adding block group\n");
5949                         return ret;
5950                 }
5951                 btrfs_extent_post_op(trans, fs_info->extent_root);
5952         }
5953
5954         /*
5955          * Ok now we commit and run the normal fsck, which will add extent
5956          * entries for all of the items it finds.
5957          */
5958         return btrfs_commit_transaction(trans, fs_info->extent_root);
5959 }
5960
5961 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
5962 {
5963         struct btrfs_path *path;
5964         struct btrfs_trans_handle *trans;
5965         struct btrfs_key key;
5966         int ret;
5967
5968         printf("Recowing metadata block %llu\n", eb->start);
5969         key.objectid = btrfs_header_owner(eb);
5970         key.type = BTRFS_ROOT_ITEM_KEY;
5971         key.offset = (u64)-1;
5972
5973         root = btrfs_read_fs_root(root->fs_info, &key);
5974         if (IS_ERR(root)) {
5975                 fprintf(stderr, "Couldn't find owner root %llu\n",
5976                         key.objectid);
5977                 return PTR_ERR(root);
5978         }
5979
5980         path = btrfs_alloc_path();
5981         if (!path)
5982                 return -ENOMEM;
5983
5984         trans = btrfs_start_transaction(root, 1);
5985         if (IS_ERR(trans)) {
5986                 btrfs_free_path(path);
5987                 return PTR_ERR(trans);
5988         }
5989
5990         path->lowest_level = btrfs_header_level(eb);
5991         if (path->lowest_level)
5992                 btrfs_node_key_to_cpu(eb, &key, 0);
5993         else
5994                 btrfs_item_key_to_cpu(eb, &key, 0);
5995
5996         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
5997         btrfs_commit_transaction(trans, root);
5998         btrfs_free_path(path);
5999         return ret;
6000 }
6001
6002 static struct option long_options[] = {
6003         { "super", 1, NULL, 's' },
6004         { "repair", 0, NULL, 0 },
6005         { "init-csum-tree", 0, NULL, 0 },
6006         { "init-extent-tree", 0, NULL, 0 },
6007         { NULL, 0, NULL, 0}
6008 };
6009
6010 const char * const cmd_check_usage[] = {
6011         "btrfs check [options] <device>",
6012         "Check an unmounted btrfs filesystem.",
6013         "",
6014         "-s|--super <superblock>     use this superblock copy",
6015         "--repair                    try to repair the filesystem",
6016         "--init-csum-tree            create a new CRC tree",
6017         "--init-extent-tree          create a new extent tree",
6018         NULL
6019 };
6020
6021 int cmd_check(int argc, char **argv)
6022 {
6023         struct cache_tree root_cache;
6024         struct btrfs_root *root;
6025         struct btrfs_fs_info *info;
6026         u64 bytenr = 0;
6027         char uuidbuf[37];
6028         int ret;
6029         int num;
6030         int option_index = 0;
6031         int init_csum_tree = 0;
6032         int init_extent_tree = 0;
6033         int rw = 0;
6034
6035         while(1) {
6036                 int c;
6037                 c = getopt_long(argc, argv, "as:", long_options,
6038                                 &option_index);
6039                 if (c < 0)
6040                         break;
6041                 switch(c) {
6042                         case 'a': /* ignored */ break;
6043                         case 's':
6044                                 num = atol(optarg);
6045                                 bytenr = btrfs_sb_offset(num);
6046                                 printf("using SB copy %d, bytenr %llu\n", num,
6047                                        (unsigned long long)bytenr);
6048                                 break;
6049                         case '?':
6050                         case 'h':
6051                                 usage(cmd_check_usage);
6052                 }
6053                 if (option_index == 1) {
6054                         printf("enabling repair mode\n");
6055                         repair = 1;
6056                         rw = 1;
6057                 } else if (option_index == 2) {
6058                         printf("Creating a new CRC tree\n");
6059                         init_csum_tree = 1;
6060                         rw = 1;
6061                 } else if (option_index == 3) {
6062                         init_extent_tree = 1;
6063                         rw = 1;
6064                         repair = 1;
6065                 }
6066
6067         }
6068         argc = argc - optind;
6069
6070         if (argc != 1)
6071                 usage(cmd_check_usage);
6072
6073         radix_tree_init();
6074         cache_tree_init(&root_cache);
6075
6076         if((ret = check_mounted(argv[optind])) < 0) {
6077                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
6078                 return ret;
6079         } else if(ret) {
6080                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
6081                 return -EBUSY;
6082         }
6083
6084         info = open_ctree_fs_info(argv[optind], bytenr, 0, rw, 1);
6085         if (!info) {
6086                 fprintf(stderr, "Couldn't open file system\n");
6087                 return -EIO;
6088         }
6089
6090         uuid_unparse(info->super_copy->fsid, uuidbuf);
6091         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
6092
6093         if (!extent_buffer_uptodate(info->tree_root->node) ||
6094             !extent_buffer_uptodate(info->dev_root->node) ||
6095             !extent_buffer_uptodate(info->extent_root->node) ||
6096             !extent_buffer_uptodate(info->chunk_root->node)) {
6097                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
6098                 return -EIO;
6099         }
6100
6101         root = info->fs_root;
6102
6103         if (init_extent_tree) {
6104                 printf("Creating a new extent tree\n");
6105                 ret = reinit_extent_tree(info);
6106                 if (ret)
6107                         return ret;
6108         }
6109         fprintf(stderr, "checking extents\n");
6110         if (init_csum_tree) {
6111                 struct btrfs_trans_handle *trans;
6112
6113                 fprintf(stderr, "Reinit crc root\n");
6114                 trans = btrfs_start_transaction(info->csum_root, 1);
6115                 if (IS_ERR(trans)) {
6116                         fprintf(stderr, "Error starting transaction\n");
6117                         return PTR_ERR(trans);
6118                 }
6119
6120                 ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
6121                 if (ret) {
6122                         fprintf(stderr, "crc root initialization failed\n");
6123                         return -EIO;
6124                 }
6125
6126                 ret = btrfs_commit_transaction(trans, info->csum_root);
6127                 if (ret)
6128                         exit(1);
6129                 goto out;
6130         }
6131         ret = check_chunks_and_extents(root);
6132         if (ret)
6133                 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
6134
6135         fprintf(stderr, "checking free space cache\n");
6136         ret = check_space_cache(root);
6137         if (ret)
6138                 goto out;
6139
6140         fprintf(stderr, "checking fs roots\n");
6141         ret = check_fs_roots(root, &root_cache);
6142         if (ret)
6143                 goto out;
6144
6145         fprintf(stderr, "checking csums\n");
6146         ret = check_csums(root);
6147         if (ret)
6148                 goto out;
6149
6150         fprintf(stderr, "checking root refs\n");
6151         ret = check_root_refs(root, &root_cache);
6152         if (ret)
6153                 goto out;
6154
6155         while (repair && !list_empty(&root->fs_info->recow_ebs)) {
6156                 struct extent_buffer *eb;
6157
6158                 eb = list_first_entry(&root->fs_info->recow_ebs,
6159                                       struct extent_buffer, recow);
6160                 ret = recow_extent_buffer(root, eb);
6161                 if (ret)
6162                         break;
6163         }
6164
6165         if (!list_empty(&root->fs_info->recow_ebs)) {
6166                 fprintf(stderr, "Transid errors in file system\n");
6167                 ret = 1;
6168         }
6169 out:
6170         free_root_recs_tree(&root_cache);
6171         close_ctree(root);
6172
6173         if (found_old_backref) { /*
6174                  * there was a disk format change when mixed
6175                  * backref was in testing tree. The old format
6176                  * existed about one week.
6177                  */
6178                 printf("\n * Found old mixed backref format. "
6179                        "The old format is not supported! *"
6180                        "\n * Please mount the FS in readonly mode, "
6181                        "backup data and re-format the FS. *\n\n");
6182                 ret = 1;
6183         }
6184         printf("found %llu bytes used err is %d\n",
6185                (unsigned long long)bytes_used, ret);
6186         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
6187         printf("total tree bytes: %llu\n",
6188                (unsigned long long)total_btree_bytes);
6189         printf("total fs tree bytes: %llu\n",
6190                (unsigned long long)total_fs_tree_bytes);
6191         printf("total extent tree bytes: %llu\n",
6192                (unsigned long long)total_extent_tree_bytes);
6193         printf("btree space waste bytes: %llu\n",
6194                (unsigned long long)btree_space_waste);
6195         printf("file data blocks allocated: %llu\n referenced %llu\n",
6196                 (unsigned long long)data_bytes_allocated,
6197                 (unsigned long long)data_bytes_referenced);
6198         printf("%s\n", BTRFS_BUILD_VERSION);
6199         return ret;
6200 }