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