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