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