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