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