btrfs: use nodesize everywhere, kill leafsize
[linux-2.6-block.git] / fs / btrfs / check-integrity.c
1 /*
2  * Copyright (C) STRATO AG 2011.  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 /*
20  * This module can be used to catch cases when the btrfs kernel
21  * code executes write requests to the disk that bring the file
22  * system in an inconsistent state. In such a state, a power-loss
23  * or kernel panic event would cause that the data on disk is
24  * lost or at least damaged.
25  *
26  * Code is added that examines all block write requests during
27  * runtime (including writes of the super block). Three rules
28  * are verified and an error is printed on violation of the
29  * rules:
30  * 1. It is not allowed to write a disk block which is
31  *    currently referenced by the super block (either directly
32  *    or indirectly).
33  * 2. When a super block is written, it is verified that all
34  *    referenced (directly or indirectly) blocks fulfill the
35  *    following requirements:
36  *    2a. All referenced blocks have either been present when
37  *        the file system was mounted, (i.e., they have been
38  *        referenced by the super block) or they have been
39  *        written since then and the write completion callback
40  *        was called and no write error was indicated and a
41  *        FLUSH request to the device where these blocks are
42  *        located was received and completed.
43  *    2b. All referenced blocks need to have a generation
44  *        number which is equal to the parent's number.
45  *
46  * One issue that was found using this module was that the log
47  * tree on disk became temporarily corrupted because disk blocks
48  * that had been in use for the log tree had been freed and
49  * reused too early, while being referenced by the written super
50  * block.
51  *
52  * The search term in the kernel log that can be used to filter
53  * on the existence of detected integrity issues is
54  * "btrfs: attempt".
55  *
56  * The integrity check is enabled via mount options. These
57  * mount options are only supported if the integrity check
58  * tool is compiled by defining BTRFS_FS_CHECK_INTEGRITY.
59  *
60  * Example #1, apply integrity checks to all metadata:
61  * mount /dev/sdb1 /mnt -o check_int
62  *
63  * Example #2, apply integrity checks to all metadata and
64  * to data extents:
65  * mount /dev/sdb1 /mnt -o check_int_data
66  *
67  * Example #3, apply integrity checks to all metadata and dump
68  * the tree that the super block references to kernel messages
69  * each time after a super block was written:
70  * mount /dev/sdb1 /mnt -o check_int,check_int_print_mask=263
71  *
72  * If the integrity check tool is included and activated in
73  * the mount options, plenty of kernel memory is used, and
74  * plenty of additional CPU cycles are spent. Enabling this
75  * functionality is not intended for normal use. In most
76  * cases, unless you are a btrfs developer who needs to verify
77  * the integrity of (super)-block write requests, do not
78  * enable the config option BTRFS_FS_CHECK_INTEGRITY to
79  * include and compile the integrity check tool.
80  *
81  * Expect millions of lines of information in the kernel log with an
82  * enabled check_int_print_mask. Therefore set LOG_BUF_SHIFT in the
83  * kernel config to at least 26 (which is 64MB). Usually the value is
84  * limited to 21 (which is 2MB) in init/Kconfig. The file needs to be
85  * changed like this before LOG_BUF_SHIFT can be set to a high value:
86  * config LOG_BUF_SHIFT
87  *       int "Kernel log buffer size (16 => 64KB, 17 => 128KB)"
88  *       range 12 30
89  */
90
91 #include <linux/sched.h>
92 #include <linux/slab.h>
93 #include <linux/buffer_head.h>
94 #include <linux/mutex.h>
95 #include <linux/genhd.h>
96 #include <linux/blkdev.h>
97 #include "ctree.h"
98 #include "disk-io.h"
99 #include "hash.h"
100 #include "transaction.h"
101 #include "extent_io.h"
102 #include "volumes.h"
103 #include "print-tree.h"
104 #include "locking.h"
105 #include "check-integrity.h"
106 #include "rcu-string.h"
107
108 #define BTRFSIC_BLOCK_HASHTABLE_SIZE 0x10000
109 #define BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE 0x10000
110 #define BTRFSIC_DEV2STATE_HASHTABLE_SIZE 0x100
111 #define BTRFSIC_BLOCK_MAGIC_NUMBER 0x14491051
112 #define BTRFSIC_BLOCK_LINK_MAGIC_NUMBER 0x11070807
113 #define BTRFSIC_DEV2STATE_MAGIC_NUMBER 0x20111530
114 #define BTRFSIC_BLOCK_STACK_FRAME_MAGIC_NUMBER 20111300
115 #define BTRFSIC_TREE_DUMP_MAX_INDENT_LEVEL (200 - 6)    /* in characters,
116                                                          * excluding " [...]" */
117 #define BTRFSIC_GENERATION_UNKNOWN ((u64)-1)
118
119 /*
120  * The definition of the bitmask fields for the print_mask.
121  * They are specified with the mount option check_integrity_print_mask.
122  */
123 #define BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE                     0x00000001
124 #define BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION         0x00000002
125 #define BTRFSIC_PRINT_MASK_TREE_AFTER_SB_WRITE                  0x00000004
126 #define BTRFSIC_PRINT_MASK_TREE_BEFORE_SB_WRITE                 0x00000008
127 #define BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH                        0x00000010
128 #define BTRFSIC_PRINT_MASK_END_IO_BIO_BH                        0x00000020
129 #define BTRFSIC_PRINT_MASK_VERBOSE                              0x00000040
130 #define BTRFSIC_PRINT_MASK_VERY_VERBOSE                         0x00000080
131 #define BTRFSIC_PRINT_MASK_INITIAL_TREE                         0x00000100
132 #define BTRFSIC_PRINT_MASK_INITIAL_ALL_TREES                    0x00000200
133 #define BTRFSIC_PRINT_MASK_INITIAL_DATABASE                     0x00000400
134 #define BTRFSIC_PRINT_MASK_NUM_COPIES                           0x00000800
135 #define BTRFSIC_PRINT_MASK_TREE_WITH_ALL_MIRRORS                0x00001000
136 #define BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH_VERBOSE                0x00002000
137
138 struct btrfsic_dev_state;
139 struct btrfsic_state;
140
141 struct btrfsic_block {
142         u32 magic_num;          /* only used for debug purposes */
143         unsigned int is_metadata:1;     /* if it is meta-data, not data-data */
144         unsigned int is_superblock:1;   /* if it is one of the superblocks */
145         unsigned int is_iodone:1;       /* if is done by lower subsystem */
146         unsigned int iodone_w_error:1;  /* error was indicated to endio */
147         unsigned int never_written:1;   /* block was added because it was
148                                          * referenced, not because it was
149                                          * written */
150         unsigned int mirror_num;        /* large enough to hold
151                                          * BTRFS_SUPER_MIRROR_MAX */
152         struct btrfsic_dev_state *dev_state;
153         u64 dev_bytenr;         /* key, physical byte num on disk */
154         u64 logical_bytenr;     /* logical byte num on disk */
155         u64 generation;
156         struct btrfs_disk_key disk_key; /* extra info to print in case of
157                                          * issues, will not always be correct */
158         struct list_head collision_resolving_node;      /* list node */
159         struct list_head all_blocks_node;       /* list node */
160
161         /* the following two lists contain block_link items */
162         struct list_head ref_to_list;   /* list */
163         struct list_head ref_from_list; /* list */
164         struct btrfsic_block *next_in_same_bio;
165         void *orig_bio_bh_private;
166         union {
167                 bio_end_io_t *bio;
168                 bh_end_io_t *bh;
169         } orig_bio_bh_end_io;
170         int submit_bio_bh_rw;
171         u64 flush_gen; /* only valid if !never_written */
172 };
173
174 /*
175  * Elements of this type are allocated dynamically and required because
176  * each block object can refer to and can be ref from multiple blocks.
177  * The key to lookup them in the hashtable is the dev_bytenr of
178  * the block ref to plus the one from the block refered from.
179  * The fact that they are searchable via a hashtable and that a
180  * ref_cnt is maintained is not required for the btrfs integrity
181  * check algorithm itself, it is only used to make the output more
182  * beautiful in case that an error is detected (an error is defined
183  * as a write operation to a block while that block is still referenced).
184  */
185 struct btrfsic_block_link {
186         u32 magic_num;          /* only used for debug purposes */
187         u32 ref_cnt;
188         struct list_head node_ref_to;   /* list node */
189         struct list_head node_ref_from; /* list node */
190         struct list_head collision_resolving_node;      /* list node */
191         struct btrfsic_block *block_ref_to;
192         struct btrfsic_block *block_ref_from;
193         u64 parent_generation;
194 };
195
196 struct btrfsic_dev_state {
197         u32 magic_num;          /* only used for debug purposes */
198         struct block_device *bdev;
199         struct btrfsic_state *state;
200         struct list_head collision_resolving_node;      /* list node */
201         struct btrfsic_block dummy_block_for_bio_bh_flush;
202         u64 last_flush_gen;
203         char name[BDEVNAME_SIZE];
204 };
205
206 struct btrfsic_block_hashtable {
207         struct list_head table[BTRFSIC_BLOCK_HASHTABLE_SIZE];
208 };
209
210 struct btrfsic_block_link_hashtable {
211         struct list_head table[BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE];
212 };
213
214 struct btrfsic_dev_state_hashtable {
215         struct list_head table[BTRFSIC_DEV2STATE_HASHTABLE_SIZE];
216 };
217
218 struct btrfsic_block_data_ctx {
219         u64 start;              /* virtual bytenr */
220         u64 dev_bytenr;         /* physical bytenr on device */
221         u32 len;
222         struct btrfsic_dev_state *dev;
223         char **datav;
224         struct page **pagev;
225         void *mem_to_free;
226 };
227
228 /* This structure is used to implement recursion without occupying
229  * any stack space, refer to btrfsic_process_metablock() */
230 struct btrfsic_stack_frame {
231         u32 magic;
232         u32 nr;
233         int error;
234         int i;
235         int limit_nesting;
236         int num_copies;
237         int mirror_num;
238         struct btrfsic_block *block;
239         struct btrfsic_block_data_ctx *block_ctx;
240         struct btrfsic_block *next_block;
241         struct btrfsic_block_data_ctx next_block_ctx;
242         struct btrfs_header *hdr;
243         struct btrfsic_stack_frame *prev;
244 };
245
246 /* Some state per mounted filesystem */
247 struct btrfsic_state {
248         u32 print_mask;
249         int include_extent_data;
250         int csum_size;
251         struct list_head all_blocks_list;
252         struct btrfsic_block_hashtable block_hashtable;
253         struct btrfsic_block_link_hashtable block_link_hashtable;
254         struct btrfs_root *root;
255         u64 max_superblock_generation;
256         struct btrfsic_block *latest_superblock;
257         u32 metablock_size;
258         u32 datablock_size;
259 };
260
261 static void btrfsic_block_init(struct btrfsic_block *b);
262 static struct btrfsic_block *btrfsic_block_alloc(void);
263 static void btrfsic_block_free(struct btrfsic_block *b);
264 static void btrfsic_block_link_init(struct btrfsic_block_link *n);
265 static struct btrfsic_block_link *btrfsic_block_link_alloc(void);
266 static void btrfsic_block_link_free(struct btrfsic_block_link *n);
267 static void btrfsic_dev_state_init(struct btrfsic_dev_state *ds);
268 static struct btrfsic_dev_state *btrfsic_dev_state_alloc(void);
269 static void btrfsic_dev_state_free(struct btrfsic_dev_state *ds);
270 static void btrfsic_block_hashtable_init(struct btrfsic_block_hashtable *h);
271 static void btrfsic_block_hashtable_add(struct btrfsic_block *b,
272                                         struct btrfsic_block_hashtable *h);
273 static void btrfsic_block_hashtable_remove(struct btrfsic_block *b);
274 static struct btrfsic_block *btrfsic_block_hashtable_lookup(
275                 struct block_device *bdev,
276                 u64 dev_bytenr,
277                 struct btrfsic_block_hashtable *h);
278 static void btrfsic_block_link_hashtable_init(
279                 struct btrfsic_block_link_hashtable *h);
280 static void btrfsic_block_link_hashtable_add(
281                 struct btrfsic_block_link *l,
282                 struct btrfsic_block_link_hashtable *h);
283 static void btrfsic_block_link_hashtable_remove(struct btrfsic_block_link *l);
284 static struct btrfsic_block_link *btrfsic_block_link_hashtable_lookup(
285                 struct block_device *bdev_ref_to,
286                 u64 dev_bytenr_ref_to,
287                 struct block_device *bdev_ref_from,
288                 u64 dev_bytenr_ref_from,
289                 struct btrfsic_block_link_hashtable *h);
290 static void btrfsic_dev_state_hashtable_init(
291                 struct btrfsic_dev_state_hashtable *h);
292 static void btrfsic_dev_state_hashtable_add(
293                 struct btrfsic_dev_state *ds,
294                 struct btrfsic_dev_state_hashtable *h);
295 static void btrfsic_dev_state_hashtable_remove(struct btrfsic_dev_state *ds);
296 static struct btrfsic_dev_state *btrfsic_dev_state_hashtable_lookup(
297                 struct block_device *bdev,
298                 struct btrfsic_dev_state_hashtable *h);
299 static struct btrfsic_stack_frame *btrfsic_stack_frame_alloc(void);
300 static void btrfsic_stack_frame_free(struct btrfsic_stack_frame *sf);
301 static int btrfsic_process_superblock(struct btrfsic_state *state,
302                                       struct btrfs_fs_devices *fs_devices);
303 static int btrfsic_process_metablock(struct btrfsic_state *state,
304                                      struct btrfsic_block *block,
305                                      struct btrfsic_block_data_ctx *block_ctx,
306                                      int limit_nesting, int force_iodone_flag);
307 static void btrfsic_read_from_block_data(
308         struct btrfsic_block_data_ctx *block_ctx,
309         void *dst, u32 offset, size_t len);
310 static int btrfsic_create_link_to_next_block(
311                 struct btrfsic_state *state,
312                 struct btrfsic_block *block,
313                 struct btrfsic_block_data_ctx
314                 *block_ctx, u64 next_bytenr,
315                 int limit_nesting,
316                 struct btrfsic_block_data_ctx *next_block_ctx,
317                 struct btrfsic_block **next_blockp,
318                 int force_iodone_flag,
319                 int *num_copiesp, int *mirror_nump,
320                 struct btrfs_disk_key *disk_key,
321                 u64 parent_generation);
322 static int btrfsic_handle_extent_data(struct btrfsic_state *state,
323                                       struct btrfsic_block *block,
324                                       struct btrfsic_block_data_ctx *block_ctx,
325                                       u32 item_offset, int force_iodone_flag);
326 static int btrfsic_map_block(struct btrfsic_state *state, u64 bytenr, u32 len,
327                              struct btrfsic_block_data_ctx *block_ctx_out,
328                              int mirror_num);
329 static int btrfsic_map_superblock(struct btrfsic_state *state, u64 bytenr,
330                                   u32 len, struct block_device *bdev,
331                                   struct btrfsic_block_data_ctx *block_ctx_out);
332 static void btrfsic_release_block_ctx(struct btrfsic_block_data_ctx *block_ctx);
333 static int btrfsic_read_block(struct btrfsic_state *state,
334                               struct btrfsic_block_data_ctx *block_ctx);
335 static void btrfsic_dump_database(struct btrfsic_state *state);
336 static int btrfsic_test_for_metadata(struct btrfsic_state *state,
337                                      char **datav, unsigned int num_pages);
338 static void btrfsic_process_written_block(struct btrfsic_dev_state *dev_state,
339                                           u64 dev_bytenr, char **mapped_datav,
340                                           unsigned int num_pages,
341                                           struct bio *bio, int *bio_is_patched,
342                                           struct buffer_head *bh,
343                                           int submit_bio_bh_rw);
344 static int btrfsic_process_written_superblock(
345                 struct btrfsic_state *state,
346                 struct btrfsic_block *const block,
347                 struct btrfs_super_block *const super_hdr);
348 static void btrfsic_bio_end_io(struct bio *bp, int bio_error_status);
349 static void btrfsic_bh_end_io(struct buffer_head *bh, int uptodate);
350 static int btrfsic_is_block_ref_by_superblock(const struct btrfsic_state *state,
351                                               const struct btrfsic_block *block,
352                                               int recursion_level);
353 static int btrfsic_check_all_ref_blocks(struct btrfsic_state *state,
354                                         struct btrfsic_block *const block,
355                                         int recursion_level);
356 static void btrfsic_print_add_link(const struct btrfsic_state *state,
357                                    const struct btrfsic_block_link *l);
358 static void btrfsic_print_rem_link(const struct btrfsic_state *state,
359                                    const struct btrfsic_block_link *l);
360 static char btrfsic_get_block_type(const struct btrfsic_state *state,
361                                    const struct btrfsic_block *block);
362 static void btrfsic_dump_tree(const struct btrfsic_state *state);
363 static void btrfsic_dump_tree_sub(const struct btrfsic_state *state,
364                                   const struct btrfsic_block *block,
365                                   int indent_level);
366 static struct btrfsic_block_link *btrfsic_block_link_lookup_or_add(
367                 struct btrfsic_state *state,
368                 struct btrfsic_block_data_ctx *next_block_ctx,
369                 struct btrfsic_block *next_block,
370                 struct btrfsic_block *from_block,
371                 u64 parent_generation);
372 static struct btrfsic_block *btrfsic_block_lookup_or_add(
373                 struct btrfsic_state *state,
374                 struct btrfsic_block_data_ctx *block_ctx,
375                 const char *additional_string,
376                 int is_metadata,
377                 int is_iodone,
378                 int never_written,
379                 int mirror_num,
380                 int *was_created);
381 static int btrfsic_process_superblock_dev_mirror(
382                 struct btrfsic_state *state,
383                 struct btrfsic_dev_state *dev_state,
384                 struct btrfs_device *device,
385                 int superblock_mirror_num,
386                 struct btrfsic_dev_state **selected_dev_state,
387                 struct btrfs_super_block *selected_super);
388 static struct btrfsic_dev_state *btrfsic_dev_state_lookup(
389                 struct block_device *bdev);
390 static void btrfsic_cmp_log_and_dev_bytenr(struct btrfsic_state *state,
391                                            u64 bytenr,
392                                            struct btrfsic_dev_state *dev_state,
393                                            u64 dev_bytenr);
394
395 static struct mutex btrfsic_mutex;
396 static int btrfsic_is_initialized;
397 static struct btrfsic_dev_state_hashtable btrfsic_dev_state_hashtable;
398
399
400 static void btrfsic_block_init(struct btrfsic_block *b)
401 {
402         b->magic_num = BTRFSIC_BLOCK_MAGIC_NUMBER;
403         b->dev_state = NULL;
404         b->dev_bytenr = 0;
405         b->logical_bytenr = 0;
406         b->generation = BTRFSIC_GENERATION_UNKNOWN;
407         b->disk_key.objectid = 0;
408         b->disk_key.type = 0;
409         b->disk_key.offset = 0;
410         b->is_metadata = 0;
411         b->is_superblock = 0;
412         b->is_iodone = 0;
413         b->iodone_w_error = 0;
414         b->never_written = 0;
415         b->mirror_num = 0;
416         b->next_in_same_bio = NULL;
417         b->orig_bio_bh_private = NULL;
418         b->orig_bio_bh_end_io.bio = NULL;
419         INIT_LIST_HEAD(&b->collision_resolving_node);
420         INIT_LIST_HEAD(&b->all_blocks_node);
421         INIT_LIST_HEAD(&b->ref_to_list);
422         INIT_LIST_HEAD(&b->ref_from_list);
423         b->submit_bio_bh_rw = 0;
424         b->flush_gen = 0;
425 }
426
427 static struct btrfsic_block *btrfsic_block_alloc(void)
428 {
429         struct btrfsic_block *b;
430
431         b = kzalloc(sizeof(*b), GFP_NOFS);
432         if (NULL != b)
433                 btrfsic_block_init(b);
434
435         return b;
436 }
437
438 static void btrfsic_block_free(struct btrfsic_block *b)
439 {
440         BUG_ON(!(NULL == b || BTRFSIC_BLOCK_MAGIC_NUMBER == b->magic_num));
441         kfree(b);
442 }
443
444 static void btrfsic_block_link_init(struct btrfsic_block_link *l)
445 {
446         l->magic_num = BTRFSIC_BLOCK_LINK_MAGIC_NUMBER;
447         l->ref_cnt = 1;
448         INIT_LIST_HEAD(&l->node_ref_to);
449         INIT_LIST_HEAD(&l->node_ref_from);
450         INIT_LIST_HEAD(&l->collision_resolving_node);
451         l->block_ref_to = NULL;
452         l->block_ref_from = NULL;
453 }
454
455 static struct btrfsic_block_link *btrfsic_block_link_alloc(void)
456 {
457         struct btrfsic_block_link *l;
458
459         l = kzalloc(sizeof(*l), GFP_NOFS);
460         if (NULL != l)
461                 btrfsic_block_link_init(l);
462
463         return l;
464 }
465
466 static void btrfsic_block_link_free(struct btrfsic_block_link *l)
467 {
468         BUG_ON(!(NULL == l || BTRFSIC_BLOCK_LINK_MAGIC_NUMBER == l->magic_num));
469         kfree(l);
470 }
471
472 static void btrfsic_dev_state_init(struct btrfsic_dev_state *ds)
473 {
474         ds->magic_num = BTRFSIC_DEV2STATE_MAGIC_NUMBER;
475         ds->bdev = NULL;
476         ds->state = NULL;
477         ds->name[0] = '\0';
478         INIT_LIST_HEAD(&ds->collision_resolving_node);
479         ds->last_flush_gen = 0;
480         btrfsic_block_init(&ds->dummy_block_for_bio_bh_flush);
481         ds->dummy_block_for_bio_bh_flush.is_iodone = 1;
482         ds->dummy_block_for_bio_bh_flush.dev_state = ds;
483 }
484
485 static struct btrfsic_dev_state *btrfsic_dev_state_alloc(void)
486 {
487         struct btrfsic_dev_state *ds;
488
489         ds = kzalloc(sizeof(*ds), GFP_NOFS);
490         if (NULL != ds)
491                 btrfsic_dev_state_init(ds);
492
493         return ds;
494 }
495
496 static void btrfsic_dev_state_free(struct btrfsic_dev_state *ds)
497 {
498         BUG_ON(!(NULL == ds ||
499                  BTRFSIC_DEV2STATE_MAGIC_NUMBER == ds->magic_num));
500         kfree(ds);
501 }
502
503 static void btrfsic_block_hashtable_init(struct btrfsic_block_hashtable *h)
504 {
505         int i;
506
507         for (i = 0; i < BTRFSIC_BLOCK_HASHTABLE_SIZE; i++)
508                 INIT_LIST_HEAD(h->table + i);
509 }
510
511 static void btrfsic_block_hashtable_add(struct btrfsic_block *b,
512                                         struct btrfsic_block_hashtable *h)
513 {
514         const unsigned int hashval =
515             (((unsigned int)(b->dev_bytenr >> 16)) ^
516              ((unsigned int)((uintptr_t)b->dev_state->bdev))) &
517              (BTRFSIC_BLOCK_HASHTABLE_SIZE - 1);
518
519         list_add(&b->collision_resolving_node, h->table + hashval);
520 }
521
522 static void btrfsic_block_hashtable_remove(struct btrfsic_block *b)
523 {
524         list_del(&b->collision_resolving_node);
525 }
526
527 static struct btrfsic_block *btrfsic_block_hashtable_lookup(
528                 struct block_device *bdev,
529                 u64 dev_bytenr,
530                 struct btrfsic_block_hashtable *h)
531 {
532         const unsigned int hashval =
533             (((unsigned int)(dev_bytenr >> 16)) ^
534              ((unsigned int)((uintptr_t)bdev))) &
535              (BTRFSIC_BLOCK_HASHTABLE_SIZE - 1);
536         struct list_head *elem;
537
538         list_for_each(elem, h->table + hashval) {
539                 struct btrfsic_block *const b =
540                     list_entry(elem, struct btrfsic_block,
541                                collision_resolving_node);
542
543                 if (b->dev_state->bdev == bdev && b->dev_bytenr == dev_bytenr)
544                         return b;
545         }
546
547         return NULL;
548 }
549
550 static void btrfsic_block_link_hashtable_init(
551                 struct btrfsic_block_link_hashtable *h)
552 {
553         int i;
554
555         for (i = 0; i < BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE; i++)
556                 INIT_LIST_HEAD(h->table + i);
557 }
558
559 static void btrfsic_block_link_hashtable_add(
560                 struct btrfsic_block_link *l,
561                 struct btrfsic_block_link_hashtable *h)
562 {
563         const unsigned int hashval =
564             (((unsigned int)(l->block_ref_to->dev_bytenr >> 16)) ^
565              ((unsigned int)(l->block_ref_from->dev_bytenr >> 16)) ^
566              ((unsigned int)((uintptr_t)l->block_ref_to->dev_state->bdev)) ^
567              ((unsigned int)((uintptr_t)l->block_ref_from->dev_state->bdev)))
568              & (BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE - 1);
569
570         BUG_ON(NULL == l->block_ref_to);
571         BUG_ON(NULL == l->block_ref_from);
572         list_add(&l->collision_resolving_node, h->table + hashval);
573 }
574
575 static void btrfsic_block_link_hashtable_remove(struct btrfsic_block_link *l)
576 {
577         list_del(&l->collision_resolving_node);
578 }
579
580 static struct btrfsic_block_link *btrfsic_block_link_hashtable_lookup(
581                 struct block_device *bdev_ref_to,
582                 u64 dev_bytenr_ref_to,
583                 struct block_device *bdev_ref_from,
584                 u64 dev_bytenr_ref_from,
585                 struct btrfsic_block_link_hashtable *h)
586 {
587         const unsigned int hashval =
588             (((unsigned int)(dev_bytenr_ref_to >> 16)) ^
589              ((unsigned int)(dev_bytenr_ref_from >> 16)) ^
590              ((unsigned int)((uintptr_t)bdev_ref_to)) ^
591              ((unsigned int)((uintptr_t)bdev_ref_from))) &
592              (BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE - 1);
593         struct list_head *elem;
594
595         list_for_each(elem, h->table + hashval) {
596                 struct btrfsic_block_link *const l =
597                     list_entry(elem, struct btrfsic_block_link,
598                                collision_resolving_node);
599
600                 BUG_ON(NULL == l->block_ref_to);
601                 BUG_ON(NULL == l->block_ref_from);
602                 if (l->block_ref_to->dev_state->bdev == bdev_ref_to &&
603                     l->block_ref_to->dev_bytenr == dev_bytenr_ref_to &&
604                     l->block_ref_from->dev_state->bdev == bdev_ref_from &&
605                     l->block_ref_from->dev_bytenr == dev_bytenr_ref_from)
606                         return l;
607         }
608
609         return NULL;
610 }
611
612 static void btrfsic_dev_state_hashtable_init(
613                 struct btrfsic_dev_state_hashtable *h)
614 {
615         int i;
616
617         for (i = 0; i < BTRFSIC_DEV2STATE_HASHTABLE_SIZE; i++)
618                 INIT_LIST_HEAD(h->table + i);
619 }
620
621 static void btrfsic_dev_state_hashtable_add(
622                 struct btrfsic_dev_state *ds,
623                 struct btrfsic_dev_state_hashtable *h)
624 {
625         const unsigned int hashval =
626             (((unsigned int)((uintptr_t)ds->bdev)) &
627              (BTRFSIC_DEV2STATE_HASHTABLE_SIZE - 1));
628
629         list_add(&ds->collision_resolving_node, h->table + hashval);
630 }
631
632 static void btrfsic_dev_state_hashtable_remove(struct btrfsic_dev_state *ds)
633 {
634         list_del(&ds->collision_resolving_node);
635 }
636
637 static struct btrfsic_dev_state *btrfsic_dev_state_hashtable_lookup(
638                 struct block_device *bdev,
639                 struct btrfsic_dev_state_hashtable *h)
640 {
641         const unsigned int hashval =
642             (((unsigned int)((uintptr_t)bdev)) &
643              (BTRFSIC_DEV2STATE_HASHTABLE_SIZE - 1));
644         struct list_head *elem;
645
646         list_for_each(elem, h->table + hashval) {
647                 struct btrfsic_dev_state *const ds =
648                     list_entry(elem, struct btrfsic_dev_state,
649                                collision_resolving_node);
650
651                 if (ds->bdev == bdev)
652                         return ds;
653         }
654
655         return NULL;
656 }
657
658 static int btrfsic_process_superblock(struct btrfsic_state *state,
659                                       struct btrfs_fs_devices *fs_devices)
660 {
661         int ret = 0;
662         struct btrfs_super_block *selected_super;
663         struct list_head *dev_head = &fs_devices->devices;
664         struct btrfs_device *device;
665         struct btrfsic_dev_state *selected_dev_state = NULL;
666         int pass;
667
668         BUG_ON(NULL == state);
669         selected_super = kzalloc(sizeof(*selected_super), GFP_NOFS);
670         if (NULL == selected_super) {
671                 printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
672                 return -1;
673         }
674
675         list_for_each_entry(device, dev_head, dev_list) {
676                 int i;
677                 struct btrfsic_dev_state *dev_state;
678
679                 if (!device->bdev || !device->name)
680                         continue;
681
682                 dev_state = btrfsic_dev_state_lookup(device->bdev);
683                 BUG_ON(NULL == dev_state);
684                 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
685                         ret = btrfsic_process_superblock_dev_mirror(
686                                         state, dev_state, device, i,
687                                         &selected_dev_state, selected_super);
688                         if (0 != ret && 0 == i) {
689                                 kfree(selected_super);
690                                 return ret;
691                         }
692                 }
693         }
694
695         if (NULL == state->latest_superblock) {
696                 printk(KERN_INFO "btrfsic: no superblock found!\n");
697                 kfree(selected_super);
698                 return -1;
699         }
700
701         state->csum_size = btrfs_super_csum_size(selected_super);
702
703         for (pass = 0; pass < 3; pass++) {
704                 int num_copies;
705                 int mirror_num;
706                 u64 next_bytenr;
707
708                 switch (pass) {
709                 case 0:
710                         next_bytenr = btrfs_super_root(selected_super);
711                         if (state->print_mask &
712                             BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
713                                 printk(KERN_INFO "root@%llu\n", next_bytenr);
714                         break;
715                 case 1:
716                         next_bytenr = btrfs_super_chunk_root(selected_super);
717                         if (state->print_mask &
718                             BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
719                                 printk(KERN_INFO "chunk@%llu\n", next_bytenr);
720                         break;
721                 case 2:
722                         next_bytenr = btrfs_super_log_root(selected_super);
723                         if (0 == next_bytenr)
724                                 continue;
725                         if (state->print_mask &
726                             BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
727                                 printk(KERN_INFO "log@%llu\n", next_bytenr);
728                         break;
729                 }
730
731                 num_copies =
732                     btrfs_num_copies(state->root->fs_info,
733                                      next_bytenr, state->metablock_size);
734                 if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
735                         printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
736                                next_bytenr, num_copies);
737
738                 for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
739                         struct btrfsic_block *next_block;
740                         struct btrfsic_block_data_ctx tmp_next_block_ctx;
741                         struct btrfsic_block_link *l;
742
743                         ret = btrfsic_map_block(state, next_bytenr,
744                                                 state->metablock_size,
745                                                 &tmp_next_block_ctx,
746                                                 mirror_num);
747                         if (ret) {
748                                 printk(KERN_INFO "btrfsic:"
749                                        " btrfsic_map_block(root @%llu,"
750                                        " mirror %d) failed!\n",
751                                        next_bytenr, mirror_num);
752                                 kfree(selected_super);
753                                 return -1;
754                         }
755
756                         next_block = btrfsic_block_hashtable_lookup(
757                                         tmp_next_block_ctx.dev->bdev,
758                                         tmp_next_block_ctx.dev_bytenr,
759                                         &state->block_hashtable);
760                         BUG_ON(NULL == next_block);
761
762                         l = btrfsic_block_link_hashtable_lookup(
763                                         tmp_next_block_ctx.dev->bdev,
764                                         tmp_next_block_ctx.dev_bytenr,
765                                         state->latest_superblock->dev_state->
766                                         bdev,
767                                         state->latest_superblock->dev_bytenr,
768                                         &state->block_link_hashtable);
769                         BUG_ON(NULL == l);
770
771                         ret = btrfsic_read_block(state, &tmp_next_block_ctx);
772                         if (ret < (int)PAGE_CACHE_SIZE) {
773                                 printk(KERN_INFO
774                                        "btrfsic: read @logical %llu failed!\n",
775                                        tmp_next_block_ctx.start);
776                                 btrfsic_release_block_ctx(&tmp_next_block_ctx);
777                                 kfree(selected_super);
778                                 return -1;
779                         }
780
781                         ret = btrfsic_process_metablock(state,
782                                                         next_block,
783                                                         &tmp_next_block_ctx,
784                                                         BTRFS_MAX_LEVEL + 3, 1);
785                         btrfsic_release_block_ctx(&tmp_next_block_ctx);
786                 }
787         }
788
789         kfree(selected_super);
790         return ret;
791 }
792
793 static int btrfsic_process_superblock_dev_mirror(
794                 struct btrfsic_state *state,
795                 struct btrfsic_dev_state *dev_state,
796                 struct btrfs_device *device,
797                 int superblock_mirror_num,
798                 struct btrfsic_dev_state **selected_dev_state,
799                 struct btrfs_super_block *selected_super)
800 {
801         struct btrfs_super_block *super_tmp;
802         u64 dev_bytenr;
803         struct buffer_head *bh;
804         struct btrfsic_block *superblock_tmp;
805         int pass;
806         struct block_device *const superblock_bdev = device->bdev;
807
808         /* super block bytenr is always the unmapped device bytenr */
809         dev_bytenr = btrfs_sb_offset(superblock_mirror_num);
810         if (dev_bytenr + BTRFS_SUPER_INFO_SIZE > device->total_bytes)
811                 return -1;
812         bh = __bread(superblock_bdev, dev_bytenr / 4096,
813                      BTRFS_SUPER_INFO_SIZE);
814         if (NULL == bh)
815                 return -1;
816         super_tmp = (struct btrfs_super_block *)
817             (bh->b_data + (dev_bytenr & 4095));
818
819         if (btrfs_super_bytenr(super_tmp) != dev_bytenr ||
820             btrfs_super_magic(super_tmp) != BTRFS_MAGIC ||
821             memcmp(device->uuid, super_tmp->dev_item.uuid, BTRFS_UUID_SIZE) ||
822             btrfs_super_nodesize(super_tmp) != state->metablock_size ||
823             btrfs_super_sectorsize(super_tmp) != state->datablock_size) {
824                 brelse(bh);
825                 return 0;
826         }
827
828         superblock_tmp =
829             btrfsic_block_hashtable_lookup(superblock_bdev,
830                                            dev_bytenr,
831                                            &state->block_hashtable);
832         if (NULL == superblock_tmp) {
833                 superblock_tmp = btrfsic_block_alloc();
834                 if (NULL == superblock_tmp) {
835                         printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
836                         brelse(bh);
837                         return -1;
838                 }
839                 /* for superblock, only the dev_bytenr makes sense */
840                 superblock_tmp->dev_bytenr = dev_bytenr;
841                 superblock_tmp->dev_state = dev_state;
842                 superblock_tmp->logical_bytenr = dev_bytenr;
843                 superblock_tmp->generation = btrfs_super_generation(super_tmp);
844                 superblock_tmp->is_metadata = 1;
845                 superblock_tmp->is_superblock = 1;
846                 superblock_tmp->is_iodone = 1;
847                 superblock_tmp->never_written = 0;
848                 superblock_tmp->mirror_num = 1 + superblock_mirror_num;
849                 if (state->print_mask & BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE)
850                         printk_in_rcu(KERN_INFO "New initial S-block (bdev %p, %s)"
851                                      " @%llu (%s/%llu/%d)\n",
852                                      superblock_bdev,
853                                      rcu_str_deref(device->name), dev_bytenr,
854                                      dev_state->name, dev_bytenr,
855                                      superblock_mirror_num);
856                 list_add(&superblock_tmp->all_blocks_node,
857                          &state->all_blocks_list);
858                 btrfsic_block_hashtable_add(superblock_tmp,
859                                             &state->block_hashtable);
860         }
861
862         /* select the one with the highest generation field */
863         if (btrfs_super_generation(super_tmp) >
864             state->max_superblock_generation ||
865             0 == state->max_superblock_generation) {
866                 memcpy(selected_super, super_tmp, sizeof(*selected_super));
867                 *selected_dev_state = dev_state;
868                 state->max_superblock_generation =
869                     btrfs_super_generation(super_tmp);
870                 state->latest_superblock = superblock_tmp;
871         }
872
873         for (pass = 0; pass < 3; pass++) {
874                 u64 next_bytenr;
875                 int num_copies;
876                 int mirror_num;
877                 const char *additional_string = NULL;
878                 struct btrfs_disk_key tmp_disk_key;
879
880                 tmp_disk_key.type = BTRFS_ROOT_ITEM_KEY;
881                 tmp_disk_key.offset = 0;
882                 switch (pass) {
883                 case 0:
884                         btrfs_set_disk_key_objectid(&tmp_disk_key,
885                                                     BTRFS_ROOT_TREE_OBJECTID);
886                         additional_string = "initial root ";
887                         next_bytenr = btrfs_super_root(super_tmp);
888                         break;
889                 case 1:
890                         btrfs_set_disk_key_objectid(&tmp_disk_key,
891                                                     BTRFS_CHUNK_TREE_OBJECTID);
892                         additional_string = "initial chunk ";
893                         next_bytenr = btrfs_super_chunk_root(super_tmp);
894                         break;
895                 case 2:
896                         btrfs_set_disk_key_objectid(&tmp_disk_key,
897                                                     BTRFS_TREE_LOG_OBJECTID);
898                         additional_string = "initial log ";
899                         next_bytenr = btrfs_super_log_root(super_tmp);
900                         if (0 == next_bytenr)
901                                 continue;
902                         break;
903                 }
904
905                 num_copies =
906                     btrfs_num_copies(state->root->fs_info,
907                                      next_bytenr, state->metablock_size);
908                 if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
909                         printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
910                                next_bytenr, num_copies);
911                 for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
912                         struct btrfsic_block *next_block;
913                         struct btrfsic_block_data_ctx tmp_next_block_ctx;
914                         struct btrfsic_block_link *l;
915
916                         if (btrfsic_map_block(state, next_bytenr,
917                                               state->metablock_size,
918                                               &tmp_next_block_ctx,
919                                               mirror_num)) {
920                                 printk(KERN_INFO "btrfsic: btrfsic_map_block("
921                                        "bytenr @%llu, mirror %d) failed!\n",
922                                        next_bytenr, mirror_num);
923                                 brelse(bh);
924                                 return -1;
925                         }
926
927                         next_block = btrfsic_block_lookup_or_add(
928                                         state, &tmp_next_block_ctx,
929                                         additional_string, 1, 1, 0,
930                                         mirror_num, NULL);
931                         if (NULL == next_block) {
932                                 btrfsic_release_block_ctx(&tmp_next_block_ctx);
933                                 brelse(bh);
934                                 return -1;
935                         }
936
937                         next_block->disk_key = tmp_disk_key;
938                         next_block->generation = BTRFSIC_GENERATION_UNKNOWN;
939                         l = btrfsic_block_link_lookup_or_add(
940                                         state, &tmp_next_block_ctx,
941                                         next_block, superblock_tmp,
942                                         BTRFSIC_GENERATION_UNKNOWN);
943                         btrfsic_release_block_ctx(&tmp_next_block_ctx);
944                         if (NULL == l) {
945                                 brelse(bh);
946                                 return -1;
947                         }
948                 }
949         }
950         if (state->print_mask & BTRFSIC_PRINT_MASK_INITIAL_ALL_TREES)
951                 btrfsic_dump_tree_sub(state, superblock_tmp, 0);
952
953         brelse(bh);
954         return 0;
955 }
956
957 static struct btrfsic_stack_frame *btrfsic_stack_frame_alloc(void)
958 {
959         struct btrfsic_stack_frame *sf;
960
961         sf = kzalloc(sizeof(*sf), GFP_NOFS);
962         if (NULL == sf)
963                 printk(KERN_INFO "btrfsic: alloc memory failed!\n");
964         else
965                 sf->magic = BTRFSIC_BLOCK_STACK_FRAME_MAGIC_NUMBER;
966         return sf;
967 }
968
969 static void btrfsic_stack_frame_free(struct btrfsic_stack_frame *sf)
970 {
971         BUG_ON(!(NULL == sf ||
972                  BTRFSIC_BLOCK_STACK_FRAME_MAGIC_NUMBER == sf->magic));
973         kfree(sf);
974 }
975
976 static int btrfsic_process_metablock(
977                 struct btrfsic_state *state,
978                 struct btrfsic_block *const first_block,
979                 struct btrfsic_block_data_ctx *const first_block_ctx,
980                 int first_limit_nesting, int force_iodone_flag)
981 {
982         struct btrfsic_stack_frame initial_stack_frame = { 0 };
983         struct btrfsic_stack_frame *sf;
984         struct btrfsic_stack_frame *next_stack;
985         struct btrfs_header *const first_hdr =
986                 (struct btrfs_header *)first_block_ctx->datav[0];
987
988         BUG_ON(!first_hdr);
989         sf = &initial_stack_frame;
990         sf->error = 0;
991         sf->i = -1;
992         sf->limit_nesting = first_limit_nesting;
993         sf->block = first_block;
994         sf->block_ctx = first_block_ctx;
995         sf->next_block = NULL;
996         sf->hdr = first_hdr;
997         sf->prev = NULL;
998
999 continue_with_new_stack_frame:
1000         sf->block->generation = le64_to_cpu(sf->hdr->generation);
1001         if (0 == sf->hdr->level) {
1002                 struct btrfs_leaf *const leafhdr =
1003                     (struct btrfs_leaf *)sf->hdr;
1004
1005                 if (-1 == sf->i) {
1006                         sf->nr = btrfs_stack_header_nritems(&leafhdr->header);
1007
1008                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1009                                 printk(KERN_INFO
1010                                        "leaf %llu items %d generation %llu"
1011                                        " owner %llu\n",
1012                                        sf->block_ctx->start, sf->nr,
1013                                        btrfs_stack_header_generation(
1014                                                &leafhdr->header),
1015                                        btrfs_stack_header_owner(
1016                                                &leafhdr->header));
1017                 }
1018
1019 continue_with_current_leaf_stack_frame:
1020                 if (0 == sf->num_copies || sf->mirror_num > sf->num_copies) {
1021                         sf->i++;
1022                         sf->num_copies = 0;
1023                 }
1024
1025                 if (sf->i < sf->nr) {
1026                         struct btrfs_item disk_item;
1027                         u32 disk_item_offset =
1028                                 (uintptr_t)(leafhdr->items + sf->i) -
1029                                 (uintptr_t)leafhdr;
1030                         struct btrfs_disk_key *disk_key;
1031                         u8 type;
1032                         u32 item_offset;
1033                         u32 item_size;
1034
1035                         if (disk_item_offset + sizeof(struct btrfs_item) >
1036                             sf->block_ctx->len) {
1037 leaf_item_out_of_bounce_error:
1038                                 printk(KERN_INFO
1039                                        "btrfsic: leaf item out of bounce at logical %llu, dev %s\n",
1040                                        sf->block_ctx->start,
1041                                        sf->block_ctx->dev->name);
1042                                 goto one_stack_frame_backwards;
1043                         }
1044                         btrfsic_read_from_block_data(sf->block_ctx,
1045                                                      &disk_item,
1046                                                      disk_item_offset,
1047                                                      sizeof(struct btrfs_item));
1048                         item_offset = btrfs_stack_item_offset(&disk_item);
1049                         item_size = btrfs_stack_item_size(&disk_item);
1050                         disk_key = &disk_item.key;
1051                         type = btrfs_disk_key_type(disk_key);
1052
1053                         if (BTRFS_ROOT_ITEM_KEY == type) {
1054                                 struct btrfs_root_item root_item;
1055                                 u32 root_item_offset;
1056                                 u64 next_bytenr;
1057
1058                                 root_item_offset = item_offset +
1059                                         offsetof(struct btrfs_leaf, items);
1060                                 if (root_item_offset + item_size >
1061                                     sf->block_ctx->len)
1062                                         goto leaf_item_out_of_bounce_error;
1063                                 btrfsic_read_from_block_data(
1064                                         sf->block_ctx, &root_item,
1065                                         root_item_offset,
1066                                         item_size);
1067                                 next_bytenr = btrfs_root_bytenr(&root_item);
1068
1069                                 sf->error =
1070                                     btrfsic_create_link_to_next_block(
1071                                                 state,
1072                                                 sf->block,
1073                                                 sf->block_ctx,
1074                                                 next_bytenr,
1075                                                 sf->limit_nesting,
1076                                                 &sf->next_block_ctx,
1077                                                 &sf->next_block,
1078                                                 force_iodone_flag,
1079                                                 &sf->num_copies,
1080                                                 &sf->mirror_num,
1081                                                 disk_key,
1082                                                 btrfs_root_generation(
1083                                                 &root_item));
1084                                 if (sf->error)
1085                                         goto one_stack_frame_backwards;
1086
1087                                 if (NULL != sf->next_block) {
1088                                         struct btrfs_header *const next_hdr =
1089                                             (struct btrfs_header *)
1090                                             sf->next_block_ctx.datav[0];
1091
1092                                         next_stack =
1093                                             btrfsic_stack_frame_alloc();
1094                                         if (NULL == next_stack) {
1095                                                 sf->error = -1;
1096                                                 btrfsic_release_block_ctx(
1097                                                                 &sf->
1098                                                                 next_block_ctx);
1099                                                 goto one_stack_frame_backwards;
1100                                         }
1101
1102                                         next_stack->i = -1;
1103                                         next_stack->block = sf->next_block;
1104                                         next_stack->block_ctx =
1105                                             &sf->next_block_ctx;
1106                                         next_stack->next_block = NULL;
1107                                         next_stack->hdr = next_hdr;
1108                                         next_stack->limit_nesting =
1109                                             sf->limit_nesting - 1;
1110                                         next_stack->prev = sf;
1111                                         sf = next_stack;
1112                                         goto continue_with_new_stack_frame;
1113                                 }
1114                         } else if (BTRFS_EXTENT_DATA_KEY == type &&
1115                                    state->include_extent_data) {
1116                                 sf->error = btrfsic_handle_extent_data(
1117                                                 state,
1118                                                 sf->block,
1119                                                 sf->block_ctx,
1120                                                 item_offset,
1121                                                 force_iodone_flag);
1122                                 if (sf->error)
1123                                         goto one_stack_frame_backwards;
1124                         }
1125
1126                         goto continue_with_current_leaf_stack_frame;
1127                 }
1128         } else {
1129                 struct btrfs_node *const nodehdr = (struct btrfs_node *)sf->hdr;
1130
1131                 if (-1 == sf->i) {
1132                         sf->nr = btrfs_stack_header_nritems(&nodehdr->header);
1133
1134                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1135                                 printk(KERN_INFO "node %llu level %d items %d"
1136                                        " generation %llu owner %llu\n",
1137                                        sf->block_ctx->start,
1138                                        nodehdr->header.level, sf->nr,
1139                                        btrfs_stack_header_generation(
1140                                        &nodehdr->header),
1141                                        btrfs_stack_header_owner(
1142                                        &nodehdr->header));
1143                 }
1144
1145 continue_with_current_node_stack_frame:
1146                 if (0 == sf->num_copies || sf->mirror_num > sf->num_copies) {
1147                         sf->i++;
1148                         sf->num_copies = 0;
1149                 }
1150
1151                 if (sf->i < sf->nr) {
1152                         struct btrfs_key_ptr key_ptr;
1153                         u32 key_ptr_offset;
1154                         u64 next_bytenr;
1155
1156                         key_ptr_offset = (uintptr_t)(nodehdr->ptrs + sf->i) -
1157                                           (uintptr_t)nodehdr;
1158                         if (key_ptr_offset + sizeof(struct btrfs_key_ptr) >
1159                             sf->block_ctx->len) {
1160                                 printk(KERN_INFO
1161                                        "btrfsic: node item out of bounce at logical %llu, dev %s\n",
1162                                        sf->block_ctx->start,
1163                                        sf->block_ctx->dev->name);
1164                                 goto one_stack_frame_backwards;
1165                         }
1166                         btrfsic_read_from_block_data(
1167                                 sf->block_ctx, &key_ptr, key_ptr_offset,
1168                                 sizeof(struct btrfs_key_ptr));
1169                         next_bytenr = btrfs_stack_key_blockptr(&key_ptr);
1170
1171                         sf->error = btrfsic_create_link_to_next_block(
1172                                         state,
1173                                         sf->block,
1174                                         sf->block_ctx,
1175                                         next_bytenr,
1176                                         sf->limit_nesting,
1177                                         &sf->next_block_ctx,
1178                                         &sf->next_block,
1179                                         force_iodone_flag,
1180                                         &sf->num_copies,
1181                                         &sf->mirror_num,
1182                                         &key_ptr.key,
1183                                         btrfs_stack_key_generation(&key_ptr));
1184                         if (sf->error)
1185                                 goto one_stack_frame_backwards;
1186
1187                         if (NULL != sf->next_block) {
1188                                 struct btrfs_header *const next_hdr =
1189                                     (struct btrfs_header *)
1190                                     sf->next_block_ctx.datav[0];
1191
1192                                 next_stack = btrfsic_stack_frame_alloc();
1193                                 if (NULL == next_stack) {
1194                                         sf->error = -1;
1195                                         goto one_stack_frame_backwards;
1196                                 }
1197
1198                                 next_stack->i = -1;
1199                                 next_stack->block = sf->next_block;
1200                                 next_stack->block_ctx = &sf->next_block_ctx;
1201                                 next_stack->next_block = NULL;
1202                                 next_stack->hdr = next_hdr;
1203                                 next_stack->limit_nesting =
1204                                     sf->limit_nesting - 1;
1205                                 next_stack->prev = sf;
1206                                 sf = next_stack;
1207                                 goto continue_with_new_stack_frame;
1208                         }
1209
1210                         goto continue_with_current_node_stack_frame;
1211                 }
1212         }
1213
1214 one_stack_frame_backwards:
1215         if (NULL != sf->prev) {
1216                 struct btrfsic_stack_frame *const prev = sf->prev;
1217
1218                 /* the one for the initial block is freed in the caller */
1219                 btrfsic_release_block_ctx(sf->block_ctx);
1220
1221                 if (sf->error) {
1222                         prev->error = sf->error;
1223                         btrfsic_stack_frame_free(sf);
1224                         sf = prev;
1225                         goto one_stack_frame_backwards;
1226                 }
1227
1228                 btrfsic_stack_frame_free(sf);
1229                 sf = prev;
1230                 goto continue_with_new_stack_frame;
1231         } else {
1232                 BUG_ON(&initial_stack_frame != sf);
1233         }
1234
1235         return sf->error;
1236 }
1237
1238 static void btrfsic_read_from_block_data(
1239         struct btrfsic_block_data_ctx *block_ctx,
1240         void *dstv, u32 offset, size_t len)
1241 {
1242         size_t cur;
1243         size_t offset_in_page;
1244         char *kaddr;
1245         char *dst = (char *)dstv;
1246         size_t start_offset = block_ctx->start & ((u64)PAGE_CACHE_SIZE - 1);
1247         unsigned long i = (start_offset + offset) >> PAGE_CACHE_SHIFT;
1248
1249         WARN_ON(offset + len > block_ctx->len);
1250         offset_in_page = (start_offset + offset) & (PAGE_CACHE_SIZE - 1);
1251
1252         while (len > 0) {
1253                 cur = min(len, ((size_t)PAGE_CACHE_SIZE - offset_in_page));
1254                 BUG_ON(i >= (block_ctx->len + PAGE_CACHE_SIZE - 1) >>
1255                             PAGE_CACHE_SHIFT);
1256                 kaddr = block_ctx->datav[i];
1257                 memcpy(dst, kaddr + offset_in_page, cur);
1258
1259                 dst += cur;
1260                 len -= cur;
1261                 offset_in_page = 0;
1262                 i++;
1263         }
1264 }
1265
1266 static int btrfsic_create_link_to_next_block(
1267                 struct btrfsic_state *state,
1268                 struct btrfsic_block *block,
1269                 struct btrfsic_block_data_ctx *block_ctx,
1270                 u64 next_bytenr,
1271                 int limit_nesting,
1272                 struct btrfsic_block_data_ctx *next_block_ctx,
1273                 struct btrfsic_block **next_blockp,
1274                 int force_iodone_flag,
1275                 int *num_copiesp, int *mirror_nump,
1276                 struct btrfs_disk_key *disk_key,
1277                 u64 parent_generation)
1278 {
1279         struct btrfsic_block *next_block = NULL;
1280         int ret;
1281         struct btrfsic_block_link *l;
1282         int did_alloc_block_link;
1283         int block_was_created;
1284
1285         *next_blockp = NULL;
1286         if (0 == *num_copiesp) {
1287                 *num_copiesp =
1288                     btrfs_num_copies(state->root->fs_info,
1289                                      next_bytenr, state->metablock_size);
1290                 if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
1291                         printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
1292                                next_bytenr, *num_copiesp);
1293                 *mirror_nump = 1;
1294         }
1295
1296         if (*mirror_nump > *num_copiesp)
1297                 return 0;
1298
1299         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1300                 printk(KERN_INFO
1301                        "btrfsic_create_link_to_next_block(mirror_num=%d)\n",
1302                        *mirror_nump);
1303         ret = btrfsic_map_block(state, next_bytenr,
1304                                 state->metablock_size,
1305                                 next_block_ctx, *mirror_nump);
1306         if (ret) {
1307                 printk(KERN_INFO
1308                        "btrfsic: btrfsic_map_block(@%llu, mirror=%d) failed!\n",
1309                        next_bytenr, *mirror_nump);
1310                 btrfsic_release_block_ctx(next_block_ctx);
1311                 *next_blockp = NULL;
1312                 return -1;
1313         }
1314
1315         next_block = btrfsic_block_lookup_or_add(state,
1316                                                  next_block_ctx, "referenced ",
1317                                                  1, force_iodone_flag,
1318                                                  !force_iodone_flag,
1319                                                  *mirror_nump,
1320                                                  &block_was_created);
1321         if (NULL == next_block) {
1322                 btrfsic_release_block_ctx(next_block_ctx);
1323                 *next_blockp = NULL;
1324                 return -1;
1325         }
1326         if (block_was_created) {
1327                 l = NULL;
1328                 next_block->generation = BTRFSIC_GENERATION_UNKNOWN;
1329         } else {
1330                 if (next_block->logical_bytenr != next_bytenr &&
1331                     !(!next_block->is_metadata &&
1332                       0 == next_block->logical_bytenr)) {
1333                         printk(KERN_INFO
1334                                "Referenced block @%llu (%s/%llu/%d)"
1335                                " found in hash table, %c,"
1336                                " bytenr mismatch (!= stored %llu).\n",
1337                                next_bytenr, next_block_ctx->dev->name,
1338                                next_block_ctx->dev_bytenr, *mirror_nump,
1339                                btrfsic_get_block_type(state, next_block),
1340                                next_block->logical_bytenr);
1341                 } else if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1342                         printk(KERN_INFO
1343                                "Referenced block @%llu (%s/%llu/%d)"
1344                                " found in hash table, %c.\n",
1345                                next_bytenr, next_block_ctx->dev->name,
1346                                next_block_ctx->dev_bytenr, *mirror_nump,
1347                                btrfsic_get_block_type(state, next_block));
1348                 next_block->logical_bytenr = next_bytenr;
1349
1350                 next_block->mirror_num = *mirror_nump;
1351                 l = btrfsic_block_link_hashtable_lookup(
1352                                 next_block_ctx->dev->bdev,
1353                                 next_block_ctx->dev_bytenr,
1354                                 block_ctx->dev->bdev,
1355                                 block_ctx->dev_bytenr,
1356                                 &state->block_link_hashtable);
1357         }
1358
1359         next_block->disk_key = *disk_key;
1360         if (NULL == l) {
1361                 l = btrfsic_block_link_alloc();
1362                 if (NULL == l) {
1363                         printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
1364                         btrfsic_release_block_ctx(next_block_ctx);
1365                         *next_blockp = NULL;
1366                         return -1;
1367                 }
1368
1369                 did_alloc_block_link = 1;
1370                 l->block_ref_to = next_block;
1371                 l->block_ref_from = block;
1372                 l->ref_cnt = 1;
1373                 l->parent_generation = parent_generation;
1374
1375                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1376                         btrfsic_print_add_link(state, l);
1377
1378                 list_add(&l->node_ref_to, &block->ref_to_list);
1379                 list_add(&l->node_ref_from, &next_block->ref_from_list);
1380
1381                 btrfsic_block_link_hashtable_add(l,
1382                                                  &state->block_link_hashtable);
1383         } else {
1384                 did_alloc_block_link = 0;
1385                 if (0 == limit_nesting) {
1386                         l->ref_cnt++;
1387                         l->parent_generation = parent_generation;
1388                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1389                                 btrfsic_print_add_link(state, l);
1390                 }
1391         }
1392
1393         if (limit_nesting > 0 && did_alloc_block_link) {
1394                 ret = btrfsic_read_block(state, next_block_ctx);
1395                 if (ret < (int)next_block_ctx->len) {
1396                         printk(KERN_INFO
1397                                "btrfsic: read block @logical %llu failed!\n",
1398                                next_bytenr);
1399                         btrfsic_release_block_ctx(next_block_ctx);
1400                         *next_blockp = NULL;
1401                         return -1;
1402                 }
1403
1404                 *next_blockp = next_block;
1405         } else {
1406                 *next_blockp = NULL;
1407         }
1408         (*mirror_nump)++;
1409
1410         return 0;
1411 }
1412
1413 static int btrfsic_handle_extent_data(
1414                 struct btrfsic_state *state,
1415                 struct btrfsic_block *block,
1416                 struct btrfsic_block_data_ctx *block_ctx,
1417                 u32 item_offset, int force_iodone_flag)
1418 {
1419         int ret;
1420         struct btrfs_file_extent_item file_extent_item;
1421         u64 file_extent_item_offset;
1422         u64 next_bytenr;
1423         u64 num_bytes;
1424         u64 generation;
1425         struct btrfsic_block_link *l;
1426
1427         file_extent_item_offset = offsetof(struct btrfs_leaf, items) +
1428                                   item_offset;
1429         if (file_extent_item_offset +
1430             offsetof(struct btrfs_file_extent_item, disk_num_bytes) >
1431             block_ctx->len) {
1432                 printk(KERN_INFO
1433                        "btrfsic: file item out of bounce at logical %llu, dev %s\n",
1434                        block_ctx->start, block_ctx->dev->name);
1435                 return -1;
1436         }
1437
1438         btrfsic_read_from_block_data(block_ctx, &file_extent_item,
1439                 file_extent_item_offset,
1440                 offsetof(struct btrfs_file_extent_item, disk_num_bytes));
1441         if (BTRFS_FILE_EXTENT_REG != file_extent_item.type ||
1442             btrfs_stack_file_extent_disk_bytenr(&file_extent_item) == 0) {
1443                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERY_VERBOSE)
1444                         printk(KERN_INFO "extent_data: type %u, disk_bytenr = %llu\n",
1445                                file_extent_item.type,
1446                                btrfs_stack_file_extent_disk_bytenr(
1447                                &file_extent_item));
1448                 return 0;
1449         }
1450
1451         if (file_extent_item_offset + sizeof(struct btrfs_file_extent_item) >
1452             block_ctx->len) {
1453                 printk(KERN_INFO
1454                        "btrfsic: file item out of bounce at logical %llu, dev %s\n",
1455                        block_ctx->start, block_ctx->dev->name);
1456                 return -1;
1457         }
1458         btrfsic_read_from_block_data(block_ctx, &file_extent_item,
1459                                      file_extent_item_offset,
1460                                      sizeof(struct btrfs_file_extent_item));
1461         next_bytenr = btrfs_stack_file_extent_disk_bytenr(&file_extent_item);
1462         if (btrfs_stack_file_extent_compression(&file_extent_item) ==
1463             BTRFS_COMPRESS_NONE) {
1464                 next_bytenr += btrfs_stack_file_extent_offset(&file_extent_item);
1465                 num_bytes = btrfs_stack_file_extent_num_bytes(&file_extent_item);
1466         } else {
1467                 num_bytes = btrfs_stack_file_extent_disk_num_bytes(&file_extent_item);
1468         }
1469         generation = btrfs_stack_file_extent_generation(&file_extent_item);
1470
1471         if (state->print_mask & BTRFSIC_PRINT_MASK_VERY_VERBOSE)
1472                 printk(KERN_INFO "extent_data: type %u, disk_bytenr = %llu,"
1473                        " offset = %llu, num_bytes = %llu\n",
1474                        file_extent_item.type,
1475                        btrfs_stack_file_extent_disk_bytenr(&file_extent_item),
1476                        btrfs_stack_file_extent_offset(&file_extent_item),
1477                        num_bytes);
1478         while (num_bytes > 0) {
1479                 u32 chunk_len;
1480                 int num_copies;
1481                 int mirror_num;
1482
1483                 if (num_bytes > state->datablock_size)
1484                         chunk_len = state->datablock_size;
1485                 else
1486                         chunk_len = num_bytes;
1487
1488                 num_copies =
1489                     btrfs_num_copies(state->root->fs_info,
1490                                      next_bytenr, state->datablock_size);
1491                 if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
1492                         printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
1493                                next_bytenr, num_copies);
1494                 for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
1495                         struct btrfsic_block_data_ctx next_block_ctx;
1496                         struct btrfsic_block *next_block;
1497                         int block_was_created;
1498
1499                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1500                                 printk(KERN_INFO "btrfsic_handle_extent_data("
1501                                        "mirror_num=%d)\n", mirror_num);
1502                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERY_VERBOSE)
1503                                 printk(KERN_INFO
1504                                        "\tdisk_bytenr = %llu, num_bytes %u\n",
1505                                        next_bytenr, chunk_len);
1506                         ret = btrfsic_map_block(state, next_bytenr,
1507                                                 chunk_len, &next_block_ctx,
1508                                                 mirror_num);
1509                         if (ret) {
1510                                 printk(KERN_INFO
1511                                        "btrfsic: btrfsic_map_block(@%llu,"
1512                                        " mirror=%d) failed!\n",
1513                                        next_bytenr, mirror_num);
1514                                 return -1;
1515                         }
1516
1517                         next_block = btrfsic_block_lookup_or_add(
1518                                         state,
1519                                         &next_block_ctx,
1520                                         "referenced ",
1521                                         0,
1522                                         force_iodone_flag,
1523                                         !force_iodone_flag,
1524                                         mirror_num,
1525                                         &block_was_created);
1526                         if (NULL == next_block) {
1527                                 printk(KERN_INFO
1528                                        "btrfsic: error, kmalloc failed!\n");
1529                                 btrfsic_release_block_ctx(&next_block_ctx);
1530                                 return -1;
1531                         }
1532                         if (!block_was_created) {
1533                                 if (next_block->logical_bytenr != next_bytenr &&
1534                                     !(!next_block->is_metadata &&
1535                                       0 == next_block->logical_bytenr)) {
1536                                         printk(KERN_INFO
1537                                                "Referenced block"
1538                                                " @%llu (%s/%llu/%d)"
1539                                                " found in hash table, D,"
1540                                                " bytenr mismatch"
1541                                                " (!= stored %llu).\n",
1542                                                next_bytenr,
1543                                                next_block_ctx.dev->name,
1544                                                next_block_ctx.dev_bytenr,
1545                                                mirror_num,
1546                                                next_block->logical_bytenr);
1547                                 }
1548                                 next_block->logical_bytenr = next_bytenr;
1549                                 next_block->mirror_num = mirror_num;
1550                         }
1551
1552                         l = btrfsic_block_link_lookup_or_add(state,
1553                                                              &next_block_ctx,
1554                                                              next_block, block,
1555                                                              generation);
1556                         btrfsic_release_block_ctx(&next_block_ctx);
1557                         if (NULL == l)
1558                                 return -1;
1559                 }
1560
1561                 next_bytenr += chunk_len;
1562                 num_bytes -= chunk_len;
1563         }
1564
1565         return 0;
1566 }
1567
1568 static int btrfsic_map_block(struct btrfsic_state *state, u64 bytenr, u32 len,
1569                              struct btrfsic_block_data_ctx *block_ctx_out,
1570                              int mirror_num)
1571 {
1572         int ret;
1573         u64 length;
1574         struct btrfs_bio *multi = NULL;
1575         struct btrfs_device *device;
1576
1577         length = len;
1578         ret = btrfs_map_block(state->root->fs_info, READ,
1579                               bytenr, &length, &multi, mirror_num);
1580
1581         if (ret) {
1582                 block_ctx_out->start = 0;
1583                 block_ctx_out->dev_bytenr = 0;
1584                 block_ctx_out->len = 0;
1585                 block_ctx_out->dev = NULL;
1586                 block_ctx_out->datav = NULL;
1587                 block_ctx_out->pagev = NULL;
1588                 block_ctx_out->mem_to_free = NULL;
1589
1590                 return ret;
1591         }
1592
1593         device = multi->stripes[0].dev;
1594         block_ctx_out->dev = btrfsic_dev_state_lookup(device->bdev);
1595         block_ctx_out->dev_bytenr = multi->stripes[0].physical;
1596         block_ctx_out->start = bytenr;
1597         block_ctx_out->len = len;
1598         block_ctx_out->datav = NULL;
1599         block_ctx_out->pagev = NULL;
1600         block_ctx_out->mem_to_free = NULL;
1601
1602         kfree(multi);
1603         if (NULL == block_ctx_out->dev) {
1604                 ret = -ENXIO;
1605                 printk(KERN_INFO "btrfsic: error, cannot lookup dev (#1)!\n");
1606         }
1607
1608         return ret;
1609 }
1610
1611 static int btrfsic_map_superblock(struct btrfsic_state *state, u64 bytenr,
1612                                   u32 len, struct block_device *bdev,
1613                                   struct btrfsic_block_data_ctx *block_ctx_out)
1614 {
1615         block_ctx_out->dev = btrfsic_dev_state_lookup(bdev);
1616         block_ctx_out->dev_bytenr = bytenr;
1617         block_ctx_out->start = bytenr;
1618         block_ctx_out->len = len;
1619         block_ctx_out->datav = NULL;
1620         block_ctx_out->pagev = NULL;
1621         block_ctx_out->mem_to_free = NULL;
1622         if (NULL != block_ctx_out->dev) {
1623                 return 0;
1624         } else {
1625                 printk(KERN_INFO "btrfsic: error, cannot lookup dev (#2)!\n");
1626                 return -ENXIO;
1627         }
1628 }
1629
1630 static void btrfsic_release_block_ctx(struct btrfsic_block_data_ctx *block_ctx)
1631 {
1632         if (block_ctx->mem_to_free) {
1633                 unsigned int num_pages;
1634
1635                 BUG_ON(!block_ctx->datav);
1636                 BUG_ON(!block_ctx->pagev);
1637                 num_pages = (block_ctx->len + (u64)PAGE_CACHE_SIZE - 1) >>
1638                             PAGE_CACHE_SHIFT;
1639                 while (num_pages > 0) {
1640                         num_pages--;
1641                         if (block_ctx->datav[num_pages]) {
1642                                 kunmap(block_ctx->pagev[num_pages]);
1643                                 block_ctx->datav[num_pages] = NULL;
1644                         }
1645                         if (block_ctx->pagev[num_pages]) {
1646                                 __free_page(block_ctx->pagev[num_pages]);
1647                                 block_ctx->pagev[num_pages] = NULL;
1648                         }
1649                 }
1650
1651                 kfree(block_ctx->mem_to_free);
1652                 block_ctx->mem_to_free = NULL;
1653                 block_ctx->pagev = NULL;
1654                 block_ctx->datav = NULL;
1655         }
1656 }
1657
1658 static int btrfsic_read_block(struct btrfsic_state *state,
1659                               struct btrfsic_block_data_ctx *block_ctx)
1660 {
1661         unsigned int num_pages;
1662         unsigned int i;
1663         u64 dev_bytenr;
1664         int ret;
1665
1666         BUG_ON(block_ctx->datav);
1667         BUG_ON(block_ctx->pagev);
1668         BUG_ON(block_ctx->mem_to_free);
1669         if (block_ctx->dev_bytenr & ((u64)PAGE_CACHE_SIZE - 1)) {
1670                 printk(KERN_INFO
1671                        "btrfsic: read_block() with unaligned bytenr %llu\n",
1672                        block_ctx->dev_bytenr);
1673                 return -1;
1674         }
1675
1676         num_pages = (block_ctx->len + (u64)PAGE_CACHE_SIZE - 1) >>
1677                     PAGE_CACHE_SHIFT;
1678         block_ctx->mem_to_free = kzalloc((sizeof(*block_ctx->datav) +
1679                                           sizeof(*block_ctx->pagev)) *
1680                                          num_pages, GFP_NOFS);
1681         if (!block_ctx->mem_to_free)
1682                 return -1;
1683         block_ctx->datav = block_ctx->mem_to_free;
1684         block_ctx->pagev = (struct page **)(block_ctx->datav + num_pages);
1685         for (i = 0; i < num_pages; i++) {
1686                 block_ctx->pagev[i] = alloc_page(GFP_NOFS);
1687                 if (!block_ctx->pagev[i])
1688                         return -1;
1689         }
1690
1691         dev_bytenr = block_ctx->dev_bytenr;
1692         for (i = 0; i < num_pages;) {
1693                 struct bio *bio;
1694                 unsigned int j;
1695
1696                 bio = btrfs_io_bio_alloc(GFP_NOFS, num_pages - i);
1697                 if (!bio) {
1698                         printk(KERN_INFO
1699                                "btrfsic: bio_alloc() for %u pages failed!\n",
1700                                num_pages - i);
1701                         return -1;
1702                 }
1703                 bio->bi_bdev = block_ctx->dev->bdev;
1704                 bio->bi_iter.bi_sector = dev_bytenr >> 9;
1705
1706                 for (j = i; j < num_pages; j++) {
1707                         ret = bio_add_page(bio, block_ctx->pagev[j],
1708                                            PAGE_CACHE_SIZE, 0);
1709                         if (PAGE_CACHE_SIZE != ret)
1710                                 break;
1711                 }
1712                 if (j == i) {
1713                         printk(KERN_INFO
1714                                "btrfsic: error, failed to add a single page!\n");
1715                         return -1;
1716                 }
1717                 if (submit_bio_wait(READ, bio)) {
1718                         printk(KERN_INFO
1719                                "btrfsic: read error at logical %llu dev %s!\n",
1720                                block_ctx->start, block_ctx->dev->name);
1721                         bio_put(bio);
1722                         return -1;
1723                 }
1724                 bio_put(bio);
1725                 dev_bytenr += (j - i) * PAGE_CACHE_SIZE;
1726                 i = j;
1727         }
1728         for (i = 0; i < num_pages; i++) {
1729                 block_ctx->datav[i] = kmap(block_ctx->pagev[i]);
1730                 if (!block_ctx->datav[i]) {
1731                         printk(KERN_INFO "btrfsic: kmap() failed (dev %s)!\n",
1732                                block_ctx->dev->name);
1733                         return -1;
1734                 }
1735         }
1736
1737         return block_ctx->len;
1738 }
1739
1740 static void btrfsic_dump_database(struct btrfsic_state *state)
1741 {
1742         struct list_head *elem_all;
1743
1744         BUG_ON(NULL == state);
1745
1746         printk(KERN_INFO "all_blocks_list:\n");
1747         list_for_each(elem_all, &state->all_blocks_list) {
1748                 const struct btrfsic_block *const b_all =
1749                     list_entry(elem_all, struct btrfsic_block,
1750                                all_blocks_node);
1751                 struct list_head *elem_ref_to;
1752                 struct list_head *elem_ref_from;
1753
1754                 printk(KERN_INFO "%c-block @%llu (%s/%llu/%d)\n",
1755                        btrfsic_get_block_type(state, b_all),
1756                        b_all->logical_bytenr, b_all->dev_state->name,
1757                        b_all->dev_bytenr, b_all->mirror_num);
1758
1759                 list_for_each(elem_ref_to, &b_all->ref_to_list) {
1760                         const struct btrfsic_block_link *const l =
1761                             list_entry(elem_ref_to,
1762                                        struct btrfsic_block_link,
1763                                        node_ref_to);
1764
1765                         printk(KERN_INFO " %c @%llu (%s/%llu/%d)"
1766                                " refers %u* to"
1767                                " %c @%llu (%s/%llu/%d)\n",
1768                                btrfsic_get_block_type(state, b_all),
1769                                b_all->logical_bytenr, b_all->dev_state->name,
1770                                b_all->dev_bytenr, b_all->mirror_num,
1771                                l->ref_cnt,
1772                                btrfsic_get_block_type(state, l->block_ref_to),
1773                                l->block_ref_to->logical_bytenr,
1774                                l->block_ref_to->dev_state->name,
1775                                l->block_ref_to->dev_bytenr,
1776                                l->block_ref_to->mirror_num);
1777                 }
1778
1779                 list_for_each(elem_ref_from, &b_all->ref_from_list) {
1780                         const struct btrfsic_block_link *const l =
1781                             list_entry(elem_ref_from,
1782                                        struct btrfsic_block_link,
1783                                        node_ref_from);
1784
1785                         printk(KERN_INFO " %c @%llu (%s/%llu/%d)"
1786                                " is ref %u* from"
1787                                " %c @%llu (%s/%llu/%d)\n",
1788                                btrfsic_get_block_type(state, b_all),
1789                                b_all->logical_bytenr, b_all->dev_state->name,
1790                                b_all->dev_bytenr, b_all->mirror_num,
1791                                l->ref_cnt,
1792                                btrfsic_get_block_type(state, l->block_ref_from),
1793                                l->block_ref_from->logical_bytenr,
1794                                l->block_ref_from->dev_state->name,
1795                                l->block_ref_from->dev_bytenr,
1796                                l->block_ref_from->mirror_num);
1797                 }
1798
1799                 printk(KERN_INFO "\n");
1800         }
1801 }
1802
1803 /*
1804  * Test whether the disk block contains a tree block (leaf or node)
1805  * (note that this test fails for the super block)
1806  */
1807 static int btrfsic_test_for_metadata(struct btrfsic_state *state,
1808                                      char **datav, unsigned int num_pages)
1809 {
1810         struct btrfs_header *h;
1811         u8 csum[BTRFS_CSUM_SIZE];
1812         u32 crc = ~(u32)0;
1813         unsigned int i;
1814
1815         if (num_pages * PAGE_CACHE_SIZE < state->metablock_size)
1816                 return 1; /* not metadata */
1817         num_pages = state->metablock_size >> PAGE_CACHE_SHIFT;
1818         h = (struct btrfs_header *)datav[0];
1819
1820         if (memcmp(h->fsid, state->root->fs_info->fsid, BTRFS_UUID_SIZE))
1821                 return 1;
1822
1823         for (i = 0; i < num_pages; i++) {
1824                 u8 *data = i ? datav[i] : (datav[i] + BTRFS_CSUM_SIZE);
1825                 size_t sublen = i ? PAGE_CACHE_SIZE :
1826                                     (PAGE_CACHE_SIZE - BTRFS_CSUM_SIZE);
1827
1828                 crc = btrfs_crc32c(crc, data, sublen);
1829         }
1830         btrfs_csum_final(crc, csum);
1831         if (memcmp(csum, h->csum, state->csum_size))
1832                 return 1;
1833
1834         return 0; /* is metadata */
1835 }
1836
1837 static void btrfsic_process_written_block(struct btrfsic_dev_state *dev_state,
1838                                           u64 dev_bytenr, char **mapped_datav,
1839                                           unsigned int num_pages,
1840                                           struct bio *bio, int *bio_is_patched,
1841                                           struct buffer_head *bh,
1842                                           int submit_bio_bh_rw)
1843 {
1844         int is_metadata;
1845         struct btrfsic_block *block;
1846         struct btrfsic_block_data_ctx block_ctx;
1847         int ret;
1848         struct btrfsic_state *state = dev_state->state;
1849         struct block_device *bdev = dev_state->bdev;
1850         unsigned int processed_len;
1851
1852         if (NULL != bio_is_patched)
1853                 *bio_is_patched = 0;
1854
1855 again:
1856         if (num_pages == 0)
1857                 return;
1858
1859         processed_len = 0;
1860         is_metadata = (0 == btrfsic_test_for_metadata(state, mapped_datav,
1861                                                       num_pages));
1862
1863         block = btrfsic_block_hashtable_lookup(bdev, dev_bytenr,
1864                                                &state->block_hashtable);
1865         if (NULL != block) {
1866                 u64 bytenr = 0;
1867                 struct list_head *elem_ref_to;
1868                 struct list_head *tmp_ref_to;
1869
1870                 if (block->is_superblock) {
1871                         bytenr = btrfs_super_bytenr((struct btrfs_super_block *)
1872                                                     mapped_datav[0]);
1873                         if (num_pages * PAGE_CACHE_SIZE <
1874                             BTRFS_SUPER_INFO_SIZE) {
1875                                 printk(KERN_INFO
1876                                        "btrfsic: cannot work with too short bios!\n");
1877                                 return;
1878                         }
1879                         is_metadata = 1;
1880                         BUG_ON(BTRFS_SUPER_INFO_SIZE & (PAGE_CACHE_SIZE - 1));
1881                         processed_len = BTRFS_SUPER_INFO_SIZE;
1882                         if (state->print_mask &
1883                             BTRFSIC_PRINT_MASK_TREE_BEFORE_SB_WRITE) {
1884                                 printk(KERN_INFO
1885                                        "[before new superblock is written]:\n");
1886                                 btrfsic_dump_tree_sub(state, block, 0);
1887                         }
1888                 }
1889                 if (is_metadata) {
1890                         if (!block->is_superblock) {
1891                                 if (num_pages * PAGE_CACHE_SIZE <
1892                                     state->metablock_size) {
1893                                         printk(KERN_INFO
1894                                                "btrfsic: cannot work with too short bios!\n");
1895                                         return;
1896                                 }
1897                                 processed_len = state->metablock_size;
1898                                 bytenr = btrfs_stack_header_bytenr(
1899                                                 (struct btrfs_header *)
1900                                                 mapped_datav[0]);
1901                                 btrfsic_cmp_log_and_dev_bytenr(state, bytenr,
1902                                                                dev_state,
1903                                                                dev_bytenr);
1904                         }
1905                         if (block->logical_bytenr != bytenr &&
1906                             !(!block->is_metadata &&
1907                               block->logical_bytenr == 0))
1908                                 printk(KERN_INFO
1909                                        "Written block @%llu (%s/%llu/%d)"
1910                                        " found in hash table, %c,"
1911                                        " bytenr mismatch"
1912                                        " (!= stored %llu).\n",
1913                                        bytenr, dev_state->name, dev_bytenr,
1914                                        block->mirror_num,
1915                                        btrfsic_get_block_type(state, block),
1916                                        block->logical_bytenr);
1917                         else if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1918                                 printk(KERN_INFO
1919                                        "Written block @%llu (%s/%llu/%d)"
1920                                        " found in hash table, %c.\n",
1921                                        bytenr, dev_state->name, dev_bytenr,
1922                                        block->mirror_num,
1923                                        btrfsic_get_block_type(state, block));
1924                         block->logical_bytenr = bytenr;
1925                 } else {
1926                         if (num_pages * PAGE_CACHE_SIZE <
1927                             state->datablock_size) {
1928                                 printk(KERN_INFO
1929                                        "btrfsic: cannot work with too short bios!\n");
1930                                 return;
1931                         }
1932                         processed_len = state->datablock_size;
1933                         bytenr = block->logical_bytenr;
1934                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1935                                 printk(KERN_INFO
1936                                        "Written block @%llu (%s/%llu/%d)"
1937                                        " found in hash table, %c.\n",
1938                                        bytenr, dev_state->name, dev_bytenr,
1939                                        block->mirror_num,
1940                                        btrfsic_get_block_type(state, block));
1941                 }
1942
1943                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1944                         printk(KERN_INFO
1945                                "ref_to_list: %cE, ref_from_list: %cE\n",
1946                                list_empty(&block->ref_to_list) ? ' ' : '!',
1947                                list_empty(&block->ref_from_list) ? ' ' : '!');
1948                 if (btrfsic_is_block_ref_by_superblock(state, block, 0)) {
1949                         printk(KERN_INFO "btrfs: attempt to overwrite %c-block"
1950                                " @%llu (%s/%llu/%d), old(gen=%llu,"
1951                                " objectid=%llu, type=%d, offset=%llu),"
1952                                " new(gen=%llu),"
1953                                " which is referenced by most recent superblock"
1954                                " (superblockgen=%llu)!\n",
1955                                btrfsic_get_block_type(state, block), bytenr,
1956                                dev_state->name, dev_bytenr, block->mirror_num,
1957                                block->generation,
1958                                btrfs_disk_key_objectid(&block->disk_key),
1959                                block->disk_key.type,
1960                                btrfs_disk_key_offset(&block->disk_key),
1961                                btrfs_stack_header_generation(
1962                                        (struct btrfs_header *) mapped_datav[0]),
1963                                state->max_superblock_generation);
1964                         btrfsic_dump_tree(state);
1965                 }
1966
1967                 if (!block->is_iodone && !block->never_written) {
1968                         printk(KERN_INFO "btrfs: attempt to overwrite %c-block"
1969                                " @%llu (%s/%llu/%d), oldgen=%llu, newgen=%llu,"
1970                                " which is not yet iodone!\n",
1971                                btrfsic_get_block_type(state, block), bytenr,
1972                                dev_state->name, dev_bytenr, block->mirror_num,
1973                                block->generation,
1974                                btrfs_stack_header_generation(
1975                                        (struct btrfs_header *)
1976                                        mapped_datav[0]));
1977                         /* it would not be safe to go on */
1978                         btrfsic_dump_tree(state);
1979                         goto continue_loop;
1980                 }
1981
1982                 /*
1983                  * Clear all references of this block. Do not free
1984                  * the block itself even if is not referenced anymore
1985                  * because it still carries valueable information
1986                  * like whether it was ever written and IO completed.
1987                  */
1988                 list_for_each_safe(elem_ref_to, tmp_ref_to,
1989                                    &block->ref_to_list) {
1990                         struct btrfsic_block_link *const l =
1991                             list_entry(elem_ref_to,
1992                                        struct btrfsic_block_link,
1993                                        node_ref_to);
1994
1995                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
1996                                 btrfsic_print_rem_link(state, l);
1997                         l->ref_cnt--;
1998                         if (0 == l->ref_cnt) {
1999                                 list_del(&l->node_ref_to);
2000                                 list_del(&l->node_ref_from);
2001                                 btrfsic_block_link_hashtable_remove(l);
2002                                 btrfsic_block_link_free(l);
2003                         }
2004                 }
2005
2006                 if (block->is_superblock)
2007                         ret = btrfsic_map_superblock(state, bytenr,
2008                                                      processed_len,
2009                                                      bdev, &block_ctx);
2010                 else
2011                         ret = btrfsic_map_block(state, bytenr, processed_len,
2012                                                 &block_ctx, 0);
2013                 if (ret) {
2014                         printk(KERN_INFO
2015                                "btrfsic: btrfsic_map_block(root @%llu)"
2016                                " failed!\n", bytenr);
2017                         goto continue_loop;
2018                 }
2019                 block_ctx.datav = mapped_datav;
2020                 /* the following is required in case of writes to mirrors,
2021                  * use the same that was used for the lookup */
2022                 block_ctx.dev = dev_state;
2023                 block_ctx.dev_bytenr = dev_bytenr;
2024
2025                 if (is_metadata || state->include_extent_data) {
2026                         block->never_written = 0;
2027                         block->iodone_w_error = 0;
2028                         if (NULL != bio) {
2029                                 block->is_iodone = 0;
2030                                 BUG_ON(NULL == bio_is_patched);
2031                                 if (!*bio_is_patched) {
2032                                         block->orig_bio_bh_private =
2033                                             bio->bi_private;
2034                                         block->orig_bio_bh_end_io.bio =
2035                                             bio->bi_end_io;
2036                                         block->next_in_same_bio = NULL;
2037                                         bio->bi_private = block;
2038                                         bio->bi_end_io = btrfsic_bio_end_io;
2039                                         *bio_is_patched = 1;
2040                                 } else {
2041                                         struct btrfsic_block *chained_block =
2042                                             (struct btrfsic_block *)
2043                                             bio->bi_private;
2044
2045                                         BUG_ON(NULL == chained_block);
2046                                         block->orig_bio_bh_private =
2047                                             chained_block->orig_bio_bh_private;
2048                                         block->orig_bio_bh_end_io.bio =
2049                                             chained_block->orig_bio_bh_end_io.
2050                                             bio;
2051                                         block->next_in_same_bio = chained_block;
2052                                         bio->bi_private = block;
2053                                 }
2054                         } else if (NULL != bh) {
2055                                 block->is_iodone = 0;
2056                                 block->orig_bio_bh_private = bh->b_private;
2057                                 block->orig_bio_bh_end_io.bh = bh->b_end_io;
2058                                 block->next_in_same_bio = NULL;
2059                                 bh->b_private = block;
2060                                 bh->b_end_io = btrfsic_bh_end_io;
2061                         } else {
2062                                 block->is_iodone = 1;
2063                                 block->orig_bio_bh_private = NULL;
2064                                 block->orig_bio_bh_end_io.bio = NULL;
2065                                 block->next_in_same_bio = NULL;
2066                         }
2067                 }
2068
2069                 block->flush_gen = dev_state->last_flush_gen + 1;
2070                 block->submit_bio_bh_rw = submit_bio_bh_rw;
2071                 if (is_metadata) {
2072                         block->logical_bytenr = bytenr;
2073                         block->is_metadata = 1;
2074                         if (block->is_superblock) {
2075                                 BUG_ON(PAGE_CACHE_SIZE !=
2076                                        BTRFS_SUPER_INFO_SIZE);
2077                                 ret = btrfsic_process_written_superblock(
2078                                                 state,
2079                                                 block,
2080                                                 (struct btrfs_super_block *)
2081                                                 mapped_datav[0]);
2082                                 if (state->print_mask &
2083                                     BTRFSIC_PRINT_MASK_TREE_AFTER_SB_WRITE) {
2084                                         printk(KERN_INFO
2085                                         "[after new superblock is written]:\n");
2086                                         btrfsic_dump_tree_sub(state, block, 0);
2087                                 }
2088                         } else {
2089                                 block->mirror_num = 0;  /* unknown */
2090                                 ret = btrfsic_process_metablock(
2091                                                 state,
2092                                                 block,
2093                                                 &block_ctx,
2094                                                 0, 0);
2095                         }
2096                         if (ret)
2097                                 printk(KERN_INFO
2098                                        "btrfsic: btrfsic_process_metablock"
2099                                        "(root @%llu) failed!\n",
2100                                        dev_bytenr);
2101                 } else {
2102                         block->is_metadata = 0;
2103                         block->mirror_num = 0;  /* unknown */
2104                         block->generation = BTRFSIC_GENERATION_UNKNOWN;
2105                         if (!state->include_extent_data
2106                             && list_empty(&block->ref_from_list)) {
2107                                 /*
2108                                  * disk block is overwritten with extent
2109                                  * data (not meta data) and we are configured
2110                                  * to not include extent data: take the
2111                                  * chance and free the block's memory
2112                                  */
2113                                 btrfsic_block_hashtable_remove(block);
2114                                 list_del(&block->all_blocks_node);
2115                                 btrfsic_block_free(block);
2116                         }
2117                 }
2118                 btrfsic_release_block_ctx(&block_ctx);
2119         } else {
2120                 /* block has not been found in hash table */
2121                 u64 bytenr;
2122
2123                 if (!is_metadata) {
2124                         processed_len = state->datablock_size;
2125                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2126                                 printk(KERN_INFO "Written block (%s/%llu/?)"
2127                                        " !found in hash table, D.\n",
2128                                        dev_state->name, dev_bytenr);
2129                         if (!state->include_extent_data) {
2130                                 /* ignore that written D block */
2131                                 goto continue_loop;
2132                         }
2133
2134                         /* this is getting ugly for the
2135                          * include_extent_data case... */
2136                         bytenr = 0;     /* unknown */
2137                         block_ctx.start = bytenr;
2138                         block_ctx.len = processed_len;
2139                         block_ctx.mem_to_free = NULL;
2140                         block_ctx.pagev = NULL;
2141                 } else {
2142                         processed_len = state->metablock_size;
2143                         bytenr = btrfs_stack_header_bytenr(
2144                                         (struct btrfs_header *)
2145                                         mapped_datav[0]);
2146                         btrfsic_cmp_log_and_dev_bytenr(state, bytenr, dev_state,
2147                                                        dev_bytenr);
2148                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2149                                 printk(KERN_INFO
2150                                        "Written block @%llu (%s/%llu/?)"
2151                                        " !found in hash table, M.\n",
2152                                        bytenr, dev_state->name, dev_bytenr);
2153
2154                         ret = btrfsic_map_block(state, bytenr, processed_len,
2155                                                 &block_ctx, 0);
2156                         if (ret) {
2157                                 printk(KERN_INFO
2158                                        "btrfsic: btrfsic_map_block(root @%llu)"
2159                                        " failed!\n",
2160                                        dev_bytenr);
2161                                 goto continue_loop;
2162                         }
2163                 }
2164                 block_ctx.datav = mapped_datav;
2165                 /* the following is required in case of writes to mirrors,
2166                  * use the same that was used for the lookup */
2167                 block_ctx.dev = dev_state;
2168                 block_ctx.dev_bytenr = dev_bytenr;
2169
2170                 block = btrfsic_block_alloc();
2171                 if (NULL == block) {
2172                         printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
2173                         btrfsic_release_block_ctx(&block_ctx);
2174                         goto continue_loop;
2175                 }
2176                 block->dev_state = dev_state;
2177                 block->dev_bytenr = dev_bytenr;
2178                 block->logical_bytenr = bytenr;
2179                 block->is_metadata = is_metadata;
2180                 block->never_written = 0;
2181                 block->iodone_w_error = 0;
2182                 block->mirror_num = 0;  /* unknown */
2183                 block->flush_gen = dev_state->last_flush_gen + 1;
2184                 block->submit_bio_bh_rw = submit_bio_bh_rw;
2185                 if (NULL != bio) {
2186                         block->is_iodone = 0;
2187                         BUG_ON(NULL == bio_is_patched);
2188                         if (!*bio_is_patched) {
2189                                 block->orig_bio_bh_private = bio->bi_private;
2190                                 block->orig_bio_bh_end_io.bio = bio->bi_end_io;
2191                                 block->next_in_same_bio = NULL;
2192                                 bio->bi_private = block;
2193                                 bio->bi_end_io = btrfsic_bio_end_io;
2194                                 *bio_is_patched = 1;
2195                         } else {
2196                                 struct btrfsic_block *chained_block =
2197                                     (struct btrfsic_block *)
2198                                     bio->bi_private;
2199
2200                                 BUG_ON(NULL == chained_block);
2201                                 block->orig_bio_bh_private =
2202                                     chained_block->orig_bio_bh_private;
2203                                 block->orig_bio_bh_end_io.bio =
2204                                     chained_block->orig_bio_bh_end_io.bio;
2205                                 block->next_in_same_bio = chained_block;
2206                                 bio->bi_private = block;
2207                         }
2208                 } else if (NULL != bh) {
2209                         block->is_iodone = 0;
2210                         block->orig_bio_bh_private = bh->b_private;
2211                         block->orig_bio_bh_end_io.bh = bh->b_end_io;
2212                         block->next_in_same_bio = NULL;
2213                         bh->b_private = block;
2214                         bh->b_end_io = btrfsic_bh_end_io;
2215                 } else {
2216                         block->is_iodone = 1;
2217                         block->orig_bio_bh_private = NULL;
2218                         block->orig_bio_bh_end_io.bio = NULL;
2219                         block->next_in_same_bio = NULL;
2220                 }
2221                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2222                         printk(KERN_INFO
2223                                "New written %c-block @%llu (%s/%llu/%d)\n",
2224                                is_metadata ? 'M' : 'D',
2225                                block->logical_bytenr, block->dev_state->name,
2226                                block->dev_bytenr, block->mirror_num);
2227                 list_add(&block->all_blocks_node, &state->all_blocks_list);
2228                 btrfsic_block_hashtable_add(block, &state->block_hashtable);
2229
2230                 if (is_metadata) {
2231                         ret = btrfsic_process_metablock(state, block,
2232                                                         &block_ctx, 0, 0);
2233                         if (ret)
2234                                 printk(KERN_INFO
2235                                        "btrfsic: process_metablock(root @%llu)"
2236                                        " failed!\n",
2237                                        dev_bytenr);
2238                 }
2239                 btrfsic_release_block_ctx(&block_ctx);
2240         }
2241
2242 continue_loop:
2243         BUG_ON(!processed_len);
2244         dev_bytenr += processed_len;
2245         mapped_datav += processed_len >> PAGE_CACHE_SHIFT;
2246         num_pages -= processed_len >> PAGE_CACHE_SHIFT;
2247         goto again;
2248 }
2249
2250 static void btrfsic_bio_end_io(struct bio *bp, int bio_error_status)
2251 {
2252         struct btrfsic_block *block = (struct btrfsic_block *)bp->bi_private;
2253         int iodone_w_error;
2254
2255         /* mutex is not held! This is not save if IO is not yet completed
2256          * on umount */
2257         iodone_w_error = 0;
2258         if (bio_error_status)
2259                 iodone_w_error = 1;
2260
2261         BUG_ON(NULL == block);
2262         bp->bi_private = block->orig_bio_bh_private;
2263         bp->bi_end_io = block->orig_bio_bh_end_io.bio;
2264
2265         do {
2266                 struct btrfsic_block *next_block;
2267                 struct btrfsic_dev_state *const dev_state = block->dev_state;
2268
2269                 if ((dev_state->state->print_mask &
2270                      BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
2271                         printk(KERN_INFO
2272                                "bio_end_io(err=%d) for %c @%llu (%s/%llu/%d)\n",
2273                                bio_error_status,
2274                                btrfsic_get_block_type(dev_state->state, block),
2275                                block->logical_bytenr, dev_state->name,
2276                                block->dev_bytenr, block->mirror_num);
2277                 next_block = block->next_in_same_bio;
2278                 block->iodone_w_error = iodone_w_error;
2279                 if (block->submit_bio_bh_rw & REQ_FLUSH) {
2280                         dev_state->last_flush_gen++;
2281                         if ((dev_state->state->print_mask &
2282                              BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
2283                                 printk(KERN_INFO
2284                                        "bio_end_io() new %s flush_gen=%llu\n",
2285                                        dev_state->name,
2286                                        dev_state->last_flush_gen);
2287                 }
2288                 if (block->submit_bio_bh_rw & REQ_FUA)
2289                         block->flush_gen = 0; /* FUA completed means block is
2290                                                * on disk */
2291                 block->is_iodone = 1; /* for FLUSH, this releases the block */
2292                 block = next_block;
2293         } while (NULL != block);
2294
2295         bp->bi_end_io(bp, bio_error_status);
2296 }
2297
2298 static void btrfsic_bh_end_io(struct buffer_head *bh, int uptodate)
2299 {
2300         struct btrfsic_block *block = (struct btrfsic_block *)bh->b_private;
2301         int iodone_w_error = !uptodate;
2302         struct btrfsic_dev_state *dev_state;
2303
2304         BUG_ON(NULL == block);
2305         dev_state = block->dev_state;
2306         if ((dev_state->state->print_mask & BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
2307                 printk(KERN_INFO
2308                        "bh_end_io(error=%d) for %c @%llu (%s/%llu/%d)\n",
2309                        iodone_w_error,
2310                        btrfsic_get_block_type(dev_state->state, block),
2311                        block->logical_bytenr, block->dev_state->name,
2312                        block->dev_bytenr, block->mirror_num);
2313
2314         block->iodone_w_error = iodone_w_error;
2315         if (block->submit_bio_bh_rw & REQ_FLUSH) {
2316                 dev_state->last_flush_gen++;
2317                 if ((dev_state->state->print_mask &
2318                      BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
2319                         printk(KERN_INFO
2320                                "bh_end_io() new %s flush_gen=%llu\n",
2321                                dev_state->name, dev_state->last_flush_gen);
2322         }
2323         if (block->submit_bio_bh_rw & REQ_FUA)
2324                 block->flush_gen = 0; /* FUA completed means block is on disk */
2325
2326         bh->b_private = block->orig_bio_bh_private;
2327         bh->b_end_io = block->orig_bio_bh_end_io.bh;
2328         block->is_iodone = 1; /* for FLUSH, this releases the block */
2329         bh->b_end_io(bh, uptodate);
2330 }
2331
2332 static int btrfsic_process_written_superblock(
2333                 struct btrfsic_state *state,
2334                 struct btrfsic_block *const superblock,
2335                 struct btrfs_super_block *const super_hdr)
2336 {
2337         int pass;
2338
2339         superblock->generation = btrfs_super_generation(super_hdr);
2340         if (!(superblock->generation > state->max_superblock_generation ||
2341               0 == state->max_superblock_generation)) {
2342                 if (state->print_mask & BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE)
2343                         printk(KERN_INFO
2344                                "btrfsic: superblock @%llu (%s/%llu/%d)"
2345                                " with old gen %llu <= %llu\n",
2346                                superblock->logical_bytenr,
2347                                superblock->dev_state->name,
2348                                superblock->dev_bytenr, superblock->mirror_num,
2349                                btrfs_super_generation(super_hdr),
2350                                state->max_superblock_generation);
2351         } else {
2352                 if (state->print_mask & BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE)
2353                         printk(KERN_INFO
2354                                "btrfsic: got new superblock @%llu (%s/%llu/%d)"
2355                                " with new gen %llu > %llu\n",
2356                                superblock->logical_bytenr,
2357                                superblock->dev_state->name,
2358                                superblock->dev_bytenr, superblock->mirror_num,
2359                                btrfs_super_generation(super_hdr),
2360                                state->max_superblock_generation);
2361
2362                 state->max_superblock_generation =
2363                     btrfs_super_generation(super_hdr);
2364                 state->latest_superblock = superblock;
2365         }
2366
2367         for (pass = 0; pass < 3; pass++) {
2368                 int ret;
2369                 u64 next_bytenr;
2370                 struct btrfsic_block *next_block;
2371                 struct btrfsic_block_data_ctx tmp_next_block_ctx;
2372                 struct btrfsic_block_link *l;
2373                 int num_copies;
2374                 int mirror_num;
2375                 const char *additional_string = NULL;
2376                 struct btrfs_disk_key tmp_disk_key = {0};
2377
2378                 btrfs_set_disk_key_objectid(&tmp_disk_key,
2379                                             BTRFS_ROOT_ITEM_KEY);
2380                 btrfs_set_disk_key_objectid(&tmp_disk_key, 0);
2381
2382                 switch (pass) {
2383                 case 0:
2384                         btrfs_set_disk_key_objectid(&tmp_disk_key,
2385                                                     BTRFS_ROOT_TREE_OBJECTID);
2386                         additional_string = "root ";
2387                         next_bytenr = btrfs_super_root(super_hdr);
2388                         if (state->print_mask &
2389                             BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
2390                                 printk(KERN_INFO "root@%llu\n", next_bytenr);
2391                         break;
2392                 case 1:
2393                         btrfs_set_disk_key_objectid(&tmp_disk_key,
2394                                                     BTRFS_CHUNK_TREE_OBJECTID);
2395                         additional_string = "chunk ";
2396                         next_bytenr = btrfs_super_chunk_root(super_hdr);
2397                         if (state->print_mask &
2398                             BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
2399                                 printk(KERN_INFO "chunk@%llu\n", next_bytenr);
2400                         break;
2401                 case 2:
2402                         btrfs_set_disk_key_objectid(&tmp_disk_key,
2403                                                     BTRFS_TREE_LOG_OBJECTID);
2404                         additional_string = "log ";
2405                         next_bytenr = btrfs_super_log_root(super_hdr);
2406                         if (0 == next_bytenr)
2407                                 continue;
2408                         if (state->print_mask &
2409                             BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
2410                                 printk(KERN_INFO "log@%llu\n", next_bytenr);
2411                         break;
2412                 }
2413
2414                 num_copies =
2415                     btrfs_num_copies(state->root->fs_info,
2416                                      next_bytenr, BTRFS_SUPER_INFO_SIZE);
2417                 if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
2418                         printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
2419                                next_bytenr, num_copies);
2420                 for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
2421                         int was_created;
2422
2423                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2424                                 printk(KERN_INFO
2425                                        "btrfsic_process_written_superblock("
2426                                        "mirror_num=%d)\n", mirror_num);
2427                         ret = btrfsic_map_block(state, next_bytenr,
2428                                                 BTRFS_SUPER_INFO_SIZE,
2429                                                 &tmp_next_block_ctx,
2430                                                 mirror_num);
2431                         if (ret) {
2432                                 printk(KERN_INFO
2433                                        "btrfsic: btrfsic_map_block(@%llu,"
2434                                        " mirror=%d) failed!\n",
2435                                        next_bytenr, mirror_num);
2436                                 return -1;
2437                         }
2438
2439                         next_block = btrfsic_block_lookup_or_add(
2440                                         state,
2441                                         &tmp_next_block_ctx,
2442                                         additional_string,
2443                                         1, 0, 1,
2444                                         mirror_num,
2445                                         &was_created);
2446                         if (NULL == next_block) {
2447                                 printk(KERN_INFO
2448                                        "btrfsic: error, kmalloc failed!\n");
2449                                 btrfsic_release_block_ctx(&tmp_next_block_ctx);
2450                                 return -1;
2451                         }
2452
2453                         next_block->disk_key = tmp_disk_key;
2454                         if (was_created)
2455                                 next_block->generation =
2456                                     BTRFSIC_GENERATION_UNKNOWN;
2457                         l = btrfsic_block_link_lookup_or_add(
2458                                         state,
2459                                         &tmp_next_block_ctx,
2460                                         next_block,
2461                                         superblock,
2462                                         BTRFSIC_GENERATION_UNKNOWN);
2463                         btrfsic_release_block_ctx(&tmp_next_block_ctx);
2464                         if (NULL == l)
2465                                 return -1;
2466                 }
2467         }
2468
2469         if (WARN_ON(-1 == btrfsic_check_all_ref_blocks(state, superblock, 0)))
2470                 btrfsic_dump_tree(state);
2471
2472         return 0;
2473 }
2474
2475 static int btrfsic_check_all_ref_blocks(struct btrfsic_state *state,
2476                                         struct btrfsic_block *const block,
2477                                         int recursion_level)
2478 {
2479         struct list_head *elem_ref_to;
2480         int ret = 0;
2481
2482         if (recursion_level >= 3 + BTRFS_MAX_LEVEL) {
2483                 /*
2484                  * Note that this situation can happen and does not
2485                  * indicate an error in regular cases. It happens
2486                  * when disk blocks are freed and later reused.
2487                  * The check-integrity module is not aware of any
2488                  * block free operations, it just recognizes block
2489                  * write operations. Therefore it keeps the linkage
2490                  * information for a block until a block is
2491                  * rewritten. This can temporarily cause incorrect
2492                  * and even circular linkage informations. This
2493                  * causes no harm unless such blocks are referenced
2494                  * by the most recent super block.
2495                  */
2496                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2497                         printk(KERN_INFO
2498                                "btrfsic: abort cyclic linkage (case 1).\n");
2499
2500                 return ret;
2501         }
2502
2503         /*
2504          * This algorithm is recursive because the amount of used stack
2505          * space is very small and the max recursion depth is limited.
2506          */
2507         list_for_each(elem_ref_to, &block->ref_to_list) {
2508                 const struct btrfsic_block_link *const l =
2509                     list_entry(elem_ref_to, struct btrfsic_block_link,
2510                                node_ref_to);
2511
2512                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2513                         printk(KERN_INFO
2514                                "rl=%d, %c @%llu (%s/%llu/%d)"
2515                                " %u* refers to %c @%llu (%s/%llu/%d)\n",
2516                                recursion_level,
2517                                btrfsic_get_block_type(state, block),
2518                                block->logical_bytenr, block->dev_state->name,
2519                                block->dev_bytenr, block->mirror_num,
2520                                l->ref_cnt,
2521                                btrfsic_get_block_type(state, l->block_ref_to),
2522                                l->block_ref_to->logical_bytenr,
2523                                l->block_ref_to->dev_state->name,
2524                                l->block_ref_to->dev_bytenr,
2525                                l->block_ref_to->mirror_num);
2526                 if (l->block_ref_to->never_written) {
2527                         printk(KERN_INFO "btrfs: attempt to write superblock"
2528                                " which references block %c @%llu (%s/%llu/%d)"
2529                                " which is never written!\n",
2530                                btrfsic_get_block_type(state, l->block_ref_to),
2531                                l->block_ref_to->logical_bytenr,
2532                                l->block_ref_to->dev_state->name,
2533                                l->block_ref_to->dev_bytenr,
2534                                l->block_ref_to->mirror_num);
2535                         ret = -1;
2536                 } else if (!l->block_ref_to->is_iodone) {
2537                         printk(KERN_INFO "btrfs: attempt to write superblock"
2538                                " which references block %c @%llu (%s/%llu/%d)"
2539                                " which is not yet iodone!\n",
2540                                btrfsic_get_block_type(state, l->block_ref_to),
2541                                l->block_ref_to->logical_bytenr,
2542                                l->block_ref_to->dev_state->name,
2543                                l->block_ref_to->dev_bytenr,
2544                                l->block_ref_to->mirror_num);
2545                         ret = -1;
2546                 } else if (l->block_ref_to->iodone_w_error) {
2547                         printk(KERN_INFO "btrfs: attempt to write superblock"
2548                                " which references block %c @%llu (%s/%llu/%d)"
2549                                " which has write error!\n",
2550                                btrfsic_get_block_type(state, l->block_ref_to),
2551                                l->block_ref_to->logical_bytenr,
2552                                l->block_ref_to->dev_state->name,
2553                                l->block_ref_to->dev_bytenr,
2554                                l->block_ref_to->mirror_num);
2555                         ret = -1;
2556                 } else if (l->parent_generation !=
2557                            l->block_ref_to->generation &&
2558                            BTRFSIC_GENERATION_UNKNOWN !=
2559                            l->parent_generation &&
2560                            BTRFSIC_GENERATION_UNKNOWN !=
2561                            l->block_ref_to->generation) {
2562                         printk(KERN_INFO "btrfs: attempt to write superblock"
2563                                " which references block %c @%llu (%s/%llu/%d)"
2564                                " with generation %llu !="
2565                                " parent generation %llu!\n",
2566                                btrfsic_get_block_type(state, l->block_ref_to),
2567                                l->block_ref_to->logical_bytenr,
2568                                l->block_ref_to->dev_state->name,
2569                                l->block_ref_to->dev_bytenr,
2570                                l->block_ref_to->mirror_num,
2571                                l->block_ref_to->generation,
2572                                l->parent_generation);
2573                         ret = -1;
2574                 } else if (l->block_ref_to->flush_gen >
2575                            l->block_ref_to->dev_state->last_flush_gen) {
2576                         printk(KERN_INFO "btrfs: attempt to write superblock"
2577                                " which references block %c @%llu (%s/%llu/%d)"
2578                                " which is not flushed out of disk's write cache"
2579                                " (block flush_gen=%llu,"
2580                                " dev->flush_gen=%llu)!\n",
2581                                btrfsic_get_block_type(state, l->block_ref_to),
2582                                l->block_ref_to->logical_bytenr,
2583                                l->block_ref_to->dev_state->name,
2584                                l->block_ref_to->dev_bytenr,
2585                                l->block_ref_to->mirror_num, block->flush_gen,
2586                                l->block_ref_to->dev_state->last_flush_gen);
2587                         ret = -1;
2588                 } else if (-1 == btrfsic_check_all_ref_blocks(state,
2589                                                               l->block_ref_to,
2590                                                               recursion_level +
2591                                                               1)) {
2592                         ret = -1;
2593                 }
2594         }
2595
2596         return ret;
2597 }
2598
2599 static int btrfsic_is_block_ref_by_superblock(
2600                 const struct btrfsic_state *state,
2601                 const struct btrfsic_block *block,
2602                 int recursion_level)
2603 {
2604         struct list_head *elem_ref_from;
2605
2606         if (recursion_level >= 3 + BTRFS_MAX_LEVEL) {
2607                 /* refer to comment at "abort cyclic linkage (case 1)" */
2608                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2609                         printk(KERN_INFO
2610                                "btrfsic: abort cyclic linkage (case 2).\n");
2611
2612                 return 0;
2613         }
2614
2615         /*
2616          * This algorithm is recursive because the amount of used stack space
2617          * is very small and the max recursion depth is limited.
2618          */
2619         list_for_each(elem_ref_from, &block->ref_from_list) {
2620                 const struct btrfsic_block_link *const l =
2621                     list_entry(elem_ref_from, struct btrfsic_block_link,
2622                                node_ref_from);
2623
2624                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2625                         printk(KERN_INFO
2626                                "rl=%d, %c @%llu (%s/%llu/%d)"
2627                                " is ref %u* from %c @%llu (%s/%llu/%d)\n",
2628                                recursion_level,
2629                                btrfsic_get_block_type(state, block),
2630                                block->logical_bytenr, block->dev_state->name,
2631                                block->dev_bytenr, block->mirror_num,
2632                                l->ref_cnt,
2633                                btrfsic_get_block_type(state, l->block_ref_from),
2634                                l->block_ref_from->logical_bytenr,
2635                                l->block_ref_from->dev_state->name,
2636                                l->block_ref_from->dev_bytenr,
2637                                l->block_ref_from->mirror_num);
2638                 if (l->block_ref_from->is_superblock &&
2639                     state->latest_superblock->dev_bytenr ==
2640                     l->block_ref_from->dev_bytenr &&
2641                     state->latest_superblock->dev_state->bdev ==
2642                     l->block_ref_from->dev_state->bdev)
2643                         return 1;
2644                 else if (btrfsic_is_block_ref_by_superblock(state,
2645                                                             l->block_ref_from,
2646                                                             recursion_level +
2647                                                             1))
2648                         return 1;
2649         }
2650
2651         return 0;
2652 }
2653
2654 static void btrfsic_print_add_link(const struct btrfsic_state *state,
2655                                    const struct btrfsic_block_link *l)
2656 {
2657         printk(KERN_INFO
2658                "Add %u* link from %c @%llu (%s/%llu/%d)"
2659                " to %c @%llu (%s/%llu/%d).\n",
2660                l->ref_cnt,
2661                btrfsic_get_block_type(state, l->block_ref_from),
2662                l->block_ref_from->logical_bytenr,
2663                l->block_ref_from->dev_state->name,
2664                l->block_ref_from->dev_bytenr, l->block_ref_from->mirror_num,
2665                btrfsic_get_block_type(state, l->block_ref_to),
2666                l->block_ref_to->logical_bytenr,
2667                l->block_ref_to->dev_state->name, l->block_ref_to->dev_bytenr,
2668                l->block_ref_to->mirror_num);
2669 }
2670
2671 static void btrfsic_print_rem_link(const struct btrfsic_state *state,
2672                                    const struct btrfsic_block_link *l)
2673 {
2674         printk(KERN_INFO
2675                "Rem %u* link from %c @%llu (%s/%llu/%d)"
2676                " to %c @%llu (%s/%llu/%d).\n",
2677                l->ref_cnt,
2678                btrfsic_get_block_type(state, l->block_ref_from),
2679                l->block_ref_from->logical_bytenr,
2680                l->block_ref_from->dev_state->name,
2681                l->block_ref_from->dev_bytenr, l->block_ref_from->mirror_num,
2682                btrfsic_get_block_type(state, l->block_ref_to),
2683                l->block_ref_to->logical_bytenr,
2684                l->block_ref_to->dev_state->name, l->block_ref_to->dev_bytenr,
2685                l->block_ref_to->mirror_num);
2686 }
2687
2688 static char btrfsic_get_block_type(const struct btrfsic_state *state,
2689                                    const struct btrfsic_block *block)
2690 {
2691         if (block->is_superblock &&
2692             state->latest_superblock->dev_bytenr == block->dev_bytenr &&
2693             state->latest_superblock->dev_state->bdev == block->dev_state->bdev)
2694                 return 'S';
2695         else if (block->is_superblock)
2696                 return 's';
2697         else if (block->is_metadata)
2698                 return 'M';
2699         else
2700                 return 'D';
2701 }
2702
2703 static void btrfsic_dump_tree(const struct btrfsic_state *state)
2704 {
2705         btrfsic_dump_tree_sub(state, state->latest_superblock, 0);
2706 }
2707
2708 static void btrfsic_dump_tree_sub(const struct btrfsic_state *state,
2709                                   const struct btrfsic_block *block,
2710                                   int indent_level)
2711 {
2712         struct list_head *elem_ref_to;
2713         int indent_add;
2714         static char buf[80];
2715         int cursor_position;
2716
2717         /*
2718          * Should better fill an on-stack buffer with a complete line and
2719          * dump it at once when it is time to print a newline character.
2720          */
2721
2722         /*
2723          * This algorithm is recursive because the amount of used stack space
2724          * is very small and the max recursion depth is limited.
2725          */
2726         indent_add = sprintf(buf, "%c-%llu(%s/%llu/%d)",
2727                              btrfsic_get_block_type(state, block),
2728                              block->logical_bytenr, block->dev_state->name,
2729                              block->dev_bytenr, block->mirror_num);
2730         if (indent_level + indent_add > BTRFSIC_TREE_DUMP_MAX_INDENT_LEVEL) {
2731                 printk("[...]\n");
2732                 return;
2733         }
2734         printk(buf);
2735         indent_level += indent_add;
2736         if (list_empty(&block->ref_to_list)) {
2737                 printk("\n");
2738                 return;
2739         }
2740         if (block->mirror_num > 1 &&
2741             !(state->print_mask & BTRFSIC_PRINT_MASK_TREE_WITH_ALL_MIRRORS)) {
2742                 printk(" [...]\n");
2743                 return;
2744         }
2745
2746         cursor_position = indent_level;
2747         list_for_each(elem_ref_to, &block->ref_to_list) {
2748                 const struct btrfsic_block_link *const l =
2749                     list_entry(elem_ref_to, struct btrfsic_block_link,
2750                                node_ref_to);
2751
2752                 while (cursor_position < indent_level) {
2753                         printk(" ");
2754                         cursor_position++;
2755                 }
2756                 if (l->ref_cnt > 1)
2757                         indent_add = sprintf(buf, " %d*--> ", l->ref_cnt);
2758                 else
2759                         indent_add = sprintf(buf, " --> ");
2760                 if (indent_level + indent_add >
2761                     BTRFSIC_TREE_DUMP_MAX_INDENT_LEVEL) {
2762                         printk("[...]\n");
2763                         cursor_position = 0;
2764                         continue;
2765                 }
2766
2767                 printk(buf);
2768
2769                 btrfsic_dump_tree_sub(state, l->block_ref_to,
2770                                       indent_level + indent_add);
2771                 cursor_position = 0;
2772         }
2773 }
2774
2775 static struct btrfsic_block_link *btrfsic_block_link_lookup_or_add(
2776                 struct btrfsic_state *state,
2777                 struct btrfsic_block_data_ctx *next_block_ctx,
2778                 struct btrfsic_block *next_block,
2779                 struct btrfsic_block *from_block,
2780                 u64 parent_generation)
2781 {
2782         struct btrfsic_block_link *l;
2783
2784         l = btrfsic_block_link_hashtable_lookup(next_block_ctx->dev->bdev,
2785                                                 next_block_ctx->dev_bytenr,
2786                                                 from_block->dev_state->bdev,
2787                                                 from_block->dev_bytenr,
2788                                                 &state->block_link_hashtable);
2789         if (NULL == l) {
2790                 l = btrfsic_block_link_alloc();
2791                 if (NULL == l) {
2792                         printk(KERN_INFO
2793                                "btrfsic: error, kmalloc" " failed!\n");
2794                         return NULL;
2795                 }
2796
2797                 l->block_ref_to = next_block;
2798                 l->block_ref_from = from_block;
2799                 l->ref_cnt = 1;
2800                 l->parent_generation = parent_generation;
2801
2802                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2803                         btrfsic_print_add_link(state, l);
2804
2805                 list_add(&l->node_ref_to, &from_block->ref_to_list);
2806                 list_add(&l->node_ref_from, &next_block->ref_from_list);
2807
2808                 btrfsic_block_link_hashtable_add(l,
2809                                                  &state->block_link_hashtable);
2810         } else {
2811                 l->ref_cnt++;
2812                 l->parent_generation = parent_generation;
2813                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2814                         btrfsic_print_add_link(state, l);
2815         }
2816
2817         return l;
2818 }
2819
2820 static struct btrfsic_block *btrfsic_block_lookup_or_add(
2821                 struct btrfsic_state *state,
2822                 struct btrfsic_block_data_ctx *block_ctx,
2823                 const char *additional_string,
2824                 int is_metadata,
2825                 int is_iodone,
2826                 int never_written,
2827                 int mirror_num,
2828                 int *was_created)
2829 {
2830         struct btrfsic_block *block;
2831
2832         block = btrfsic_block_hashtable_lookup(block_ctx->dev->bdev,
2833                                                block_ctx->dev_bytenr,
2834                                                &state->block_hashtable);
2835         if (NULL == block) {
2836                 struct btrfsic_dev_state *dev_state;
2837
2838                 block = btrfsic_block_alloc();
2839                 if (NULL == block) {
2840                         printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
2841                         return NULL;
2842                 }
2843                 dev_state = btrfsic_dev_state_lookup(block_ctx->dev->bdev);
2844                 if (NULL == dev_state) {
2845                         printk(KERN_INFO
2846                                "btrfsic: error, lookup dev_state failed!\n");
2847                         btrfsic_block_free(block);
2848                         return NULL;
2849                 }
2850                 block->dev_state = dev_state;
2851                 block->dev_bytenr = block_ctx->dev_bytenr;
2852                 block->logical_bytenr = block_ctx->start;
2853                 block->is_metadata = is_metadata;
2854                 block->is_iodone = is_iodone;
2855                 block->never_written = never_written;
2856                 block->mirror_num = mirror_num;
2857                 if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
2858                         printk(KERN_INFO
2859                                "New %s%c-block @%llu (%s/%llu/%d)\n",
2860                                additional_string,
2861                                btrfsic_get_block_type(state, block),
2862                                block->logical_bytenr, dev_state->name,
2863                                block->dev_bytenr, mirror_num);
2864                 list_add(&block->all_blocks_node, &state->all_blocks_list);
2865                 btrfsic_block_hashtable_add(block, &state->block_hashtable);
2866                 if (NULL != was_created)
2867                         *was_created = 1;
2868         } else {
2869                 if (NULL != was_created)
2870                         *was_created = 0;
2871         }
2872
2873         return block;
2874 }
2875
2876 static void btrfsic_cmp_log_and_dev_bytenr(struct btrfsic_state *state,
2877                                            u64 bytenr,
2878                                            struct btrfsic_dev_state *dev_state,
2879                                            u64 dev_bytenr)
2880 {
2881         int num_copies;
2882         int mirror_num;
2883         int ret;
2884         struct btrfsic_block_data_ctx block_ctx;
2885         int match = 0;
2886
2887         num_copies = btrfs_num_copies(state->root->fs_info,
2888                                       bytenr, state->metablock_size);
2889
2890         for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
2891                 ret = btrfsic_map_block(state, bytenr, state->metablock_size,
2892                                         &block_ctx, mirror_num);
2893                 if (ret) {
2894                         printk(KERN_INFO "btrfsic:"
2895                                " btrfsic_map_block(logical @%llu,"
2896                                " mirror %d) failed!\n",
2897                                bytenr, mirror_num);
2898                         continue;
2899                 }
2900
2901                 if (dev_state->bdev == block_ctx.dev->bdev &&
2902                     dev_bytenr == block_ctx.dev_bytenr) {
2903                         match++;
2904                         btrfsic_release_block_ctx(&block_ctx);
2905                         break;
2906                 }
2907                 btrfsic_release_block_ctx(&block_ctx);
2908         }
2909
2910         if (WARN_ON(!match)) {
2911                 printk(KERN_INFO "btrfs: attempt to write M-block which contains logical bytenr that doesn't map to dev+physical bytenr of submit_bio,"
2912                        " buffer->log_bytenr=%llu, submit_bio(bdev=%s,"
2913                        " phys_bytenr=%llu)!\n",
2914                        bytenr, dev_state->name, dev_bytenr);
2915                 for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
2916                         ret = btrfsic_map_block(state, bytenr,
2917                                                 state->metablock_size,
2918                                                 &block_ctx, mirror_num);
2919                         if (ret)
2920                                 continue;
2921
2922                         printk(KERN_INFO "Read logical bytenr @%llu maps to"
2923                                " (%s/%llu/%d)\n",
2924                                bytenr, block_ctx.dev->name,
2925                                block_ctx.dev_bytenr, mirror_num);
2926                 }
2927         }
2928 }
2929
2930 static struct btrfsic_dev_state *btrfsic_dev_state_lookup(
2931                 struct block_device *bdev)
2932 {
2933         struct btrfsic_dev_state *ds;
2934
2935         ds = btrfsic_dev_state_hashtable_lookup(bdev,
2936                                                 &btrfsic_dev_state_hashtable);
2937         return ds;
2938 }
2939
2940 int btrfsic_submit_bh(int rw, struct buffer_head *bh)
2941 {
2942         struct btrfsic_dev_state *dev_state;
2943
2944         if (!btrfsic_is_initialized)
2945                 return submit_bh(rw, bh);
2946
2947         mutex_lock(&btrfsic_mutex);
2948         /* since btrfsic_submit_bh() might also be called before
2949          * btrfsic_mount(), this might return NULL */
2950         dev_state = btrfsic_dev_state_lookup(bh->b_bdev);
2951
2952         /* Only called to write the superblock (incl. FLUSH/FUA) */
2953         if (NULL != dev_state &&
2954             (rw & WRITE) && bh->b_size > 0) {
2955                 u64 dev_bytenr;
2956
2957                 dev_bytenr = 4096 * bh->b_blocknr;
2958                 if (dev_state->state->print_mask &
2959                     BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
2960                         printk(KERN_INFO
2961                                "submit_bh(rw=0x%x, blocknr=%llu (bytenr %llu),"
2962                                " size=%zu, data=%p, bdev=%p)\n",
2963                                rw, (unsigned long long)bh->b_blocknr,
2964                                dev_bytenr, bh->b_size, bh->b_data, bh->b_bdev);
2965                 btrfsic_process_written_block(dev_state, dev_bytenr,
2966                                               &bh->b_data, 1, NULL,
2967                                               NULL, bh, rw);
2968         } else if (NULL != dev_state && (rw & REQ_FLUSH)) {
2969                 if (dev_state->state->print_mask &
2970                     BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
2971                         printk(KERN_INFO
2972                                "submit_bh(rw=0x%x FLUSH, bdev=%p)\n",
2973                                rw, bh->b_bdev);
2974                 if (!dev_state->dummy_block_for_bio_bh_flush.is_iodone) {
2975                         if ((dev_state->state->print_mask &
2976                              (BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH |
2977                               BTRFSIC_PRINT_MASK_VERBOSE)))
2978                                 printk(KERN_INFO
2979                                        "btrfsic_submit_bh(%s) with FLUSH"
2980                                        " but dummy block already in use"
2981                                        " (ignored)!\n",
2982                                        dev_state->name);
2983                 } else {
2984                         struct btrfsic_block *const block =
2985                                 &dev_state->dummy_block_for_bio_bh_flush;
2986
2987                         block->is_iodone = 0;
2988                         block->never_written = 0;
2989                         block->iodone_w_error = 0;
2990                         block->flush_gen = dev_state->last_flush_gen + 1;
2991                         block->submit_bio_bh_rw = rw;
2992                         block->orig_bio_bh_private = bh->b_private;
2993                         block->orig_bio_bh_end_io.bh = bh->b_end_io;
2994                         block->next_in_same_bio = NULL;
2995                         bh->b_private = block;
2996                         bh->b_end_io = btrfsic_bh_end_io;
2997                 }
2998         }
2999         mutex_unlock(&btrfsic_mutex);
3000         return submit_bh(rw, bh);
3001 }
3002
3003 static void __btrfsic_submit_bio(int rw, struct bio *bio)
3004 {
3005         struct btrfsic_dev_state *dev_state;
3006
3007         if (!btrfsic_is_initialized)
3008                 return;
3009
3010         mutex_lock(&btrfsic_mutex);
3011         /* since btrfsic_submit_bio() is also called before
3012          * btrfsic_mount(), this might return NULL */
3013         dev_state = btrfsic_dev_state_lookup(bio->bi_bdev);
3014         if (NULL != dev_state &&
3015             (rw & WRITE) && NULL != bio->bi_io_vec) {
3016                 unsigned int i;
3017                 u64 dev_bytenr;
3018                 u64 cur_bytenr;
3019                 int bio_is_patched;
3020                 char **mapped_datav;
3021
3022                 dev_bytenr = 512 * bio->bi_iter.bi_sector;
3023                 bio_is_patched = 0;
3024                 if (dev_state->state->print_mask &
3025                     BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
3026                         printk(KERN_INFO
3027                                "submit_bio(rw=0x%x, bi_vcnt=%u,"
3028                                " bi_sector=%llu (bytenr %llu), bi_bdev=%p)\n",
3029                                rw, bio->bi_vcnt,
3030                                (unsigned long long)bio->bi_iter.bi_sector,
3031                                dev_bytenr, bio->bi_bdev);
3032
3033                 mapped_datav = kmalloc(sizeof(*mapped_datav) * bio->bi_vcnt,
3034                                        GFP_NOFS);
3035                 if (!mapped_datav)
3036                         goto leave;
3037                 cur_bytenr = dev_bytenr;
3038                 for (i = 0; i < bio->bi_vcnt; i++) {
3039                         BUG_ON(bio->bi_io_vec[i].bv_len != PAGE_CACHE_SIZE);
3040                         mapped_datav[i] = kmap(bio->bi_io_vec[i].bv_page);
3041                         if (!mapped_datav[i]) {
3042                                 while (i > 0) {
3043                                         i--;
3044                                         kunmap(bio->bi_io_vec[i].bv_page);
3045                                 }
3046                                 kfree(mapped_datav);
3047                                 goto leave;
3048                         }
3049                         if (dev_state->state->print_mask &
3050                             BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH_VERBOSE)
3051                                 printk(KERN_INFO
3052                                        "#%u: bytenr=%llu, len=%u, offset=%u\n",
3053                                        i, cur_bytenr, bio->bi_io_vec[i].bv_len,
3054                                        bio->bi_io_vec[i].bv_offset);
3055                         cur_bytenr += bio->bi_io_vec[i].bv_len;
3056                 }
3057                 btrfsic_process_written_block(dev_state, dev_bytenr,
3058                                               mapped_datav, bio->bi_vcnt,
3059                                               bio, &bio_is_patched,
3060                                               NULL, rw);
3061                 while (i > 0) {
3062                         i--;
3063                         kunmap(bio->bi_io_vec[i].bv_page);
3064                 }
3065                 kfree(mapped_datav);
3066         } else if (NULL != dev_state && (rw & REQ_FLUSH)) {
3067                 if (dev_state->state->print_mask &
3068                     BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
3069                         printk(KERN_INFO
3070                                "submit_bio(rw=0x%x FLUSH, bdev=%p)\n",
3071                                rw, bio->bi_bdev);
3072                 if (!dev_state->dummy_block_for_bio_bh_flush.is_iodone) {
3073                         if ((dev_state->state->print_mask &
3074                              (BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH |
3075                               BTRFSIC_PRINT_MASK_VERBOSE)))
3076                                 printk(KERN_INFO
3077                                        "btrfsic_submit_bio(%s) with FLUSH"
3078                                        " but dummy block already in use"
3079                                        " (ignored)!\n",
3080                                        dev_state->name);
3081                 } else {
3082                         struct btrfsic_block *const block =
3083                                 &dev_state->dummy_block_for_bio_bh_flush;
3084
3085                         block->is_iodone = 0;
3086                         block->never_written = 0;
3087                         block->iodone_w_error = 0;
3088                         block->flush_gen = dev_state->last_flush_gen + 1;
3089                         block->submit_bio_bh_rw = rw;
3090                         block->orig_bio_bh_private = bio->bi_private;
3091                         block->orig_bio_bh_end_io.bio = bio->bi_end_io;
3092                         block->next_in_same_bio = NULL;
3093                         bio->bi_private = block;
3094                         bio->bi_end_io = btrfsic_bio_end_io;
3095                 }
3096         }
3097 leave:
3098         mutex_unlock(&btrfsic_mutex);
3099 }
3100
3101 void btrfsic_submit_bio(int rw, struct bio *bio)
3102 {
3103         __btrfsic_submit_bio(rw, bio);
3104         submit_bio(rw, bio);
3105 }
3106
3107 int btrfsic_submit_bio_wait(int rw, struct bio *bio)
3108 {
3109         __btrfsic_submit_bio(rw, bio);
3110         return submit_bio_wait(rw, bio);
3111 }
3112
3113 int btrfsic_mount(struct btrfs_root *root,
3114                   struct btrfs_fs_devices *fs_devices,
3115                   int including_extent_data, u32 print_mask)
3116 {
3117         int ret;
3118         struct btrfsic_state *state;
3119         struct list_head *dev_head = &fs_devices->devices;
3120         struct btrfs_device *device;
3121
3122         if (root->nodesize & ((u64)PAGE_CACHE_SIZE - 1)) {
3123                 printk(KERN_INFO
3124                        "btrfsic: cannot handle nodesize %d not being a multiple of PAGE_CACHE_SIZE %ld!\n",
3125                        root->nodesize, PAGE_CACHE_SIZE);
3126                 return -1;
3127         }
3128         if (root->sectorsize & ((u64)PAGE_CACHE_SIZE - 1)) {
3129                 printk(KERN_INFO
3130                        "btrfsic: cannot handle sectorsize %d not being a multiple of PAGE_CACHE_SIZE %ld!\n",
3131                        root->sectorsize, PAGE_CACHE_SIZE);
3132                 return -1;
3133         }
3134         state = kzalloc(sizeof(*state), GFP_NOFS);
3135         if (NULL == state) {
3136                 printk(KERN_INFO "btrfs check-integrity: kmalloc() failed!\n");
3137                 return -1;
3138         }
3139
3140         if (!btrfsic_is_initialized) {
3141                 mutex_init(&btrfsic_mutex);
3142                 btrfsic_dev_state_hashtable_init(&btrfsic_dev_state_hashtable);
3143                 btrfsic_is_initialized = 1;
3144         }
3145         mutex_lock(&btrfsic_mutex);
3146         state->root = root;
3147         state->print_mask = print_mask;
3148         state->include_extent_data = including_extent_data;
3149         state->csum_size = 0;
3150         state->metablock_size = root->nodesize;
3151         state->datablock_size = root->sectorsize;
3152         INIT_LIST_HEAD(&state->all_blocks_list);
3153         btrfsic_block_hashtable_init(&state->block_hashtable);
3154         btrfsic_block_link_hashtable_init(&state->block_link_hashtable);
3155         state->max_superblock_generation = 0;
3156         state->latest_superblock = NULL;
3157
3158         list_for_each_entry(device, dev_head, dev_list) {
3159                 struct btrfsic_dev_state *ds;
3160                 char *p;
3161
3162                 if (!device->bdev || !device->name)
3163                         continue;
3164
3165                 ds = btrfsic_dev_state_alloc();
3166                 if (NULL == ds) {
3167                         printk(KERN_INFO
3168                                "btrfs check-integrity: kmalloc() failed!\n");
3169                         mutex_unlock(&btrfsic_mutex);
3170                         return -1;
3171                 }
3172                 ds->bdev = device->bdev;
3173                 ds->state = state;
3174                 bdevname(ds->bdev, ds->name);
3175                 ds->name[BDEVNAME_SIZE - 1] = '\0';
3176                 for (p = ds->name; *p != '\0'; p++);
3177                 while (p > ds->name && *p != '/')
3178                         p--;
3179                 if (*p == '/')
3180                         p++;
3181                 strlcpy(ds->name, p, sizeof(ds->name));
3182                 btrfsic_dev_state_hashtable_add(ds,
3183                                                 &btrfsic_dev_state_hashtable);
3184         }
3185
3186         ret = btrfsic_process_superblock(state, fs_devices);
3187         if (0 != ret) {
3188                 mutex_unlock(&btrfsic_mutex);
3189                 btrfsic_unmount(root, fs_devices);
3190                 return ret;
3191         }
3192
3193         if (state->print_mask & BTRFSIC_PRINT_MASK_INITIAL_DATABASE)
3194                 btrfsic_dump_database(state);
3195         if (state->print_mask & BTRFSIC_PRINT_MASK_INITIAL_TREE)
3196                 btrfsic_dump_tree(state);
3197
3198         mutex_unlock(&btrfsic_mutex);
3199         return 0;
3200 }
3201
3202 void btrfsic_unmount(struct btrfs_root *root,
3203                      struct btrfs_fs_devices *fs_devices)
3204 {
3205         struct list_head *elem_all;
3206         struct list_head *tmp_all;
3207         struct btrfsic_state *state;
3208         struct list_head *dev_head = &fs_devices->devices;
3209         struct btrfs_device *device;
3210
3211         if (!btrfsic_is_initialized)
3212                 return;
3213
3214         mutex_lock(&btrfsic_mutex);
3215
3216         state = NULL;
3217         list_for_each_entry(device, dev_head, dev_list) {
3218                 struct btrfsic_dev_state *ds;
3219
3220                 if (!device->bdev || !device->name)
3221                         continue;
3222
3223                 ds = btrfsic_dev_state_hashtable_lookup(
3224                                 device->bdev,
3225                                 &btrfsic_dev_state_hashtable);
3226                 if (NULL != ds) {
3227                         state = ds->state;
3228                         btrfsic_dev_state_hashtable_remove(ds);
3229                         btrfsic_dev_state_free(ds);
3230                 }
3231         }
3232
3233         if (NULL == state) {
3234                 printk(KERN_INFO
3235                        "btrfsic: error, cannot find state information"
3236                        " on umount!\n");
3237                 mutex_unlock(&btrfsic_mutex);
3238                 return;
3239         }
3240
3241         /*
3242          * Don't care about keeping the lists' state up to date,
3243          * just free all memory that was allocated dynamically.
3244          * Free the blocks and the block_links.
3245          */
3246         list_for_each_safe(elem_all, tmp_all, &state->all_blocks_list) {
3247                 struct btrfsic_block *const b_all =
3248                     list_entry(elem_all, struct btrfsic_block,
3249                                all_blocks_node);
3250                 struct list_head *elem_ref_to;
3251                 struct list_head *tmp_ref_to;
3252
3253                 list_for_each_safe(elem_ref_to, tmp_ref_to,
3254                                    &b_all->ref_to_list) {
3255                         struct btrfsic_block_link *const l =
3256                             list_entry(elem_ref_to,
3257                                        struct btrfsic_block_link,
3258                                        node_ref_to);
3259
3260                         if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
3261                                 btrfsic_print_rem_link(state, l);
3262
3263                         l->ref_cnt--;
3264                         if (0 == l->ref_cnt)
3265                                 btrfsic_block_link_free(l);
3266                 }
3267
3268                 if (b_all->is_iodone || b_all->never_written)
3269                         btrfsic_block_free(b_all);
3270                 else
3271                         printk(KERN_INFO "btrfs: attempt to free %c-block"
3272                                " @%llu (%s/%llu/%d) on umount which is"
3273                                " not yet iodone!\n",
3274                                btrfsic_get_block_type(state, b_all),
3275                                b_all->logical_bytenr, b_all->dev_state->name,
3276                                b_all->dev_bytenr, b_all->mirror_num);
3277         }
3278
3279         mutex_unlock(&btrfsic_mutex);
3280
3281         kfree(state);
3282 }