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