check-integrity.c 99.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/*
 * Copyright (C) STRATO AG 2011.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License v2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 021110-1307, USA.
 */

/*
 * This module can be used to catch cases when the btrfs kernel
 * code executes write requests to the disk that bring the file
 * system in an inconsistent state. In such a state, a power-loss
 * or kernel panic event would cause that the data on disk is
 * lost or at least damaged.
 *
 * Code is added that examines all block write requests during
 * runtime (including writes of the super block). Three rules
 * are verified and an error is printed on violation of the
 * rules:
 * 1. It is not allowed to write a disk block which is
 *    currently referenced by the super block (either directly
 *    or indirectly).
 * 2. When a super block is written, it is verified that all
 *    referenced (directly or indirectly) blocks fulfill the
 *    following requirements:
 *    2a. All referenced blocks have either been present when
 *        the file system was mounted, (i.e., they have been
 *        referenced by the super block) or they have been
 *        written since then and the write completion callback
40 41 42
 *        was called and no write error was indicated and a
 *        FLUSH request to the device where these blocks are
 *        located was received and completed.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
 *    2b. All referenced blocks need to have a generation
 *        number which is equal to the parent's number.
 *
 * One issue that was found using this module was that the log
 * tree on disk became temporarily corrupted because disk blocks
 * that had been in use for the log tree had been freed and
 * reused too early, while being referenced by the written super
 * block.
 *
 * The search term in the kernel log that can be used to filter
 * on the existence of detected integrity issues is
 * "btrfs: attempt".
 *
 * The integrity check is enabled via mount options. These
 * mount options are only supported if the integrity check
 * tool is compiled by defining BTRFS_FS_CHECK_INTEGRITY.
 *
 * Example #1, apply integrity checks to all metadata:
 * mount /dev/sdb1 /mnt -o check_int
 *
 * Example #2, apply integrity checks to all metadata and
 * to data extents:
 * mount /dev/sdb1 /mnt -o check_int_data
 *
 * Example #3, apply integrity checks to all metadata and dump
 * the tree that the super block references to kernel messages
 * each time after a super block was written:
 * mount /dev/sdb1 /mnt -o check_int,check_int_print_mask=263
 *
 * If the integrity check tool is included and activated in
 * the mount options, plenty of kernel memory is used, and
 * plenty of additional CPU cycles are spent. Enabling this
 * functionality is not intended for normal use. In most
 * cases, unless you are a btrfs developer who needs to verify
 * the integrity of (super)-block write requests, do not
 * enable the config option BTRFS_FS_CHECK_INTEGRITY to
 * include and compile the integrity check tool.
 */

#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/buffer_head.h>
#include <linux/mutex.h>
#include <linux/crc32c.h>
#include <linux/genhd.h>
#include <linux/blkdev.h>
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "extent_io.h"
#include "volumes.h"
#include "print-tree.h"
#include "locking.h"
#include "check-integrity.h"
97
#include "rcu-string.h"
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

#define BTRFSIC_BLOCK_HASHTABLE_SIZE 0x10000
#define BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE 0x10000
#define BTRFSIC_DEV2STATE_HASHTABLE_SIZE 0x100
#define BTRFSIC_BLOCK_MAGIC_NUMBER 0x14491051
#define BTRFSIC_BLOCK_LINK_MAGIC_NUMBER 0x11070807
#define BTRFSIC_DEV2STATE_MAGIC_NUMBER 0x20111530
#define BTRFSIC_BLOCK_STACK_FRAME_MAGIC_NUMBER 20111300
#define BTRFSIC_TREE_DUMP_MAX_INDENT_LEVEL (200 - 6)	/* in characters,
							 * excluding " [...]" */
#define BTRFSIC_GENERATION_UNKNOWN ((u64)-1)

/*
 * The definition of the bitmask fields for the print_mask.
 * They are specified with the mount option check_integrity_print_mask.
 */
#define BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE			0x00000001
#define BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION		0x00000002
#define BTRFSIC_PRINT_MASK_TREE_AFTER_SB_WRITE			0x00000004
#define BTRFSIC_PRINT_MASK_TREE_BEFORE_SB_WRITE			0x00000008
#define BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH			0x00000010
#define BTRFSIC_PRINT_MASK_END_IO_BIO_BH			0x00000020
#define BTRFSIC_PRINT_MASK_VERBOSE				0x00000040
#define BTRFSIC_PRINT_MASK_VERY_VERBOSE				0x00000080
#define BTRFSIC_PRINT_MASK_INITIAL_TREE				0x00000100
#define BTRFSIC_PRINT_MASK_INITIAL_ALL_TREES			0x00000200
#define BTRFSIC_PRINT_MASK_INITIAL_DATABASE			0x00000400
#define BTRFSIC_PRINT_MASK_NUM_COPIES				0x00000800
#define BTRFSIC_PRINT_MASK_TREE_WITH_ALL_MIRRORS		0x00001000

struct btrfsic_dev_state;
struct btrfsic_state;

struct btrfsic_block {
	u32 magic_num;		/* only used for debug purposes */
	unsigned int is_metadata:1;	/* if it is meta-data, not data-data */
	unsigned int is_superblock:1;	/* if it is one of the superblocks */
	unsigned int is_iodone:1;	/* if is done by lower subsystem */
	unsigned int iodone_w_error:1;	/* error was indicated to endio */
	unsigned int never_written:1;	/* block was added because it was
					 * referenced, not because it was
					 * written */
140
	unsigned int mirror_num;	/* large enough to hold
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
					 * BTRFS_SUPER_MIRROR_MAX */
	struct btrfsic_dev_state *dev_state;
	u64 dev_bytenr;		/* key, physical byte num on disk */
	u64 logical_bytenr;	/* logical byte num on disk */
	u64 generation;
	struct btrfs_disk_key disk_key;	/* extra info to print in case of
					 * issues, will not always be correct */
	struct list_head collision_resolving_node;	/* list node */
	struct list_head all_blocks_node;	/* list node */

	/* the following two lists contain block_link items */
	struct list_head ref_to_list;	/* list */
	struct list_head ref_from_list;	/* list */
	struct btrfsic_block *next_in_same_bio;
	void *orig_bio_bh_private;
	union {
		bio_end_io_t *bio;
		bh_end_io_t *bh;
	} orig_bio_bh_end_io;
	int submit_bio_bh_rw;
	u64 flush_gen; /* only valid if !never_written */
};

/*
 * Elements of this type are allocated dynamically and required because
 * each block object can refer to and can be ref from multiple blocks.
 * The key to lookup them in the hashtable is the dev_bytenr of
 * the block ref to plus the one from the block refered from.
 * The fact that they are searchable via a hashtable and that a
 * ref_cnt is maintained is not required for the btrfs integrity
 * check algorithm itself, it is only used to make the output more
 * beautiful in case that an error is detected (an error is defined
 * as a write operation to a block while that block is still referenced).
 */
struct btrfsic_block_link {
	u32 magic_num;		/* only used for debug purposes */
	u32 ref_cnt;
	struct list_head node_ref_to;	/* list node */
	struct list_head node_ref_from;	/* list node */
	struct list_head collision_resolving_node;	/* list node */
	struct btrfsic_block *block_ref_to;
	struct btrfsic_block *block_ref_from;
	u64 parent_generation;
};

struct btrfsic_dev_state {
	u32 magic_num;		/* only used for debug purposes */
	struct block_device *bdev;
	struct btrfsic_state *state;
	struct list_head collision_resolving_node;	/* list node */
	struct btrfsic_block dummy_block_for_bio_bh_flush;
	u64 last_flush_gen;
	char name[BDEVNAME_SIZE];
};

struct btrfsic_block_hashtable {
	struct list_head table[BTRFSIC_BLOCK_HASHTABLE_SIZE];
};

struct btrfsic_block_link_hashtable {
	struct list_head table[BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE];
};

struct btrfsic_dev_state_hashtable {
	struct list_head table[BTRFSIC_DEV2STATE_HASHTABLE_SIZE];
};

struct btrfsic_block_data_ctx {
	u64 start;		/* virtual bytenr */
	u64 dev_bytenr;		/* physical bytenr on device */
	u32 len;
	struct btrfsic_dev_state *dev;
213 214 215
	char **datav;
	struct page **pagev;
	void *mem_to_free;
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
};

/* This structure is used to implement recursion without occupying
 * any stack space, refer to btrfsic_process_metablock() */
struct btrfsic_stack_frame {
	u32 magic;
	u32 nr;
	int error;
	int i;
	int limit_nesting;
	int num_copies;
	int mirror_num;
	struct btrfsic_block *block;
	struct btrfsic_block_data_ctx *block_ctx;
	struct btrfsic_block *next_block;
	struct btrfsic_block_data_ctx next_block_ctx;
	struct btrfs_header *hdr;
	struct btrfsic_stack_frame *prev;
};

/* Some state per mounted filesystem */
struct btrfsic_state {
	u32 print_mask;
	int include_extent_data;
	int csum_size;
	struct list_head all_blocks_list;
	struct btrfsic_block_hashtable block_hashtable;
	struct btrfsic_block_link_hashtable block_link_hashtable;
	struct btrfs_root *root;
	u64 max_superblock_generation;
	struct btrfsic_block *latest_superblock;
247 248
	u32 metablock_size;
	u32 datablock_size;
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
};

static void btrfsic_block_init(struct btrfsic_block *b);
static struct btrfsic_block *btrfsic_block_alloc(void);
static void btrfsic_block_free(struct btrfsic_block *b);
static void btrfsic_block_link_init(struct btrfsic_block_link *n);
static struct btrfsic_block_link *btrfsic_block_link_alloc(void);
static void btrfsic_block_link_free(struct btrfsic_block_link *n);
static void btrfsic_dev_state_init(struct btrfsic_dev_state *ds);
static struct btrfsic_dev_state *btrfsic_dev_state_alloc(void);
static void btrfsic_dev_state_free(struct btrfsic_dev_state *ds);
static void btrfsic_block_hashtable_init(struct btrfsic_block_hashtable *h);
static void btrfsic_block_hashtable_add(struct btrfsic_block *b,
					struct btrfsic_block_hashtable *h);
static void btrfsic_block_hashtable_remove(struct btrfsic_block *b);
static struct btrfsic_block *btrfsic_block_hashtable_lookup(
		struct block_device *bdev,
		u64 dev_bytenr,
		struct btrfsic_block_hashtable *h);
static void btrfsic_block_link_hashtable_init(
		struct btrfsic_block_link_hashtable *h);
static void btrfsic_block_link_hashtable_add(
		struct btrfsic_block_link *l,
		struct btrfsic_block_link_hashtable *h);
static void btrfsic_block_link_hashtable_remove(struct btrfsic_block_link *l);
static struct btrfsic_block_link *btrfsic_block_link_hashtable_lookup(
		struct block_device *bdev_ref_to,
		u64 dev_bytenr_ref_to,
		struct block_device *bdev_ref_from,
		u64 dev_bytenr_ref_from,
		struct btrfsic_block_link_hashtable *h);
static void btrfsic_dev_state_hashtable_init(
		struct btrfsic_dev_state_hashtable *h);
static void btrfsic_dev_state_hashtable_add(
		struct btrfsic_dev_state *ds,
		struct btrfsic_dev_state_hashtable *h);
static void btrfsic_dev_state_hashtable_remove(struct btrfsic_dev_state *ds);
static struct btrfsic_dev_state *btrfsic_dev_state_hashtable_lookup(
		struct block_device *bdev,
		struct btrfsic_dev_state_hashtable *h);
static struct btrfsic_stack_frame *btrfsic_stack_frame_alloc(void);
static void btrfsic_stack_frame_free(struct btrfsic_stack_frame *sf);
static int btrfsic_process_superblock(struct btrfsic_state *state,
				      struct btrfs_fs_devices *fs_devices);
static int btrfsic_process_metablock(struct btrfsic_state *state,
				     struct btrfsic_block *block,
				     struct btrfsic_block_data_ctx *block_ctx,
				     int limit_nesting, int force_iodone_flag);
297 298 299
static void btrfsic_read_from_block_data(
	struct btrfsic_block_data_ctx *block_ctx,
	void *dst, u32 offset, size_t len);
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
static int btrfsic_create_link_to_next_block(
		struct btrfsic_state *state,
		struct btrfsic_block *block,
		struct btrfsic_block_data_ctx
		*block_ctx, u64 next_bytenr,
		int limit_nesting,
		struct btrfsic_block_data_ctx *next_block_ctx,
		struct btrfsic_block **next_blockp,
		int force_iodone_flag,
		int *num_copiesp, int *mirror_nump,
		struct btrfs_disk_key *disk_key,
		u64 parent_generation);
static int btrfsic_handle_extent_data(struct btrfsic_state *state,
				      struct btrfsic_block *block,
				      struct btrfsic_block_data_ctx *block_ctx,
				      u32 item_offset, int force_iodone_flag);
static int btrfsic_map_block(struct btrfsic_state *state, u64 bytenr, u32 len,
			     struct btrfsic_block_data_ctx *block_ctx_out,
			     int mirror_num);
static int btrfsic_map_superblock(struct btrfsic_state *state, u64 bytenr,
				  u32 len, struct block_device *bdev,
				  struct btrfsic_block_data_ctx *block_ctx_out);
static void btrfsic_release_block_ctx(struct btrfsic_block_data_ctx *block_ctx);
static int btrfsic_read_block(struct btrfsic_state *state,
			      struct btrfsic_block_data_ctx *block_ctx);
static void btrfsic_dump_database(struct btrfsic_state *state);
326
static void btrfsic_complete_bio_end_io(struct bio *bio, int err);
327
static int btrfsic_test_for_metadata(struct btrfsic_state *state,
328
				     char **datav, unsigned int num_pages);
329
static void btrfsic_process_written_block(struct btrfsic_dev_state *dev_state,
330 331 332
					  u64 dev_bytenr, char **mapped_datav,
					  unsigned int num_pages,
					  struct bio *bio, int *bio_is_patched,
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
					  struct buffer_head *bh,
					  int submit_bio_bh_rw);
static int btrfsic_process_written_superblock(
		struct btrfsic_state *state,
		struct btrfsic_block *const block,
		struct btrfs_super_block *const super_hdr);
static void btrfsic_bio_end_io(struct bio *bp, int bio_error_status);
static void btrfsic_bh_end_io(struct buffer_head *bh, int uptodate);
static int btrfsic_is_block_ref_by_superblock(const struct btrfsic_state *state,
					      const struct btrfsic_block *block,
					      int recursion_level);
static int btrfsic_check_all_ref_blocks(struct btrfsic_state *state,
					struct btrfsic_block *const block,
					int recursion_level);
static void btrfsic_print_add_link(const struct btrfsic_state *state,
				   const struct btrfsic_block_link *l);
static void btrfsic_print_rem_link(const struct btrfsic_state *state,
				   const struct btrfsic_block_link *l);
static char btrfsic_get_block_type(const struct btrfsic_state *state,
				   const struct btrfsic_block *block);
static void btrfsic_dump_tree(const struct btrfsic_state *state);
static void btrfsic_dump_tree_sub(const struct btrfsic_state *state,
				  const struct btrfsic_block *block,
				  int indent_level);
static struct btrfsic_block_link *btrfsic_block_link_lookup_or_add(
		struct btrfsic_state *state,
		struct btrfsic_block_data_ctx *next_block_ctx,
		struct btrfsic_block *next_block,
		struct btrfsic_block *from_block,
		u64 parent_generation);
static struct btrfsic_block *btrfsic_block_lookup_or_add(
		struct btrfsic_state *state,
		struct btrfsic_block_data_ctx *block_ctx,
		const char *additional_string,
		int is_metadata,
		int is_iodone,
		int never_written,
		int mirror_num,
		int *was_created);
static int btrfsic_process_superblock_dev_mirror(
		struct btrfsic_state *state,
		struct btrfsic_dev_state *dev_state,
		struct btrfs_device *device,
		int superblock_mirror_num,
		struct btrfsic_dev_state **selected_dev_state,
		struct btrfs_super_block *selected_super);
static struct btrfsic_dev_state *btrfsic_dev_state_lookup(
		struct block_device *bdev);
static void btrfsic_cmp_log_and_dev_bytenr(struct btrfsic_state *state,
					   u64 bytenr,
					   struct btrfsic_dev_state *dev_state,
384
					   u64 dev_bytenr);
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

static struct mutex btrfsic_mutex;
static int btrfsic_is_initialized;
static struct btrfsic_dev_state_hashtable btrfsic_dev_state_hashtable;


static void btrfsic_block_init(struct btrfsic_block *b)
{
	b->magic_num = BTRFSIC_BLOCK_MAGIC_NUMBER;
	b->dev_state = NULL;
	b->dev_bytenr = 0;
	b->logical_bytenr = 0;
	b->generation = BTRFSIC_GENERATION_UNKNOWN;
	b->disk_key.objectid = 0;
	b->disk_key.type = 0;
	b->disk_key.offset = 0;
	b->is_metadata = 0;
	b->is_superblock = 0;
	b->is_iodone = 0;
	b->iodone_w_error = 0;
	b->never_written = 0;
	b->mirror_num = 0;
	b->next_in_same_bio = NULL;
	b->orig_bio_bh_private = NULL;
	b->orig_bio_bh_end_io.bio = NULL;
	INIT_LIST_HEAD(&b->collision_resolving_node);
	INIT_LIST_HEAD(&b->all_blocks_node);
	INIT_LIST_HEAD(&b->ref_to_list);
	INIT_LIST_HEAD(&b->ref_from_list);
	b->submit_bio_bh_rw = 0;
	b->flush_gen = 0;
}

static struct btrfsic_block *btrfsic_block_alloc(void)
{
	struct btrfsic_block *b;

	b = kzalloc(sizeof(*b), GFP_NOFS);
	if (NULL != b)
		btrfsic_block_init(b);

	return b;
}

static void btrfsic_block_free(struct btrfsic_block *b)
{
	BUG_ON(!(NULL == b || BTRFSIC_BLOCK_MAGIC_NUMBER == b->magic_num));
	kfree(b);
}

static void btrfsic_block_link_init(struct btrfsic_block_link *l)
{
	l->magic_num = BTRFSIC_BLOCK_LINK_MAGIC_NUMBER;
	l->ref_cnt = 1;
	INIT_LIST_HEAD(&l->node_ref_to);
	INIT_LIST_HEAD(&l->node_ref_from);
	INIT_LIST_HEAD(&l->collision_resolving_node);
	l->block_ref_to = NULL;
	l->block_ref_from = NULL;
}

static struct btrfsic_block_link *btrfsic_block_link_alloc(void)
{
	struct btrfsic_block_link *l;

	l = kzalloc(sizeof(*l), GFP_NOFS);
	if (NULL != l)
		btrfsic_block_link_init(l);

	return l;
}

static void btrfsic_block_link_free(struct btrfsic_block_link *l)
{
	BUG_ON(!(NULL == l || BTRFSIC_BLOCK_LINK_MAGIC_NUMBER == l->magic_num));
	kfree(l);
}

static void btrfsic_dev_state_init(struct btrfsic_dev_state *ds)
{
	ds->magic_num = BTRFSIC_DEV2STATE_MAGIC_NUMBER;
	ds->bdev = NULL;
	ds->state = NULL;
	ds->name[0] = '\0';
	INIT_LIST_HEAD(&ds->collision_resolving_node);
	ds->last_flush_gen = 0;
	btrfsic_block_init(&ds->dummy_block_for_bio_bh_flush);
	ds->dummy_block_for_bio_bh_flush.is_iodone = 1;
	ds->dummy_block_for_bio_bh_flush.dev_state = ds;
}

static struct btrfsic_dev_state *btrfsic_dev_state_alloc(void)
{
	struct btrfsic_dev_state *ds;

	ds = kzalloc(sizeof(*ds), GFP_NOFS);
	if (NULL != ds)
		btrfsic_dev_state_init(ds);

	return ds;
}

static void btrfsic_dev_state_free(struct btrfsic_dev_state *ds)
{
	BUG_ON(!(NULL == ds ||
		 BTRFSIC_DEV2STATE_MAGIC_NUMBER == ds->magic_num));
	kfree(ds);
}

static void btrfsic_block_hashtable_init(struct btrfsic_block_hashtable *h)
{
	int i;

	for (i = 0; i < BTRFSIC_BLOCK_HASHTABLE_SIZE; i++)
		INIT_LIST_HEAD(h->table + i);
}

static void btrfsic_block_hashtable_add(struct btrfsic_block *b,
					struct btrfsic_block_hashtable *h)
{
	const unsigned int hashval =
	    (((unsigned int)(b->dev_bytenr >> 16)) ^
	     ((unsigned int)((uintptr_t)b->dev_state->bdev))) &
	     (BTRFSIC_BLOCK_HASHTABLE_SIZE - 1);

	list_add(&b->collision_resolving_node, h->table + hashval);
}

static void btrfsic_block_hashtable_remove(struct btrfsic_block *b)
{
	list_del(&b->collision_resolving_node);
}

static struct btrfsic_block *btrfsic_block_hashtable_lookup(
		struct block_device *bdev,
		u64 dev_bytenr,
		struct btrfsic_block_hashtable *h)
{
	const unsigned int hashval =
	    (((unsigned int)(dev_bytenr >> 16)) ^
	     ((unsigned int)((uintptr_t)bdev))) &
	     (BTRFSIC_BLOCK_HASHTABLE_SIZE - 1);
	struct list_head *elem;

	list_for_each(elem, h->table + hashval) {
		struct btrfsic_block *const b =
		    list_entry(elem, struct btrfsic_block,
			       collision_resolving_node);

		if (b->dev_state->bdev == bdev && b->dev_bytenr == dev_bytenr)
			return b;
	}

	return NULL;
}

static void btrfsic_block_link_hashtable_init(
		struct btrfsic_block_link_hashtable *h)
{
	int i;

	for (i = 0; i < BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE; i++)
		INIT_LIST_HEAD(h->table + i);
}

static void btrfsic_block_link_hashtable_add(
		struct btrfsic_block_link *l,
		struct btrfsic_block_link_hashtable *h)
{
	const unsigned int hashval =
	    (((unsigned int)(l->block_ref_to->dev_bytenr >> 16)) ^
	     ((unsigned int)(l->block_ref_from->dev_bytenr >> 16)) ^
	     ((unsigned int)((uintptr_t)l->block_ref_to->dev_state->bdev)) ^
	     ((unsigned int)((uintptr_t)l->block_ref_from->dev_state->bdev)))
	     & (BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE - 1);

	BUG_ON(NULL == l->block_ref_to);
	BUG_ON(NULL == l->block_ref_from);
	list_add(&l->collision_resolving_node, h->table + hashval);
}

static void btrfsic_block_link_hashtable_remove(struct btrfsic_block_link *l)
{
	list_del(&l->collision_resolving_node);
}

static struct btrfsic_block_link *btrfsic_block_link_hashtable_lookup(
		struct block_device *bdev_ref_to,
		u64 dev_bytenr_ref_to,
		struct block_device *bdev_ref_from,
		u64 dev_bytenr_ref_from,
		struct btrfsic_block_link_hashtable *h)
{
	const unsigned int hashval =
	    (((unsigned int)(dev_bytenr_ref_to >> 16)) ^
	     ((unsigned int)(dev_bytenr_ref_from >> 16)) ^
	     ((unsigned int)((uintptr_t)bdev_ref_to)) ^
	     ((unsigned int)((uintptr_t)bdev_ref_from))) &
	     (BTRFSIC_BLOCK_LINK_HASHTABLE_SIZE - 1);
	struct list_head *elem;

	list_for_each(elem, h->table + hashval) {
		struct btrfsic_block_link *const l =
		    list_entry(elem, struct btrfsic_block_link,
			       collision_resolving_node);

		BUG_ON(NULL == l->block_ref_to);
		BUG_ON(NULL == l->block_ref_from);
		if (l->block_ref_to->dev_state->bdev == bdev_ref_to &&
		    l->block_ref_to->dev_bytenr == dev_bytenr_ref_to &&
		    l->block_ref_from->dev_state->bdev == bdev_ref_from &&
		    l->block_ref_from->dev_bytenr == dev_bytenr_ref_from)
			return l;
	}

	return NULL;
}

static void btrfsic_dev_state_hashtable_init(
		struct btrfsic_dev_state_hashtable *h)
{
	int i;

	for (i = 0; i < BTRFSIC_DEV2STATE_HASHTABLE_SIZE; i++)
		INIT_LIST_HEAD(h->table + i);
}

static void btrfsic_dev_state_hashtable_add(
		struct btrfsic_dev_state *ds,
		struct btrfsic_dev_state_hashtable *h)
{
	const unsigned int hashval =
	    (((unsigned int)((uintptr_t)ds->bdev)) &
	     (BTRFSIC_DEV2STATE_HASHTABLE_SIZE - 1));

	list_add(&ds->collision_resolving_node, h->table + hashval);
}

static void btrfsic_dev_state_hashtable_remove(struct btrfsic_dev_state *ds)
{
	list_del(&ds->collision_resolving_node);
}

static struct btrfsic_dev_state *btrfsic_dev_state_hashtable_lookup(
		struct block_device *bdev,
		struct btrfsic_dev_state_hashtable *h)
{
	const unsigned int hashval =
	    (((unsigned int)((uintptr_t)bdev)) &
	     (BTRFSIC_DEV2STATE_HASHTABLE_SIZE - 1));
	struct list_head *elem;

	list_for_each(elem, h->table + hashval) {
		struct btrfsic_dev_state *const ds =
		    list_entry(elem, struct btrfsic_dev_state,
			       collision_resolving_node);

		if (ds->bdev == bdev)
			return ds;
	}

	return NULL;
}

static int btrfsic_process_superblock(struct btrfsic_state *state,
				      struct btrfs_fs_devices *fs_devices)
{
652
	int ret = 0;
653 654 655 656 657 658 659
	struct btrfs_super_block *selected_super;
	struct list_head *dev_head = &fs_devices->devices;
	struct btrfs_device *device;
	struct btrfsic_dev_state *selected_dev_state = NULL;
	int pass;

	BUG_ON(NULL == state);
660
	selected_super = kzalloc(sizeof(*selected_super), GFP_NOFS);
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
	if (NULL == selected_super) {
		printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
		return -1;
	}

	list_for_each_entry(device, dev_head, dev_list) {
		int i;
		struct btrfsic_dev_state *dev_state;

		if (!device->bdev || !device->name)
			continue;

		dev_state = btrfsic_dev_state_lookup(device->bdev);
		BUG_ON(NULL == dev_state);
		for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
			ret = btrfsic_process_superblock_dev_mirror(
					state, dev_state, device, i,
					&selected_dev_state, selected_super);
			if (0 != ret && 0 == i) {
				kfree(selected_super);
				return ret;
			}
		}
	}

	if (NULL == state->latest_superblock) {
		printk(KERN_INFO "btrfsic: no superblock found!\n");
		kfree(selected_super);
		return -1;
	}

	state->csum_size = btrfs_super_csum_size(selected_super);

	for (pass = 0; pass < 3; pass++) {
		int num_copies;
		int mirror_num;
		u64 next_bytenr;

		switch (pass) {
		case 0:
			next_bytenr = btrfs_super_root(selected_super);
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
704
				printk(KERN_INFO "root@%llu\n", next_bytenr);
705 706 707 708 709
			break;
		case 1:
			next_bytenr = btrfs_super_chunk_root(selected_super);
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
710
				printk(KERN_INFO "chunk@%llu\n", next_bytenr);
711 712 713 714 715 716 717
			break;
		case 2:
			next_bytenr = btrfs_super_log_root(selected_super);
			if (0 == next_bytenr)
				continue;
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
718
				printk(KERN_INFO "log@%llu\n", next_bytenr);
719 720 721 722
			break;
		}

		num_copies =
723
		    btrfs_num_copies(state->root->fs_info,
724
				     next_bytenr, state->metablock_size);
725 726
		if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
			printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
727
			       next_bytenr, num_copies);
728 729 730 731 732 733

		for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
			struct btrfsic_block *next_block;
			struct btrfsic_block_data_ctx tmp_next_block_ctx;
			struct btrfsic_block_link *l;

734 735
			ret = btrfsic_map_block(state, next_bytenr,
						state->metablock_size,
736 737 738 739 740 741
						&tmp_next_block_ctx,
						mirror_num);
			if (ret) {
				printk(KERN_INFO "btrfsic:"
				       " btrfsic_map_block(root @%llu,"
				       " mirror %d) failed!\n",
742
				       next_bytenr, mirror_num);
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
				kfree(selected_super);
				return -1;
			}

			next_block = btrfsic_block_hashtable_lookup(
					tmp_next_block_ctx.dev->bdev,
					tmp_next_block_ctx.dev_bytenr,
					&state->block_hashtable);
			BUG_ON(NULL == next_block);

			l = btrfsic_block_link_hashtable_lookup(
					tmp_next_block_ctx.dev->bdev,
					tmp_next_block_ctx.dev_bytenr,
					state->latest_superblock->dev_state->
					bdev,
					state->latest_superblock->dev_bytenr,
					&state->block_link_hashtable);
			BUG_ON(NULL == l);

			ret = btrfsic_read_block(state, &tmp_next_block_ctx);
763
			if (ret < (int)PAGE_CACHE_SIZE) {
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
				printk(KERN_INFO
				       "btrfsic: read @logical %llu failed!\n",
				       tmp_next_block_ctx.start);
				btrfsic_release_block_ctx(&tmp_next_block_ctx);
				kfree(selected_super);
				return -1;
			}

			ret = btrfsic_process_metablock(state,
							next_block,
							&tmp_next_block_ctx,
							BTRFS_MAX_LEVEL + 3, 1);
			btrfsic_release_block_ctx(&tmp_next_block_ctx);
		}
	}

	kfree(selected_super);
	return ret;
}

static int btrfsic_process_superblock_dev_mirror(
		struct btrfsic_state *state,
		struct btrfsic_dev_state *dev_state,
		struct btrfs_device *device,
		int superblock_mirror_num,
		struct btrfsic_dev_state **selected_dev_state,
		struct btrfs_super_block *selected_super)
{
	struct btrfs_super_block *super_tmp;
	u64 dev_bytenr;
	struct buffer_head *bh;
	struct btrfsic_block *superblock_tmp;
	int pass;
	struct block_device *const superblock_bdev = device->bdev;

	/* super block bytenr is always the unmapped device bytenr */
	dev_bytenr = btrfs_sb_offset(superblock_mirror_num);
801 802 803 804
	if (dev_bytenr + BTRFS_SUPER_INFO_SIZE > device->total_bytes)
		return -1;
	bh = __bread(superblock_bdev, dev_bytenr / 4096,
		     BTRFS_SUPER_INFO_SIZE);
805 806 807 808 809 810
	if (NULL == bh)
		return -1;
	super_tmp = (struct btrfs_super_block *)
	    (bh->b_data + (dev_bytenr & 4095));

	if (btrfs_super_bytenr(super_tmp) != dev_bytenr ||
811
	    btrfs_super_magic(super_tmp) != BTRFS_MAGIC ||
812 813 814 815
	    memcmp(device->uuid, super_tmp->dev_item.uuid, BTRFS_UUID_SIZE) ||
	    btrfs_super_nodesize(super_tmp) != state->metablock_size ||
	    btrfs_super_leafsize(super_tmp) != state->metablock_size ||
	    btrfs_super_sectorsize(super_tmp) != state->datablock_size) {
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
		brelse(bh);
		return 0;
	}

	superblock_tmp =
	    btrfsic_block_hashtable_lookup(superblock_bdev,
					   dev_bytenr,
					   &state->block_hashtable);
	if (NULL == superblock_tmp) {
		superblock_tmp = btrfsic_block_alloc();
		if (NULL == superblock_tmp) {
			printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
			brelse(bh);
			return -1;
		}
		/* for superblock, only the dev_bytenr makes sense */
		superblock_tmp->dev_bytenr = dev_bytenr;
		superblock_tmp->dev_state = dev_state;
		superblock_tmp->logical_bytenr = dev_bytenr;
		superblock_tmp->generation = btrfs_super_generation(super_tmp);
		superblock_tmp->is_metadata = 1;
		superblock_tmp->is_superblock = 1;
		superblock_tmp->is_iodone = 1;
		superblock_tmp->never_written = 0;
		superblock_tmp->mirror_num = 1 + superblock_mirror_num;
		if (state->print_mask & BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE)
842 843 844
			printk_in_rcu(KERN_INFO "New initial S-block (bdev %p, %s)"
				     " @%llu (%s/%llu/%d)\n",
				     superblock_bdev,
845 846
				     rcu_str_deref(device->name), dev_bytenr,
				     dev_state->name, dev_bytenr,
847
				     superblock_mirror_num);
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
		list_add(&superblock_tmp->all_blocks_node,
			 &state->all_blocks_list);
		btrfsic_block_hashtable_add(superblock_tmp,
					    &state->block_hashtable);
	}

	/* select the one with the highest generation field */
	if (btrfs_super_generation(super_tmp) >
	    state->max_superblock_generation ||
	    0 == state->max_superblock_generation) {
		memcpy(selected_super, super_tmp, sizeof(*selected_super));
		*selected_dev_state = dev_state;
		state->max_superblock_generation =
		    btrfs_super_generation(super_tmp);
		state->latest_superblock = superblock_tmp;
	}

	for (pass = 0; pass < 3; pass++) {
		u64 next_bytenr;
		int num_copies;
		int mirror_num;
		const char *additional_string = NULL;
		struct btrfs_disk_key tmp_disk_key;

		tmp_disk_key.type = BTRFS_ROOT_ITEM_KEY;
		tmp_disk_key.offset = 0;
		switch (pass) {
		case 0:
876 877
			btrfs_set_disk_key_objectid(&tmp_disk_key,
						    BTRFS_ROOT_TREE_OBJECTID);
878 879 880 881
			additional_string = "initial root ";
			next_bytenr = btrfs_super_root(super_tmp);
			break;
		case 1:
882 883
			btrfs_set_disk_key_objectid(&tmp_disk_key,
						    BTRFS_CHUNK_TREE_OBJECTID);
884 885 886 887
			additional_string = "initial chunk ";
			next_bytenr = btrfs_super_chunk_root(super_tmp);
			break;
		case 2:
888 889
			btrfs_set_disk_key_objectid(&tmp_disk_key,
						    BTRFS_TREE_LOG_OBJECTID);
890 891 892 893 894 895 896 897
			additional_string = "initial log ";
			next_bytenr = btrfs_super_log_root(super_tmp);
			if (0 == next_bytenr)
				continue;
			break;
		}

		num_copies =
898
		    btrfs_num_copies(state->root->fs_info,
899
				     next_bytenr, state->metablock_size);
900 901
		if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
			printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
902
			       next_bytenr, num_copies);
903 904 905 906 907
		for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
			struct btrfsic_block *next_block;
			struct btrfsic_block_data_ctx tmp_next_block_ctx;
			struct btrfsic_block_link *l;

908 909
			if (btrfsic_map_block(state, next_bytenr,
					      state->metablock_size,
910 911 912 913
					      &tmp_next_block_ctx,
					      mirror_num)) {
				printk(KERN_INFO "btrfsic: btrfsic_map_block("
				       "bytenr @%llu, mirror %d) failed!\n",
914
				       next_bytenr, mirror_num);
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
				brelse(bh);
				return -1;
			}

			next_block = btrfsic_block_lookup_or_add(
					state, &tmp_next_block_ctx,
					additional_string, 1, 1, 0,
					mirror_num, NULL);
			if (NULL == next_block) {
				btrfsic_release_block_ctx(&tmp_next_block_ctx);
				brelse(bh);
				return -1;
			}

			next_block->disk_key = tmp_disk_key;
			next_block->generation = BTRFSIC_GENERATION_UNKNOWN;
			l = btrfsic_block_link_lookup_or_add(
					state, &tmp_next_block_ctx,
					next_block, superblock_tmp,
					BTRFSIC_GENERATION_UNKNOWN);
			btrfsic_release_block_ctx(&tmp_next_block_ctx);
			if (NULL == l) {
				brelse(bh);
				return -1;
			}
		}
	}
	if (state->print_mask & BTRFSIC_PRINT_MASK_INITIAL_ALL_TREES)
		btrfsic_dump_tree_sub(state, superblock_tmp, 0);

	brelse(bh);
	return 0;
}

static struct btrfsic_stack_frame *btrfsic_stack_frame_alloc(void)
{
	struct btrfsic_stack_frame *sf;

	sf = kzalloc(sizeof(*sf), GFP_NOFS);
	if (NULL == sf)
		printk(KERN_INFO "btrfsic: alloc memory failed!\n");
	else
		sf->magic = BTRFSIC_BLOCK_STACK_FRAME_MAGIC_NUMBER;
	return sf;
}

static void btrfsic_stack_frame_free(struct btrfsic_stack_frame *sf)
{
	BUG_ON(!(NULL == sf ||
		 BTRFSIC_BLOCK_STACK_FRAME_MAGIC_NUMBER == sf->magic));
	kfree(sf);
}

static int btrfsic_process_metablock(
		struct btrfsic_state *state,
		struct btrfsic_block *const first_block,
		struct btrfsic_block_data_ctx *const first_block_ctx,
		int first_limit_nesting, int force_iodone_flag)
{
	struct btrfsic_stack_frame initial_stack_frame = { 0 };
	struct btrfsic_stack_frame *sf;
	struct btrfsic_stack_frame *next_stack;
977 978
	struct btrfs_header *const first_hdr =
		(struct btrfs_header *)first_block_ctx->datav[0];
979

980
	BUG_ON(!first_hdr);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
	sf = &initial_stack_frame;
	sf->error = 0;
	sf->i = -1;
	sf->limit_nesting = first_limit_nesting;
	sf->block = first_block;
	sf->block_ctx = first_block_ctx;
	sf->next_block = NULL;
	sf->hdr = first_hdr;
	sf->prev = NULL;

continue_with_new_stack_frame:
	sf->block->generation = le64_to_cpu(sf->hdr->generation);
	if (0 == sf->hdr->level) {
		struct btrfs_leaf *const leafhdr =
		    (struct btrfs_leaf *)sf->hdr;

		if (-1 == sf->i) {
998
			sf->nr = btrfs_stack_header_nritems(&leafhdr->header);
999 1000 1001 1002 1003

			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO
				       "leaf %llu items %d generation %llu"
				       " owner %llu\n",
1004
				       sf->block_ctx->start, sf->nr,
1005 1006 1007 1008
				       btrfs_stack_header_generation(
					       &leafhdr->header),
				       btrfs_stack_header_owner(
					       &leafhdr->header));
1009 1010 1011 1012 1013 1014 1015 1016 1017
		}

continue_with_current_leaf_stack_frame:
		if (0 == sf->num_copies || sf->mirror_num > sf->num_copies) {
			sf->i++;
			sf->num_copies = 0;
		}

		if (sf->i < sf->nr) {
1018 1019 1020 1021 1022
			struct btrfs_item disk_item;
			u32 disk_item_offset =
				(uintptr_t)(leafhdr->items + sf->i) -
				(uintptr_t)leafhdr;
			struct btrfs_disk_key *disk_key;
1023
			u8 type;
1024
			u32 item_offset;
1025
			u32 item_size;
1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
			if (disk_item_offset + sizeof(struct btrfs_item) >
			    sf->block_ctx->len) {
leaf_item_out_of_bounce_error:
				printk(KERN_INFO
				       "btrfsic: leaf item out of bounce at logical %llu, dev %s\n",
				       sf->block_ctx->start,
				       sf->block_ctx->dev->name);
				goto one_stack_frame_backwards;
			}
			btrfsic_read_from_block_data(sf->block_ctx,
						     &disk_item,
						     disk_item_offset,
						     sizeof(struct btrfs_item));
1040 1041
			item_offset = btrfs_stack_item_offset(&disk_item);
			item_size = btrfs_stack_item_offset(&disk_item);
1042
			disk_key = &disk_item.key;
1043
			type = btrfs_disk_key_type(disk_key);
1044 1045

			if (BTRFS_ROOT_ITEM_KEY == type) {
1046 1047 1048 1049 1050 1051
				struct btrfs_root_item root_item;
				u32 root_item_offset;
				u64 next_bytenr;

				root_item_offset = item_offset +
					offsetof(struct btrfs_leaf, items);
1052
				if (root_item_offset + item_size >
1053 1054 1055 1056 1057
				    sf->block_ctx->len)
					goto leaf_item_out_of_bounce_error;
				btrfsic_read_from_block_data(
					sf->block_ctx, &root_item,
					root_item_offset,
1058
					item_size);
1059
				next_bytenr = btrfs_root_bytenr(&root_item);
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

				sf->error =
				    btrfsic_create_link_to_next_block(
						state,
						sf->block,
						sf->block_ctx,
						next_bytenr,
						sf->limit_nesting,
						&sf->next_block_ctx,
						&sf->next_block,
						force_iodone_flag,
						&sf->num_copies,
						&sf->mirror_num,
						disk_key,
1074 1075
						btrfs_root_generation(
						&root_item));
1076 1077 1078 1079 1080 1081
				if (sf->error)
					goto one_stack_frame_backwards;

				if (NULL != sf->next_block) {
					struct btrfs_header *const next_hdr =
					    (struct btrfs_header *)
1082
					    sf->next_block_ctx.datav[0];
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122

					next_stack =
					    btrfsic_stack_frame_alloc();
					if (NULL == next_stack) {
						btrfsic_release_block_ctx(
								&sf->
								next_block_ctx);
						goto one_stack_frame_backwards;
					}

					next_stack->i = -1;
					next_stack->block = sf->next_block;
					next_stack->block_ctx =
					    &sf->next_block_ctx;
					next_stack->next_block = NULL;
					next_stack->hdr = next_hdr;
					next_stack->limit_nesting =
					    sf->limit_nesting - 1;
					next_stack->prev = sf;
					sf = next_stack;
					goto continue_with_new_stack_frame;
				}
			} else if (BTRFS_EXTENT_DATA_KEY == type &&
				   state->include_extent_data) {
				sf->error = btrfsic_handle_extent_data(
						state,
						sf->block,
						sf->block_ctx,
						item_offset,
						force_iodone_flag);
				if (sf->error)
					goto one_stack_frame_backwards;
			}

			goto continue_with_current_leaf_stack_frame;
		}
	} else {
		struct btrfs_node *const nodehdr = (struct btrfs_node *)sf->hdr;

		if (-1 == sf->i) {
1123
			sf->nr = btrfs_stack_header_nritems(&nodehdr->header);
1124 1125 1126 1127 1128 1129

			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO "node %llu level %d items %d"
				       " generation %llu owner %llu\n",
				       sf->block_ctx->start,
				       nodehdr->header.level, sf->nr,
1130 1131 1132 1133
				       btrfs_stack_header_generation(
				       &nodehdr->header),
				       btrfs_stack_header_owner(
				       &nodehdr->header));
1134 1135 1136 1137 1138 1139 1140 1141 1142
		}

continue_with_current_node_stack_frame:
		if (0 == sf->num_copies || sf->mirror_num > sf->num_copies) {
			sf->i++;
			sf->num_copies = 0;
		}

		if (sf->i < sf->nr) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
			struct btrfs_key_ptr key_ptr;
			u32 key_ptr_offset;
			u64 next_bytenr;

			key_ptr_offset = (uintptr_t)(nodehdr->ptrs + sf->i) -
					  (uintptr_t)nodehdr;
			if (key_ptr_offset + sizeof(struct btrfs_key_ptr) >
			    sf->block_ctx->len) {
				printk(KERN_INFO
				       "btrfsic: node item out of bounce at logical %llu, dev %s\n",
				       sf->block_ctx->start,
				       sf->block_ctx->dev->name);
				goto one_stack_frame_backwards;
			}
			btrfsic_read_from_block_data(
				sf->block_ctx, &key_ptr, key_ptr_offset,
				sizeof(struct btrfs_key_ptr));
1160
			next_bytenr = btrfs_stack_key_blockptr(&key_ptr);
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

			sf->error = btrfsic_create_link_to_next_block(
					state,
					sf->block,
					sf->block_ctx,
					next_bytenr,
					sf->limit_nesting,
					&sf->next_block_ctx,
					&sf->next_block,
					force_iodone_flag,
					&sf->num_copies,
					&sf->mirror_num,
1173
					&key_ptr.key,
1174
					btrfs_stack_key_generation(&key_ptr));
1175 1176 1177 1178 1179 1180
			if (sf->error)
				goto one_stack_frame_backwards;

			if (NULL != sf->next_block) {
				struct btrfs_header *const next_hdr =
				    (struct btrfs_header *)
1181
				    sf->next_block_ctx.datav[0];
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

				next_stack = btrfsic_stack_frame_alloc();
				if (NULL == next_stack)
					goto one_stack_frame_backwards;

				next_stack->i = -1;
				next_stack->block = sf->next_block;
				next_stack->block_ctx = &sf->next_block_ctx;
				next_stack->next_block = NULL;
				next_stack->hdr = next_hdr;
				next_stack->limit_nesting =
				    sf->limit_nesting - 1;
				next_stack->prev = sf;
				sf = next_stack;
				goto continue_with_new_stack_frame;
			}

			goto continue_with_current_node_stack_frame;
		}
	}

one_stack_frame_backwards:
	if (NULL != sf->prev) {
		struct btrfsic_stack_frame *const prev = sf->prev;

		/* the one for the initial block is freed in the caller */
		btrfsic_release_block_ctx(sf->block_ctx);

		if (sf->error) {
			prev->error = sf->error;
			btrfsic_stack_frame_free(sf);
			sf = prev;
			goto one_stack_frame_backwards;
		}

		btrfsic_stack_frame_free(sf);
		sf = prev;
		goto continue_with_new_stack_frame;
	} else {
		BUG_ON(&initial_stack_frame != sf);
	}

	return sf->error;
}

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
static void btrfsic_read_from_block_data(
	struct btrfsic_block_data_ctx *block_ctx,
	void *dstv, u32 offset, size_t len)
{
	size_t cur;
	size_t offset_in_page;
	char *kaddr;
	char *dst = (char *)dstv;
	size_t start_offset = block_ctx->start & ((u64)PAGE_CACHE_SIZE - 1);
	unsigned long i = (start_offset + offset) >> PAGE_CACHE_SHIFT;

	WARN_ON(offset + len > block_ctx->len);
1239
	offset_in_page = (start_offset + offset) & (PAGE_CACHE_SIZE - 1);
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

	while (len > 0) {
		cur = min(len, ((size_t)PAGE_CACHE_SIZE - offset_in_page));
		BUG_ON(i >= (block_ctx->len + PAGE_CACHE_SIZE - 1) >>
			    PAGE_CACHE_SHIFT);
		kaddr = block_ctx->datav[i];
		memcpy(dst, kaddr + offset_in_page, cur);

		dst += cur;
		len -= cur;
		offset_in_page = 0;
		i++;
	}
}

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
static int btrfsic_create_link_to_next_block(
		struct btrfsic_state *state,
		struct btrfsic_block *block,
		struct btrfsic_block_data_ctx *block_ctx,
		u64 next_bytenr,
		int limit_nesting,
		struct btrfsic_block_data_ctx *next_block_ctx,
		struct btrfsic_block **next_blockp,
		int force_iodone_flag,
		int *num_copiesp, int *mirror_nump,
		struct btrfs_disk_key *disk_key,
		u64 parent_generation)
{
	struct btrfsic_block *next_block = NULL;
	int ret;
	struct btrfsic_block_link *l;
	int did_alloc_block_link;
	int block_was_created;

	*next_blockp = NULL;
	if (0 == *num_copiesp) {
		*num_copiesp =
1277
		    btrfs_num_copies(state->root->fs_info,
1278
				     next_bytenr, state->metablock_size);
1279 1280
		if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
			printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
1281
			       next_bytenr, *num_copiesp);
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
		*mirror_nump = 1;
	}

	if (*mirror_nump > *num_copiesp)
		return 0;

	if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
		printk(KERN_INFO
		       "btrfsic_create_link_to_next_block(mirror_num=%d)\n",
		       *mirror_nump);
	ret = btrfsic_map_block(state, next_bytenr,
1293
				state->metablock_size,
1294 1295 1296 1297
				next_block_ctx, *mirror_nump);
	if (ret) {
		printk(KERN_INFO
		       "btrfsic: btrfsic_map_block(@%llu, mirror=%d) failed!\n",
1298
		       next_bytenr, *mirror_nump);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
		btrfsic_release_block_ctx(next_block_ctx);
		*next_blockp = NULL;
		return -1;
	}

	next_block = btrfsic_block_lookup_or_add(state,
						 next_block_ctx, "referenced ",
						 1, force_iodone_flag,
						 !force_iodone_flag,
						 *mirror_nump,
						 &block_was_created);
	if (NULL == next_block) {
		btrfsic_release_block_ctx(next_block_ctx);
		*next_blockp = NULL;
		return -1;
	}
	if (block_was_created) {
		l = NULL;
		next_block->generation = BTRFSIC_GENERATION_UNKNOWN;
	} else {
		if (next_block->logical_bytenr != next_bytenr &&
		    !(!next_block->is_metadata &&
		      0 == next_block->logical_bytenr)) {
			printk(KERN_INFO
			       "Referenced block @%llu (%s/%llu/%d)"
			       " found in hash table, %c,"
			       " bytenr mismatch (!= stored %llu).\n",
1326 1327
			       next_bytenr, next_block_ctx->dev->name,
			       next_block_ctx->dev_bytenr, *mirror_nump,
1328
			       btrfsic_get_block_type(state, next_block),
1329
			       next_block->logical_bytenr);
1330 1331 1332 1333
		} else if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "Referenced block @%llu (%s/%llu/%d)"
			       " found in hash table, %c.\n",
1334 1335
			       next_bytenr, next_block_ctx->dev->name,
			       next_block_ctx->dev_bytenr, *mirror_nump,
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
			       btrfsic_get_block_type(state, next_block));
		next_block->logical_bytenr = next_bytenr;

		next_block->mirror_num = *mirror_nump;
		l = btrfsic_block_link_hashtable_lookup(
				next_block_ctx->dev->bdev,
				next_block_ctx->dev_bytenr,
				block_ctx->dev->bdev,
				block_ctx->dev_bytenr,
				&state->block_link_hashtable);
	}

	next_block->disk_key = *disk_key;
	if (NULL == l) {
		l = btrfsic_block_link_alloc();
		if (NULL == l) {
			printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
			btrfsic_release_block_ctx(next_block_ctx);
			*next_blockp = NULL;
			return -1;
		}

		did_alloc_block_link = 1;
		l->block_ref_to = next_block;
		l->block_ref_from = block;
		l->ref_cnt = 1;
		l->parent_generation = parent_generation;

		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			btrfsic_print_add_link(state, l);

		list_add(&l->node_ref_to, &block->ref_to_list);
		list_add(&l->node_ref_from, &next_block->ref_from_list);

		btrfsic_block_link_hashtable_add(l,
						 &state->block_link_hashtable);
	} else {
		did_alloc_block_link = 0;
		if (0 == limit_nesting) {
			l->ref_cnt++;
			l->parent_generation = parent_generation;
			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				btrfsic_print_add_link(state, l);
		}
	}

	if (limit_nesting > 0 && did_alloc_block_link) {
		ret = btrfsic_read_block(state, next_block_ctx);
1384
		if (ret < (int)next_block_ctx->len) {
1385 1386
			printk(KERN_INFO
			       "btrfsic: read block @logical %llu failed!\n",
1387
			       next_bytenr);
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
			btrfsic_release_block_ctx(next_block_ctx);
			*next_blockp = NULL;
			return -1;
		}

		*next_blockp = next_block;
	} else {
		*next_blockp = NULL;
	}
	(*mirror_nump)++;

	return 0;
}

static int btrfsic_handle_extent_data(
		struct btrfsic_state *state,
		struct btrfsic_block *block,
		struct btrfsic_block_data_ctx *block_ctx,
		u32 item_offset, int force_iodone_flag)
{
	int ret;
1409 1410 1411 1412 1413
	struct btrfs_file_extent_item file_extent_item;
	u64 file_extent_item_offset;
	u64 next_bytenr;
	u64 num_bytes;
	u64 generation;
1414 1415
	struct btrfsic_block_link *l;

1416 1417
	file_extent_item_offset = offsetof(struct btrfs_leaf, items) +
				  item_offset;
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
	if (file_extent_item_offset +
	    offsetof(struct btrfs_file_extent_item, disk_num_bytes) >
	    block_ctx->len) {
		printk(KERN_INFO
		       "btrfsic: file item out of bounce at logical %llu, dev %s\n",
		       block_ctx->start, block_ctx->dev->name);
		return -1;
	}

	btrfsic_read_from_block_data(block_ctx, &file_extent_item,
		file_extent_item_offset,
		offsetof(struct btrfs_file_extent_item, disk_num_bytes));
	if (BTRFS_FILE_EXTENT_REG != file_extent_item.type ||
1431
	    btrfs_stack_file_extent_disk_bytenr(&file_extent_item) == 0) {
1432 1433 1434
		if (state->print_mask & BTRFSIC_PRINT_MASK_VERY_VERBOSE)
			printk(KERN_INFO "extent_data: type %u, disk_bytenr = %llu\n",
			       file_extent_item.type,
1435 1436
			       btrfs_stack_file_extent_disk_bytenr(
			       &file_extent_item));
1437 1438 1439
		return 0;
	}

1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
	if (file_extent_item_offset + sizeof(struct btrfs_file_extent_item) >
	    block_ctx->len) {
		printk(KERN_INFO
		       "btrfsic: file item out of bounce at logical %llu, dev %s\n",
		       block_ctx->start, block_ctx->dev->name);
		return -1;
	}
	btrfsic_read_from_block_data(block_ctx, &file_extent_item,
				     file_extent_item_offset,
				     sizeof(struct btrfs_file_extent_item));
1450 1451 1452 1453 1454
	next_bytenr = btrfs_stack_file_extent_disk_bytenr(&file_extent_item) +
		      btrfs_stack_file_extent_offset(&file_extent_item);
	generation = btrfs_stack_file_extent_generation(&file_extent_item);
	num_bytes = btrfs_stack_file_extent_num_bytes(&file_extent_item);
	generation = btrfs_stack_file_extent_generation(&file_extent_item);
1455

1456 1457 1458
	if (state->print_mask & BTRFSIC_PRINT_MASK_VERY_VERBOSE)
		printk(KERN_INFO "extent_data: type %u, disk_bytenr = %llu,"
		       " offset = %llu, num_bytes = %llu\n",
1459
		       file_extent_item.type,
1460 1461
		       btrfs_stack_file_extent_disk_bytenr(&file_extent_item),
		       btrfs_stack_file_extent_offset(&file_extent_item),
1462
		       num_bytes);
1463 1464 1465 1466 1467
	while (num_bytes > 0) {
		u32 chunk_len;
		int num_copies;
		int mirror_num;

1468 1469
		if (num_bytes > state->datablock_size)
			chunk_len = state->datablock_size;
1470 1471 1472 1473
		else
			chunk_len = num_bytes;

		num_copies =
1474
		    btrfs_num_copies(state->root->fs_info,
1475
				     next_bytenr, state->datablock_size);
1476 1477
		if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
			printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
1478
			       next_bytenr, num_copies);
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
		for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
			struct btrfsic_block_data_ctx next_block_ctx;
			struct btrfsic_block *next_block;
			int block_was_created;

			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO "btrfsic_handle_extent_data("
				       "mirror_num=%d)\n", mirror_num);
			if (state->print_mask & BTRFSIC_PRINT_MASK_VERY_VERBOSE)
				printk(KERN_INFO
				       "\tdisk_bytenr = %llu, num_bytes %u\n",
1490
				       next_bytenr, chunk_len);
1491 1492 1493 1494 1495 1496 1497
			ret = btrfsic_map_block(state, next_bytenr,
						chunk_len, &next_block_ctx,
						mirror_num);
			if (ret) {
				printk(KERN_INFO
				       "btrfsic: btrfsic_map_block(@%llu,"
				       " mirror=%d) failed!\n",
1498
				       next_bytenr, mirror_num);
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
				return -1;
			}

			next_block = btrfsic_block_lookup_or_add(
					state,
					&next_block_ctx,
					"referenced ",
					0,
					force_iodone_flag,
					!force_iodone_flag,
					mirror_num,
					&block_was_created);
			if (NULL == next_block) {
				printk(KERN_INFO
				       "btrfsic: error, kmalloc failed!\n");
				btrfsic_release_block_ctx(&next_block_ctx);
				return -1;
			}
			if (!block_was_created) {
				if (next_block->logical_bytenr != next_bytenr &&
				    !(!next_block->is_metadata &&
				      0 == next_block->logical_bytenr)) {
					printk(KERN_INFO
					       "Referenced block"
					       " @%llu (%s/%llu/%d)"
					       " found in hash table, D,"
					       " bytenr mismatch"
					       " (!= stored %llu).\n",
1527
					       next_bytenr,
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
					       next_block_ctx.dev->name,
					       next_block_ctx.dev_bytenr,
					       mirror_num,
					       next_block->logical_bytenr);
				}
				next_block->logical_bytenr = next_bytenr;
				next_block->mirror_num = mirror_num;
			}

			l = btrfsic_block_link_lookup_or_add(state,
							     &next_block_ctx,
							     next_block, block,
							     generation);
			btrfsic_release_block_ctx(&next_block_ctx);
			if (NULL == l)
				return -1;
		}

		next_bytenr += chunk_len;
		num_bytes -= chunk_len;
	}

	return 0;
}

static int btrfsic_map_block(struct btrfsic_state *state, u64 bytenr, u32 len,
			     struct btrfsic_block_data_ctx *block_ctx_out,
			     int mirror_num)
{
	int ret;
	u64 length;
	struct btrfs_bio *multi = NULL;
	struct btrfs_device *device;

	length = len;
1563
	ret = btrfs_map_block(state->root->fs_info, READ,
1564 1565
			      bytenr, &length, &multi, mirror_num);

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
	if (ret) {
		block_ctx_out->start = 0;
		block_ctx_out->dev_bytenr = 0;
		block_ctx_out->len = 0;
		block_ctx_out->dev = NULL;
		block_ctx_out->datav = NULL;
		block_ctx_out->pagev = NULL;
		block_ctx_out->mem_to_free = NULL;

		return ret;
	}

1578 1579 1580 1581 1582
	device = multi->stripes[0].dev;
	block_ctx_out->dev = btrfsic_dev_state_lookup(device->bdev);
	block_ctx_out->dev_bytenr = multi->stripes[0].physical;
	block_ctx_out->start = bytenr;
	block_ctx_out->len = len;
1583 1584 1585
	block_ctx_out->datav = NULL;
	block_ctx_out->pagev = NULL;
	block_ctx_out->mem_to_free = NULL;
1586

1587
	kfree(multi);
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
	if (NULL == block_ctx_out->dev) {
		ret = -ENXIO;
		printk(KERN_INFO "btrfsic: error, cannot lookup dev (#1)!\n");
	}

	return ret;
}

static int btrfsic_map_superblock(struct btrfsic_state *state, u64 bytenr,
				  u32 len, struct block_device *bdev,
				  struct btrfsic_block_data_ctx *block_ctx_out)
{
	block_ctx_out->dev = btrfsic_dev_state_lookup(bdev);
	block_ctx_out->dev_bytenr = bytenr;
	block_ctx_out->start = bytenr;
	block_ctx_out->len = len;
1604 1605 1606
	block_ctx_out->datav = NULL;
	block_ctx_out->pagev = NULL;
	block_ctx_out->mem_to_free = NULL;
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
	if (NULL != block_ctx_out->dev) {
		return 0;
	} else {
		printk(KERN_INFO "btrfsic: error, cannot lookup dev (#2)!\n");
		return -ENXIO;
	}
}

static void btrfsic_release_block_ctx(struct btrfsic_block_data_ctx *block_ctx)
{
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
	if (block_ctx->mem_to_free) {
		unsigned int num_pages;

		BUG_ON(!block_ctx->datav);
		BUG_ON(!block_ctx->pagev);
		num_pages = (block_ctx->len + (u64)PAGE_CACHE_SIZE - 1) >>
			    PAGE_CACHE_SHIFT;
		while (num_pages > 0) {
			num_pages--;
			if (block_ctx->datav[num_pages]) {
				kunmap(block_ctx->pagev[num_pages]);
				block_ctx->datav[num_pages] = NULL;
			}
			if (block_ctx->pagev[num_pages]) {
				__free_page(block_ctx->pagev[num_pages]);
				block_ctx->pagev[num_pages] = NULL;
			}
		}

		kfree(block_ctx->mem_to_free);
		block_ctx->mem_to_free = NULL;
		block_ctx->pagev = NULL;
		block_ctx->datav = NULL;
1640 1641 1642 1643 1644 1645
	}
}

static int btrfsic_read_block(struct btrfsic_state *state,
			      struct btrfsic_block_data_ctx *block_ctx)
{
1646 1647 1648 1649 1650 1651 1652 1653 1654
	unsigned int num_pages;
	unsigned int i;
	u64 dev_bytenr;
	int ret;

	BUG_ON(block_ctx->datav);
	BUG_ON(block_ctx->pagev);
	BUG_ON(block_ctx->mem_to_free);
	if (block_ctx->dev_bytenr & ((u64)PAGE_CACHE_SIZE - 1)) {
1655 1656
		printk(KERN_INFO
		       "btrfsic: read_block() with unaligned bytenr %llu\n",
1657
		       block_ctx->dev_bytenr);
1658 1659
		return -1;
	}
1660 1661 1662 1663 1664 1665 1666

	num_pages = (block_ctx->len + (u64)PAGE_CACHE_SIZE - 1) >>
		    PAGE_CACHE_SHIFT;
	block_ctx->mem_to_free = kzalloc((sizeof(*block_ctx->datav) +
					  sizeof(*block_ctx->pagev)) *
					 num_pages, GFP_NOFS);
	if (!block_ctx->mem_to_free)
1667
		return -1;
1668 1669 1670 1671 1672 1673
	block_ctx->datav = block_ctx->mem_to_free;
	block_ctx->pagev = (struct page **)(block_ctx->datav + num_pages);
	for (i = 0; i < num_pages; i++) {
		block_ctx->pagev[i] = alloc_page(GFP_NOFS);
		if (!block_ctx->pagev[i])
			return -1;
1674 1675
	}

1676 1677 1678 1679 1680 1681
	dev_bytenr = block_ctx->dev_bytenr;
	for (i = 0; i < num_pages;) {
		struct bio *bio;
		unsigned int j;
		DECLARE_COMPLETION_ONSTACK(complete);

1682
		bio = btrfs_io_bio_alloc(GFP_NOFS, num_pages - i);
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
		if (!bio) {
			printk(KERN_INFO
			       "btrfsic: bio_alloc() for %u pages failed!\n",
			       num_pages - i);
			return -1;
		}
		bio->bi_bdev = block_ctx->dev->bdev;
		bio->bi_sector = dev_bytenr >> 9;
		bio->bi_end_io = btrfsic_complete_bio_end_io;
		bio->bi_private = &complete;

		for (j = i; j < num_pages; j++) {
			ret = bio_add_page(bio, block_ctx->pagev[j],
					   PAGE_CACHE_SIZE, 0);
			if (PAGE_CACHE_SIZE != ret)
				break;
		}
		if (j == i) {
			printk(KERN_INFO
			       "btrfsic: error, failed to add a single page!\n");
			return -1;
		}
		submit_bio(READ, bio);

		/* this will also unplug the queue */
		wait_for_completion(&complete);

		if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) {
			printk(KERN_INFO
			       "btrfsic: read error at logical %llu dev %s!\n",
			       block_ctx->start, block_ctx->dev->name);
			bio_put(bio);
			return -1;
		}
		bio_put(bio);
		dev_bytenr += (j - i) * PAGE_CACHE_SIZE;
		i = j;
	}
	for (i = 0; i < num_pages; i++) {
		block_ctx->datav[i] = kmap(block_ctx->pagev[i]);
		if (!block_ctx->datav[i]) {
			printk(KERN_INFO "btrfsic: kmap() failed (dev %s)!\n",
			       block_ctx->dev->name);
			return -1;
		}
	}
1729 1730 1731 1732

	return block_ctx->len;
}

1733 1734 1735 1736 1737
static void btrfsic_complete_bio_end_io(struct bio *bio, int err)
{
	complete((struct completion *)bio->bi_private);
}

1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
static void btrfsic_dump_database(struct btrfsic_state *state)
{
	struct list_head *elem_all;

	BUG_ON(NULL == state);

	printk(KERN_INFO "all_blocks_list:\n");
	list_for_each(elem_all, &state->all_blocks_list) {
		const struct btrfsic_block *const b_all =
		    list_entry(elem_all, struct btrfsic_block,
			       all_blocks_node);
		struct list_head *elem_ref_to;
		struct list_head *elem_ref_from;

		printk(KERN_INFO "%c-block @%llu (%s/%llu/%d)\n",
		       btrfsic_get_block_type(state, b_all),
1754 1755
		       b_all->logical_bytenr, b_all->dev_state->name,
		       b_all->dev_bytenr, b_all->mirror_num);
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

		list_for_each(elem_ref_to, &b_all->ref_to_list) {
			const struct btrfsic_block_link *const l =
			    list_entry(elem_ref_to,
				       struct btrfsic_block_link,
				       node_ref_to);

			printk(KERN_INFO " %c @%llu (%s/%llu/%d)"
			       " refers %u* to"
			       " %c @%llu (%s/%llu/%d)\n",
			       btrfsic_get_block_type(state, b_all),
1767 1768
			       b_all->logical_bytenr, b_all->dev_state->name,
			       b_all->dev_bytenr, b_all->mirror_num,
1769 1770 1771 1772
			       l->ref_cnt,
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
1773
			       l->block_ref_to->dev_bytenr,
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
			       l->block_ref_to->mirror_num);
		}

		list_for_each(elem_ref_from, &b_all->ref_from_list) {
			const struct btrfsic_block_link *const l =
			    list_entry(elem_ref_from,
				       struct btrfsic_block_link,
				       node_ref_from);

			printk(KERN_INFO " %c @%llu (%s/%llu/%d)"
			       " is ref %u* from"
			       " %c @%llu (%s/%llu/%d)\n",
			       btrfsic_get_block_type(state, b_all),
1787 1788
			       b_all->logical_bytenr, b_all->dev_state->name,
			       b_all->dev_bytenr, b_all->mirror_num,
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
			       l->ref_cnt,
			       btrfsic_get_block_type(state, l->block_ref_from),
			       l->block_ref_from->logical_bytenr,
			       l->block_ref_from->dev_state->name,
			       l->block_ref_from->dev_bytenr,
			       l->block_ref_from->mirror_num);
		}

		printk(KERN_INFO "\n");
	}
}

/*
 * Test whether the disk block contains a tree block (leaf or node)
 * (note that this test fails for the super block)
 */
static int btrfsic_test_for_metadata(struct btrfsic_state *state,
1806
				     char **datav, unsigned int num_pages)
1807 1808 1809 1810
{
	struct btrfs_header *h;
	u8 csum[BTRFS_CSUM_SIZE];
	u32 crc = ~(u32)0;
1811
	unsigned int i;
1812

1813 1814 1815 1816
	if (num_pages * PAGE_CACHE_SIZE < state->metablock_size)
		return 1; /* not metadata */
	num_pages = state->metablock_size >> PAGE_CACHE_SHIFT;
	h = (struct btrfs_header *)datav[0];
1817 1818

	if (memcmp(h->fsid, state->root->fs_info->fsid, BTRFS_UUID_SIZE))
1819
		return 1;
1820

1821 1822 1823 1824 1825 1826 1827
	for (i = 0; i < num_pages; i++) {
		u8 *data = i ? datav[i] : (datav[i] + BTRFS_CSUM_SIZE);
		size_t sublen = i ? PAGE_CACHE_SIZE :
				    (PAGE_CACHE_SIZE - BTRFS_CSUM_SIZE);

		crc = crc32c(crc, data, sublen);
	}
1828 1829
	btrfs_csum_final(crc, csum);
	if (memcmp(csum, h->csum, state->csum_size))
1830
		return 1;
1831

1832
	return 0; /* is metadata */
1833 1834 1835
}

static void btrfsic_process_written_block(struct btrfsic_dev_state *dev_state,
1836 1837 1838
					  u64 dev_bytenr, char **mapped_datav,
					  unsigned int num_pages,
					  struct bio *bio, int *bio_is_patched,
1839 1840 1841 1842 1843 1844 1845 1846 1847
					  struct buffer_head *bh,
					  int submit_bio_bh_rw)
{
	int is_metadata;
	struct btrfsic_block *block;
	struct btrfsic_block_data_ctx block_ctx;
	int ret;
	struct btrfsic_state *state = dev_state->state;
	struct block_device *bdev = dev_state->bdev;
1848
	unsigned int processed_len;
1849 1850 1851 1852

	if (NULL != bio_is_patched)
		*bio_is_patched = 0;

1853 1854 1855 1856 1857 1858 1859 1860
again:
	if (num_pages == 0)
		return;

	processed_len = 0;
	is_metadata = (0 == btrfsic_test_for_metadata(state, mapped_datav,
						      num_pages));

1861 1862 1863
	block = btrfsic_block_hashtable_lookup(bdev, dev_bytenr,
					       &state->block_hashtable);
	if (NULL != block) {
1864
		u64 bytenr = 0;
1865 1866 1867 1868
		struct list_head *elem_ref_to;
		struct list_head *tmp_ref_to;

		if (block->is_superblock) {
1869 1870
			bytenr = btrfs_super_bytenr((struct btrfs_super_block *)
						    mapped_datav[0]);
1871 1872 1873 1874 1875 1876
			if (num_pages * PAGE_CACHE_SIZE <
			    BTRFS_SUPER_INFO_SIZE) {
				printk(KERN_INFO
				       "btrfsic: cannot work with too short bios!\n");
				return;
			}
1877
			is_metadata = 1;
1878 1879
			BUG_ON(BTRFS_SUPER_INFO_SIZE & (PAGE_CACHE_SIZE - 1));
			processed_len = BTRFS_SUPER_INFO_SIZE;
1880 1881 1882 1883 1884 1885 1886 1887 1888
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_TREE_BEFORE_SB_WRITE) {
				printk(KERN_INFO
				       "[before new superblock is written]:\n");
				btrfsic_dump_tree_sub(state, block, 0);
			}
		}
		if (is_metadata) {
			if (!block->is_superblock) {
1889 1890 1891 1892 1893 1894 1895
				if (num_pages * PAGE_CACHE_SIZE <
				    state->metablock_size) {
					printk(KERN_INFO
					       "btrfsic: cannot work with too short bios!\n");
					return;
				}
				processed_len = state->metablock_size;
1896 1897 1898
				bytenr = btrfs_stack_header_bytenr(
						(struct btrfs_header *)
						mapped_datav[0]);
1899 1900
				btrfsic_cmp_log_and_dev_bytenr(state, bytenr,
							       dev_state,
1901
							       dev_bytenr);
1902 1903 1904 1905 1906 1907 1908
			}
			if (block->logical_bytenr != bytenr) {
				printk(KERN_INFO
				       "Written block @%llu (%s/%llu/%d)"
				       " found in hash table, %c,"
				       " bytenr mismatch"
				       " (!= stored %llu).\n",
1909
				       bytenr, dev_state->name, dev_bytenr,
1910 1911 1912 1913 1914 1915 1916 1917 1918
				       block->mirror_num,
				       btrfsic_get_block_type(state, block),
				       block->logical_bytenr);
				block->logical_bytenr = bytenr;
			} else if (state->print_mask &
				   BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO
				       "Written block @%llu (%s/%llu/%d)"
				       " found in hash table, %c.\n",
1919
				       bytenr, dev_state->name, dev_bytenr,
1920 1921 1922
				       block->mirror_num,
				       btrfsic_get_block_type(state, block));
		} else {
1923 1924 1925 1926 1927 1928 1929
			if (num_pages * PAGE_CACHE_SIZE <
			    state->datablock_size) {
				printk(KERN_INFO
				       "btrfsic: cannot work with too short bios!\n");
				return;
			}
			processed_len = state->datablock_size;
1930 1931 1932 1933 1934
			bytenr = block->logical_bytenr;
			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO
				       "Written block @%llu (%s/%llu/%d)"
				       " found in hash table, %c.\n",
1935
				       bytenr, dev_state->name, dev_bytenr,
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
				       block->mirror_num,
				       btrfsic_get_block_type(state, block));
		}

		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "ref_to_list: %cE, ref_from_list: %cE\n",
			       list_empty(&block->ref_to_list) ? ' ' : '!',
			       list_empty(&block->ref_from_list) ? ' ' : '!');
		if (btrfsic_is_block_ref_by_superblock(state, block, 0)) {
			printk(KERN_INFO "btrfs: attempt to overwrite %c-block"
			       " @%llu (%s/%llu/%d), old(gen=%llu,"
			       " objectid=%llu, type=%d, offset=%llu),"
			       " new(gen=%llu),"
			       " which is referenced by most recent superblock"
			       " (superblockgen=%llu)!\n",
1952 1953 1954
			       btrfsic_get_block_type(state, block), bytenr,
			       dev_state->name, dev_bytenr, block->mirror_num,
			       block->generation,
1955
			       btrfs_disk_key_objectid(&block->disk_key),
1956
			       block->disk_key.type,
1957 1958 1959
			       btrfs_disk_key_offset(&block->disk_key),
			       btrfs_stack_header_generation(
				       (struct btrfs_header *) mapped_datav[0]),
1960 1961 1962 1963 1964 1965 1966 1967
			       state->max_superblock_generation);
			btrfsic_dump_tree(state);
		}

		if (!block->is_iodone && !block->never_written) {
			printk(KERN_INFO "btrfs: attempt to overwrite %c-block"
			       " @%llu (%s/%llu/%d), oldgen=%llu, newgen=%llu,"
			       " which is not yet iodone!\n",
1968 1969 1970
			       btrfsic_get_block_type(state, block), bytenr,
			       dev_state->name, dev_bytenr, block->mirror_num,
			       block->generation,
1971 1972 1973
			       btrfs_stack_header_generation(
				       (struct btrfs_header *)
				       mapped_datav[0]));
1974 1975
			/* it would not be safe to go on */
			btrfsic_dump_tree(state);
1976
			goto continue_loop;
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
		}

		/*
		 * Clear all references of this block. Do not free
		 * the block itself even if is not referenced anymore
		 * because it still carries valueable information
		 * like whether it was ever written and IO completed.
		 */
		list_for_each_safe(elem_ref_to, tmp_ref_to,
				   &block->ref_to_list) {
			struct btrfsic_block_link *const l =
			    list_entry(elem_ref_to,
				       struct btrfsic_block_link,
				       node_ref_to);

			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				btrfsic_print_rem_link(state, l);
			l->ref_cnt--;
			if (0 == l->ref_cnt) {
				list_del(&l->node_ref_to);
				list_del(&l->node_ref_from);
				btrfsic_block_link_hashtable_remove(l);
				btrfsic_block_link_free(l);
			}
		}

		if (block->is_superblock)
2004 2005
			ret = btrfsic_map_superblock(state, bytenr,
						     processed_len,
2006 2007
						     bdev, &block_ctx);
		else
2008
			ret = btrfsic_map_block(state, bytenr, processed_len,
2009 2010 2011 2012
						&block_ctx, 0);
		if (ret) {
			printk(KERN_INFO
			       "btrfsic: btrfsic_map_block(root @%llu)"
2013
			       " failed!\n", bytenr);
2014
			goto continue_loop;
2015
		}
2016
		block_ctx.datav = mapped_datav;
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
		/* the following is required in case of writes to mirrors,
		 * use the same that was used for the lookup */
		block_ctx.dev = dev_state;
		block_ctx.dev_bytenr = dev_bytenr;

		if (is_metadata || state->include_extent_data) {
			block->never_written = 0;
			block->iodone_w_error = 0;
			if (NULL != bio) {
				block->is_iodone = 0;
				BUG_ON(NULL == bio_is_patched);
				if (!*bio_is_patched) {
					block->orig_bio_bh_private =
					    bio->bi_private;
					block->orig_bio_bh_end_io.bio =
					    bio->bi_end_io;
					block->next_in_same_bio = NULL;
					bio->bi_private = block;
					bio->bi_end_io = btrfsic_bio_end_io;
					*bio_is_patched = 1;
				} else {
					struct btrfsic_block *chained_block =
					    (struct btrfsic_block *)
					    bio->bi_private;

					BUG_ON(NULL == chained_block);
					block->orig_bio_bh_private =
					    chained_block->orig_bio_bh_private;
					block->orig_bio_bh_end_io.bio =
					    chained_block->orig_bio_bh_end_io.
					    bio;
					block->next_in_same_bio = chained_block;
					bio->bi_private = block;
				}
			} else if (NULL != bh) {
				block->is_iodone = 0;
				block->orig_bio_bh_private = bh->b_private;
				block->orig_bio_bh_end_io.bh = bh->b_end_io;
				block->next_in_same_bio = NULL;
				bh->b_private = block;
				bh->b_end_io = btrfsic_bh_end_io;
			} else {
				block->is_iodone = 1;
				block->orig_bio_bh_private = NULL;
				block->orig_bio_bh_end_io.bio = NULL;
				block->next_in_same_bio = NULL;
			}
		}

		block->flush_gen = dev_state->last_flush_gen + 1;
		block->submit_bio_bh_rw = submit_bio_bh_rw;
		if (is_metadata) {
			block->logical_bytenr = bytenr;
			block->is_metadata = 1;
			if (block->is_superblock) {
2072 2073
				BUG_ON(PAGE_CACHE_SIZE !=
				       BTRFS_SUPER_INFO_SIZE);
2074 2075 2076 2077
				ret = btrfsic_process_written_superblock(
						state,
						block,
						(struct btrfs_super_block *)
2078
						mapped_datav[0]);
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
				if (state->print_mask &
				    BTRFSIC_PRINT_MASK_TREE_AFTER_SB_WRITE) {
					printk(KERN_INFO
					"[after new superblock is written]:\n");
					btrfsic_dump_tree_sub(state, block, 0);
				}
			} else {
				block->mirror_num = 0;	/* unknown */
				ret = btrfsic_process_metablock(
						state,
						block,
						&block_ctx,
						0, 0);
			}
			if (ret)
				printk(KERN_INFO
				       "btrfsic: btrfsic_process_metablock"
				       "(root @%llu) failed!\n",
2097
				       dev_bytenr);
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
		} else {
			block->is_metadata = 0;
			block->mirror_num = 0;	/* unknown */
			block->generation = BTRFSIC_GENERATION_UNKNOWN;
			if (!state->include_extent_data
			    && list_empty(&block->ref_from_list)) {
				/*
				 * disk block is overwritten with extent
				 * data (not meta data) and we are configured
				 * to not include extent data: take the
				 * chance and free the block's memory
				 */
				btrfsic_block_hashtable_remove(block);
				list_del(&block->all_blocks_node);
				btrfsic_block_free(block);
			}
		}
		btrfsic_release_block_ctx(&block_ctx);
	} else {
		/* block has not been found in hash table */
		u64 bytenr;

		if (!is_metadata) {
2121
			processed_len = state->datablock_size;
2122 2123 2124
			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO "Written block (%s/%llu/?)"
				       " !found in hash table, D.\n",
2125
				       dev_state->name, dev_bytenr);
2126 2127 2128 2129
			if (!state->include_extent_data) {
				/* ignore that written D block */
				goto continue_loop;
			}
2130 2131 2132 2133 2134

			/* this is getting ugly for the
			 * include_extent_data case... */
			bytenr = 0;	/* unknown */
			block_ctx.start = bytenr;
2135 2136 2137
			block_ctx.len = processed_len;
			block_ctx.mem_to_free = NULL;
			block_ctx.pagev = NULL;
2138
		} else {
2139
			processed_len = state->metablock_size;
2140 2141 2142
			bytenr = btrfs_stack_header_bytenr(
					(struct btrfs_header *)
					mapped_datav[0]);
2143
			btrfsic_cmp_log_and_dev_bytenr(state, bytenr, dev_state,
2144
						       dev_bytenr);
2145 2146 2147 2148
			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO
				       "Written block @%llu (%s/%llu/?)"
				       " !found in hash table, M.\n",
2149
				       bytenr, dev_state->name, dev_bytenr);
2150

2151 2152
			ret = btrfsic_map_block(state, bytenr, processed_len,
						&block_ctx, 0);
2153 2154 2155 2156
			if (ret) {
				printk(KERN_INFO
				       "btrfsic: btrfsic_map_block(root @%llu)"
				       " failed!\n",
2157
				       dev_bytenr);
2158
				goto continue_loop;
2159 2160
			}
		}
2161
		block_ctx.datav = mapped_datav;
2162 2163 2164 2165 2166 2167 2168 2169 2170
		/* the following is required in case of writes to mirrors,
		 * use the same that was used for the lookup */
		block_ctx.dev = dev_state;
		block_ctx.dev_bytenr = dev_bytenr;

		block = btrfsic_block_alloc();
		if (NULL == block) {
			printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
			btrfsic_release_block_ctx(&block_ctx);
2171
			goto continue_loop;
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
		}
		block->dev_state = dev_state;
		block->dev_bytenr = dev_bytenr;
		block->logical_bytenr = bytenr;
		block->is_metadata = is_metadata;
		block->never_written = 0;
		block->iodone_w_error = 0;
		block->mirror_num = 0;	/* unknown */
		block->flush_gen = dev_state->last_flush_gen + 1;
		block->submit_bio_bh_rw = submit_bio_bh_rw;
		if (NULL != bio) {
			block->is_iodone = 0;
			BUG_ON(NULL == bio_is_patched);
			if (!*bio_is_patched) {
				block->orig_bio_bh_private = bio->bi_private;
				block->orig_bio_bh_end_io.bio = bio->bi_end_io;
				block->next_in_same_bio = NULL;
				bio->bi_private = block;
				bio->bi_end_io = btrfsic_bio_end_io;
				*bio_is_patched = 1;
			} else {
				struct btrfsic_block *chained_block =
				    (struct btrfsic_block *)
				    bio->bi_private;

				BUG_ON(NULL == chained_block);
				block->orig_bio_bh_private =
				    chained_block->orig_bio_bh_private;
				block->orig_bio_bh_end_io.bio =
				    chained_block->orig_bio_bh_end_io.bio;
				block->next_in_same_bio = chained_block;
				bio->bi_private = block;
			}
		} else if (NULL != bh) {
			block->is_iodone = 0;
			block->orig_bio_bh_private = bh->b_private;
			block->orig_bio_bh_end_io.bh = bh->b_end_io;
			block->next_in_same_bio = NULL;
			bh->b_private = block;
			bh->b_end_io = btrfsic_bh_end_io;
		} else {
			block->is_iodone = 1;
			block->orig_bio_bh_private = NULL;
			block->orig_bio_bh_end_io.bio = NULL;
			block->next_in_same_bio = NULL;
		}
		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "New written %c-block @%llu (%s/%llu/%d)\n",
			       is_metadata ? 'M' : 'D',
2222 2223
			       block->logical_bytenr, block->dev_state->name,
			       block->dev_bytenr, block->mirror_num);
2224 2225 2226 2227 2228
		list_add(&block->all_blocks_node, &state->all_blocks_list);
		btrfsic_block_hashtable_add(block, &state->block_hashtable);

		if (is_metadata) {
			ret = btrfsic_process_metablock(state, block,
2229
							&block_ctx, 0, 0);
2230 2231 2232 2233
			if (ret)
				printk(KERN_INFO
				       "btrfsic: process_metablock(root @%llu)"
				       " failed!\n",
2234
				       dev_bytenr);
2235 2236 2237
		}
		btrfsic_release_block_ctx(&block_ctx);
	}
2238 2239 2240 2241 2242 2243 2244

continue_loop:
	BUG_ON(!processed_len);
	dev_bytenr += processed_len;
	mapped_datav += processed_len >> PAGE_CACHE_SHIFT;
	num_pages -= processed_len >> PAGE_CACHE_SHIFT;
	goto again;
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
}

static void btrfsic_bio_end_io(struct bio *bp, int bio_error_status)
{
	struct btrfsic_block *block = (struct btrfsic_block *)bp->bi_private;
	int iodone_w_error;

	/* mutex is not held! This is not save if IO is not yet completed
	 * on umount */
	iodone_w_error = 0;
	if (bio_error_status)
		iodone_w_error = 1;

	BUG_ON(NULL == block);
	bp->bi_private = block->orig_bio_bh_private;
	bp->bi_end_io = block->orig_bio_bh_end_io.bio;

	do {
		struct btrfsic_block *next_block;
		struct btrfsic_dev_state *const dev_state = block->dev_state;

		if ((dev_state->state->print_mask &
		     BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
			printk(KERN_INFO
			       "bio_end_io(err=%d) for %c @%llu (%s/%llu/%d)\n",
			       bio_error_status,
			       btrfsic_get_block_type(dev_state->state, block),
2272 2273
			       block->logical_bytenr, dev_state->name,
			       block->dev_bytenr, block->mirror_num);
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
		next_block = block->next_in_same_bio;
		block->iodone_w_error = iodone_w_error;
		if (block->submit_bio_bh_rw & REQ_FLUSH) {
			dev_state->last_flush_gen++;
			if ((dev_state->state->print_mask &
			     BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
				printk(KERN_INFO
				       "bio_end_io() new %s flush_gen=%llu\n",
				       dev_state->name,
				       dev_state->last_flush_gen);
		}
		if (block->submit_bio_bh_rw & REQ_FUA)
			block->flush_gen = 0; /* FUA completed means block is
					       * on disk */
		block->is_iodone = 1; /* for FLUSH, this releases the block */
		block = next_block;
	} while (NULL != block);

	bp->bi_end_io(bp, bio_error_status);
}

static void btrfsic_bh_end_io(struct buffer_head *bh, int uptodate)
{
	struct btrfsic_block *block = (struct btrfsic_block *)bh->b_private;
	int iodone_w_error = !uptodate;
	struct btrfsic_dev_state *dev_state;

	BUG_ON(NULL == block);
	dev_state = block->dev_state;
	if ((dev_state->state->print_mask & BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
		printk(KERN_INFO
		       "bh_end_io(error=%d) for %c @%llu (%s/%llu/%d)\n",
		       iodone_w_error,
		       btrfsic_get_block_type(dev_state->state, block),
2308 2309
		       block->logical_bytenr, block->dev_state->name,
		       block->dev_bytenr, block->mirror_num);
2310 2311 2312 2313 2314 2315 2316 2317

	block->iodone_w_error = iodone_w_error;
	if (block->submit_bio_bh_rw & REQ_FLUSH) {
		dev_state->last_flush_gen++;
		if ((dev_state->state->print_mask &
		     BTRFSIC_PRINT_MASK_END_IO_BIO_BH))
			printk(KERN_INFO
			       "bh_end_io() new %s flush_gen=%llu\n",
2318
			       dev_state->name, dev_state->last_flush_gen);
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
	}
	if (block->submit_bio_bh_rw & REQ_FUA)
		block->flush_gen = 0; /* FUA completed means block is on disk */

	bh->b_private = block->orig_bio_bh_private;
	bh->b_end_io = block->orig_bio_bh_end_io.bh;
	block->is_iodone = 1; /* for FLUSH, this releases the block */
	bh->b_end_io(bh, uptodate);
}

static int btrfsic_process_written_superblock(
		struct btrfsic_state *state,
		struct btrfsic_block *const superblock,
		struct btrfs_super_block *const super_hdr)
{
	int pass;

	superblock->generation = btrfs_super_generation(super_hdr);
	if (!(superblock->generation > state->max_superblock_generation ||
	      0 == state->max_superblock_generation)) {
		if (state->print_mask & BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE)
			printk(KERN_INFO
			       "btrfsic: superblock @%llu (%s/%llu/%d)"
			       " with old gen %llu <= %llu\n",
2343
			       superblock->logical_bytenr,
2344
			       superblock->dev_state->name,
2345
			       superblock->dev_bytenr, superblock->mirror_num,
2346 2347 2348 2349 2350 2351 2352
			       btrfs_super_generation(super_hdr),
			       state->max_superblock_generation);
	} else {
		if (state->print_mask & BTRFSIC_PRINT_MASK_SUPERBLOCK_WRITE)
			printk(KERN_INFO
			       "btrfsic: got new superblock @%llu (%s/%llu/%d)"
			       " with new gen %llu > %llu\n",
2353
			       superblock->logical_bytenr,
2354
			       superblock->dev_state->name,
2355
			       superblock->dev_bytenr, superblock->mirror_num,
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
			       btrfs_super_generation(super_hdr),
			       state->max_superblock_generation);

		state->max_superblock_generation =
		    btrfs_super_generation(super_hdr);
		state->latest_superblock = superblock;
	}

	for (pass = 0; pass < 3; pass++) {
		int ret;
		u64 next_bytenr;
		struct btrfsic_block *next_block;
		struct btrfsic_block_data_ctx tmp_next_block_ctx;
		struct btrfsic_block_link *l;
		int num_copies;
		int mirror_num;
		const char *additional_string = NULL;
2373
		struct btrfs_disk_key tmp_disk_key = {0};
2374

2375 2376 2377
		btrfs_set_disk_key_objectid(&tmp_disk_key,
					    BTRFS_ROOT_ITEM_KEY);
		btrfs_set_disk_key_objectid(&tmp_disk_key, 0);
2378 2379 2380

		switch (pass) {
		case 0:
2381 2382
			btrfs_set_disk_key_objectid(&tmp_disk_key,
						    BTRFS_ROOT_TREE_OBJECTID);
2383 2384 2385 2386
			additional_string = "root ";
			next_bytenr = btrfs_super_root(super_hdr);
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
2387
				printk(KERN_INFO "root@%llu\n", next_bytenr);
2388 2389
			break;
		case 1:
2390 2391
			btrfs_set_disk_key_objectid(&tmp_disk_key,
						    BTRFS_CHUNK_TREE_OBJECTID);
2392 2393 2394 2395
			additional_string = "chunk ";
			next_bytenr = btrfs_super_chunk_root(super_hdr);
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
2396
				printk(KERN_INFO "chunk@%llu\n", next_bytenr);
2397 2398
			break;
		case 2:
2399 2400
			btrfs_set_disk_key_objectid(&tmp_disk_key,
						    BTRFS_TREE_LOG_OBJECTID);
2401 2402 2403 2404 2405 2406
			additional_string = "log ";
			next_bytenr = btrfs_super_log_root(super_hdr);
			if (0 == next_bytenr)
				continue;
			if (state->print_mask &
			    BTRFSIC_PRINT_MASK_ROOT_CHUNK_LOG_TREE_LOCATION)
2407
				printk(KERN_INFO "log@%llu\n", next_bytenr);
2408 2409 2410 2411
			break;
		}

		num_copies =
2412
		    btrfs_num_copies(state->root->fs_info,
2413
				     next_bytenr, BTRFS_SUPER_INFO_SIZE);
2414 2415
		if (state->print_mask & BTRFSIC_PRINT_MASK_NUM_COPIES)
			printk(KERN_INFO "num_copies(log_bytenr=%llu) = %d\n",
2416
			       next_bytenr, num_copies);
2417 2418 2419 2420 2421 2422 2423
		for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
			int was_created;

			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				printk(KERN_INFO
				       "btrfsic_process_written_superblock("
				       "mirror_num=%d)\n", mirror_num);
2424 2425
			ret = btrfsic_map_block(state, next_bytenr,
						BTRFS_SUPER_INFO_SIZE,
2426 2427 2428 2429 2430 2431
						&tmp_next_block_ctx,
						mirror_num);
			if (ret) {
				printk(KERN_INFO
				       "btrfsic: btrfsic_map_block(@%llu,"
				       " mirror=%d) failed!\n",
2432
				       next_bytenr, mirror_num);
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
				return -1;
			}

			next_block = btrfsic_block_lookup_or_add(
					state,
					&tmp_next_block_ctx,
					additional_string,
					1, 0, 1,
					mirror_num,
					&was_created);
			if (NULL == next_block) {
				printk(KERN_INFO
				       "btrfsic: error, kmalloc failed!\n");
				btrfsic_release_block_ctx(&tmp_next_block_ctx);
				return -1;
			}

			next_block->disk_key = tmp_disk_key;
			if (was_created)
				next_block->generation =
				    BTRFSIC_GENERATION_UNKNOWN;
			l = btrfsic_block_link_lookup_or_add(
					state,
					&tmp_next_block_ctx,
					next_block,
					superblock,
					BTRFSIC_GENERATION_UNKNOWN);
			btrfsic_release_block_ctx(&tmp_next_block_ctx);
			if (NULL == l)
				return -1;
		}
	}

	if (-1 == btrfsic_check_all_ref_blocks(state, superblock, 0)) {
		WARN_ON(1);
		btrfsic_dump_tree(state);
	}

	return 0;
}

static int btrfsic_check_all_ref_blocks(struct btrfsic_state *state,
					struct btrfsic_block *const block,
					int recursion_level)
{
	struct list_head *elem_ref_to;
	int ret = 0;

	if (recursion_level >= 3 + BTRFS_MAX_LEVEL) {
		/*
		 * Note that this situation can happen and does not
		 * indicate an error in regular cases. It happens
		 * when disk blocks are freed and later reused.
		 * The check-integrity module is not aware of any
		 * block free operations, it just recognizes block
		 * write operations. Therefore it keeps the linkage
		 * information for a block until a block is
		 * rewritten. This can temporarily cause incorrect
		 * and even circular linkage informations. This
		 * causes no harm unless such blocks are referenced
		 * by the most recent super block.
		 */
		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "btrfsic: abort cyclic linkage (case 1).\n");

		return ret;
	}

	/*
	 * This algorithm is recursive because the amount of used stack
	 * space is very small and the max recursion depth is limited.
	 */
	list_for_each(elem_ref_to, &block->ref_to_list) {
		const struct btrfsic_block_link *const l =
		    list_entry(elem_ref_to, struct btrfsic_block_link,
			       node_ref_to);

		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "rl=%d, %c @%llu (%s/%llu/%d)"
			       " %u* refers to %c @%llu (%s/%llu/%d)\n",
			       recursion_level,
			       btrfsic_get_block_type(state, block),
2517 2518
			       block->logical_bytenr, block->dev_state->name,
			       block->dev_bytenr, block->mirror_num,
2519 2520 2521 2522
			       l->ref_cnt,
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
2523
			       l->block_ref_to->dev_bytenr,
2524 2525 2526 2527 2528 2529 2530 2531
			       l->block_ref_to->mirror_num);
		if (l->block_ref_to->never_written) {
			printk(KERN_INFO "btrfs: attempt to write superblock"
			       " which references block %c @%llu (%s/%llu/%d)"
			       " which is never written!\n",
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
2532
			       l->block_ref_to->dev_bytenr,
2533 2534 2535 2536 2537 2538 2539 2540 2541
			       l->block_ref_to->mirror_num);
			ret = -1;
		} else if (!l->block_ref_to->is_iodone) {
			printk(KERN_INFO "btrfs: attempt to write superblock"
			       " which references block %c @%llu (%s/%llu/%d)"
			       " which is not yet iodone!\n",
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
2542
			       l->block_ref_to->dev_bytenr,
2543 2544
			       l->block_ref_to->mirror_num);
			ret = -1;
2545 2546 2547 2548 2549 2550 2551
		} else if (l->block_ref_to->iodone_w_error) {
			printk(KERN_INFO "btrfs: attempt to write superblock"
			       " which references block %c @%llu (%s/%llu/%d)"
			       " which has write error!\n",
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
2552
			       l->block_ref_to->dev_bytenr,
2553 2554
			       l->block_ref_to->mirror_num);
			ret = -1;
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
		} else if (l->parent_generation !=
			   l->block_ref_to->generation &&
			   BTRFSIC_GENERATION_UNKNOWN !=
			   l->parent_generation &&
			   BTRFSIC_GENERATION_UNKNOWN !=
			   l->block_ref_to->generation) {
			printk(KERN_INFO "btrfs: attempt to write superblock"
			       " which references block %c @%llu (%s/%llu/%d)"
			       " with generation %llu !="
			       " parent generation %llu!\n",
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
2568
			       l->block_ref_to->dev_bytenr,
2569
			       l->block_ref_to->mirror_num,
2570 2571
			       l->block_ref_to->generation,
			       l->parent_generation);
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
			ret = -1;
		} else if (l->block_ref_to->flush_gen >
			   l->block_ref_to->dev_state->last_flush_gen) {
			printk(KERN_INFO "btrfs: attempt to write superblock"
			       " which references block %c @%llu (%s/%llu/%d)"
			       " which is not flushed out of disk's write cache"
			       " (block flush_gen=%llu,"
			       " dev->flush_gen=%llu)!\n",
			       btrfsic_get_block_type(state, l->block_ref_to),
			       l->block_ref_to->logical_bytenr,
			       l->block_ref_to->dev_state->name,
2583 2584
			       l->block_ref_to->dev_bytenr,
			       l->block_ref_to->mirror_num, block->flush_gen,
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
			       l->block_ref_to->dev_state->last_flush_gen);
			ret = -1;
		} else if (-1 == btrfsic_check_all_ref_blocks(state,
							      l->block_ref_to,
							      recursion_level +
							      1)) {
			ret = -1;
		}
	}

	return ret;
}

static int btrfsic_is_block_ref_by_superblock(
		const struct btrfsic_state *state,
		const struct btrfsic_block *block,
		int recursion_level)
{
	struct list_head *elem_ref_from;

	if (recursion_level >= 3 + BTRFS_MAX_LEVEL) {
		/* refer to comment at "abort cyclic linkage (case 1)" */
		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "btrfsic: abort cyclic linkage (case 2).\n");

		return 0;
	}

	/*
	 * This algorithm is recursive because the amount of used stack space
	 * is very small and the max recursion depth is limited.
	 */
	list_for_each(elem_ref_from, &block->ref_from_list) {
		const struct btrfsic_block_link *const l =
		    list_entry(elem_ref_from, struct btrfsic_block_link,
			       node_ref_from);

		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "rl=%d, %c @%llu (%s/%llu/%d)"
			       " is ref %u* from %c @%llu (%s/%llu/%d)\n",
			       recursion_level,
			       btrfsic_get_block_type(state, block),
2629 2630
			       block->logical_bytenr, block->dev_state->name,
			       block->dev_bytenr, block->mirror_num,
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
			       l->ref_cnt,
			       btrfsic_get_block_type(state, l->block_ref_from),
			       l->block_ref_from->logical_bytenr,
			       l->block_ref_from->dev_state->name,
			       l->block_ref_from->dev_bytenr,
			       l->block_ref_from->mirror_num);
		if (l->block_ref_from->is_superblock &&
		    state->latest_superblock->dev_bytenr ==
		    l->block_ref_from->dev_bytenr &&
		    state->latest_superblock->dev_state->bdev ==
		    l->block_ref_from->dev_state->bdev)
			return 1;
		else if (btrfsic_is_block_ref_by_superblock(state,
							    l->block_ref_from,
							    recursion_level +
							    1))
			return 1;
	}

	return 0;
}

static void btrfsic_print_add_link(const struct btrfsic_state *state,
				   const struct btrfsic_block_link *l)
{
	printk(KERN_INFO
	       "Add %u* link from %c @%llu (%s/%llu/%d)"
	       " to %c @%llu (%s/%llu/%d).\n",
	       l->ref_cnt,
	       btrfsic_get_block_type(state, l->block_ref_from),
2661
	       l->block_ref_from->logical_bytenr,
2662
	       l->block_ref_from->dev_state->name,
2663
	       l->block_ref_from->dev_bytenr, l->block_ref_from->mirror_num,
2664
	       btrfsic_get_block_type(state, l->block_ref_to),
2665 2666
	       l->block_ref_to->logical_bytenr,
	       l->block_ref_to->dev_state->name, l->block_ref_to->dev_bytenr,
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
	       l->block_ref_to->mirror_num);
}

static void btrfsic_print_rem_link(const struct btrfsic_state *state,
				   const struct btrfsic_block_link *l)
{
	printk(KERN_INFO
	       "Rem %u* link from %c @%llu (%s/%llu/%d)"
	       " to %c @%llu (%s/%llu/%d).\n",
	       l->ref_cnt,
	       btrfsic_get_block_type(state, l->block_ref_from),
2678
	       l->block_ref_from->logical_bytenr,
2679
	       l->block_ref_from->dev_state->name,
2680
	       l->block_ref_from->dev_bytenr, l->block_ref_from->mirror_num,
2681
	       btrfsic_get_block_type(state, l->block_ref_to),
2682 2683
	       l->block_ref_to->logical_bytenr,
	       l->block_ref_to->dev_state->name, l->block_ref_to->dev_bytenr,
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
	       l->block_ref_to->mirror_num);
}

static char btrfsic_get_block_type(const struct btrfsic_state *state,
				   const struct btrfsic_block *block)
{
	if (block->is_superblock &&
	    state->latest_superblock->dev_bytenr == block->dev_bytenr &&
	    state->latest_superblock->dev_state->bdev == block->dev_state->bdev)
		return 'S';
	else if (block->is_superblock)
		return 's';
	else if (block->is_metadata)
		return 'M';
	else
		return 'D';
}

static void btrfsic_dump_tree(const struct btrfsic_state *state)
{
	btrfsic_dump_tree_sub(state, state->latest_superblock, 0);
}

static void btrfsic_dump_tree_sub(const struct btrfsic_state *state,
				  const struct btrfsic_block *block,
				  int indent_level)
{
	struct list_head *elem_ref_to;
	int indent_add;
	static char buf[80];
	int cursor_position;

	/*
	 * Should better fill an on-stack buffer with a complete line and
	 * dump it at once when it is time to print a newline character.
	 */

	/*
	 * This algorithm is recursive because the amount of used stack space
	 * is very small and the max recursion depth is limited.
	 */
	indent_add = sprintf(buf, "%c-%llu(%s/%llu/%d)",
			     btrfsic_get_block_type(state, block),
2727 2728
			     block->logical_bytenr, block->dev_state->name,
			     block->dev_bytenr, block->mirror_num);
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
	if (indent_level + indent_add > BTRFSIC_TREE_DUMP_MAX_INDENT_LEVEL) {
		printk("[...]\n");
		return;
	}
	printk(buf);
	indent_level += indent_add;
	if (list_empty(&block->ref_to_list)) {
		printk("\n");
		return;
	}
	if (block->mirror_num > 1 &&
	    !(state->print_mask & BTRFSIC_PRINT_MASK_TREE_WITH_ALL_MIRRORS)) {
		printk(" [...]\n");
		return;
	}

	cursor_position = indent_level;
	list_for_each(elem_ref_to, &block->ref_to_list) {
		const struct btrfsic_block_link *const l =
		    list_entry(elem_ref_to, struct btrfsic_block_link,
			       node_ref_to);

		while (cursor_position < indent_level) {
			printk(" ");
			cursor_position++;
		}
		if (l->ref_cnt > 1)
			indent_add = sprintf(buf, " %d*--> ", l->ref_cnt);
		else
			indent_add = sprintf(buf, " --> ");
		if (indent_level + indent_add >
		    BTRFSIC_TREE_DUMP_MAX_INDENT_LEVEL) {
			printk("[...]\n");
			cursor_position = 0;
			continue;
		}

		printk(buf);

		btrfsic_dump_tree_sub(state, l->block_ref_to,
				      indent_level + indent_add);
		cursor_position = 0;
	}
}

static struct btrfsic_block_link *btrfsic_block_link_lookup_or_add(
		struct btrfsic_state *state,
		struct btrfsic_block_data_ctx *next_block_ctx,
		struct btrfsic_block *next_block,
		struct btrfsic_block *from_block,
		u64 parent_generation)
{
	struct btrfsic_block_link *l;

	l = btrfsic_block_link_hashtable_lookup(next_block_ctx->dev->bdev,
						next_block_ctx->dev_bytenr,
						from_block->dev_state->bdev,
						from_block->dev_bytenr,
						&state->block_link_hashtable);
	if (NULL == l) {
		l = btrfsic_block_link_alloc();
		if (NULL == l) {
			printk(KERN_INFO
			       "btrfsic: error, kmalloc" " failed!\n");
			return NULL;
		}

		l->block_ref_to = next_block;
		l->block_ref_from = from_block;
		l->ref_cnt = 1;
		l->parent_generation = parent_generation;

		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			btrfsic_print_add_link(state, l);

		list_add(&l->node_ref_to, &from_block->ref_to_list);
		list_add(&l->node_ref_from, &next_block->ref_from_list);

		btrfsic_block_link_hashtable_add(l,
						 &state->block_link_hashtable);
	} else {
		l->ref_cnt++;
		l->parent_generation = parent_generation;
		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			btrfsic_print_add_link(state, l);
	}

	return l;
}

static struct btrfsic_block *btrfsic_block_lookup_or_add(
		struct btrfsic_state *state,
		struct btrfsic_block_data_ctx *block_ctx,
		const char *additional_string,
		int is_metadata,
		int is_iodone,
		int never_written,
		int mirror_num,
		int *was_created)
{
	struct btrfsic_block *block;

	block = btrfsic_block_hashtable_lookup(block_ctx->dev->bdev,
					       block_ctx->dev_bytenr,
					       &state->block_hashtable);
	if (NULL == block) {
		struct btrfsic_dev_state *dev_state;

		block = btrfsic_block_alloc();
		if (NULL == block) {
			printk(KERN_INFO "btrfsic: error, kmalloc failed!\n");
			return NULL;
		}
		dev_state = btrfsic_dev_state_lookup(block_ctx->dev->bdev);
		if (NULL == dev_state) {
			printk(KERN_INFO
			       "btrfsic: error, lookup dev_state failed!\n");
			btrfsic_block_free(block);
			return NULL;
		}
		block->dev_state = dev_state;
		block->dev_bytenr = block_ctx->dev_bytenr;
		block->logical_bytenr = block_ctx->start;
		block->is_metadata = is_metadata;
		block->is_iodone = is_iodone;
		block->never_written = never_written;
		block->mirror_num = mirror_num;
		if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
			printk(KERN_INFO
			       "New %s%c-block @%llu (%s/%llu/%d)\n",
			       additional_string,
			       btrfsic_get_block_type(state, block),
2861 2862
			       block->logical_bytenr, dev_state->name,
			       block->dev_bytenr, mirror_num);
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
		list_add(&block->all_blocks_node, &state->all_blocks_list);
		btrfsic_block_hashtable_add(block, &state->block_hashtable);
		if (NULL != was_created)
			*was_created = 1;
	} else {
		if (NULL != was_created)
			*was_created = 0;
	}

	return block;
}

static void btrfsic_cmp_log_and_dev_bytenr(struct btrfsic_state *state,
					   u64 bytenr,
					   struct btrfsic_dev_state *dev_state,
2878
					   u64 dev_bytenr)
2879 2880 2881 2882 2883 2884 2885
{
	int num_copies;
	int mirror_num;
	int ret;
	struct btrfsic_block_data_ctx block_ctx;
	int match = 0;

2886
	num_copies = btrfs_num_copies(state->root->fs_info,
2887
				      bytenr, state->metablock_size);
2888 2889

	for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
2890
		ret = btrfsic_map_block(state, bytenr, state->metablock_size,
2891 2892 2893 2894 2895
					&block_ctx, mirror_num);
		if (ret) {
			printk(KERN_INFO "btrfsic:"
			       " btrfsic_map_block(logical @%llu,"
			       " mirror %d) failed!\n",
2896
			       bytenr, mirror_num);
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
			continue;
		}

		if (dev_state->bdev == block_ctx.dev->bdev &&
		    dev_bytenr == block_ctx.dev_bytenr) {
			match++;
			btrfsic_release_block_ctx(&block_ctx);
			break;
		}
		btrfsic_release_block_ctx(&block_ctx);
	}

	if (!match) {
		printk(KERN_INFO "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=%s,"
		       " phys_bytenr=%llu)!\n",
2913
		       bytenr, dev_state->name, dev_bytenr);
2914
		for (mirror_num = 1; mirror_num <= num_copies; mirror_num++) {
2915 2916
			ret = btrfsic_map_block(state, bytenr,
						state->metablock_size,
2917 2918 2919 2920 2921 2922
						&block_ctx, mirror_num);
			if (ret)
				continue;

			printk(KERN_INFO "Read logical bytenr @%llu maps to"
			       " (%s/%llu/%d)\n",
2923 2924
			       bytenr, block_ctx.dev->name,
			       block_ctx.dev_bytenr, mirror_num);
2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
		}
		WARN_ON(1);
	}
}

static struct btrfsic_dev_state *btrfsic_dev_state_lookup(
		struct block_device *bdev)
{
	struct btrfsic_dev_state *ds;

	ds = btrfsic_dev_state_hashtable_lookup(bdev,
						&btrfsic_dev_state_hashtable);
	return ds;
}

int btrfsic_submit_bh(int rw, struct buffer_head *bh)
{
	struct btrfsic_dev_state *dev_state;

	if (!btrfsic_is_initialized)
		return submit_bh(rw, bh);

	mutex_lock(&btrfsic_mutex);
	/* since btrfsic_submit_bh() might also be called before
	 * btrfsic_mount(), this might return NULL */
	dev_state = btrfsic_dev_state_lookup(bh->b_bdev);

	/* Only called to write the superblock (incl. FLUSH/FUA) */
	if (NULL != dev_state &&
	    (rw & WRITE) && bh->b_size > 0) {
		u64 dev_bytenr;

		dev_bytenr = 4096 * bh->b_blocknr;
		if (dev_state->state->print_mask &
		    BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
			printk(KERN_INFO
2961
			       "submit_bh(rw=0x%x, blocknr=%llu (bytenr %llu),"
2962
			       " size=%lu, data=%p, bdev=%p)\n",
2963 2964
			       rw, (unsigned long long)bh->b_blocknr,
			       dev_bytenr,
2965 2966
			       (unsigned long)bh->b_size, bh->b_data,
			       bh->b_bdev);
2967
		btrfsic_process_written_block(dev_state, dev_bytenr,
2968
					      &bh->b_data, 1, NULL,
2969 2970 2971 2972 2973
					      NULL, bh, rw);
	} else if (NULL != dev_state && (rw & REQ_FLUSH)) {
		if (dev_state->state->print_mask &
		    BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
			printk(KERN_INFO
2974
			       "submit_bh(rw=0x%x FLUSH, bdev=%p)\n",
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
			       rw, bh->b_bdev);
		if (!dev_state->dummy_block_for_bio_bh_flush.is_iodone) {
			if ((dev_state->state->print_mask &
			     (BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH |
			      BTRFSIC_PRINT_MASK_VERBOSE)))
				printk(KERN_INFO
				       "btrfsic_submit_bh(%s) with FLUSH"
				       " but dummy block already in use"
				       " (ignored)!\n",
				       dev_state->name);
		} else {
			struct btrfsic_block *const block =
				&dev_state->dummy_block_for_bio_bh_flush;

			block->is_iodone = 0;
			block->never_written = 0;
			block->iodone_w_error = 0;
			block->flush_gen = dev_state->last_flush_gen + 1;
			block->submit_bio_bh_rw = rw;
			block->orig_bio_bh_private = bh->b_private;
			block->orig_bio_bh_end_io.bh = bh->b_end_io;
			block->next_in_same_bio = NULL;
			bh->b_private = block;
			bh->b_end_io = btrfsic_bh_end_io;
		}
	}
	mutex_unlock(&btrfsic_mutex);
	return submit_bh(rw, bh);
}

void btrfsic_submit_bio(int rw, struct bio *bio)
{
	struct btrfsic_dev_state *dev_state;

	if (!btrfsic_is_initialized) {
		submit_bio(rw, bio);
		return;
	}

	mutex_lock(&btrfsic_mutex);
	/* since btrfsic_submit_bio() is also called before
	 * btrfsic_mount(), this might return NULL */
	dev_state = btrfsic_dev_state_lookup(bio->bi_bdev);
	if (NULL != dev_state &&
	    (rw & WRITE) && NULL != bio->bi_io_vec) {
		unsigned int i;
		u64 dev_bytenr;
		int bio_is_patched;
3023
		char **mapped_datav;
3024 3025 3026 3027 3028 3029 3030

		dev_bytenr = 512 * bio->bi_sector;
		bio_is_patched = 0;
		if (dev_state->state->print_mask &
		    BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
			printk(KERN_INFO
			       "submit_bio(rw=0x%x, bi_vcnt=%u,"
3031 3032 3033 3034
			       " bi_sector=%llu (bytenr %llu), bi_bdev=%p)\n",
			       rw, bio->bi_vcnt,
			       (unsigned long long)bio->bi_sector, dev_bytenr,
			       bio->bi_bdev);
3035

3036 3037 3038 3039
		mapped_datav = kmalloc(sizeof(*mapped_datav) * bio->bi_vcnt,
				       GFP_NOFS);
		if (!mapped_datav)
			goto leave;
3040
		for (i = 0; i < bio->bi_vcnt; i++) {
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
			BUG_ON(bio->bi_io_vec[i].bv_len != PAGE_CACHE_SIZE);
			mapped_datav[i] = kmap(bio->bi_io_vec[i].bv_page);
			if (!mapped_datav[i]) {
				while (i > 0) {
					i--;
					kunmap(bio->bi_io_vec[i].bv_page);
				}
				kfree(mapped_datav);
				goto leave;
			}
3051 3052 3053 3054 3055 3056
			if ((BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH |
			     BTRFSIC_PRINT_MASK_VERBOSE) ==
			    (dev_state->state->print_mask &
			     (BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH |
			      BTRFSIC_PRINT_MASK_VERBOSE)))
				printk(KERN_INFO
3057
				       "#%u: page=%p, len=%u, offset=%u\n",
3058 3059 3060
				       i, bio->bi_io_vec[i].bv_page,
				       bio->bi_io_vec[i].bv_len,
				       bio->bi_io_vec[i].bv_offset);
3061 3062 3063 3064 3065 3066 3067
		}
		btrfsic_process_written_block(dev_state, dev_bytenr,
					      mapped_datav, bio->bi_vcnt,
					      bio, &bio_is_patched,
					      NULL, rw);
		while (i > 0) {
			i--;
3068 3069
			kunmap(bio->bi_io_vec[i].bv_page);
		}
3070
		kfree(mapped_datav);
3071 3072 3073 3074
	} else if (NULL != dev_state && (rw & REQ_FLUSH)) {
		if (dev_state->state->print_mask &
		    BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH)
			printk(KERN_INFO
3075
			       "submit_bio(rw=0x%x FLUSH, bdev=%p)\n",
3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
			       rw, bio->bi_bdev);
		if (!dev_state->dummy_block_for_bio_bh_flush.is_iodone) {
			if ((dev_state->state->print_mask &
			     (BTRFSIC_PRINT_MASK_SUBMIT_BIO_BH |
			      BTRFSIC_PRINT_MASK_VERBOSE)))
				printk(KERN_INFO
				       "btrfsic_submit_bio(%s) with FLUSH"
				       " but dummy block already in use"
				       " (ignored)!\n",
				       dev_state->name);
		} else {
			struct btrfsic_block *const block =
				&dev_state->dummy_block_for_bio_bh_flush;

			block->is_iodone = 0;
			block->never_written = 0;
			block->iodone_w_error = 0;
			block->flush_gen = dev_state->last_flush_gen + 1;
			block->submit_bio_bh_rw = rw;
			block->orig_bio_bh_private = bio->bi_private;
			block->orig_bio_bh_end_io.bio = bio->bi_end_io;
			block->next_in_same_bio = NULL;
			bio->bi_private = block;
			bio->bi_end_io = btrfsic_bio_end_io;
		}
	}
3102
leave:
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
	mutex_unlock(&btrfsic_mutex);

	submit_bio(rw, bio);
}

int btrfsic_mount(struct btrfs_root *root,
		  struct btrfs_fs_devices *fs_devices,
		  int including_extent_data, u32 print_mask)
{
	int ret;
	struct btrfsic_state *state;
	struct list_head *dev_head = &fs_devices->devices;
	struct btrfs_device *device;

3117 3118 3119 3120 3121 3122 3123 3124 3125
	if (root->nodesize != root->leafsize) {
		printk(KERN_INFO
		       "btrfsic: cannot handle nodesize %d != leafsize %d!\n",
		       root->nodesize, root->leafsize);
		return -1;
	}
	if (root->nodesize & ((u64)PAGE_CACHE_SIZE - 1)) {
		printk(KERN_INFO
		       "btrfsic: cannot handle nodesize %d not being a multiple of PAGE_CACHE_SIZE %ld!\n",
3126
		       root->nodesize, PAGE_CACHE_SIZE);
3127 3128 3129 3130 3131
		return -1;
	}
	if (root->leafsize & ((u64)PAGE_CACHE_SIZE - 1)) {
		printk(KERN_INFO
		       "btrfsic: cannot handle leafsize %d not being a multiple of PAGE_CACHE_SIZE %ld!\n",
3132
		       root->leafsize, PAGE_CACHE_SIZE);
3133 3134 3135 3136 3137
		return -1;
	}
	if (root->sectorsize & ((u64)PAGE_CACHE_SIZE - 1)) {
		printk(KERN_INFO
		       "btrfsic: cannot handle sectorsize %d not being a multiple of PAGE_CACHE_SIZE %ld!\n",
3138
		       root->sectorsize, PAGE_CACHE_SIZE);
3139 3140
		return -1;
	}
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156
	state = kzalloc(sizeof(*state), GFP_NOFS);
	if (NULL == state) {
		printk(KERN_INFO "btrfs check-integrity: kmalloc() failed!\n");
		return -1;
	}

	if (!btrfsic_is_initialized) {
		mutex_init(&btrfsic_mutex);
		btrfsic_dev_state_hashtable_init(&btrfsic_dev_state_hashtable);
		btrfsic_is_initialized = 1;
	}
	mutex_lock(&btrfsic_mutex);
	state->root = root;
	state->print_mask = print_mask;
	state->include_extent_data = including_extent_data;
	state->csum_size = 0;
3157 3158
	state->metablock_size = root->nodesize;
	state->datablock_size = root->sectorsize;
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
	INIT_LIST_HEAD(&state->all_blocks_list);
	btrfsic_block_hashtable_init(&state->block_hashtable);
	btrfsic_block_link_hashtable_init(&state->block_link_hashtable);
	state->max_superblock_generation = 0;
	state->latest_superblock = NULL;

	list_for_each_entry(device, dev_head, dev_list) {
		struct btrfsic_dev_state *ds;
		char *p;

		if (!device->bdev || !device->name)
			continue;

		ds = btrfsic_dev_state_alloc();
		if (NULL == ds) {
			printk(KERN_INFO
			       "btrfs check-integrity: kmalloc() failed!\n");
			mutex_unlock(&btrfsic_mutex);
			return -1;
		}
		ds->bdev = device->bdev;
		ds->state = state;
		bdevname(ds->bdev, ds->name);
		ds->name[BDEVNAME_SIZE - 1] = '\0';
		for (p = ds->name; *p != '\0'; p++);
		while (p > ds->name && *p != '/')
			p--;
		if (*p == '/')
			p++;
		strlcpy(ds->name, p, sizeof(ds->name));
		btrfsic_dev_state_hashtable_add(ds,
						&btrfsic_dev_state_hashtable);
	}

	ret = btrfsic_process_superblock(state, fs_devices);
	if (0 != ret) {
		mutex_unlock(&btrfsic_mutex);
		btrfsic_unmount(root, fs_devices);
		return ret;
	}

	if (state->print_mask & BTRFSIC_PRINT_MASK_INITIAL_DATABASE)
		btrfsic_dump_database(state);
	if (state->print_mask & BTRFSIC_PRINT_MASK_INITIAL_TREE)
		btrfsic_dump_tree(state);

	mutex_unlock(&btrfsic_mutex);
	return 0;
}

void btrfsic_unmount(struct btrfs_root *root,
		     struct btrfs_fs_devices *fs_devices)
{
	struct list_head *elem_all;
	struct list_head *tmp_all;
	struct btrfsic_state *state;
	struct list_head *dev_head = &fs_devices->devices;
	struct btrfs_device *device;

	if (!btrfsic_is_initialized)
		return;

	mutex_lock(&btrfsic_mutex);

	state = NULL;
	list_for_each_entry(device, dev_head, dev_list) {
		struct btrfsic_dev_state *ds;

		if (!device->bdev || !device->name)
			continue;

		ds = btrfsic_dev_state_hashtable_lookup(
				device->bdev,
				&btrfsic_dev_state_hashtable);
		if (NULL != ds) {
			state = ds->state;
			btrfsic_dev_state_hashtable_remove(ds);
			btrfsic_dev_state_free(ds);
		}
	}

	if (NULL == state) {
		printk(KERN_INFO
		       "btrfsic: error, cannot find state information"
		       " on umount!\n");
		mutex_unlock(&btrfsic_mutex);
		return;
	}

	/*
	 * Don't care about keeping the lists' state up to date,
	 * just free all memory that was allocated dynamically.
	 * Free the blocks and the block_links.
	 */
	list_for_each_safe(elem_all, tmp_all, &state->all_blocks_list) {
		struct btrfsic_block *const b_all =
		    list_entry(elem_all, struct btrfsic_block,
			       all_blocks_node);
		struct list_head *elem_ref_to;
		struct list_head *tmp_ref_to;

		list_for_each_safe(elem_ref_to, tmp_ref_to,
				   &b_all->ref_to_list) {
			struct btrfsic_block_link *const l =
			    list_entry(elem_ref_to,
				       struct btrfsic_block_link,
				       node_ref_to);

			if (state->print_mask & BTRFSIC_PRINT_MASK_VERBOSE)
				btrfsic_print_rem_link(state, l);

			l->ref_cnt--;
			if (0 == l->ref_cnt)
				btrfsic_block_link_free(l);
		}

3275
		if (b_all->is_iodone || b_all->never_written)
3276 3277 3278 3279 3280 3281
			btrfsic_block_free(b_all);
		else
			printk(KERN_INFO "btrfs: attempt to free %c-block"
			       " @%llu (%s/%llu/%d) on umount which is"
			       " not yet iodone!\n",
			       btrfsic_get_block_type(state, b_all),
3282 3283
			       b_all->logical_bytenr, b_all->dev_state->name,
			       b_all->dev_bytenr, b_all->mirror_num);
3284 3285 3286 3287 3288 3289
	}

	mutex_unlock(&btrfsic_mutex);

	kfree(state);
}