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