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