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