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