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