btrfs-progs: cleanup whitespace in is_same_blk_file
[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         /* We don't believe this either, reset it and iterate backref */
1963         rec->found_link = 0;
1964
1965         /* Remove all backref including the valid ones */
1966         list_for_each_entry_safe(backref, tmp, &rec->backrefs, list) {
1967                 ret = btrfs_unlink(trans, root, rec->ino, backref->dir,
1968                                    backref->index, backref->name,
1969                                    backref->namelen, 0);
1970                 if (ret < 0)
1971                         goto out;
1972
1973                 /* remove invalid backref, so it won't be added back */
1974                 if (!(backref->found_dir_index &&
1975                       backref->found_dir_item &&
1976                       backref->found_inode_ref)) {
1977                         list_del(&backref->list);
1978                         free(backref);
1979                 } else {
1980                         rec->found_link++;
1981                 }
1982         }
1983
1984         /* Set nlink to 0 */
1985         key.objectid = rec->ino;
1986         key.type = BTRFS_INODE_ITEM_KEY;
1987         key.offset = 0;
1988         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1989         if (ret < 0)
1990                 goto out;
1991         if (ret > 0) {
1992                 ret = -ENOENT;
1993                 goto out;
1994         }
1995         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1996                                     struct btrfs_inode_item);
1997         btrfs_set_inode_nlink(path->nodes[0], inode_item, 0);
1998         btrfs_mark_buffer_dirty(path->nodes[0]);
1999         btrfs_release_path(path);
2000
2001         /*
2002          * Add back valid inode_ref/dir_item/dir_index,
2003          * add_link() will handle the nlink inc, so new nlink must be correct
2004          */
2005         list_for_each_entry(backref, &rec->backrefs, list) {
2006                 ret = btrfs_add_link(trans, root, rec->ino, backref->dir,
2007                                      backref->name, backref->namelen,
2008                                      backref->ref_type, &backref->index, 1);
2009                 if (ret < 0)
2010                         goto out;
2011         }
2012 out:
2013         btrfs_release_path(path);
2014         return ret;
2015 }
2016
2017 static int repair_inode_nlinks(struct btrfs_trans_handle *trans,
2018                                struct btrfs_root *root,
2019                                struct btrfs_path *path,
2020                                struct inode_record *rec)
2021 {
2022         char *dir_name = "lost+found";
2023         char namebuf[BTRFS_NAME_LEN] = {0};
2024         u64 lost_found_ino;
2025         u32 mode = 0700;
2026         u8 type = 0;
2027         int namelen = 0;
2028         int name_recovered = 0;
2029         int type_recovered = 0;
2030         int ret = 0;
2031
2032         /*
2033          * Get file name and type first before these invalid inode ref
2034          * are deleted by remove_all_invalid_backref()
2035          */
2036         name_recovered = !find_file_name(rec, namebuf, &namelen);
2037         type_recovered = !find_file_type(rec, &type);
2038
2039         if (!name_recovered) {
2040                 printf("Can't get file name for inode %llu, using '%llu' as fallback\n",
2041                        rec->ino, rec->ino);
2042                 namelen = count_digits(rec->ino);
2043                 sprintf(namebuf, "%llu", rec->ino);
2044                 name_recovered = 1;
2045         }
2046         if (!type_recovered) {
2047                 printf("Can't get file type for inode %llu, using FILE as fallback\n",
2048                        rec->ino);
2049                 type = BTRFS_FT_REG_FILE;
2050                 type_recovered = 1;
2051         }
2052
2053         ret = reset_nlink(trans, root, path, rec);
2054         if (ret < 0) {
2055                 fprintf(stderr,
2056                         "Failed to reset nlink for inode %llu: %s\n",
2057                         rec->ino, strerror(-ret));
2058                 goto out;
2059         }
2060
2061         if (rec->found_link == 0) {
2062                 lost_found_ino = root->highest_inode;
2063                 if (lost_found_ino >= BTRFS_LAST_FREE_OBJECTID) {
2064                         ret = -EOVERFLOW;
2065                         goto out;
2066                 }
2067                 lost_found_ino++;
2068                 ret = btrfs_mkdir(trans, root, dir_name, strlen(dir_name),
2069                                   BTRFS_FIRST_FREE_OBJECTID, &lost_found_ino,
2070                                   mode);
2071                 if (ret < 0) {
2072                         fprintf(stderr, "Failed to create '%s' dir: %s",
2073                                 dir_name, strerror(-ret));
2074                         goto out;
2075                 }
2076                 ret = btrfs_add_link(trans, root, rec->ino, lost_found_ino,
2077                                      namebuf, namelen, type, NULL, 1);
2078                 if (ret == -EEXIST) {
2079                         /*
2080                          * Conflicting file name, add ".INO" as suffix * +1 for '.'
2081                          */
2082                         if (namelen + count_digits(rec->ino) + 1 >
2083                             BTRFS_NAME_LEN) {
2084                                 ret = -EFBIG;
2085                                 goto out;
2086                         }
2087                         snprintf(namebuf + namelen, BTRFS_NAME_LEN - namelen,
2088                                  ".%llu", rec->ino);
2089                         namelen += count_digits(rec->ino) + 1;
2090                         ret = btrfs_add_link(trans, root, rec->ino,
2091                                              lost_found_ino, namebuf,
2092                                              namelen, type, NULL, 1);
2093                 }
2094                 if (ret < 0) {
2095                         fprintf(stderr,
2096                                 "Failed to link the inode %llu to %s dir: %s",
2097                                 rec->ino, dir_name, strerror(-ret));
2098                         goto out;
2099                 }
2100                 /*
2101                  * Just increase the found_link, don't actually add the
2102                  * backref. This will make things easier and this inode
2103                  * record will be freed after the repair is done.
2104                  * So fsck will not report problem about this inode.
2105                  */
2106                 rec->found_link++;
2107                 printf("Moving file '%.*s' to '%s' dir since it has no valid backref\n",
2108                        namelen, namebuf, dir_name);
2109         }
2110         rec->errors &= ~I_ERR_LINK_COUNT_WRONG;
2111         printf("Fixed the nlink of inode %llu\n", rec->ino);
2112 out:
2113         btrfs_release_path(path);
2114         return ret;
2115 }
2116
2117 /*
2118  * Check if there is any normal(reg or prealloc) file extent for given
2119  * ino.
2120  * This is used to determine the file type when neither its dir_index/item or
2121  * inode_item exists.
2122  *
2123  * This will *NOT* report error, if any error happens, just consider it does
2124  * not have any normal file extent.
2125  */
2126 static int find_normal_file_extent(struct btrfs_root *root, u64 ino)
2127 {
2128         struct btrfs_path *path;
2129         struct btrfs_key key;
2130         struct btrfs_key found_key;
2131         struct btrfs_file_extent_item *fi;
2132         u8 type;
2133         int ret = 0;
2134
2135         path = btrfs_alloc_path();
2136         if (!path)
2137                 goto out;
2138         key.objectid = ino;
2139         key.type = BTRFS_EXTENT_DATA_KEY;
2140         key.offset = 0;
2141
2142         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2143         if (ret < 0) {
2144                 ret = 0;
2145                 goto out;
2146         }
2147         if (ret && path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2148                 ret = btrfs_next_leaf(root, path);
2149                 if (ret) {
2150                         ret = 0;
2151                         goto out;
2152                 }
2153         }
2154         while (1) {
2155                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2156                                       path->slots[0]);
2157                 if (found_key.objectid != ino ||
2158                     found_key.type != BTRFS_EXTENT_DATA_KEY)
2159                         break;
2160                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
2161                                     struct btrfs_file_extent_item);
2162                 type = btrfs_file_extent_type(path->nodes[0], fi);
2163                 if (type != BTRFS_FILE_EXTENT_INLINE) {
2164                         ret = 1;
2165                         goto out;
2166                 }
2167         }
2168 out:
2169         btrfs_free_path(path);
2170         return ret;
2171 }
2172
2173 static u32 btrfs_type_to_imode(u8 type)
2174 {
2175         static u32 imode_by_btrfs_type[] = {
2176                 [BTRFS_FT_REG_FILE]     = S_IFREG,
2177                 [BTRFS_FT_DIR]          = S_IFDIR,
2178                 [BTRFS_FT_CHRDEV]       = S_IFCHR,
2179                 [BTRFS_FT_BLKDEV]       = S_IFBLK,
2180                 [BTRFS_FT_FIFO]         = S_IFIFO,
2181                 [BTRFS_FT_SOCK]         = S_IFSOCK,
2182                 [BTRFS_FT_SYMLINK]      = S_IFLNK,
2183         };
2184
2185         return imode_by_btrfs_type[(type)];
2186 }
2187
2188 static int repair_inode_no_item(struct btrfs_trans_handle *trans,
2189                                 struct btrfs_root *root,
2190                                 struct btrfs_path *path,
2191                                 struct inode_record *rec)
2192 {
2193         u8 filetype;
2194         u32 mode = 0700;
2195         int type_recovered = 0;
2196         int ret = 0;
2197
2198         /*
2199          * TODO:
2200          * 1. salvage data from existing file extent and
2201          *    punch hole to keep fi ext consistent.
2202          * 2. salvage data from extent tree
2203          */
2204         printf("Trying to rebuild inode:%llu\n", rec->ino);
2205
2206         type_recovered = !find_file_type(rec, &filetype);
2207
2208         /*
2209          * Try to determine inode type if type not found.
2210          *
2211          * For found regular file extent, it must be FILE.
2212          * For found dir_item/index, it must be DIR.
2213          *
2214          * For undetermined one, use FILE as fallback.
2215          *
2216          * TODO:
2217          * 1. If found extent belong to it in extent tree, it must be FILE
2218          *    Need extra hook in extent tree scan.
2219          * 2. If found backref(inode_index/item is already handled) to it,
2220          *    it must be DIR.
2221          *    Need new inode-inode ref structure to allow search for that.
2222          */
2223         if (!type_recovered) {
2224                 if (rec->found_file_extent &&
2225                     find_normal_file_extent(root, rec->ino)) {
2226                         type_recovered = 1;
2227                         filetype = BTRFS_FT_REG_FILE;
2228                 } else if (rec->found_dir_item) {
2229                         type_recovered = 1;
2230                         filetype = BTRFS_FT_DIR;
2231                 } else {
2232                         printf("Can't determint the filetype for inode %llu, assume it is a normal file\n",
2233                                rec->ino);
2234                         type_recovered = 1;
2235                         filetype = BTRFS_FT_REG_FILE;
2236                 }
2237         }
2238
2239         ret = btrfs_new_inode(trans, root, rec->ino,
2240                               mode | btrfs_type_to_imode(filetype));
2241         if (ret < 0)
2242                 goto out;
2243
2244         /*
2245          * Here inode rebuild is done, we only rebuild the inode item,
2246          * don't repair the nlink(like move to lost+found).
2247          * That is the job of nlink repair.
2248          *
2249          * We just fill the record and return
2250          */
2251         rec->found_dir_item = 1;
2252         rec->imode = mode | btrfs_type_to_imode(filetype);
2253         rec->nlink = 0;
2254         rec->errors &= ~I_ERR_NO_INODE_ITEM;
2255         /* Ensure the inode_nlinks repair function will be called */
2256         rec->errors |= I_ERR_LINK_COUNT_WRONG;
2257 out:
2258         return ret;
2259 }
2260
2261 static int try_repair_inode(struct btrfs_root *root, struct inode_record *rec)
2262 {
2263         struct btrfs_trans_handle *trans;
2264         struct btrfs_path *path;
2265         int ret = 0;
2266
2267         if (!(rec->errors & (I_ERR_DIR_ISIZE_WRONG |
2268                              I_ERR_NO_ORPHAN_ITEM |
2269                              I_ERR_LINK_COUNT_WRONG |
2270                              I_ERR_NO_INODE_ITEM)))
2271                 return rec->errors;
2272
2273         path = btrfs_alloc_path();
2274         if (!path)
2275                 return -ENOMEM;
2276
2277         /*
2278          * For nlink repair, it may create a dir and add link, so
2279          * 2 for parent(256)'s dir_index and dir_item
2280          * 2 for lost+found dir's inode_item and inode_ref
2281          * 1 for the new inode_ref of the file
2282          * 2 for lost+found dir's dir_index and dir_item for the file
2283          */
2284         trans = btrfs_start_transaction(root, 7);
2285         if (IS_ERR(trans)) {
2286                 btrfs_free_path(path);
2287                 return PTR_ERR(trans);
2288         }
2289
2290         if (rec->errors & I_ERR_NO_INODE_ITEM)
2291                 ret = repair_inode_no_item(trans, root, path, rec);
2292         if (!ret && rec->errors & I_ERR_DIR_ISIZE_WRONG)
2293                 ret = repair_inode_isize(trans, root, path, rec);
2294         if (!ret && rec->errors & I_ERR_NO_ORPHAN_ITEM)
2295                 ret = repair_inode_orphan_item(trans, root, path, rec);
2296         if (!ret && rec->errors & I_ERR_LINK_COUNT_WRONG)
2297                 ret = repair_inode_nlinks(trans, root, path, rec);
2298         btrfs_commit_transaction(trans, root);
2299         btrfs_free_path(path);
2300         return ret;
2301 }
2302
2303 static int check_inode_recs(struct btrfs_root *root,
2304                             struct cache_tree *inode_cache)
2305 {
2306         struct cache_extent *cache;
2307         struct ptr_node *node;
2308         struct inode_record *rec;
2309         struct inode_backref *backref;
2310         int stage = 0;
2311         int ret;
2312         int err = 0;
2313         u64 error = 0;
2314         u64 root_dirid = btrfs_root_dirid(&root->root_item);
2315
2316         if (btrfs_root_refs(&root->root_item) == 0) {
2317                 if (!cache_tree_empty(inode_cache))
2318                         fprintf(stderr, "warning line %d\n", __LINE__);
2319                 return 0;
2320         }
2321
2322         /*
2323          * We need to record the highest inode number for later 'lost+found'
2324          * dir creation.
2325          * We must select a ino not used/refered by any existing inode, or
2326          * 'lost+found' ino may be a missing ino in a corrupted leaf,
2327          * this may cause 'lost+found' dir has wrong nlinks.
2328          */
2329         cache = last_cache_extent(inode_cache);
2330         if (cache) {
2331                 node = container_of(cache, struct ptr_node, cache);
2332                 rec = node->data;
2333                 if (rec->ino > root->highest_inode)
2334                         root->highest_inode = rec->ino;
2335         }
2336
2337         /*
2338          * We need to repair backrefs first because we could change some of the
2339          * errors in the inode recs.
2340          *
2341          * We also need to go through and delete invalid backrefs first and then
2342          * add the correct ones second.  We do this because we may get EEXIST
2343          * when adding back the correct index because we hadn't yet deleted the
2344          * invalid index.
2345          *
2346          * For example, if we were missing a dir index then the directories
2347          * isize would be wrong, so if we fixed the isize to what we thought it
2348          * would be and then fixed the backref we'd still have a invalid fs, so
2349          * we need to add back the dir index and then check to see if the isize
2350          * is still wrong.
2351          */
2352         while (stage < 3) {
2353                 stage++;
2354                 if (stage == 3 && !err)
2355                         break;
2356
2357                 cache = search_cache_extent(inode_cache, 0);
2358                 while (repair && cache) {
2359                         node = container_of(cache, struct ptr_node, cache);
2360                         rec = node->data;
2361                         cache = next_cache_extent(cache);
2362
2363                         /* Need to free everything up and rescan */
2364                         if (stage == 3) {
2365                                 remove_cache_extent(inode_cache, &node->cache);
2366                                 free(node);
2367                                 free_inode_rec(rec);
2368                                 continue;
2369                         }
2370
2371                         if (list_empty(&rec->backrefs))
2372                                 continue;
2373
2374                         ret = repair_inode_backrefs(root, rec, inode_cache,
2375                                                     stage == 1);
2376                         if (ret < 0) {
2377                                 err = ret;
2378                                 stage = 2;
2379                                 break;
2380                         } if (ret > 0) {
2381                                 err = -EAGAIN;
2382                         }
2383                 }
2384         }
2385         if (err)
2386                 return err;
2387
2388         rec = get_inode_rec(inode_cache, root_dirid, 0);
2389         if (rec) {
2390                 ret = check_root_dir(rec);
2391                 if (ret) {
2392                         fprintf(stderr, "root %llu root dir %llu error\n",
2393                                 (unsigned long long)root->root_key.objectid,
2394                                 (unsigned long long)root_dirid);
2395                         print_inode_error(root, rec);
2396                         error++;
2397                 }
2398         } else {
2399                 if (repair) {
2400                         struct btrfs_trans_handle *trans;
2401
2402                         trans = btrfs_start_transaction(root, 1);
2403                         if (IS_ERR(trans)) {
2404                                 err = PTR_ERR(trans);
2405                                 return err;
2406                         }
2407
2408                         fprintf(stderr,
2409                                 "root %llu missing its root dir, recreating\n",
2410                                 (unsigned long long)root->objectid);
2411
2412                         ret = btrfs_make_root_dir(trans, root, root_dirid);
2413                         BUG_ON(ret);
2414
2415                         btrfs_commit_transaction(trans, root);
2416                         return -EAGAIN;
2417                 }
2418
2419                 fprintf(stderr, "root %llu root dir %llu not found\n",
2420                         (unsigned long long)root->root_key.objectid,
2421                         (unsigned long long)root_dirid);
2422         }
2423
2424         while (1) {
2425                 cache = search_cache_extent(inode_cache, 0);
2426                 if (!cache)
2427                         break;
2428                 node = container_of(cache, struct ptr_node, cache);
2429                 rec = node->data;
2430                 remove_cache_extent(inode_cache, &node->cache);
2431                 free(node);
2432                 if (rec->ino == root_dirid ||
2433                     rec->ino == BTRFS_ORPHAN_OBJECTID) {
2434                         free_inode_rec(rec);
2435                         continue;
2436                 }
2437
2438                 if (rec->errors & I_ERR_NO_ORPHAN_ITEM) {
2439                         ret = check_orphan_item(root, rec->ino);
2440                         if (ret == 0)
2441                                 rec->errors &= ~I_ERR_NO_ORPHAN_ITEM;
2442                         if (can_free_inode_rec(rec)) {
2443                                 free_inode_rec(rec);
2444                                 continue;
2445                         }
2446                 }
2447
2448                 if (!rec->found_inode_item)
2449                         rec->errors |= I_ERR_NO_INODE_ITEM;
2450                 if (rec->found_link != rec->nlink)
2451                         rec->errors |= I_ERR_LINK_COUNT_WRONG;
2452                 if (repair) {
2453                         ret = try_repair_inode(root, rec);
2454                         if (ret == 0 && can_free_inode_rec(rec)) {
2455                                 free_inode_rec(rec);
2456                                 continue;
2457                         }
2458                         ret = 0;
2459                 }
2460
2461                 error++;
2462                 print_inode_error(root, rec);
2463                 list_for_each_entry(backref, &rec->backrefs, list) {
2464                         if (!backref->found_dir_item)
2465                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
2466                         if (!backref->found_dir_index)
2467                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
2468                         if (!backref->found_inode_ref)
2469                                 backref->errors |= REF_ERR_NO_INODE_REF;
2470                         fprintf(stderr, "\tunresolved ref dir %llu index %llu"
2471                                 " namelen %u name %s filetype %d errors %x",
2472                                 (unsigned long long)backref->dir,
2473                                 (unsigned long long)backref->index,
2474                                 backref->namelen, backref->name,
2475                                 backref->filetype, backref->errors);
2476                         print_ref_error(backref->errors);
2477                 }
2478                 free_inode_rec(rec);
2479         }
2480         return (error > 0) ? -1 : 0;
2481 }
2482
2483 static struct root_record *get_root_rec(struct cache_tree *root_cache,
2484                                         u64 objectid)
2485 {
2486         struct cache_extent *cache;
2487         struct root_record *rec = NULL;
2488         int ret;
2489
2490         cache = lookup_cache_extent(root_cache, objectid, 1);
2491         if (cache) {
2492                 rec = container_of(cache, struct root_record, cache);
2493         } else {
2494                 rec = calloc(1, sizeof(*rec));
2495                 rec->objectid = objectid;
2496                 INIT_LIST_HEAD(&rec->backrefs);
2497                 rec->cache.start = objectid;
2498                 rec->cache.size = 1;
2499
2500                 ret = insert_cache_extent(root_cache, &rec->cache);
2501                 BUG_ON(ret);
2502         }
2503         return rec;
2504 }
2505
2506 static struct root_backref *get_root_backref(struct root_record *rec,
2507                                              u64 ref_root, u64 dir, u64 index,
2508                                              const char *name, int namelen)
2509 {
2510         struct root_backref *backref;
2511
2512         list_for_each_entry(backref, &rec->backrefs, list) {
2513                 if (backref->ref_root != ref_root || backref->dir != dir ||
2514                     backref->namelen != namelen)
2515                         continue;
2516                 if (memcmp(name, backref->name, namelen))
2517                         continue;
2518                 return backref;
2519         }
2520
2521         backref = malloc(sizeof(*backref) + namelen + 1);
2522         memset(backref, 0, sizeof(*backref));
2523         backref->ref_root = ref_root;
2524         backref->dir = dir;
2525         backref->index = index;
2526         backref->namelen = namelen;
2527         memcpy(backref->name, name, namelen);
2528         backref->name[namelen] = '\0';
2529         list_add_tail(&backref->list, &rec->backrefs);
2530         return backref;
2531 }
2532
2533 static void free_root_record(struct cache_extent *cache)
2534 {
2535         struct root_record *rec;
2536         struct root_backref *backref;
2537
2538         rec = container_of(cache, struct root_record, cache);
2539         while (!list_empty(&rec->backrefs)) {
2540                 backref = list_entry(rec->backrefs.next,
2541                                      struct root_backref, list);
2542                 list_del(&backref->list);
2543                 free(backref);
2544         }
2545
2546         kfree(rec);
2547 }
2548
2549 FREE_EXTENT_CACHE_BASED_TREE(root_recs, free_root_record);
2550
2551 static int add_root_backref(struct cache_tree *root_cache,
2552                             u64 root_id, u64 ref_root, u64 dir, u64 index,
2553                             const char *name, int namelen,
2554                             int item_type, int errors)
2555 {
2556         struct root_record *rec;
2557         struct root_backref *backref;
2558
2559         rec = get_root_rec(root_cache, root_id);
2560         backref = get_root_backref(rec, ref_root, dir, index, name, namelen);
2561
2562         backref->errors |= errors;
2563
2564         if (item_type != BTRFS_DIR_ITEM_KEY) {
2565                 if (backref->found_dir_index || backref->found_back_ref ||
2566                     backref->found_forward_ref) {
2567                         if (backref->index != index)
2568                                 backref->errors |= REF_ERR_INDEX_UNMATCH;
2569                 } else {
2570                         backref->index = index;
2571                 }
2572         }
2573
2574         if (item_type == BTRFS_DIR_ITEM_KEY) {
2575                 if (backref->found_forward_ref)
2576                         rec->found_ref++;
2577                 backref->found_dir_item = 1;
2578         } else if (item_type == BTRFS_DIR_INDEX_KEY) {
2579                 backref->found_dir_index = 1;
2580         } else if (item_type == BTRFS_ROOT_REF_KEY) {
2581                 if (backref->found_forward_ref)
2582                         backref->errors |= REF_ERR_DUP_ROOT_REF;
2583                 else if (backref->found_dir_item)
2584                         rec->found_ref++;
2585                 backref->found_forward_ref = 1;
2586         } else if (item_type == BTRFS_ROOT_BACKREF_KEY) {
2587                 if (backref->found_back_ref)
2588                         backref->errors |= REF_ERR_DUP_ROOT_BACKREF;
2589                 backref->found_back_ref = 1;
2590         } else {
2591                 BUG_ON(1);
2592         }
2593
2594         if (backref->found_forward_ref && backref->found_dir_item)
2595                 backref->reachable = 1;
2596         return 0;
2597 }
2598
2599 static int merge_root_recs(struct btrfs_root *root,
2600                            struct cache_tree *src_cache,
2601                            struct cache_tree *dst_cache)
2602 {
2603         struct cache_extent *cache;
2604         struct ptr_node *node;
2605         struct inode_record *rec;
2606         struct inode_backref *backref;
2607         int ret = 0;
2608
2609         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
2610                 free_inode_recs_tree(src_cache);
2611                 return 0;
2612         }
2613
2614         while (1) {
2615                 cache = search_cache_extent(src_cache, 0);
2616                 if (!cache)
2617                         break;
2618                 node = container_of(cache, struct ptr_node, cache);
2619                 rec = node->data;
2620                 remove_cache_extent(src_cache, &node->cache);
2621                 free(node);
2622
2623                 ret = is_child_root(root, root->objectid, rec->ino);
2624                 if (ret < 0)
2625                         break;
2626                 else if (ret == 0)
2627                         goto skip;
2628
2629                 list_for_each_entry(backref, &rec->backrefs, list) {
2630                         BUG_ON(backref->found_inode_ref);
2631                         if (backref->found_dir_item)
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_ITEM_KEY,
2636                                         backref->errors);
2637                         if (backref->found_dir_index)
2638                                 add_root_backref(dst_cache, rec->ino,
2639                                         root->root_key.objectid, backref->dir,
2640                                         backref->index, backref->name,
2641                                         backref->namelen, BTRFS_DIR_INDEX_KEY,
2642                                         backref->errors);
2643                 }
2644 skip:
2645                 free_inode_rec(rec);
2646         }
2647         if (ret < 0)
2648                 return ret;
2649         return 0;
2650 }
2651
2652 static int check_root_refs(struct btrfs_root *root,
2653                            struct cache_tree *root_cache)
2654 {
2655         struct root_record *rec;
2656         struct root_record *ref_root;
2657         struct root_backref *backref;
2658         struct cache_extent *cache;
2659         int loop = 1;
2660         int ret;
2661         int error;
2662         int errors = 0;
2663
2664         rec = get_root_rec(root_cache, BTRFS_FS_TREE_OBJECTID);
2665         rec->found_ref = 1;
2666
2667         /* fixme: this can not detect circular references */
2668         while (loop) {
2669                 loop = 0;
2670                 cache = search_cache_extent(root_cache, 0);
2671                 while (1) {
2672                         if (!cache)
2673                                 break;
2674                         rec = container_of(cache, struct root_record, cache);
2675                         cache = next_cache_extent(cache);
2676
2677                         if (rec->found_ref == 0)
2678                                 continue;
2679
2680                         list_for_each_entry(backref, &rec->backrefs, list) {
2681                                 if (!backref->reachable)
2682                                         continue;
2683
2684                                 ref_root = get_root_rec(root_cache,
2685                                                         backref->ref_root);
2686                                 if (ref_root->found_ref > 0)
2687                                         continue;
2688
2689                                 backref->reachable = 0;
2690                                 rec->found_ref--;
2691                                 if (rec->found_ref == 0)
2692                                         loop = 1;
2693                         }
2694                 }
2695         }
2696
2697         cache = search_cache_extent(root_cache, 0);
2698         while (1) {
2699                 if (!cache)
2700                         break;
2701                 rec = container_of(cache, struct root_record, cache);
2702                 cache = next_cache_extent(cache);
2703
2704                 if (rec->found_ref == 0 &&
2705                     rec->objectid >= BTRFS_FIRST_FREE_OBJECTID &&
2706                     rec->objectid <= BTRFS_LAST_FREE_OBJECTID) {
2707                         ret = check_orphan_item(root->fs_info->tree_root,
2708                                                 rec->objectid);
2709                         if (ret == 0)
2710                                 continue;
2711
2712                         /*
2713                          * If we don't have a root item then we likely just have
2714                          * a dir item in a snapshot for this root but no actual
2715                          * ref key or anything so it's meaningless.
2716                          */
2717                         if (!rec->found_root_item)
2718                                 continue;
2719                         errors++;
2720                         fprintf(stderr, "fs tree %llu not referenced\n",
2721                                 (unsigned long long)rec->objectid);
2722                 }
2723
2724                 error = 0;
2725                 if (rec->found_ref > 0 && !rec->found_root_item)
2726                         error = 1;
2727                 list_for_each_entry(backref, &rec->backrefs, list) {
2728                         if (!backref->found_dir_item)
2729                                 backref->errors |= REF_ERR_NO_DIR_ITEM;
2730                         if (!backref->found_dir_index)
2731                                 backref->errors |= REF_ERR_NO_DIR_INDEX;
2732                         if (!backref->found_back_ref)
2733                                 backref->errors |= REF_ERR_NO_ROOT_BACKREF;
2734                         if (!backref->found_forward_ref)
2735                                 backref->errors |= REF_ERR_NO_ROOT_REF;
2736                         if (backref->reachable && backref->errors)
2737                                 error = 1;
2738                 }
2739                 if (!error)
2740                         continue;
2741
2742                 errors++;
2743                 fprintf(stderr, "fs tree %llu refs %u %s\n",
2744                         (unsigned long long)rec->objectid, rec->found_ref,
2745                          rec->found_root_item ? "" : "not found");
2746
2747                 list_for_each_entry(backref, &rec->backrefs, list) {
2748                         if (!backref->reachable)
2749                                 continue;
2750                         if (!backref->errors && rec->found_root_item)
2751                                 continue;
2752                         fprintf(stderr, "\tunresolved ref root %llu dir %llu"
2753                                 " index %llu namelen %u name %s errors %x\n",
2754                                 (unsigned long long)backref->ref_root,
2755                                 (unsigned long long)backref->dir,
2756                                 (unsigned long long)backref->index,
2757                                 backref->namelen, backref->name,
2758                                 backref->errors);
2759                         print_ref_error(backref->errors);
2760                 }
2761         }
2762         return errors > 0 ? 1 : 0;
2763 }
2764
2765 static int process_root_ref(struct extent_buffer *eb, int slot,
2766                             struct btrfs_key *key,
2767                             struct cache_tree *root_cache)
2768 {
2769         u64 dirid;
2770         u64 index;
2771         u32 len;
2772         u32 name_len;
2773         struct btrfs_root_ref *ref;
2774         char namebuf[BTRFS_NAME_LEN];
2775         int error;
2776
2777         ref = btrfs_item_ptr(eb, slot, struct btrfs_root_ref);
2778
2779         dirid = btrfs_root_ref_dirid(eb, ref);
2780         index = btrfs_root_ref_sequence(eb, ref);
2781         name_len = btrfs_root_ref_name_len(eb, ref);
2782
2783         if (name_len <= BTRFS_NAME_LEN) {
2784                 len = name_len;
2785                 error = 0;
2786         } else {
2787                 len = BTRFS_NAME_LEN;
2788                 error = REF_ERR_NAME_TOO_LONG;
2789         }
2790         read_extent_buffer(eb, namebuf, (unsigned long)(ref + 1), len);
2791
2792         if (key->type == BTRFS_ROOT_REF_KEY) {
2793                 add_root_backref(root_cache, key->offset, key->objectid, dirid,
2794                                  index, namebuf, len, key->type, error);
2795         } else {
2796                 add_root_backref(root_cache, key->objectid, key->offset, dirid,
2797                                  index, namebuf, len, key->type, error);
2798         }
2799         return 0;
2800 }
2801
2802 static void free_corrupt_block(struct cache_extent *cache)
2803 {
2804         struct btrfs_corrupt_block *corrupt;
2805
2806         corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
2807         free(corrupt);
2808 }
2809
2810 FREE_EXTENT_CACHE_BASED_TREE(corrupt_blocks, free_corrupt_block);
2811
2812 /*
2813  * Repair the btree of the given root.
2814  *
2815  * The fix is to remove the node key in corrupt_blocks cache_tree.
2816  * and rebalance the tree.
2817  * After the fix, the btree should be writeable.
2818  */
2819 static int repair_btree(struct btrfs_root *root,
2820                         struct cache_tree *corrupt_blocks)
2821 {
2822         struct btrfs_trans_handle *trans;
2823         struct btrfs_path *path;
2824         struct btrfs_corrupt_block *corrupt;
2825         struct cache_extent *cache;
2826         struct btrfs_key key;
2827         u64 offset;
2828         int level;
2829         int ret = 0;
2830
2831         if (cache_tree_empty(corrupt_blocks))
2832                 return 0;
2833
2834         path = btrfs_alloc_path();
2835         if (!path)
2836                 return -ENOMEM;
2837
2838         trans = btrfs_start_transaction(root, 1);
2839         if (IS_ERR(trans)) {
2840                 ret = PTR_ERR(trans);
2841                 fprintf(stderr, "Error starting transaction: %s\n",
2842                         strerror(-ret));
2843                 goto out_free_path;
2844         }
2845         cache = first_cache_extent(corrupt_blocks);
2846         while (cache) {
2847                 corrupt = container_of(cache, struct btrfs_corrupt_block,
2848                                        cache);
2849                 level = corrupt->level;
2850                 path->lowest_level = level;
2851                 key.objectid = corrupt->key.objectid;
2852                 key.type = corrupt->key.type;
2853                 key.offset = corrupt->key.offset;
2854
2855                 /*
2856                  * Here we don't want to do any tree balance, since it may
2857                  * cause a balance with corrupted brother leaf/node,
2858                  * so ins_len set to 0 here.
2859                  * Balance will be done after all corrupt node/leaf is deleted.
2860                  */
2861                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2862                 if (ret < 0)
2863                         goto out;
2864                 offset = btrfs_node_blockptr(path->nodes[level],
2865                                              path->slots[level]);
2866
2867                 /* Remove the ptr */
2868                 ret = btrfs_del_ptr(trans, root, path, level,
2869                                     path->slots[level]);
2870                 if (ret < 0)
2871                         goto out;
2872                 /*
2873                  * Remove the corresponding extent
2874                  * return value is not concerned.
2875                  */
2876                 btrfs_release_path(path);
2877                 ret = btrfs_free_extent(trans, root, offset, root->nodesize,
2878                                         0, root->root_key.objectid,
2879                                         level - 1, 0);
2880                 cache = next_cache_extent(cache);
2881         }
2882
2883         /* Balance the btree using btrfs_search_slot() */
2884         cache = first_cache_extent(corrupt_blocks);
2885         while (cache) {
2886                 corrupt = container_of(cache, struct btrfs_corrupt_block,
2887                                        cache);
2888                 memcpy(&key, &corrupt->key, sizeof(key));
2889                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2890                 if (ret < 0)
2891                         goto out;
2892                 /* return will always >0 since it won't find the item */
2893                 ret = 0;
2894                 btrfs_release_path(path);
2895                 cache = next_cache_extent(cache);
2896         }
2897 out:
2898         btrfs_commit_transaction(trans, root);
2899 out_free_path:
2900         btrfs_free_path(path);
2901         return ret;
2902 }
2903
2904 static int check_fs_root(struct btrfs_root *root,
2905                          struct cache_tree *root_cache,
2906                          struct walk_control *wc)
2907 {
2908         int ret = 0;
2909         int err = 0;
2910         int wret;
2911         int level;
2912         struct btrfs_path path;
2913         struct shared_node root_node;
2914         struct root_record *rec;
2915         struct btrfs_root_item *root_item = &root->root_item;
2916         struct cache_tree corrupt_blocks;
2917         enum btrfs_tree_block_status status;
2918
2919         /*
2920          * Reuse the corrupt_block cache tree to record corrupted tree block
2921          *
2922          * Unlike the usage in extent tree check, here we do it in a per
2923          * fs/subvol tree base.
2924          */
2925         cache_tree_init(&corrupt_blocks);
2926         root->fs_info->corrupt_blocks = &corrupt_blocks;
2927         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
2928                 rec = get_root_rec(root_cache, root->root_key.objectid);
2929                 if (btrfs_root_refs(root_item) > 0)
2930                         rec->found_root_item = 1;
2931         }
2932
2933         btrfs_init_path(&path);
2934         memset(&root_node, 0, sizeof(root_node));
2935         cache_tree_init(&root_node.root_cache);
2936         cache_tree_init(&root_node.inode_cache);
2937
2938         level = btrfs_header_level(root->node);
2939         memset(wc->nodes, 0, sizeof(wc->nodes));
2940         wc->nodes[level] = &root_node;
2941         wc->active_node = level;
2942         wc->root_level = level;
2943
2944         /* We may not have checked the root block, lets do that now */
2945         if (btrfs_is_leaf(root->node))
2946                 status = btrfs_check_leaf(root, NULL, root->node);
2947         else
2948                 status = btrfs_check_node(root, NULL, root->node);
2949         if (status != BTRFS_TREE_BLOCK_CLEAN)
2950                 return -EIO;
2951
2952         if (btrfs_root_refs(root_item) > 0 ||
2953             btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2954                 path.nodes[level] = root->node;
2955                 extent_buffer_get(root->node);
2956                 path.slots[level] = 0;
2957         } else {
2958                 struct btrfs_key key;
2959                 struct btrfs_disk_key found_key;
2960
2961                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2962                 level = root_item->drop_level;
2963                 path.lowest_level = level;
2964                 wret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
2965                 if (wret < 0)
2966                         goto skip_walking;
2967                 btrfs_node_key(path.nodes[level], &found_key,
2968                                 path.slots[level]);
2969                 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
2970                                         sizeof(found_key)));
2971         }
2972
2973         while (1) {
2974                 wret = walk_down_tree(root, &path, wc, &level);
2975                 if (wret < 0)
2976                         ret = wret;
2977                 if (wret != 0)
2978                         break;
2979
2980                 wret = walk_up_tree(root, &path, wc, &level);
2981                 if (wret < 0)
2982                         ret = wret;
2983                 if (wret != 0)
2984                         break;
2985         }
2986 skip_walking:
2987         btrfs_release_path(&path);
2988
2989         if (!cache_tree_empty(&corrupt_blocks)) {
2990                 struct cache_extent *cache;
2991                 struct btrfs_corrupt_block *corrupt;
2992
2993                 printf("The following tree block(s) is corrupted in tree %llu:\n",
2994                        root->root_key.objectid);
2995                 cache = first_cache_extent(&corrupt_blocks);
2996                 while (cache) {
2997                         corrupt = container_of(cache,
2998                                                struct btrfs_corrupt_block,
2999                                                cache);
3000                         printf("\ttree block bytenr: %llu, level: %d, node key: (%llu, %u, %llu)\n",
3001                                cache->start, corrupt->level,
3002                                corrupt->key.objectid, corrupt->key.type,
3003                                corrupt->key.offset);
3004                         cache = next_cache_extent(cache);
3005                 }
3006                 if (repair) {
3007                         printf("Try to repair the btree for root %llu\n",
3008                                root->root_key.objectid);
3009                         ret = repair_btree(root, &corrupt_blocks);
3010                         if (ret < 0)
3011                                 fprintf(stderr, "Failed to repair btree: %s\n",
3012                                         strerror(-ret));
3013                         if (!ret)
3014                                 printf("Btree for root %llu is fixed\n",
3015                                        root->root_key.objectid);
3016                 }
3017         }
3018
3019         err = merge_root_recs(root, &root_node.root_cache, root_cache);
3020         if (err < 0)
3021                 ret = err;
3022
3023         if (root_node.current) {
3024                 root_node.current->checked = 1;
3025                 maybe_free_inode_rec(&root_node.inode_cache,
3026                                 root_node.current);
3027         }
3028
3029         err = check_inode_recs(root, &root_node.inode_cache);
3030         if (!ret)
3031                 ret = err;
3032
3033         free_corrupt_blocks_tree(&corrupt_blocks);
3034         root->fs_info->corrupt_blocks = NULL;
3035         return ret;
3036 }
3037
3038 static int fs_root_objectid(u64 objectid)
3039 {
3040         if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
3041             objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3042                 return 1;
3043         return is_fstree(objectid);
3044 }
3045
3046 static int check_fs_roots(struct btrfs_root *root,
3047                           struct cache_tree *root_cache)
3048 {
3049         struct btrfs_path path;
3050         struct btrfs_key key;
3051         struct walk_control wc;
3052         struct extent_buffer *leaf, *tree_node;
3053         struct btrfs_root *tmp_root;
3054         struct btrfs_root *tree_root = root->fs_info->tree_root;
3055         int ret;
3056         int err = 0;
3057
3058         /*
3059          * Just in case we made any changes to the extent tree that weren't
3060          * reflected into the free space cache yet.
3061          */
3062         if (repair)
3063                 reset_cached_block_groups(root->fs_info);
3064         memset(&wc, 0, sizeof(wc));
3065         cache_tree_init(&wc.shared);
3066         btrfs_init_path(&path);
3067
3068 again:
3069         key.offset = 0;
3070         key.objectid = 0;
3071         key.type = BTRFS_ROOT_ITEM_KEY;
3072         ret = btrfs_search_slot(NULL, tree_root, &key, &path, 0, 0);
3073         if (ret < 0) {
3074                 err = 1;
3075                 goto out;
3076         }
3077         tree_node = tree_root->node;
3078         while (1) {
3079                 if (tree_node != tree_root->node) {
3080                         free_root_recs_tree(root_cache);
3081                         btrfs_release_path(&path);
3082                         goto again;
3083                 }
3084                 leaf = path.nodes[0];
3085                 if (path.slots[0] >= btrfs_header_nritems(leaf)) {
3086                         ret = btrfs_next_leaf(tree_root, &path);
3087                         if (ret) {
3088                                 if (ret < 0)
3089                                         err = 1;
3090                                 break;
3091                         }
3092                         leaf = path.nodes[0];
3093                 }
3094                 btrfs_item_key_to_cpu(leaf, &key, path.slots[0]);
3095                 if (key.type == BTRFS_ROOT_ITEM_KEY &&
3096                     fs_root_objectid(key.objectid)) {
3097                         if (key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
3098                                 tmp_root = btrfs_read_fs_root_no_cache(
3099                                                 root->fs_info, &key);
3100                         } else {
3101                                 key.offset = (u64)-1;
3102                                 tmp_root = btrfs_read_fs_root(
3103                                                 root->fs_info, &key);
3104                         }
3105                         if (IS_ERR(tmp_root)) {
3106                                 err = 1;
3107                                 goto next;
3108                         }
3109                         ret = check_fs_root(tmp_root, root_cache, &wc);
3110                         if (ret == -EAGAIN) {
3111                                 free_root_recs_tree(root_cache);
3112                                 btrfs_release_path(&path);
3113                                 goto again;
3114                         }
3115                         if (ret)
3116                                 err = 1;
3117                         if (key.objectid == BTRFS_TREE_RELOC_OBJECTID)
3118                                 btrfs_free_fs_root(tmp_root);
3119                 } else if (key.type == BTRFS_ROOT_REF_KEY ||
3120                            key.type == BTRFS_ROOT_BACKREF_KEY) {
3121                         process_root_ref(leaf, path.slots[0], &key,
3122                                          root_cache);
3123                 }
3124 next:
3125                 path.slots[0]++;
3126         }
3127 out:
3128         btrfs_release_path(&path);
3129         if (err)
3130                 free_extent_cache_tree(&wc.shared);
3131         if (!cache_tree_empty(&wc.shared))
3132                 fprintf(stderr, "warning line %d\n", __LINE__);
3133
3134         return err;
3135 }
3136
3137 static int all_backpointers_checked(struct extent_record *rec, int print_errs)
3138 {
3139         struct list_head *cur = rec->backrefs.next;
3140         struct extent_backref *back;
3141         struct tree_backref *tback;
3142         struct data_backref *dback;
3143         u64 found = 0;
3144         int err = 0;
3145
3146         while(cur != &rec->backrefs) {
3147                 back = list_entry(cur, struct extent_backref, list);
3148                 cur = cur->next;
3149                 if (!back->found_extent_tree) {
3150                         err = 1;
3151                         if (!print_errs)
3152                                 goto out;
3153                         if (back->is_data) {
3154                                 dback = (struct data_backref *)back;
3155                                 fprintf(stderr, "Backref %llu %s %llu"
3156                                         " owner %llu offset %llu num_refs %lu"
3157                                         " not found in extent tree\n",
3158                                         (unsigned long long)rec->start,
3159                                         back->full_backref ?
3160                                         "parent" : "root",
3161                                         back->full_backref ?
3162                                         (unsigned long long)dback->parent:
3163                                         (unsigned long long)dback->root,
3164                                         (unsigned long long)dback->owner,
3165                                         (unsigned long long)dback->offset,
3166                                         (unsigned long)dback->num_refs);
3167                         } else {
3168                                 tback = (struct tree_backref *)back;
3169                                 fprintf(stderr, "Backref %llu parent %llu"
3170                                         " root %llu not found in extent tree\n",
3171                                         (unsigned long long)rec->start,
3172                                         (unsigned long long)tback->parent,
3173                                         (unsigned long long)tback->root);
3174                         }
3175                 }
3176                 if (!back->is_data && !back->found_ref) {
3177                         err = 1;
3178                         if (!print_errs)
3179                                 goto out;
3180                         tback = (struct tree_backref *)back;
3181                         fprintf(stderr, "Backref %llu %s %llu not referenced back %p\n",
3182                                 (unsigned long long)rec->start,
3183                                 back->full_backref ? "parent" : "root",
3184                                 back->full_backref ?
3185                                 (unsigned long long)tback->parent :
3186                                 (unsigned long long)tback->root, back);
3187                 }
3188                 if (back->is_data) {
3189                         dback = (struct data_backref *)back;
3190                         if (dback->found_ref != dback->num_refs) {
3191                                 err = 1;
3192                                 if (!print_errs)
3193                                         goto out;
3194                                 fprintf(stderr, "Incorrect local backref count"
3195                                         " on %llu %s %llu owner %llu"
3196                                         " offset %llu found %u wanted %u back %p\n",
3197                                         (unsigned long long)rec->start,
3198                                         back->full_backref ?
3199                                         "parent" : "root",
3200                                         back->full_backref ?
3201                                         (unsigned long long)dback->parent:
3202                                         (unsigned long long)dback->root,
3203                                         (unsigned long long)dback->owner,
3204                                         (unsigned long long)dback->offset,
3205                                         dback->found_ref, dback->num_refs, back);
3206                         }
3207                         if (dback->disk_bytenr != rec->start) {
3208                                 err = 1;
3209                                 if (!print_errs)
3210                                         goto out;
3211                                 fprintf(stderr, "Backref disk bytenr does not"
3212                                         " match extent record, bytenr=%llu, "
3213                                         "ref bytenr=%llu\n",
3214                                         (unsigned long long)rec->start,
3215                                         (unsigned long long)dback->disk_bytenr);
3216                         }
3217
3218                         if (dback->bytes != rec->nr) {
3219                                 err = 1;
3220                                 if (!print_errs)
3221                                         goto out;
3222                                 fprintf(stderr, "Backref bytes do not match "
3223                                         "extent backref, bytenr=%llu, ref "
3224                                         "bytes=%llu, backref bytes=%llu\n",
3225                                         (unsigned long long)rec->start,
3226                                         (unsigned long long)rec->nr,
3227                                         (unsigned long long)dback->bytes);
3228                         }
3229                 }
3230                 if (!back->is_data) {
3231                         found += 1;
3232                 } else {
3233                         dback = (struct data_backref *)back;
3234                         found += dback->found_ref;
3235                 }
3236         }
3237         if (found != rec->refs) {
3238                 err = 1;
3239                 if (!print_errs)
3240                         goto out;
3241                 fprintf(stderr, "Incorrect global backref count "
3242                         "on %llu found %llu wanted %llu\n",
3243                         (unsigned long long)rec->start,
3244                         (unsigned long long)found,
3245                         (unsigned long long)rec->refs);
3246         }
3247 out:
3248         return err;
3249 }
3250
3251 static int free_all_extent_backrefs(struct extent_record *rec)
3252 {
3253         struct extent_backref *back;
3254         struct list_head *cur;
3255         while (!list_empty(&rec->backrefs)) {
3256                 cur = rec->backrefs.next;
3257                 back = list_entry(cur, struct extent_backref, list);
3258                 list_del(cur);
3259                 free(back);
3260         }
3261         return 0;
3262 }
3263
3264 static void free_extent_record_cache(struct btrfs_fs_info *fs_info,
3265                                      struct cache_tree *extent_cache)
3266 {
3267         struct cache_extent *cache;
3268         struct extent_record *rec;
3269
3270         while (1) {
3271                 cache = first_cache_extent(extent_cache);
3272                 if (!cache)
3273                         break;
3274                 rec = container_of(cache, struct extent_record, cache);
3275                 btrfs_unpin_extent(fs_info, rec->start, rec->max_size);
3276                 remove_cache_extent(extent_cache, cache);
3277                 free_all_extent_backrefs(rec);
3278                 free(rec);
3279         }
3280 }
3281
3282 static int maybe_free_extent_rec(struct cache_tree *extent_cache,
3283                                  struct extent_record *rec)
3284 {
3285         if (rec->content_checked && rec->owner_ref_checked &&
3286             rec->extent_item_refs == rec->refs && rec->refs > 0 &&
3287             rec->num_duplicates == 0 && !all_backpointers_checked(rec, 0)) {
3288                 remove_cache_extent(extent_cache, &rec->cache);
3289                 free_all_extent_backrefs(rec);
3290                 list_del_init(&rec->list);
3291                 free(rec);
3292         }
3293         return 0;
3294 }
3295
3296 static int check_owner_ref(struct btrfs_root *root,
3297                             struct extent_record *rec,
3298                             struct extent_buffer *buf)
3299 {
3300         struct extent_backref *node;
3301         struct tree_backref *back;
3302         struct btrfs_root *ref_root;
3303         struct btrfs_key key;
3304         struct btrfs_path path;
3305         struct extent_buffer *parent;
3306         int level;
3307         int found = 0;
3308         int ret;
3309
3310         list_for_each_entry(node, &rec->backrefs, list) {
3311                 if (node->is_data)
3312                         continue;
3313                 if (!node->found_ref)
3314                         continue;
3315                 if (node->full_backref)
3316                         continue;
3317                 back = (struct tree_backref *)node;
3318                 if (btrfs_header_owner(buf) == back->root)
3319                         return 0;
3320         }
3321         BUG_ON(rec->is_root);
3322
3323         /* try to find the block by search corresponding fs tree */
3324         key.objectid = btrfs_header_owner(buf);
3325         key.type = BTRFS_ROOT_ITEM_KEY;
3326         key.offset = (u64)-1;
3327
3328         ref_root = btrfs_read_fs_root(root->fs_info, &key);
3329         if (IS_ERR(ref_root))
3330                 return 1;
3331
3332         level = btrfs_header_level(buf);
3333         if (level == 0)
3334                 btrfs_item_key_to_cpu(buf, &key, 0);
3335         else
3336                 btrfs_node_key_to_cpu(buf, &key, 0);
3337
3338         btrfs_init_path(&path);
3339         path.lowest_level = level + 1;
3340         ret = btrfs_search_slot(NULL, ref_root, &key, &path, 0, 0);
3341         if (ret < 0)
3342                 return 0;
3343
3344         parent = path.nodes[level + 1];
3345         if (parent && buf->start == btrfs_node_blockptr(parent,
3346                                                         path.slots[level + 1]))
3347                 found = 1;
3348
3349         btrfs_release_path(&path);
3350         return found ? 0 : 1;
3351 }
3352
3353 static int is_extent_tree_record(struct extent_record *rec)
3354 {
3355         struct list_head *cur = rec->backrefs.next;
3356         struct extent_backref *node;
3357         struct tree_backref *back;
3358         int is_extent = 0;
3359
3360         while(cur != &rec->backrefs) {
3361                 node = list_entry(cur, struct extent_backref, list);
3362                 cur = cur->next;
3363                 if (node->is_data)
3364                         return 0;
3365                 back = (struct tree_backref *)node;
3366                 if (node->full_backref)
3367                         return 0;
3368                 if (back->root == BTRFS_EXTENT_TREE_OBJECTID)
3369                         is_extent = 1;
3370         }
3371         return is_extent;
3372 }
3373
3374
3375 static int record_bad_block_io(struct btrfs_fs_info *info,
3376                                struct cache_tree *extent_cache,
3377                                u64 start, u64 len)
3378 {
3379         struct extent_record *rec;
3380         struct cache_extent *cache;
3381         struct btrfs_key key;
3382
3383         cache = lookup_cache_extent(extent_cache, start, len);
3384         if (!cache)
3385                 return 0;
3386
3387         rec = container_of(cache, struct extent_record, cache);
3388         if (!is_extent_tree_record(rec))
3389                 return 0;
3390
3391         btrfs_disk_key_to_cpu(&key, &rec->parent_key);
3392         return btrfs_add_corrupt_extent_record(info, &key, start, len, 0);
3393 }
3394
3395 static int swap_values(struct btrfs_root *root, struct btrfs_path *path,
3396                        struct extent_buffer *buf, int slot)
3397 {
3398         if (btrfs_header_level(buf)) {
3399                 struct btrfs_key_ptr ptr1, ptr2;
3400
3401                 read_extent_buffer(buf, &ptr1, btrfs_node_key_ptr_offset(slot),
3402                                    sizeof(struct btrfs_key_ptr));
3403                 read_extent_buffer(buf, &ptr2,
3404                                    btrfs_node_key_ptr_offset(slot + 1),
3405                                    sizeof(struct btrfs_key_ptr));
3406                 write_extent_buffer(buf, &ptr1,
3407                                     btrfs_node_key_ptr_offset(slot + 1),
3408                                     sizeof(struct btrfs_key_ptr));
3409                 write_extent_buffer(buf, &ptr2,
3410                                     btrfs_node_key_ptr_offset(slot),
3411                                     sizeof(struct btrfs_key_ptr));
3412                 if (slot == 0) {
3413                         struct btrfs_disk_key key;
3414                         btrfs_node_key(buf, &key, 0);
3415                         btrfs_fixup_low_keys(root, path, &key,
3416                                              btrfs_header_level(buf) + 1);
3417                 }
3418         } else {
3419                 struct btrfs_item *item1, *item2;
3420                 struct btrfs_key k1, k2;
3421                 char *item1_data, *item2_data;
3422                 u32 item1_offset, item2_offset, item1_size, item2_size;
3423
3424                 item1 = btrfs_item_nr(slot);
3425                 item2 = btrfs_item_nr(slot + 1);
3426                 btrfs_item_key_to_cpu(buf, &k1, slot);
3427                 btrfs_item_key_to_cpu(buf, &k2, slot + 1);
3428                 item1_offset = btrfs_item_offset(buf, item1);
3429                 item2_offset = btrfs_item_offset(buf, item2);
3430                 item1_size = btrfs_item_size(buf, item1);
3431                 item2_size = btrfs_item_size(buf, item2);
3432
3433                 item1_data = malloc(item1_size);
3434                 if (!item1_data)
3435                         return -ENOMEM;
3436                 item2_data = malloc(item2_size);
3437                 if (!item2_data) {
3438                         free(item1_data);
3439                         return -ENOMEM;
3440                 }
3441
3442                 read_extent_buffer(buf, item1_data, item1_offset, item1_size);
3443                 read_extent_buffer(buf, item2_data, item2_offset, item2_size);
3444
3445                 write_extent_buffer(buf, item1_data, item2_offset, item2_size);
3446                 write_extent_buffer(buf, item2_data, item1_offset, item1_size);
3447                 free(item1_data);
3448                 free(item2_data);
3449
3450                 btrfs_set_item_offset(buf, item1, item2_offset);
3451                 btrfs_set_item_offset(buf, item2, item1_offset);
3452                 btrfs_set_item_size(buf, item1, item2_size);
3453                 btrfs_set_item_size(buf, item2, item1_size);
3454
3455                 path->slots[0] = slot;
3456                 btrfs_set_item_key_unsafe(root, path, &k2);
3457                 path->slots[0] = slot + 1;
3458                 btrfs_set_item_key_unsafe(root, path, &k1);
3459         }
3460         return 0;
3461 }
3462
3463 static int fix_key_order(struct btrfs_trans_handle *trans,
3464                          struct btrfs_root *root,
3465                          struct btrfs_path *path)
3466 {
3467         struct extent_buffer *buf;
3468         struct btrfs_key k1, k2;
3469         int i;
3470         int level = path->lowest_level;
3471         int ret = -EIO;
3472
3473         buf = path->nodes[level];
3474         for (i = 0; i < btrfs_header_nritems(buf) - 1; i++) {
3475                 if (level) {
3476                         btrfs_node_key_to_cpu(buf, &k1, i);
3477                         btrfs_node_key_to_cpu(buf, &k2, i + 1);
3478                 } else {
3479                         btrfs_item_key_to_cpu(buf, &k1, i);
3480                         btrfs_item_key_to_cpu(buf, &k2, i + 1);
3481                 }
3482                 if (btrfs_comp_cpu_keys(&k1, &k2) < 0)
3483                         continue;
3484                 ret = swap_values(root, path, buf, i);
3485                 if (ret)
3486                         break;
3487                 btrfs_mark_buffer_dirty(buf);
3488                 i = 0;
3489         }
3490         return ret;
3491 }
3492
3493 static int delete_bogus_item(struct btrfs_trans_handle *trans,
3494                              struct btrfs_root *root,
3495                              struct btrfs_path *path,
3496                              struct extent_buffer *buf, int slot)
3497 {
3498         struct btrfs_key key;
3499         int nritems = btrfs_header_nritems(buf);
3500
3501         btrfs_item_key_to_cpu(buf, &key, slot);
3502
3503         /* These are all the keys we can deal with missing. */
3504         if (key.type != BTRFS_DIR_INDEX_KEY &&
3505             key.type != BTRFS_EXTENT_ITEM_KEY &&
3506             key.type != BTRFS_METADATA_ITEM_KEY &&
3507             key.type != BTRFS_TREE_BLOCK_REF_KEY &&
3508             key.type != BTRFS_EXTENT_DATA_REF_KEY)
3509                 return -1;
3510
3511         printf("Deleting bogus item [%llu,%u,%llu] at slot %d on block %llu\n",
3512                (unsigned long long)key.objectid, key.type,
3513                (unsigned long long)key.offset, slot, buf->start);
3514         memmove_extent_buffer(buf, btrfs_item_nr_offset(slot),
3515                               btrfs_item_nr_offset(slot + 1),
3516                               sizeof(struct btrfs_item) *
3517                               (nritems - slot - 1));
3518         btrfs_set_header_nritems(buf, nritems - 1);
3519         if (slot == 0) {
3520                 struct btrfs_disk_key disk_key;
3521
3522                 btrfs_item_key(buf, &disk_key, 0);
3523                 btrfs_fixup_low_keys(root, path, &disk_key, 1);
3524         }
3525         btrfs_mark_buffer_dirty(buf);
3526         return 0;
3527 }
3528
3529 static int fix_item_offset(struct btrfs_trans_handle *trans,
3530                            struct btrfs_root *root,
3531                            struct btrfs_path *path)
3532 {
3533         struct extent_buffer *buf;
3534         int i;
3535         int ret = 0;
3536
3537         /* We should only get this for leaves */
3538         BUG_ON(path->lowest_level);
3539         buf = path->nodes[0];
3540 again:
3541         for (i = 0; i < btrfs_header_nritems(buf); i++) {
3542                 unsigned int shift = 0, offset;
3543
3544                 if (i == 0 && btrfs_item_end_nr(buf, i) !=
3545                     BTRFS_LEAF_DATA_SIZE(root)) {
3546                         if (btrfs_item_end_nr(buf, i) >
3547                             BTRFS_LEAF_DATA_SIZE(root)) {
3548                                 ret = delete_bogus_item(trans, root, path,
3549                                                         buf, i);
3550                                 if (!ret)
3551                                         goto again;
3552                                 fprintf(stderr, "item is off the end of the "
3553                                         "leaf, can't fix\n");
3554                                 ret = -EIO;
3555                                 break;
3556                         }
3557                         shift = BTRFS_LEAF_DATA_SIZE(root) -
3558                                 btrfs_item_end_nr(buf, i);
3559                 } else if (i > 0 && btrfs_item_end_nr(buf, i) !=
3560                            btrfs_item_offset_nr(buf, i - 1)) {
3561                         if (btrfs_item_end_nr(buf, i) >
3562                             btrfs_item_offset_nr(buf, i - 1)) {
3563                                 ret = delete_bogus_item(trans, root, path,
3564                                                         buf, i);
3565                                 if (!ret)
3566                                         goto again;
3567                                 fprintf(stderr, "items overlap, can't fix\n");
3568                                 ret = -EIO;
3569                                 break;
3570                         }
3571                         shift = btrfs_item_offset_nr(buf, i - 1) -
3572                                 btrfs_item_end_nr(buf, i);
3573                 }
3574                 if (!shift)
3575                         continue;
3576
3577                 printf("Shifting item nr %d by %u bytes in block %llu\n",
3578                        i, shift, (unsigned long long)buf->start);
3579                 offset = btrfs_item_offset_nr(buf, i);
3580                 memmove_extent_buffer(buf,
3581                                       btrfs_leaf_data(buf) + offset + shift,
3582                                       btrfs_leaf_data(buf) + offset,
3583                                       btrfs_item_size_nr(buf, i));
3584                 btrfs_set_item_offset(buf, btrfs_item_nr(i),
3585                                       offset + shift);
3586                 btrfs_mark_buffer_dirty(buf);
3587         }
3588
3589         /*
3590          * We may have moved things, in which case we want to exit so we don't
3591          * write those changes out.  Once we have proper abort functionality in
3592          * progs this can be changed to something nicer.
3593          */
3594         BUG_ON(ret);
3595         return ret;
3596 }
3597
3598 /*
3599  * Attempt to fix basic block failures.  If we can't fix it for whatever reason
3600  * then just return -EIO.
3601  */
3602 static int try_to_fix_bad_block(struct btrfs_trans_handle *trans,
3603                                 struct btrfs_root *root,
3604                                 struct extent_buffer *buf,
3605                                 enum btrfs_tree_block_status status)
3606 {
3607         struct ulist *roots;
3608         struct ulist_node *node;
3609         struct btrfs_root *search_root;
3610         struct btrfs_path *path;
3611         struct ulist_iterator iter;
3612         struct btrfs_key root_key, key;
3613         int ret;
3614
3615         if (status != BTRFS_TREE_BLOCK_BAD_KEY_ORDER &&
3616             status != BTRFS_TREE_BLOCK_INVALID_OFFSETS)
3617                 return -EIO;
3618
3619         path = btrfs_alloc_path();
3620         if (!path)
3621                 return -EIO;
3622
3623         ret = btrfs_find_all_roots(trans, root->fs_info, buf->start,
3624                                    0, &roots);
3625         if (ret) {
3626                 btrfs_free_path(path);
3627                 return -EIO;
3628         }
3629
3630         ULIST_ITER_INIT(&iter);
3631         while ((node = ulist_next(roots, &iter))) {
3632                 root_key.objectid = node->val;
3633                 root_key.type = BTRFS_ROOT_ITEM_KEY;
3634                 root_key.offset = (u64)-1;
3635
3636                 search_root = btrfs_read_fs_root(root->fs_info, &root_key);
3637                 if (IS_ERR(root)) {
3638                         ret = -EIO;
3639                         break;
3640                 }
3641
3642                 record_root_in_trans(trans, search_root);
3643
3644                 path->lowest_level = btrfs_header_level(buf);
3645                 path->skip_check_block = 1;
3646                 if (path->lowest_level)
3647                         btrfs_node_key_to_cpu(buf, &key, 0);
3648                 else
3649                         btrfs_item_key_to_cpu(buf, &key, 0);
3650                 ret = btrfs_search_slot(trans, search_root, &key, path, 0, 1);
3651                 if (ret) {
3652                         ret = -EIO;
3653                         break;
3654                 }
3655                 if (status == BTRFS_TREE_BLOCK_BAD_KEY_ORDER)
3656                         ret = fix_key_order(trans, search_root, path);
3657                 else if (status == BTRFS_TREE_BLOCK_INVALID_OFFSETS)
3658                         ret = fix_item_offset(trans, search_root, path);
3659                 if (ret)
3660                         break;
3661                 btrfs_release_path(path);
3662         }
3663         ulist_free(roots);
3664         btrfs_free_path(path);
3665         return ret;
3666 }
3667
3668 static int check_block(struct btrfs_trans_handle *trans,
3669                        struct btrfs_root *root,
3670                        struct cache_tree *extent_cache,
3671                        struct extent_buffer *buf, u64 flags)
3672 {
3673         struct extent_record *rec;
3674         struct cache_extent *cache;
3675         struct btrfs_key key;
3676         enum btrfs_tree_block_status status;
3677         int ret = 0;
3678         int level;
3679
3680         cache = lookup_cache_extent(extent_cache, buf->start, buf->len);
3681         if (!cache)
3682                 return 1;
3683         rec = container_of(cache, struct extent_record, cache);
3684         rec->generation = btrfs_header_generation(buf);
3685
3686         level = btrfs_header_level(buf);
3687         if (btrfs_header_nritems(buf) > 0) {
3688
3689                 if (level == 0)
3690                         btrfs_item_key_to_cpu(buf, &key, 0);
3691                 else
3692                         btrfs_node_key_to_cpu(buf, &key, 0);
3693
3694                 rec->info_objectid = key.objectid;
3695         }
3696         rec->info_level = level;
3697
3698         if (btrfs_is_leaf(buf))
3699                 status = btrfs_check_leaf(root, &rec->parent_key, buf);
3700         else
3701                 status = btrfs_check_node(root, &rec->parent_key, buf);
3702
3703         if (status != BTRFS_TREE_BLOCK_CLEAN) {
3704                 if (repair)
3705                         status = try_to_fix_bad_block(trans, root, buf,
3706                                                       status);
3707                 if (status != BTRFS_TREE_BLOCK_CLEAN) {
3708                         ret = -EIO;
3709                         fprintf(stderr, "bad block %llu\n",
3710                                 (unsigned long long)buf->start);
3711                 } else {
3712                         /*
3713                          * Signal to callers we need to start the scan over
3714                          * again since we'll have cow'ed blocks.
3715                          */
3716                         ret = -EAGAIN;
3717                 }
3718         } else {
3719                 rec->content_checked = 1;
3720                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
3721                         rec->owner_ref_checked = 1;
3722                 else {
3723                         ret = check_owner_ref(root, rec, buf);
3724                         if (!ret)
3725                                 rec->owner_ref_checked = 1;
3726                 }
3727         }
3728         if (!ret)
3729                 maybe_free_extent_rec(extent_cache, rec);
3730         return ret;
3731 }
3732
3733 static struct tree_backref *find_tree_backref(struct extent_record *rec,
3734                                                 u64 parent, u64 root)
3735 {
3736         struct list_head *cur = rec->backrefs.next;
3737         struct extent_backref *node;
3738         struct tree_backref *back;
3739
3740         while(cur != &rec->backrefs) {
3741                 node = list_entry(cur, struct extent_backref, list);
3742                 cur = cur->next;
3743                 if (node->is_data)
3744                         continue;
3745                 back = (struct tree_backref *)node;
3746                 if (parent > 0) {
3747                         if (!node->full_backref)
3748                                 continue;
3749                         if (parent == back->parent)
3750                                 return back;
3751                 } else {
3752                         if (node->full_backref)
3753                                 continue;
3754                         if (back->root == root)
3755                                 return back;
3756                 }
3757         }
3758         return NULL;
3759 }
3760
3761 static struct tree_backref *alloc_tree_backref(struct extent_record *rec,
3762                                                 u64 parent, u64 root)
3763 {
3764         struct tree_backref *ref = malloc(sizeof(*ref));
3765         memset(&ref->node, 0, sizeof(ref->node));
3766         if (parent > 0) {
3767                 ref->parent = parent;
3768                 ref->node.full_backref = 1;
3769         } else {
3770                 ref->root = root;
3771                 ref->node.full_backref = 0;
3772         }
3773         list_add_tail(&ref->node.list, &rec->backrefs);
3774
3775         return ref;
3776 }
3777
3778 static struct data_backref *find_data_backref(struct extent_record *rec,
3779                                                 u64 parent, u64 root,
3780                                                 u64 owner, u64 offset,
3781                                                 int found_ref,
3782                                                 u64 disk_bytenr, u64 bytes)
3783 {
3784         struct list_head *cur = rec->backrefs.next;
3785         struct extent_backref *node;
3786         struct data_backref *back;
3787
3788         while(cur != &rec->backrefs) {
3789                 node = list_entry(cur, struct extent_backref, list);
3790                 cur = cur->next;
3791                 if (!node->is_data)
3792                         continue;
3793                 back = (struct data_backref *)node;
3794                 if (parent > 0) {
3795                         if (!node->full_backref)
3796                                 continue;
3797                         if (parent == back->parent)
3798                                 return back;
3799                 } else {
3800                         if (node->full_backref)
3801                                 continue;
3802                         if (back->root == root && back->owner == owner &&
3803                             back->offset == offset) {
3804                                 if (found_ref && node->found_ref &&
3805                                     (back->bytes != bytes ||
3806                                     back->disk_bytenr != disk_bytenr))
3807                                         continue;
3808                                 return back;
3809                         }
3810                 }
3811         }
3812         return NULL;
3813 }
3814
3815 static struct data_backref *alloc_data_backref(struct extent_record *rec,
3816                                                 u64 parent, u64 root,
3817                                                 u64 owner, u64 offset,
3818                                                 u64 max_size)
3819 {
3820         struct data_backref *ref = malloc(sizeof(*ref));
3821         memset(&ref->node, 0, sizeof(ref->node));
3822         ref->node.is_data = 1;
3823
3824         if (parent > 0) {
3825                 ref->parent = parent;
3826                 ref->owner = 0;
3827                 ref->offset = 0;
3828                 ref->node.full_backref = 1;
3829         } else {
3830                 ref->root = root;
3831                 ref->owner = owner;
3832                 ref->offset = offset;
3833                 ref->node.full_backref = 0;
3834         }
3835         ref->bytes = max_size;
3836         ref->found_ref = 0;
3837         ref->num_refs = 0;
3838         list_add_tail(&ref->node.list, &rec->backrefs);
3839         if (max_size > rec->max_size)
3840                 rec->max_size = max_size;
3841         return ref;
3842 }
3843
3844 static int add_extent_rec(struct cache_tree *extent_cache,
3845                           struct btrfs_key *parent_key, u64 parent_gen,
3846                           u64 start, u64 nr, u64 extent_item_refs,
3847                           int is_root, int inc_ref, int set_checked,
3848                           int metadata, int extent_rec, u64 max_size)
3849 {
3850         struct extent_record *rec;
3851         struct cache_extent *cache;
3852         int ret = 0;
3853         int dup = 0;
3854
3855         cache = lookup_cache_extent(extent_cache, start, nr);
3856         if (cache) {
3857                 rec = container_of(cache, struct extent_record, cache);
3858                 if (inc_ref)
3859                         rec->refs++;
3860                 if (rec->nr == 1)
3861                         rec->nr = max(nr, max_size);
3862
3863                 /*
3864                  * We need to make sure to reset nr to whatever the extent
3865                  * record says was the real size, this way we can compare it to
3866                  * the backrefs.
3867                  */
3868                 if (extent_rec) {
3869                         if (start != rec->start || rec->found_rec) {
3870                                 struct extent_record *tmp;
3871
3872                                 dup = 1;
3873                                 if (list_empty(&rec->list))
3874                                         list_add_tail(&rec->list,
3875                                                       &duplicate_extents);
3876
3877                                 /*
3878                                  * We have to do this song and dance in case we
3879                                  * find an extent record that falls inside of
3880                                  * our current extent record but does not have
3881                                  * the same objectid.
3882                                  */
3883                                 tmp = malloc(sizeof(*tmp));
3884                                 if (!tmp)
3885                                         return -ENOMEM;
3886                                 tmp->start = start;
3887                                 tmp->max_size = max_size;
3888                                 tmp->nr = nr;
3889                                 tmp->found_rec = 1;
3890                                 tmp->metadata = metadata;
3891                                 tmp->extent_item_refs = extent_item_refs;
3892                                 INIT_LIST_HEAD(&tmp->list);
3893                                 list_add_tail(&tmp->list, &rec->dups);
3894                                 rec->num_duplicates++;
3895                         } else {
3896                                 rec->nr = nr;
3897                                 rec->found_rec = 1;
3898                         }
3899                 }
3900
3901                 if (extent_item_refs && !dup) {
3902                         if (rec->extent_item_refs) {
3903                                 fprintf(stderr, "block %llu rec "
3904                                         "extent_item_refs %llu, passed %llu\n",
3905                                         (unsigned long long)start,
3906                                         (unsigned long long)
3907                                                         rec->extent_item_refs,
3908                                         (unsigned long long)extent_item_refs);
3909                         }
3910                         rec->extent_item_refs = extent_item_refs;
3911                 }
3912                 if (is_root)
3913                         rec->is_root = 1;
3914                 if (set_checked) {
3915                         rec->content_checked = 1;
3916                         rec->owner_ref_checked = 1;
3917                 }
3918
3919                 if (parent_key)
3920                         btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
3921                 if (parent_gen)
3922                         rec->parent_generation = parent_gen;
3923
3924                 if (rec->max_size < max_size)
3925                         rec->max_size = max_size;
3926
3927                 maybe_free_extent_rec(extent_cache, rec);
3928                 return ret;
3929         }
3930         rec = malloc(sizeof(*rec));
3931         rec->start = start;
3932         rec->max_size = max_size;
3933         rec->nr = max(nr, max_size);
3934         rec->found_rec = !!extent_rec;
3935         rec->content_checked = 0;
3936         rec->owner_ref_checked = 0;
3937         rec->num_duplicates = 0;
3938         rec->metadata = metadata;
3939         INIT_LIST_HEAD(&rec->backrefs);
3940         INIT_LIST_HEAD(&rec->dups);
3941         INIT_LIST_HEAD(&rec->list);
3942
3943         if (is_root)
3944                 rec->is_root = 1;
3945         else
3946                 rec->is_root = 0;
3947
3948         if (inc_ref)
3949                 rec->refs = 1;
3950         else
3951                 rec->refs = 0;
3952
3953         if (extent_item_refs)
3954                 rec->extent_item_refs = extent_item_refs;
3955         else
3956                 rec->extent_item_refs = 0;
3957
3958         if (parent_key)
3959                 btrfs_cpu_key_to_disk(&rec->parent_key, parent_key);
3960         else
3961                 memset(&rec->parent_key, 0, sizeof(*parent_key));
3962
3963         if (parent_gen)
3964                 rec->parent_generation = parent_gen;
3965         else
3966                 rec->parent_generation = 0;
3967
3968         rec->cache.start = start;
3969         rec->cache.size = nr;
3970         ret = insert_cache_extent(extent_cache, &rec->cache);
3971         BUG_ON(ret);
3972         bytes_used += nr;
3973         if (set_checked) {
3974                 rec->content_checked = 1;
3975                 rec->owner_ref_checked = 1;
3976         }
3977         return ret;
3978 }
3979
3980 static int add_tree_backref(struct cache_tree *extent_cache, u64 bytenr,
3981                             u64 parent, u64 root, int found_ref)
3982 {
3983         struct extent_record *rec;
3984         struct tree_backref *back;
3985         struct cache_extent *cache;
3986
3987         cache = lookup_cache_extent(extent_cache, bytenr, 1);
3988         if (!cache) {
3989                 add_extent_rec(extent_cache, NULL, 0, bytenr,
3990                                1, 0, 0, 0, 0, 1, 0, 0);
3991                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
3992                 if (!cache)
3993                         abort();
3994         }
3995
3996         rec = container_of(cache, struct extent_record, cache);
3997         if (rec->start != bytenr) {
3998                 abort();
3999         }
4000
4001         back = find_tree_backref(rec, parent, root);
4002         if (!back)
4003                 back = alloc_tree_backref(rec, parent, root);
4004
4005         if (found_ref) {
4006                 if (back->node.found_ref) {
4007                         fprintf(stderr, "Extent back ref already exists "
4008                                 "for %llu parent %llu root %llu \n",
4009                                 (unsigned long long)bytenr,
4010                                 (unsigned long long)parent,
4011                                 (unsigned long long)root);
4012                 }
4013                 back->node.found_ref = 1;
4014         } else {
4015                 if (back->node.found_extent_tree) {
4016                         fprintf(stderr, "Extent back ref already exists "
4017                                 "for %llu parent %llu root %llu \n",
4018                                 (unsigned long long)bytenr,
4019                                 (unsigned long long)parent,
4020                                 (unsigned long long)root);
4021                 }
4022                 back->node.found_extent_tree = 1;
4023         }
4024         maybe_free_extent_rec(extent_cache, rec);
4025         return 0;
4026 }
4027
4028 static int add_data_backref(struct cache_tree *extent_cache, u64 bytenr,
4029                             u64 parent, u64 root, u64 owner, u64 offset,
4030                             u32 num_refs, int found_ref, u64 max_size)
4031 {
4032         struct extent_record *rec;
4033         struct data_backref *back;
4034         struct cache_extent *cache;
4035
4036         cache = lookup_cache_extent(extent_cache, bytenr, 1);
4037         if (!cache) {
4038                 add_extent_rec(extent_cache, NULL, 0, bytenr, 1, 0, 0, 0, 0,
4039                                0, 0, max_size);
4040                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
4041                 if (!cache)
4042                         abort();
4043         }
4044
4045         rec = container_of(cache, struct extent_record, cache);
4046         if (rec->max_size < max_size)
4047                 rec->max_size = max_size;
4048
4049         /*
4050          * If found_ref is set then max_size is the real size and must match the
4051          * existing refs.  So if we have already found a ref then we need to
4052          * make sure that this ref matches the existing one, otherwise we need
4053          * to add a new backref so we can notice that the backrefs don't match
4054          * and we need to figure out who is telling the truth.  This is to
4055          * account for that awful fsync bug I introduced where we'd end up with
4056          * a btrfs_file_extent_item that would have its length include multiple
4057          * prealloc extents or point inside of a prealloc extent.
4058          */
4059         back = find_data_backref(rec, parent, root, owner, offset, found_ref,
4060                                  bytenr, max_size);
4061         if (!back)
4062                 back = alloc_data_backref(rec, parent, root, owner, offset,
4063                                           max_size);
4064
4065         if (found_ref) {
4066                 BUG_ON(num_refs != 1);
4067                 if (back->node.found_ref)
4068                         BUG_ON(back->bytes != max_size);
4069                 back->node.found_ref = 1;
4070                 back->found_ref += 1;
4071                 back->bytes = max_size;
4072                 back->disk_bytenr = bytenr;
4073                 rec->refs += 1;
4074                 rec->content_checked = 1;
4075                 rec->owner_ref_checked = 1;
4076         } else {
4077                 if (back->node.found_extent_tree) {
4078                         fprintf(stderr, "Extent back ref already exists "
4079                                 "for %llu parent %llu root %llu "
4080                                 "owner %llu offset %llu num_refs %lu\n",
4081                                 (unsigned long long)bytenr,
4082                                 (unsigned long long)parent,
4083                                 (unsigned long long)root,
4084                                 (unsigned long long)owner,
4085                                 (unsigned long long)offset,
4086                                 (unsigned long)num_refs);
4087                 }
4088                 back->num_refs = num_refs;
4089                 back->node.found_extent_tree = 1;
4090         }
4091         maybe_free_extent_rec(extent_cache, rec);
4092         return 0;
4093 }
4094
4095 static int add_pending(struct cache_tree *pending,
4096                        struct cache_tree *seen, u64 bytenr, u32 size)
4097 {
4098         int ret;
4099         ret = add_cache_extent(seen, bytenr, size);
4100         if (ret)
4101                 return ret;
4102         add_cache_extent(pending, bytenr, size);
4103         return 0;
4104 }
4105
4106 static int pick_next_pending(struct cache_tree *pending,
4107                         struct cache_tree *reada,
4108                         struct cache_tree *nodes,
4109                         u64 last, struct block_info *bits, int bits_nr,
4110                         int *reada_bits)
4111 {
4112         unsigned long node_start = last;
4113         struct cache_extent *cache;
4114         int ret;
4115
4116         cache = search_cache_extent(reada, 0);
4117         if (cache) {
4118                 bits[0].start = cache->start;
4119                 bits[0].size = cache->size;
4120                 *reada_bits = 1;
4121                 return 1;
4122         }
4123         *reada_bits = 0;
4124         if (node_start > 32768)
4125                 node_start -= 32768;
4126
4127         cache = search_cache_extent(nodes, node_start);
4128         if (!cache)
4129                 cache = search_cache_extent(nodes, 0);
4130
4131         if (!cache) {
4132                  cache = search_cache_extent(pending, 0);
4133                  if (!cache)
4134                          return 0;
4135                  ret = 0;
4136                  do {
4137                          bits[ret].start = cache->start;
4138                          bits[ret].size = cache->size;
4139                          cache = next_cache_extent(cache);
4140                          ret++;
4141                  } while (cache && ret < bits_nr);
4142                  return ret;
4143         }
4144
4145         ret = 0;
4146         do {
4147                 bits[ret].start = cache->start;
4148                 bits[ret].size = cache->size;
4149                 cache = next_cache_extent(cache);
4150                 ret++;
4151         } while (cache && ret < bits_nr);
4152
4153         if (bits_nr - ret > 8) {
4154                 u64 lookup = bits[0].start + bits[0].size;
4155                 struct cache_extent *next;
4156                 next = search_cache_extent(pending, lookup);
4157                 while(next) {
4158                         if (next->start - lookup > 32768)
4159                                 break;
4160                         bits[ret].start = next->start;
4161                         bits[ret].size = next->size;
4162                         lookup = next->start + next->size;
4163                         ret++;
4164                         if (ret == bits_nr)
4165                                 break;
4166                         next = next_cache_extent(next);
4167                         if (!next)
4168                                 break;
4169                 }
4170         }
4171         return ret;
4172 }
4173
4174 static void free_chunk_record(struct cache_extent *cache)
4175 {
4176         struct chunk_record *rec;
4177
4178         rec = container_of(cache, struct chunk_record, cache);
4179         list_del_init(&rec->list);
4180         list_del_init(&rec->dextents);
4181         free(rec);
4182 }
4183
4184 void free_chunk_cache_tree(struct cache_tree *chunk_cache)
4185 {
4186         cache_tree_free_extents(chunk_cache, free_chunk_record);
4187 }
4188
4189 static void free_device_record(struct rb_node *node)
4190 {
4191         struct device_record *rec;
4192
4193         rec = container_of(node, struct device_record, node);
4194         free(rec);
4195 }
4196
4197 FREE_RB_BASED_TREE(device_cache, free_device_record);
4198
4199 int insert_block_group_record(struct block_group_tree *tree,
4200                               struct block_group_record *bg_rec)
4201 {
4202         int ret;
4203
4204         ret = insert_cache_extent(&tree->tree, &bg_rec->cache);
4205         if (ret)
4206                 return ret;
4207
4208         list_add_tail(&bg_rec->list, &tree->block_groups);
4209         return 0;
4210 }
4211
4212 static void free_block_group_record(struct cache_extent *cache)
4213 {
4214         struct block_group_record *rec;
4215
4216         rec = container_of(cache, struct block_group_record, cache);
4217         list_del_init(&rec->list);
4218         free(rec);
4219 }
4220
4221 void free_block_group_tree(struct block_group_tree *tree)
4222 {
4223         cache_tree_free_extents(&tree->tree, free_block_group_record);
4224 }
4225
4226 int insert_device_extent_record(struct device_extent_tree *tree,
4227                                 struct device_extent_record *de_rec)
4228 {
4229         int ret;
4230
4231         /*
4232          * Device extent is a bit different from the other extents, because
4233          * the extents which belong to the different devices may have the
4234          * same start and size, so we need use the special extent cache
4235          * search/insert functions.
4236          */
4237         ret = insert_cache_extent2(&tree->tree, &de_rec->cache);
4238         if (ret)
4239                 return ret;
4240
4241         list_add_tail(&de_rec->chunk_list, &tree->no_chunk_orphans);
4242         list_add_tail(&de_rec->device_list, &tree->no_device_orphans);
4243         return 0;
4244 }
4245
4246 static void free_device_extent_record(struct cache_extent *cache)
4247 {
4248         struct device_extent_record *rec;
4249
4250         rec = container_of(cache, struct device_extent_record, cache);
4251         if (!list_empty(&rec->chunk_list))
4252                 list_del_init(&rec->chunk_list);
4253         if (!list_empty(&rec->device_list))
4254                 list_del_init(&rec->device_list);
4255         free(rec);
4256 }
4257
4258 void free_device_extent_tree(struct device_extent_tree *tree)
4259 {
4260         cache_tree_free_extents(&tree->tree, free_device_extent_record);
4261 }
4262
4263 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4264 static int process_extent_ref_v0(struct cache_tree *extent_cache,
4265                                  struct extent_buffer *leaf, int slot)
4266 {
4267         struct btrfs_extent_ref_v0 *ref0;
4268         struct btrfs_key key;
4269
4270         btrfs_item_key_to_cpu(leaf, &key, slot);
4271         ref0 = btrfs_item_ptr(leaf, slot, struct btrfs_extent_ref_v0);
4272         if (btrfs_ref_objectid_v0(leaf, ref0) < BTRFS_FIRST_FREE_OBJECTID) {
4273                 add_tree_backref(extent_cache, key.objectid, key.offset, 0, 0);
4274         } else {
4275                 add_data_backref(extent_cache, key.objectid, key.offset, 0,
4276                                  0, 0, btrfs_ref_count_v0(leaf, ref0), 0, 0);
4277         }
4278         return 0;
4279 }
4280 #endif
4281
4282 struct chunk_record *btrfs_new_chunk_record(struct extent_buffer *leaf,
4283                                             struct btrfs_key *key,
4284                                             int slot)
4285 {
4286         struct btrfs_chunk *ptr;
4287         struct chunk_record *rec;
4288         int num_stripes, i;
4289
4290         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4291         num_stripes = btrfs_chunk_num_stripes(leaf, ptr);
4292
4293         rec = malloc(btrfs_chunk_record_size(num_stripes));
4294         if (!rec) {
4295                 fprintf(stderr, "memory allocation failed\n");
4296                 exit(-1);
4297         }
4298
4299         memset(rec, 0, btrfs_chunk_record_size(num_stripes));
4300
4301         INIT_LIST_HEAD(&rec->list);
4302         INIT_LIST_HEAD(&rec->dextents);
4303         rec->bg_rec = NULL;
4304
4305         rec->cache.start = key->offset;
4306         rec->cache.size = btrfs_chunk_length(leaf, ptr);
4307
4308         rec->generation = btrfs_header_generation(leaf);
4309
4310         rec->objectid = key->objectid;
4311         rec->type = key->type;
4312         rec->offset = key->offset;
4313
4314         rec->length = rec->cache.size;
4315         rec->owner = btrfs_chunk_owner(leaf, ptr);
4316         rec->stripe_len = btrfs_chunk_stripe_len(leaf, ptr);
4317         rec->type_flags = btrfs_chunk_type(leaf, ptr);
4318         rec->io_width = btrfs_chunk_io_width(leaf, ptr);
4319         rec->io_align = btrfs_chunk_io_align(leaf, ptr);
4320         rec->sector_size = btrfs_chunk_sector_size(leaf, ptr);
4321         rec->num_stripes = num_stripes;
4322         rec->sub_stripes = btrfs_chunk_sub_stripes(leaf, ptr);
4323
4324         for (i = 0; i < rec->num_stripes; ++i) {
4325                 rec->stripes[i].devid =
4326                         btrfs_stripe_devid_nr(leaf, ptr, i);
4327                 rec->stripes[i].offset =
4328                         btrfs_stripe_offset_nr(leaf, ptr, i);
4329                 read_extent_buffer(leaf, rec->stripes[i].dev_uuid,
4330                                 (unsigned long)btrfs_stripe_dev_uuid_nr(ptr, i),
4331                                 BTRFS_UUID_SIZE);
4332         }
4333
4334         return rec;
4335 }
4336
4337 static int process_chunk_item(struct cache_tree *chunk_cache,
4338                               struct btrfs_key *key, struct extent_buffer *eb,
4339                               int slot)
4340 {
4341         struct chunk_record *rec;
4342         int ret = 0;
4343
4344         rec = btrfs_new_chunk_record(eb, key, slot);
4345         ret = insert_cache_extent(chunk_cache, &rec->cache);
4346         if (ret) {
4347                 fprintf(stderr, "Chunk[%llu, %llu] existed.\n",
4348                         rec->offset, rec->length);
4349                 free(rec);
4350         }
4351
4352         return ret;
4353 }
4354
4355 static int process_device_item(struct rb_root *dev_cache,
4356                 struct btrfs_key *key, struct extent_buffer *eb, int slot)
4357 {
4358         struct btrfs_dev_item *ptr;
4359         struct device_record *rec;
4360         int ret = 0;
4361
4362         ptr = btrfs_item_ptr(eb,
4363                 slot, struct btrfs_dev_item);
4364
4365         rec = malloc(sizeof(*rec));
4366         if (!rec) {
4367                 fprintf(stderr, "memory allocation failed\n");
4368                 return -ENOMEM;
4369         }
4370
4371         rec->devid = key->offset;
4372         rec->generation = btrfs_header_generation(eb);
4373
4374         rec->objectid = key->objectid;
4375         rec->type = key->type;
4376         rec->offset = key->offset;
4377
4378         rec->devid = btrfs_device_id(eb, ptr);
4379         rec->total_byte = btrfs_device_total_bytes(eb, ptr);
4380         rec->byte_used = btrfs_device_bytes_used(eb, ptr);
4381
4382         ret = rb_insert(dev_cache, &rec->node, device_record_compare);
4383         if (ret) {
4384                 fprintf(stderr, "Device[%llu] existed.\n", rec->devid);
4385                 free(rec);
4386         }
4387
4388         return ret;
4389 }
4390
4391 struct block_group_record *
4392 btrfs_new_block_group_record(struct extent_buffer *leaf, struct btrfs_key *key,
4393                              int slot)
4394 {
4395         struct btrfs_block_group_item *ptr;
4396         struct block_group_record *rec;
4397
4398         rec = malloc(sizeof(*rec));
4399         if (!rec) {
4400                 fprintf(stderr, "memory allocation failed\n");
4401                 exit(-1);
4402         }
4403         memset(rec, 0, sizeof(*rec));
4404
4405         rec->cache.start = key->objectid;
4406         rec->cache.size = key->offset;
4407
4408         rec->generation = btrfs_header_generation(leaf);
4409
4410         rec->objectid = key->objectid;
4411         rec->type = key->type;
4412         rec->offset = key->offset;
4413
4414         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item);
4415         rec->flags = btrfs_disk_block_group_flags(leaf, ptr);
4416
4417         INIT_LIST_HEAD(&rec->list);
4418
4419         return rec;
4420 }
4421
4422 static int process_block_group_item(struct block_group_tree *block_group_cache,
4423                                     struct btrfs_key *key,
4424                                     struct extent_buffer *eb, int slot)
4425 {
4426         struct block_group_record *rec;
4427         int ret = 0;
4428
4429         rec = btrfs_new_block_group_record(eb, key, slot);
4430         ret = insert_block_group_record(block_group_cache, rec);
4431         if (ret) {
4432                 fprintf(stderr, "Block Group[%llu, %llu] existed.\n",
4433                         rec->objectid, rec->offset);
4434                 free(rec);
4435         }
4436
4437         return ret;
4438 }
4439
4440 struct device_extent_record *
4441 btrfs_new_device_extent_record(struct extent_buffer *leaf,
4442                                struct btrfs_key *key, int slot)
4443 {
4444         struct device_extent_record *rec;
4445         struct btrfs_dev_extent *ptr;
4446
4447         rec = malloc(sizeof(*rec));
4448         if (!rec) {
4449                 fprintf(stderr, "memory allocation failed\n");
4450                 exit(-1);
4451         }
4452         memset(rec, 0, sizeof(*rec));
4453
4454         rec->cache.objectid = key->objectid;
4455         rec->cache.start = key->offset;
4456
4457         rec->generation = btrfs_header_generation(leaf);
4458
4459         rec->objectid = key->objectid;
4460         rec->type = key->type;
4461         rec->offset = key->offset;
4462
4463         ptr = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
4464         rec->chunk_objecteid =
4465                 btrfs_dev_extent_chunk_objectid(leaf, ptr);
4466         rec->chunk_offset =
4467                 btrfs_dev_extent_chunk_offset(leaf, ptr);
4468         rec->length = btrfs_dev_extent_length(leaf, ptr);
4469         rec->cache.size = rec->length;
4470
4471         INIT_LIST_HEAD(&rec->chunk_list);
4472         INIT_LIST_HEAD(&rec->device_list);
4473
4474         return rec;
4475 }
4476
4477 static int
4478 process_device_extent_item(struct device_extent_tree *dev_extent_cache,
4479                            struct btrfs_key *key, struct extent_buffer *eb,
4480                            int slot)
4481 {
4482         struct device_extent_record *rec;
4483         int ret;
4484
4485         rec = btrfs_new_device_extent_record(eb, key, slot);
4486         ret = insert_device_extent_record(dev_extent_cache, rec);
4487         if (ret) {
4488                 fprintf(stderr,
4489                         "Device extent[%llu, %llu, %llu] existed.\n",
4490                         rec->objectid, rec->offset, rec->length);
4491                 free(rec);
4492         }
4493
4494         return ret;
4495 }
4496
4497 static int process_extent_item(struct btrfs_root *root,
4498                                struct cache_tree *extent_cache,
4499                                struct extent_buffer *eb, int slot)
4500 {
4501         struct btrfs_extent_item *ei;
4502         struct btrfs_extent_inline_ref *iref;
4503         struct btrfs_extent_data_ref *dref;
4504         struct btrfs_shared_data_ref *sref;
4505         struct btrfs_key key;
4506         unsigned long end;
4507         unsigned long ptr;
4508         int type;
4509         u32 item_size = btrfs_item_size_nr(eb, slot);
4510         u64 refs = 0;
4511         u64 offset;
4512         u64 num_bytes;
4513         int metadata = 0;
4514
4515         btrfs_item_key_to_cpu(eb, &key, slot);
4516
4517         if (key.type == BTRFS_METADATA_ITEM_KEY) {
4518                 metadata = 1;
4519                 num_bytes = root->leafsize;
4520         } else {
4521                 num_bytes = key.offset;
4522         }
4523
4524         if (item_size < sizeof(*ei)) {
4525 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4526                 struct btrfs_extent_item_v0 *ei0;
4527                 BUG_ON(item_size != sizeof(*ei0));
4528                 ei0 = btrfs_item_ptr(eb, slot, struct btrfs_extent_item_v0);
4529                 refs = btrfs_extent_refs_v0(eb, ei0);
4530 #else
4531                 BUG();
4532 #endif
4533                 return add_extent_rec(extent_cache, NULL, 0, key.objectid,
4534                                       num_bytes, refs, 0, 0, 0, metadata, 1,
4535                                       num_bytes);
4536         }
4537
4538         ei = btrfs_item_ptr(eb, slot, struct btrfs_extent_item);
4539         refs = btrfs_extent_refs(eb, ei);
4540
4541         add_extent_rec(extent_cache, NULL, 0, key.objectid, num_bytes,
4542                        refs, 0, 0, 0, metadata, 1, num_bytes);
4543
4544         ptr = (unsigned long)(ei + 1);
4545         if (btrfs_extent_flags(eb, ei) & BTRFS_EXTENT_FLAG_TREE_BLOCK &&
4546             key.type == BTRFS_EXTENT_ITEM_KEY)
4547                 ptr += sizeof(struct btrfs_tree_block_info);
4548
4549         end = (unsigned long)ei + item_size;
4550         while (ptr < end) {
4551                 iref = (struct btrfs_extent_inline_ref *)ptr;
4552                 type = btrfs_extent_inline_ref_type(eb, iref);
4553                 offset = btrfs_extent_inline_ref_offset(eb, iref);
4554                 switch (type) {
4555                 case BTRFS_TREE_BLOCK_REF_KEY:
4556                         add_tree_backref(extent_cache, key.objectid,
4557                                          0, offset, 0);
4558                         break;
4559                 case BTRFS_SHARED_BLOCK_REF_KEY:
4560                         add_tree_backref(extent_cache, key.objectid,
4561                                          offset, 0, 0);
4562                         break;
4563                 case BTRFS_EXTENT_DATA_REF_KEY:
4564                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
4565                         add_data_backref(extent_cache, key.objectid, 0,
4566                                         btrfs_extent_data_ref_root(eb, dref),
4567                                         btrfs_extent_data_ref_objectid(eb,
4568                                                                        dref),
4569                                         btrfs_extent_data_ref_offset(eb, dref),
4570                                         btrfs_extent_data_ref_count(eb, dref),
4571                                         0, num_bytes);
4572                         break;
4573                 case BTRFS_SHARED_DATA_REF_KEY:
4574                         sref = (struct btrfs_shared_data_ref *)(iref + 1);
4575                         add_data_backref(extent_cache, key.objectid, offset,
4576                                         0, 0, 0,
4577                                         btrfs_shared_data_ref_count(eb, sref),
4578                                         0, num_bytes);
4579                         break;
4580                 default:
4581                         fprintf(stderr, "corrupt extent record: key %Lu %u %Lu\n",
4582                                 key.objectid, key.type, num_bytes);
4583                         goto out;
4584                 }
4585                 ptr += btrfs_extent_inline_ref_size(type);
4586         }
4587         WARN_ON(ptr > end);
4588 out:
4589         return 0;
4590 }
4591
4592 static int check_cache_range(struct btrfs_root *root,
4593                              struct btrfs_block_group_cache *cache,
4594                              u64 offset, u64 bytes)
4595 {
4596         struct btrfs_free_space *entry;
4597         u64 *logical;
4598         u64 bytenr;
4599         int stripe_len;
4600         int i, nr, ret;
4601
4602         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
4603                 bytenr = btrfs_sb_offset(i);
4604                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
4605                                        cache->key.objectid, bytenr, 0,
4606                                        &logical, &nr, &stripe_len);
4607                 if (ret)
4608                         return ret;
4609
4610                 while (nr--) {
4611                         if (logical[nr] + stripe_len <= offset)
4612                                 continue;
4613                         if (offset + bytes <= logical[nr])
4614                                 continue;
4615                         if (logical[nr] == offset) {
4616                                 if (stripe_len >= bytes) {
4617                                         kfree(logical);
4618                                         return 0;
4619                                 }
4620                                 bytes -= stripe_len;
4621                                 offset += stripe_len;
4622                         } else if (logical[nr] < offset) {
4623                                 if (logical[nr] + stripe_len >=
4624                                     offset + bytes) {
4625                                         kfree(logical);
4626                                         return 0;
4627                                 }
4628                                 bytes = (offset + bytes) -
4629                                         (logical[nr] + stripe_len);
4630                                 offset = logical[nr] + stripe_len;
4631                         } else {
4632                                 /*
4633                                  * Could be tricky, the super may land in the
4634                                  * middle of the area we're checking.  First
4635                                  * check the easiest case, it's at the end.
4636                                  */
4637                                 if (logical[nr] + stripe_len >=
4638                                     bytes + offset) {
4639                                         bytes = logical[nr] - offset;
4640                                         continue;
4641                                 }
4642
4643                                 /* Check the left side */
4644                                 ret = check_cache_range(root, cache,
4645                                                         offset,
4646                                                         logical[nr] - offset);
4647                                 if (ret) {
4648                                         kfree(logical);
4649                                         return ret;
4650                                 }
4651
4652                                 /* Now we continue with the right side */
4653                                 bytes = (offset + bytes) -
4654                                         (logical[nr] + stripe_len);
4655                                 offset = logical[nr] + stripe_len;
4656                         }
4657                 }
4658
4659                 kfree(logical);
4660         }
4661
4662         entry = btrfs_find_free_space(cache->free_space_ctl, offset, bytes);
4663         if (!entry) {
4664                 fprintf(stderr, "There is no free space entry for %Lu-%Lu\n",
4665                         offset, offset+bytes);
4666                 return -EINVAL;
4667         }
4668
4669         if (entry->offset != offset) {
4670                 fprintf(stderr, "Wanted offset %Lu, found %Lu\n", offset,
4671                         entry->offset);
4672                 return -EINVAL;
4673         }
4674
4675         if (entry->bytes != bytes) {
4676                 fprintf(stderr, "Wanted bytes %Lu, found %Lu for off %Lu\n",
4677                         bytes, entry->bytes, offset);
4678                 return -EINVAL;
4679         }
4680
4681         unlink_free_space(cache->free_space_ctl, entry);
4682         free(entry);
4683         return 0;
4684 }
4685
4686 static int verify_space_cache(struct btrfs_root *root,
4687                               struct btrfs_block_group_cache *cache)
4688 {
4689         struct btrfs_path *path;
4690         struct extent_buffer *leaf;
4691         struct btrfs_key key;
4692         u64 last;
4693         int ret = 0;
4694
4695         path = btrfs_alloc_path();
4696         if (!path)
4697                 return -ENOMEM;
4698
4699         root = root->fs_info->extent_root;
4700
4701         last = max_t(u64, cache->key.objectid, BTRFS_SUPER_INFO_OFFSET);
4702
4703         key.objectid = last;
4704         key.offset = 0;
4705         key.type = BTRFS_EXTENT_ITEM_KEY;
4706
4707         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4708         if (ret < 0)
4709                 goto out;
4710         ret = 0;
4711         while (1) {
4712                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4713                         ret = btrfs_next_leaf(root, path);
4714                         if (ret < 0)
4715                                 goto out;
4716                         if (ret > 0) {
4717                                 ret = 0;
4718                                 break;
4719                         }
4720                 }
4721                 leaf = path->nodes[0];
4722                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4723                 if (key.objectid >= cache->key.offset + cache->key.objectid)
4724                         break;
4725                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
4726                     key.type != BTRFS_METADATA_ITEM_KEY) {
4727                         path->slots[0]++;
4728                         continue;
4729                 }
4730
4731                 if (last == key.objectid) {
4732                         if (key.type == BTRFS_EXTENT_ITEM_KEY)
4733                                 last = key.objectid + key.offset;
4734                         else
4735                                 last = key.objectid + root->leafsize;
4736                         path->slots[0]++;
4737                         continue;
4738                 }
4739
4740                 ret = check_cache_range(root, cache, last,
4741                                         key.objectid - last);
4742                 if (ret)
4743                         break;
4744                 if (key.type == BTRFS_EXTENT_ITEM_KEY)
4745                         last = key.objectid + key.offset;
4746                 else
4747                         last = key.objectid + root->leafsize;
4748                 path->slots[0]++;
4749         }
4750
4751         if (last < cache->key.objectid + cache->key.offset)
4752                 ret = check_cache_range(root, cache, last,
4753                                         cache->key.objectid +
4754                                         cache->key.offset - last);
4755
4756 out:
4757         btrfs_free_path(path);
4758
4759         if (!ret &&
4760             !RB_EMPTY_ROOT(&cache->free_space_ctl->free_space_offset)) {
4761                 fprintf(stderr, "There are still entries left in the space "
4762                         "cache\n");
4763                 ret = -EINVAL;
4764         }
4765
4766         return ret;
4767 }
4768
4769 static int check_space_cache(struct btrfs_root *root)
4770 {
4771         struct btrfs_block_group_cache *cache;
4772         u64 start = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
4773         int ret;
4774         int error = 0;
4775
4776         if (btrfs_super_cache_generation(root->fs_info->super_copy) != -1ULL &&
4777             btrfs_super_generation(root->fs_info->super_copy) !=
4778             btrfs_super_cache_generation(root->fs_info->super_copy)) {
4779                 printf("cache and super generation don't match, space cache "
4780                        "will be invalidated\n");
4781                 return 0;
4782         }
4783
4784         while (1) {
4785                 cache = btrfs_lookup_first_block_group(root->fs_info, start);
4786                 if (!cache)
4787                         break;
4788
4789                 start = cache->key.objectid + cache->key.offset;
4790                 if (!cache->free_space_ctl) {
4791                         if (btrfs_init_free_space_ctl(cache,
4792                                                       root->sectorsize)) {
4793                                 ret = -ENOMEM;
4794                                 break;
4795                         }
4796                 } else {
4797                         btrfs_remove_free_space_cache(cache);
4798                 }
4799
4800                 ret = load_free_space_cache(root->fs_info, cache);
4801                 if (!ret)
4802                         continue;
4803
4804                 ret = verify_space_cache(root, cache);
4805                 if (ret) {
4806                         fprintf(stderr, "cache appears valid but isnt %Lu\n",
4807                                 cache->key.objectid);
4808                         error++;
4809                 }
4810         }
4811
4812         return error ? -EINVAL : 0;
4813 }
4814
4815 static int read_extent_data(struct btrfs_root *root, char *data,
4816                         u64 logical, u64 *len, int mirror)
4817 {
4818         u64 offset = 0;
4819         struct btrfs_multi_bio *multi = NULL;
4820         struct btrfs_fs_info *info = root->fs_info;
4821         struct btrfs_device *device;
4822         int ret = 0;
4823         u64 max_len = *len;
4824
4825         ret = btrfs_map_block(&info->mapping_tree, READ, logical, len,
4826                               &multi, mirror, NULL);
4827         if (ret) {
4828                 fprintf(stderr, "Couldn't map the block %llu\n",
4829                                 logical + offset);
4830                 goto err;
4831         }
4832         device = multi->stripes[0].dev;
4833
4834         if (device->fd == 0)
4835                 goto err;
4836         if (*len > max_len)
4837                 *len = max_len;
4838
4839         ret = pread64(device->fd, data, *len, multi->stripes[0].physical);
4840         if (ret != *len)
4841                 ret = -EIO;
4842         else
4843                 ret = 0;
4844 err:
4845         kfree(multi);
4846         return ret;
4847 }
4848
4849 static int check_extent_csums(struct btrfs_root *root, u64 bytenr,
4850                         u64 num_bytes, unsigned long leaf_offset,
4851                         struct extent_buffer *eb) {
4852
4853         u64 offset = 0;
4854         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
4855         char *data;
4856         unsigned long csum_offset;
4857         u32 csum;
4858         u32 csum_expected;
4859         u64 read_len;
4860         u64 data_checked = 0;
4861         u64 tmp;
4862         int ret = 0;
4863         int mirror;
4864         int num_copies;
4865
4866         if (num_bytes % root->sectorsize)
4867                 return -EINVAL;
4868
4869         data = malloc(num_bytes);
4870         if (!data)
4871                 return -ENOMEM;
4872
4873         while (offset < num_bytes) {
4874                 mirror = 0;
4875 again:
4876                 read_len = num_bytes - offset;
4877                 /* read as much space once a time */
4878                 ret = read_extent_data(root, data + offset,
4879                                 bytenr + offset, &read_len, mirror);
4880                 if (ret)
4881                         goto out;
4882                 data_checked = 0;
4883                 /* verify every 4k data's checksum */
4884                 while (data_checked < read_len) {
4885                         csum = ~(u32)0;
4886                         tmp = offset + data_checked;
4887
4888                         csum = btrfs_csum_data(NULL, (char *)data + tmp,
4889                                                csum, root->sectorsize);
4890                         btrfs_csum_final(csum, (char *)&csum);
4891
4892                         csum_offset = leaf_offset +
4893                                  tmp / root->sectorsize * csum_size;
4894                         read_extent_buffer(eb, (char *)&csum_expected,
4895                                            csum_offset, csum_size);
4896                         /* try another mirror */
4897                         if (csum != csum_expected) {
4898                                 fprintf(stderr, "mirror %d bytenr %llu csum %u expected csum %u\n",
4899                                                 mirror, bytenr + tmp,
4900                                                 csum, csum_expected);
4901                                 num_copies = btrfs_num_copies(
4902                                                 &root->fs_info->mapping_tree,
4903                                                 bytenr, num_bytes);
4904                                 if (mirror < num_copies - 1) {
4905                                         mirror += 1;
4906                                         goto again;
4907                                 }
4908                         }
4909                         data_checked += root->sectorsize;
4910                 }
4911                 offset += read_len;
4912         }
4913 out:
4914         free(data);
4915         return ret;
4916 }
4917
4918 static int check_extent_exists(struct btrfs_root *root, u64 bytenr,
4919                                u64 num_bytes)
4920 {
4921         struct btrfs_path *path;
4922         struct extent_buffer *leaf;
4923         struct btrfs_key key;
4924         int ret;
4925
4926         path = btrfs_alloc_path();
4927         if (!path) {
4928                 fprintf(stderr, "Error allocing path\n");
4929                 return -ENOMEM;
4930         }
4931
4932         key.objectid = bytenr;
4933         key.type = BTRFS_EXTENT_ITEM_KEY;
4934         key.offset = (u64)-1;
4935
4936 again:
4937         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
4938                                 0, 0);
4939         if (ret < 0) {
4940                 fprintf(stderr, "Error looking up extent record %d\n", ret);
4941                 btrfs_free_path(path);
4942                 return ret;
4943         } else if (ret) {
4944                 if (path->slots[0] > 0) {
4945                         path->slots[0]--;
4946                 } else {
4947                         ret = btrfs_prev_leaf(root, path);
4948                         if (ret < 0) {
4949                                 goto out;
4950                         } else if (ret > 0) {
4951                                 ret = 0;
4952                                 goto out;
4953                         }
4954                 }
4955         }
4956
4957         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4958
4959         /*
4960          * Block group items come before extent items if they have the same
4961          * bytenr, so walk back one more just in case.  Dear future traveler,
4962          * first congrats on mastering time travel.  Now if it's not too much
4963          * trouble could you go back to 2006 and tell Chris to make the
4964          * BLOCK_GROUP_ITEM_KEY (and BTRFS_*_REF_KEY) lower than the
4965          * EXTENT_ITEM_KEY please?
4966          */
4967         while (key.type > BTRFS_EXTENT_ITEM_KEY) {
4968                 if (path->slots[0] > 0) {
4969                         path->slots[0]--;
4970                 } else {
4971                         ret = btrfs_prev_leaf(root, path);
4972                         if (ret < 0) {
4973                                 goto out;
4974                         } else if (ret > 0) {
4975                                 ret = 0;
4976                                 goto out;
4977                         }
4978                 }
4979                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4980         }
4981
4982         while (num_bytes) {
4983                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4984                         ret = btrfs_next_leaf(root, path);
4985                         if (ret < 0) {
4986                                 fprintf(stderr, "Error going to next leaf "
4987                                         "%d\n", ret);
4988                                 btrfs_free_path(path);
4989                                 return ret;
4990                         } else if (ret) {
4991                                 break;
4992                         }
4993                 }
4994                 leaf = path->nodes[0];
4995                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4996                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
4997                         path->slots[0]++;
4998                         continue;
4999                 }
5000                 if (key.objectid + key.offset < bytenr) {
5001                         path->slots[0]++;
5002                         continue;
5003                 }
5004                 if (key.objectid > bytenr + num_bytes)
5005                         break;
5006
5007                 if (key.objectid == bytenr) {
5008                         if (key.offset >= num_bytes) {
5009                                 num_bytes = 0;
5010                                 break;
5011                         }
5012                         num_bytes -= key.offset;
5013                         bytenr += key.offset;
5014                 } else if (key.objectid < bytenr) {
5015                         if (key.objectid + key.offset >= bytenr + num_bytes) {
5016                                 num_bytes = 0;
5017                                 break;
5018                         }
5019                         num_bytes = (bytenr + num_bytes) -
5020                                 (key.objectid + key.offset);
5021                         bytenr = key.objectid + key.offset;
5022                 } else {
5023                         if (key.objectid + key.offset < bytenr + num_bytes) {
5024                                 u64 new_start = key.objectid + key.offset;
5025                                 u64 new_bytes = bytenr + num_bytes - new_start;
5026
5027                                 /*
5028                                  * Weird case, the extent is in the middle of
5029                                  * our range, we'll have to search one side
5030                                  * and then the other.  Not sure if this happens
5031                                  * in real life, but no harm in coding it up
5032                                  * anyway just in case.
5033                                  */
5034                                 btrfs_release_path(path);
5035                                 ret = check_extent_exists(root, new_start,
5036                                                           new_bytes);
5037                                 if (ret) {
5038                                         fprintf(stderr, "Right section didn't "
5039                                                 "have a record\n");
5040                                         break;
5041                                 }
5042                                 num_bytes = key.objectid - bytenr;
5043                                 goto again;
5044                         }
5045                         num_bytes = key.objectid - bytenr;
5046                 }
5047                 path->slots[0]++;
5048         }
5049         ret = 0;
5050
5051 out:
5052         if (num_bytes && !ret) {
5053                 fprintf(stderr, "There are no extents for csum range "
5054                         "%Lu-%Lu\n", bytenr, bytenr+num_bytes);
5055                 ret = 1;
5056         }
5057
5058         btrfs_free_path(path);
5059         return ret;
5060 }
5061
5062 static int check_csums(struct btrfs_root *root)
5063 {
5064         struct btrfs_path *path;
5065         struct extent_buffer *leaf;
5066         struct btrfs_key key;
5067         u64 offset = 0, num_bytes = 0;
5068         u16 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
5069         int errors = 0;
5070         int ret;
5071         u64 data_len;
5072         unsigned long leaf_offset;
5073
5074         root = root->fs_info->csum_root;
5075         if (!extent_buffer_uptodate(root->node)) {
5076                 fprintf(stderr, "No valid csum tree found\n");
5077                 return -ENOENT;
5078         }
5079
5080         key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
5081         key.type = BTRFS_EXTENT_CSUM_KEY;
5082         key.offset = 0;
5083
5084         path = btrfs_alloc_path();
5085         if (!path)
5086                 return -ENOMEM;
5087
5088         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5089         if (ret < 0) {
5090                 fprintf(stderr, "Error searching csum tree %d\n", ret);
5091                 btrfs_free_path(path);
5092                 return ret;
5093         }
5094
5095         if (ret > 0 && path->slots[0])
5096                 path->slots[0]--;
5097         ret = 0;
5098
5099         while (1) {
5100                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5101                         ret = btrfs_next_leaf(root, path);
5102                         if (ret < 0) {
5103                                 fprintf(stderr, "Error going to next leaf "
5104                                         "%d\n", ret);
5105                                 break;
5106                         }
5107                         if (ret)
5108                                 break;
5109                 }
5110                 leaf = path->nodes[0];
5111
5112                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5113                 if (key.type != BTRFS_EXTENT_CSUM_KEY) {
5114                         path->slots[0]++;
5115                         continue;
5116                 }
5117
5118                 data_len = (btrfs_item_size_nr(leaf, path->slots[0]) /
5119                               csum_size) * root->sectorsize;
5120                 if (!check_data_csum)
5121                         goto skip_csum_check;
5122                 leaf_offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
5123                 ret = check_extent_csums(root, key.offset, data_len,
5124                                          leaf_offset, leaf);
5125                 if (ret)
5126                         break;
5127 skip_csum_check:
5128                 if (!num_bytes) {
5129                         offset = key.offset;
5130                 } else if (key.offset != offset + num_bytes) {
5131                         ret = check_extent_exists(root, offset, num_bytes);
5132                         if (ret) {
5133                                 fprintf(stderr, "Csum exists for %Lu-%Lu but "
5134                                         "there is no extent record\n",
5135                                         offset, offset+num_bytes);
5136                                 errors++;
5137                         }
5138                         offset = key.offset;
5139                         num_bytes = 0;
5140                 }
5141                 num_bytes += data_len;
5142                 path->slots[0]++;
5143         }
5144
5145         btrfs_free_path(path);
5146         return errors;
5147 }
5148
5149 static int is_dropped_key(struct btrfs_key *key,
5150                           struct btrfs_key *drop_key) {
5151         if (key->objectid < drop_key->objectid)
5152                 return 1;
5153         else if (key->objectid == drop_key->objectid) {
5154                 if (key->type < drop_key->type)
5155                         return 1;
5156                 else if (key->type == drop_key->type) {
5157                         if (key->offset < drop_key->offset)
5158                                 return 1;
5159                 }
5160         }
5161         return 0;
5162 }
5163
5164 static int calc_extent_flag(struct btrfs_root *root,
5165                            struct cache_tree *extent_cache,
5166                            struct extent_buffer *buf,
5167                            struct root_item_record *ri,
5168                            u64 *flags)
5169 {
5170         int i;
5171         int nritems = btrfs_header_nritems(buf);
5172         struct btrfs_key key;
5173         struct extent_record *rec;
5174         struct cache_extent *cache;
5175         struct data_backref *dback;
5176         struct tree_backref *tback;
5177         struct extent_buffer *new_buf;
5178         u64 owner = 0;
5179         u64 bytenr;
5180         u64 offset;
5181         u64 ptr;
5182         int size;
5183         int ret;
5184         u8 level;
5185
5186         /*
5187          * Except file/reloc tree, we can not have
5188          * FULL BACKREF MODE
5189          */
5190         if (ri->objectid < BTRFS_FIRST_FREE_OBJECTID)
5191                 goto normal;
5192         /*
5193          * root node
5194          */
5195         if (buf->start == ri->bytenr)
5196                 goto normal;
5197         if (btrfs_is_leaf(buf)) {
5198                 /*
5199                  * we are searching from original root, world
5200                  * peace is achieved, we use normal backref.
5201                  */
5202                 owner = btrfs_header_owner(buf);
5203                 if (owner == ri->objectid)
5204                         goto normal;
5205                 /*
5206                  * we check every eb here, and if any of
5207                  * eb dosen't have original root refers
5208                  * to this eb, we set full backref flag for
5209                  * this extent, otherwise normal backref.
5210                  */
5211                 for (i = 0; i < nritems; i++) {
5212                         struct btrfs_file_extent_item *fi;
5213                         btrfs_item_key_to_cpu(buf, &key, i);
5214
5215                         if (key.type != BTRFS_EXTENT_DATA_KEY)
5216                                 continue;
5217                         fi = btrfs_item_ptr(buf, i,
5218                                             struct btrfs_file_extent_item);
5219                         if (btrfs_file_extent_type(buf, fi) ==
5220                             BTRFS_FILE_EXTENT_INLINE)
5221                                 continue;
5222                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5223                                 continue;
5224                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
5225                         cache = lookup_cache_extent(extent_cache, bytenr, 1);
5226                         if (!cache)
5227                                 goto full_backref;
5228                         offset = btrfs_file_extent_offset(buf, fi);
5229                         rec = container_of(cache, struct extent_record, cache);
5230                         dback = find_data_backref(rec, 0, ri->objectid, owner,
5231                                         key.offset - offset, 1, bytenr, bytenr);
5232                         if (!dback)
5233                                 goto full_backref;
5234                 }
5235                 goto full_backref;
5236         } else {
5237                 level = btrfs_header_level(buf);
5238                 for (i = 0; i < nritems; i++) {
5239                         ptr = btrfs_node_blockptr(buf, i);
5240                         size = btrfs_level_size(root, level);
5241                         if (i == 0) {
5242                                 new_buf = read_tree_block(root, ptr, size, 0);
5243                                 if (!extent_buffer_uptodate(new_buf)) {
5244                                         free_extent_buffer(new_buf);
5245                                         ret = -EIO;
5246                                         return ret;
5247                                 }
5248                                 /*
5249                                  * we are searching from origin root, world
5250                                  * peace is achieved, we use normal backref.
5251                                  */
5252                                 owner = btrfs_header_owner(new_buf);
5253                                 free_extent_buffer(new_buf);
5254                                 if (owner == ri->objectid)
5255                                         goto normal;
5256                         }
5257                         cache = lookup_cache_extent(extent_cache, ptr, size);
5258                         if (!cache)
5259                                 goto full_backref;
5260                         rec = container_of(cache, struct extent_record, cache);
5261                         tback = find_tree_backref(rec, 0, owner);
5262                         if (!tback)
5263                                 goto full_backref;
5264                 }
5265
5266         }
5267 normal:
5268         *flags = 0;
5269         cache = lookup_cache_extent(extent_cache, buf->start, 1);
5270         /* we have added this extent before */
5271         BUG_ON(!cache);
5272         rec = container_of(cache, struct extent_record, cache);
5273         rec->flag_block_full_backref = 0;
5274         return 0;
5275 full_backref:
5276         *flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5277         cache = lookup_cache_extent(extent_cache, buf->start, 1);
5278         /* we have added this extent before */
5279         BUG_ON(!cache);
5280         rec = container_of(cache, struct extent_record, cache);
5281         rec->flag_block_full_backref = 1;
5282         return 0;
5283 }
5284
5285 static int run_next_block(struct btrfs_trans_handle *trans,
5286                           struct btrfs_root *root,
5287                           struct block_info *bits,
5288                           int bits_nr,
5289                           u64 *last,
5290                           struct cache_tree *pending,
5291                           struct cache_tree *seen,
5292                           struct cache_tree *reada,
5293                           struct cache_tree *nodes,
5294                           struct cache_tree *extent_cache,
5295                           struct cache_tree *chunk_cache,
5296                           struct rb_root *dev_cache,
5297                           struct block_group_tree *block_group_cache,
5298                           struct device_extent_tree *dev_extent_cache,
5299                           struct root_item_record *ri)
5300 {
5301         struct extent_buffer *buf;
5302         u64 bytenr;
5303         u32 size;
5304         u64 parent;
5305         u64 owner;
5306         u64 flags;
5307         u64 ptr;
5308         u64 gen = 0;
5309         int ret = 0;
5310         int i;
5311         int nritems;
5312         struct btrfs_key key;
5313         struct cache_extent *cache;
5314         int reada_bits;
5315
5316         nritems = pick_next_pending(pending, reada, nodes, *last, bits,
5317                                     bits_nr, &reada_bits);
5318         if (nritems == 0)
5319                 return 1;
5320
5321         if (!reada_bits) {
5322                 for(i = 0; i < nritems; i++) {
5323                         ret = add_cache_extent(reada, bits[i].start,
5324                                                bits[i].size);
5325                         if (ret == -EEXIST)
5326                                 continue;
5327
5328                         /* fixme, get the parent transid */
5329                         readahead_tree_block(root, bits[i].start,
5330                                              bits[i].size, 0);
5331                 }
5332         }
5333         *last = bits[0].start;
5334         bytenr = bits[0].start;
5335         size = bits[0].size;
5336
5337         cache = lookup_cache_extent(pending, bytenr, size);
5338         if (cache) {
5339                 remove_cache_extent(pending, cache);
5340                 free(cache);
5341         }
5342         cache = lookup_cache_extent(reada, bytenr, size);
5343         if (cache) {
5344                 remove_cache_extent(reada, cache);
5345                 free(cache);
5346         }
5347         cache = lookup_cache_extent(nodes, bytenr, size);
5348         if (cache) {
5349                 remove_cache_extent(nodes, cache);
5350                 free(cache);
5351         }
5352         cache = lookup_cache_extent(extent_cache, bytenr, size);
5353         if (cache) {
5354                 struct extent_record *rec;
5355
5356                 rec = container_of(cache, struct extent_record, cache);
5357                 gen = rec->parent_generation;
5358         }
5359
5360         /* fixme, get the real parent transid */
5361         buf = read_tree_block(root, bytenr, size, gen);
5362         if (!extent_buffer_uptodate(buf)) {
5363                 record_bad_block_io(root->fs_info,
5364                                     extent_cache, bytenr, size);
5365                 goto out;
5366         }
5367
5368         nritems = btrfs_header_nritems(buf);
5369
5370         /*
5371          * FIXME, this only works only if we don't have any full
5372          * backref mode.
5373          */
5374         if (!init_extent_tree) {
5375                 ret = btrfs_lookup_extent_info(NULL, root, bytenr,
5376                                        btrfs_header_level(buf), 1, NULL,
5377                                        &flags);
5378                 if (ret < 0)
5379                         goto out;
5380         } else {
5381                 flags = 0;
5382                 ret = calc_extent_flag(root, extent_cache, buf, ri, &flags);
5383                 if (ret < 0)
5384                         goto out;
5385         }
5386
5387         if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5388                 parent = bytenr;
5389                 owner = 0;
5390         } else {
5391                 parent = 0;
5392                 owner = btrfs_header_owner(buf);
5393         }
5394
5395         ret = check_block(trans, root, extent_cache, buf, flags);
5396         if (ret)
5397                 goto out;
5398
5399         if (btrfs_is_leaf(buf)) {
5400                 btree_space_waste += btrfs_leaf_free_space(root, buf);
5401                 for (i = 0; i < nritems; i++) {
5402                         struct btrfs_file_extent_item *fi;
5403                         btrfs_item_key_to_cpu(buf, &key, i);
5404                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
5405                                 process_extent_item(root, extent_cache, buf,
5406                                                     i);
5407                                 continue;
5408                         }
5409                         if (key.type == BTRFS_METADATA_ITEM_KEY) {
5410                                 process_extent_item(root, extent_cache, buf,
5411                                                     i);
5412                                 continue;
5413                         }
5414                         if (key.type == BTRFS_EXTENT_CSUM_KEY) {
5415                                 total_csum_bytes +=
5416                                         btrfs_item_size_nr(buf, i);
5417                                 continue;
5418                         }
5419                         if (key.type == BTRFS_CHUNK_ITEM_KEY) {
5420                                 process_chunk_item(chunk_cache, &key, buf, i);
5421                                 continue;
5422                         }
5423                         if (key.type == BTRFS_DEV_ITEM_KEY) {
5424                                 process_device_item(dev_cache, &key, buf, i);
5425                                 continue;
5426                         }
5427                         if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5428                                 process_block_group_item(block_group_cache,
5429                                         &key, buf, i);
5430                                 continue;
5431                         }
5432                         if (key.type == BTRFS_DEV_EXTENT_KEY) {
5433                                 process_device_extent_item(dev_extent_cache,
5434                                         &key, buf, i);
5435                                 continue;
5436
5437                         }
5438                         if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
5439 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5440                                 process_extent_ref_v0(extent_cache, buf, i);
5441 #else
5442                                 BUG();
5443 #endif
5444                                 continue;
5445                         }
5446
5447                         if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
5448                                 add_tree_backref(extent_cache, key.objectid, 0,
5449                                                  key.offset, 0);
5450                                 continue;
5451                         }
5452                         if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
5453                                 add_tree_backref(extent_cache, key.objectid,
5454                                                  key.offset, 0, 0);
5455                                 continue;
5456                         }
5457                         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
5458                                 struct btrfs_extent_data_ref *ref;
5459                                 ref = btrfs_item_ptr(buf, i,
5460                                                 struct btrfs_extent_data_ref);
5461                                 add_data_backref(extent_cache,
5462                                         key.objectid, 0,
5463                                         btrfs_extent_data_ref_root(buf, ref),
5464                                         btrfs_extent_data_ref_objectid(buf,
5465                                                                        ref),
5466                                         btrfs_extent_data_ref_offset(buf, ref),
5467                                         btrfs_extent_data_ref_count(buf, ref),
5468                                         0, root->sectorsize);
5469                                 continue;
5470                         }
5471                         if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
5472                                 struct btrfs_shared_data_ref *ref;
5473                                 ref = btrfs_item_ptr(buf, i,
5474                                                 struct btrfs_shared_data_ref);
5475                                 add_data_backref(extent_cache,
5476                                         key.objectid, key.offset, 0, 0, 0,
5477                                         btrfs_shared_data_ref_count(buf, ref),
5478                                         0, root->sectorsize);
5479                                 continue;
5480                         }
5481                         if (key.type == BTRFS_ORPHAN_ITEM_KEY) {
5482                                 struct bad_item *bad;
5483
5484                                 if (key.objectid == BTRFS_ORPHAN_OBJECTID)
5485                                         continue;
5486                                 if (!owner)
5487                                         continue;
5488                                 bad = malloc(sizeof(struct bad_item));
5489                                 if (!bad)
5490                                         continue;
5491                                 INIT_LIST_HEAD(&bad->list);
5492                                 memcpy(&bad->key, &key,
5493                                        sizeof(struct btrfs_key));
5494                                 bad->root_id = owner;
5495                                 list_add_tail(&bad->list, &delete_items);
5496                                 continue;
5497                         }
5498                         if (key.type != BTRFS_EXTENT_DATA_KEY)
5499                                 continue;
5500                         fi = btrfs_item_ptr(buf, i,
5501                                             struct btrfs_file_extent_item);
5502                         if (btrfs_file_extent_type(buf, fi) ==
5503                             BTRFS_FILE_EXTENT_INLINE)
5504                                 continue;
5505                         if (btrfs_file_extent_disk_bytenr(buf, fi) == 0)
5506                                 continue;
5507
5508                         data_bytes_allocated +=
5509                                 btrfs_file_extent_disk_num_bytes(buf, fi);
5510                         if (data_bytes_allocated < root->sectorsize) {
5511                                 abort();
5512                         }
5513                         data_bytes_referenced +=
5514                                 btrfs_file_extent_num_bytes(buf, fi);
5515                         add_data_backref(extent_cache,
5516                                 btrfs_file_extent_disk_bytenr(buf, fi),
5517                                 parent, owner, key.objectid, key.offset -
5518                                 btrfs_file_extent_offset(buf, fi), 1, 1,
5519                                 btrfs_file_extent_disk_num_bytes(buf, fi));
5520                 }
5521         } else {
5522                 int level;
5523                 struct btrfs_key first_key;
5524
5525                 first_key.objectid = 0;
5526
5527                 if (nritems > 0)
5528                         btrfs_item_key_to_cpu(buf, &first_key, 0);
5529                 level = btrfs_header_level(buf);
5530                 for (i = 0; i < nritems; i++) {
5531                         ptr = btrfs_node_blockptr(buf, i);
5532                         size = btrfs_level_size(root, level - 1);
5533                         btrfs_node_key_to_cpu(buf, &key, i);
5534                         if (ri != NULL) {
5535                                 if ((level == ri->drop_level)
5536                                     && is_dropped_key(&key, &ri->drop_key)) {
5537                                         continue;
5538                                 }
5539                         }
5540                         ret = add_extent_rec(extent_cache, &key,
5541                                              btrfs_node_ptr_generation(buf, i),
5542                                              ptr, size, 0, 0, 1, 0, 1, 0,
5543                                              size);
5544                         BUG_ON(ret);
5545
5546                         add_tree_backref(extent_cache, ptr, parent, owner, 1);
5547
5548                         if (level > 1) {
5549                                 add_pending(nodes, seen, ptr, size);
5550                         } else {
5551                                 add_pending(pending, seen, ptr, size);
5552                         }
5553                 }
5554                 btree_space_waste += (BTRFS_NODEPTRS_PER_BLOCK(root) -
5555                                       nritems) * sizeof(struct btrfs_key_ptr);
5556         }
5557         total_btree_bytes += buf->len;
5558         if (fs_root_objectid(btrfs_header_owner(buf)))
5559                 total_fs_tree_bytes += buf->len;
5560         if (btrfs_header_owner(buf) == BTRFS_EXTENT_TREE_OBJECTID)
5561                 total_extent_tree_bytes += buf->len;
5562         if (!found_old_backref &&
5563             btrfs_header_owner(buf) == BTRFS_TREE_RELOC_OBJECTID &&
5564             btrfs_header_backref_rev(buf) == BTRFS_MIXED_BACKREF_REV &&
5565             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC))
5566                 found_old_backref = 1;
5567 out:
5568         free_extent_buffer(buf);
5569         return ret;
5570 }
5571
5572 static int add_root_to_pending(struct extent_buffer *buf,
5573                                struct cache_tree *extent_cache,
5574                                struct cache_tree *pending,
5575                                struct cache_tree *seen,
5576                                struct cache_tree *nodes,
5577                                u64 objectid)
5578 {
5579         if (btrfs_header_level(buf) > 0)
5580                 add_pending(nodes, seen, buf->start, buf->len);
5581         else
5582                 add_pending(pending, seen, buf->start, buf->len);
5583         add_extent_rec(extent_cache, NULL, 0, buf->start, buf->len,
5584                        0, 1, 1, 0, 1, 0, buf->len);
5585
5586         if (objectid == BTRFS_TREE_RELOC_OBJECTID ||
5587             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
5588                 add_tree_backref(extent_cache, buf->start, buf->start,
5589                                  0, 1);
5590         else
5591                 add_tree_backref(extent_cache, buf->start, 0, objectid, 1);
5592         return 0;
5593 }
5594
5595 /* as we fix the tree, we might be deleting blocks that
5596  * we're tracking for repair.  This hook makes sure we
5597  * remove any backrefs for blocks as we are fixing them.
5598  */
5599 static int free_extent_hook(struct btrfs_trans_handle *trans,
5600                             struct btrfs_root *root,
5601                             u64 bytenr, u64 num_bytes, u64 parent,
5602                             u64 root_objectid, u64 owner, u64 offset,
5603                             int refs_to_drop)
5604 {
5605         struct extent_record *rec;
5606         struct cache_extent *cache;
5607         int is_data;
5608         struct cache_tree *extent_cache = root->fs_info->fsck_extent_cache;
5609
5610         is_data = owner >= BTRFS_FIRST_FREE_OBJECTID;
5611         cache = lookup_cache_extent(extent_cache, bytenr, num_bytes);
5612         if (!cache)
5613                 return 0;
5614
5615         rec = container_of(cache, struct extent_record, cache);
5616         if (is_data) {
5617                 struct data_backref *back;
5618                 back = find_data_backref(rec, parent, root_objectid, owner,
5619                                          offset, 1, bytenr, num_bytes);
5620                 if (!back)
5621                         goto out;
5622                 if (back->node.found_ref) {
5623                         back->found_ref -= refs_to_drop;
5624                         if (rec->refs)
5625                                 rec->refs -= refs_to_drop;
5626                 }
5627                 if (back->node.found_extent_tree) {
5628                         back->num_refs -= refs_to_drop;
5629                         if (rec->extent_item_refs)
5630                                 rec->extent_item_refs -= refs_to_drop;
5631                 }
5632                 if (back->found_ref == 0)
5633                         back->node.found_ref = 0;
5634                 if (back->num_refs == 0)
5635                         back->node.found_extent_tree = 0;
5636
5637                 if (!back->node.found_extent_tree && back->node.found_ref) {
5638                         list_del(&back->node.list);
5639                         free(back);
5640                 }
5641         } else {
5642                 struct tree_backref *back;
5643                 back = find_tree_backref(rec, parent, root_objectid);
5644                 if (!back)
5645                         goto out;
5646                 if (back->node.found_ref) {
5647                         if (rec->refs)
5648                                 rec->refs--;
5649                         back->node.found_ref = 0;
5650                 }
5651                 if (back->node.found_extent_tree) {
5652                         if (rec->extent_item_refs)
5653                                 rec->extent_item_refs--;
5654                         back->node.found_extent_tree = 0;
5655                 }
5656                 if (!back->node.found_extent_tree && back->node.found_ref) {
5657                         list_del(&back->node.list);
5658                         free(back);
5659                 }
5660         }
5661         maybe_free_extent_rec(extent_cache, rec);
5662 out:
5663         return 0;
5664 }
5665
5666 static int delete_extent_records(struct btrfs_trans_handle *trans,
5667                                  struct btrfs_root *root,
5668                                  struct btrfs_path *path,
5669                                  u64 bytenr, u64 new_len)
5670 {
5671         struct btrfs_key key;
5672         struct btrfs_key found_key;
5673         struct extent_buffer *leaf;
5674         int ret;
5675         int slot;
5676
5677
5678         key.objectid = bytenr;
5679         key.type = (u8)-1;
5680         key.offset = (u64)-1;
5681
5682         while(1) {
5683                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
5684                                         &key, path, 0, 1);
5685                 if (ret < 0)
5686                         break;
5687
5688                 if (ret > 0) {
5689                         ret = 0;
5690                         if (path->slots[0] == 0)
5691                                 break;
5692                         path->slots[0]--;
5693                 }
5694                 ret = 0;
5695
5696                 leaf = path->nodes[0];
5697                 slot = path->slots[0];
5698
5699                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5700                 if (found_key.objectid != bytenr)
5701                         break;
5702
5703                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
5704                     found_key.type != BTRFS_METADATA_ITEM_KEY &&
5705                     found_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
5706                     found_key.type != BTRFS_EXTENT_DATA_REF_KEY &&
5707                     found_key.type != BTRFS_EXTENT_REF_V0_KEY &&
5708                     found_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
5709                     found_key.type != BTRFS_SHARED_DATA_REF_KEY) {
5710                         btrfs_release_path(path);
5711                         if (found_key.type == 0) {
5712                                 if (found_key.offset == 0)
5713                                         break;
5714                                 key.offset = found_key.offset - 1;
5715                                 key.type = found_key.type;
5716                         }
5717                         key.type = found_key.type - 1;
5718                         key.offset = (u64)-1;
5719                         continue;
5720                 }
5721
5722                 fprintf(stderr, "repair deleting extent record: key %Lu %u %Lu\n",
5723                         found_key.objectid, found_key.type, found_key.offset);
5724
5725                 ret = btrfs_del_item(trans, root->fs_info->extent_root, path);
5726                 if (ret)
5727                         break;
5728                 btrfs_release_path(path);
5729
5730                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5731                     found_key.type == BTRFS_METADATA_ITEM_KEY) {
5732                         u64 bytes = (found_key.type == BTRFS_EXTENT_ITEM_KEY) ?
5733                                 found_key.offset : root->leafsize;
5734
5735                         ret = btrfs_update_block_group(trans, root, bytenr,
5736                                                        bytes, 0, 0);
5737                         if (ret)
5738                                 break;
5739                 }
5740         }
5741
5742         btrfs_release_path(path);
5743         return ret;
5744 }
5745
5746 /*
5747  * for a single backref, this will allocate a new extent
5748  * and add the backref to it.
5749  */
5750 static int record_extent(struct btrfs_trans_handle *trans,
5751                          struct btrfs_fs_info *info,
5752                          struct btrfs_path *path,
5753                          struct extent_record *rec,
5754                          struct extent_backref *back,
5755                          int allocated, u64 flags)
5756 {
5757         int ret;
5758         struct btrfs_root *extent_root = info->extent_root;
5759         struct extent_buffer *leaf;
5760         struct btrfs_key ins_key;
5761         struct btrfs_extent_item *ei;
5762         struct tree_backref *tback;
5763         struct data_backref *dback;
5764         struct btrfs_tree_block_info *bi;
5765
5766         if (!back->is_data)
5767                 rec->max_size = max_t(u64, rec->max_size,
5768                                     info->extent_root->leafsize);
5769
5770         if (!allocated) {
5771                 u32 item_size = sizeof(*ei);
5772
5773                 if (!back->is_data)
5774                         item_size += sizeof(*bi);
5775
5776                 ins_key.objectid = rec->start;
5777                 ins_key.offset = rec->max_size;
5778                 ins_key.type = BTRFS_EXTENT_ITEM_KEY;
5779
5780                 ret = btrfs_insert_empty_item(trans, extent_root, path,
5781                                         &ins_key, item_size);
5782                 if (ret)
5783                         goto fail;
5784
5785                 leaf = path->nodes[0];
5786                 ei = btrfs_item_ptr(leaf, path->slots[0],
5787                                     struct btrfs_extent_item);
5788
5789                 btrfs_set_extent_refs(leaf, ei, 0);
5790                 btrfs_set_extent_generation(leaf, ei, rec->generation);
5791
5792                 if (back->is_data) {
5793                         btrfs_set_extent_flags(leaf, ei,
5794                                                BTRFS_EXTENT_FLAG_DATA);
5795                 } else {
5796                         struct btrfs_disk_key copy_key;;
5797
5798                         tback = (struct tree_backref *)back;
5799                         bi = (struct btrfs_tree_block_info *)(ei + 1);
5800                         memset_extent_buffer(leaf, 0, (unsigned long)bi,
5801                                              sizeof(*bi));
5802
5803                         btrfs_set_disk_key_objectid(&copy_key,
5804                                                     rec->info_objectid);
5805                         btrfs_set_disk_key_type(&copy_key, 0);
5806                         btrfs_set_disk_key_offset(&copy_key, 0);
5807
5808                         btrfs_set_tree_block_level(leaf, bi, rec->info_level);
5809                         btrfs_set_tree_block_key(leaf, bi, &copy_key);
5810
5811                         btrfs_set_extent_flags(leaf, ei,
5812                                                BTRFS_EXTENT_FLAG_TREE_BLOCK | flags);
5813                 }
5814
5815                 btrfs_mark_buffer_dirty(leaf);
5816                 ret = btrfs_update_block_group(trans, extent_root, rec->start,
5817                                                rec->max_size, 1, 0);
5818                 if (ret)
5819                         goto fail;
5820                 btrfs_release_path(path);
5821         }
5822
5823         if (back->is_data) {
5824                 u64 parent;
5825                 int i;
5826
5827                 dback = (struct data_backref *)back;
5828                 if (back->full_backref)
5829                         parent = dback->parent;
5830                 else
5831                         parent = 0;
5832
5833                 for (i = 0; i < dback->found_ref; i++) {
5834                         /* if parent != 0, we're doing a full backref
5835                          * passing BTRFS_FIRST_FREE_OBJECTID as the owner
5836                          * just makes the backref allocator create a data
5837                          * backref
5838                          */
5839                         ret = btrfs_inc_extent_ref(trans, info->extent_root,
5840                                                    rec->start, rec->max_size,
5841                                                    parent,
5842                                                    dback->root,
5843                                                    parent ?
5844                                                    BTRFS_FIRST_FREE_OBJECTID :
5845                                                    dback->owner,
5846                                                    dback->offset);
5847                         if (ret)
5848                                 break;
5849                 }
5850                 fprintf(stderr, "adding new data backref"
5851                                 " on %llu %s %llu owner %llu"
5852                                 " offset %llu found %d\n",
5853                                 (unsigned long long)rec->start,
5854                                 back->full_backref ?
5855                                 "parent" : "root",
5856                                 back->full_backref ?
5857                                 (unsigned long long)parent :
5858                                 (unsigned long long)dback->root,
5859                                 (unsigned long long)dback->owner,
5860                                 (unsigned long long)dback->offset,
5861                                 dback->found_ref);
5862         } else {
5863                 u64 parent;
5864
5865                 tback = (struct tree_backref *)back;
5866                 if (back->full_backref)
5867                         parent = tback->parent;
5868                 else
5869                         parent = 0;
5870
5871                 ret = btrfs_inc_extent_ref(trans, info->extent_root,
5872                                            rec->start, rec->max_size,
5873                                            parent, tback->root, 0, 0);
5874                 fprintf(stderr, "adding new tree backref on "
5875                         "start %llu len %llu parent %llu root %llu\n",
5876                         rec->start, rec->max_size, tback->parent, tback->root);
5877         }
5878         if (ret)
5879                 goto fail;
5880 fail:
5881         btrfs_release_path(path);
5882         return ret;
5883 }
5884
5885 struct extent_entry {
5886         u64 bytenr;
5887         u64 bytes;
5888         int count;
5889         int broken;
5890         struct list_head list;
5891 };
5892
5893 static struct extent_entry *find_entry(struct list_head *entries,
5894                                        u64 bytenr, u64 bytes)
5895 {
5896         struct extent_entry *entry = NULL;
5897
5898         list_for_each_entry(entry, entries, list) {
5899                 if (entry->bytenr == bytenr && entry->bytes == bytes)
5900                         return entry;
5901         }
5902
5903         return NULL;
5904 }
5905
5906 static struct extent_entry *find_most_right_entry(struct list_head *entries)
5907 {
5908         struct extent_entry *entry, *best = NULL, *prev = NULL;
5909
5910         list_for_each_entry(entry, entries, list) {
5911                 if (!prev) {
5912                         prev = entry;
5913                         continue;
5914                 }
5915
5916                 /*
5917                  * If there are as many broken entries as entries then we know
5918                  * not to trust this particular entry.
5919                  */
5920                 if (entry->broken == entry->count)
5921                         continue;
5922
5923                 /*
5924                  * If our current entry == best then we can't be sure our best
5925                  * is really the best, so we need to keep searching.
5926                  */
5927                 if (best && best->count == entry->count) {
5928                         prev = entry;
5929                         best = NULL;
5930                         continue;
5931                 }
5932
5933                 /* Prev == entry, not good enough, have to keep searching */
5934                 if (!prev->broken && prev->count == entry->count)
5935                         continue;
5936
5937                 if (!best)
5938                         best = (prev->count > entry->count) ? prev : entry;
5939                 else if (best->count < entry->count)
5940                         best = entry;
5941                 prev = entry;
5942         }
5943
5944         return best;
5945 }
5946
5947 static int repair_ref(struct btrfs_trans_handle *trans,
5948                       struct btrfs_fs_info *info, struct btrfs_path *path,
5949                       struct data_backref *dback, struct extent_entry *entry)
5950 {
5951         struct btrfs_root *root;
5952         struct btrfs_file_extent_item *fi;
5953         struct extent_buffer *leaf;
5954         struct btrfs_key key;
5955         u64 bytenr, bytes;
5956         int ret;
5957
5958         key.objectid = dback->root;
5959         key.type = BTRFS_ROOT_ITEM_KEY;
5960         key.offset = (u64)-1;
5961         root = btrfs_read_fs_root(info, &key);
5962         if (IS_ERR(root)) {
5963                 fprintf(stderr, "Couldn't find root for our ref\n");
5964                 return -EINVAL;
5965         }
5966
5967         /*
5968          * The backref points to the original offset of the extent if it was
5969          * split, so we need to search down to the offset we have and then walk
5970          * forward until we find the backref we're looking for.
5971          */
5972         key.objectid = dback->owner;
5973         key.type = BTRFS_EXTENT_DATA_KEY;
5974         key.offset = dback->offset;
5975         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5976         if (ret < 0) {
5977                 fprintf(stderr, "Error looking up ref %d\n", ret);
5978                 return ret;
5979         }
5980
5981         while (1) {
5982                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5983                         ret = btrfs_next_leaf(root, path);
5984                         if (ret) {
5985                                 fprintf(stderr, "Couldn't find our ref, next\n");
5986                                 return -EINVAL;
5987                         }
5988                 }
5989                 leaf = path->nodes[0];
5990                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5991                 if (key.objectid != dback->owner ||
5992                     key.type != BTRFS_EXTENT_DATA_KEY) {
5993                         fprintf(stderr, "Couldn't find our ref, search\n");
5994                         return -EINVAL;
5995                 }
5996                 fi = btrfs_item_ptr(leaf, path->slots[0],
5997                                     struct btrfs_file_extent_item);
5998                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5999                 bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6000
6001                 if (bytenr == dback->disk_bytenr && bytes == dback->bytes)
6002                         break;
6003                 path->slots[0]++;
6004         }
6005
6006         btrfs_release_path(path);
6007
6008         /*
6009          * Have to make sure that this root gets updated when we commit the
6010          * transaction
6011          */
6012         record_root_in_trans(trans, root);
6013
6014         /*
6015          * Ok we have the key of the file extent we want to fix, now we can cow
6016          * down to the thing and fix it.
6017          */
6018         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6019         if (ret < 0) {
6020                 fprintf(stderr, "Error cowing down to ref [%Lu, %u, %Lu]: %d\n",
6021                         key.objectid, key.type, key.offset, ret);
6022                 return ret;
6023         }
6024         if (ret > 0) {
6025                 fprintf(stderr, "Well that's odd, we just found this key "
6026                         "[%Lu, %u, %Lu]\n", key.objectid, key.type,
6027                         key.offset);
6028                 return -EINVAL;
6029         }
6030         leaf = path->nodes[0];
6031         fi = btrfs_item_ptr(leaf, path->slots[0],
6032                             struct btrfs_file_extent_item);
6033
6034         if (btrfs_file_extent_compression(leaf, fi) &&
6035             dback->disk_bytenr != entry->bytenr) {
6036                 fprintf(stderr, "Ref doesn't match the record start and is "
6037                         "compressed, please take a btrfs-image of this file "
6038                         "system and send it to a btrfs developer so they can "
6039                         "complete this functionality for bytenr %Lu\n",
6040                         dback->disk_bytenr);
6041                 return -EINVAL;
6042         }
6043
6044         if (dback->node.broken && dback->disk_bytenr != entry->bytenr) {
6045                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6046         } else if (dback->disk_bytenr > entry->bytenr) {
6047                 u64 off_diff, offset;
6048
6049                 off_diff = dback->disk_bytenr - entry->bytenr;
6050                 offset = btrfs_file_extent_offset(leaf, fi);
6051                 if (dback->disk_bytenr + offset +
6052                     btrfs_file_extent_num_bytes(leaf, fi) >
6053                     entry->bytenr + entry->bytes) {
6054                         fprintf(stderr, "Ref is past the entry end, please "
6055                                 "take a btrfs-image of this file system and "
6056                                 "send it to a btrfs developer, ref %Lu\n",
6057                                 dback->disk_bytenr);
6058                         return -EINVAL;
6059                 }
6060                 offset += off_diff;
6061                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6062                 btrfs_set_file_extent_offset(leaf, fi, offset);
6063         } else if (dback->disk_bytenr < entry->bytenr) {
6064                 u64 offset;
6065
6066                 offset = btrfs_file_extent_offset(leaf, fi);
6067                 if (dback->disk_bytenr + offset < entry->bytenr) {
6068                         fprintf(stderr, "Ref is before the entry start, please"
6069                                 " take a btrfs-image of this file system and "
6070                                 "send it to a btrfs developer, ref %Lu\n",
6071                                 dback->disk_bytenr);
6072                         return -EINVAL;
6073                 }
6074
6075                 offset += dback->disk_bytenr;
6076                 offset -= entry->bytenr;
6077                 btrfs_set_file_extent_disk_bytenr(leaf, fi, entry->bytenr);
6078                 btrfs_set_file_extent_offset(leaf, fi, offset);
6079         }
6080
6081         btrfs_set_file_extent_disk_num_bytes(leaf, fi, entry->bytes);
6082
6083         /*
6084          * Chances are if disk_num_bytes were wrong then so is ram_bytes, but
6085          * only do this if we aren't using compression, otherwise it's a
6086          * trickier case.
6087          */
6088         if (!btrfs_file_extent_compression(leaf, fi))
6089                 btrfs_set_file_extent_ram_bytes(leaf, fi, entry->bytes);
6090         else
6091                 printf("ram bytes may be wrong?\n");
6092         btrfs_mark_buffer_dirty(leaf);
6093         btrfs_release_path(path);
6094         return 0;
6095 }
6096
6097 static int verify_backrefs(struct btrfs_trans_handle *trans,
6098                            struct btrfs_fs_info *info, struct btrfs_path *path,
6099                            struct extent_record *rec)
6100 {
6101         struct extent_backref *back;
6102         struct data_backref *dback;
6103         struct extent_entry *entry, *best = NULL;
6104         LIST_HEAD(entries);
6105         int nr_entries = 0;
6106         int broken_entries = 0;
6107         int ret = 0;
6108         short mismatch = 0;
6109
6110         /*
6111          * Metadata is easy and the backrefs should always agree on bytenr and
6112          * size, if not we've got bigger issues.
6113          */
6114         if (rec->metadata)
6115                 return 0;
6116
6117         list_for_each_entry(back, &rec->backrefs, list) {
6118                 if (back->full_backref || !back->is_data)
6119                         continue;
6120
6121                 dback = (struct data_backref *)back;
6122
6123                 /*
6124                  * We only pay attention to backrefs that we found a real
6125                  * backref for.
6126                  */
6127                 if (dback->found_ref == 0)
6128                         continue;
6129
6130                 /*
6131                  * For now we only catch when the bytes don't match, not the
6132                  * bytenr.  We can easily do this at the same time, but I want
6133                  * to have a fs image to test on before we just add repair
6134                  * functionality willy-nilly so we know we won't screw up the
6135                  * repair.
6136                  */
6137
6138                 entry = find_entry(&entries, dback->disk_bytenr,
6139                                    dback->bytes);
6140                 if (!entry) {
6141                         entry = malloc(sizeof(struct extent_entry));
6142                         if (!entry) {
6143                                 ret = -ENOMEM;
6144                                 goto out;
6145                         }
6146                         memset(entry, 0, sizeof(*entry));
6147                         entry->bytenr = dback->disk_bytenr;
6148                         entry->bytes = dback->bytes;
6149                         list_add_tail(&entry->list, &entries);
6150                         nr_entries++;
6151                 }
6152
6153                 /*
6154                  * If we only have on entry we may think the entries agree when
6155                  * in reality they don't so we have to do some extra checking.
6156                  */
6157                 if (dback->disk_bytenr != rec->start ||
6158                     dback->bytes != rec->nr || back->broken)
6159                         mismatch = 1;
6160
6161                 if (back->broken) {
6162                         entry->broken++;
6163                         broken_entries++;
6164                 }
6165
6166                 entry->count++;
6167         }
6168
6169         /* Yay all the backrefs agree, carry on good sir */
6170         if (nr_entries <= 1 && !mismatch)
6171                 goto out;
6172
6173         fprintf(stderr, "attempting to repair backref discrepency for bytenr "
6174                 "%Lu\n", rec->start);
6175
6176         /*
6177          * First we want to see if the backrefs can agree amongst themselves who
6178          * is right, so figure out which one of the entries has the highest
6179          * count.
6180          */
6181         best = find_most_right_entry(&entries);
6182
6183         /*
6184          * Ok so we may have an even split between what the backrefs think, so
6185          * this is where we use the extent ref to see what it thinks.
6186          */
6187         if (!best) {
6188                 entry = find_entry(&entries, rec->start, rec->nr);
6189                 if (!entry && (!broken_entries || !rec->found_rec)) {
6190                         fprintf(stderr, "Backrefs don't agree with each other "
6191                                 "and extent record doesn't agree with anybody,"
6192                                 " so we can't fix bytenr %Lu bytes %Lu\n",
6193                                 rec->start, rec->nr);
6194                         ret = -EINVAL;
6195                         goto out;
6196                 } else if (!entry) {
6197                         /*
6198                          * Ok our backrefs were broken, we'll assume this is the
6199                          * correct value and add an entry for this range.
6200                          */
6201                         entry = malloc(sizeof(struct extent_entry));
6202                         if (!entry) {
6203                                 ret = -ENOMEM;
6204                                 goto out;
6205                         }
6206                         memset(entry, 0, sizeof(*entry));
6207                         entry->bytenr = rec->start;
6208                         entry->bytes = rec->nr;
6209                         list_add_tail(&entry->list, &entries);
6210                         nr_entries++;
6211                 }
6212                 entry->count++;
6213                 best = find_most_right_entry(&entries);
6214                 if (!best) {
6215                         fprintf(stderr, "Backrefs and extent record evenly "
6216                                 "split on who is right, this is going to "
6217                                 "require user input to fix bytenr %Lu bytes "
6218                                 "%Lu\n", rec->start, rec->nr);
6219                         ret = -EINVAL;
6220                         goto out;
6221                 }
6222         }
6223
6224         /*
6225          * I don't think this can happen currently as we'll abort() if we catch
6226          * this case higher up, but in case somebody removes that we still can't
6227          * deal with it properly here yet, so just bail out of that's the case.
6228          */
6229         if (best->bytenr != rec->start) {
6230                 fprintf(stderr, "Extent start and backref starts don't match, "
6231                         "please use btrfs-image on this file system and send "
6232                         "it to a btrfs developer so they can make fsck fix "
6233                         "this particular case.  bytenr is %Lu, bytes is %Lu\n",
6234                         rec->start, rec->nr);
6235                 ret = -EINVAL;
6236                 goto out;
6237         }
6238
6239         /*
6240          * Ok great we all agreed on an extent record, let's go find the real
6241          * references and fix up the ones that don't match.
6242          */
6243         list_for_each_entry(back, &rec->backrefs, list) {
6244                 if (back->full_backref || !back->is_data)
6245                         continue;
6246
6247                 dback = (struct data_backref *)back;
6248
6249                 /*
6250                  * Still ignoring backrefs that don't have a real ref attached
6251                  * to them.
6252                  */
6253                 if (dback->found_ref == 0)
6254                         continue;
6255
6256                 if (dback->bytes == best->bytes &&
6257                     dback->disk_bytenr == best->bytenr)
6258                         continue;
6259
6260                 ret = repair_ref(trans, info, path, dback, best);
6261                 if (ret)
6262                         goto out;
6263         }
6264
6265         /*
6266          * Ok we messed with the actual refs, which means we need to drop our
6267          * entire cache and go back and rescan.  I know this is a huge pain and
6268          * adds a lot of extra work, but it's the only way to be safe.  Once all
6269          * the backrefs agree we may not need to do anything to the extent
6270          * record itself.
6271          */
6272         ret = -EAGAIN;
6273 out:
6274         while (!list_empty(&entries)) {
6275                 entry = list_entry(entries.next, struct extent_entry, list);
6276                 list_del_init(&entry->list);
6277                 free(entry);
6278         }
6279         return ret;
6280 }
6281
6282 static int process_duplicates(struct btrfs_root *root,
6283                               struct cache_tree *extent_cache,
6284                               struct extent_record *rec)
6285 {
6286         struct extent_record *good, *tmp;
6287         struct cache_extent *cache;
6288         int ret;
6289
6290         /*
6291          * If we found a extent record for this extent then return, or if we
6292          * have more than one duplicate we are likely going to need to delete
6293          * something.
6294          */
6295         if (rec->found_rec || rec->num_duplicates > 1)
6296                 return 0;
6297
6298         /* Shouldn't happen but just in case */
6299         BUG_ON(!rec->num_duplicates);
6300
6301         /*
6302          * So this happens if we end up with a backref that doesn't match the
6303          * actual extent entry.  So either the backref is bad or the extent
6304          * entry is bad.  Either way we want to have the extent_record actually
6305          * reflect what we found in the extent_tree, so we need to take the
6306          * duplicate out and use that as the extent_record since the only way we
6307          * get a duplicate is if we find a real life BTRFS_EXTENT_ITEM_KEY.
6308          */
6309         remove_cache_extent(extent_cache, &rec->cache);
6310
6311         good = list_entry(rec->dups.next, struct extent_record, list);
6312         list_del_init(&good->list);
6313         INIT_LIST_HEAD(&good->backrefs);
6314         INIT_LIST_HEAD(&good->dups);
6315         good->cache.start = good->start;
6316         good->cache.size = good->nr;
6317         good->content_checked = 0;
6318         good->owner_ref_checked = 0;
6319         good->num_duplicates = 0;
6320         good->refs = rec->refs;
6321         list_splice_init(&rec->backrefs, &good->backrefs);
6322         while (1) {
6323                 cache = lookup_cache_extent(extent_cache, good->start,
6324                                             good->nr);
6325                 if (!cache)
6326                         break;
6327                 tmp = container_of(cache, struct extent_record, cache);
6328
6329                 /*
6330                  * If we find another overlapping extent and it's found_rec is
6331                  * set then it's a duplicate and we need to try and delete
6332                  * something.
6333                  */
6334                 if (tmp->found_rec || tmp->num_duplicates > 0) {
6335                         if (list_empty(&good->list))
6336                                 list_add_tail(&good->list,
6337                                               &duplicate_extents);
6338                         good->num_duplicates += tmp->num_duplicates + 1;
6339                         list_splice_init(&tmp->dups, &good->dups);
6340                         list_del_init(&tmp->list);
6341                         list_add_tail(&tmp->list, &good->dups);
6342                         remove_cache_extent(extent_cache, &tmp->cache);
6343                         continue;
6344                 }
6345
6346                 /*
6347                  * Ok we have another non extent item backed extent rec, so lets
6348                  * just add it to this extent and carry on like we did above.
6349                  */
6350                 good->refs += tmp->refs;
6351                 list_splice_init(&tmp->backrefs, &good->backrefs);
6352                 remove_cache_extent(extent_cache, &tmp->cache);
6353                 free(tmp);
6354         }
6355         ret = insert_cache_extent(extent_cache, &good->cache);
6356         BUG_ON(ret);
6357         free(rec);
6358         return good->num_duplicates ? 0 : 1;
6359 }
6360
6361 static int delete_duplicate_records(struct btrfs_trans_handle *trans,
6362                                     struct btrfs_root *root,
6363                                     struct extent_record *rec)
6364 {
6365         LIST_HEAD(delete_list);
6366         struct btrfs_path *path;
6367         struct extent_record *tmp, *good, *n;
6368         int nr_del = 0;
6369         int ret = 0;
6370         struct btrfs_key key;
6371
6372         path = btrfs_alloc_path();
6373         if (!path) {
6374                 ret = -ENOMEM;
6375                 goto out;
6376         }
6377
6378         good = rec;
6379         /* Find the record that covers all of the duplicates. */
6380         list_for_each_entry(tmp, &rec->dups, list) {
6381                 if (good->start < tmp->start)
6382                         continue;
6383                 if (good->nr > tmp->nr)
6384                         continue;
6385
6386                 if (tmp->start + tmp->nr < good->start + good->nr) {
6387                         fprintf(stderr, "Ok we have overlapping extents that "
6388                                 "aren't completely covered by eachother, this "
6389                                 "is going to require more careful thought.  "
6390                                 "The extents are [%Lu-%Lu] and [%Lu-%Lu]\n",
6391                                 tmp->start, tmp->nr, good->start, good->nr);
6392                         abort();
6393                 }
6394                 good = tmp;
6395         }
6396
6397         if (good != rec)
6398                 list_add_tail(&rec->list, &delete_list);
6399
6400         list_for_each_entry_safe(tmp, n, &rec->dups, list) {
6401                 if (tmp == good)
6402                         continue;
6403                 list_move_tail(&tmp->list, &delete_list);
6404         }
6405
6406         root = root->fs_info->extent_root;
6407         list_for_each_entry(tmp, &delete_list, list) {
6408                 if (tmp->found_rec == 0)
6409                         continue;
6410                 key.objectid = tmp->start;
6411                 key.type = BTRFS_EXTENT_ITEM_KEY;
6412                 key.offset = tmp->nr;
6413
6414                 /* Shouldn't happen but just in case */
6415                 if (tmp->metadata) {
6416                         fprintf(stderr, "Well this shouldn't happen, extent "
6417                                 "record overlaps but is metadata? "
6418                                 "[%Lu, %Lu]\n", tmp->start, tmp->nr);
6419                         abort();
6420                 }
6421
6422                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
6423                 if (ret) {
6424                         if (ret > 0)
6425                                 ret = -EINVAL;
6426                         goto out;
6427                 }
6428                 ret = btrfs_del_item(trans, root, path);
6429                 if (ret)
6430                         goto out;
6431                 btrfs_release_path(path);
6432                 nr_del++;
6433         }
6434
6435 out:
6436         while (!list_empty(&delete_list)) {
6437                 tmp = list_entry(delete_list.next, struct extent_record, list);
6438                 list_del_init(&tmp->list);
6439                 if (tmp == rec)
6440                         continue;
6441                 free(tmp);
6442         }
6443
6444         while (!list_empty(&rec->dups)) {
6445                 tmp = list_entry(rec->dups.next, struct extent_record, list);
6446                 list_del_init(&tmp->list);
6447                 free(tmp);
6448         }
6449
6450         btrfs_free_path(path);
6451
6452         if (!ret && !nr_del)
6453                 rec->num_duplicates = 0;
6454
6455         return ret ? ret : nr_del;
6456 }
6457
6458 static int find_possible_backrefs(struct btrfs_trans_handle *trans,
6459                                   struct btrfs_fs_info *info,
6460                                   struct btrfs_path *path,
6461                                   struct cache_tree *extent_cache,
6462                                   struct extent_record *rec)
6463 {
6464         struct btrfs_root *root;
6465         struct extent_backref *back;
6466         struct data_backref *dback;
6467         struct cache_extent *cache;
6468         struct btrfs_file_extent_item *fi;
6469         struct btrfs_key key;
6470         u64 bytenr, bytes;
6471         int ret;
6472
6473         list_for_each_entry(back, &rec->backrefs, list) {
6474                 /* Don't care about full backrefs (poor unloved backrefs) */
6475                 if (back->full_backref || !back->is_data)
6476                         continue;
6477
6478                 dback = (struct data_backref *)back;
6479
6480                 /* We found this one, we don't need to do a lookup */
6481                 if (dback->found_ref)
6482                         continue;
6483
6484                 key.objectid = dback->root;
6485                 key.type = BTRFS_ROOT_ITEM_KEY;
6486                 key.offset = (u64)-1;
6487
6488                 root = btrfs_read_fs_root(info, &key);
6489
6490                 /* No root, definitely a bad ref, skip */
6491                 if (IS_ERR(root) && PTR_ERR(root) == -ENOENT)
6492                         continue;
6493                 /* Other err, exit */
6494                 if (IS_ERR(root))
6495                         return PTR_ERR(root);
6496
6497                 key.objectid = dback->owner;
6498                 key.type = BTRFS_EXTENT_DATA_KEY;
6499                 key.offset = dback->offset;
6500                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6501                 if (ret) {
6502                         btrfs_release_path(path);
6503                         if (ret < 0)
6504                                 return ret;
6505                         /* Didn't find it, we can carry on */
6506                         ret = 0;
6507                         continue;
6508                 }
6509
6510                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6511                                     struct btrfs_file_extent_item);
6512                 bytenr = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
6513                 bytes = btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
6514                 btrfs_release_path(path);
6515                 cache = lookup_cache_extent(extent_cache, bytenr, 1);
6516                 if (cache) {
6517                         struct extent_record *tmp;
6518                         tmp = container_of(cache, struct extent_record, cache);
6519
6520                         /*
6521                          * If we found an extent record for the bytenr for this
6522                          * particular backref then we can't add it to our
6523                          * current extent record.  We only want to add backrefs
6524                          * that don't have a corresponding extent item in the
6525                          * extent tree since they likely belong to this record
6526                          * and we need to fix it if it doesn't match bytenrs.
6527                          */
6528                         if  (tmp->found_rec)
6529                                 continue;
6530                 }
6531
6532                 dback->found_ref += 1;
6533                 dback->disk_bytenr = bytenr;
6534                 dback->bytes = bytes;
6535
6536                 /*
6537                  * Set this so the verify backref code knows not to trust the
6538                  * values in this backref.
6539                  */
6540                 back->broken = 1;
6541         }
6542
6543         return 0;
6544 }
6545
6546 /*
6547  * when an incorrect extent item is found, this will delete
6548  * all of the existing entries for it and recreate them
6549  * based on what the tree scan found.
6550  */
6551 static int fixup_extent_refs(struct btrfs_trans_handle *trans,
6552                              struct btrfs_fs_info *info,
6553                              struct cache_tree *extent_cache,
6554                              struct extent_record *rec)
6555 {
6556         int ret;
6557         struct btrfs_path *path;
6558         struct list_head *cur = rec->backrefs.next;
6559         struct cache_extent *cache;
6560         struct extent_backref *back;
6561         int allocated = 0;
6562         u64 flags = 0;
6563
6564         /*
6565          * remember our flags for recreating the extent.
6566          * FIXME, if we have cleared extent tree, we can not
6567          * lookup extent info in extent tree.
6568          */
6569         if (!init_extent_tree) {
6570                 ret = btrfs_lookup_extent_info(NULL, info->extent_root,
6571                                         rec->start, rec->max_size,
6572                                         rec->metadata, NULL, &flags);
6573                 if (ret < 0)
6574                         return ret;
6575         } else {
6576                 if (rec->flag_block_full_backref)
6577                         flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6578         }
6579
6580         path = btrfs_alloc_path();
6581         if (!path)
6582                 return -ENOMEM;
6583
6584         if (rec->refs != rec->extent_item_refs && !rec->metadata) {
6585                 /*
6586                  * Sometimes the backrefs themselves are so broken they don't
6587                  * get attached to any meaningful rec, so first go back and
6588                  * check any of our backrefs that we couldn't find and throw
6589                  * them into the list if we find the backref so that
6590                  * verify_backrefs can figure out what to do.
6591                  */
6592                 ret = find_possible_backrefs(trans, info, path, extent_cache,
6593                                              rec);
6594                 if (ret < 0)
6595                         goto out;
6596         }
6597
6598         /* step one, make sure all of the backrefs agree */
6599         ret = verify_backrefs(trans, info, path, rec);
6600         if (ret < 0)
6601                 goto out;
6602
6603         /* step two, delete all the existing records */
6604         ret = delete_extent_records(trans, info->extent_root, path,
6605                                     rec->start, rec->max_size);
6606
6607         if (ret < 0)
6608                 goto out;
6609
6610         /* was this block corrupt?  If so, don't add references to it */
6611         cache = lookup_cache_extent(info->corrupt_blocks,
6612                                     rec->start, rec->max_size);
6613         if (cache) {
6614                 ret = 0;
6615                 goto out;
6616         }
6617
6618         /* step three, recreate all the refs we did find */
6619         while(cur != &rec->backrefs) {
6620                 back = list_entry(cur, struct extent_backref, list);
6621                 cur = cur->next;
6622
6623                 /*
6624                  * if we didn't find any references, don't create a
6625                  * new extent record
6626                  */
6627                 if (!back->found_ref)
6628                         continue;
6629
6630                 ret = record_extent(trans, info, path, rec, back, allocated, flags);
6631                 allocated = 1;
6632
6633                 if (ret)
6634                         goto out;
6635         }
6636 out:
6637         btrfs_free_path(path);
6638         return ret;
6639 }
6640
6641 /* right now we only prune from the extent allocation tree */
6642 static int prune_one_block(struct btrfs_trans_handle *trans,
6643                            struct btrfs_fs_info *info,
6644                            struct btrfs_corrupt_block *corrupt)
6645 {
6646         int ret;
6647         struct btrfs_path path;
6648         struct extent_buffer *eb;
6649         u64 found;
6650         int slot;
6651         int nritems;
6652         int level = corrupt->level + 1;
6653
6654         btrfs_init_path(&path);
6655 again:
6656         /* we want to stop at the parent to our busted block */
6657         path.lowest_level = level;
6658
6659         ret = btrfs_search_slot(trans, info->extent_root,
6660                                 &corrupt->key, &path, -1, 1);
6661
6662         if (ret < 0)
6663                 goto out;
6664
6665         eb = path.nodes[level];
6666         if (!eb) {
6667                 ret = -ENOENT;
6668                 goto out;
6669         }
6670
6671         /*
6672          * hopefully the search gave us the block we want to prune,
6673          * lets try that first
6674          */
6675         slot = path.slots[level];
6676         found =  btrfs_node_blockptr(eb, slot);
6677         if (found == corrupt->cache.start)
6678                 goto del_ptr;
6679
6680         nritems = btrfs_header_nritems(eb);
6681
6682         /* the search failed, lets scan this node and hope we find it */
6683         for (slot = 0; slot < nritems; slot++) {
6684                 found =  btrfs_node_blockptr(eb, slot);
6685                 if (found == corrupt->cache.start)
6686                         goto del_ptr;
6687         }
6688         /*
6689          * we couldn't find the bad block.  TODO, search all the nodes for pointers
6690          * to this block
6691          */
6692         if (eb == info->extent_root->node) {
6693                 ret = -ENOENT;
6694                 goto out;
6695         } else {
6696                 level++;
6697                 btrfs_release_path(&path);
6698                 goto again;
6699         }
6700
6701 del_ptr:
6702         printk("deleting pointer to block %Lu\n", corrupt->cache.start);
6703         ret = btrfs_del_ptr(trans, info->extent_root, &path, level, slot);
6704
6705 out:
6706         btrfs_release_path(&path);
6707         return ret;
6708 }
6709
6710 static int prune_corrupt_blocks(struct btrfs_trans_handle *trans,
6711                                 struct btrfs_fs_info *info)
6712 {
6713         struct cache_extent *cache;
6714         struct btrfs_corrupt_block *corrupt;
6715
6716         cache = search_cache_extent(info->corrupt_blocks, 0);
6717         while (1) {
6718                 if (!cache)
6719                         break;
6720                 corrupt = container_of(cache, struct btrfs_corrupt_block, cache);
6721                 prune_one_block(trans, info, corrupt);
6722                 cache = next_cache_extent(cache);
6723         }
6724         return 0;
6725 }
6726
6727 static void reset_cached_block_groups(struct btrfs_fs_info *fs_info)
6728 {
6729         struct btrfs_block_group_cache *cache;
6730         u64 start, end;
6731         int ret;
6732
6733         while (1) {
6734                 ret = find_first_extent_bit(&fs_info->free_space_cache, 0,
6735                                             &start, &end, EXTENT_DIRTY);
6736                 if (ret)
6737                         break;
6738                 clear_extent_dirty(&fs_info->free_space_cache, start, end,
6739                                    GFP_NOFS);
6740         }
6741
6742         start = 0;
6743         while (1) {
6744                 cache = btrfs_lookup_first_block_group(fs_info, start);
6745                 if (!cache)
6746                         break;
6747                 if (cache->cached)
6748                         cache->cached = 0;
6749                 start = cache->key.objectid + cache->key.offset;
6750         }
6751 }
6752
6753 static int check_extent_refs(struct btrfs_trans_handle *trans,
6754                              struct btrfs_root *root,
6755                              struct cache_tree *extent_cache)
6756 {
6757         struct extent_record *rec;
6758         struct cache_extent *cache;
6759         int err = 0;
6760         int ret = 0;
6761         int fixed = 0;
6762         int had_dups = 0;
6763
6764         if (repair) {
6765                 /*
6766                  * if we're doing a repair, we have to make sure
6767                  * we don't allocate from the problem extents.
6768                  * In the worst case, this will be all the
6769                  * extents in the FS
6770                  */
6771                 cache = search_cache_extent(extent_cache, 0);
6772                 while(cache) {
6773                         rec = container_of(cache, struct extent_record, cache);
6774                         btrfs_pin_extent(root->fs_info,
6775                                          rec->start, rec->max_size);
6776                         cache = next_cache_extent(cache);
6777                 }
6778
6779                 /* pin down all the corrupted blocks too */
6780                 cache = search_cache_extent(root->fs_info->corrupt_blocks, 0);
6781                 while(cache) {
6782                         btrfs_pin_extent(root->fs_info,
6783                                          cache->start, cache->size);
6784                         cache = next_cache_extent(cache);
6785                 }
6786                 prune_corrupt_blocks(trans, root->fs_info);
6787                 reset_cached_block_groups(root->fs_info);
6788         }
6789
6790         /*
6791          * We need to delete any duplicate entries we find first otherwise we
6792          * could mess up the extent tree when we have backrefs that actually
6793          * belong to a different extent item and not the weird duplicate one.
6794          */
6795         while (repair && !list_empty(&duplicate_extents)) {
6796                 rec = list_entry(duplicate_extents.next, struct extent_record,
6797                                  list);
6798                 list_del_init(&rec->list);
6799
6800                 /* Sometimes we can find a backref before we find an actual
6801                  * extent, so we need to process it a little bit to see if there
6802                  * truly are multiple EXTENT_ITEM_KEY's for the same range, or
6803                  * if this is a backref screwup.  If we need to delete stuff
6804                  * process_duplicates() will return 0, otherwise it will return
6805                  * 1 and we
6806                  */
6807                 if (process_duplicates(root, extent_cache, rec))
6808                         continue;
6809                 ret = delete_duplicate_records(trans, root, rec);
6810                 if (ret < 0)
6811                         return ret;
6812                 /*
6813                  * delete_duplicate_records will return the number of entries
6814                  * deleted, so if it's greater than 0 then we know we actually
6815                  * did something and we need to remove.
6816                  */
6817                 if (ret)
6818                         had_dups = 1;
6819         }
6820
6821         if (had_dups)
6822                 return -EAGAIN;
6823
6824         while(1) {
6825                 fixed = 0;
6826                 cache = search_cache_extent(extent_cache, 0);
6827                 if (!cache)
6828                         break;
6829                 rec = container_of(cache, struct extent_record, cache);
6830                 if (rec->num_duplicates) {
6831                         fprintf(stderr, "extent item %llu has multiple extent "
6832                                 "items\n", (unsigned long long)rec->start);
6833                         err = 1;
6834                 }
6835
6836                 if (rec->refs != rec->extent_item_refs) {
6837                         fprintf(stderr, "ref mismatch on [%llu %llu] ",
6838                                 (unsigned long long)rec->start,
6839                                 (unsigned long long)rec->nr);
6840                         fprintf(stderr, "extent item %llu, found %llu\n",
6841                                 (unsigned long long)rec->extent_item_refs,
6842                                 (unsigned long long)rec->refs);
6843                         if (!fixed && repair) {
6844                                 ret = fixup_extent_refs(trans, root->fs_info,
6845                                                         extent_cache, rec);
6846                                 if (ret)
6847                                         goto repair_abort;
6848                                 fixed = 1;
6849                         }
6850                         err = 1;
6851
6852                 }
6853                 if (all_backpointers_checked(rec, 1)) {
6854                         fprintf(stderr, "backpointer mismatch on [%llu %llu]\n",
6855                                 (unsigned long long)rec->start,
6856                                 (unsigned long long)rec->nr);
6857
6858                         if (!fixed && repair) {
6859                                 ret = fixup_extent_refs(trans, root->fs_info,
6860                                                         extent_cache, rec);
6861                                 if (ret)
6862                                         goto repair_abort;
6863                                 fixed = 1;
6864                         }
6865
6866                         err = 1;
6867                 }
6868                 if (!rec->owner_ref_checked) {
6869                         fprintf(stderr, "owner ref check failed [%llu %llu]\n",
6870                                 (unsigned long long)rec->start,
6871                                 (unsigned long long)rec->nr);
6872                         if (!fixed && repair) {
6873                                 ret = fixup_extent_refs(trans, root->fs_info,
6874                                                         extent_cache, rec);
6875                                 if (ret)
6876                                         goto repair_abort;
6877                                 fixed = 1;
6878                         }
6879                         err = 1;
6880                 }
6881
6882                 remove_cache_extent(extent_cache, cache);
6883                 free_all_extent_backrefs(rec);
6884                 free(rec);
6885         }
6886 repair_abort:
6887         if (repair) {
6888                 if (ret && ret != -EAGAIN) {
6889                         fprintf(stderr, "failed to repair damaged filesystem, aborting\n");
6890                         exit(1);
6891                 } else if (!ret) {
6892                         btrfs_fix_block_accounting(trans, root);
6893                 }
6894                 if (err)
6895                         fprintf(stderr, "repaired damaged extent references\n");
6896                 return ret;
6897         }
6898         return err;
6899 }
6900
6901 u64 calc_stripe_length(u64 type, u64 length, int num_stripes)
6902 {
6903         u64 stripe_size;
6904
6905         if (type & BTRFS_BLOCK_GROUP_RAID0) {
6906                 stripe_size = length;
6907                 stripe_size /= num_stripes;
6908         } else if (type & BTRFS_BLOCK_GROUP_RAID10) {
6909                 stripe_size = length * 2;
6910                 stripe_size /= num_stripes;
6911         } else if (type & BTRFS_BLOCK_GROUP_RAID5) {
6912                 stripe_size = length;
6913                 stripe_size /= (num_stripes - 1);
6914         } else if (type & BTRFS_BLOCK_GROUP_RAID6) {
6915                 stripe_size = length;
6916                 stripe_size /= (num_stripes - 2);
6917         } else {
6918                 stripe_size = length;
6919         }
6920         return stripe_size;
6921 }
6922
6923 /*
6924  * Check the chunk with its block group/dev list ref:
6925  * Return 0 if all refs seems valid.
6926  * Return 1 if part of refs seems valid, need later check for rebuild ref
6927  * like missing block group and needs to search extent tree to rebuild them.
6928  * Return -1 if essential refs are missing and unable to rebuild.
6929  */
6930 static int check_chunk_refs(struct chunk_record *chunk_rec,
6931                             struct block_group_tree *block_group_cache,
6932                             struct device_extent_tree *dev_extent_cache,
6933                             int silent)
6934 {
6935         struct cache_extent *block_group_item;
6936         struct block_group_record *block_group_rec;
6937         struct cache_extent *dev_extent_item;
6938         struct device_extent_record *dev_extent_rec;
6939         u64 devid;
6940         u64 offset;
6941         u64 length;
6942         int i;
6943         int ret = 0;
6944
6945         block_group_item = lookup_cache_extent(&block_group_cache->tree,
6946                                                chunk_rec->offset,
6947                                                chunk_rec->length);
6948         if (block_group_item) {
6949                 block_group_rec = container_of(block_group_item,
6950                                                struct block_group_record,
6951                                                cache);
6952                 if (chunk_rec->length != block_group_rec->offset ||
6953                     chunk_rec->offset != block_group_rec->objectid ||
6954                     chunk_rec->type_flags != block_group_rec->flags) {
6955                         if (!silent)
6956                                 fprintf(stderr,
6957                                         "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) mismatch with block group[%llu, %u, %llu]: offset(%llu), objectid(%llu), flags(%llu)\n",
6958                                         chunk_rec->objectid,
6959                                         chunk_rec->type,
6960                                         chunk_rec->offset,
6961                                         chunk_rec->length,
6962                                         chunk_rec->offset,
6963                                         chunk_rec->type_flags,
6964                                         block_group_rec->objectid,
6965                                         block_group_rec->type,
6966                                         block_group_rec->offset,
6967                                         block_group_rec->offset,
6968                                         block_group_rec->objectid,
6969                                         block_group_rec->flags);
6970                         ret = -1;
6971                 } else {
6972                         list_del_init(&block_group_rec->list);
6973                         chunk_rec->bg_rec = block_group_rec;
6974                 }
6975         } else {
6976                 if (!silent)
6977                         fprintf(stderr,
6978                                 "Chunk[%llu, %u, %llu]: length(%llu), offset(%llu), type(%llu) is not found in block group\n",
6979                                 chunk_rec->objectid,
6980                                 chunk_rec->type,
6981                                 chunk_rec->offset,
6982                                 chunk_rec->length,
6983                                 chunk_rec->offset,
6984                                 chunk_rec->type_flags);
6985                 ret = 1;
6986         }
6987
6988         length = calc_stripe_length(chunk_rec->type_flags, chunk_rec->length,
6989                                     chunk_rec->num_stripes);
6990         for (i = 0; i < chunk_rec->num_stripes; ++i) {
6991                 devid = chunk_rec->stripes[i].devid;
6992                 offset = chunk_rec->stripes[i].offset;
6993                 dev_extent_item = lookup_cache_extent2(&dev_extent_cache->tree,
6994                                                        devid, offset, length);
6995                 if (dev_extent_item) {
6996                         dev_extent_rec = container_of(dev_extent_item,
6997                                                 struct device_extent_record,
6998                                                 cache);
6999                         if (dev_extent_rec->objectid != devid ||
7000                             dev_extent_rec->offset != offset ||
7001                             dev_extent_rec->chunk_offset != chunk_rec->offset ||
7002                             dev_extent_rec->length != length) {
7003                                 if (!silent)
7004                                         fprintf(stderr,
7005                                                 "Chunk[%llu, %u, %llu] stripe[%llu, %llu] dismatch dev extent[%llu, %llu, %llu]\n",
7006                                                 chunk_rec->objectid,
7007                                                 chunk_rec->type,
7008                                                 chunk_rec->offset,
7009                                                 chunk_rec->stripes[i].devid,
7010                                                 chunk_rec->stripes[i].offset,
7011                                                 dev_extent_rec->objectid,
7012                                                 dev_extent_rec->offset,
7013                                                 dev_extent_rec->length);
7014                                 ret = -1;
7015                         } else {
7016                                 list_move(&dev_extent_rec->chunk_list,
7017                                           &chunk_rec->dextents);
7018                         }
7019                 } else {
7020                         if (!silent)
7021                                 fprintf(stderr,
7022                                         "Chunk[%llu, %u, %llu] stripe[%llu, %llu] is not found in dev extent\n",
7023                                         chunk_rec->objectid,
7024                                         chunk_rec->type,
7025                                         chunk_rec->offset,
7026                                         chunk_rec->stripes[i].devid,
7027                                         chunk_rec->stripes[i].offset);
7028                         ret = -1;
7029                 }
7030         }
7031         return ret;
7032 }
7033
7034 /* check btrfs_chunk -> btrfs_dev_extent / btrfs_block_group_item */
7035 int check_chunks(struct cache_tree *chunk_cache,
7036                  struct block_group_tree *block_group_cache,
7037                  struct device_extent_tree *dev_extent_cache,
7038                  struct list_head *good, struct list_head *bad,
7039                  struct list_head *rebuild, int silent)
7040 {
7041         struct cache_extent *chunk_item;
7042         struct chunk_record *chunk_rec;
7043         struct block_group_record *bg_rec;
7044         struct device_extent_record *dext_rec;
7045         int err;
7046         int ret = 0;
7047
7048         chunk_item = first_cache_extent(chunk_cache);
7049         while (chunk_item) {
7050                 chunk_rec = container_of(chunk_item, struct chunk_record,
7051                                          cache);
7052                 err = check_chunk_refs(chunk_rec, block_group_cache,
7053                                        dev_extent_cache, silent);
7054                 if (err)
7055                         ret = err;
7056                 if (err == 0 && good)
7057                         list_add_tail(&chunk_rec->list, good);
7058                 if (err > 0 && rebuild)
7059                         list_add_tail(&chunk_rec->list, rebuild);
7060                 if (err < 0 && bad)
7061                         list_add_tail(&chunk_rec->list, bad);
7062                 chunk_item = next_cache_extent(chunk_item);
7063         }
7064
7065         list_for_each_entry(bg_rec, &block_group_cache->block_groups, list) {
7066                 if (!silent)
7067                         fprintf(stderr,
7068                                 "Block group[%llu, %llu] (flags = %llu) didn't find the relative chunk.\n",
7069                                 bg_rec->objectid,
7070                                 bg_rec->offset,
7071                                 bg_rec->flags);
7072                 if (!ret)
7073                         ret = 1;
7074         }
7075
7076         list_for_each_entry(dext_rec, &dev_extent_cache->no_chunk_orphans,
7077                             chunk_list) {
7078                 if (!silent)
7079                         fprintf(stderr,
7080                                 "Device extent[%llu, %llu, %llu] didn't find the relative chunk.\n",
7081                                 dext_rec->objectid,
7082                                 dext_rec->offset,
7083                                 dext_rec->length);
7084                 if (!ret)
7085                         ret = 1;
7086         }
7087         return ret;
7088 }
7089
7090
7091 static int check_device_used(struct device_record *dev_rec,
7092                              struct device_extent_tree *dext_cache)
7093 {
7094         struct cache_extent *cache;
7095         struct device_extent_record *dev_extent_rec;
7096         u64 total_byte = 0;
7097
7098         cache = search_cache_extent2(&dext_cache->tree, dev_rec->devid, 0);
7099         while (cache) {
7100                 dev_extent_rec = container_of(cache,
7101                                               struct device_extent_record,
7102                                               cache);
7103                 if (dev_extent_rec->objectid != dev_rec->devid)
7104                         break;
7105
7106                 list_del_init(&dev_extent_rec->device_list);
7107                 total_byte += dev_extent_rec->length;
7108                 cache = next_cache_extent(cache);
7109         }
7110
7111         if (total_byte != dev_rec->byte_used) {
7112                 fprintf(stderr,
7113                         "Dev extent's total-byte(%llu) is not equal to byte-used(%llu) in dev[%llu, %u, %llu]\n",
7114                         total_byte, dev_rec->byte_used, dev_rec->objectid,
7115                         dev_rec->type, dev_rec->offset);
7116                 return -1;
7117         } else {
7118                 return 0;
7119         }
7120 }
7121
7122 /* check btrfs_dev_item -> btrfs_dev_extent */
7123 static int check_devices(struct rb_root *dev_cache,
7124                          struct device_extent_tree *dev_extent_cache)
7125 {
7126         struct rb_node *dev_node;
7127         struct device_record *dev_rec;
7128         struct device_extent_record *dext_rec;
7129         int err;
7130         int ret = 0;
7131
7132         dev_node = rb_first(dev_cache);
7133         while (dev_node) {
7134                 dev_rec = container_of(dev_node, struct device_record, node);
7135                 err = check_device_used(dev_rec, dev_extent_cache);
7136                 if (err)
7137                         ret = err;
7138
7139                 dev_node = rb_next(dev_node);
7140         }
7141         list_for_each_entry(dext_rec, &dev_extent_cache->no_device_orphans,
7142                             device_list) {
7143                 fprintf(stderr,
7144                         "Device extent[%llu, %llu, %llu] didn't find its device.\n",
7145                         dext_rec->objectid, dext_rec->offset, dext_rec->length);
7146                 if (!ret)
7147                         ret = 1;
7148         }
7149         return ret;
7150 }
7151
7152 static int add_root_item_to_list(struct list_head *head,
7153                                   u64 objectid, u64 bytenr,
7154                                   u8 level, u8 drop_level,
7155                                   int level_size, struct btrfs_key *drop_key)
7156 {
7157
7158         struct root_item_record *ri_rec;
7159         ri_rec = malloc(sizeof(*ri_rec));
7160         if (!ri_rec)
7161                 return -ENOMEM;
7162         ri_rec->bytenr = bytenr;
7163         ri_rec->objectid = objectid;
7164         ri_rec->level = level;
7165         ri_rec->level_size = level_size;
7166         ri_rec->drop_level = drop_level;
7167         if (drop_key)
7168                 memcpy(&ri_rec->drop_key, drop_key, sizeof(*drop_key));
7169         list_add_tail(&ri_rec->list, head);
7170
7171         return 0;
7172 }
7173
7174 static int deal_root_from_list(struct list_head *list,
7175                                struct btrfs_trans_handle *trans,
7176                                struct btrfs_root *root,
7177                                struct block_info *bits,
7178                                int bits_nr,
7179                                struct cache_tree *pending,
7180                                struct cache_tree *seen,
7181                                struct cache_tree *reada,
7182                                struct cache_tree *nodes,
7183                                struct cache_tree *extent_cache,
7184                                struct cache_tree *chunk_cache,
7185                                struct rb_root *dev_cache,
7186                                struct block_group_tree *block_group_cache,
7187                                struct device_extent_tree *dev_extent_cache)
7188 {
7189         int ret = 0;
7190         u64 last;
7191
7192         while (!list_empty(list)) {
7193                 struct root_item_record *rec;
7194                 struct extent_buffer *buf;
7195                 rec = list_entry(list->next,
7196                                  struct root_item_record, list);
7197                 last = 0;
7198                 buf = read_tree_block(root->fs_info->tree_root,
7199                                       rec->bytenr, rec->level_size, 0);
7200                 if (!extent_buffer_uptodate(buf)) {
7201                         free_extent_buffer(buf);
7202                         ret = -EIO;
7203                         break;
7204                 }
7205                 add_root_to_pending(buf, extent_cache, pending,
7206                                     seen, nodes, rec->objectid);
7207                 /*
7208                  * To rebuild extent tree, we need deal with snapshot
7209                  * one by one, otherwise we deal with node firstly which
7210                  * can maximize readahead.
7211                  */
7212                 if (!init_extent_tree && !rec->drop_level)
7213                         goto skip;
7214                 while (1) {
7215                         ret = run_next_block(trans, root, bits, bits_nr, &last,
7216                                              pending, seen, reada,
7217                                              nodes, extent_cache,
7218                                              chunk_cache, dev_cache,
7219                                              block_group_cache,
7220                                              dev_extent_cache, rec);
7221                         if (ret != 0)
7222                                 break;
7223                 }
7224 skip:
7225                 free_extent_buffer(buf);
7226                 list_del(&rec->list);
7227                 free(rec);
7228         }
7229         while (ret >= 0) {
7230                 ret = run_next_block(trans, root, bits, bits_nr, &last,
7231                                      pending, seen, reada,
7232                                      nodes, extent_cache,
7233                                      chunk_cache, dev_cache,
7234                                      block_group_cache,
7235                                      dev_extent_cache, NULL);
7236                 if (ret != 0) {
7237                         if (ret > 0)
7238                                 ret = 0;
7239                         break;
7240                 }
7241         }
7242         return ret;
7243 }
7244
7245 static int check_chunks_and_extents(struct btrfs_root *root)
7246 {
7247         struct rb_root dev_cache;
7248         struct cache_tree chunk_cache;
7249         struct block_group_tree block_group_cache;
7250         struct device_extent_tree dev_extent_cache;
7251         struct cache_tree extent_cache;
7252         struct cache_tree seen;
7253         struct cache_tree pending;
7254         struct cache_tree reada;
7255         struct cache_tree nodes;
7256         struct cache_tree corrupt_blocks;
7257         struct btrfs_path path;
7258         struct btrfs_key key;
7259         struct btrfs_key found_key;
7260         int ret, err = 0;
7261         struct block_info *bits;
7262         int bits_nr;
7263         struct extent_buffer *leaf;
7264         struct btrfs_trans_handle *trans = NULL;
7265         int slot;
7266         struct btrfs_root_item ri;
7267         struct list_head dropping_trees;
7268         struct list_head normal_trees;
7269         struct btrfs_root *root1;
7270         u64 objectid;
7271         u32 level_size;
7272         u8 level;
7273
7274         dev_cache = RB_ROOT;
7275         cache_tree_init(&chunk_cache);
7276         block_group_tree_init(&block_group_cache);
7277         device_extent_tree_init(&dev_extent_cache);
7278
7279         cache_tree_init(&extent_cache);
7280         cache_tree_init(&seen);
7281         cache_tree_init(&pending);
7282         cache_tree_init(&nodes);
7283         cache_tree_init(&reada);
7284         cache_tree_init(&corrupt_blocks);
7285         INIT_LIST_HEAD(&dropping_trees);
7286         INIT_LIST_HEAD(&normal_trees);
7287
7288         if (repair) {
7289                 trans = btrfs_start_transaction(root, 1);
7290                 if (IS_ERR(trans)) {
7291                         fprintf(stderr, "Error starting transaction\n");
7292                         return PTR_ERR(trans);
7293                 }
7294                 root->fs_info->fsck_extent_cache = &extent_cache;
7295                 root->fs_info->free_extent_hook = free_extent_hook;
7296                 root->fs_info->corrupt_blocks = &corrupt_blocks;
7297         }
7298
7299         bits_nr = 1024;
7300         bits = malloc(bits_nr * sizeof(struct block_info));
7301         if (!bits) {
7302                 perror("malloc");
7303                 exit(1);
7304         }
7305
7306 again:
7307         root1 = root->fs_info->tree_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         root1 = root->fs_info->chunk_root;
7315         level = btrfs_header_level(root1->node);
7316         ret = add_root_item_to_list(&normal_trees, root1->root_key.objectid,
7317                                     root1->node->start, level, 0,
7318                                     btrfs_level_size(root1, level), NULL);
7319         if (ret < 0)
7320                 goto out;
7321         btrfs_init_path(&path);
7322         key.offset = 0;
7323         key.objectid = 0;
7324         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
7325         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
7326                                         &key, &path, 0, 0);
7327         if (ret < 0)
7328                 goto out;
7329         while(1) {
7330                 leaf = path.nodes[0];
7331                 slot = path.slots[0];
7332                 if (slot >= btrfs_header_nritems(path.nodes[0])) {
7333                         ret = btrfs_next_leaf(root, &path);
7334                         if (ret != 0)
7335                                 break;
7336                         leaf = path.nodes[0];
7337                         slot = path.slots[0];
7338                 }
7339                 btrfs_item_key_to_cpu(leaf, &found_key, path.slots[0]);
7340                 if (btrfs_key_type(&found_key) == BTRFS_ROOT_ITEM_KEY) {
7341                         unsigned long offset;
7342
7343                         offset = btrfs_item_ptr_offset(leaf, path.slots[0]);
7344                         read_extent_buffer(leaf, &ri, offset, sizeof(ri));
7345                         if (btrfs_disk_key_objectid(&ri.drop_progress) == 0) {
7346                                 level = btrfs_root_level(&ri);
7347                                 level_size = btrfs_level_size(root, level);
7348                                 ret = add_root_item_to_list(&normal_trees,
7349                                                 found_key.objectid,
7350                                                 btrfs_root_bytenr(&ri), level,
7351                                                 0, level_size, NULL);
7352                                 if (ret < 0)
7353                                         goto out;
7354                         } else {
7355                                 level = btrfs_root_level(&ri);
7356                                 level_size = btrfs_level_size(root, level);
7357                                 objectid = found_key.objectid;
7358                                 btrfs_disk_key_to_cpu(&found_key,
7359                                                       &ri.drop_progress);
7360                                 ret = add_root_item_to_list(&dropping_trees,
7361                                                 objectid,
7362                                                 btrfs_root_bytenr(&ri),
7363                                                 level, ri.drop_level,
7364                                                 level_size, &found_key);
7365                                 if (ret < 0)
7366                                         goto out;
7367                         }
7368                 }
7369                 path.slots[0]++;
7370         }
7371         btrfs_release_path(&path);
7372         ret = deal_root_from_list(&normal_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         ret = deal_root_from_list(&dropping_trees, trans, root,
7380                                   bits, bits_nr, &pending, &seen,
7381                                   &reada, &nodes, &extent_cache,
7382                                   &chunk_cache, &dev_cache, &block_group_cache,
7383                                   &dev_extent_cache);
7384         if (ret < 0)
7385                 goto out;
7386         if (ret >= 0)
7387                 ret = check_extent_refs(trans, root, &extent_cache);
7388         if (ret == -EAGAIN) {
7389                 ret = btrfs_commit_transaction(trans, root);
7390                 if (ret)
7391                         goto out;
7392
7393                 trans = btrfs_start_transaction(root, 1);
7394                 if (IS_ERR(trans)) {
7395                         ret = PTR_ERR(trans);
7396                         goto out;
7397                 }
7398
7399                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
7400                 free_extent_cache_tree(&seen);
7401                 free_extent_cache_tree(&pending);
7402                 free_extent_cache_tree(&reada);
7403                 free_extent_cache_tree(&nodes);
7404                 free_chunk_cache_tree(&chunk_cache);
7405                 free_block_group_tree(&block_group_cache);
7406                 free_device_cache_tree(&dev_cache);
7407                 free_device_extent_tree(&dev_extent_cache);
7408                 free_extent_record_cache(root->fs_info, &extent_cache);
7409                 goto again;
7410         }
7411
7412         err = check_chunks(&chunk_cache, &block_group_cache,
7413                            &dev_extent_cache, NULL, NULL, NULL, 0);
7414         if (err && !ret)
7415                 ret = err;
7416
7417         err = check_devices(&dev_cache, &dev_extent_cache);
7418         if (err && !ret)
7419                 ret = err;
7420
7421 out:
7422         if (trans) {
7423                 err = btrfs_commit_transaction(trans, root);
7424                 if (!ret)
7425                         ret = err;
7426         }
7427         if (repair) {
7428                 free_corrupt_blocks_tree(root->fs_info->corrupt_blocks);
7429                 root->fs_info->fsck_extent_cache = NULL;
7430                 root->fs_info->free_extent_hook = NULL;
7431                 root->fs_info->corrupt_blocks = NULL;
7432         }
7433         free(bits);
7434         free_chunk_cache_tree(&chunk_cache);
7435         free_device_cache_tree(&dev_cache);
7436         free_block_group_tree(&block_group_cache);
7437         free_device_extent_tree(&dev_extent_cache);
7438         free_extent_cache_tree(&seen);
7439         free_extent_cache_tree(&pending);
7440         free_extent_cache_tree(&reada);
7441         free_extent_cache_tree(&nodes);
7442         return ret;
7443 }
7444
7445 static int btrfs_fsck_reinit_root(struct btrfs_trans_handle *trans,
7446                            struct btrfs_root *root, int overwrite)
7447 {
7448         struct extent_buffer *c;
7449         struct extent_buffer *old = root->node;
7450         int level;
7451         int ret;
7452         struct btrfs_disk_key disk_key = {0,0,0};
7453
7454         level = 0;
7455
7456         if (overwrite) {
7457                 c = old;
7458                 extent_buffer_get(c);
7459                 goto init;
7460         }
7461         c = btrfs_alloc_free_block(trans, root,
7462                                    btrfs_level_size(root, 0),
7463                                    root->root_key.objectid,
7464                                    &disk_key, level, 0, 0);
7465         if (IS_ERR(c)) {
7466                 c = old;
7467                 extent_buffer_get(c);
7468                 overwrite = 1;
7469         }
7470 init:
7471         memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
7472         btrfs_set_header_level(c, level);
7473         btrfs_set_header_bytenr(c, c->start);
7474         btrfs_set_header_generation(c, trans->transid);
7475         btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
7476         btrfs_set_header_owner(c, root->root_key.objectid);
7477
7478         write_extent_buffer(c, root->fs_info->fsid,
7479                             btrfs_header_fsid(), BTRFS_FSID_SIZE);
7480
7481         write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
7482                             btrfs_header_chunk_tree_uuid(c),
7483                             BTRFS_UUID_SIZE);
7484
7485         btrfs_mark_buffer_dirty(c);
7486         /*
7487          * this case can happen in the following case:
7488          *
7489          * 1.overwrite previous root.
7490          *
7491          * 2.reinit reloc data root, this is because we skip pin
7492          * down reloc data tree before which means we can allocate
7493          * same block bytenr here.
7494          */
7495         if (old->start == c->start) {
7496                 btrfs_set_root_generation(&root->root_item,
7497                                           trans->transid);
7498                 root->root_item.level = btrfs_header_level(root->node);
7499                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
7500                                         &root->root_key, &root->root_item);
7501                 if (ret) {
7502                         free_extent_buffer(c);
7503                         return ret;
7504                 }
7505         }
7506         free_extent_buffer(old);
7507         root->node = c;
7508         add_root_to_dirty_list(root);
7509         return 0;
7510 }
7511
7512 static int pin_down_tree_blocks(struct btrfs_fs_info *fs_info,
7513                                 struct extent_buffer *eb, int tree_root)
7514 {
7515         struct extent_buffer *tmp;
7516         struct btrfs_root_item *ri;
7517         struct btrfs_key key;
7518         u64 bytenr;
7519         u32 leafsize;
7520         int level = btrfs_header_level(eb);
7521         int nritems;
7522         int ret;
7523         int i;
7524
7525         /*
7526          * If we have pinned this block before, don't pin it again.
7527          * This can not only avoid forever loop with broken filesystem
7528          * but also give us some speedups.
7529          */
7530         if (test_range_bit(&fs_info->pinned_extents, eb->start,
7531                            eb->start + eb->len - 1, EXTENT_DIRTY, 0))
7532                 return 0;
7533
7534         btrfs_pin_extent(fs_info, eb->start, eb->len);
7535
7536         leafsize = btrfs_super_leafsize(fs_info->super_copy);
7537         nritems = btrfs_header_nritems(eb);
7538         for (i = 0; i < nritems; i++) {
7539                 if (level == 0) {
7540                         btrfs_item_key_to_cpu(eb, &key, i);
7541                         if (key.type != BTRFS_ROOT_ITEM_KEY)
7542                                 continue;
7543                         /* Skip the extent root and reloc roots */
7544                         if (key.objectid == BTRFS_EXTENT_TREE_OBJECTID ||
7545                             key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
7546                             key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
7547                                 continue;
7548                         ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
7549                         bytenr = btrfs_disk_root_bytenr(eb, ri);
7550
7551                         /*
7552                          * If at any point we start needing the real root we
7553                          * will have to build a stump root for the root we are
7554                          * in, but for now this doesn't actually use the root so
7555                          * just pass in extent_root.
7556                          */
7557                         tmp = read_tree_block(fs_info->extent_root, bytenr,
7558                                               leafsize, 0);
7559                         if (!tmp) {
7560                                 fprintf(stderr, "Error reading root block\n");
7561                                 return -EIO;
7562                         }
7563                         ret = pin_down_tree_blocks(fs_info, tmp, 0);
7564                         free_extent_buffer(tmp);
7565                         if (ret)
7566                                 return ret;
7567                 } else {
7568                         bytenr = btrfs_node_blockptr(eb, i);
7569
7570                         /* If we aren't the tree root don't read the block */
7571                         if (level == 1 && !tree_root) {
7572                                 btrfs_pin_extent(fs_info, bytenr, leafsize);
7573                                 continue;
7574                         }
7575
7576                         tmp = read_tree_block(fs_info->extent_root, bytenr,
7577                                               leafsize, 0);
7578                         if (!tmp) {
7579                                 fprintf(stderr, "Error reading tree block\n");
7580                                 return -EIO;
7581                         }
7582                         ret = pin_down_tree_blocks(fs_info, tmp, tree_root);
7583                         free_extent_buffer(tmp);
7584                         if (ret)
7585                                 return ret;
7586                 }
7587         }
7588
7589         return 0;
7590 }
7591
7592 static int pin_metadata_blocks(struct btrfs_fs_info *fs_info)
7593 {
7594         int ret;
7595
7596         ret = pin_down_tree_blocks(fs_info, fs_info->chunk_root->node, 0);
7597         if (ret)
7598                 return ret;
7599
7600         return pin_down_tree_blocks(fs_info, fs_info->tree_root->node, 1);
7601 }
7602
7603 static int reset_block_groups(struct btrfs_fs_info *fs_info)
7604 {
7605         struct btrfs_block_group_cache *cache;
7606         struct btrfs_path *path;
7607         struct extent_buffer *leaf;
7608         struct btrfs_chunk *chunk;
7609         struct btrfs_key key;
7610         int ret;
7611         u64 start;
7612
7613         path = btrfs_alloc_path();
7614         if (!path)
7615                 return -ENOMEM;
7616
7617         key.objectid = 0;
7618         key.type = BTRFS_CHUNK_ITEM_KEY;
7619         key.offset = 0;
7620
7621         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
7622         if (ret < 0) {
7623                 btrfs_free_path(path);
7624                 return ret;
7625         }
7626
7627         /*
7628          * We do this in case the block groups were screwed up and had alloc
7629          * bits that aren't actually set on the chunks.  This happens with
7630          * restored images every time and could happen in real life I guess.
7631          */
7632         fs_info->avail_data_alloc_bits = 0;
7633         fs_info->avail_metadata_alloc_bits = 0;
7634         fs_info->avail_system_alloc_bits = 0;
7635
7636         /* First we need to create the in-memory block groups */
7637         while (1) {
7638                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7639                         ret = btrfs_next_leaf(fs_info->chunk_root, path);
7640                         if (ret < 0) {
7641                                 btrfs_free_path(path);
7642                                 return ret;
7643                         }
7644                         if (ret) {
7645                                 ret = 0;
7646                                 break;
7647                         }
7648                 }
7649                 leaf = path->nodes[0];
7650                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7651                 if (key.type != BTRFS_CHUNK_ITEM_KEY) {
7652                         path->slots[0]++;
7653                         continue;
7654                 }
7655
7656                 chunk = btrfs_item_ptr(leaf, path->slots[0],
7657                                        struct btrfs_chunk);
7658                 btrfs_add_block_group(fs_info, 0,
7659                                       btrfs_chunk_type(leaf, chunk),
7660                                       key.objectid, key.offset,
7661                                       btrfs_chunk_length(leaf, chunk));
7662                 set_extent_dirty(&fs_info->free_space_cache, key.offset,
7663                                  key.offset + btrfs_chunk_length(leaf, chunk),
7664                                  GFP_NOFS);
7665                 path->slots[0]++;
7666         }
7667         start = 0;
7668         while (1) {
7669                 cache = btrfs_lookup_first_block_group(fs_info, start);
7670                 if (!cache)
7671                         break;
7672                 cache->cached = 1;
7673                 start = cache->key.objectid + cache->key.offset;
7674         }
7675
7676         btrfs_free_path(path);
7677         return 0;
7678 }
7679
7680 static int reset_balance(struct btrfs_trans_handle *trans,
7681                          struct btrfs_fs_info *fs_info)
7682 {
7683         struct btrfs_root *root = fs_info->tree_root;
7684         struct btrfs_path *path;
7685         struct extent_buffer *leaf;
7686         struct btrfs_key key;
7687         int del_slot, del_nr = 0;
7688         int ret;
7689         int found = 0;
7690
7691         path = btrfs_alloc_path();
7692         if (!path)
7693                 return -ENOMEM;
7694
7695         key.objectid = BTRFS_BALANCE_OBJECTID;
7696         key.type = BTRFS_BALANCE_ITEM_KEY;
7697         key.offset = 0;
7698
7699         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
7700         if (ret) {
7701                 if (ret > 0)
7702                         ret = 0;
7703                 if (!ret)
7704                         goto reinit_data_reloc;
7705                 else
7706                         goto out;
7707         }
7708
7709         ret = btrfs_del_item(trans, root, path);
7710         if (ret)
7711                 goto out;
7712         btrfs_release_path(path);
7713
7714         key.objectid = BTRFS_TREE_RELOC_OBJECTID;
7715         key.type = BTRFS_ROOT_ITEM_KEY;
7716         key.offset = 0;
7717
7718         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
7719         if (ret < 0)
7720                 goto out;
7721         while (1) {
7722                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7723                         if (!found)
7724                                 break;
7725
7726                         if (del_nr) {
7727                                 ret = btrfs_del_items(trans, root, path,
7728                                                       del_slot, del_nr);
7729                                 del_nr = 0;
7730                                 if (ret)
7731                                         goto out;
7732                         }
7733                         key.offset++;
7734                         btrfs_release_path(path);
7735
7736                         found = 0;
7737                         ret = btrfs_search_slot(trans, root, &key, path,
7738                                                 -1, 1);
7739                         if (ret < 0)
7740                                 goto out;
7741                         continue;
7742                 }
7743                 found = 1;
7744                 leaf = path->nodes[0];
7745                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7746                 if (key.objectid > BTRFS_TREE_RELOC_OBJECTID)
7747                         break;
7748                 if (key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7749                         path->slots[0]++;
7750                         continue;
7751                 }
7752                 if (!del_nr) {
7753                         del_slot = path->slots[0];
7754                         del_nr = 1;
7755                 } else {
7756                         del_nr++;
7757                 }
7758                 path->slots[0]++;
7759         }
7760
7761         if (del_nr) {
7762                 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
7763                 if (ret)
7764                         goto out;
7765         }
7766         btrfs_release_path(path);
7767
7768 reinit_data_reloc:
7769         key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
7770         key.type = BTRFS_ROOT_ITEM_KEY;
7771         key.offset = (u64)-1;
7772         root = btrfs_read_fs_root(fs_info, &key);
7773         if (IS_ERR(root)) {
7774                 fprintf(stderr, "Error reading data reloc tree\n");
7775                 return PTR_ERR(root);
7776         }
7777         record_root_in_trans(trans, root);
7778         ret = btrfs_fsck_reinit_root(trans, root, 0);
7779         if (ret)
7780                 goto out;
7781         ret = btrfs_make_root_dir(trans, root, BTRFS_FIRST_FREE_OBJECTID);
7782 out:
7783         btrfs_free_path(path);
7784         return ret;
7785 }
7786
7787 static int reinit_extent_tree(struct btrfs_trans_handle *trans,
7788                               struct btrfs_fs_info *fs_info)
7789 {
7790         u64 start = 0;
7791         int ret;
7792
7793         /*
7794          * The only reason we don't do this is because right now we're just
7795          * walking the trees we find and pinning down their bytes, we don't look
7796          * at any of the leaves.  In order to do mixed groups we'd have to check
7797          * the leaves of any fs roots and pin down the bytes for any file
7798          * extents we find.  Not hard but why do it if we don't have to?
7799          */
7800         if (btrfs_fs_incompat(fs_info, BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)) {
7801                 fprintf(stderr, "We don't support re-initing the extent tree "
7802                         "for mixed block groups yet, please notify a btrfs "
7803                         "developer you want to do this so they can add this "
7804                         "functionality.\n");
7805                 return -EINVAL;
7806         }
7807
7808         /*
7809          * first we need to walk all of the trees except the extent tree and pin
7810          * down the bytes that are in use so we don't overwrite any existing
7811          * metadata.
7812          */
7813         ret = pin_metadata_blocks(fs_info);
7814         if (ret) {
7815                 fprintf(stderr, "error pinning down used bytes\n");
7816                 return ret;
7817         }
7818
7819         /*
7820          * Need to drop all the block groups since we're going to recreate all
7821          * of them again.
7822          */
7823         btrfs_free_block_groups(fs_info);
7824         ret = reset_block_groups(fs_info);
7825         if (ret) {
7826                 fprintf(stderr, "error resetting the block groups\n");
7827                 return ret;
7828         }
7829
7830         /* Ok we can allocate now, reinit the extent root */
7831         ret = btrfs_fsck_reinit_root(trans, fs_info->extent_root, 0);
7832         if (ret) {
7833                 fprintf(stderr, "extent root initialization failed\n");
7834                 /*
7835                  * When the transaction code is updated we should end the
7836                  * transaction, but for now progs only knows about commit so
7837                  * just return an error.
7838                  */
7839                 return ret;
7840         }
7841
7842         /*
7843          * Now we have all the in-memory block groups setup so we can make
7844          * allocations properly, and the metadata we care about is safe since we
7845          * pinned all of it above.
7846          */
7847         while (1) {
7848                 struct btrfs_block_group_cache *cache;
7849
7850                 cache = btrfs_lookup_first_block_group(fs_info, start);
7851                 if (!cache)
7852                         break;
7853                 start = cache->key.objectid + cache->key.offset;
7854                 ret = btrfs_insert_item(trans, fs_info->extent_root,
7855                                         &cache->key, &cache->item,
7856                                         sizeof(cache->item));
7857                 if (ret) {
7858                         fprintf(stderr, "Error adding block group\n");
7859                         return ret;
7860                 }
7861                 btrfs_extent_post_op(trans, fs_info->extent_root);
7862         }
7863
7864         ret = reset_balance(trans, fs_info);
7865         if (ret)
7866                 fprintf(stderr, "error reseting the pending balance\n");
7867
7868         return ret;
7869 }
7870
7871 static int recow_extent_buffer(struct btrfs_root *root, struct extent_buffer *eb)
7872 {
7873         struct btrfs_path *path;
7874         struct btrfs_trans_handle *trans;
7875         struct btrfs_key key;
7876         int ret;
7877
7878         printf("Recowing metadata block %llu\n", eb->start);
7879         key.objectid = btrfs_header_owner(eb);
7880         key.type = BTRFS_ROOT_ITEM_KEY;
7881         key.offset = (u64)-1;
7882
7883         root = btrfs_read_fs_root(root->fs_info, &key);
7884         if (IS_ERR(root)) {
7885                 fprintf(stderr, "Couldn't find owner root %llu\n",
7886                         key.objectid);
7887                 return PTR_ERR(root);
7888         }
7889
7890         path = btrfs_alloc_path();
7891         if (!path)
7892                 return -ENOMEM;
7893
7894         trans = btrfs_start_transaction(root, 1);
7895         if (IS_ERR(trans)) {
7896                 btrfs_free_path(path);
7897                 return PTR_ERR(trans);
7898         }
7899
7900         path->lowest_level = btrfs_header_level(eb);
7901         if (path->lowest_level)
7902                 btrfs_node_key_to_cpu(eb, &key, 0);
7903         else
7904                 btrfs_item_key_to_cpu(eb, &key, 0);
7905
7906         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7907         btrfs_commit_transaction(trans, root);
7908         btrfs_free_path(path);
7909         return ret;
7910 }
7911
7912 static int delete_bad_item(struct btrfs_root *root, struct bad_item *bad)
7913 {
7914         struct btrfs_path *path;
7915         struct btrfs_trans_handle *trans;
7916         struct btrfs_key key;
7917         int ret;
7918
7919         printf("Deleting bad item [%llu,%u,%llu]\n", bad->key.objectid,
7920                bad->key.type, bad->key.offset);
7921         key.objectid = bad->root_id;
7922         key.type = BTRFS_ROOT_ITEM_KEY;
7923         key.offset = (u64)-1;
7924
7925         root = btrfs_read_fs_root(root->fs_info, &key);
7926         if (IS_ERR(root)) {
7927                 fprintf(stderr, "Couldn't find owner root %llu\n",
7928                         key.objectid);
7929                 return PTR_ERR(root);
7930         }
7931
7932         path = btrfs_alloc_path();
7933         if (!path)
7934                 return -ENOMEM;
7935
7936         trans = btrfs_start_transaction(root, 1);
7937         if (IS_ERR(trans)) {
7938                 btrfs_free_path(path);
7939                 return PTR_ERR(trans);
7940         }
7941
7942         ret = btrfs_search_slot(trans, root, &bad->key, path, -1, 1);
7943         if (ret) {
7944                 if (ret > 0)
7945                         ret = 0;
7946                 goto out;
7947         }
7948         ret = btrfs_del_item(trans, root, path);
7949 out:
7950         btrfs_commit_transaction(trans, root);
7951         btrfs_free_path(path);
7952         return ret;
7953 }
7954
7955 static int zero_log_tree(struct btrfs_root *root)
7956 {
7957         struct btrfs_trans_handle *trans;
7958         int ret;
7959
7960         trans = btrfs_start_transaction(root, 1);
7961         if (IS_ERR(trans)) {
7962                 ret = PTR_ERR(trans);
7963                 return ret;
7964         }
7965         btrfs_set_super_log_root(root->fs_info->super_copy, 0);
7966         btrfs_set_super_log_root_level(root->fs_info->super_copy, 0);
7967         ret = btrfs_commit_transaction(trans, root);
7968         return ret;
7969 }
7970
7971 static int populate_csum(struct btrfs_trans_handle *trans,
7972                          struct btrfs_root *csum_root, char *buf, u64 start,
7973                          u64 len)
7974 {
7975         u64 offset = 0;
7976         u64 sectorsize;
7977         int ret = 0;
7978
7979         while (offset < len) {
7980                 sectorsize = csum_root->sectorsize;
7981                 ret = read_extent_data(csum_root, buf, start + offset,
7982                                        &sectorsize, 0);
7983                 if (ret)
7984                         break;
7985                 ret = btrfs_csum_file_block(trans, csum_root, start + len,
7986                                             start + offset, buf, sectorsize);
7987                 if (ret)
7988                         break;
7989                 offset += sectorsize;
7990         }
7991         return ret;
7992 }
7993
7994 static int fill_csum_tree(struct btrfs_trans_handle *trans,
7995                           struct btrfs_root *csum_root)
7996 {
7997         struct btrfs_root *extent_root = csum_root->fs_info->extent_root;
7998         struct btrfs_path *path;
7999         struct btrfs_extent_item *ei;
8000         struct extent_buffer *leaf;
8001         char *buf;
8002         struct btrfs_key key;
8003         int ret;
8004
8005         path = btrfs_alloc_path();
8006         if (!path)
8007                 return -ENOMEM;
8008
8009         key.objectid = 0;
8010         key.type = BTRFS_EXTENT_ITEM_KEY;
8011         key.offset = 0;
8012
8013         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
8014         if (ret < 0) {
8015                 btrfs_free_path(path);
8016                 return ret;
8017         }
8018
8019         buf = malloc(csum_root->sectorsize);
8020         if (!buf) {
8021                 btrfs_free_path(path);
8022                 return -ENOMEM;
8023         }
8024
8025         while (1) {
8026                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8027                         ret = btrfs_next_leaf(extent_root, path);
8028                         if (ret < 0)
8029                                 break;
8030                         if (ret) {
8031                                 ret = 0;
8032                                 break;
8033                         }
8034                 }
8035                 leaf = path->nodes[0];
8036
8037                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
8038                 if (key.type != BTRFS_EXTENT_ITEM_KEY) {
8039                         path->slots[0]++;
8040                         continue;
8041                 }
8042
8043                 ei = btrfs_item_ptr(leaf, path->slots[0],
8044                                     struct btrfs_extent_item);
8045                 if (!(btrfs_extent_flags(leaf, ei) &
8046                       BTRFS_EXTENT_FLAG_DATA)) {
8047                         path->slots[0]++;
8048                         continue;
8049                 }
8050
8051                 ret = populate_csum(trans, csum_root, buf, key.objectid,
8052                                     key.offset);
8053                 if (ret)
8054                         break;
8055                 path->slots[0]++;
8056         }
8057
8058         btrfs_free_path(path);
8059         free(buf);
8060         return ret;
8061 }
8062
8063 struct root_item_info {
8064         /* level of the root */
8065         u8 level;
8066         /* number of nodes at this level, must be 1 for a root */
8067         int node_count;
8068         u64 bytenr;
8069         u64 gen;
8070         struct cache_extent cache_extent;
8071 };
8072
8073 static struct cache_tree *roots_info_cache = NULL;
8074
8075 static void free_roots_info_cache(void)
8076 {
8077         if (!roots_info_cache)
8078                 return;
8079
8080         while (!cache_tree_empty(roots_info_cache)) {
8081                 struct cache_extent *entry;
8082                 struct root_item_info *rii;
8083
8084                 entry = first_cache_extent(roots_info_cache);
8085                 if (!entry)
8086                         break;
8087                 remove_cache_extent(roots_info_cache, entry);
8088                 rii = container_of(entry, struct root_item_info, cache_extent);
8089                 free(rii);
8090         }
8091
8092         free(roots_info_cache);
8093         roots_info_cache = NULL;
8094 }
8095
8096 static int build_roots_info_cache(struct btrfs_fs_info *info)
8097 {
8098         int ret = 0;
8099         struct btrfs_key key;
8100         struct extent_buffer *leaf;
8101         struct btrfs_path *path;
8102
8103         if (!roots_info_cache) {
8104                 roots_info_cache = malloc(sizeof(*roots_info_cache));
8105                 if (!roots_info_cache)
8106                         return -ENOMEM;
8107                 cache_tree_init(roots_info_cache);
8108         }
8109
8110         path = btrfs_alloc_path();
8111         if (!path)
8112                 return -ENOMEM;
8113
8114         key.objectid = 0;
8115         key.type = BTRFS_EXTENT_ITEM_KEY;
8116         key.offset = 0;
8117
8118         ret = btrfs_search_slot(NULL, info->extent_root, &key, path, 0, 0);
8119         if (ret < 0)
8120                 goto out;
8121         leaf = path->nodes[0];
8122
8123         while (1) {
8124                 struct btrfs_key found_key;
8125                 struct btrfs_extent_item *ei;
8126                 struct btrfs_extent_inline_ref *iref;
8127                 int slot = path->slots[0];
8128                 int type;
8129                 u64 flags;
8130                 u64 root_id;
8131                 u8 level;
8132                 struct cache_extent *entry;
8133                 struct root_item_info *rii;
8134
8135                 if (slot >= btrfs_header_nritems(leaf)) {
8136                         ret = btrfs_next_leaf(info->extent_root, path);
8137                         if (ret < 0) {
8138                                 break;
8139                         } else if (ret) {
8140                                 ret = 0;
8141                                 break;
8142                         }
8143                         leaf = path->nodes[0];
8144                         slot = path->slots[0];
8145                 }
8146
8147                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8148
8149                 if (found_key.type != BTRFS_EXTENT_ITEM_KEY &&
8150                     found_key.type != BTRFS_METADATA_ITEM_KEY)
8151                         goto next;
8152
8153                 ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
8154                 flags = btrfs_extent_flags(leaf, ei);
8155
8156                 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
8157                     !(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
8158                         goto next;
8159
8160                 if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
8161                         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
8162                         level = found_key.offset;
8163                 } else {
8164                         struct btrfs_tree_block_info *info;
8165
8166                         info = (struct btrfs_tree_block_info *)(ei + 1);
8167                         iref = (struct btrfs_extent_inline_ref *)(info + 1);
8168                         level = btrfs_tree_block_level(leaf, info);
8169                 }
8170
8171                 /*
8172                  * For a root extent, it must be of the following type and the
8173                  * first (and only one) iref in the item.
8174                  */
8175                 type = btrfs_extent_inline_ref_type(leaf, iref);
8176                 if (type != BTRFS_TREE_BLOCK_REF_KEY)
8177                         goto next;
8178
8179                 root_id = btrfs_extent_inline_ref_offset(leaf, iref);
8180                 entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8181                 if (!entry) {
8182                         rii = malloc(sizeof(struct root_item_info));
8183                         if (!rii) {
8184                                 ret = -ENOMEM;
8185                                 goto out;
8186                         }
8187                         rii->cache_extent.start = root_id;
8188                         rii->cache_extent.size = 1;
8189                         rii->level = (u8)-1;
8190                         entry = &rii->cache_extent;
8191                         ret = insert_cache_extent(roots_info_cache, entry);
8192                         ASSERT(ret == 0);
8193                 } else {
8194                         rii = container_of(entry, struct root_item_info,
8195                                            cache_extent);
8196                 }
8197
8198                 ASSERT(rii->cache_extent.start == root_id);
8199                 ASSERT(rii->cache_extent.size == 1);
8200
8201                 if (level > rii->level || rii->level == (u8)-1) {
8202                         rii->level = level;
8203                         rii->bytenr = found_key.objectid;
8204                         rii->gen = btrfs_extent_generation(leaf, ei);
8205                         rii->node_count = 1;
8206                 } else if (level == rii->level) {
8207                         rii->node_count++;
8208                 }
8209 next:
8210                 path->slots[0]++;
8211         }
8212
8213 out:
8214         btrfs_free_path(path);
8215
8216         return ret;
8217 }
8218
8219 static int maybe_repair_root_item(struct btrfs_fs_info *info,
8220                                   struct btrfs_path *path,
8221                                   const struct btrfs_key *root_key,
8222                                   const int read_only_mode)
8223 {
8224         const u64 root_id = root_key->objectid;
8225         struct cache_extent *entry;
8226         struct root_item_info *rii;
8227         struct btrfs_root_item ri;
8228         unsigned long offset;
8229
8230         entry = lookup_cache_extent(roots_info_cache, root_id, 1);
8231         if (!entry) {
8232                 fprintf(stderr,
8233                         "Error: could not find extent items for root %llu\n",
8234                         root_key->objectid);
8235                 return -ENOENT;
8236         }
8237
8238         rii = container_of(entry, struct root_item_info, cache_extent);
8239         ASSERT(rii->cache_extent.start == root_id);
8240         ASSERT(rii->cache_extent.size == 1);
8241
8242         if (rii->node_count != 1) {
8243                 fprintf(stderr,
8244                         "Error: could not find btree root extent for root %llu\n",
8245                         root_id);
8246                 return -ENOENT;
8247         }
8248
8249         offset = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
8250         read_extent_buffer(path->nodes[0], &ri, offset, sizeof(ri));
8251
8252         if (btrfs_root_bytenr(&ri) != rii->bytenr ||
8253             btrfs_root_level(&ri) != rii->level ||
8254             btrfs_root_generation(&ri) != rii->gen) {
8255
8256                 /*
8257                  * If we're in repair mode but our caller told us to not update
8258                  * the root item, i.e. just check if it needs to be updated, don't
8259                  * print this message, since the caller will call us again shortly
8260                  * for the same root item without read only mode (the caller will
8261                  * open a transaction first).
8262                  */
8263                 if (!(read_only_mode && repair))
8264                         fprintf(stderr,
8265                                 "%sroot item for root %llu,"
8266                                 " current bytenr %llu, current gen %llu, current level %u,"
8267                                 " new bytenr %llu, new gen %llu, new level %u\n",
8268                                 (read_only_mode ? "" : "fixing "),
8269                                 root_id,
8270                                 btrfs_root_bytenr(&ri), btrfs_root_generation(&ri),
8271                                 btrfs_root_level(&ri),
8272                                 rii->bytenr, rii->gen, rii->level);
8273
8274                 if (btrfs_root_generation(&ri) > rii->gen) {
8275                         fprintf(stderr,
8276                                 "root %llu has a root item with a more recent gen (%llu) compared to the found root node (%llu)\n",
8277                                 root_id, btrfs_root_generation(&ri), rii->gen);
8278                         return -EINVAL;
8279                 }
8280
8281                 if (!read_only_mode) {
8282                         btrfs_set_root_bytenr(&ri, rii->bytenr);
8283                         btrfs_set_root_level(&ri, rii->level);
8284                         btrfs_set_root_generation(&ri, rii->gen);
8285                         write_extent_buffer(path->nodes[0], &ri,
8286                                             offset, sizeof(ri));
8287                 }
8288
8289                 return 1;
8290         }
8291
8292         return 0;
8293 }
8294
8295 /*
8296  * A regression introduced in the 3.17 kernel (more specifically in 3.17-rc2),
8297  * caused read-only snapshots to be corrupted if they were created at a moment
8298  * when the source subvolume/snapshot had orphan items. The issue was that the
8299  * on-disk root items became incorrect, referring to the pre orphan cleanup root
8300  * node instead of the post orphan cleanup root node.
8301  * So this function, and its callees, just detects and fixes those cases. Even
8302  * though the regression was for read-only snapshots, this function applies to
8303  * any snapshot/subvolume root.
8304  * This must be run before any other repair code - not doing it so, makes other
8305  * repair code delete or modify backrefs in the extent tree for example, which
8306  * will result in an inconsistent fs after repairing the root items.
8307  */
8308 static int repair_root_items(struct btrfs_fs_info *info)
8309 {
8310         struct btrfs_path *path = NULL;
8311         struct btrfs_key key;
8312         struct extent_buffer *leaf;
8313         struct btrfs_trans_handle *trans = NULL;
8314         int ret = 0;
8315         int bad_roots = 0;
8316         int need_trans = 0;
8317
8318         ret = build_roots_info_cache(info);
8319         if (ret)
8320                 goto out;
8321
8322         path = btrfs_alloc_path();
8323         if (!path) {
8324                 ret = -ENOMEM;
8325                 goto out;
8326         }
8327
8328         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
8329         key.type = BTRFS_ROOT_ITEM_KEY;
8330         key.offset = 0;
8331
8332 again:
8333         /*
8334          * Avoid opening and committing transactions if a leaf doesn't have
8335          * any root items that need to be fixed, so that we avoid rotating
8336          * backup roots unnecessarily.
8337          */
8338         if (need_trans) {
8339                 trans = btrfs_start_transaction(info->tree_root, 1);
8340                 if (IS_ERR(trans)) {
8341                         ret = PTR_ERR(trans);
8342                         goto out;
8343                 }
8344         }
8345
8346         ret = btrfs_search_slot(trans, info->tree_root, &key, path,
8347                                 0, trans ? 1 : 0);
8348         if (ret < 0)
8349                 goto out;
8350         leaf = path->nodes[0];
8351
8352         while (1) {
8353                 struct btrfs_key found_key;
8354
8355                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
8356                         int no_more_keys = find_next_key(path, &key);
8357
8358                         btrfs_release_path(path);
8359                         if (trans) {
8360                                 ret = btrfs_commit_transaction(trans,
8361                                                                info->tree_root);
8362                                 trans = NULL;
8363                                 if (ret < 0)
8364                                         goto out;
8365                         }
8366                         need_trans = 0;
8367                         if (no_more_keys)
8368                                 break;
8369                         goto again;
8370                 }
8371
8372                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8373
8374                 if (found_key.type != BTRFS_ROOT_ITEM_KEY)
8375                         goto next;
8376
8377                 ret = maybe_repair_root_item(info, path, &found_key,
8378                                              trans ? 0 : 1);
8379                 if (ret < 0)
8380                         goto out;
8381                 if (ret) {
8382                         if (!trans && repair) {
8383                                 need_trans = 1;
8384                                 key = found_key;
8385                                 btrfs_release_path(path);
8386                                 goto again;
8387                         }
8388                         bad_roots++;
8389                 }
8390 next:
8391                 path->slots[0]++;
8392         }
8393         ret = 0;
8394 out:
8395         free_roots_info_cache();
8396         if (path)
8397                 btrfs_free_path(path);
8398         if (ret < 0)
8399                 return ret;
8400
8401         return bad_roots;
8402 }
8403
8404 static struct option long_options[] = {
8405         { "super", 1, NULL, 's' },
8406         { "repair", 0, NULL, 0 },
8407         { "init-csum-tree", 0, NULL, 0 },
8408         { "init-extent-tree", 0, NULL, 0 },
8409         { "check-data-csum", 0, NULL, 0 },
8410         { "backup", 0, NULL, 0 },
8411         { "subvol-extents", 1, NULL, 'E' },
8412         { "qgroup-report", 0, NULL, 'Q' },
8413         { "tree-root", 1, NULL, 'r' },
8414         { NULL, 0, NULL, 0}
8415 };
8416
8417 const char * const cmd_check_usage[] = {
8418         "btrfs check [options] <device>",
8419         "Check an unmounted btrfs filesystem.",
8420         "",
8421         "-s|--super <superblock>     use this superblock copy",
8422         "-b|--backup                 use the backup root copy",
8423         "--repair                    try to repair the filesystem",
8424         "--init-csum-tree            create a new CRC tree",
8425         "--init-extent-tree          create a new extent tree",
8426         "--check-data-csum           verify checkums of data blocks",
8427         "--qgroup-report             print a report on qgroup consistency",
8428         "--subvol-extents <subvolid> print subvolume extents and sharing state",
8429         "--tree-root <bytenr>        use the given bytenr for the tree root",
8430         NULL
8431 };
8432
8433 int cmd_check(int argc, char **argv)
8434 {
8435         struct cache_tree root_cache;
8436         struct btrfs_root *root;
8437         struct btrfs_fs_info *info;
8438         u64 bytenr = 0;
8439         u64 subvolid = 0;
8440         u64 tree_root_bytenr = 0;
8441         char uuidbuf[BTRFS_UUID_UNPARSED_SIZE];
8442         int ret;
8443         u64 num;
8444         int option_index = 0;
8445         int init_csum_tree = 0;
8446         int qgroup_report = 0;
8447         enum btrfs_open_ctree_flags ctree_flags = OPEN_CTREE_EXCLUSIVE;
8448
8449         while(1) {
8450                 int c;
8451                 c = getopt_long(argc, argv, "as:br:", long_options,
8452                                 &option_index);
8453                 if (c < 0)
8454                         break;
8455                 switch(c) {
8456                         case 'a': /* ignored */ break;
8457                         case 'b':
8458                                 ctree_flags |= OPEN_CTREE_BACKUP_ROOT;
8459                                 break;
8460                         case 's':
8461                                 num = arg_strtou64(optarg);
8462                                 if (num >= BTRFS_SUPER_MIRROR_MAX) {
8463                                         fprintf(stderr,
8464                                                 "ERROR: super mirror should be less than: %d\n",
8465                                                 BTRFS_SUPER_MIRROR_MAX);
8466                                         exit(1);
8467                                 }
8468                                 bytenr = btrfs_sb_offset(((int)num));
8469                                 printf("using SB copy %llu, bytenr %llu\n", num,
8470                                        (unsigned long long)bytenr);
8471                                 break;
8472                         case 'Q':
8473                                 qgroup_report = 1;
8474                                 break;
8475                         case 'E':
8476                                 subvolid = arg_strtou64(optarg);
8477                                 break;
8478                         case 'r':
8479                                 tree_root_bytenr = arg_strtou64(optarg);
8480                                 break;
8481                         case '?':
8482                         case 'h':
8483                                 usage(cmd_check_usage);
8484                 }
8485                 if (option_index == 1) {
8486                         printf("enabling repair mode\n");
8487                         repair = 1;
8488                         ctree_flags |= OPEN_CTREE_WRITES;
8489                 } else if (option_index == 2) {
8490                         printf("Creating a new CRC tree\n");
8491                         init_csum_tree = 1;
8492                         repair = 1;
8493                         ctree_flags |= OPEN_CTREE_WRITES;
8494                 } else if (option_index == 3) {
8495                         init_extent_tree = 1;
8496                         ctree_flags |= (OPEN_CTREE_WRITES |
8497                                         OPEN_CTREE_NO_BLOCK_GROUPS);
8498                         repair = 1;
8499                 } else if (option_index == 4) {
8500                         check_data_csum = 1;
8501                 }
8502         }
8503         argc = argc - optind;
8504
8505         if (check_argc_exact(argc, 1))
8506                 usage(cmd_check_usage);
8507
8508         radix_tree_init();
8509         cache_tree_init(&root_cache);
8510
8511         if((ret = check_mounted(argv[optind])) < 0) {
8512                 fprintf(stderr, "Could not check mount status: %s\n", strerror(-ret));
8513                 goto err_out;
8514         } else if(ret) {
8515                 fprintf(stderr, "%s is currently mounted. Aborting.\n", argv[optind]);
8516                 ret = -EBUSY;
8517                 goto err_out;
8518         }
8519
8520         /* only allow partial opening under repair mode */
8521         if (repair)
8522                 ctree_flags |= OPEN_CTREE_PARTIAL;
8523
8524         info = open_ctree_fs_info(argv[optind], bytenr, tree_root_bytenr,
8525                                   ctree_flags);
8526         if (!info) {
8527                 fprintf(stderr, "Couldn't open file system\n");
8528                 ret = -EIO;
8529                 goto err_out;
8530         }
8531
8532         root = info->fs_root;
8533
8534         /*
8535          * repair mode will force us to commit transaction which
8536          * will make us fail to load log tree when mounting.
8537          */
8538         if (repair && btrfs_super_log_root(info->super_copy)) {
8539                 ret = ask_user("repair mode will force to clear out log tree, Are you sure?");
8540                 if (!ret) {
8541                         ret = 1;
8542                         goto close_out;
8543                 }
8544                 ret = zero_log_tree(root);
8545                 if (ret) {
8546                         fprintf(stderr, "fail to zero log tree\n");
8547                         goto close_out;
8548                 }
8549         }
8550
8551         uuid_unparse(info->super_copy->fsid, uuidbuf);
8552         if (qgroup_report) {
8553                 printf("Print quota groups for %s\nUUID: %s\n", argv[optind],
8554                        uuidbuf);
8555                 ret = qgroup_verify_all(info);
8556                 if (ret == 0)
8557                         print_qgroup_report(1);
8558                 goto close_out;
8559         }
8560         if (subvolid) {
8561                 printf("Print extent state for subvolume %llu on %s\nUUID: %s\n",
8562                        subvolid, argv[optind], uuidbuf);
8563                 ret = print_extent_state(info, subvolid);
8564                 goto close_out;
8565         }
8566         printf("Checking filesystem on %s\nUUID: %s\n", argv[optind], uuidbuf);
8567
8568         if (!extent_buffer_uptodate(info->tree_root->node) ||
8569             !extent_buffer_uptodate(info->dev_root->node) ||
8570             !extent_buffer_uptodate(info->chunk_root->node)) {
8571                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
8572                 ret = -EIO;
8573                 goto close_out;
8574         }
8575
8576         if (init_extent_tree || init_csum_tree) {
8577                 struct btrfs_trans_handle *trans;
8578
8579                 trans = btrfs_start_transaction(info->extent_root, 0);
8580                 if (IS_ERR(trans)) {
8581                         fprintf(stderr, "Error starting transaction\n");
8582                         ret = PTR_ERR(trans);
8583                         goto close_out;
8584                 }
8585
8586                 if (init_extent_tree) {
8587                         printf("Creating a new extent tree\n");
8588                         ret = reinit_extent_tree(trans, info);
8589                         if (ret)
8590                                 goto close_out;
8591                 }
8592
8593                 if (init_csum_tree) {
8594                         fprintf(stderr, "Reinit crc root\n");
8595                         ret = btrfs_fsck_reinit_root(trans, info->csum_root, 0);
8596                         if (ret) {
8597                                 fprintf(stderr, "crc root initialization failed\n");
8598                                 ret = -EIO;
8599                                 goto close_out;
8600                         }
8601
8602                         ret = fill_csum_tree(trans, info->csum_root);
8603                         if (ret) {
8604                                 fprintf(stderr, "crc refilling failed\n");
8605                                 return -EIO;
8606                         }
8607                 }
8608                 /*
8609                  * Ok now we commit and run the normal fsck, which will add
8610                  * extent entries for all of the items it finds.
8611                  */
8612                 ret = btrfs_commit_transaction(trans, info->extent_root);
8613                 if (ret)
8614                         goto close_out;
8615         }
8616         if (!extent_buffer_uptodate(info->extent_root->node)) {
8617                 fprintf(stderr, "Critical roots corrupted, unable to fsck the FS\n");
8618                 ret = -EIO;
8619                 goto close_out;
8620         }
8621         if (!extent_buffer_uptodate(info->csum_root->node)) {
8622                 fprintf(stderr, "Checksum root corrupted, rerun with --init-csum-tree option\n");
8623                 ret = -EIO;
8624                 goto close_out;
8625         }
8626
8627         fprintf(stderr, "checking extents\n");
8628         ret = check_chunks_and_extents(root);
8629         if (ret)
8630                 fprintf(stderr, "Errors found in extent allocation tree or chunk allocation\n");
8631
8632         ret = repair_root_items(info);
8633         if (ret < 0)
8634                 goto close_out;
8635         if (repair) {
8636                 fprintf(stderr, "Fixed %d roots.\n", ret);
8637                 ret = 0;
8638         } else if (ret > 0) {
8639                 fprintf(stderr,
8640                        "Found %d roots with an outdated root item.\n",
8641                        ret);
8642                 fprintf(stderr,
8643                         "Please run a filesystem check with the option --repair to fix them.\n");
8644                 ret = 1;
8645                 goto close_out;
8646         }
8647
8648         fprintf(stderr, "checking free space cache\n");
8649         ret = check_space_cache(root);
8650         if (ret)
8651                 goto out;
8652
8653         /*
8654          * We used to have to have these hole extents in between our real
8655          * extents so if we don't have this flag set we need to make sure there
8656          * are no gaps in the file extents for inodes, otherwise we can just
8657          * ignore it when this happens.
8658          */
8659         no_holes = btrfs_fs_incompat(root->fs_info,
8660                                      BTRFS_FEATURE_INCOMPAT_NO_HOLES);
8661         fprintf(stderr, "checking fs roots\n");
8662         ret = check_fs_roots(root, &root_cache);
8663         if (ret)
8664                 goto out;
8665
8666         fprintf(stderr, "checking csums\n");
8667         ret = check_csums(root);
8668         if (ret)
8669                 goto out;
8670
8671         fprintf(stderr, "checking root refs\n");
8672         ret = check_root_refs(root, &root_cache);
8673         if (ret)
8674                 goto out;
8675
8676         while (repair && !list_empty(&root->fs_info->recow_ebs)) {
8677                 struct extent_buffer *eb;
8678
8679                 eb = list_first_entry(&root->fs_info->recow_ebs,
8680                                       struct extent_buffer, recow);
8681                 list_del_init(&eb->recow);
8682                 ret = recow_extent_buffer(root, eb);
8683                 if (ret)
8684                         break;
8685         }
8686
8687         while (!list_empty(&delete_items)) {
8688                 struct bad_item *bad;
8689
8690                 bad = list_first_entry(&delete_items, struct bad_item, list);
8691                 list_del_init(&bad->list);
8692                 if (repair)
8693                         ret = delete_bad_item(root, bad);
8694                 free(bad);
8695         }
8696
8697         if (info->quota_enabled) {
8698                 int err;
8699                 fprintf(stderr, "checking quota groups\n");
8700                 err = qgroup_verify_all(info);
8701                 if (err)
8702                         goto out;
8703         }
8704
8705         if (!list_empty(&root->fs_info->recow_ebs)) {
8706                 fprintf(stderr, "Transid errors in file system\n");
8707                 ret = 1;
8708         }
8709 out:
8710         print_qgroup_report(0);
8711         if (found_old_backref) { /*
8712                  * there was a disk format change when mixed
8713                  * backref was in testing tree. The old format
8714                  * existed about one week.
8715                  */
8716                 printf("\n * Found old mixed backref format. "
8717                        "The old format is not supported! *"
8718                        "\n * Please mount the FS in readonly mode, "
8719                        "backup data and re-format the FS. *\n\n");
8720                 ret = 1;
8721         }
8722         printf("found %llu bytes used err is %d\n",
8723                (unsigned long long)bytes_used, ret);
8724         printf("total csum bytes: %llu\n",(unsigned long long)total_csum_bytes);
8725         printf("total tree bytes: %llu\n",
8726                (unsigned long long)total_btree_bytes);
8727         printf("total fs tree bytes: %llu\n",
8728                (unsigned long long)total_fs_tree_bytes);
8729         printf("total extent tree bytes: %llu\n",
8730                (unsigned long long)total_extent_tree_bytes);
8731         printf("btree space waste bytes: %llu\n",
8732                (unsigned long long)btree_space_waste);
8733         printf("file data blocks allocated: %llu\n referenced %llu\n",
8734                 (unsigned long long)data_bytes_allocated,
8735                 (unsigned long long)data_bytes_referenced);
8736         printf("%s\n", BTRFS_BUILD_VERSION);
8737
8738         free_root_recs_tree(&root_cache);
8739 close_out:
8740         close_ctree(root);
8741 err_out:
8742         return ret;
8743 }