dm-integrity.c 132.9 KB
Newer Older
M
Mikulas Patocka 已提交
1 2 3 4 5 6 7 8
/*
 * Copyright (C) 2016-2017 Red Hat, Inc. All rights reserved.
 * Copyright (C) 2016-2017 Milan Broz
 * Copyright (C) 2016-2017 Mikulas Patocka
 *
 * This file is released under the GPL.
 */

9 10
#include "dm-bio-record.h"

11
#include <linux/compiler.h>
M
Mikulas Patocka 已提交
12 13 14 15 16 17 18 19
#include <linux/module.h>
#include <linux/device-mapper.h>
#include <linux/dm-io.h>
#include <linux/vmalloc.h>
#include <linux/sort.h>
#include <linux/rbtree.h>
#include <linux/delay.h>
#include <linux/random.h>
20
#include <linux/reboot.h>
M
Mikulas Patocka 已提交
21 22 23
#include <crypto/hash.h>
#include <crypto/skcipher.h>
#include <linux/async_tx.h>
24
#include <linux/dm-bufio.h>
M
Mikulas Patocka 已提交
25 26 27 28 29

#define DM_MSG_PREFIX "integrity"

#define DEFAULT_INTERLEAVE_SECTORS	32768
#define DEFAULT_JOURNAL_SIZE_FACTOR	7
30
#define DEFAULT_SECTORS_PER_BITMAP_BIT	32768
M
Mikulas Patocka 已提交
31 32 33 34
#define DEFAULT_BUFFER_SECTORS		128
#define DEFAULT_JOURNAL_WATERMARK	50
#define DEFAULT_SYNC_MSEC		10000
#define DEFAULT_MAX_JOURNAL_SECTORS	131072
35 36
#define MIN_LOG2_INTERLEAVE_SECTORS	3
#define MAX_LOG2_INTERLEAVE_SECTORS	31
M
Mikulas Patocka 已提交
37
#define METADATA_WORKQUEUE_MAX_ACTIVE	16
38 39
#define RECALC_SECTORS			8192
#define RECALC_WRITE_SUPER		16
40 41
#define BITMAP_BLOCK_SIZE		4096	/* don't change it */
#define BITMAP_FLUSH_INTERVAL		(10 * HZ)
42
#define DISCARD_FILLER			0xf6
43
#define SALT_SIZE			16
M
Mikulas Patocka 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56

/*
 * Warning - DEBUG_PRINT prints security-sensitive data to the log,
 * so it should not be enabled in the official kernel
 */
//#define DEBUG_PRINT
//#define INTERNAL_VERIFY

/*
 * On disk structures
 */

#define SB_MAGIC			"integrt"
57 58
#define SB_VERSION_1			1
#define SB_VERSION_2			2
59
#define SB_VERSION_3			3
60
#define SB_VERSION_4			4
61
#define SB_VERSION_5			5
M
Mikulas Patocka 已提交
62
#define SB_SECTORS			8
63
#define MAX_SECTORS_PER_BLOCK		8
M
Mikulas Patocka 已提交
64 65 66 67 68 69 70 71 72

struct superblock {
	__u8 magic[8];
	__u8 version;
	__u8 log2_interleave_sectors;
	__u16 integrity_tag_size;
	__u32 journal_sections;
	__u64 provided_data_sectors;	/* userspace uses this value */
	__u32 flags;
73
	__u8 log2_sectors_per_block;
74 75
	__u8 log2_blocks_per_bitmap_bit;
	__u8 pad[2];
76
	__u64 recalc_sector;
77 78
	__u8 pad2[8];
	__u8 salt[SALT_SIZE];
M
Mikulas Patocka 已提交
79 80 81
};

#define SB_FLAG_HAVE_JOURNAL_MAC	0x1
82
#define SB_FLAG_RECALCULATING		0x2
83
#define SB_FLAG_DIRTY_BITMAP		0x4
84
#define SB_FLAG_FIXED_PADDING		0x8
85
#define SB_FLAG_FIXED_HMAC		0x10
M
Mikulas Patocka 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99

#define	JOURNAL_ENTRY_ROUNDUP		8

typedef __u64 commit_id_t;
#define JOURNAL_MAC_PER_SECTOR		8

struct journal_entry {
	union {
		struct {
			__u32 sector_lo;
			__u32 sector_hi;
		} s;
		__u64 sector;
	} u;
100
	commit_id_t last_bytes[];
101
	/* __u8 tag[0]; */
M
Mikulas Patocka 已提交
102 103
};

104 105
#define journal_entry_tag(ic, je)		((__u8 *)&(je)->last_bytes[(ic)->sectors_per_block])

M
Mikulas Patocka 已提交
106
#if BITS_PER_LONG == 64
107
#define journal_entry_set_sector(je, x)		do { smp_wmb(); WRITE_ONCE((je)->u.sector, cpu_to_le64(x)); } while (0)
M
Mikulas Patocka 已提交
108
#else
C
Christoph Hellwig 已提交
109
#define journal_entry_set_sector(je, x)		do { (je)->u.s.sector_lo = cpu_to_le32(x); smp_wmb(); WRITE_ONCE((je)->u.s.sector_hi, cpu_to_le32((x) >> 32)); } while (0)
M
Mikulas Patocka 已提交
110
#endif
C
Christoph Hellwig 已提交
111
#define journal_entry_get_sector(je)		le64_to_cpu((je)->u.sector)
M
Mikulas Patocka 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
#define journal_entry_is_unused(je)		((je)->u.s.sector_hi == cpu_to_le32(-1))
#define journal_entry_set_unused(je)		do { ((je)->u.s.sector_hi = cpu_to_le32(-1)); } while (0)
#define journal_entry_is_inprogress(je)		((je)->u.s.sector_hi == cpu_to_le32(-2))
#define journal_entry_set_inprogress(je)	do { ((je)->u.s.sector_hi = cpu_to_le32(-2)); } while (0)

#define JOURNAL_BLOCK_SECTORS		8
#define JOURNAL_SECTOR_DATA		((1 << SECTOR_SHIFT) - sizeof(commit_id_t))
#define JOURNAL_MAC_SIZE		(JOURNAL_MAC_PER_SECTOR * JOURNAL_BLOCK_SECTORS)

struct journal_sector {
	__u8 entries[JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR];
	__u8 mac[JOURNAL_MAC_PER_SECTOR];
	commit_id_t commit_id;
};

127
#define MAX_TAG_SIZE			(JOURNAL_SECTOR_DATA - JOURNAL_MAC_PER_SECTOR - offsetof(struct journal_entry, last_bytes[MAX_SECTORS_PER_BLOCK]))
M
Mikulas Patocka 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

#define METADATA_PADDING_SECTORS	8

#define N_COMMIT_IDS			4

static unsigned char prev_commit_seq(unsigned char seq)
{
	return (seq + N_COMMIT_IDS - 1) % N_COMMIT_IDS;
}

static unsigned char next_commit_seq(unsigned char seq)
{
	return (seq + 1) % N_COMMIT_IDS;
}

/*
 * In-memory structures
 */

struct journal_node {
	struct rb_node node;
	sector_t sector;
};

struct alg_spec {
	char *alg_string;
	char *key_string;
	__u8 *key;
	unsigned key_size;
};

struct dm_integrity_c {
	struct dm_dev *dev;
161
	struct dm_dev *meta_dev;
M
Mikulas Patocka 已提交
162 163 164
	unsigned tag_size;
	__s8 log2_tag_size;
	sector_t start;
165
	mempool_t journal_io_mempool;
M
Mikulas Patocka 已提交
166 167 168 169 170
	struct dm_io_client *io;
	struct dm_bufio_client *bufio;
	struct workqueue_struct *metadata_wq;
	struct superblock *sb;
	unsigned journal_pages;
171 172
	unsigned n_bitmap_blocks;

M
Mikulas Patocka 已提交
173 174 175
	struct page_list *journal;
	struct page_list *journal_io;
	struct page_list *journal_xor;
176 177 178 179
	struct page_list *recalc_bitmap;
	struct page_list *may_write_bitmap;
	struct bitmap_block_status *bbs;
	unsigned bitmap_flush_interval;
180 181
	int synchronous_mode;
	struct bio_list synchronous_bios;
182
	struct delayed_work bitmap_flush_work;
M
Mikulas Patocka 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

	struct crypto_skcipher *journal_crypt;
	struct scatterlist **journal_scatterlist;
	struct scatterlist **journal_io_scatterlist;
	struct skcipher_request **sk_requests;

	struct crypto_shash *journal_mac;

	struct journal_node *journal_tree;
	struct rb_root journal_tree_root;

	sector_t provided_data_sectors;

	unsigned short journal_entry_size;
	unsigned char journal_entries_per_sector;
	unsigned char journal_section_entries;
199
	unsigned short journal_section_sectors;
M
Mikulas Patocka 已提交
200 201
	unsigned journal_sections;
	unsigned journal_entries;
202 203
	sector_t data_device_sectors;
	sector_t meta_device_sectors;
M
Mikulas Patocka 已提交
204 205 206 207
	unsigned initial_sectors;
	unsigned metadata_run;
	__s8 log2_metadata_run;
	__u8 log2_buffer_sectors;
208
	__u8 sectors_per_block;
209
	__u8 log2_blocks_per_bitmap_bit;
M
Mikulas Patocka 已提交
210 211 212 213 214 215 216

	unsigned char mode;

	int failed;

	struct crypto_shash *internal_hash;

217 218
	struct dm_target *ti;

M
Mikulas Patocka 已提交
219 220
	/* these variables are locked with endio_wait.lock */
	struct rb_root in_progress;
221
	struct list_head wait_list;
M
Mikulas Patocka 已提交
222 223
	wait_queue_head_t endio_wait;
	struct workqueue_struct *wait_wq;
224
	struct workqueue_struct *offload_wq;
M
Mikulas Patocka 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

	unsigned char commit_seq;
	commit_id_t commit_ids[N_COMMIT_IDS];

	unsigned committed_section;
	unsigned n_committed_sections;

	unsigned uncommitted_section;
	unsigned n_uncommitted_sections;

	unsigned free_section;
	unsigned char free_section_entry;
	unsigned free_sectors;

	unsigned free_sectors_threshold;

	struct workqueue_struct *commit_wq;
	struct work_struct commit_work;

	struct workqueue_struct *writer_wq;
	struct work_struct writer_work;

247 248 249 250 251
	struct workqueue_struct *recalc_wq;
	struct work_struct recalc_work;
	u8 *recalc_buffer;
	u8 *recalc_tags;

M
Mikulas Patocka 已提交
252 253 254 255 256 257 258 259 260 261 262 263
	struct bio_list flush_bio_list;

	unsigned long autocommit_jiffies;
	struct timer_list autocommit_timer;
	unsigned autocommit_msec;

	wait_queue_head_t copy_to_journal_wait;

	struct completion crypto_backoff;

	bool journal_uptodate;
	bool just_formatted;
264
	bool recalculate_flag;
265
	bool reset_recalculate_flag;
266
	bool discard;
267
	bool fix_padding;
268
	bool fix_hmac;
269
	bool legacy_recalculate;
M
Mikulas Patocka 已提交
270 271 272 273

	struct alg_spec internal_hash_alg;
	struct alg_spec journal_crypt_alg;
	struct alg_spec journal_mac_alg;
274 275

	atomic64_t number_of_mismatches;
276 277

	struct notifier_block reboot_notifier;
M
Mikulas Patocka 已提交
278 279 280 281
};

struct dm_integrity_range {
	sector_t logical_sector;
282
	sector_t n_sectors;
283 284 285 286 287 288 289 290
	bool waiting;
	union {
		struct rb_node node;
		struct {
			struct task_struct *task;
			struct list_head wait_entry;
		};
	};
M
Mikulas Patocka 已提交
291 292 293 294 295 296
};

struct dm_integrity_io {
	struct work_struct work;

	struct dm_integrity_c *ic;
297
	enum req_opf op;
M
Mikulas Patocka 已提交
298 299 300 301 302 303 304 305
	bool fua;

	struct dm_integrity_range range;

	sector_t metadata_block;
	unsigned metadata_offset;

	atomic_t in_flight;
306
	blk_status_t bi_status;
M
Mikulas Patocka 已提交
307 308 309

	struct completion *completion;

310
	struct dm_bio_details bio_details;
M
Mikulas Patocka 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323
};

struct journal_completion {
	struct dm_integrity_c *ic;
	atomic_t in_flight;
	struct completion comp;
};

struct journal_io {
	struct dm_integrity_range range;
	struct journal_completion *comp;
};

324 325 326 327 328 329 330 331 332 333
struct bitmap_block_status {
	struct work_struct work;
	struct dm_integrity_c *ic;
	unsigned idx;
	unsigned long *bitmap;
	struct bio_list bio_queue;
	spinlock_t bio_queue_lock;

};

M
Mikulas Patocka 已提交
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
static struct kmem_cache *journal_io_cache;

#define JOURNAL_IO_MEMPOOL	32

#ifdef DEBUG_PRINT
#define DEBUG_print(x, ...)	printk(KERN_DEBUG x, ##__VA_ARGS__)
static void __DEBUG_bytes(__u8 *bytes, size_t len, const char *msg, ...)
{
	va_list args;
	va_start(args, msg);
	vprintk(msg, args);
	va_end(args);
	if (len)
		pr_cont(":");
	while (len) {
		pr_cont(" %02x", *bytes);
		bytes++;
		len--;
	}
	pr_cont("\n");
}
#define DEBUG_bytes(bytes, len, msg, ...)	__DEBUG_bytes(bytes, len, KERN_DEBUG msg, ##__VA_ARGS__)
#else
#define DEBUG_print(x, ...)			do { } while (0)
#define DEBUG_bytes(bytes, len, msg, ...)	do { } while (0)
#endif

361 362 363 364 365 366 367 368
static void dm_integrity_prepare(struct request *rq)
{
}

static void dm_integrity_complete(struct request *rq, unsigned int nr_bytes)
{
}

M
Mikulas Patocka 已提交
369 370 371
/*
 * DM Integrity profile, protection is performed layer above (dm-crypt)
 */
372
static const struct blk_integrity_profile dm_integrity_profile = {
M
Mikulas Patocka 已提交
373 374 375
	.name			= "DM-DIF-EXT-TAG",
	.generate_fn		= NULL,
	.verify_fn		= NULL,
376 377
	.prepare_fn		= dm_integrity_prepare,
	.complete_fn		= dm_integrity_complete,
M
Mikulas Patocka 已提交
378 379 380 381 382 383 384 385
};

static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map);
static void integrity_bio_wait(struct work_struct *w);
static void dm_integrity_dtr(struct dm_target *ti);

static void dm_integrity_io_error(struct dm_integrity_c *ic, const char *msg, int err)
{
386 387
	if (err == -EILSEQ)
		atomic64_inc(&ic->number_of_mismatches);
M
Mikulas Patocka 已提交
388 389 390 391 392 393
	if (!cmpxchg(&ic->failed, 0, err))
		DMERR("Error on %s: %d", msg, err);
}

static int dm_integrity_failed(struct dm_integrity_c *ic)
{
394
	return READ_ONCE(ic->failed);
M
Mikulas Patocka 已提交
395 396
}

397 398
static bool dm_integrity_disable_recalculate(struct dm_integrity_c *ic)
{
399 400 401 402 403
	if (ic->legacy_recalculate)
		return false;
	if (!(ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) ?
	    ic->internal_hash_alg.key || ic->journal_mac_alg.key :
	    ic->internal_hash_alg.key && !ic->journal_mac_alg.key)
404 405 406 407
		return true;
	return false;
}

M
Mikulas Patocka 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420
static commit_id_t dm_integrity_commit_id(struct dm_integrity_c *ic, unsigned i,
					  unsigned j, unsigned char seq)
{
	/*
	 * Xor the number with section and sector, so that if a piece of
	 * journal is written at wrong place, it is detected.
	 */
	return ic->commit_ids[seq] ^ cpu_to_le64(((__u64)i << 32) ^ j);
}

static void get_area_and_offset(struct dm_integrity_c *ic, sector_t data_sector,
				sector_t *area, sector_t *offset)
{
421 422 423 424 425 426 427 428
	if (!ic->meta_dev) {
		__u8 log2_interleave_sectors = ic->sb->log2_interleave_sectors;
		*area = data_sector >> log2_interleave_sectors;
		*offset = (unsigned)data_sector & ((1U << log2_interleave_sectors) - 1);
	} else {
		*area = 0;
		*offset = data_sector;
	}
M
Mikulas Patocka 已提交
429 430
}

431 432 433 434 435 436
#define sector_to_block(ic, n)						\
do {									\
	BUG_ON((n) & (unsigned)((ic)->sectors_per_block - 1));		\
	(n) >>= (ic)->sb->log2_sectors_per_block;			\
} while (0)

M
Mikulas Patocka 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449
static __u64 get_metadata_sector_and_offset(struct dm_integrity_c *ic, sector_t area,
					    sector_t offset, unsigned *metadata_offset)
{
	__u64 ms;
	unsigned mo;

	ms = area << ic->sb->log2_interleave_sectors;
	if (likely(ic->log2_metadata_run >= 0))
		ms += area << ic->log2_metadata_run;
	else
		ms += area * ic->metadata_run;
	ms >>= ic->log2_buffer_sectors;

450 451
	sector_to_block(ic, offset);

M
Mikulas Patocka 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
	if (likely(ic->log2_tag_size >= 0)) {
		ms += offset >> (SECTOR_SHIFT + ic->log2_buffer_sectors - ic->log2_tag_size);
		mo = (offset << ic->log2_tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
	} else {
		ms += (__u64)offset * ic->tag_size >> (SECTOR_SHIFT + ic->log2_buffer_sectors);
		mo = (offset * ic->tag_size) & ((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - 1);
	}
	*metadata_offset = mo;
	return ms;
}

static sector_t get_data_sector(struct dm_integrity_c *ic, sector_t area, sector_t offset)
{
	sector_t result;

467 468 469
	if (ic->meta_dev)
		return offset;

M
Mikulas Patocka 已提交
470 471 472 473 474 475 476
	result = area << ic->sb->log2_interleave_sectors;
	if (likely(ic->log2_metadata_run >= 0))
		result += (area + 1) << ic->log2_metadata_run;
	else
		result += (area + 1) * ic->metadata_run;

	result += (sector_t)ic->initial_sectors + offset;
477 478
	result += ic->start;

M
Mikulas Patocka 已提交
479 480 481 482 483 484 485 486 487
	return result;
}

static void wraparound_section(struct dm_integrity_c *ic, unsigned *sec_ptr)
{
	if (unlikely(*sec_ptr >= ic->journal_sections))
		*sec_ptr -= ic->journal_sections;
}

488 489
static void sb_set_version(struct dm_integrity_c *ic)
{
490 491 492
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC))
		ic->sb->version = SB_VERSION_5;
	else if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING))
493 494
		ic->sb->version = SB_VERSION_4;
	else if (ic->mode == 'B' || ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP))
495 496
		ic->sb->version = SB_VERSION_3;
	else if (ic->meta_dev || ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
497 498 499 500 501
		ic->sb->version = SB_VERSION_2;
	else
		ic->sb->version = SB_VERSION_1;
}

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
static int sb_mac(struct dm_integrity_c *ic, bool wr)
{
	SHASH_DESC_ON_STACK(desc, ic->journal_mac);
	int r;
	unsigned size = crypto_shash_digestsize(ic->journal_mac);

	if (sizeof(struct superblock) + size > 1 << SECTOR_SHIFT) {
		dm_integrity_io_error(ic, "digest is too long", -EINVAL);
		return -EINVAL;
	}

	desc->tfm = ic->journal_mac;

	r = crypto_shash_init(desc);
	if (unlikely(r < 0)) {
		dm_integrity_io_error(ic, "crypto_shash_init", r);
		return r;
	}

	r = crypto_shash_update(desc, (__u8 *)ic->sb, (1 << SECTOR_SHIFT) - size);
	if (unlikely(r < 0)) {
		dm_integrity_io_error(ic, "crypto_shash_update", r);
		return r;
	}

	if (likely(wr)) {
		r = crypto_shash_final(desc, (__u8 *)ic->sb + (1 << SECTOR_SHIFT) - size);
		if (unlikely(r < 0)) {
			dm_integrity_io_error(ic, "crypto_shash_final", r);
			return r;
		}
	} else {
		__u8 result[HASH_MAX_DIGESTSIZE];
		r = crypto_shash_final(desc, result);
		if (unlikely(r < 0)) {
			dm_integrity_io_error(ic, "crypto_shash_final", r);
			return r;
		}
		if (memcmp((__u8 *)ic->sb + (1 << SECTOR_SHIFT) - size, result, size)) {
			dm_integrity_io_error(ic, "superblock mac", -EILSEQ);
			return -EILSEQ;
		}
	}

	return 0;
}

M
Mikulas Patocka 已提交
549 550 551 552
static int sync_rw_sb(struct dm_integrity_c *ic, int op, int op_flags)
{
	struct dm_io_request io_req;
	struct dm_io_region io_loc;
553
	int r;
M
Mikulas Patocka 已提交
554 555 556 557 558 559 560

	io_req.bi_op = op;
	io_req.bi_op_flags = op_flags;
	io_req.mem.type = DM_IO_KMEM;
	io_req.mem.ptr.addr = ic->sb;
	io_req.notify.fn = NULL;
	io_req.client = ic->io;
561
	io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
M
Mikulas Patocka 已提交
562 563 564
	io_loc.sector = ic->start;
	io_loc.count = SB_SECTORS;

565
	if (op == REQ_OP_WRITE) {
566
		sb_set_version(ic);
567 568 569 570 571 572
		if (ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
			r = sb_mac(ic, true);
			if (unlikely(r))
				return r;
		}
	}
573

574 575 576 577 578 579 580 581 582 583 584 585 586
	r = dm_io(&io_req, 1, &io_loc, NULL);
	if (unlikely(r))
		return r;

	if (op == REQ_OP_READ) {
		if (ic->mode != 'R' && ic->journal_mac && ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
			r = sb_mac(ic, false);
			if (unlikely(r))
				return r;
		}
	}

	return 0;
M
Mikulas Patocka 已提交
587 588
}

589 590 591 592 593
#define BITMAP_OP_TEST_ALL_SET		0
#define BITMAP_OP_TEST_ALL_CLEAR	1
#define BITMAP_OP_SET			2
#define BITMAP_OP_CLEAR			3

594 595
static bool block_bitmap_op(struct dm_integrity_c *ic, struct page_list *bitmap,
			    sector_t sector, sector_t n_sectors, int mode)
596 597 598 599 600
{
	unsigned long bit, end_bit, this_end_bit, page, end_page;
	unsigned long *data;

	if (unlikely(((sector | n_sectors) & ((1 << ic->sb->log2_sectors_per_block) - 1)) != 0)) {
601
		DMCRIT("invalid bitmap access (%llx,%llx,%d,%d,%d)",
602 603
			sector,
			n_sectors,
604 605 606 607 608 609 610 611 612 613
			ic->sb->log2_sectors_per_block,
			ic->log2_blocks_per_bitmap_bit,
			mode);
		BUG();
	}

	if (unlikely(!n_sectors))
		return true;

	bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
614 615
	end_bit = (sector + n_sectors - 1) >>
		(ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
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 652 653 654 655 656 657 658 659 660 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 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

	page = bit / (PAGE_SIZE * 8);
	bit %= PAGE_SIZE * 8;

	end_page = end_bit / (PAGE_SIZE * 8);
	end_bit %= PAGE_SIZE * 8;

repeat:
	if (page < end_page) {
		this_end_bit = PAGE_SIZE * 8 - 1;
	} else {
		this_end_bit = end_bit;
	}

	data = lowmem_page_address(bitmap[page].page);

	if (mode == BITMAP_OP_TEST_ALL_SET) {
		while (bit <= this_end_bit) {
			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
				do {
					if (data[bit / BITS_PER_LONG] != -1)
						return false;
					bit += BITS_PER_LONG;
				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
				continue;
			}
			if (!test_bit(bit, data))
				return false;
			bit++;
		}
	} else if (mode == BITMAP_OP_TEST_ALL_CLEAR) {
		while (bit <= this_end_bit) {
			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
				do {
					if (data[bit / BITS_PER_LONG] != 0)
						return false;
					bit += BITS_PER_LONG;
				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
				continue;
			}
			if (test_bit(bit, data))
				return false;
			bit++;
		}
	} else if (mode == BITMAP_OP_SET) {
		while (bit <= this_end_bit) {
			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
				do {
					data[bit / BITS_PER_LONG] = -1;
					bit += BITS_PER_LONG;
				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
				continue;
			}
			__set_bit(bit, data);
			bit++;
		}
	} else if (mode == BITMAP_OP_CLEAR) {
		if (!bit && this_end_bit == PAGE_SIZE * 8 - 1)
			clear_page(data);
		else while (bit <= this_end_bit) {
			if (!(bit % BITS_PER_LONG) && this_end_bit >= bit + BITS_PER_LONG - 1) {
				do {
					data[bit / BITS_PER_LONG] = 0;
					bit += BITS_PER_LONG;
				} while (this_end_bit >= bit + BITS_PER_LONG - 1);
				continue;
			}
			__clear_bit(bit, data);
			bit++;
		}
	} else {
		BUG();
	}

	if (unlikely(page < end_page)) {
		bit = 0;
		page++;
		goto repeat;
	}

	return true;
}

static void block_bitmap_copy(struct dm_integrity_c *ic, struct page_list *dst, struct page_list *src)
{
	unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);
	unsigned i;

	for (i = 0; i < n_bitmap_pages; i++) {
		unsigned long *dst_data = lowmem_page_address(dst[i].page);
		unsigned long *src_data = lowmem_page_address(src[i].page);
		copy_page(dst_data, src_data);
	}
}

static struct bitmap_block_status *sector_to_bitmap_block(struct dm_integrity_c *ic, sector_t sector)
{
	unsigned bit = sector >> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
	unsigned bitmap_block = bit / (BITMAP_BLOCK_SIZE * 8);

	BUG_ON(bitmap_block >= ic->n_bitmap_blocks);
	return &ic->bbs[bitmap_block];
}

M
Mikulas Patocka 已提交
720 721 722 723 724 725 726 727
static void access_journal_check(struct dm_integrity_c *ic, unsigned section, unsigned offset,
				 bool e, const char *function)
{
#if defined(CONFIG_DM_DEBUG) || defined(INTERNAL_VERIFY)
	unsigned limit = e ? ic->journal_section_entries : ic->journal_section_sectors;

	if (unlikely(section >= ic->journal_sections) ||
	    unlikely(offset >= limit)) {
728 729
		DMCRIT("%s: invalid access at (%u,%u), limit (%u,%u)",
		       function, section, offset, ic->journal_sections, limit);
M
Mikulas Patocka 已提交
730 731 732 733 734 735 736 737 738 739
		BUG();
	}
#endif
}

static void page_list_location(struct dm_integrity_c *ic, unsigned section, unsigned offset,
			       unsigned *pl_index, unsigned *pl_offset)
{
	unsigned sector;

740
	access_journal_check(ic, section, offset, false, "page_list_location");
M
Mikulas Patocka 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784

	sector = section * ic->journal_section_sectors + offset;

	*pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
	*pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);
}

static struct journal_sector *access_page_list(struct dm_integrity_c *ic, struct page_list *pl,
					       unsigned section, unsigned offset, unsigned *n_sectors)
{
	unsigned pl_index, pl_offset;
	char *va;

	page_list_location(ic, section, offset, &pl_index, &pl_offset);

	if (n_sectors)
		*n_sectors = (PAGE_SIZE - pl_offset) >> SECTOR_SHIFT;

	va = lowmem_page_address(pl[pl_index].page);

	return (struct journal_sector *)(va + pl_offset);
}

static struct journal_sector *access_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset)
{
	return access_page_list(ic, ic->journal, section, offset, NULL);
}

static struct journal_entry *access_journal_entry(struct dm_integrity_c *ic, unsigned section, unsigned n)
{
	unsigned rel_sector, offset;
	struct journal_sector *js;

	access_journal_check(ic, section, n, true, "access_journal_entry");

	rel_sector = n % JOURNAL_BLOCK_SECTORS;
	offset = n / JOURNAL_BLOCK_SECTORS;

	js = access_journal(ic, section, rel_sector);
	return (struct journal_entry *)((char *)js + offset * ic->journal_entry_size);
}

static struct journal_sector *access_journal_data(struct dm_integrity_c *ic, unsigned section, unsigned n)
{
785
	n <<= ic->sb->log2_sectors_per_block;
M
Mikulas Patocka 已提交
786

787 788 789 790 791
	n += JOURNAL_BLOCK_SECTORS;

	access_journal_check(ic, section, n, false, "access_journal_data");

	return access_journal(ic, section, n);
M
Mikulas Patocka 已提交
792 793 794 795 796 797 798 799 800 801 802
}

static void section_mac(struct dm_integrity_c *ic, unsigned section, __u8 result[JOURNAL_MAC_SIZE])
{
	SHASH_DESC_ON_STACK(desc, ic->journal_mac);
	int r;
	unsigned j, size;

	desc->tfm = ic->journal_mac;

	r = crypto_shash_init(desc);
803
	if (unlikely(r < 0)) {
M
Mikulas Patocka 已提交
804 805 806 807
		dm_integrity_io_error(ic, "crypto_shash_init", r);
		goto err;
	}

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
		uint64_t section_le;

		r = crypto_shash_update(desc, (__u8 *)&ic->sb->salt, SALT_SIZE);
		if (unlikely(r < 0)) {
			dm_integrity_io_error(ic, "crypto_shash_update", r);
			goto err;
		}

		section_le = cpu_to_le64(section);
		r = crypto_shash_update(desc, (__u8 *)&section_le, sizeof section_le);
		if (unlikely(r < 0)) {
			dm_integrity_io_error(ic, "crypto_shash_update", r);
			goto err;
		}
	}

M
Mikulas Patocka 已提交
825 826 827
	for (j = 0; j < ic->journal_section_entries; j++) {
		struct journal_entry *je = access_journal_entry(ic, section, j);
		r = crypto_shash_update(desc, (__u8 *)&je->u.sector, sizeof je->u.sector);
828
		if (unlikely(r < 0)) {
M
Mikulas Patocka 已提交
829 830 831 832 833 834 835 836 837
			dm_integrity_io_error(ic, "crypto_shash_update", r);
			goto err;
		}
	}

	size = crypto_shash_digestsize(ic->journal_mac);

	if (likely(size <= JOURNAL_MAC_SIZE)) {
		r = crypto_shash_final(desc, result);
838
		if (unlikely(r < 0)) {
M
Mikulas Patocka 已提交
839 840 841 842 843
			dm_integrity_io_error(ic, "crypto_shash_final", r);
			goto err;
		}
		memset(result + size, 0, JOURNAL_MAC_SIZE - size);
	} else {
K
Kees Cook 已提交
844 845 846 847 848 849
		__u8 digest[HASH_MAX_DIGESTSIZE];

		if (WARN_ON(size > sizeof(digest))) {
			dm_integrity_io_error(ic, "digest_size", -EINVAL);
			goto err;
		}
M
Mikulas Patocka 已提交
850
		r = crypto_shash_final(desc, digest);
851
		if (unlikely(r < 0)) {
M
Mikulas Patocka 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 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
			dm_integrity_io_error(ic, "crypto_shash_final", r);
			goto err;
		}
		memcpy(result, digest, JOURNAL_MAC_SIZE);
	}

	return;
err:
	memset(result, 0, JOURNAL_MAC_SIZE);
}

static void rw_section_mac(struct dm_integrity_c *ic, unsigned section, bool wr)
{
	__u8 result[JOURNAL_MAC_SIZE];
	unsigned j;

	if (!ic->journal_mac)
		return;

	section_mac(ic, section, result);

	for (j = 0; j < JOURNAL_BLOCK_SECTORS; j++) {
		struct journal_sector *js = access_journal(ic, section, j);

		if (likely(wr))
			memcpy(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR);
		else {
			if (memcmp(&js->mac, result + (j * JOURNAL_MAC_PER_SECTOR), JOURNAL_MAC_PER_SECTOR))
				dm_integrity_io_error(ic, "journal mac", -EILSEQ);
		}
	}
}

static void complete_journal_op(void *context)
{
	struct journal_completion *comp = context;
	BUG_ON(!atomic_read(&comp->in_flight));
	if (likely(atomic_dec_and_test(&comp->in_flight)))
		complete(&comp->comp);
}

static void xor_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
			unsigned n_sections, struct journal_completion *comp)
{
	struct async_submit_ctl submit;
	size_t n_bytes = (size_t)(n_sections * ic->journal_section_sectors) << SECTOR_SHIFT;
	unsigned pl_index, pl_offset, section_index;
	struct page_list *source_pl, *target_pl;

	if (likely(encrypt)) {
		source_pl = ic->journal;
		target_pl = ic->journal_io;
	} else {
		source_pl = ic->journal_io;
		target_pl = ic->journal;
	}

	page_list_location(ic, section, 0, &pl_index, &pl_offset);

	atomic_add(roundup(pl_offset + n_bytes, PAGE_SIZE) >> PAGE_SHIFT, &comp->in_flight);

	init_async_submit(&submit, ASYNC_TX_XOR_ZERO_DST, NULL, complete_journal_op, comp, NULL);

	section_index = pl_index;

	do {
		size_t this_step;
		struct page *src_pages[2];
		struct page *dst_page;

		while (unlikely(pl_index == section_index)) {
			unsigned dummy;
			if (likely(encrypt))
				rw_section_mac(ic, section, true);
			section++;
			n_sections--;
			if (!n_sections)
				break;
			page_list_location(ic, section, 0, &section_index, &dummy);
		}

		this_step = min(n_bytes, (size_t)PAGE_SIZE - pl_offset);
		dst_page = target_pl[pl_index].page;
		src_pages[0] = source_pl[pl_index].page;
		src_pages[1] = ic->journal_xor[pl_index].page;

		async_xor(dst_page, src_pages, pl_offset, 2, this_step, &submit);

		pl_index++;
		pl_offset = 0;
		n_bytes -= this_step;
	} while (n_bytes);

	BUG_ON(n_sections);

	async_tx_issue_pending_all();
}

static void complete_journal_encrypt(struct crypto_async_request *req, int err)
{
	struct journal_completion *comp = req->data;
	if (unlikely(err)) {
		if (likely(err == -EINPROGRESS)) {
			complete(&comp->ic->crypto_backoff);
			return;
		}
		dm_integrity_io_error(comp->ic, "asynchronous encrypt", err);
	}
	complete_journal_op(comp);
}

static bool do_crypt(bool encrypt, struct skcipher_request *req, struct journal_completion *comp)
{
	int r;
966
	skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
M
Mikulas Patocka 已提交
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
				      complete_journal_encrypt, comp);
	if (likely(encrypt))
		r = crypto_skcipher_encrypt(req);
	else
		r = crypto_skcipher_decrypt(req);
	if (likely(!r))
		return false;
	if (likely(r == -EINPROGRESS))
		return true;
	if (likely(r == -EBUSY)) {
		wait_for_completion(&comp->ic->crypto_backoff);
		reinit_completion(&comp->ic->crypto_backoff);
		return true;
	}
	dm_integrity_io_error(comp->ic, "encrypt", r);
	return false;
}

static void crypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
			  unsigned n_sections, struct journal_completion *comp)
{
	struct scatterlist **source_sg;
	struct scatterlist **target_sg;

	atomic_add(2, &comp->in_flight);

	if (likely(encrypt)) {
		source_sg = ic->journal_scatterlist;
		target_sg = ic->journal_io_scatterlist;
	} else {
		source_sg = ic->journal_io_scatterlist;
		target_sg = ic->journal_scatterlist;
	}

	do {
		struct skcipher_request *req;
		unsigned ivsize;
		char *iv;

		if (likely(encrypt))
			rw_section_mac(ic, section, true);

		req = ic->sk_requests[section];
		ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
		iv = req->iv;

		memcpy(iv, iv + ivsize, ivsize);

		req->src = source_sg[section];
		req->dst = target_sg[section];

		if (unlikely(do_crypt(encrypt, req, comp)))
			atomic_inc(&comp->in_flight);

		section++;
		n_sections--;
	} while (n_sections);

	atomic_dec(&comp->in_flight);
	complete_journal_op(comp);
}

static void encrypt_journal(struct dm_integrity_c *ic, bool encrypt, unsigned section,
			    unsigned n_sections, struct journal_completion *comp)
{
	if (ic->journal_xor)
		return xor_journal(ic, encrypt, section, n_sections, comp);
	else
		return crypt_journal(ic, encrypt, section, n_sections, comp);
}

static void complete_journal_io(unsigned long error, void *context)
{
	struct journal_completion *comp = context;
	if (unlikely(error != 0))
		dm_integrity_io_error(comp->ic, "writing journal", -EIO);
	complete_journal_op(comp);
}

1046 1047
static void rw_journal_sectors(struct dm_integrity_c *ic, int op, int op_flags,
			       unsigned sector, unsigned n_sectors, struct journal_completion *comp)
M
Mikulas Patocka 已提交
1048 1049 1050
{
	struct dm_io_request io_req;
	struct dm_io_region io_loc;
1051
	unsigned pl_index, pl_offset;
M
Mikulas Patocka 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
	int r;

	if (unlikely(dm_integrity_failed(ic))) {
		if (comp)
			complete_journal_io(-1UL, comp);
		return;
	}

	pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
	pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);

	io_req.bi_op = op;
	io_req.bi_op_flags = op_flags;
	io_req.mem.type = DM_IO_PAGE_LIST;
	if (ic->journal_io)
		io_req.mem.ptr.pl = &ic->journal_io[pl_index];
	else
		io_req.mem.ptr.pl = &ic->journal[pl_index];
	io_req.mem.offset = pl_offset;
	if (likely(comp != NULL)) {
		io_req.notify.fn = complete_journal_io;
		io_req.notify.context = comp;
	} else {
		io_req.notify.fn = NULL;
	}
	io_req.client = ic->io;
1078
	io_loc.bdev = ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev;
M
Mikulas Patocka 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	io_loc.sector = ic->start + SB_SECTORS + sector;
	io_loc.count = n_sectors;

	r = dm_io(&io_req, 1, &io_loc, NULL);
	if (unlikely(r)) {
		dm_integrity_io_error(ic, op == REQ_OP_READ ? "reading journal" : "writing journal", r);
		if (comp) {
			WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
			complete_journal_io(-1UL, comp);
		}
	}
}

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
static void rw_journal(struct dm_integrity_c *ic, int op, int op_flags, unsigned section,
		       unsigned n_sections, struct journal_completion *comp)
{
	unsigned sector, n_sectors;

	sector = section * ic->journal_section_sectors;
	n_sectors = n_sections * ic->journal_section_sectors;

	rw_journal_sectors(ic, op, op_flags, sector, n_sectors, comp);
}

M
Mikulas Patocka 已提交
1103 1104 1105 1106 1107 1108 1109 1110
static void write_journal(struct dm_integrity_c *ic, unsigned commit_start, unsigned commit_sections)
{
	struct journal_completion io_comp;
	struct journal_completion crypt_comp_1;
	struct journal_completion crypt_comp_2;
	unsigned i;

	io_comp.ic = ic;
1111
	init_completion(&io_comp.comp);
M
Mikulas Patocka 已提交
1112 1113 1114 1115 1116

	if (commit_start + commit_sections <= ic->journal_sections) {
		io_comp.in_flight = (atomic_t)ATOMIC_INIT(1);
		if (ic->journal_io) {
			crypt_comp_1.ic = ic;
1117
			init_completion(&crypt_comp_1.comp);
M
Mikulas Patocka 已提交
1118 1119 1120 1121 1122 1123 1124
			crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
			encrypt_journal(ic, true, commit_start, commit_sections, &crypt_comp_1);
			wait_for_completion_io(&crypt_comp_1.comp);
		} else {
			for (i = 0; i < commit_sections; i++)
				rw_section_mac(ic, commit_start + i, true);
		}
J
Jan Kara 已提交
1125 1126
		rw_journal(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, commit_start,
			   commit_sections, &io_comp);
M
Mikulas Patocka 已提交
1127 1128 1129 1130 1131 1132
	} else {
		unsigned to_end;
		io_comp.in_flight = (atomic_t)ATOMIC_INIT(2);
		to_end = ic->journal_sections - commit_start;
		if (ic->journal_io) {
			crypt_comp_1.ic = ic;
1133
			init_completion(&crypt_comp_1.comp);
M
Mikulas Patocka 已提交
1134 1135 1136 1137
			crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
			encrypt_journal(ic, true, commit_start, to_end, &crypt_comp_1);
			if (try_wait_for_completion(&crypt_comp_1.comp)) {
				rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
1138
				reinit_completion(&crypt_comp_1.comp);
M
Mikulas Patocka 已提交
1139 1140 1141 1142 1143
				crypt_comp_1.in_flight = (atomic_t)ATOMIC_INIT(0);
				encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_1);
				wait_for_completion_io(&crypt_comp_1.comp);
			} else {
				crypt_comp_2.ic = ic;
1144
				init_completion(&crypt_comp_2.comp);
M
Mikulas Patocka 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
				crypt_comp_2.in_flight = (atomic_t)ATOMIC_INIT(0);
				encrypt_journal(ic, true, 0, commit_sections - to_end, &crypt_comp_2);
				wait_for_completion_io(&crypt_comp_1.comp);
				rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
				wait_for_completion_io(&crypt_comp_2.comp);
			}
		} else {
			for (i = 0; i < to_end; i++)
				rw_section_mac(ic, commit_start + i, true);
			rw_journal(ic, REQ_OP_WRITE, REQ_FUA, commit_start, to_end, &io_comp);
			for (i = 0; i < commit_sections - to_end; i++)
				rw_section_mac(ic, i, true);
		}
		rw_journal(ic, REQ_OP_WRITE, REQ_FUA, 0, commit_sections - to_end, &io_comp);
	}

	wait_for_completion_io(&io_comp.comp);
}

static void copy_from_journal(struct dm_integrity_c *ic, unsigned section, unsigned offset,
			      unsigned n_sectors, sector_t target, io_notify_fn fn, void *data)
{
	struct dm_io_request io_req;
	struct dm_io_region io_loc;
	int r;
	unsigned sector, pl_index, pl_offset;

1172 1173
	BUG_ON((target | n_sectors | offset) & (unsigned)(ic->sectors_per_block - 1));

M
Mikulas Patocka 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
	if (unlikely(dm_integrity_failed(ic))) {
		fn(-1UL, data);
		return;
	}

	sector = section * ic->journal_section_sectors + JOURNAL_BLOCK_SECTORS + offset;

	pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
	pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);

	io_req.bi_op = REQ_OP_WRITE;
	io_req.bi_op_flags = 0;
	io_req.mem.type = DM_IO_PAGE_LIST;
	io_req.mem.ptr.pl = &ic->journal[pl_index];
	io_req.mem.offset = pl_offset;
	io_req.notify.fn = fn;
	io_req.notify.context = data;
	io_req.client = ic->io;
	io_loc.bdev = ic->dev->bdev;
1193
	io_loc.sector = target;
M
Mikulas Patocka 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202
	io_loc.count = n_sectors;

	r = dm_io(&io_req, 1, &io_loc, NULL);
	if (unlikely(r)) {
		WARN_ONCE(1, "asynchronous dm_io failed: %d", r);
		fn(-1UL, data);
	}
}

1203 1204 1205
static bool ranges_overlap(struct dm_integrity_range *range1, struct dm_integrity_range *range2)
{
	return range1->logical_sector < range2->logical_sector + range2->n_sectors &&
1206
	       range1->logical_sector + range1->n_sectors > range2->logical_sector;
1207 1208 1209
}

static bool add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range, bool check_waiting)
M
Mikulas Patocka 已提交
1210 1211 1212 1213
{
	struct rb_node **n = &ic->in_progress.rb_node;
	struct rb_node *parent;

1214 1215
	BUG_ON((new_range->logical_sector | new_range->n_sectors) & (unsigned)(ic->sectors_per_block - 1));

1216 1217 1218 1219 1220 1221 1222 1223
	if (likely(check_waiting)) {
		struct dm_integrity_range *range;
		list_for_each_entry(range, &ic->wait_list, wait_entry) {
			if (unlikely(ranges_overlap(range, new_range)))
				return false;
		}
	}

M
Mikulas Patocka 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
	parent = NULL;

	while (*n) {
		struct dm_integrity_range *range = container_of(*n, struct dm_integrity_range, node);

		parent = *n;
		if (new_range->logical_sector + new_range->n_sectors <= range->logical_sector) {
			n = &range->node.rb_left;
		} else if (new_range->logical_sector >= range->logical_sector + range->n_sectors) {
			n = &range->node.rb_right;
		} else {
			return false;
		}
	}

	rb_link_node(&new_range->node, parent, n);
	rb_insert_color(&new_range->node, &ic->in_progress);

	return true;
}

static void remove_range_unlocked(struct dm_integrity_c *ic, struct dm_integrity_range *range)
{
	rb_erase(&range->node, &ic->in_progress);
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	while (unlikely(!list_empty(&ic->wait_list))) {
		struct dm_integrity_range *last_range =
			list_first_entry(&ic->wait_list, struct dm_integrity_range, wait_entry);
		struct task_struct *last_range_task;
		last_range_task = last_range->task;
		list_del(&last_range->wait_entry);
		if (!add_new_range(ic, last_range, false)) {
			last_range->task = last_range_task;
			list_add(&last_range->wait_entry, &ic->wait_list);
			break;
		}
		last_range->waiting = false;
		wake_up_process(last_range_task);
	}
M
Mikulas Patocka 已提交
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
}

static void remove_range(struct dm_integrity_c *ic, struct dm_integrity_range *range)
{
	unsigned long flags;

	spin_lock_irqsave(&ic->endio_wait.lock, flags);
	remove_range_unlocked(ic, range);
	spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
}

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
static void wait_and_add_new_range(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
{
	new_range->waiting = true;
	list_add_tail(&new_range->wait_entry, &ic->wait_list);
	new_range->task = current;
	do {
		__set_current_state(TASK_UNINTERRUPTIBLE);
		spin_unlock_irq(&ic->endio_wait.lock);
		io_schedule();
		spin_lock_irq(&ic->endio_wait.lock);
	} while (unlikely(new_range->waiting));
}

1286 1287 1288 1289 1290 1291
static void add_new_range_and_wait(struct dm_integrity_c *ic, struct dm_integrity_range *new_range)
{
	if (unlikely(!add_new_range(ic, new_range, true)))
		wait_and_add_new_range(ic, new_range);
}

M
Mikulas Patocka 已提交
1292 1293 1294 1295 1296 1297 1298 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 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 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 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
static void init_journal_node(struct journal_node *node)
{
	RB_CLEAR_NODE(&node->node);
	node->sector = (sector_t)-1;
}

static void add_journal_node(struct dm_integrity_c *ic, struct journal_node *node, sector_t sector)
{
	struct rb_node **link;
	struct rb_node *parent;

	node->sector = sector;
	BUG_ON(!RB_EMPTY_NODE(&node->node));

	link = &ic->journal_tree_root.rb_node;
	parent = NULL;

	while (*link) {
		struct journal_node *j;
		parent = *link;
		j = container_of(parent, struct journal_node, node);
		if (sector < j->sector)
			link = &j->node.rb_left;
		else
			link = &j->node.rb_right;
	}

	rb_link_node(&node->node, parent, link);
	rb_insert_color(&node->node, &ic->journal_tree_root);
}

static void remove_journal_node(struct dm_integrity_c *ic, struct journal_node *node)
{
	BUG_ON(RB_EMPTY_NODE(&node->node));
	rb_erase(&node->node, &ic->journal_tree_root);
	init_journal_node(node);
}

#define NOT_FOUND	(-1U)

static unsigned find_journal_node(struct dm_integrity_c *ic, sector_t sector, sector_t *next_sector)
{
	struct rb_node *n = ic->journal_tree_root.rb_node;
	unsigned found = NOT_FOUND;
	*next_sector = (sector_t)-1;
	while (n) {
		struct journal_node *j = container_of(n, struct journal_node, node);
		if (sector == j->sector) {
			found = j - ic->journal_tree;
		}
		if (sector < j->sector) {
			*next_sector = j->sector;
			n = j->node.rb_left;
		} else {
			n = j->node.rb_right;
		}
	}

	return found;
}

static bool test_journal_node(struct dm_integrity_c *ic, unsigned pos, sector_t sector)
{
	struct journal_node *node, *next_node;
	struct rb_node *next;

	if (unlikely(pos >= ic->journal_entries))
		return false;
	node = &ic->journal_tree[pos];
	if (unlikely(RB_EMPTY_NODE(&node->node)))
		return false;
	if (unlikely(node->sector != sector))
		return false;

	next = rb_next(&node->node);
	if (unlikely(!next))
		return true;

	next_node = container_of(next, struct journal_node, node);
	return next_node->sector != sector;
}

static bool find_newer_committed_node(struct dm_integrity_c *ic, struct journal_node *node)
{
	struct rb_node *next;
	struct journal_node *next_node;
	unsigned next_section;

	BUG_ON(RB_EMPTY_NODE(&node->node));

	next = rb_next(&node->node);
	if (unlikely(!next))
		return false;

	next_node = container_of(next, struct journal_node, node);

	if (next_node->sector != node->sector)
		return false;

	next_section = (unsigned)(next_node - ic->journal_tree) / ic->journal_section_entries;
	if (next_section >= ic->committed_section &&
	    next_section < ic->committed_section + ic->n_committed_sections)
		return true;
	if (next_section + ic->journal_sections < ic->committed_section + ic->n_committed_sections)
		return true;

	return false;
}

#define TAG_READ	0
#define TAG_WRITE	1
#define TAG_CMP		2

static int dm_integrity_rw_tag(struct dm_integrity_c *ic, unsigned char *tag, sector_t *metadata_block,
			       unsigned *metadata_offset, unsigned total_size, int op)
{
1408 1409 1410 1411 1412
#define MAY_BE_FILLER		1
#define MAY_BE_HASH		2
	unsigned hash_offset = 0;
	unsigned may_be = MAY_BE_HASH | (ic->discard ? MAY_BE_FILLER : 0);

M
Mikulas Patocka 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
	do {
		unsigned char *data, *dp;
		struct dm_buffer *b;
		unsigned to_copy;
		int r;

		r = dm_integrity_failed(ic);
		if (unlikely(r))
			return r;

		data = dm_bufio_read(ic->bufio, *metadata_block, &b);
1424
		if (IS_ERR(data))
M
Mikulas Patocka 已提交
1425 1426 1427 1428 1429 1430 1431 1432
			return PTR_ERR(data);

		to_copy = min((1U << SECTOR_SHIFT << ic->log2_buffer_sectors) - *metadata_offset, total_size);
		dp = data + *metadata_offset;
		if (op == TAG_READ) {
			memcpy(tag, dp, to_copy);
		} else if (op == TAG_WRITE) {
			memcpy(dp, tag, to_copy);
1433
			dm_bufio_mark_partial_buffer_dirty(b, *metadata_offset, *metadata_offset + to_copy);
1434
		} else {
M
Mikulas Patocka 已提交
1435 1436
			/* e.g.: op == TAG_CMP */

1437 1438 1439
			if (likely(is_power_of_2(ic->tag_size))) {
				if (unlikely(memcmp(dp, tag, to_copy)))
					if (unlikely(!ic->discard) ||
1440
					    unlikely(memchr_inv(dp, DISCARD_FILLER, to_copy) != NULL)) {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
						goto thorough_test;
				}
			} else {
				unsigned i, ts;
thorough_test:
				ts = total_size;

				for (i = 0; i < to_copy; i++, ts--) {
					if (unlikely(dp[i] != tag[i]))
						may_be &= ~MAY_BE_HASH;
					if (likely(dp[i] != DISCARD_FILLER))
						may_be &= ~MAY_BE_FILLER;
					hash_offset++;
					if (unlikely(hash_offset == ic->tag_size)) {
						if (unlikely(!may_be)) {
							dm_bufio_release(b);
							return ts;
						}
						hash_offset = 0;
						may_be = MAY_BE_HASH | (ic->discard ? MAY_BE_FILLER : 0);
					}
M
Mikulas Patocka 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
				}
			}
		}
		dm_bufio_release(b);

		tag += to_copy;
		*metadata_offset += to_copy;
		if (unlikely(*metadata_offset == 1U << SECTOR_SHIFT << ic->log2_buffer_sectors)) {
			(*metadata_block)++;
			*metadata_offset = 0;
		}
1473 1474 1475 1476 1477

		if (unlikely(!is_power_of_2(ic->tag_size))) {
			hash_offset = (hash_offset + to_copy) % ic->tag_size;
		}

M
Mikulas Patocka 已提交
1478 1479 1480 1481
		total_size -= to_copy;
	} while (unlikely(total_size));

	return 0;
1482 1483
#undef MAY_BE_FILLER
#undef MAY_BE_HASH
M
Mikulas Patocka 已提交
1484 1485
}

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
struct flush_request {
	struct dm_io_request io_req;
	struct dm_io_region io_reg;
	struct dm_integrity_c *ic;
	struct completion comp;
};

static void flush_notify(unsigned long error, void *fr_)
{
	struct flush_request *fr = fr_;
	if (unlikely(error != 0))
1497
		dm_integrity_io_error(fr->ic, "flushing disk cache", -EIO);
1498 1499 1500 1501
	complete(&fr->comp);
}

static void dm_integrity_flush_buffers(struct dm_integrity_c *ic, bool flush_data)
M
Mikulas Patocka 已提交
1502 1503
{
	int r;
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525

	struct flush_request fr;

	if (!ic->meta_dev)
		flush_data = false;
	if (flush_data) {
		fr.io_req.bi_op = REQ_OP_WRITE,
		fr.io_req.bi_op_flags = REQ_PREFLUSH | REQ_SYNC,
		fr.io_req.mem.type = DM_IO_KMEM,
		fr.io_req.mem.ptr.addr = NULL,
		fr.io_req.notify.fn = flush_notify,
		fr.io_req.notify.context = &fr;
		fr.io_req.client = dm_bufio_get_dm_io_client(ic->bufio),
		fr.io_reg.bdev = ic->dev->bdev,
		fr.io_reg.sector = 0,
		fr.io_reg.count = 0,
		fr.ic = ic;
		init_completion(&fr.comp);
		r = dm_io(&fr.io_req, 1, &fr.io_reg, NULL);
		BUG_ON(r);
	}

M
Mikulas Patocka 已提交
1526 1527 1528
	r = dm_bufio_write_dirty_buffers(ic->bufio);
	if (unlikely(r))
		dm_integrity_io_error(ic, "writing tags", r);
1529 1530 1531

	if (flush_data)
		wait_for_completion(&fr.comp);
M
Mikulas Patocka 已提交
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
}

static void sleep_on_endio_wait(struct dm_integrity_c *ic)
{
	DECLARE_WAITQUEUE(wait, current);
	__add_wait_queue(&ic->endio_wait, &wait);
	__set_current_state(TASK_UNINTERRUPTIBLE);
	spin_unlock_irq(&ic->endio_wait.lock);
	io_schedule();
	spin_lock_irq(&ic->endio_wait.lock);
	__remove_wait_queue(&ic->endio_wait, &wait);
}

1545
static void autocommit_fn(struct timer_list *t)
M
Mikulas Patocka 已提交
1546
{
1547
	struct dm_integrity_c *ic = from_timer(ic, t, autocommit_timer);
M
Mikulas Patocka 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

	if (likely(!dm_integrity_failed(ic)))
		queue_work(ic->commit_wq, &ic->commit_work);
}

static void schedule_autocommit(struct dm_integrity_c *ic)
{
	if (!timer_pending(&ic->autocommit_timer))
		mod_timer(&ic->autocommit_timer, jiffies + ic->autocommit_jiffies);
}

static void submit_flush_bio(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
{
	struct bio *bio;
1562 1563 1564
	unsigned long flags;

	spin_lock_irqsave(&ic->endio_wait.lock, flags);
M
Mikulas Patocka 已提交
1565 1566
	bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
	bio_list_add(&ic->flush_bio_list, bio);
1567 1568
	spin_unlock_irqrestore(&ic->endio_wait.lock, flags);

M
Mikulas Patocka 已提交
1569 1570 1571 1572 1573 1574
	queue_work(ic->commit_wq, &ic->commit_work);
}

static void do_endio(struct dm_integrity_c *ic, struct bio *bio)
{
	int r = dm_integrity_failed(ic);
1575 1576
	if (unlikely(r) && !bio->bi_status)
		bio->bi_status = errno_to_blk_status(r);
1577 1578 1579 1580 1581 1582 1583 1584
	if (unlikely(ic->synchronous_mode) && bio_op(bio) == REQ_OP_WRITE) {
		unsigned long flags;
		spin_lock_irqsave(&ic->endio_wait.lock, flags);
		bio_list_add(&ic->synchronous_bios, bio);
		queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
		spin_unlock_irqrestore(&ic->endio_wait.lock, flags);
		return;
	}
M
Mikulas Patocka 已提交
1585 1586 1587 1588 1589 1590 1591
	bio_endio(bio);
}

static void do_endio_flush(struct dm_integrity_c *ic, struct dm_integrity_io *dio)
{
	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));

1592
	if (unlikely(dio->fua) && likely(!bio->bi_status) && likely(!dm_integrity_failed(ic)))
M
Mikulas Patocka 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
		submit_flush_bio(ic, dio);
	else
		do_endio(ic, bio);
}

static void dec_in_flight(struct dm_integrity_io *dio)
{
	if (atomic_dec_and_test(&dio->in_flight)) {
		struct dm_integrity_c *ic = dio->ic;
		struct bio *bio;

		remove_range(ic, &dio->range);

1606
		if (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))
M
Mikulas Patocka 已提交
1607 1608 1609 1610
			schedule_autocommit(ic);

		bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));

1611 1612 1613
		if (unlikely(dio->bi_status) && !bio->bi_status)
			bio->bi_status = dio->bi_status;
		if (likely(!bio->bi_status) && unlikely(bio_sectors(bio) != dio->range.n_sectors)) {
M
Mikulas Patocka 已提交
1614 1615 1616
			dio->range.logical_sector += dio->range.n_sectors;
			bio_advance(bio, dio->range.n_sectors << SECTOR_SHIFT);
			INIT_WORK(&dio->work, integrity_bio_wait);
1617
			queue_work(ic->offload_wq, &dio->work);
M
Mikulas Patocka 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
			return;
		}
		do_endio_flush(ic, dio);
	}
}

static void integrity_end_io(struct bio *bio)
{
	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));

1628 1629
	dm_bio_restore(&dio->bio_details, bio);
	if (bio->bi_integrity)
M
Mikulas Patocka 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
		bio->bi_opf |= REQ_INTEGRITY;

	if (dio->completion)
		complete(dio->completion);

	dec_in_flight(dio);
}

static void integrity_sector_checksum(struct dm_integrity_c *ic, sector_t sector,
				      const char *data, char *result)
{
	__u64 sector_le = cpu_to_le64(sector);
	SHASH_DESC_ON_STACK(req, ic->internal_hash);
	int r;
	unsigned digest_size;

	req->tfm = ic->internal_hash;

	r = crypto_shash_init(req);
	if (unlikely(r < 0)) {
		dm_integrity_io_error(ic, "crypto_shash_init", r);
		goto failed;
	}

1654 1655 1656 1657 1658 1659 1660 1661
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) {
		r = crypto_shash_update(req, (__u8 *)&ic->sb->salt, SALT_SIZE);
		if (unlikely(r < 0)) {
			dm_integrity_io_error(ic, "crypto_shash_update", r);
			goto failed;
		}
	}

M
Mikulas Patocka 已提交
1662 1663 1664 1665 1666 1667
	r = crypto_shash_update(req, (const __u8 *)&sector_le, sizeof sector_le);
	if (unlikely(r < 0)) {
		dm_integrity_io_error(ic, "crypto_shash_update", r);
		goto failed;
	}

1668
	r = crypto_shash_update(req, data, ic->sectors_per_block << SECTOR_SHIFT);
M
Mikulas Patocka 已提交
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
	if (unlikely(r < 0)) {
		dm_integrity_io_error(ic, "crypto_shash_update", r);
		goto failed;
	}

	r = crypto_shash_final(req, result);
	if (unlikely(r < 0)) {
		dm_integrity_io_error(ic, "crypto_shash_final", r);
		goto failed;
	}

	digest_size = crypto_shash_digestsize(ic->internal_hash);
	if (unlikely(digest_size < ic->tag_size))
		memset(result + digest_size, 0, ic->tag_size - digest_size);

	return;

failed:
	/* this shouldn't happen anyway, the hash functions have no reason to fail */
	get_random_bytes(result, ic->tag_size);
}

static void integrity_metadata(struct work_struct *w)
{
	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);
	struct dm_integrity_c *ic = dio->ic;

	int r;

	if (ic->internal_hash) {
		struct bvec_iter iter;
		struct bio_vec bv;
		unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
		struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
		char *checksums;
1704
		unsigned extra_space = unlikely(digest_size > ic->tag_size) ? digest_size - ic->tag_size : 0;
1705
		char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
1706 1707
		sector_t sector;
		unsigned sectors_to_process;
M
Mikulas Patocka 已提交
1708

1709 1710 1711
		if (unlikely(ic->mode == 'R'))
			goto skip_io;

1712 1713 1714 1715 1716
		if (likely(dio->op != REQ_OP_DISCARD))
			checksums = kmalloc((PAGE_SIZE >> SECTOR_SHIFT >> ic->sb->log2_sectors_per_block) * ic->tag_size + extra_space,
					    GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
		else
			checksums = kmalloc(PAGE_SIZE, GFP_NOIO | __GFP_NORETRY | __GFP_NOWARN);
K
Kees Cook 已提交
1717
		if (!checksums) {
M
Mikulas Patocka 已提交
1718
			checksums = checksums_onstack;
K
Kees Cook 已提交
1719 1720 1721 1722 1723 1724
			if (WARN_ON(extra_space &&
				    digest_size > sizeof(checksums_onstack))) {
				r = -EINVAL;
				goto error;
			}
		}
M
Mikulas Patocka 已提交
1725

1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
		if (unlikely(dio->op == REQ_OP_DISCARD)) {
			sector_t bi_sector = dio->bio_details.bi_iter.bi_sector;
			unsigned bi_size = dio->bio_details.bi_iter.bi_size;
			unsigned max_size = likely(checksums != checksums_onstack) ? PAGE_SIZE : HASH_MAX_DIGESTSIZE;
			unsigned max_blocks = max_size / ic->tag_size;
			memset(checksums, DISCARD_FILLER, max_size);

			while (bi_size) {
				unsigned this_step_blocks = bi_size >> (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
				this_step_blocks = min(this_step_blocks, max_blocks);
				r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
							this_step_blocks * ic->tag_size, TAG_WRITE);
				if (unlikely(r)) {
					if (likely(checksums != checksums_onstack))
						kfree(checksums);
					goto error;
				}

				/*if (bi_size < this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block)) {
					printk("BUGG: bi_sector: %llx, bi_size: %u\n", bi_sector, bi_size);
					printk("BUGG: this_step_blocks: %u\n", this_step_blocks);
					BUG();
				}*/
				bi_size -= this_step_blocks << (SECTOR_SHIFT + ic->sb->log2_sectors_per_block);
				bi_sector += this_step_blocks << ic->sb->log2_sectors_per_block;
			}

			if (likely(checksums != checksums_onstack))
				kfree(checksums);
			goto skip_io;
		}

		sector = dio->range.logical_sector;
		sectors_to_process = dio->range.n_sectors;

1761
		__bio_for_each_segment(bv, bio, iter, dio->bio_details.bi_iter) {
M
Mikulas Patocka 已提交
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
			unsigned pos;
			char *mem, *checksums_ptr;

again:
			mem = (char *)kmap_atomic(bv.bv_page) + bv.bv_offset;
			pos = 0;
			checksums_ptr = checksums;
			do {
				integrity_sector_checksum(ic, sector, mem + pos, checksums_ptr);
				checksums_ptr += ic->tag_size;
1772 1773 1774
				sectors_to_process -= ic->sectors_per_block;
				pos += ic->sectors_per_block << SECTOR_SHIFT;
				sector += ic->sectors_per_block;
M
Mikulas Patocka 已提交
1775 1776 1777 1778
			} while (pos < bv.bv_len && sectors_to_process && checksums != checksums_onstack);
			kunmap_atomic(mem);

			r = dm_integrity_rw_tag(ic, checksums, &dio->metadata_block, &dio->metadata_offset,
1779
						checksums_ptr - checksums, dio->op == REQ_OP_READ ? TAG_CMP : TAG_WRITE);
M
Mikulas Patocka 已提交
1780 1781
			if (unlikely(r)) {
				if (r > 0) {
1782 1783
					char b[BDEVNAME_SIZE];
					DMERR_LIMIT("%s: Checksum failed at sector 0x%llx", bio_devname(bio, b),
1784
						    (sector - ((r + ic->tag_size - 1) / ic->tag_size)));
M
Mikulas Patocka 已提交
1785
					r = -EILSEQ;
1786
					atomic64_inc(&ic->number_of_mismatches);
M
Mikulas Patocka 已提交
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
				}
				if (likely(checksums != checksums_onstack))
					kfree(checksums);
				goto error;
			}

			if (!sectors_to_process)
				break;

			if (unlikely(pos < bv.bv_len)) {
				bv.bv_offset += pos;
				bv.bv_len -= pos;
				goto again;
			}
		}

		if (likely(checksums != checksums_onstack))
			kfree(checksums);
	} else {
1806
		struct bio_integrity_payload *bip = dio->bio_details.bi_integrity;
M
Mikulas Patocka 已提交
1807 1808 1809 1810

		if (bip) {
			struct bio_vec biv;
			struct bvec_iter iter;
1811 1812 1813
			unsigned data_to_process = dio->range.n_sectors;
			sector_to_block(ic, data_to_process);
			data_to_process *= ic->tag_size;
M
Mikulas Patocka 已提交
1814 1815 1816 1817 1818 1819 1820 1821 1822

			bip_for_each_vec(biv, bip, iter) {
				unsigned char *tag;
				unsigned this_len;

				BUG_ON(PageHighMem(biv.bv_page));
				tag = lowmem_page_address(biv.bv_page) + biv.bv_offset;
				this_len = min(biv.bv_len, data_to_process);
				r = dm_integrity_rw_tag(ic, tag, &dio->metadata_block, &dio->metadata_offset,
1823
							this_len, dio->op == REQ_OP_READ ? TAG_READ : TAG_WRITE);
M
Mikulas Patocka 已提交
1824 1825 1826 1827 1828 1829 1830 1831
				if (unlikely(r))
					goto error;
				data_to_process -= this_len;
				if (!data_to_process)
					break;
			}
		}
	}
1832
skip_io:
M
Mikulas Patocka 已提交
1833 1834 1835
	dec_in_flight(dio);
	return;
error:
1836
	dio->bi_status = errno_to_blk_status(r);
M
Mikulas Patocka 已提交
1837 1838 1839 1840 1841 1842 1843
	dec_in_flight(dio);
}

static int dm_integrity_map(struct dm_target *ti, struct bio *bio)
{
	struct dm_integrity_c *ic = ti->private;
	struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));
1844
	struct bio_integrity_payload *bip;
M
Mikulas Patocka 已提交
1845 1846 1847 1848

	sector_t area, offset;

	dio->ic = ic;
1849
	dio->bi_status = 0;
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
	dio->op = bio_op(bio);

	if (unlikely(dio->op == REQ_OP_DISCARD)) {
		if (ti->max_io_len) {
			sector_t sec = dm_target_offset(ti, bio->bi_iter.bi_sector);
			unsigned log2_max_io_len = __fls(ti->max_io_len);
			sector_t start_boundary = sec >> log2_max_io_len;
			sector_t end_boundary = (sec + bio_sectors(bio) - 1) >> log2_max_io_len;
			if (start_boundary < end_boundary) {
				sector_t len = ti->max_io_len - (sec & (ti->max_io_len - 1));
				dm_accept_partial_bio(bio, len);
			}
		}
	}
M
Mikulas Patocka 已提交
1864 1865 1866 1867 1868 1869 1870

	if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
		submit_flush_bio(ic, dio);
		return DM_MAPIO_SUBMITTED;
	}

	dio->range.logical_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
1871
	dio->fua = dio->op == REQ_OP_WRITE && bio->bi_opf & REQ_FUA;
M
Mikulas Patocka 已提交
1872 1873 1874 1875 1876 1877 1878 1879 1880
	if (unlikely(dio->fua)) {
		/*
		 * Don't pass down the FUA flag because we have to flush
		 * disk cache anyway.
		 */
		bio->bi_opf &= ~REQ_FUA;
	}
	if (unlikely(dio->range.logical_sector + bio_sectors(bio) > ic->provided_data_sectors)) {
		DMERR("Too big sector number: 0x%llx + 0x%x > 0x%llx",
1881 1882
		      dio->range.logical_sector, bio_sectors(bio),
		      ic->provided_data_sectors);
1883
		return DM_MAPIO_KILL;
M
Mikulas Patocka 已提交
1884
	}
1885 1886 1887
	if (unlikely((dio->range.logical_sector | bio_sectors(bio)) & (unsigned)(ic->sectors_per_block - 1))) {
		DMERR("Bio not aligned on %u sectors: 0x%llx, 0x%x",
		      ic->sectors_per_block,
1888
		      dio->range.logical_sector, bio_sectors(bio));
1889
		return DM_MAPIO_KILL;
1890 1891
	}

1892
	if (ic->sectors_per_block > 1 && likely(dio->op != REQ_OP_DISCARD)) {
1893 1894 1895
		struct bvec_iter iter;
		struct bio_vec bv;
		bio_for_each_segment(bv, bio, iter) {
1896
			if (unlikely(bv.bv_len & ((ic->sectors_per_block << SECTOR_SHIFT) - 1))) {
1897 1898
				DMERR("Bio vector (%u,%u) is not aligned on %u-sector boundary",
					bv.bv_offset, bv.bv_len, ic->sectors_per_block);
1899
				return DM_MAPIO_KILL;
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
			}
		}
	}

	bip = bio_integrity(bio);
	if (!ic->internal_hash) {
		if (bip) {
			unsigned wanted_tag_size = bio_sectors(bio) >> ic->sb->log2_sectors_per_block;
			if (ic->log2_tag_size >= 0)
				wanted_tag_size <<= ic->log2_tag_size;
			else
				wanted_tag_size *= ic->tag_size;
			if (unlikely(wanted_tag_size != bip->bip_iter.bi_size)) {
1913 1914
				DMERR("Invalid integrity data size %u, expected %u",
				      bip->bip_iter.bi_size, wanted_tag_size);
1915
				return DM_MAPIO_KILL;
1916 1917 1918 1919 1920
			}
		}
	} else {
		if (unlikely(bip != NULL)) {
			DMERR("Unexpected integrity data when using internal hash");
1921
			return DM_MAPIO_KILL;
1922 1923
		}
	}
M
Mikulas Patocka 已提交
1924

1925
	if (unlikely(ic->mode == 'R') && unlikely(dio->op != REQ_OP_READ))
1926
		return DM_MAPIO_KILL;
1927

M
Mikulas Patocka 已提交
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
	get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
	dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
	bio->bi_iter.bi_sector = get_data_sector(ic, area, offset);

	dm_integrity_map_continue(dio, true);
	return DM_MAPIO_SUBMITTED;
}

static bool __journal_read_write(struct dm_integrity_io *dio, struct bio *bio,
				 unsigned journal_section, unsigned journal_entry)
{
	struct dm_integrity_c *ic = dio->ic;
	sector_t logical_sector;
	unsigned n_sectors;

	logical_sector = dio->range.logical_sector;
	n_sectors = dio->range.n_sectors;
	do {
		struct bio_vec bv = bio_iovec(bio);
		char *mem;

		if (unlikely(bv.bv_len >> SECTOR_SHIFT > n_sectors))
			bv.bv_len = n_sectors << SECTOR_SHIFT;
		n_sectors -= bv.bv_len >> SECTOR_SHIFT;
		bio_advance_iter(bio, &bio->bi_iter, bv.bv_len);
retry_kmap:
		mem = kmap_atomic(bv.bv_page);
1955
		if (likely(dio->op == REQ_OP_WRITE))
M
Mikulas Patocka 已提交
1956 1957 1958 1959 1960
			flush_dcache_page(bv.bv_page);

		do {
			struct journal_entry *je = access_journal_entry(ic, journal_section, journal_entry);

1961
			if (unlikely(dio->op == REQ_OP_READ)) {
M
Mikulas Patocka 已提交
1962
				struct journal_sector *js;
1963 1964
				char *mem_ptr;
				unsigned s;
M
Mikulas Patocka 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975

				if (unlikely(journal_entry_is_inprogress(je))) {
					flush_dcache_page(bv.bv_page);
					kunmap_atomic(mem);

					__io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
					goto retry_kmap;
				}
				smp_rmb();
				BUG_ON(journal_entry_get_sector(je) != logical_sector);
				js = access_journal_data(ic, journal_section, journal_entry);
1976 1977 1978 1979 1980 1981 1982 1983
				mem_ptr = mem + bv.bv_offset;
				s = 0;
				do {
					memcpy(mem_ptr, js, JOURNAL_SECTOR_DATA);
					*(commit_id_t *)(mem_ptr + JOURNAL_SECTOR_DATA) = je->last_bytes[s];
					js++;
					mem_ptr += 1 << SECTOR_SHIFT;
				} while (++s < ic->sectors_per_block);
M
Mikulas Patocka 已提交
1984 1985
#ifdef INTERNAL_VERIFY
				if (ic->internal_hash) {
1986
					char checksums_onstack[max((size_t)HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
M
Mikulas Patocka 已提交
1987 1988

					integrity_sector_checksum(ic, logical_sector, mem + bv.bv_offset, checksums_onstack);
1989
					if (unlikely(memcmp(checksums_onstack, journal_entry_tag(ic, je), ic->tag_size))) {
1990
						DMERR_LIMIT("Checksum failed when reading from journal, at sector 0x%llx",
1991
							    logical_sector);
M
Mikulas Patocka 已提交
1992 1993 1994 1995 1996 1997 1998 1999
					}
				}
#endif
			}

			if (!ic->internal_hash) {
				struct bio_integrity_payload *bip = bio_integrity(bio);
				unsigned tag_todo = ic->tag_size;
2000
				char *tag_ptr = journal_entry_tag(ic, je);
M
Mikulas Patocka 已提交
2001 2002 2003 2004 2005 2006 2007

				if (bip) do {
					struct bio_vec biv = bvec_iter_bvec(bip->bip_vec, bip->bip_iter);
					unsigned tag_now = min(biv.bv_len, tag_todo);
					char *tag_addr;
					BUG_ON(PageHighMem(biv.bv_page));
					tag_addr = lowmem_page_address(biv.bv_page) + biv.bv_offset;
2008
					if (likely(dio->op == REQ_OP_WRITE))
M
Mikulas Patocka 已提交
2009 2010 2011 2012 2013 2014 2015
						memcpy(tag_ptr, tag_addr, tag_now);
					else
						memcpy(tag_addr, tag_ptr, tag_now);
					bvec_iter_advance(bip->bip_vec, &bip->bip_iter, tag_now);
					tag_ptr += tag_now;
					tag_todo -= tag_now;
				} while (unlikely(tag_todo)); else {
2016
					if (likely(dio->op == REQ_OP_WRITE))
M
Mikulas Patocka 已提交
2017 2018 2019 2020
						memset(tag_ptr, 0, tag_todo);
				}
			}

2021
			if (likely(dio->op == REQ_OP_WRITE)) {
M
Mikulas Patocka 已提交
2022
				struct journal_sector *js;
2023
				unsigned s;
M
Mikulas Patocka 已提交
2024 2025

				js = access_journal_data(ic, journal_section, journal_entry);
2026 2027 2028 2029 2030 2031
				memcpy(js, mem + bv.bv_offset, ic->sectors_per_block << SECTOR_SHIFT);

				s = 0;
				do {
					je->last_bytes[s] = js[s].commit_id;
				} while (++s < ic->sectors_per_block);
M
Mikulas Patocka 已提交
2032 2033 2034 2035

				if (ic->internal_hash) {
					unsigned digest_size = crypto_shash_digestsize(ic->internal_hash);
					if (unlikely(digest_size > ic->tag_size)) {
K
Kees Cook 已提交
2036
						char checksums_onstack[HASH_MAX_DIGESTSIZE];
M
Mikulas Patocka 已提交
2037
						integrity_sector_checksum(ic, logical_sector, (char *)js, checksums_onstack);
2038
						memcpy(journal_entry_tag(ic, je), checksums_onstack, ic->tag_size);
M
Mikulas Patocka 已提交
2039
					} else
2040
						integrity_sector_checksum(ic, logical_sector, (char *)js, journal_entry_tag(ic, je));
M
Mikulas Patocka 已提交
2041 2042 2043 2044
				}

				journal_entry_set_sector(je, logical_sector);
			}
2045
			logical_sector += ic->sectors_per_block;
M
Mikulas Patocka 已提交
2046 2047 2048 2049 2050 2051 2052 2053

			journal_entry++;
			if (unlikely(journal_entry == ic->journal_section_entries)) {
				journal_entry = 0;
				journal_section++;
				wraparound_section(ic, &journal_section);
			}

2054 2055
			bv.bv_offset += ic->sectors_per_block << SECTOR_SHIFT;
		} while (bv.bv_len -= ic->sectors_per_block << SECTOR_SHIFT);
M
Mikulas Patocka 已提交
2056

2057
		if (unlikely(dio->op == REQ_OP_READ))
M
Mikulas Patocka 已提交
2058 2059 2060 2061
			flush_dcache_page(bv.bv_page);
		kunmap_atomic(mem);
	} while (n_sectors);

2062
	if (likely(dio->op == REQ_OP_WRITE)) {
M
Mikulas Patocka 已提交
2063 2064 2065
		smp_mb();
		if (unlikely(waitqueue_active(&ic->copy_to_journal_wait)))
			wake_up(&ic->copy_to_journal_wait);
2066
		if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold) {
M
Mikulas Patocka 已提交
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
			queue_work(ic->commit_wq, &ic->commit_work);
		} else {
			schedule_autocommit(ic);
		}
	} else {
		remove_range(ic, &dio->range);
	}

	if (unlikely(bio->bi_iter.bi_size)) {
		sector_t area, offset;

		dio->range.logical_sector = logical_sector;
		get_area_and_offset(ic, dio->range.logical_sector, &area, &offset);
		dio->metadata_block = get_metadata_sector_and_offset(ic, area, offset, &dio->metadata_offset);
		return true;
	}

	return false;
}

static void dm_integrity_map_continue(struct dm_integrity_io *dio, bool from_map)
{
	struct dm_integrity_c *ic = dio->ic;
	struct bio *bio = dm_bio_from_per_bio_data(dio, sizeof(struct dm_integrity_io));
	unsigned journal_section, journal_entry;
	unsigned journal_read_pos;
	struct completion read_comp;
2094
	bool discard_retried = false;
2095 2096 2097
	bool need_sync_io = ic->internal_hash && dio->op == REQ_OP_READ;
	if (unlikely(dio->op == REQ_OP_DISCARD) && ic->mode != 'D')
		need_sync_io = true;
M
Mikulas Patocka 已提交
2098 2099 2100

	if (need_sync_io && from_map) {
		INIT_WORK(&dio->work, integrity_bio_wait);
2101
		queue_work(ic->offload_wq, &dio->work);
M
Mikulas Patocka 已提交
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
		return;
	}

lock_retry:
	spin_lock_irq(&ic->endio_wait.lock);
retry:
	if (unlikely(dm_integrity_failed(ic))) {
		spin_unlock_irq(&ic->endio_wait.lock);
		do_endio(ic, bio);
		return;
	}
	dio->range.n_sectors = bio_sectors(bio);
	journal_read_pos = NOT_FOUND;
2115 2116
	if (ic->mode == 'J' && likely(dio->op != REQ_OP_DISCARD)) {
		if (dio->op == REQ_OP_WRITE) {
M
Mikulas Patocka 已提交
2117
			unsigned next_entry, i, pos;
2118
			unsigned ws, we, range_sectors;
M
Mikulas Patocka 已提交
2119

2120
			dio->range.n_sectors = min(dio->range.n_sectors,
2121
						   (sector_t)ic->free_sectors << ic->sb->log2_sectors_per_block);
2122 2123 2124 2125 2126 2127
			if (unlikely(!dio->range.n_sectors)) {
				if (from_map)
					goto offload_to_thread;
				sleep_on_endio_wait(ic);
				goto retry;
			}
2128 2129
			range_sectors = dio->range.n_sectors >> ic->sb->log2_sectors_per_block;
			ic->free_sectors -= range_sectors;
M
Mikulas Patocka 已提交
2130 2131 2132
			journal_section = ic->free_section;
			journal_entry = ic->free_section_entry;

2133
			next_entry = ic->free_section_entry + range_sectors;
M
Mikulas Patocka 已提交
2134 2135 2136 2137 2138 2139 2140 2141
			ic->free_section_entry = next_entry % ic->journal_section_entries;
			ic->free_section += next_entry / ic->journal_section_entries;
			ic->n_uncommitted_sections += next_entry / ic->journal_section_entries;
			wraparound_section(ic, &ic->free_section);

			pos = journal_section * ic->journal_section_entries + journal_entry;
			ws = journal_section;
			we = journal_entry;
2142 2143
			i = 0;
			do {
M
Mikulas Patocka 已提交
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
				struct journal_entry *je;

				add_journal_node(ic, &ic->journal_tree[pos], dio->range.logical_sector + i);
				pos++;
				if (unlikely(pos >= ic->journal_entries))
					pos = 0;

				je = access_journal_entry(ic, ws, we);
				BUG_ON(!journal_entry_is_unused(je));
				journal_entry_set_inprogress(je);
				we++;
				if (unlikely(we == ic->journal_section_entries)) {
					we = 0;
					ws++;
					wraparound_section(ic, &ws);
				}
2160
			} while ((i += ic->sectors_per_block) < dio->range.n_sectors);
M
Mikulas Patocka 已提交
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171

			spin_unlock_irq(&ic->endio_wait.lock);
			goto journal_read_write;
		} else {
			sector_t next_sector;
			journal_read_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
			if (likely(journal_read_pos == NOT_FOUND)) {
				if (unlikely(dio->range.n_sectors > next_sector - dio->range.logical_sector))
					dio->range.n_sectors = next_sector - dio->range.logical_sector;
			} else {
				unsigned i;
2172 2173 2174
				unsigned jp = journal_read_pos + 1;
				for (i = ic->sectors_per_block; i < dio->range.n_sectors; i += ic->sectors_per_block, jp++) {
					if (!test_journal_node(ic, jp, dio->range.logical_sector + i))
M
Mikulas Patocka 已提交
2175 2176 2177 2178 2179 2180
						break;
				}
				dio->range.n_sectors = i;
			}
		}
	}
2181
	if (unlikely(!add_new_range(ic, &dio->range, true))) {
M
Mikulas Patocka 已提交
2182 2183 2184 2185 2186 2187
		/*
		 * We must not sleep in the request routine because it could
		 * stall bios on current->bio_list.
		 * So, we offload the bio to a workqueue if we have to sleep.
		 */
		if (from_map) {
2188
offload_to_thread:
M
Mikulas Patocka 已提交
2189 2190 2191 2192 2193
			spin_unlock_irq(&ic->endio_wait.lock);
			INIT_WORK(&dio->work, integrity_bio_wait);
			queue_work(ic->wait_wq, &dio->work);
			return;
		}
2194 2195
		if (journal_read_pos != NOT_FOUND)
			dio->range.n_sectors = ic->sectors_per_block;
2196
		wait_and_add_new_range(ic, &dio->range);
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
		/*
		 * wait_and_add_new_range drops the spinlock, so the journal
		 * may have been changed arbitrarily. We need to recheck.
		 * To simplify the code, we restrict I/O size to just one block.
		 */
		if (journal_read_pos != NOT_FOUND) {
			sector_t next_sector;
			unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
			if (unlikely(new_pos != journal_read_pos)) {
				remove_range_unlocked(ic, &dio->range);
				goto retry;
			}
		}
M
Mikulas Patocka 已提交
2210
	}
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
	if (ic->mode == 'J' && likely(dio->op == REQ_OP_DISCARD) && !discard_retried) {
		sector_t next_sector;
		unsigned new_pos = find_journal_node(ic, dio->range.logical_sector, &next_sector);
		if (unlikely(new_pos != NOT_FOUND) ||
		    unlikely(next_sector < dio->range.logical_sector - dio->range.n_sectors)) {
			remove_range_unlocked(ic, &dio->range);
			spin_unlock_irq(&ic->endio_wait.lock);
			queue_work(ic->commit_wq, &ic->commit_work);
			flush_workqueue(ic->commit_wq);
			queue_work(ic->writer_wq, &ic->writer_work);
			flush_workqueue(ic->writer_wq);
			discard_retried = true;
			goto lock_retry;
		}
	}
M
Mikulas Patocka 已提交
2226 2227 2228 2229 2230 2231 2232 2233
	spin_unlock_irq(&ic->endio_wait.lock);

	if (unlikely(journal_read_pos != NOT_FOUND)) {
		journal_section = journal_read_pos / ic->journal_section_entries;
		journal_entry = journal_read_pos % ic->journal_section_entries;
		goto journal_read_write;
	}

2234
	if (ic->mode == 'B' && (dio->op == REQ_OP_WRITE || unlikely(dio->op == REQ_OP_DISCARD))) {
2235 2236 2237
		if (!block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
				     dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
			struct bitmap_block_status *bbs;
2238

2239
			bbs = sector_to_bitmap_block(ic, dio->range.logical_sector);
2240 2241 2242 2243 2244 2245 2246 2247
			spin_lock(&bbs->bio_queue_lock);
			bio_list_add(&bbs->bio_queue, bio);
			spin_unlock(&bbs->bio_queue_lock);
			queue_work(ic->writer_wq, &bbs->work);
			return;
		}
	}

M
Mikulas Patocka 已提交
2248 2249 2250
	dio->in_flight = (atomic_t)ATOMIC_INIT(2);

	if (need_sync_io) {
2251
		init_completion(&read_comp);
M
Mikulas Patocka 已提交
2252 2253 2254 2255
		dio->completion = &read_comp;
	} else
		dio->completion = NULL;

2256
	dm_bio_record(&dio->bio_details, bio);
2257
	bio_set_dev(bio, ic->dev->bdev);
M
Mikulas Patocka 已提交
2258 2259 2260 2261
	bio->bi_integrity = NULL;
	bio->bi_opf &= ~REQ_INTEGRITY;
	bio->bi_end_io = integrity_end_io;
	bio->bi_iter.bi_size = dio->range.n_sectors << SECTOR_SHIFT;
2262

2263 2264
	if (unlikely(dio->op == REQ_OP_DISCARD) && likely(ic->mode != 'D')) {
		integrity_metadata(&dio->work);
2265
		dm_integrity_flush_buffers(ic, false);
2266 2267 2268 2269

		dio->in_flight = (atomic_t)ATOMIC_INIT(1);
		dio->completion = NULL;

2270
		submit_bio_noacct(bio);
2271 2272 2273 2274

		return;
	}

2275
	submit_bio_noacct(bio);
M
Mikulas Patocka 已提交
2276 2277 2278

	if (need_sync_io) {
		wait_for_completion_io(&read_comp);
2279
		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
2280 2281
		    dio->range.logical_sector + dio->range.n_sectors > le64_to_cpu(ic->sb->recalc_sector))
			goto skip_check;
2282
		if (ic->mode == 'B') {
2283 2284
			if (!block_bitmap_op(ic, ic->recalc_bitmap, dio->range.logical_sector,
					     dio->range.n_sectors, BITMAP_OP_TEST_ALL_CLEAR))
2285 2286 2287
				goto skip_check;
		}

2288 2289 2290
		if (likely(!bio->bi_status))
			integrity_metadata(&dio->work);
		else
2291
skip_check:
2292 2293
			dec_in_flight(dio);

M
Mikulas Patocka 已提交
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
	} else {
		INIT_WORK(&dio->work, integrity_metadata);
		queue_work(ic->metadata_wq, &dio->work);
	}

	return;

journal_read_write:
	if (unlikely(__journal_read_write(dio, bio, journal_section, journal_entry)))
		goto lock_retry;

	do_endio_flush(ic, dio);
}


static void integrity_bio_wait(struct work_struct *w)
{
	struct dm_integrity_io *dio = container_of(w, struct dm_integrity_io, work);

	dm_integrity_map_continue(dio, false);
}

static void pad_uncommitted(struct dm_integrity_c *ic)
{
	if (ic->free_section_entry) {
		ic->free_sectors -= ic->journal_section_entries - ic->free_section_entry;
		ic->free_section_entry = 0;
		ic->free_section++;
		wraparound_section(ic, &ic->free_section);
		ic->n_uncommitted_sections++;
	}
2325
	if (WARN_ON(ic->journal_sections * ic->journal_section_entries !=
2326 2327 2328 2329 2330 2331 2332 2333
		    (ic->n_uncommitted_sections + ic->n_committed_sections) *
		    ic->journal_section_entries + ic->free_sectors)) {
		DMCRIT("journal_sections %u, journal_section_entries %u, "
		       "n_uncommitted_sections %u, n_committed_sections %u, "
		       "journal_section_entries %u, free_sectors %u",
		       ic->journal_sections, ic->journal_section_entries,
		       ic->n_uncommitted_sections, ic->n_committed_sections,
		       ic->journal_section_entries, ic->free_sectors);
2334
	}
M
Mikulas Patocka 已提交
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
}

static void integrity_commit(struct work_struct *w)
{
	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, commit_work);
	unsigned commit_start, commit_sections;
	unsigned i, j, n;
	struct bio *flushes;

	del_timer(&ic->autocommit_timer);

	spin_lock_irq(&ic->endio_wait.lock);
	flushes = bio_list_get(&ic->flush_bio_list);
	if (unlikely(ic->mode != 'J')) {
		spin_unlock_irq(&ic->endio_wait.lock);
2350
		dm_integrity_flush_buffers(ic, true);
M
Mikulas Patocka 已提交
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
		goto release_flush_bios;
	}

	pad_uncommitted(ic);
	commit_start = ic->uncommitted_section;
	commit_sections = ic->n_uncommitted_sections;
	spin_unlock_irq(&ic->endio_wait.lock);

	if (!commit_sections)
		goto release_flush_bios;

	i = commit_start;
	for (n = 0; n < commit_sections; n++) {
		for (j = 0; j < ic->journal_section_entries; j++) {
			struct journal_entry *je;
			je = access_journal_entry(ic, i, j);
			io_wait_event(ic->copy_to_journal_wait, !journal_entry_is_inprogress(je));
		}
		for (j = 0; j < ic->journal_section_sectors; j++) {
			struct journal_sector *js;
			js = access_journal(ic, i, j);
			js->commit_id = dm_integrity_commit_id(ic, i, j, ic->commit_seq);
		}
		i++;
		if (unlikely(i >= ic->journal_sections))
			ic->commit_seq = next_commit_seq(ic->commit_seq);
		wraparound_section(ic, &i);
	}
	smp_rmb();

	write_journal(ic, commit_start, commit_sections);

	spin_lock_irq(&ic->endio_wait.lock);
	ic->uncommitted_section += commit_sections;
	wraparound_section(ic, &ic->uncommitted_section);
	ic->n_uncommitted_sections -= commit_sections;
	ic->n_committed_sections += commit_sections;
	spin_unlock_irq(&ic->endio_wait.lock);

2390
	if (READ_ONCE(ic->free_sectors) <= ic->free_sectors_threshold)
M
Mikulas Patocka 已提交
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
		queue_work(ic->writer_wq, &ic->writer_work);

release_flush_bios:
	while (flushes) {
		struct bio *next = flushes->bi_next;
		flushes->bi_next = NULL;
		do_endio(ic, flushes);
		flushes = next;
	}
}

static void complete_copy_from_journal(unsigned long error, void *context)
{
	struct journal_io *io = context;
	struct journal_completion *comp = io->comp;
	struct dm_integrity_c *ic = comp->ic;
	remove_range(ic, &io->range);
2408
	mempool_free(io, &ic->journal_io_mempool);
M
Mikulas Patocka 已提交
2409 2410 2411 2412 2413
	if (unlikely(error != 0))
		dm_integrity_io_error(ic, "copying from journal", -EIO);
	complete_journal_op(comp);
}

2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
static void restore_last_bytes(struct dm_integrity_c *ic, struct journal_sector *js,
			       struct journal_entry *je)
{
	unsigned s = 0;
	do {
		js->commit_id = je->last_bytes[s];
		js++;
	} while (++s < ic->sectors_per_block);
}

M
Mikulas Patocka 已提交
2424 2425 2426 2427 2428
static void do_journal_write(struct dm_integrity_c *ic, unsigned write_start,
			     unsigned write_sections, bool from_replay)
{
	unsigned i, j, n;
	struct journal_completion comp;
2429 2430 2431
	struct blk_plug plug;

	blk_start_plug(&plug);
M
Mikulas Patocka 已提交
2432 2433 2434

	comp.ic = ic;
	comp.in_flight = (atomic_t)ATOMIC_INIT(1);
2435
	init_completion(&comp.comp);
M
Mikulas Patocka 已提交
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454

	i = write_start;
	for (n = 0; n < write_sections; n++, i++, wraparound_section(ic, &i)) {
#ifndef INTERNAL_VERIFY
		if (unlikely(from_replay))
#endif
			rw_section_mac(ic, i, false);
		for (j = 0; j < ic->journal_section_entries; j++) {
			struct journal_entry *je = access_journal_entry(ic, i, j);
			sector_t sec, area, offset;
			unsigned k, l, next_loop;
			sector_t metadata_block;
			unsigned metadata_offset;
			struct journal_io *io;

			if (journal_entry_is_unused(je))
				continue;
			BUG_ON(unlikely(journal_entry_is_inprogress(je)) && !from_replay);
			sec = journal_entry_get_sector(je);
2455 2456 2457 2458 2459 2460
			if (unlikely(from_replay)) {
				if (unlikely(sec & (unsigned)(ic->sectors_per_block - 1))) {
					dm_integrity_io_error(ic, "invalid sector in journal", -EIO);
					sec &= ~(sector_t)(ic->sectors_per_block - 1);
				}
			}
2461 2462
			if (unlikely(sec >= ic->provided_data_sectors))
				continue;
M
Mikulas Patocka 已提交
2463
			get_area_and_offset(ic, sec, &area, &offset);
2464
			restore_last_bytes(ic, access_journal_data(ic, i, j), je);
M
Mikulas Patocka 已提交
2465 2466 2467 2468 2469 2470 2471
			for (k = j + 1; k < ic->journal_section_entries; k++) {
				struct journal_entry *je2 = access_journal_entry(ic, i, k);
				sector_t sec2, area2, offset2;
				if (journal_entry_is_unused(je2))
					break;
				BUG_ON(unlikely(journal_entry_is_inprogress(je2)) && !from_replay);
				sec2 = journal_entry_get_sector(je2);
2472 2473
				if (unlikely(sec2 >= ic->provided_data_sectors))
					break;
M
Mikulas Patocka 已提交
2474
				get_area_and_offset(ic, sec2, &area2, &offset2);
2475
				if (area2 != area || offset2 != offset + ((k - j) << ic->sb->log2_sectors_per_block))
M
Mikulas Patocka 已提交
2476
					break;
2477
				restore_last_bytes(ic, access_journal_data(ic, i, k), je2);
M
Mikulas Patocka 已提交
2478 2479 2480
			}
			next_loop = k - 1;

2481
			io = mempool_alloc(&ic->journal_io_mempool, GFP_NOIO);
M
Mikulas Patocka 已提交
2482 2483
			io->comp = &comp;
			io->range.logical_sector = sec;
2484
			io->range.n_sectors = (k - j) << ic->sb->log2_sectors_per_block;
M
Mikulas Patocka 已提交
2485 2486

			spin_lock_irq(&ic->endio_wait.lock);
2487
			add_new_range_and_wait(ic, &io->range);
M
Mikulas Patocka 已提交
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498

			if (likely(!from_replay)) {
				struct journal_node *section_node = &ic->journal_tree[i * ic->journal_section_entries];

				/* don't write if there is newer committed sector */
				while (j < k && find_newer_committed_node(ic, &section_node[j])) {
					struct journal_entry *je2 = access_journal_entry(ic, i, j);

					journal_entry_set_unused(je2);
					remove_journal_node(ic, &section_node[j]);
					j++;
2499 2500
					sec += ic->sectors_per_block;
					offset += ic->sectors_per_block;
M
Mikulas Patocka 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
				}
				while (j < k && find_newer_committed_node(ic, &section_node[k - 1])) {
					struct journal_entry *je2 = access_journal_entry(ic, i, k - 1);

					journal_entry_set_unused(je2);
					remove_journal_node(ic, &section_node[k - 1]);
					k--;
				}
				if (j == k) {
					remove_range_unlocked(ic, &io->range);
					spin_unlock_irq(&ic->endio_wait.lock);
2512
					mempool_free(io, &ic->journal_io_mempool);
M
Mikulas Patocka 已提交
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
					goto skip_io;
				}
				for (l = j; l < k; l++) {
					remove_journal_node(ic, &section_node[l]);
				}
			}
			spin_unlock_irq(&ic->endio_wait.lock);

			metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);
			for (l = j; l < k; l++) {
				int r;
				struct journal_entry *je2 = access_journal_entry(ic, i, l);

				if (
#ifndef INTERNAL_VERIFY
				    unlikely(from_replay) &&
#endif
				    ic->internal_hash) {
K
Kees Cook 已提交
2531
					char test_tag[max_t(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
M
Mikulas Patocka 已提交
2532

2533
					integrity_sector_checksum(ic, sec + ((l - j) << ic->sb->log2_sectors_per_block),
M
Mikulas Patocka 已提交
2534
								  (char *)access_journal_data(ic, i, l), test_tag);
2535
					if (unlikely(memcmp(test_tag, journal_entry_tag(ic, je2), ic->tag_size)))
M
Mikulas Patocka 已提交
2536 2537 2538 2539
						dm_integrity_io_error(ic, "tag mismatch when replaying journal", -EILSEQ);
				}

				journal_entry_set_unused(je2);
2540
				r = dm_integrity_rw_tag(ic, journal_entry_tag(ic, je2), &metadata_block, &metadata_offset,
M
Mikulas Patocka 已提交
2541 2542 2543 2544 2545 2546 2547
							ic->tag_size, TAG_WRITE);
				if (unlikely(r)) {
					dm_integrity_io_error(ic, "reading tags", r);
				}
			}

			atomic_inc(&comp.in_flight);
2548 2549 2550
			copy_from_journal(ic, i, j << ic->sb->log2_sectors_per_block,
					  (k - j) << ic->sb->log2_sectors_per_block,
					  get_data_sector(ic, area, offset),
M
Mikulas Patocka 已提交
2551 2552 2553 2554 2555 2556 2557 2558
					  complete_copy_from_journal, io);
skip_io:
			j = next_loop;
		}
	}

	dm_bufio_write_dirty_buffers_async(ic->bufio);

2559 2560
	blk_finish_plug(&plug);

M
Mikulas Patocka 已提交
2561 2562 2563
	complete_journal_op(&comp);
	wait_for_completion_io(&comp.comp);

2564
	dm_integrity_flush_buffers(ic, true);
M
Mikulas Patocka 已提交
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
}

static void integrity_writer(struct work_struct *w)
{
	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, writer_work);
	unsigned write_start, write_sections;

	unsigned prev_free_sectors;

	/* the following test is not needed, but it tests the replay code */
2575
	if (unlikely(dm_post_suspending(ic->ti)) && !ic->meta_dev)
M
Mikulas Patocka 已提交
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
		return;

	spin_lock_irq(&ic->endio_wait.lock);
	write_start = ic->committed_section;
	write_sections = ic->n_committed_sections;
	spin_unlock_irq(&ic->endio_wait.lock);

	if (!write_sections)
		return;

	do_journal_write(ic, write_start, write_sections, false);

	spin_lock_irq(&ic->endio_wait.lock);

	ic->committed_section += write_sections;
	wraparound_section(ic, &ic->committed_section);
	ic->n_committed_sections -= write_sections;

	prev_free_sectors = ic->free_sectors;
	ic->free_sectors += write_sections * ic->journal_section_entries;
	if (unlikely(!prev_free_sectors))
		wake_up_locked(&ic->endio_wait);

	spin_unlock_irq(&ic->endio_wait.lock);
}

2602 2603 2604 2605
static void recalc_write_super(struct dm_integrity_c *ic)
{
	int r;

2606
	dm_integrity_flush_buffers(ic, false);
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
	if (dm_integrity_failed(ic))
		return;

	r = sync_rw_sb(ic, REQ_OP_WRITE, 0);
	if (unlikely(r))
		dm_integrity_io_error(ic, "writing superblock", r);
}

static void integrity_recalc(struct work_struct *w)
{
	struct dm_integrity_c *ic = container_of(w, struct dm_integrity_c, recalc_work);
	struct dm_integrity_range range;
	struct dm_io_request io_req;
	struct dm_io_region io_loc;
	sector_t area, offset;
	sector_t metadata_block;
	unsigned metadata_offset;
2624
	sector_t logical_sector, n_sectors;
2625 2626 2627 2628 2629
	__u8 *t;
	unsigned i;
	int r;
	unsigned super_counter = 0;

2630 2631
	DEBUG_print("start recalculation... (position %llx)\n", le64_to_cpu(ic->sb->recalc_sector));

2632 2633 2634 2635
	spin_lock_irq(&ic->endio_wait.lock);

next_chunk:

2636
	if (unlikely(dm_post_suspending(ic->ti)))
2637 2638 2639
		goto unlock_ret;

	range.logical_sector = le64_to_cpu(ic->sb->recalc_sector);
2640 2641
	if (unlikely(range.logical_sector >= ic->provided_data_sectors)) {
		if (ic->mode == 'B') {
2642
			block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
2643 2644 2645
			DEBUG_print("queue_delayed_work: bitmap_flush_work\n");
			queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
		}
2646
		goto unlock_ret;
2647
	}
2648 2649 2650 2651

	get_area_and_offset(ic, range.logical_sector, &area, &offset);
	range.n_sectors = min((sector_t)RECALC_SECTORS, ic->provided_data_sectors - range.logical_sector);
	if (!ic->meta_dev)
2652
		range.n_sectors = min(range.n_sectors, ((sector_t)1U << ic->sb->log2_interleave_sectors) - (unsigned)offset);
2653

2654
	add_new_range_and_wait(ic, &range);
2655
	spin_unlock_irq(&ic->endio_wait.lock);
2656 2657 2658 2659 2660 2661 2662
	logical_sector = range.logical_sector;
	n_sectors = range.n_sectors;

	if (ic->mode == 'B') {
		if (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector, n_sectors, BITMAP_OP_TEST_ALL_CLEAR)) {
			goto advance_and_next;
		}
2663 2664
		while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector,
				       ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2665 2666 2667 2668
			logical_sector += ic->sectors_per_block;
			n_sectors -= ic->sectors_per_block;
			cond_resched();
		}
2669 2670
		while (block_bitmap_op(ic, ic->recalc_bitmap, logical_sector + n_sectors - ic->sectors_per_block,
				       ic->sectors_per_block, BITMAP_OP_TEST_ALL_CLEAR)) {
2671 2672 2673 2674 2675 2676
			n_sectors -= ic->sectors_per_block;
			cond_resched();
		}
		get_area_and_offset(ic, logical_sector, &area, &offset);
	}

2677
	DEBUG_print("recalculating: %llx, %llx\n", logical_sector, n_sectors);
2678 2679 2680

	if (unlikely(++super_counter == RECALC_WRITE_SUPER)) {
		recalc_write_super(ic);
2681 2682 2683
		if (ic->mode == 'B') {
			queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
		}
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
		super_counter = 0;
	}

	if (unlikely(dm_integrity_failed(ic)))
		goto err;

	io_req.bi_op = REQ_OP_READ;
	io_req.bi_op_flags = 0;
	io_req.mem.type = DM_IO_VMA;
	io_req.mem.ptr.addr = ic->recalc_buffer;
	io_req.notify.fn = NULL;
	io_req.client = ic->io;
	io_loc.bdev = ic->dev->bdev;
	io_loc.sector = get_data_sector(ic, area, offset);
2698
	io_loc.count = n_sectors;
2699 2700 2701 2702 2703 2704 2705 2706

	r = dm_io(&io_req, 1, &io_loc, NULL);
	if (unlikely(r)) {
		dm_integrity_io_error(ic, "reading data", r);
		goto err;
	}

	t = ic->recalc_tags;
2707 2708
	for (i = 0; i < n_sectors; i += ic->sectors_per_block) {
		integrity_sector_checksum(ic, logical_sector + i, ic->recalc_buffer + (i << SECTOR_SHIFT), t);
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
		t += ic->tag_size;
	}

	metadata_block = get_metadata_sector_and_offset(ic, area, offset, &metadata_offset);

	r = dm_integrity_rw_tag(ic, ic->recalc_tags, &metadata_block, &metadata_offset, t - ic->recalc_tags, TAG_WRITE);
	if (unlikely(r)) {
		dm_integrity_io_error(ic, "writing tags", r);
		goto err;
	}

2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
	if (ic->mode == 'B') {
		sector_t start, end;
		start = (range.logical_sector >>
			 (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
			(ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
		end = ((range.logical_sector + range.n_sectors) >>
		       (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)) <<
			(ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
		block_bitmap_op(ic, ic->recalc_bitmap, start, end - start, BITMAP_OP_CLEAR);
	}

2731 2732 2733
advance_and_next:
	cond_resched();

2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
	spin_lock_irq(&ic->endio_wait.lock);
	remove_range_unlocked(ic, &range);
	ic->sb->recalc_sector = cpu_to_le64(range.logical_sector + range.n_sectors);
	goto next_chunk;

err:
	remove_range(ic, &range);
	return;

unlock_ret:
	spin_unlock_irq(&ic->endio_wait.lock);

	recalc_write_super(ic);
}

2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
static void bitmap_block_work(struct work_struct *w)
{
	struct bitmap_block_status *bbs = container_of(w, struct bitmap_block_status, work);
	struct dm_integrity_c *ic = bbs->ic;
	struct bio *bio;
	struct bio_list bio_queue;
	struct bio_list waiting;

	bio_list_init(&waiting);

	spin_lock(&bbs->bio_queue_lock);
	bio_queue = bbs->bio_queue;
	bio_list_init(&bbs->bio_queue);
	spin_unlock(&bbs->bio_queue_lock);

	while ((bio = bio_list_pop(&bio_queue))) {
		struct dm_integrity_io *dio;

		dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));

2769 2770
		if (block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
				    dio->range.n_sectors, BITMAP_OP_TEST_ALL_SET)) {
2771 2772
			remove_range(ic, &dio->range);
			INIT_WORK(&dio->work, integrity_bio_wait);
2773
			queue_work(ic->offload_wq, &dio->work);
2774
		} else {
2775 2776
			block_bitmap_op(ic, ic->journal, dio->range.logical_sector,
					dio->range.n_sectors, BITMAP_OP_SET);
2777 2778 2779 2780 2781 2782 2783
			bio_list_add(&waiting, bio);
		}
	}

	if (bio_list_empty(&waiting))
		return;

2784 2785 2786
	rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC,
			   bbs->idx * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT),
			   BITMAP_BLOCK_SIZE >> SECTOR_SHIFT, NULL);
2787 2788 2789 2790

	while ((bio = bio_list_pop(&waiting))) {
		struct dm_integrity_io *dio = dm_per_bio_data(bio, sizeof(struct dm_integrity_io));

2791 2792
		block_bitmap_op(ic, ic->may_write_bitmap, dio->range.logical_sector,
				dio->range.n_sectors, BITMAP_OP_SET);
2793 2794 2795

		remove_range(ic, &dio->range);
		INIT_WORK(&dio->work, integrity_bio_wait);
2796
		queue_work(ic->offload_wq, &dio->work);
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806
	}

	queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, ic->bitmap_flush_interval);
}

static void bitmap_flush_work(struct work_struct *work)
{
	struct dm_integrity_c *ic = container_of(work, struct dm_integrity_c, bitmap_flush_work.work);
	struct dm_integrity_range range;
	unsigned long limit;
2807
	struct bio *bio;
2808

2809
	dm_integrity_flush_buffers(ic, false);
2810 2811 2812 2813 2814 2815 2816 2817

	range.logical_sector = 0;
	range.n_sectors = ic->provided_data_sectors;

	spin_lock_irq(&ic->endio_wait.lock);
	add_new_range_and_wait(ic, &range);
	spin_unlock_irq(&ic->endio_wait.lock);

2818
	dm_integrity_flush_buffers(ic, true);
2819 2820 2821 2822 2823 2824 2825

	limit = ic->provided_data_sectors;
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
		limit = le64_to_cpu(ic->sb->recalc_sector)
			>> (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit)
			<< (ic->sb->log2_sectors_per_block + ic->log2_blocks_per_bitmap_bit);
	}
2826
	/*DEBUG_print("zeroing journal\n");*/
2827 2828 2829
	block_bitmap_op(ic, ic->journal, 0, limit, BITMAP_OP_CLEAR);
	block_bitmap_op(ic, ic->may_write_bitmap, 0, limit, BITMAP_OP_CLEAR);

2830 2831
	rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
			   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
2832

2833 2834 2835 2836 2837 2838 2839 2840
	spin_lock_irq(&ic->endio_wait.lock);
	remove_range_unlocked(ic, &range);
	while (unlikely((bio = bio_list_pop(&ic->synchronous_bios)) != NULL)) {
		bio_endio(bio);
		spin_unlock_irq(&ic->endio_wait.lock);
		spin_lock_irq(&ic->endio_wait.lock);
	}
	spin_unlock_irq(&ic->endio_wait.lock);
2841 2842 2843
}


M
Mikulas Patocka 已提交
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
static void init_journal(struct dm_integrity_c *ic, unsigned start_section,
			 unsigned n_sections, unsigned char commit_seq)
{
	unsigned i, j, n;

	if (!n_sections)
		return;

	for (n = 0; n < n_sections; n++) {
		i = start_section + n;
		wraparound_section(ic, &i);
		for (j = 0; j < ic->journal_section_sectors; j++) {
			struct journal_sector *js = access_journal(ic, i, j);
			memset(&js->entries, 0, JOURNAL_SECTOR_DATA);
			js->commit_id = dm_integrity_commit_id(ic, i, j, commit_seq);
		}
		for (j = 0; j < ic->journal_section_entries; j++) {
			struct journal_entry *je = access_journal_entry(ic, i, j);
			journal_entry_set_unused(je);
		}
	}

	write_journal(ic, start_section, n_sections);
}

static int find_commit_seq(struct dm_integrity_c *ic, unsigned i, unsigned j, commit_id_t id)
{
	unsigned char k;
	for (k = 0; k < N_COMMIT_IDS; k++) {
		if (dm_integrity_commit_id(ic, i, j, k) == id)
			return k;
	}
	dm_integrity_io_error(ic, "journal commit id", -EIO);
	return -EIO;
}

static void replay_journal(struct dm_integrity_c *ic)
{
	unsigned i, j;
	bool used_commit_ids[N_COMMIT_IDS];
	unsigned max_commit_id_sections[N_COMMIT_IDS];
	unsigned write_start, write_sections;
	unsigned continue_section;
	bool journal_empty;
	unsigned char unused, last_used, want_commit_seq;

2890 2891 2892
	if (ic->mode == 'R')
		return;

M
Mikulas Patocka 已提交
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
	if (ic->journal_uptodate)
		return;

	last_used = 0;
	write_start = 0;

	if (!ic->just_formatted) {
		DEBUG_print("reading journal\n");
		rw_journal(ic, REQ_OP_READ, 0, 0, ic->journal_sections, NULL);
		if (ic->journal_io)
			DEBUG_bytes(lowmem_page_address(ic->journal_io[0].page), 64, "read journal");
		if (ic->journal_io) {
			struct journal_completion crypt_comp;
			crypt_comp.ic = ic;
2907
			init_completion(&crypt_comp.comp);
M
Mikulas Patocka 已提交
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 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 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 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 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
			crypt_comp.in_flight = (atomic_t)ATOMIC_INIT(0);
			encrypt_journal(ic, false, 0, ic->journal_sections, &crypt_comp);
			wait_for_completion(&crypt_comp.comp);
		}
		DEBUG_bytes(lowmem_page_address(ic->journal[0].page), 64, "decrypted journal");
	}

	if (dm_integrity_failed(ic))
		goto clear_journal;

	journal_empty = true;
	memset(used_commit_ids, 0, sizeof used_commit_ids);
	memset(max_commit_id_sections, 0, sizeof max_commit_id_sections);
	for (i = 0; i < ic->journal_sections; i++) {
		for (j = 0; j < ic->journal_section_sectors; j++) {
			int k;
			struct journal_sector *js = access_journal(ic, i, j);
			k = find_commit_seq(ic, i, j, js->commit_id);
			if (k < 0)
				goto clear_journal;
			used_commit_ids[k] = true;
			max_commit_id_sections[k] = i;
		}
		if (journal_empty) {
			for (j = 0; j < ic->journal_section_entries; j++) {
				struct journal_entry *je = access_journal_entry(ic, i, j);
				if (!journal_entry_is_unused(je)) {
					journal_empty = false;
					break;
				}
			}
		}
	}

	if (!used_commit_ids[N_COMMIT_IDS - 1]) {
		unused = N_COMMIT_IDS - 1;
		while (unused && !used_commit_ids[unused - 1])
			unused--;
	} else {
		for (unused = 0; unused < N_COMMIT_IDS; unused++)
			if (!used_commit_ids[unused])
				break;
		if (unused == N_COMMIT_IDS) {
			dm_integrity_io_error(ic, "journal commit ids", -EIO);
			goto clear_journal;
		}
	}
	DEBUG_print("first unused commit seq %d [%d,%d,%d,%d]\n",
		    unused, used_commit_ids[0], used_commit_ids[1],
		    used_commit_ids[2], used_commit_ids[3]);

	last_used = prev_commit_seq(unused);
	want_commit_seq = prev_commit_seq(last_used);

	if (!used_commit_ids[want_commit_seq] && used_commit_ids[prev_commit_seq(want_commit_seq)])
		journal_empty = true;

	write_start = max_commit_id_sections[last_used] + 1;
	if (unlikely(write_start >= ic->journal_sections))
		want_commit_seq = next_commit_seq(want_commit_seq);
	wraparound_section(ic, &write_start);

	i = write_start;
	for (write_sections = 0; write_sections < ic->journal_sections; write_sections++) {
		for (j = 0; j < ic->journal_section_sectors; j++) {
			struct journal_sector *js = access_journal(ic, i, j);

			if (js->commit_id != dm_integrity_commit_id(ic, i, j, want_commit_seq)) {
				/*
				 * This could be caused by crash during writing.
				 * We won't replay the inconsistent part of the
				 * journal.
				 */
				DEBUG_print("commit id mismatch at position (%u, %u): %d != %d\n",
					    i, j, find_commit_seq(ic, i, j, js->commit_id), want_commit_seq);
				goto brk;
			}
		}
		i++;
		if (unlikely(i >= ic->journal_sections))
			want_commit_seq = next_commit_seq(want_commit_seq);
		wraparound_section(ic, &i);
	}
brk:

	if (!journal_empty) {
		DEBUG_print("replaying %u sections, starting at %u, commit seq %d\n",
			    write_sections, write_start, want_commit_seq);
		do_journal_write(ic, write_start, write_sections, true);
	}

	if (write_sections == ic->journal_sections && (ic->mode == 'J' || journal_empty)) {
		continue_section = write_start;
		ic->commit_seq = want_commit_seq;
		DEBUG_print("continuing from section %u, commit seq %d\n", write_start, ic->commit_seq);
	} else {
		unsigned s;
		unsigned char erase_seq;
clear_journal:
		DEBUG_print("clearing journal\n");

		erase_seq = prev_commit_seq(prev_commit_seq(last_used));
		s = write_start;
		init_journal(ic, s, 1, erase_seq);
		s++;
		wraparound_section(ic, &s);
		if (ic->journal_sections >= 2) {
			init_journal(ic, s, ic->journal_sections - 2, erase_seq);
			s += ic->journal_sections - 2;
			wraparound_section(ic, &s);
			init_journal(ic, s, 1, erase_seq);
		}

		continue_section = 0;
		ic->commit_seq = next_commit_seq(erase_seq);
	}

	ic->committed_section = continue_section;
	ic->n_committed_sections = 0;

	ic->uncommitted_section = continue_section;
	ic->n_uncommitted_sections = 0;

	ic->free_section = continue_section;
	ic->free_section_entry = 0;
	ic->free_sectors = ic->journal_entries;

	ic->journal_tree_root = RB_ROOT;
	for (i = 0; i < ic->journal_entries; i++)
		init_journal_node(&ic->journal_tree[i]);
}

3040
static void dm_integrity_enter_synchronous_mode(struct dm_integrity_c *ic)
3041
{
3042
	DEBUG_print("dm_integrity_enter_synchronous_mode\n");
3043 3044

	if (ic->mode == 'B') {
3045 3046 3047
		ic->bitmap_flush_interval = msecs_to_jiffies(10) + 1;
		ic->synchronous_mode = 1;

3048 3049 3050 3051
		cancel_delayed_work_sync(&ic->bitmap_flush_work);
		queue_delayed_work(ic->commit_wq, &ic->bitmap_flush_work, 0);
		flush_workqueue(ic->commit_wq);
	}
3052 3053 3054 3055 3056 3057 3058 3059 3060
}

static int dm_integrity_reboot(struct notifier_block *n, unsigned long code, void *x)
{
	struct dm_integrity_c *ic = container_of(n, struct dm_integrity_c, reboot_notifier);

	DEBUG_print("dm_integrity_reboot\n");

	dm_integrity_enter_synchronous_mode(ic);
3061 3062 3063 3064

	return NOTIFY_DONE;
}

M
Mikulas Patocka 已提交
3065 3066 3067
static void dm_integrity_postsuspend(struct dm_target *ti)
{
	struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
3068
	int r;
M
Mikulas Patocka 已提交
3069

3070
	WARN_ON(unregister_reboot_notifier(&ic->reboot_notifier));
M
Mikulas Patocka 已提交
3071 3072 3073

	del_timer_sync(&ic->autocommit_timer);

3074 3075 3076
	if (ic->recalc_wq)
		drain_workqueue(ic->recalc_wq);

3077 3078 3079
	if (ic->mode == 'B')
		cancel_delayed_work_sync(&ic->bitmap_flush_work);

M
Mikulas Patocka 已提交
3080 3081 3082 3083
	queue_work(ic->commit_wq, &ic->commit_work);
	drain_workqueue(ic->commit_wq);

	if (ic->mode == 'J') {
3084 3085
		if (ic->meta_dev)
			queue_work(ic->writer_wq, &ic->writer_work);
M
Mikulas Patocka 已提交
3086
		drain_workqueue(ic->writer_wq);
3087
		dm_integrity_flush_buffers(ic, true);
M
Mikulas Patocka 已提交
3088 3089
	}

3090
	if (ic->mode == 'B') {
3091
		dm_integrity_flush_buffers(ic, true);
3092
#if 1
3093
		/* set to 0 to test bitmap replay code */
3094 3095 3096 3097 3098 3099 3100 3101
		init_journal(ic, 0, ic->journal_sections, 0);
		ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
		r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
		if (unlikely(r))
			dm_integrity_io_error(ic, "writing superblock", r);
#endif
	}

M
Mikulas Patocka 已提交
3102 3103 3104 3105 3106 3107 3108 3109
	BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));

	ic->journal_uptodate = true;
}

static void dm_integrity_resume(struct dm_target *ti)
{
	struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
3110
	__u64 old_provided_data_sectors = le64_to_cpu(ic->sb->provided_data_sectors);
3111
	int r;
3112

3113 3114
	DEBUG_print("resume\n");

3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
	if (ic->provided_data_sectors != old_provided_data_sectors) {
		if (ic->provided_data_sectors > old_provided_data_sectors &&
		    ic->mode == 'B' &&
		    ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit) {
			rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
					   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
			block_bitmap_op(ic, ic->journal, old_provided_data_sectors,
					ic->provided_data_sectors - old_provided_data_sectors, BITMAP_OP_SET);
			rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
					   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
		}

		ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);
		r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
		if (unlikely(r))
			dm_integrity_io_error(ic, "writing superblock", r);
	}

3133 3134
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_DIRTY_BITMAP)) {
		DEBUG_print("resume dirty_bitmap\n");
3135 3136
		rw_journal_sectors(ic, REQ_OP_READ, 0, 0,
				   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3137
		if (ic->mode == 'B') {
3138 3139
			if (ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
			    !ic->reset_recalculate_flag) {
3140 3141
				block_bitmap_copy(ic, ic->recalc_bitmap, ic->journal);
				block_bitmap_copy(ic, ic->may_write_bitmap, ic->journal);
3142 3143
				if (!block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors,
						     BITMAP_OP_TEST_ALL_CLEAR)) {
3144 3145 3146 3147
					ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
					ic->sb->recalc_sector = cpu_to_le64(0);
				}
			} else {
3148 3149
				DEBUG_print("non-matching blocks_per_bitmap_bit: %u, %u\n",
					    ic->sb->log2_blocks_per_bitmap_bit, ic->log2_blocks_per_bitmap_bit);
3150 3151 3152 3153
				ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
				block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
				block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_SET);
				block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_SET);
3154 3155
				rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
						   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3156 3157 3158 3159 3160
				ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
				ic->sb->recalc_sector = cpu_to_le64(0);
			}
		} else {
			if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
3161 3162
			      block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) ||
			    ic->reset_recalculate_flag) {
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
				ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
				ic->sb->recalc_sector = cpu_to_le64(0);
			}
			init_journal(ic, 0, ic->journal_sections, 0);
			replay_journal(ic);
			ic->sb->flags &= ~cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
		}
		r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
		if (unlikely(r))
			dm_integrity_io_error(ic, "writing superblock", r);
	} else {
		replay_journal(ic);
3175 3176 3177 3178
		if (ic->reset_recalculate_flag) {
			ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
			ic->sb->recalc_sector = cpu_to_le64(0);
		}
3179 3180 3181 3182 3183 3184
		if (ic->mode == 'B') {
			ic->sb->flags |= cpu_to_le32(SB_FLAG_DIRTY_BITMAP);
			ic->sb->log2_blocks_per_bitmap_bit = ic->log2_blocks_per_bitmap_bit;
			r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
			if (unlikely(r))
				dm_integrity_io_error(ic, "writing superblock", r);
M
Mikulas Patocka 已提交
3185

3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
			block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
			block_bitmap_op(ic, ic->recalc_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
			block_bitmap_op(ic, ic->may_write_bitmap, 0, ic->provided_data_sectors, BITMAP_OP_CLEAR);
			if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
			    le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors) {
				block_bitmap_op(ic, ic->journal, le64_to_cpu(ic->sb->recalc_sector),
						ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
				block_bitmap_op(ic, ic->recalc_bitmap, le64_to_cpu(ic->sb->recalc_sector),
						ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
				block_bitmap_op(ic, ic->may_write_bitmap, le64_to_cpu(ic->sb->recalc_sector),
						ic->provided_data_sectors - le64_to_cpu(ic->sb->recalc_sector), BITMAP_OP_SET);
			}
3198 3199
			rw_journal_sectors(ic, REQ_OP_WRITE, REQ_FUA | REQ_SYNC, 0,
					   ic->n_bitmap_blocks * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT), NULL);
3200 3201
		}
	}
M
Mikulas Patocka 已提交
3202

3203 3204
	DEBUG_print("testing recalc: %x\n", ic->sb->flags);
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
3205
		__u64 recalc_pos = le64_to_cpu(ic->sb->recalc_sector);
3206
		DEBUG_print("recalc pos: %llx / %llx\n", recalc_pos, ic->provided_data_sectors);
3207 3208 3209 3210 3211 3212 3213
		if (recalc_pos < ic->provided_data_sectors) {
			queue_work(ic->recalc_wq, &ic->recalc_work);
		} else if (recalc_pos > ic->provided_data_sectors) {
			ic->sb->recalc_sector = cpu_to_le64(ic->provided_data_sectors);
			recalc_write_super(ic);
		}
	}
3214 3215 3216 3217 3218

	ic->reboot_notifier.notifier_call = dm_integrity_reboot;
	ic->reboot_notifier.next = NULL;
	ic->reboot_notifier.priority = INT_MAX - 1;	/* be notified after md and before hardware drivers */
	WARN_ON(register_reboot_notifier(&ic->reboot_notifier));
3219 3220

#if 0
3221
	/* set to 1 to stress test synchronous mode */
3222 3223
	dm_integrity_enter_synchronous_mode(ic);
#endif
M
Mikulas Patocka 已提交
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
}

static void dm_integrity_status(struct dm_target *ti, status_type_t type,
				unsigned status_flags, char *result, unsigned maxlen)
{
	struct dm_integrity_c *ic = (struct dm_integrity_c *)ti->private;
	unsigned arg_count;
	size_t sz = 0;

	switch (type) {
	case STATUSTYPE_INFO:
3235
		DMEMIT("%llu %llu",
M
Mike Snitzer 已提交
3236
			(unsigned long long)atomic64_read(&ic->number_of_mismatches),
3237
			ic->provided_data_sectors);
3238
		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
3239
			DMEMIT(" %llu", le64_to_cpu(ic->sb->recalc_sector));
3240 3241
		else
			DMEMIT(" -");
M
Mikulas Patocka 已提交
3242 3243 3244 3245 3246 3247
		break;

	case STATUSTYPE_TABLE: {
		__u64 watermark_percentage = (__u64)(ic->journal_entries - ic->free_sectors_threshold) * 100;
		watermark_percentage += ic->journal_entries / 2;
		do_div(watermark_percentage, ic->journal_entries);
3248
		arg_count = 3;
3249
		arg_count += !!ic->meta_dev;
3250
		arg_count += ic->sectors_per_block != 1;
3251
		arg_count += !!(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING));
3252
		arg_count += ic->reset_recalculate_flag;
3253
		arg_count += ic->discard;
3254 3255
		arg_count += ic->mode == 'J';
		arg_count += ic->mode == 'J';
3256 3257
		arg_count += ic->mode == 'B';
		arg_count += ic->mode == 'B';
M
Mikulas Patocka 已提交
3258 3259 3260
		arg_count += !!ic->internal_hash_alg.alg_string;
		arg_count += !!ic->journal_crypt_alg.alg_string;
		arg_count += !!ic->journal_mac_alg.alg_string;
3261
		arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0;
3262
		arg_count += (ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0;
3263
		arg_count += ic->legacy_recalculate;
3264
		DMEMIT("%s %llu %u %c %u", ic->dev->name, ic->start,
M
Mikulas Patocka 已提交
3265
		       ic->tag_size, ic->mode, arg_count);
3266 3267
		if (ic->meta_dev)
			DMEMIT(" meta_device:%s", ic->meta_dev->name);
3268 3269
		if (ic->sectors_per_block != 1)
			DMEMIT(" block_size:%u", ic->sectors_per_block << SECTOR_SHIFT);
3270
		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))
3271
			DMEMIT(" recalculate");
3272 3273
		if (ic->reset_recalculate_flag)
			DMEMIT(" reset_recalculate");
3274 3275
		if (ic->discard)
			DMEMIT(" allow_discards");
3276 3277 3278
		DMEMIT(" journal_sectors:%u", ic->initial_sectors - SB_SECTORS);
		DMEMIT(" interleave_sectors:%u", 1U << ic->sb->log2_interleave_sectors);
		DMEMIT(" buffer_sectors:%u", 1U << ic->log2_buffer_sectors);
3279 3280 3281 3282
		if (ic->mode == 'J') {
			DMEMIT(" journal_watermark:%u", (unsigned)watermark_percentage);
			DMEMIT(" commit_time:%u", ic->autocommit_msec);
		}
3283
		if (ic->mode == 'B') {
3284
			DMEMIT(" sectors_per_bit:%llu", (sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit);
3285 3286
			DMEMIT(" bitmap_flush_interval:%u", jiffies_to_msecs(ic->bitmap_flush_interval));
		}
3287 3288
		if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING)) != 0)
			DMEMIT(" fix_padding");
3289 3290
		if ((ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_HMAC)) != 0)
			DMEMIT(" fix_hmac");
3291 3292
		if (ic->legacy_recalculate)
			DMEMIT(" legacy_recalculate");
M
Mikulas Patocka 已提交
3293 3294 3295 3296 3297 3298 3299 3300 3301

#define EMIT_ALG(a, n)							\
		do {							\
			if (ic->a.alg_string) {				\
				DMEMIT(" %s:%s", n, ic->a.alg_string);	\
				if (ic->a.key_string)			\
					DMEMIT(":%s", ic->a.key_string);\
			}						\
		} while (0)
3302 3303 3304
		EMIT_ALG(internal_hash_alg, "internal_hash");
		EMIT_ALG(journal_crypt_alg, "journal_crypt");
		EMIT_ALG(journal_mac_alg, "journal_mac");
M
Mikulas Patocka 已提交
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314
		break;
	}
	}
}

static int dm_integrity_iterate_devices(struct dm_target *ti,
					iterate_devices_callout_fn fn, void *data)
{
	struct dm_integrity_c *ic = ti->private;

3315 3316 3317 3318
	if (!ic->meta_dev)
		return fn(ti, ic->dev, ic->start + ic->initial_sectors + ic->metadata_run, ti->len, data);
	else
		return fn(ti, ic->dev, 0, ti->len, data);
M
Mikulas Patocka 已提交
3319 3320
}

3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
static void dm_integrity_io_hints(struct dm_target *ti, struct queue_limits *limits)
{
	struct dm_integrity_c *ic = ti->private;

	if (ic->sectors_per_block > 1) {
		limits->logical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
		limits->physical_block_size = ic->sectors_per_block << SECTOR_SHIFT;
		blk_limits_io_min(limits, ic->sectors_per_block << SECTOR_SHIFT);
	}
}

M
Mikulas Patocka 已提交
3332 3333 3334 3335 3336
static void calculate_journal_section_size(struct dm_integrity_c *ic)
{
	unsigned sector_space = JOURNAL_SECTOR_DATA;

	ic->journal_sections = le32_to_cpu(ic->sb->journal_sections);
3337
	ic->journal_entry_size = roundup(offsetof(struct journal_entry, last_bytes[ic->sectors_per_block]) + ic->tag_size,
M
Mikulas Patocka 已提交
3338 3339 3340 3341 3342 3343
					 JOURNAL_ENTRY_ROUNDUP);

	if (ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC))
		sector_space -= JOURNAL_MAC_PER_SECTOR;
	ic->journal_entries_per_sector = sector_space / ic->journal_entry_size;
	ic->journal_section_entries = ic->journal_entries_per_sector * JOURNAL_BLOCK_SECTORS;
3344
	ic->journal_section_sectors = (ic->journal_section_entries << ic->sb->log2_sectors_per_block) + JOURNAL_BLOCK_SECTORS;
M
Mikulas Patocka 已提交
3345 3346 3347 3348 3349 3350 3351 3352 3353
	ic->journal_entries = ic->journal_section_entries * ic->journal_sections;
}

static int calculate_device_limits(struct dm_integrity_c *ic)
{
	__u64 initial_sectors;

	calculate_journal_section_size(ic);
	initial_sectors = SB_SECTORS + (__u64)ic->journal_section_sectors * ic->journal_sections;
3354
	if (initial_sectors + METADATA_PADDING_SECTORS >= ic->meta_device_sectors || initial_sectors > UINT_MAX)
M
Mikulas Patocka 已提交
3355 3356 3357
		return -EINVAL;
	ic->initial_sectors = initial_sectors;

3358 3359
	if (!ic->meta_dev) {
		sector_t last_sector, last_area, last_offset;
M
Mikulas Patocka 已提交
3360

3361 3362 3363 3364 3365 3366 3367 3368
		/* we have to maintain excessive padding for compatibility with existing volumes */
		__u64 metadata_run_padding =
			ic->sb->flags & cpu_to_le32(SB_FLAG_FIXED_PADDING) ?
			(__u64)(METADATA_PADDING_SECTORS << SECTOR_SHIFT) :
			(__u64)(1 << SECTOR_SHIFT << METADATA_PADDING_SECTORS);

		ic->metadata_run = round_up((__u64)ic->tag_size << (ic->sb->log2_interleave_sectors - ic->sb->log2_sectors_per_block),
					    metadata_run_padding) >> SECTOR_SHIFT;
3369 3370 3371 3372
		if (!(ic->metadata_run & (ic->metadata_run - 1)))
			ic->log2_metadata_run = __ffs(ic->metadata_run);
		else
			ic->log2_metadata_run = -1;
M
Mikulas Patocka 已提交
3373

3374 3375 3376 3377 3378
		get_area_and_offset(ic, ic->provided_data_sectors - 1, &last_area, &last_offset);
		last_sector = get_data_sector(ic, last_area, last_offset);
		if (last_sector < ic->start || last_sector >= ic->meta_device_sectors)
			return -EINVAL;
	} else {
3379
		__u64 meta_size = (ic->provided_data_sectors >> ic->sb->log2_sectors_per_block) * ic->tag_size;
3380 3381 3382 3383 3384 3385 3386 3387 3388
		meta_size = (meta_size + ((1U << (ic->log2_buffer_sectors + SECTOR_SHIFT)) - 1))
				>> (ic->log2_buffer_sectors + SECTOR_SHIFT);
		meta_size <<= ic->log2_buffer_sectors;
		if (ic->initial_sectors + meta_size < ic->initial_sectors ||
		    ic->initial_sectors + meta_size > ic->meta_device_sectors)
			return -EINVAL;
		ic->metadata_run = 1;
		ic->log2_metadata_run = 0;
	}
M
Mikulas Patocka 已提交
3389 3390 3391 3392

	return 0;
}

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
static void get_provided_data_sectors(struct dm_integrity_c *ic)
{
	if (!ic->meta_dev) {
		int test_bit;
		ic->provided_data_sectors = 0;
		for (test_bit = fls64(ic->meta_device_sectors) - 1; test_bit >= 3; test_bit--) {
			__u64 prev_data_sectors = ic->provided_data_sectors;

			ic->provided_data_sectors |= (sector_t)1 << test_bit;
			if (calculate_device_limits(ic))
				ic->provided_data_sectors = prev_data_sectors;
		}
	} else {
		ic->provided_data_sectors = ic->data_device_sectors;
		ic->provided_data_sectors &= ~(sector_t)(ic->sectors_per_block - 1);
	}
}

M
Mikulas Patocka 已提交
3411 3412 3413 3414 3415
static int initialize_superblock(struct dm_integrity_c *ic, unsigned journal_sectors, unsigned interleave_sectors)
{
	unsigned journal_sections;
	int test_bit;

3416
	memset(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT);
M
Mikulas Patocka 已提交
3417 3418
	memcpy(ic->sb->magic, SB_MAGIC, 8);
	ic->sb->integrity_tag_size = cpu_to_le16(ic->tag_size);
3419
	ic->sb->log2_sectors_per_block = __ffs(ic->sectors_per_block);
M
Mikulas Patocka 已提交
3420 3421 3422 3423 3424 3425 3426 3427
	if (ic->journal_mac_alg.alg_string)
		ic->sb->flags |= cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC);

	calculate_journal_section_size(ic);
	journal_sections = journal_sectors / ic->journal_section_sectors;
	if (!journal_sections)
		journal_sections = 1;

3428 3429 3430 3431 3432
	if (ic->fix_hmac && (ic->internal_hash_alg.alg_string || ic->journal_mac_alg.alg_string)) {
		ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_HMAC);
		get_random_bytes(ic->sb->salt, SALT_SIZE);
	}

3433
	if (!ic->meta_dev) {
3434 3435
		if (ic->fix_padding)
			ic->sb->flags |= cpu_to_le32(SB_FLAG_FIXED_PADDING);
3436 3437 3438 3439 3440 3441 3442
		ic->sb->journal_sections = cpu_to_le32(journal_sections);
		if (!interleave_sectors)
			interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
		ic->sb->log2_interleave_sectors = __fls(interleave_sectors);
		ic->sb->log2_interleave_sectors = max((__u8)MIN_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);
		ic->sb->log2_interleave_sectors = min((__u8)MAX_LOG2_INTERLEAVE_SECTORS, ic->sb->log2_interleave_sectors);

3443
		get_provided_data_sectors(ic);
3444 3445 3446 3447
		if (!ic->provided_data_sectors)
			return -EINVAL;
	} else {
		ic->sb->log2_interleave_sectors = 0;
3448 3449 3450 3451

		get_provided_data_sectors(ic);
		if (!ic->provided_data_sectors)
			return -EINVAL;
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462

try_smaller_buffer:
		ic->sb->journal_sections = cpu_to_le32(0);
		for (test_bit = fls(journal_sections) - 1; test_bit >= 0; test_bit--) {
			__u32 prev_journal_sections = le32_to_cpu(ic->sb->journal_sections);
			__u32 test_journal_sections = prev_journal_sections | (1U << test_bit);
			if (test_journal_sections > journal_sections)
				continue;
			ic->sb->journal_sections = cpu_to_le32(test_journal_sections);
			if (calculate_device_limits(ic))
				ic->sb->journal_sections = cpu_to_le32(prev_journal_sections);
M
Mikulas Patocka 已提交
3463

3464 3465 3466 3467 3468 3469 3470 3471
		}
		if (!le32_to_cpu(ic->sb->journal_sections)) {
			if (ic->log2_buffer_sectors > 3) {
				ic->log2_buffer_sectors--;
				goto try_smaller_buffer;
			}
			return -EINVAL;
		}
M
Mikulas Patocka 已提交
3472 3473 3474 3475
	}

	ic->sb->provided_data_sectors = cpu_to_le64(ic->provided_data_sectors);

3476 3477
	sb_set_version(ic);

M
Mikulas Patocka 已提交
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487
	return 0;
}

static void dm_integrity_set(struct dm_target *ti, struct dm_integrity_c *ic)
{
	struct gendisk *disk = dm_disk(dm_table_get_md(ti->table));
	struct blk_integrity bi;

	memset(&bi, 0, sizeof(bi));
	bi.profile = &dm_integrity_profile;
3488 3489
	bi.tuple_size = ic->tag_size;
	bi.tag_size = bi.tuple_size;
3490
	bi.interval_exp = ic->sb->log2_sectors_per_block + SECTOR_SHIFT;
M
Mikulas Patocka 已提交
3491 3492 3493 3494 3495

	blk_integrity_register(disk, &bi);
	blk_queue_max_integrity_segments(disk->queue, UINT_MAX);
}

3496
static void dm_integrity_free_page_list(struct page_list *pl)
M
Mikulas Patocka 已提交
3497 3498 3499 3500 3501
{
	unsigned i;

	if (!pl)
		return;
3502 3503
	for (i = 0; pl[i].page; i++)
		__free_page(pl[i].page);
M
Mikulas Patocka 已提交
3504 3505 3506
	kvfree(pl);
}

3507
static struct page_list *dm_integrity_alloc_page_list(unsigned n_pages)
M
Mikulas Patocka 已提交
3508 3509 3510 3511
{
	struct page_list *pl;
	unsigned i;

3512
	pl = kvmalloc_array(n_pages + 1, sizeof(struct page_list), GFP_KERNEL | __GFP_ZERO);
M
Mikulas Patocka 已提交
3513 3514 3515
	if (!pl)
		return NULL;

3516
	for (i = 0; i < n_pages; i++) {
M
Mikulas Patocka 已提交
3517 3518
		pl[i].page = alloc_page(GFP_KERNEL);
		if (!pl[i].page) {
3519
			dm_integrity_free_page_list(pl);
M
Mikulas Patocka 已提交
3520 3521 3522 3523 3524
			return NULL;
		}
		if (i)
			pl[i - 1].next = &pl[i];
	}
3525 3526
	pl[i].page = NULL;
	pl[i].next = NULL;
M
Mikulas Patocka 已提交
3527 3528 3529 3530 3531 3532 3533 3534 3535

	return pl;
}

static void dm_integrity_free_journal_scatterlist(struct dm_integrity_c *ic, struct scatterlist **sl)
{
	unsigned i;
	for (i = 0; i < ic->journal_sections; i++)
		kvfree(sl[i]);
3536
	kvfree(sl);
M
Mikulas Patocka 已提交
3537 3538
}

3539 3540
static struct scatterlist **dm_integrity_alloc_journal_scatterlist(struct dm_integrity_c *ic,
								   struct page_list *pl)
M
Mikulas Patocka 已提交
3541 3542 3543 3544
{
	struct scatterlist **sl;
	unsigned i;

3545 3546 3547
	sl = kvmalloc_array(ic->journal_sections,
			    sizeof(struct scatterlist *),
			    GFP_KERNEL | __GFP_ZERO);
M
Mikulas Patocka 已提交
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
	if (!sl)
		return NULL;

	for (i = 0; i < ic->journal_sections; i++) {
		struct scatterlist *s;
		unsigned start_index, start_offset;
		unsigned end_index, end_offset;
		unsigned n_pages;
		unsigned idx;

		page_list_location(ic, i, 0, &start_index, &start_offset);
3559 3560
		page_list_location(ic, i, ic->journal_section_sectors - 1,
				   &end_index, &end_offset);
M
Mikulas Patocka 已提交
3561 3562 3563

		n_pages = (end_index - start_index + 1);

3564 3565
		s = kvmalloc_array(n_pages, sizeof(struct scatterlist),
				   GFP_KERNEL);
M
Mikulas Patocka 已提交
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
		if (!s) {
			dm_integrity_free_journal_scatterlist(ic, sl);
			return NULL;
		}

		sg_init_table(s, n_pages);
		for (idx = start_index; idx <= end_index; idx++) {
			char *va = lowmem_page_address(pl[idx].page);
			unsigned start = 0, end = PAGE_SIZE;
			if (idx == start_index)
				start = start_offset;
			if (idx == end_index)
				end = end_offset + (1 << SECTOR_SHIFT);
			sg_set_buf(&s[idx - start_index], va + start, end - start);
		}

		sl[i] = s;
	}

	return sl;
}

static void free_alg(struct alg_spec *a)
{
3590 3591
	kfree_sensitive(a->alg_string);
	kfree_sensitive(a->key);
M
Mikulas Patocka 已提交
3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
	memset(a, 0, sizeof *a);
}

static int get_alg_and_key(const char *arg, struct alg_spec *a, char **error, char *error_inval)
{
	char *k;

	free_alg(a);

	a->alg_string = kstrdup(strchr(arg, ':') + 1, GFP_KERNEL);
	if (!a->alg_string)
		goto nomem;

	k = strchr(a->alg_string, ':');
	if (k) {
		*k = 0;
		a->key_string = k + 1;
		if (strlen(a->key_string) & 1)
			goto inval;

		a->key_size = strlen(a->key_string) / 2;
		a->key = kmalloc(a->key_size, GFP_KERNEL);
		if (!a->key)
			goto nomem;
3616 3617
		if (hex2bin(a->key, a->key_string, a->key_size))
			goto inval;
M
Mikulas Patocka 已提交
3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
	}

	return 0;
inval:
	*error = error_inval;
	return -EINVAL;
nomem:
	*error = "Out of memory for an argument";
	return -ENOMEM;
}

static int get_mac(struct crypto_shash **hash, struct alg_spec *a, char **error,
		   char *error_alg, char *error_key)
{
	int r;

	if (a->alg_string) {
3635
		*hash = crypto_alloc_shash(a->alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
M
Mikulas Patocka 已提交
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648
		if (IS_ERR(*hash)) {
			*error = error_alg;
			r = PTR_ERR(*hash);
			*hash = NULL;
			return r;
		}

		if (a->key) {
			r = crypto_shash_setkey(*hash, a->key, a->key_size);
			if (r) {
				*error = error_key;
				return r;
			}
3649 3650 3651
		} else if (crypto_shash_get_flags(*hash) & CRYPTO_TFM_NEED_KEY) {
			*error = error_key;
			return -ENOKEY;
M
Mikulas Patocka 已提交
3652 3653 3654 3655 3656 3657
		}
	}

	return 0;
}

3658 3659 3660 3661 3662
static int create_journal(struct dm_integrity_c *ic, char **error)
{
	int r = 0;
	unsigned i;
	__u64 journal_pages, journal_desc_size, journal_tree_size;
3663 3664
	unsigned char *crypt_data = NULL, *crypt_iv = NULL;
	struct skcipher_request *req = NULL;
3665 3666 3667 3668 3669

	ic->commit_ids[0] = cpu_to_le64(0x1111111111111111ULL);
	ic->commit_ids[1] = cpu_to_le64(0x2222222222222222ULL);
	ic->commit_ids[2] = cpu_to_le64(0x3333333333333333ULL);
	ic->commit_ids[3] = cpu_to_le64(0x4444444444444444ULL);
3670 3671 3672 3673

	journal_pages = roundup((__u64)ic->journal_sections * ic->journal_section_sectors,
				PAGE_SIZE >> SECTOR_SHIFT) >> (PAGE_SHIFT - SECTOR_SHIFT);
	journal_desc_size = journal_pages * sizeof(struct page_list);
3674
	if (journal_pages >= totalram_pages() - totalhigh_pages() || journal_desc_size > ULONG_MAX) {
3675 3676 3677 3678 3679 3680
		*error = "Journal doesn't fit into memory";
		r = -ENOMEM;
		goto bad;
	}
	ic->journal_pages = journal_pages;

3681
	ic->journal = dm_integrity_alloc_page_list(ic->journal_pages);
3682 3683 3684 3685 3686 3687 3688 3689 3690 3691
	if (!ic->journal) {
		*error = "Could not allocate memory for journal";
		r = -ENOMEM;
		goto bad;
	}
	if (ic->journal_crypt_alg.alg_string) {
		unsigned ivsize, blocksize;
		struct journal_completion comp;

		comp.ic = ic;
3692
		ic->journal_crypt = crypto_alloc_skcipher(ic->journal_crypt_alg.alg_string, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
		if (IS_ERR(ic->journal_crypt)) {
			*error = "Invalid journal cipher";
			r = PTR_ERR(ic->journal_crypt);
			ic->journal_crypt = NULL;
			goto bad;
		}
		ivsize = crypto_skcipher_ivsize(ic->journal_crypt);
		blocksize = crypto_skcipher_blocksize(ic->journal_crypt);

		if (ic->journal_crypt_alg.key) {
			r = crypto_skcipher_setkey(ic->journal_crypt, ic->journal_crypt_alg.key,
						   ic->journal_crypt_alg.key_size);
			if (r) {
				*error = "Error setting encryption key";
				goto bad;
			}
		}
		DEBUG_print("cipher %s, block size %u iv size %u\n",
			    ic->journal_crypt_alg.alg_string, blocksize, ivsize);

3713
		ic->journal_io = dm_integrity_alloc_page_list(ic->journal_pages);
3714 3715 3716 3717 3718 3719 3720 3721
		if (!ic->journal_io) {
			*error = "Could not allocate memory for journal io";
			r = -ENOMEM;
			goto bad;
		}

		if (blocksize == 1) {
			struct scatterlist *sg;
3722 3723 3724 3725 3726 3727 3728 3729

			req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
			if (!req) {
				*error = "Could not allocate crypt request";
				r = -ENOMEM;
				goto bad;
			}

3730
			crypt_iv = kzalloc(ivsize, GFP_KERNEL);
3731 3732 3733 3734 3735
			if (!crypt_iv) {
				*error = "Could not allocate iv";
				r = -ENOMEM;
				goto bad;
			}
3736

3737
			ic->journal_xor = dm_integrity_alloc_page_list(ic->journal_pages);
3738 3739 3740 3741 3742 3743
			if (!ic->journal_xor) {
				*error = "Could not allocate memory for journal xor";
				r = -ENOMEM;
				goto bad;
			}

3744 3745 3746
			sg = kvmalloc_array(ic->journal_pages + 1,
					    sizeof(struct scatterlist),
					    GFP_KERNEL);
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
			if (!sg) {
				*error = "Unable to allocate sg list";
				r = -ENOMEM;
				goto bad;
			}
			sg_init_table(sg, ic->journal_pages + 1);
			for (i = 0; i < ic->journal_pages; i++) {
				char *va = lowmem_page_address(ic->journal_xor[i].page);
				clear_page(va);
				sg_set_buf(&sg[i], va, PAGE_SIZE);
			}
			sg_set_buf(&sg[i], &ic->commit_ids, sizeof ic->commit_ids);

3760 3761
			skcipher_request_set_crypt(req, sg, sg,
						   PAGE_SIZE * ic->journal_pages + sizeof ic->commit_ids, crypt_iv);
3762
			init_completion(&comp.comp);
3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
			comp.in_flight = (atomic_t)ATOMIC_INIT(1);
			if (do_crypt(true, req, &comp))
				wait_for_completion(&comp.comp);
			kvfree(sg);
			r = dm_integrity_failed(ic);
			if (r) {
				*error = "Unable to encrypt journal";
				goto bad;
			}
			DEBUG_bytes(lowmem_page_address(ic->journal_xor[0].page), 64, "xor data");

			crypto_free_skcipher(ic->journal_crypt);
			ic->journal_crypt = NULL;
		} else {
			unsigned crypt_len = roundup(ivsize, blocksize);
3778

3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792
			req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
			if (!req) {
				*error = "Could not allocate crypt request";
				r = -ENOMEM;
				goto bad;
			}

			crypt_iv = kmalloc(ivsize, GFP_KERNEL);
			if (!crypt_iv) {
				*error = "Could not allocate iv";
				r = -ENOMEM;
				goto bad;
			}

3793 3794 3795 3796 3797 3798
			crypt_data = kmalloc(crypt_len, GFP_KERNEL);
			if (!crypt_data) {
				*error = "Unable to allocate crypt data";
				r = -ENOMEM;
				goto bad;
			}
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811

			ic->journal_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal);
			if (!ic->journal_scatterlist) {
				*error = "Unable to allocate sg list";
				r = -ENOMEM;
				goto bad;
			}
			ic->journal_io_scatterlist = dm_integrity_alloc_journal_scatterlist(ic, ic->journal_io);
			if (!ic->journal_io_scatterlist) {
				*error = "Unable to allocate sg list";
				r = -ENOMEM;
				goto bad;
			}
3812 3813 3814
			ic->sk_requests = kvmalloc_array(ic->journal_sections,
							 sizeof(struct skcipher_request *),
							 GFP_KERNEL | __GFP_ZERO);
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824
			if (!ic->sk_requests) {
				*error = "Unable to allocate sk requests";
				r = -ENOMEM;
				goto bad;
			}
			for (i = 0; i < ic->journal_sections; i++) {
				struct scatterlist sg;
				struct skcipher_request *section_req;
				__u32 section_le = cpu_to_le32(i);

3825
				memset(crypt_iv, 0x00, ivsize);
3826 3827 3828 3829
				memset(crypt_data, 0x00, crypt_len);
				memcpy(crypt_data, &section_le, min((size_t)crypt_len, sizeof(section_le)));

				sg_init_one(&sg, crypt_data, crypt_len);
3830
				skcipher_request_set_crypt(req, &sg, &sg, crypt_len, crypt_iv);
3831
				init_completion(&comp.comp);
3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
				comp.in_flight = (atomic_t)ATOMIC_INIT(1);
				if (do_crypt(true, req, &comp))
					wait_for_completion(&comp.comp);

				r = dm_integrity_failed(ic);
				if (r) {
					*error = "Unable to generate iv";
					goto bad;
				}

				section_req = skcipher_request_alloc(ic->journal_crypt, GFP_KERNEL);
				if (!section_req) {
					*error = "Unable to allocate crypt request";
					r = -ENOMEM;
					goto bad;
				}
3848 3849
				section_req->iv = kmalloc_array(ivsize, 2,
								GFP_KERNEL);
3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881
				if (!section_req->iv) {
					skcipher_request_free(section_req);
					*error = "Unable to allocate iv";
					r = -ENOMEM;
					goto bad;
				}
				memcpy(section_req->iv + ivsize, crypt_data, ivsize);
				section_req->cryptlen = (size_t)ic->journal_section_sectors << SECTOR_SHIFT;
				ic->sk_requests[i] = section_req;
				DEBUG_bytes(crypt_data, ivsize, "iv(%u)", i);
			}
		}
	}

	for (i = 0; i < N_COMMIT_IDS; i++) {
		unsigned j;
retest_commit_id:
		for (j = 0; j < i; j++) {
			if (ic->commit_ids[j] == ic->commit_ids[i]) {
				ic->commit_ids[i] = cpu_to_le64(le64_to_cpu(ic->commit_ids[i]) + 1);
				goto retest_commit_id;
			}
		}
		DEBUG_print("commit id %u: %016llx\n", i, ic->commit_ids[i]);
	}

	journal_tree_size = (__u64)ic->journal_entries * sizeof(struct journal_node);
	if (journal_tree_size > ULONG_MAX) {
		*error = "Journal doesn't fit into memory";
		r = -ENOMEM;
		goto bad;
	}
3882
	ic->journal_tree = kvmalloc(journal_tree_size, GFP_KERNEL);
3883 3884 3885 3886 3887
	if (!ic->journal_tree) {
		*error = "Could not allocate memory for journal tree";
		r = -ENOMEM;
	}
bad:
3888
	kfree(crypt_data);
3889 3890 3891
	kfree(crypt_iv);
	skcipher_request_free(req);

3892 3893 3894
	return r;
}

M
Mikulas Patocka 已提交
3895
/*
3896
 * Construct a integrity mapping
M
Mikulas Patocka 已提交
3897 3898 3899 3900 3901
 *
 * Arguments:
 *	device
 *	offset from the start of the device
 *	tag size
3902
 *	D - direct writes, J - journal writes, B - bitmap mode, R - recovery mode
M
Mikulas Patocka 已提交
3903 3904
 *	number of optional arguments
 *	optional arguments:
3905 3906 3907 3908 3909
 *		journal_sectors
 *		interleave_sectors
 *		buffer_sectors
 *		journal_watermark
 *		commit_time
3910 3911
 *		meta_device
 *		block_size
3912 3913
 *		sectors_per_bit
 *		bitmap_flush_interval
3914 3915 3916
 *		internal_hash
 *		journal_crypt
 *		journal_mac
3917
 *		recalculate
M
Mikulas Patocka 已提交
3918 3919 3920 3921 3922 3923 3924 3925
 */
static int dm_integrity_ctr(struct dm_target *ti, unsigned argc, char **argv)
{
	struct dm_integrity_c *ic;
	char dummy;
	int r;
	unsigned extra_args;
	struct dm_arg_set as;
E
Eric Biggers 已提交
3926
	static const struct dm_arg _args[] = {
3927
		{0, 18, "Invalid number of feature args"},
M
Mikulas Patocka 已提交
3928 3929 3930 3931 3932
	};
	unsigned journal_sectors, interleave_sectors, buffer_sectors, journal_watermark, sync_msec;
	bool should_write_sb;
	__u64 threshold;
	unsigned long long start;
3933 3934 3935 3936
	__s8 log2_sectors_per_bitmap_bit = -1;
	__s8 log2_blocks_per_bitmap_bit;
	__u64 bits_in_journal;
	__u64 n_bitmap_bits;
M
Mikulas Patocka 已提交
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951

#define DIRECT_ARGUMENTS	4

	if (argc <= DIRECT_ARGUMENTS) {
		ti->error = "Invalid argument count";
		return -EINVAL;
	}

	ic = kzalloc(sizeof(struct dm_integrity_c), GFP_KERNEL);
	if (!ic) {
		ti->error = "Cannot allocate integrity context";
		return -ENOMEM;
	}
	ti->private = ic;
	ti->per_io_data_size = sizeof(struct dm_integrity_io);
3952
	ic->ti = ti;
M
Mikulas Patocka 已提交
3953 3954

	ic->in_progress = RB_ROOT;
3955
	INIT_LIST_HEAD(&ic->wait_list);
M
Mikulas Patocka 已提交
3956 3957 3958 3959
	init_waitqueue_head(&ic->endio_wait);
	bio_list_init(&ic->flush_bio_list);
	init_waitqueue_head(&ic->copy_to_journal_wait);
	init_completion(&ic->crypto_backoff);
3960
	atomic64_set(&ic->number_of_mismatches, 0);
3961
	ic->bitmap_flush_interval = BITMAP_FLUSH_INTERVAL;
M
Mikulas Patocka 已提交
3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983

	r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &ic->dev);
	if (r) {
		ti->error = "Device lookup failed";
		goto bad;
	}

	if (sscanf(argv[1], "%llu%c", &start, &dummy) != 1 || start != (sector_t)start) {
		ti->error = "Invalid starting offset";
		r = -EINVAL;
		goto bad;
	}
	ic->start = start;

	if (strcmp(argv[2], "-")) {
		if (sscanf(argv[2], "%u%c", &ic->tag_size, &dummy) != 1 || !ic->tag_size) {
			ti->error = "Invalid tag size";
			r = -EINVAL;
			goto bad;
		}
	}

3984 3985
	if (!strcmp(argv[3], "J") || !strcmp(argv[3], "B") ||
	    !strcmp(argv[3], "D") || !strcmp(argv[3], "R")) {
M
Mikulas Patocka 已提交
3986
		ic->mode = argv[3][0];
3987 3988
	} else {
		ti->error = "Invalid mode (expecting J, B, D, R)";
M
Mikulas Patocka 已提交
3989 3990 3991 3992
		r = -EINVAL;
		goto bad;
	}

3993
	journal_sectors = 0;
M
Mikulas Patocka 已提交
3994 3995 3996 3997
	interleave_sectors = DEFAULT_INTERLEAVE_SECTORS;
	buffer_sectors = DEFAULT_BUFFER_SECTORS;
	journal_watermark = DEFAULT_JOURNAL_WATERMARK;
	sync_msec = DEFAULT_SYNC_MSEC;
3998
	ic->sectors_per_block = 1;
M
Mikulas Patocka 已提交
3999 4000 4001 4002 4003 4004 4005 4006 4007 4008

	as.argc = argc - DIRECT_ARGUMENTS;
	as.argv = argv + DIRECT_ARGUMENTS;
	r = dm_read_arg_group(_args, &as, &extra_args, &ti->error);
	if (r)
		goto bad;

	while (extra_args--) {
		const char *opt_string;
		unsigned val;
4009
		unsigned long long llval;
M
Mikulas Patocka 已提交
4010 4011 4012 4013 4014 4015
		opt_string = dm_shift_arg(&as);
		if (!opt_string) {
			r = -EINVAL;
			ti->error = "Not enough feature arguments";
			goto bad;
		}
4016
		if (sscanf(opt_string, "journal_sectors:%u%c", &val, &dummy) == 1)
4017
			journal_sectors = val ? val : 1;
4018
		else if (sscanf(opt_string, "interleave_sectors:%u%c", &val, &dummy) == 1)
M
Mikulas Patocka 已提交
4019
			interleave_sectors = val;
4020
		else if (sscanf(opt_string, "buffer_sectors:%u%c", &val, &dummy) == 1)
M
Mikulas Patocka 已提交
4021
			buffer_sectors = val;
4022
		else if (sscanf(opt_string, "journal_watermark:%u%c", &val, &dummy) == 1 && val <= 100)
M
Mikulas Patocka 已提交
4023
			journal_watermark = val;
4024
		else if (sscanf(opt_string, "commit_time:%u%c", &val, &dummy) == 1)
M
Mikulas Patocka 已提交
4025
			sync_msec = val;
4026
		else if (!strncmp(opt_string, "meta_device:", strlen("meta_device:"))) {
4027 4028 4029 4030
			if (ic->meta_dev) {
				dm_put_device(ti, ic->meta_dev);
				ic->meta_dev = NULL;
			}
4031 4032
			r = dm_get_device(ti, strchr(opt_string, ':') + 1,
					  dm_table_get_mode(ti->table), &ic->meta_dev);
4033 4034 4035 4036 4037
			if (r) {
				ti->error = "Device lookup failed";
				goto bad;
			}
		} else if (sscanf(opt_string, "block_size:%u%c", &val, &dummy) == 1) {
4038 4039 4040 4041 4042 4043 4044 4045
			if (val < 1 << SECTOR_SHIFT ||
			    val > MAX_SECTORS_PER_BLOCK << SECTOR_SHIFT ||
			    (val & (val -1))) {
				r = -EINVAL;
				ti->error = "Invalid block_size argument";
				goto bad;
			}
			ic->sectors_per_block = val >> SECTOR_SHIFT;
4046 4047 4048 4049 4050 4051
		} else if (sscanf(opt_string, "sectors_per_bit:%llu%c", &llval, &dummy) == 1) {
			log2_sectors_per_bitmap_bit = !llval ? 0 : __ilog2_u64(llval);
		} else if (sscanf(opt_string, "bitmap_flush_interval:%u%c", &val, &dummy) == 1) {
			if (val >= (uint64_t)UINT_MAX * 1000 / HZ) {
				r = -EINVAL;
				ti->error = "Invalid bitmap_flush_interval argument";
4052
				goto bad;
4053 4054
			}
			ic->bitmap_flush_interval = msecs_to_jiffies(val);
4055
		} else if (!strncmp(opt_string, "internal_hash:", strlen("internal_hash:"))) {
M
Mikulas Patocka 已提交
4056
			r = get_alg_and_key(opt_string, &ic->internal_hash_alg, &ti->error,
4057
					    "Invalid internal_hash argument");
M
Mikulas Patocka 已提交
4058 4059
			if (r)
				goto bad;
4060
		} else if (!strncmp(opt_string, "journal_crypt:", strlen("journal_crypt:"))) {
M
Mikulas Patocka 已提交
4061
			r = get_alg_and_key(opt_string, &ic->journal_crypt_alg, &ti->error,
4062
					    "Invalid journal_crypt argument");
M
Mikulas Patocka 已提交
4063 4064
			if (r)
				goto bad;
4065
		} else if (!strncmp(opt_string, "journal_mac:", strlen("journal_mac:"))) {
4066
			r = get_alg_and_key(opt_string, &ic->journal_mac_alg, &ti->error,
4067
					    "Invalid journal_mac argument");
M
Mikulas Patocka 已提交
4068 4069
			if (r)
				goto bad;
4070
		} else if (!strcmp(opt_string, "recalculate")) {
4071
			ic->recalculate_flag = true;
4072 4073 4074
		} else if (!strcmp(opt_string, "reset_recalculate")) {
			ic->recalculate_flag = true;
			ic->reset_recalculate_flag = true;
4075 4076
		} else if (!strcmp(opt_string, "allow_discards")) {
			ic->discard = true;
4077 4078
		} else if (!strcmp(opt_string, "fix_padding")) {
			ic->fix_padding = true;
4079 4080
		} else if (!strcmp(opt_string, "fix_hmac")) {
			ic->fix_hmac = true;
4081 4082
		} else if (!strcmp(opt_string, "legacy_recalculate")) {
			ic->legacy_recalculate = true;
M
Mikulas Patocka 已提交
4083 4084 4085 4086 4087 4088 4089
		} else {
			r = -EINVAL;
			ti->error = "Invalid argument";
			goto bad;
		}
	}

4090 4091 4092 4093 4094 4095 4096 4097
	ic->data_device_sectors = i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT;
	if (!ic->meta_dev)
		ic->meta_device_sectors = ic->data_device_sectors;
	else
		ic->meta_device_sectors = i_size_read(ic->meta_dev->bdev->bd_inode) >> SECTOR_SHIFT;

	if (!journal_sectors) {
		journal_sectors = min((sector_t)DEFAULT_MAX_JOURNAL_SECTORS,
4098
				      ic->data_device_sectors >> DEFAULT_JOURNAL_SIZE_FACTOR);
4099 4100 4101 4102 4103 4104
	}

	if (!buffer_sectors)
		buffer_sectors = 1;
	ic->log2_buffer_sectors = min((int)__fls(buffer_sectors), 31 - SECTOR_SHIFT);

M
Mikulas Patocka 已提交
4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
	r = get_mac(&ic->internal_hash, &ic->internal_hash_alg, &ti->error,
		    "Invalid internal hash", "Error setting internal hash key");
	if (r)
		goto bad;

	r = get_mac(&ic->journal_mac, &ic->journal_mac_alg, &ti->error,
		    "Invalid journal mac", "Error setting journal mac key");
	if (r)
		goto bad;

	if (!ic->tag_size) {
		if (!ic->internal_hash) {
			ti->error = "Unknown tag size";
			r = -EINVAL;
			goto bad;
		}
		ic->tag_size = crypto_shash_digestsize(ic->internal_hash);
	}
	if (ic->tag_size > MAX_TAG_SIZE) {
		ti->error = "Too big tag size";
		r = -EINVAL;
		goto bad;
	}
	if (!(ic->tag_size & (ic->tag_size - 1)))
		ic->log2_tag_size = __ffs(ic->tag_size);
	else
		ic->log2_tag_size = -1;

4133 4134 4135 4136 4137 4138
	if (ic->mode == 'B' && !ic->internal_hash) {
		r = -EINVAL;
		ti->error = "Bitmap mode can be only used with internal hash";
		goto bad;
	}

4139 4140 4141 4142 4143 4144
	if (ic->discard && !ic->internal_hash) {
		r = -EINVAL;
		ti->error = "Discard can be only used with internal hash";
		goto bad;
	}

M
Mikulas Patocka 已提交
4145 4146
	ic->autocommit_jiffies = msecs_to_jiffies(sync_msec);
	ic->autocommit_msec = sync_msec;
4147
	timer_setup(&ic->autocommit_timer, autocommit_fn, 0);
M
Mikulas Patocka 已提交
4148 4149 4150 4151 4152 4153 4154 4155 4156

	ic->io = dm_io_client_create();
	if (IS_ERR(ic->io)) {
		r = PTR_ERR(ic->io);
		ic->io = NULL;
		ti->error = "Cannot allocate dm io";
		goto bad;
	}

4157 4158
	r = mempool_init_slab_pool(&ic->journal_io_mempool, JOURNAL_IO_MEMPOOL, journal_io_cache);
	if (r) {
M
Mikulas Patocka 已提交
4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181
		ti->error = "Cannot allocate mempool";
		goto bad;
	}

	ic->metadata_wq = alloc_workqueue("dm-integrity-metadata",
					  WQ_MEM_RECLAIM, METADATA_WORKQUEUE_MAX_ACTIVE);
	if (!ic->metadata_wq) {
		ti->error = "Cannot allocate workqueue";
		r = -ENOMEM;
		goto bad;
	}

	/*
	 * If this workqueue were percpu, it would cause bio reordering
	 * and reduced performance.
	 */
	ic->wait_wq = alloc_workqueue("dm-integrity-wait", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
	if (!ic->wait_wq) {
		ti->error = "Cannot allocate workqueue";
		r = -ENOMEM;
		goto bad;
	}

4182 4183 4184 4185 4186 4187 4188 4189
	ic->offload_wq = alloc_workqueue("dm-integrity-offload", WQ_MEM_RECLAIM,
					  METADATA_WORKQUEUE_MAX_ACTIVE);
	if (!ic->offload_wq) {
		ti->error = "Cannot allocate workqueue";
		r = -ENOMEM;
		goto bad;
	}

M
Mikulas Patocka 已提交
4190 4191 4192 4193 4194 4195 4196 4197
	ic->commit_wq = alloc_workqueue("dm-integrity-commit", WQ_MEM_RECLAIM, 1);
	if (!ic->commit_wq) {
		ti->error = "Cannot allocate workqueue";
		r = -ENOMEM;
		goto bad;
	}
	INIT_WORK(&ic->commit_work, integrity_commit);

4198
	if (ic->mode == 'J' || ic->mode == 'B') {
M
Mikulas Patocka 已提交
4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219
		ic->writer_wq = alloc_workqueue("dm-integrity-writer", WQ_MEM_RECLAIM, 1);
		if (!ic->writer_wq) {
			ti->error = "Cannot allocate workqueue";
			r = -ENOMEM;
			goto bad;
		}
		INIT_WORK(&ic->writer_work, integrity_writer);
	}

	ic->sb = alloc_pages_exact(SB_SECTORS << SECTOR_SHIFT, GFP_KERNEL);
	if (!ic->sb) {
		r = -ENOMEM;
		ti->error = "Cannot allocate superblock area";
		goto bad;
	}

	r = sync_rw_sb(ic, REQ_OP_READ, 0);
	if (r) {
		ti->error = "Error reading superblock";
		goto bad;
	}
4220 4221 4222
	should_write_sb = false;
	if (memcmp(ic->sb->magic, SB_MAGIC, 8)) {
		if (ic->mode != 'R') {
4223 4224 4225 4226
			if (memchr_inv(ic->sb, 0, SB_SECTORS << SECTOR_SHIFT)) {
				r = -EINVAL;
				ti->error = "The device is not initialized";
				goto bad;
M
Mikulas Patocka 已提交
4227 4228 4229 4230 4231 4232 4233 4234
			}
		}

		r = initialize_superblock(ic, journal_sectors, interleave_sectors);
		if (r) {
			ti->error = "Could not initialize superblock";
			goto bad;
		}
4235 4236
		if (ic->mode != 'R')
			should_write_sb = true;
M
Mikulas Patocka 已提交
4237 4238
	}

4239
	if (!ic->sb->version || ic->sb->version > SB_VERSION_5) {
M
Mikulas Patocka 已提交
4240 4241 4242 4243 4244 4245
		r = -EINVAL;
		ti->error = "Unknown version";
		goto bad;
	}
	if (le16_to_cpu(ic->sb->integrity_tag_size) != ic->tag_size) {
		r = -EINVAL;
4246 4247 4248 4249 4250 4251
		ti->error = "Tag size doesn't match the information in superblock";
		goto bad;
	}
	if (ic->sb->log2_sectors_per_block != __ffs(ic->sectors_per_block)) {
		r = -EINVAL;
		ti->error = "Block size doesn't match the information in superblock";
M
Mikulas Patocka 已提交
4252 4253
		goto bad;
	}
4254 4255 4256 4257 4258
	if (!le32_to_cpu(ic->sb->journal_sections)) {
		r = -EINVAL;
		ti->error = "Corrupted superblock, journal_sections is 0";
		goto bad;
	}
M
Mikulas Patocka 已提交
4259
	/* make sure that ti->max_io_len doesn't overflow */
4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
	if (!ic->meta_dev) {
		if (ic->sb->log2_interleave_sectors < MIN_LOG2_INTERLEAVE_SECTORS ||
		    ic->sb->log2_interleave_sectors > MAX_LOG2_INTERLEAVE_SECTORS) {
			r = -EINVAL;
			ti->error = "Invalid interleave_sectors in the superblock";
			goto bad;
		}
	} else {
		if (ic->sb->log2_interleave_sectors) {
			r = -EINVAL;
			ti->error = "Invalid interleave_sectors in the superblock";
			goto bad;
		}
M
Mikulas Patocka 已提交
4273
	}
4274
	if (!!(ic->sb->flags & cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC)) != !!ic->journal_mac_alg.alg_string) {
M
Mikulas Patocka 已提交
4275
		r = -EINVAL;
4276
		ti->error = "Journal mac mismatch";
M
Mikulas Patocka 已提交
4277 4278
		goto bad;
	}
4279 4280 4281

	get_provided_data_sectors(ic);
	if (!ic->provided_data_sectors) {
M
Mikulas Patocka 已提交
4282
		r = -EINVAL;
4283
		ti->error = "The device is too small";
M
Mikulas Patocka 已提交
4284 4285
		goto bad;
	}
4286 4287

try_smaller_buffer:
M
Mikulas Patocka 已提交
4288 4289
	r = calculate_device_limits(ic);
	if (r) {
4290 4291 4292 4293 4294 4295
		if (ic->meta_dev) {
			if (ic->log2_buffer_sectors > 3) {
				ic->log2_buffer_sectors--;
				goto try_smaller_buffer;
			}
		}
M
Mikulas Patocka 已提交
4296 4297 4298
		ti->error = "The device is too small";
		goto bad;
	}
4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319

	if (log2_sectors_per_bitmap_bit < 0)
		log2_sectors_per_bitmap_bit = __fls(DEFAULT_SECTORS_PER_BITMAP_BIT);
	if (log2_sectors_per_bitmap_bit < ic->sb->log2_sectors_per_block)
		log2_sectors_per_bitmap_bit = ic->sb->log2_sectors_per_block;

	bits_in_journal = ((__u64)ic->journal_section_sectors * ic->journal_sections) << (SECTOR_SHIFT + 3);
	if (bits_in_journal > UINT_MAX)
		bits_in_journal = UINT_MAX;
	while (bits_in_journal < (ic->provided_data_sectors + ((sector_t)1 << log2_sectors_per_bitmap_bit) - 1) >> log2_sectors_per_bitmap_bit)
		log2_sectors_per_bitmap_bit++;

	log2_blocks_per_bitmap_bit = log2_sectors_per_bitmap_bit - ic->sb->log2_sectors_per_block;
	ic->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
	if (should_write_sb) {
		ic->sb->log2_blocks_per_bitmap_bit = log2_blocks_per_bitmap_bit;
	}
	n_bitmap_bits = ((ic->provided_data_sectors >> ic->sb->log2_sectors_per_block)
				+ (((sector_t)1 << log2_blocks_per_bitmap_bit) - 1)) >> log2_blocks_per_bitmap_bit;
	ic->n_bitmap_blocks = DIV_ROUND_UP(n_bitmap_bits, BITMAP_BLOCK_SIZE * 8);

4320 4321 4322
	if (!ic->meta_dev)
		ic->log2_buffer_sectors = min(ic->log2_buffer_sectors, (__u8)__ffs(ic->metadata_run));

4323 4324 4325 4326 4327
	if (ti->len > ic->provided_data_sectors) {
		r = -EINVAL;
		ti->error = "Not enough provided sectors for requested mapping size";
		goto bad;
	}
M
Mikulas Patocka 已提交
4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343


	threshold = (__u64)ic->journal_entries * (100 - journal_watermark);
	threshold += 50;
	do_div(threshold, 100);
	ic->free_sectors_threshold = threshold;

	DEBUG_print("initialized:\n");
	DEBUG_print("	integrity_tag_size %u\n", le16_to_cpu(ic->sb->integrity_tag_size));
	DEBUG_print("	journal_entry_size %u\n", ic->journal_entry_size);
	DEBUG_print("	journal_entries_per_sector %u\n", ic->journal_entries_per_sector);
	DEBUG_print("	journal_section_entries %u\n", ic->journal_section_entries);
	DEBUG_print("	journal_section_sectors %u\n", ic->journal_section_sectors);
	DEBUG_print("	journal_sections %u\n", (unsigned)le32_to_cpu(ic->sb->journal_sections));
	DEBUG_print("	journal_entries %u\n", ic->journal_entries);
	DEBUG_print("	log2_interleave_sectors %d\n", ic->sb->log2_interleave_sectors);
4344
	DEBUG_print("	data_device_sectors 0x%llx\n", i_size_read(ic->dev->bdev->bd_inode) >> SECTOR_SHIFT);
M
Mikulas Patocka 已提交
4345 4346 4347
	DEBUG_print("	initial_sectors 0x%x\n", ic->initial_sectors);
	DEBUG_print("	metadata_run 0x%x\n", ic->metadata_run);
	DEBUG_print("	log2_metadata_run %d\n", ic->log2_metadata_run);
4348
	DEBUG_print("	provided_data_sectors 0x%llx (%llu)\n", ic->provided_data_sectors, ic->provided_data_sectors);
M
Mikulas Patocka 已提交
4349
	DEBUG_print("	log2_buffer_sectors %u\n", ic->log2_buffer_sectors);
4350
	DEBUG_print("	bits_in_journal %llu\n", bits_in_journal);
M
Mikulas Patocka 已提交
4351

4352
	if (ic->recalculate_flag && !(ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING))) {
4353 4354 4355 4356
		ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
		ic->sb->recalc_sector = cpu_to_le64(0);
	}

4357
	if (ic->internal_hash) {
4358
		ic->recalc_wq = alloc_workqueue("dm-integrity-recalc", WQ_MEM_RECLAIM, 1);
4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370
		if (!ic->recalc_wq ) {
			ti->error = "Cannot allocate workqueue";
			r = -ENOMEM;
			goto bad;
		}
		INIT_WORK(&ic->recalc_work, integrity_recalc);
		ic->recalc_buffer = vmalloc(RECALC_SECTORS << SECTOR_SHIFT);
		if (!ic->recalc_buffer) {
			ti->error = "Cannot allocate buffer for recalculating";
			r = -ENOMEM;
			goto bad;
		}
4371 4372
		ic->recalc_tags = kvmalloc_array(RECALC_SECTORS >> ic->sb->log2_sectors_per_block,
						 ic->tag_size, GFP_KERNEL);
4373 4374 4375 4376 4377
		if (!ic->recalc_tags) {
			ti->error = "Cannot allocate tags for recalculating";
			r = -ENOMEM;
			goto bad;
		}
4378 4379 4380 4381 4382 4383
	} else {
		if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING)) {
			ti->error = "Recalculate can only be specified with internal_hash";
			r = -EINVAL;
			goto bad;
		}
4384 4385
	}

4386 4387 4388 4389 4390 4391 4392 4393
	if (ic->sb->flags & cpu_to_le32(SB_FLAG_RECALCULATING) &&
	    le64_to_cpu(ic->sb->recalc_sector) < ic->provided_data_sectors &&
	    dm_integrity_disable_recalculate(ic)) {
		ti->error = "Recalculating with HMAC is disabled for security reasons - if you really need it, use the argument \"legacy_recalculate\"";
		r = -EOPNOTSUPP;
		goto bad;
	}

4394 4395
	ic->bufio = dm_bufio_client_create(ic->meta_dev ? ic->meta_dev->bdev : ic->dev->bdev,
			1U << (SECTOR_SHIFT + ic->log2_buffer_sectors), 1, 0, NULL, NULL);
M
Mikulas Patocka 已提交
4396 4397 4398 4399 4400 4401 4402 4403
	if (IS_ERR(ic->bufio)) {
		r = PTR_ERR(ic->bufio);
		ti->error = "Cannot initialize dm-bufio";
		ic->bufio = NULL;
		goto bad;
	}
	dm_bufio_set_sector_offset(ic->bufio, ic->start + ic->initial_sectors);

4404 4405 4406 4407
	if (ic->mode != 'R') {
		r = create_journal(ic, &ti->error);
		if (r)
			goto bad;
4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446

	}

	if (ic->mode == 'B') {
		unsigned i;
		unsigned n_bitmap_pages = DIV_ROUND_UP(ic->n_bitmap_blocks, PAGE_SIZE / BITMAP_BLOCK_SIZE);

		ic->recalc_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
		if (!ic->recalc_bitmap) {
			r = -ENOMEM;
			goto bad;
		}
		ic->may_write_bitmap = dm_integrity_alloc_page_list(n_bitmap_pages);
		if (!ic->may_write_bitmap) {
			r = -ENOMEM;
			goto bad;
		}
		ic->bbs = kvmalloc_array(ic->n_bitmap_blocks, sizeof(struct bitmap_block_status), GFP_KERNEL);
		if (!ic->bbs) {
			r = -ENOMEM;
			goto bad;
		}
		INIT_DELAYED_WORK(&ic->bitmap_flush_work, bitmap_flush_work);
		for (i = 0; i < ic->n_bitmap_blocks; i++) {
			struct bitmap_block_status *bbs = &ic->bbs[i];
			unsigned sector, pl_index, pl_offset;

			INIT_WORK(&bbs->work, bitmap_block_work);
			bbs->ic = ic;
			bbs->idx = i;
			bio_list_init(&bbs->bio_queue);
			spin_lock_init(&bbs->bio_queue_lock);

			sector = i * (BITMAP_BLOCK_SIZE >> SECTOR_SHIFT);
			pl_index = sector >> (PAGE_SHIFT - SECTOR_SHIFT);
			pl_offset = (sector << SECTOR_SHIFT) & (PAGE_SIZE - 1);

			bbs->bitmap = lowmem_page_address(ic->journal[pl_index].page) + pl_offset;
		}
4447
	}
M
Mikulas Patocka 已提交
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465

	if (should_write_sb) {
		int r;

		init_journal(ic, 0, ic->journal_sections, 0);
		r = dm_integrity_failed(ic);
		if (unlikely(r)) {
			ti->error = "Error initializing journal";
			goto bad;
		}
		r = sync_rw_sb(ic, REQ_OP_WRITE, REQ_FUA);
		if (r) {
			ti->error = "Error initializing superblock";
			goto bad;
		}
		ic->just_formatted = true;
	}

4466 4467 4468 4469 4470
	if (!ic->meta_dev) {
		r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
		if (r)
			goto bad;
	}
4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
	if (ic->mode == 'B') {
		unsigned max_io_len = ((sector_t)ic->sectors_per_block << ic->log2_blocks_per_bitmap_bit) * (BITMAP_BLOCK_SIZE * 8);
		if (!max_io_len)
			max_io_len = 1U << 31;
		DEBUG_print("max_io_len: old %u, new %u\n", ti->max_io_len, max_io_len);
		if (!ti->max_io_len || ti->max_io_len > max_io_len) {
			r = dm_set_target_max_io_len(ti, max_io_len);
			if (r)
				goto bad;
		}
	}
M
Mikulas Patocka 已提交
4482 4483 4484 4485 4486 4487

	if (!ic->internal_hash)
		dm_integrity_set(ti, ic);

	ti->num_flush_bios = 1;
	ti->flush_supported = true;
4488 4489
	if (ic->discard)
		ti->num_discard_bios = 1;
M
Mikulas Patocka 已提交
4490 4491

	return 0;
4492

M
Mikulas Patocka 已提交
4493 4494 4495 4496 4497 4498 4499 4500 4501 4502
bad:
	dm_integrity_dtr(ti);
	return r;
}

static void dm_integrity_dtr(struct dm_target *ti)
{
	struct dm_integrity_c *ic = ti->private;

	BUG_ON(!RB_EMPTY_ROOT(&ic->in_progress));
4503
	BUG_ON(!list_empty(&ic->wait_list));
M
Mikulas Patocka 已提交
4504 4505 4506 4507 4508

	if (ic->metadata_wq)
		destroy_workqueue(ic->metadata_wq);
	if (ic->wait_wq)
		destroy_workqueue(ic->wait_wq);
4509 4510
	if (ic->offload_wq)
		destroy_workqueue(ic->offload_wq);
M
Mikulas Patocka 已提交
4511 4512 4513 4514
	if (ic->commit_wq)
		destroy_workqueue(ic->commit_wq);
	if (ic->writer_wq)
		destroy_workqueue(ic->writer_wq);
4515 4516
	if (ic->recalc_wq)
		destroy_workqueue(ic->recalc_wq);
4517 4518
	vfree(ic->recalc_buffer);
	kvfree(ic->recalc_tags);
4519
	kvfree(ic->bbs);
M
Mikulas Patocka 已提交
4520 4521
	if (ic->bufio)
		dm_bufio_client_destroy(ic->bufio);
4522
	mempool_exit(&ic->journal_io_mempool);
M
Mikulas Patocka 已提交
4523 4524 4525 4526
	if (ic->io)
		dm_io_client_destroy(ic->io);
	if (ic->dev)
		dm_put_device(ti, ic->dev);
4527 4528
	if (ic->meta_dev)
		dm_put_device(ti, ic->meta_dev);
4529 4530 4531
	dm_integrity_free_page_list(ic->journal);
	dm_integrity_free_page_list(ic->journal_io);
	dm_integrity_free_page_list(ic->journal_xor);
4532 4533
	dm_integrity_free_page_list(ic->recalc_bitmap);
	dm_integrity_free_page_list(ic->may_write_bitmap);
M
Mikulas Patocka 已提交
4534 4535 4536 4537 4538 4539 4540 4541 4542 4543
	if (ic->journal_scatterlist)
		dm_integrity_free_journal_scatterlist(ic, ic->journal_scatterlist);
	if (ic->journal_io_scatterlist)
		dm_integrity_free_journal_scatterlist(ic, ic->journal_io_scatterlist);
	if (ic->sk_requests) {
		unsigned i;

		for (i = 0; i < ic->journal_sections; i++) {
			struct skcipher_request *req = ic->sk_requests[i];
			if (req) {
4544
				kfree_sensitive(req->iv);
M
Mikulas Patocka 已提交
4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
				skcipher_request_free(req);
			}
		}
		kvfree(ic->sk_requests);
	}
	kvfree(ic->journal_tree);
	if (ic->sb)
		free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);

	if (ic->internal_hash)
		crypto_free_shash(ic->internal_hash);
	free_alg(&ic->internal_hash_alg);

	if (ic->journal_crypt)
		crypto_free_skcipher(ic->journal_crypt);
	free_alg(&ic->journal_crypt_alg);

	if (ic->journal_mac)
		crypto_free_shash(ic->journal_mac);
	free_alg(&ic->journal_mac_alg);

	kfree(ic);
}

static struct target_type integrity_target = {
	.name			= "integrity",
4571
	.version		= {1, 8, 0},
M
Mikulas Patocka 已提交
4572 4573 4574 4575 4576 4577 4578 4579 4580
	.module			= THIS_MODULE,
	.features		= DM_TARGET_SINGLETON | DM_TARGET_INTEGRITY,
	.ctr			= dm_integrity_ctr,
	.dtr			= dm_integrity_dtr,
	.map			= dm_integrity_map,
	.postsuspend		= dm_integrity_postsuspend,
	.resume			= dm_integrity_resume,
	.status			= dm_integrity_status,
	.iterate_devices	= dm_integrity_iterate_devices,
4581
	.io_hints		= dm_integrity_io_hints,
M
Mikulas Patocka 已提交
4582 4583
};

4584
static int __init dm_integrity_init(void)
M
Mikulas Patocka 已提交
4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602
{
	int r;

	journal_io_cache = kmem_cache_create("integrity_journal_io",
					     sizeof(struct journal_io), 0, 0, NULL);
	if (!journal_io_cache) {
		DMERR("can't allocate journal io cache");
		return -ENOMEM;
	}

	r = dm_register_target(&integrity_target);

	if (r < 0)
		DMERR("register failed %d", r);

	return r;
}

4603
static void __exit dm_integrity_exit(void)
M
Mikulas Patocka 已提交
4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615
{
	dm_unregister_target(&integrity_target);
	kmem_cache_destroy(journal_io_cache);
}

module_init(dm_integrity_init);
module_exit(dm_integrity_exit);

MODULE_AUTHOR("Milan Broz");
MODULE_AUTHOR("Mikulas Patocka");
MODULE_DESCRIPTION(DM_NAME " target for integrity tags extension");
MODULE_LICENSE("GPL");