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