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